piątek, 14 sierpnia 2009

Unstoppable force meets immovable object

Code generation - here I come, once again.
Once upon a time I had to create a cms system. The system was quite large and I had to do it in about one month. What is more, the main reason I was creating the new system was to fix the issues we had with the old one. The point is that I had really not enough time.
However, I was able to create quite a decent application. I was rather satisfied with the result and the system didn't have a lot of code repetitions in its core.
Most of the logic was handled by business classes and they implemented good abstraction, i.e. versioning, cache and such stuff were implemented in base classes. However, the project had similar controllers and models (models in framework I used were something between a classic model and controller) for every module such as article, news, banner, etc. Due to a short deadline I was literally copying the files and changing names in them using replace function in IDE. Then, when I had some time to work on that code I changed all literal strings and other things specific to modules to constants that pointed to configuration in particular modules. My aim was to create classes that didn't force me to think while I was replacing text in source files, e.g. instead the sentence "Article has been added successfully" in template file I started using something like $moduleConfig[ARTICLE][TEXT_ADD_SUCCESS]. Well, that was my poor man's code generation. It had all the features of code generation besides the generator ;) At least I didn't have automatic code generation but I was manually copying files from other modules that were my templates.
To be honest, we've never encountered any serious problems with this approach and it worked quite well. However, I always thought that if I were given a week or so to work on this code and refactor it to extract base classes for models and controllers, the project would be so much better. The project was crippled with the fact that the whole code for these controller and model classes was duplicated. Unfortunately, I was never given the time to fix it before I left my ex-company. Everything was prepared, base classes should implement all the logic and child classes would know who they were and what constants they should use.
That story showed me that code generation, when used improperly, may seem an easy solution to a problem that should be addressed in another way.
Every tiny bit of logic that is generated shows that it should be placed in another element in design or higher in inheritance hierarchy.

First observation - IMHO, no application logic should be automatically generated.

But what about classes that give us strong typing for a cost of code generation? I'm not talking about typed DataSets in .NET because they suck so bad that they are not even worth mentioning but let's talk for example about classes generated from SubSonic. In the simplest approach generated classes reflect tables in database and they have strongly typed fields that represent columns in tables.
What are the advantages?
- you won't misspell a column in a table
- you also won't assign e.g. a string to an integer
But what are the disadvantages?
- you end up having lots of code that doesn't implement any logic at all
- every time you change database schema you need to regenerate your database classes
- if you generate CRUD from it, you will have problem achieving good level of code coverage
- if you change field name in database and want to keep property name in class, you may get confused using different names for same thing

Sometimes I think that we are paying too much for strong typing. Maybe the IDE should check the database and automagically check source code? For example, when I was writing a simple program in F#, the IDE checked if I specified correct format in literal string that was used in the method. When I specified in string representing format that I was expecting int and the corresponding argument was string, the IDE was smart enough to discover this problem. What is more, even if you misspell some fields you must have not tested the application at all if you didn't find this error.

Some frameworks let you write code that goes pretty well without the need to generate code (e.g. PHP frameworks); others (like ASP.NET that needs to see every control as a variable with a type, name and all that stuff) may try to force you to generate some code. Of course, I'm not a big fan of the latter.

And one final remark. I don't consider operations performed by a compiler to be code generation. Generated code may occur only in source files that developers are maintaining. We don't maintain byte code or low-level assembly instructions. The same goes with different forms of syntactic sugar that are handled by compiler and translated to "normal code" behind the scenes.
My friend wrote a note about on his blog: http://binary.freeperspective.net/countzero/2009/08/14/code-generators/. He says that he will come back to this issue. I'm eager to read his thoughts about the topic of code generation.

poniedziałek, 10 sierpnia 2009

Static code analysis - how much is it worth?

Recently, I've been using some tools to statically analyze my code. These tools are:
StyleCop
FxCop
CloneDetective

The sooner you start using these tools, the better. If you start using them in early development of your project, they may give you some hints about structure of your code and lead you to some good patterns. However, if you try analyze a project that consists of thousands of lines... well, what can I say - you'll just get the message that you did something wrong.
For instance, if you always use ToString() without specifying CultureInfo you'll get so many warnings that it would be almost impossible to correct them. To get meaningful notices that are important to your project you'll have to uncheck lots of rules in FxCop and StyleCop.
Clone Detective is a bit different from the previous tools. It analyzes source code to find code duplication. It's nice to have such a tool, especially when working with rather big projects. It may show that you're writing something that has been already written and also it encourages people not to use copy and paste. In one of my previous posts I wrote that code generation is just another way of doing copy and paste, my buddy Clone Detective says same thing ;) Yet again, if you start working with Clone Detective early, you'll be glad to see code duplication statistics showing maybe 5% of duplicated code. However, if you run it against a big project and see statistics at 40% or higher, it will just show you how miserable your life is.

There are lots of resources about all of these tools (guides, podcasts, etc.) so I don't want to talk about it in details. Yet, I wanted to state my current opinion on all of these tools.
If you're writing code that cannot pass static code analysis tests, I don't think these tools will "show you the way". These tools are for people who want to write good, bug free code. Good code is far more than sequence of brackets and letters. Good code has meaning, has design and all these little things that static analysis just cannot check. If you have some time and want to write and learn how to write code according to standards, then, hell yeah, give it a shot. However, if you are going to spend one hour writing unit tests or one hour adding all those CultureInfos - write some unit tests.
I was using these tools on my project that has lots of unit tests and I think that it was the main reason I was able to easily resolve all warnings. To be honest, I don't really think that the code is better after the analysis, but it's nice to see that I don't get any warnings. Also, I agree that these tools showed me some nice patterns that I didn't know about. But the bottom line is that I wouldn't be able to correct my warnings without unit tests. What is more, maybe my application is more portable and code is sticking to the rules, but it passed the tests before, and these tests are the real mark that everything is fine and the project is healthy.
Recently I ran a static analysis against some big project at work and they just showed me that the project sucks (as if I didn't know that before). I also think even if it would pass fxcop and stylecop tests it would still suck (clone detective is a different story). As Homer Simpson said: "This book has no answers". These tools also don't have real answers. Maybe some day these kind of tests will be run by compiler but we all know that code that compiles is not an indication of a bug free application.
I'm still under the spell of Bruce Eckel's article Strong Typing vs. Strong Testing.
Static analysis, in my opinion, is somewhat like strong typing.

P.S. My friend wrote an interesting post about static code analysis - Static analysis tools – one step closer to writing bugfree software.

sobota, 8 sierpnia 2009

Epic fail of proz kudoz

My wife is a translator and a user of proz.com. Recently she found a polite mail from proz team in her inbox saying that their site was hijacked:

This notice is to inform you that certain ProZ.com user
information was recently accessed improperly. Your profile may be
among those affected.

Among the forms of data accessed in the security breach were
name, email address, postal address and phone number. Login
information (usernames and passwords) was also accessed, though
passwords are protected by encryption. Other forms of information,
such as financial information, etc., were not accessed. (ProZ.com
does not store credit card information, etc.)

For more information about this incident, see:
http://www.proz.com/about/security


When I saw this email I checked if md5 hash of her password was present in hash databases - fortunately it wasn't. Then I started thinking about rainbow tables attacks and such stuff. I also thought that maybe password was hashed with sha-1, salted and there was more magic going on with it. I tried to ask myself if releasing password information was such a big deal if password was properly encrypted. Well, I still think it IS a big deal but i couldn't foresee what was coming.

I checked the page from email and read some faq about this recent security breach. One of the questions was:

Can you explain in more detail how password encryption works?

If your password is "uncle3pablo", what is stored in the database is something completely different: an encrypted version of the password like "dW5jbGUzcGFibG8=". What was accessed were the encrypted versions. If a person attempts to log in to your account with the encrypted version of your password, it will fail.


Hey... dW5jbGUzcGFibG8=??? It's goddamn base64. WTF?! You're showing that you're using base64 and you're saying that password is safely stored?! What is more, you're saying that a hijacker cannot log in with this password. Well, if you add "a" letter before password the hijacker will also be unable to log in with this "encrypted" password version.
To all people responsible for proz: base64 is an encoding used for transferring binary or other data in ascii text format http://en.wikipedia.org/wiki/Base64. Base64 IS NOT cryptography. Base64 is as safe for storing password as plain text.

What really makes me wonder is that someone responsible for such a big portal for translators decided that passwords will be encoded with base64.

FAIL!
UHJvei5jb20gLSB5b3Ugc3VjayE= - crack that password.

sobota, 13 czerwca 2009

Regex dollars can't buy me love

Short note about regex dollars.
I always thought that regex dollar sign $ in SingleLine mode means end of the character string (I thought it is like 0 <zero> in the end of C string, some kind of delimiter that ends string). However i found out that regex like ^[0-9]+$ matches not only digits but also strings like "123\n". It matches strings that not only have characters specified in regex pattern but also the same strings that end with single \n.
Lately, i had to validate user input from webpage end i ended up checking if the string matches regex and also checking if the string doesn't end with \n. I didn't like the solution and with great help from stackoverflow users i found out that only way to mark end of string is using \z. After a bit more research i was able to find some more explanation:

The difference between ‹\Z› and ‹\z› comes into play when the last character in your subject text is a line break. In that case, ‹\Z› can match at the very end of the subject text, after the final line break, as well as immediately before that line break. The benefit is that you can search for ‹omega\Z› without having to worry about stripping off a trailing line break at the end of your subject text. When reading a file line by line, some tools include the line break at the end of the line, whereas others don’t; ‹\Z› masks this difference. ‹\z› matches only at the very end of the subject text, so it will not match text if a trailing line break follows. The anchor ‹$› is equivalent to ‹\Z›, as long as you do not turn on the “^ and $ match at line breaks” option. This option is off by default for all regex flavors except Ruby. Ruby does not offer a way to turn this option off. Just like ‹\Z›, ‹$› matches at the very end of the subject text, as well as before the final line break, if any.


Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan. Copyright 2009 Jan Goyvaerts and Steven Levithan, 978-0-596-2068-7

To sum up, the only safe way to mark the end of character string is to use \z instead of $. At least if it is input from webpage or any source where user doesn't press enter to confirm their input.
Weird... I was really used to $.

sobota, 6 czerwca 2009

Fancy stuff

Tell me something mister...
If i read everything about:
- design patterns
- dependency injection
- aspect oriented programming
- mocking
- oop principles
- extreme programming
Read The Mythical Man-Month. Twice.
And Code Complete. Three times.
Read all the documents about CLR.
Get to know all the animals from the O'Reilly series.
Read all Jon Skeet articles and answers.
Pass all microsoft exams.
Become mvp in everything from share point to compact framework.
Install vs2010 and .net 4.0 on virtual pc running windows 7.

Will i be able to write single line of code that does exactly what i want to?
Will it be error free?
Will it be easy to modify?
Will it meet open-close principle?

Yes? So i will do it! ;)

Links

.net

Regex character classes


asp.net

inline tags


unrelated

nippon kazauwa

There's something about linq... PART 1

In one of my previous posts i wrote that linq2sql (DLINQ - however you name it) is an example of poor abstraction. After a while of thinking and using linq2sql i must say that i've changed my mind... It is not an example of poor abstraction, it's a goddamn disaster.

At first i thought that linq2sql may be a problem because using same language to communicate with List object, xml document and database seems like mission impossible. What makes me wonder is that all these smart-ass guys at microsoft thought that's an excellent idea. Well, you can communicate with people from different countries without using their native language but that's kinda hard and you just can't express everything. That's the problem that linq suffers from. There are some more analogies. Some people may learn common language like english and then they can communicate pretty well with each other. However, that demands other people to learn language other than their native. Same thing with linq providers. If every datasource had well written linq provider maybe it would be really nice to query everything with linq. Well, i highly doubt that there are good linq providers for even most important datasources. What is more, even if you can speak english because you've learnt to do so, in most cases you won't be able communicate as fluently as in your native language and expressing more complicated/specific thoughts may still be a problem. And again, i'm experiencing same thing with linq. You just can't create common interface for every datasource without creating some methods that will be ignored in most of the datasources because they exist only for the sake of one particular medium.
Enough analogies, i will give some examples.

In this part i want to show one problem that i lately ran into. This problem may seem to be a bit rare but i think it opens whole range of problems that you may encounter using linq2sql. In second part i will provide examples of problems that you may encounter in even simple projects.
I would like to thanks stackoverflow and especially sambo99 for helping me to solve this problem in general.
The details of the problem are here: http://stackoverflow.com/questions/959501/problem-with-deadlock-on-select-update.
To sum up i need get a record from database and then update it. However i was running into a problem when more than one thread tried to this at the same time. Some more explanation. Suppose there are two threads - thread A and thread B. The sequence of events may be as follows:
A: select record
B: select record
B: update record
A: update record
As you can see thread A was updating data that thread was changed by thread B - obvious conflict.
OK, I thought. Transaction at Serializable Isolation Level will solve the issue. So i created a transaction and what i've got?
Exception: Transaction (Process ID 59) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
Wtf? After reading some articles about deadlock, changing indexes in table, rewritting the code for datasets and then even for simple sqlcommands, creating simple test table i went to stackoverflow and fortunately got an answer. Sql server needs a little hint. I need to select the row with (updlock). I tried using some hints before but they didn't work, finally updlock worked. Hurray.
Wait... Hurray? But what about linq? Awww....
Whispering: You just can't do it with linq.
What?
You just can't do it with linq.
Damn.

But smart guys from microsoft came up with some interesting ideas.
Solution 1: create a stored procedure (you must be kidding me... i'm using your wonderful orm just to hear - don't use it - write a stored procedure instead)
Solution 2: you may still write a query by hand and execute on database, sth like IEnumerable version = (IEnumerable)dc.ExecuteQuery(typeof(string), "select top 1 some_field from some_table with (tablockx)"); (ok, you MUST be kidding... do you really call this solution?)
Some more details:
http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/2d6fdb2e-e17e-4a4c-8da0-6968e60ef855
http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/24890e00-f224-4f6a-a596-f9b2f524aa39
http://stackoverflow.com/questions/190666/linq-to-sql-and-concurrency-issues

More examples in part 2, coming soon ;)

Happy coding.