Sunday, November 16, 2008

How to serialize Lambda Expressions

At times I need to serialize my Lambda Expressions, to pass to some web service . Normally this wasn't possible but I realized the MetaLinq project allows it. MetaLinq actually grants us modifiable Expression trees. As you might now know Expression Trees are immutable just like strings. Anyway let's serialize and deserialize a Lambda expression within the code:

Expression<Func<int,int>> myLambda = z => z*z ;

// Create a mutable expression, we are using ExpressionBuilder namespace in MetaLinq here
var mutableExpression = ExpressionBuilder.EditableExpression.CreateEditableExpression(myLambda);

// Serialize it
var serializer = new XmlSerializer(typeof(EditableLambdaExpression));
var sw = new StringWriter();
serializer.Serialize(sw, mutableExpression);

// Get the lambda as string, actually sw.ToString() will give us it in string form

var sr = new StringReader(sw.ToString());

var anotherSerializer = new XmlSerializer(typeof(EditableLambdaExpression));

// Deserialize it
var myex = anotherSerializer.Deserialize(sr) as EditableExpression;

// Convert it to lambda expresion

var myNewLambda = myex.ToExpression() as LambdaExpression;

// Invoke it, outputs 16 as expected
Console.Write(myNewLambda.Compile().DynamicInvoke(4));


So this shows us how to convert an expression to string and restore back to expression and invoke it. DynamicInvoke used here since I assumed we don't know the type here. I hope you find it useful

Friday, June 20, 2008

Web development: Ruby on Rails versus ASP.NET , Flex, PHP and other Java stuff

I've got some feedback from my earlier post on ASP.NET versus Others . In that particular post I claimed ASP.NET WebForms works best for me and I presented my own reasons why I think that way. I might be a little biased may be so I'd like to share my opinions for the other side of the equation, namely Rails versus Others:



There is an old saying that, "Teacher will appear , when the student is ready". The fundemantal reason rails emerged was because there was a need for it, mainly from java developers. Java web frameworks generally have excellent architectures. They are clean and they follow good design practices. However following good design practices made them a bit more academic rather than practical. First the EJB 1 and 2 nightmares frustrated java developers then they settled to some ground with Spring and Hibernate. Although this solution was acceptable, the development overhead was rather large. The idea beyond rails is to compact this entire J2ee thingy to an acceptable size and replace a verbose language like java with an elegant language called ruby and we got rails.

When I first dived into rails I really thought that was the answer I was looking for. So I loved it too much. (Then I went back to asp.net. But I wouldn't do that if there were no mono. I am biased against MS)

Ruby had two main philosophies. "Convention over configuration" and "Don't repeat yourself". We will discuss about them. Also rails was the main push behind the RESTFUL Webservices.

Let's get to Pros and Cons of Rails:

Pros of Ruby On Rails:
*
Open Source and Community Driven
* Cross platform, works every where
* Ruby is an elegant language
* Extremely Scalable (a front end proxy balancer will do it)
* Built in unit testing and ajax support
* Clean seperation of layers
* Zero configuration (convention over configuration)
* Extremely flexible
* Main stream, good community and lot's of books

Well this are the good things come into my mind. Looks promising right ? Let's see the other side of the equation.


Cons of Ruby On Rails:
* Single threaded!!! Wow this is quite intersting for a web framework. Fortunately this doesn't prevent us to build scalable applications
* No unicode yet. You can over come this with JRuby on Rails and IronRuby on Rails
* Green threads. It doesn't use real os threads. Look above.
* The down side of the MVC pattern. You have to type a lot of html
* Database abstraction is too thin. This is something I don't like. The columns in your db implictly becomes properties of your classes. Even if there is no code !!!
* Most software shops don't know about it. So it is unlikely that you can use it at work.


Well that's all in my mind. Let's get into one by one comparison

Ruby on Rails versus Java frameworks:


Now they say a picture is worth a thousand words. That's a true comparison of java frameworks and rails. It basicly eliminates boring stuff like xml configuration of spring and hibernate. Sure Java frameworks is far more powerful than rails. But if you say who needs an 800 pounds of gorilla. Then rails is the right way to go. Note that Java also have JRuby on Rails and Groovy on Rails. This comparison excludes them but points the traditional approach of java web frameworks. I know this isn't enough for technical comparison but that's all I am gonna say about it now.

Ruby on Rails versus PHP:

Yes I am a php basher. Compared to plain PHP rails is superior Period. Plain php is too old. It's like COBOL imho. And the irony is Facebook uses PHP. Well... But PHP has a lot of grown frameworks. Even Rails like ones like Cake or Symfony. A quick google will tell you more. But my suggestion would be to stay away from PHP unless you are dealing with legacy stuff.

Ruby on Rails versus ASP.NET:

I already made a detailed comparsion ASP.NET versus Others. Telling why I found ASP.NET superior. But unlike my php comparison , I find this is a matter of personal taste. Rails is an excellent framework offers valid solutions. If you like more componentize approach with .NET/mono power then ASP.NET is the way to go. Otherwise rails may suit you better.
One technical thing rails is better is that it can emulate true bidirectional associations. For instance:
my_school.students << my_student
implicitly does a my_student.School = my_school

The same situation is extremely difficult to achive with static languages like C#.In general you do explicitly

mySchool.Students.Add(myStudent);
myStudent.School = mySchool;



Ruby on Rails versus Flex:

Now this can't be a comparison because Flex is for pure front end. And you can perfectly use Flex with Rails. Even there is a book for it. Flexible Rails. Some people call Flex+ Rails as the RIA Nirvana. I told you I like a componentized approach. Flex is perfect for that. And rails is very good at serializing the domain data back and forth to Flex. If you can tolarate a flash thingie running inside your application (which I can't!) this is a perfect way to go.

Others:
Wheather rails is a hype or not, it is a really milestone in web application programming. It inspired other web framework developers a lot. Python got Django and TurboGears, PHP got Cake and Symfony, ASP.NET got MonoRail and ASP.NET MVC. Unfortunately I am not involved with them so I can't really compare them.


Conclusion:
If you tried others and still not satisfied try rails. I am sure that you won't regret. And where do you start ? I personally start with the Agile book available on rails' web site. But there is a huge documentation & screen casts on web too. Good luck !

Thursday, June 19, 2008

Java swing developer's painful moments!

I've programmed swing for while when I was java programmer. And I admit it was quite painful for me. At those times, before group layout in netbeans 5 emerged, we were forced to use some silly java layouts. The reason for that was suppose to be the sake of cross platformity. I remember absolute coordinates were highly discouraged in swing world. Instead, all we had was those crappy layouts namely, spring, grid, gridbag, etc. I know some people implement their own layouts and some use things like JGoodies. But all I remember is a bad taste from swing. Now watch this clip.

Funny right ? Well when I watched that I saw my self in a way. I never understood why I have to suffer that much. Now let me show you something. You probably know about the Mono framework I mentioned earlier. The open source .net implementation. It also implemented Windows Forms so that it allows us to run windows forms applications on linux too. And all you need is mono and its windows forms packages. No wine nor nothing else extra needed: Here are some screenshots for NUnit and NClass running on linux:



Nunit above running on linuxNClass above running on linux.

The interesting thing is both applications are written with windows forms (and written for windows without considering cross platformity) and windows forms uses absolute position and docking approach. So I feel pity for the moments I suffered for swing. Thank you mono!!!

Forkwind Part 4: Domain Driven Design and Record Driven Design

Forkwind is a tutorial on how to build a well designed .net application. This is the 4th part of our forkwind implementation. If you are not aware of the master thread and forkwind, please go here first for introduction.


Introduction:

In this part, we are going to dive in to some theory again. We are going to discuss two design methodologies. Domain driven design and record oriented design. In my honest opinion both methodologies are decent. But slowly record oriented design isbecoming obselete. Actually this discussion is not very popular in the software world beyond .net. Most of the recent frameworks like rails and java frameworks use domain driven design as de facto standard. .NET world however is quite lagging in this manner.

What is Record Oriented Development ?

I am not going to make a formal definition. But in practice, record oriented development focuses on the records within the database. It is record centric in a sense. Database records are passed within layers. Records are just mere containers and having no semantic meaning. In .NET world datasets used together with datatables are good examples to this methodology. They are mostly typeless but just records. In .net 2.0 we had Typed Datasets but they are merely generated code.

Usually the first step in record driven development is to design the database , tables and relations and build your application on top of that. If we were developing Forkwind in a record oriented manner, then first we would have created tables like Company, Product, Supplier ,etc


What is Domain Oriented Development ?

In domain driven development, we define domain entities to solve our particular problem. It is a more object oriented approach. For example Forkwind is an application to keep track of orders to customers and suppliers. So we create typed objects like Customer and Supplier as a first step. We generally ignore the database design to later part thanks to ORM tools and object databases. Though there is one exception to that : If the database is already created and with full of data then we have to adapt our domain entities according to that tables. This is a common and painful scenario with domain driven development.



Why domain driven development is not popular in .NET ?

This has historical reasons. Before .NET, I was coding with MFC and pure Win32 for gui stuff in windows. Frankly speaking both MFC and Win32 was dirtier than my toilet. The api was terrible. Then came the Visual Basic 6. When VB6 emerged, my neigbour's son became a more productive programmer than I am. VB6, which I never liked, allowed developers quickly design applications. Managers liked it very much because all that matters was the software running. They are not concerned with the maintenance nightmare coming from "Quick and Dirty" approach of VB6. I also conspire Bill Gates himself was a big pusher of Visual Basic because of his personal sympathy to BASIC. VB6 was using ADO to connect database which is completely record oriented. So when .NET emerged , record oriented approach already widely accepted in .net world. Also microsoft used this fact to sell its IDE so called Visual studio to show how easy to create an application just by dragging and dropping a database table to the screen. They made a propaganda on that this approach such that you are suppose to produce quicker (but dirtier) applications and you will save money on development costs (but lose on maintenance). The last reason is the Microsof's failed ORM Mapper called Objectspaces. Microsoft was planning to deliver this ORM mapper with Visual Studio 2005. But project failed miserably. So MS silently carried on ignoring domain driven development methodologies till 2007-2008 where we have linq to sql and ADO.NET Entity framework now.

Enough history let's get into technical details:

Domain Driven Development Pros:

* More Object Oriented approach
* Much better maintenance
* Sounds more correct

Domain Driven Development Cons:
* Less mainstream on .NET
* Requires skill!!
* You have to use things like ORM

Record Driven Development Pros:
* Easier for novice
* Visual studio tools integrates better
* Faster development (though pace diminishes if project grows)

Record Driven Development Cons:


* Likely to lead maintenance nightmare!!!


Basically Domain driven development dissects a complex problem into smaller pieces. But it can be complex at times. Record driven approach is more simple, just get the records from the db and publish. Since we usually aim better design and better maintence in general , domain driven approach is favorable to me. And that's what we are doing in Forkwind.

In the next part * Forkwind Part 5: A first visit to unit testing: (Not Available at the moment) again we are back to coding. We will write our first unit tests for Forkwind. Till then stay tuned!!




Real Human Face with 3D Flash

Now isn't this fantastic!!! Just move your mouse and it follows:





The original site is :http://motionportrait.com/

Wednesday, June 18, 2008

Forkwind Part 3: Creating the domain model :

This is the 3rd part of our forkwind implementation. If you are not aware of the master thread and forkwind, please go here first.

Introduction

After discussing about modules and assemblies in part 2, we can again get our hands dirty with the code. Once the project skeleton up , the next thing is to implement the model or the domain model.
Technically the domain model has nothing to do with code but this is something you should be able to generate while thinking about the problem or discussing with the customer. For instance, the Forkwind application is a solution for tracking orders from suppliers and customers. So considering these, what concepts are being visualized in our minds ? We have a supplier and we have a customer. We also have orders. Since we have orders, we have also products. This is a very basic abstraction but it is extremely useful. We should also be able to tell the relationship type between these entities. For instance a supplier has many products

You should be able to do this just by thinking or with a piece of paper and pen. The rest of the implementation is just filling the gaps and details.

Forkwind Domain Model:

Since we have modelized the basics, we can fill the gaps by simply scetching an informal class diagram. I use a small program called dia but a piece of paper is just good. No need for fancy uml software.

Here's my diagram:



If it it doesn't make sense to you you can follow it from the source where I posted at the end of this post.
Here's my solution explorer:


When you look at the code you will see all properties marked as virtual. This is due to we will use NHibernate in the next posts and in order to do lazy loading properties must be virtual. Don't worry we will come to that.

Let's go each of these classes briefly:

DomainObject: This is the base class for all our entities. This is the place we can put common code. Currently it has an Id field. This for mostly nhibernate but it is practical to have an Id for each of our domain entites (I would use a guid type for an object database like db4o). It's type is long.

Company: This is the base type for suppliers and customers since we assume they are companies. It has general properties like Name, Adress etc. A company has one address.

Customer : This is derived from company and represents our customers. Also a customer has many customer orders.

Supplier : This is dervied from company and represents our suppliers. Also a supplier has many supplier orders and a supplier has many products.

Product: This represents a product type actually not the product itself. This is a common confusion when developing our models. Our product has a property called Quantity. But for an instance of the product the quantity would be always one. But in general we model the product type as model. A product can belong to many categories and a product belongs to a supplier.

Category:
This is for categorizing our products. It is hierachical. A category has one parent category and a category has many children categories and a category has many products.

Order:
This is the base class for SupplierOrder and CustomerOrder. Why I seperated those into two ? This is completly with instict. I just presume they might have different behaviorus and properties depending on your company policy. An Order has many OrderLineItems.

SupplierOrder:
Derived from Order. A SupplierOrder has a supplier

CustomerOrder:
Derived from Order. A CustomerOrder has a Customer

OrderLineItem:
This represents an each line in our Orders. An OrderLineItem has a Product.

OrderStatus:
This is basically an enum represents the state of our orders. It can be pending (by default this is set in the Order's constructor), cancelled or completed

Address: Represents an address used by a company.

This is pretty much about our domain model. It looks okay to me and it is ready to be cooked. Sure we might refactor it. One thing you should notice, we haven't done anything about database. Because this is domain driven design, it is the domain that derives our design and we completely ignore the database unlike the traditional approach.

The code is here. In the next part Forkwind Part 4: Domain Driven Design and Record Driven Design we will get into some theory and investigate why we have chosen domain driven design over a database driven design. Till then stay tuned!




Tuesday, June 17, 2008

Forkwind: Part 2: Modularity, .NET Assembly and Namespaces

This is the 2nd part of our forkwind implementation. If you are not aware of the master thread and forkwind, please go here first.

Introduction

In this article, I'll briefly dig modularity and how it maps into .NET assemblies. Modularity is simply dividing our applications into smaller modules. The benefits are obvious: Debugging is easer, and multiple people in the team can work in different modules without affecting each other. Finally, modules are rather isolated so further modifications can be made to one module without breaking the system. This provides us good maintainability for a particular project.

In .NET world, our assemblies act as modules (formally, a module is a code file in .NET but we will ignore this fact to prevent confusion). Each project we create in Visual Studio corresponds to an assembly. It can be a dll or it can be an exe. Even for a web application (and not for a website!) all we get is a dll along with some aspx files. .Net assemblies also provide us additional benefits like versioning, security and ease of deployment.


Assemblies in Forkwind:

In Forkwind, in Part 1 as you remember we have generated several projects/assemblies. This may seem natural to you since we have a layers: a gui layer , a test layer etc. But why did we create separate projects ? It is technically possible that we could have created a web application project and we could build all our code right into that (and even including unit testing). Is it to reduce the pain of an environment with multiple developers ? Certainly not. If you read above my informal definition to modularity, you will understand the reason. We are looking for good design! And good design dictates us building our application in modules. In some case it is perfectly valid to have a single assembly and in some cases using multiple assemblies can be overkill. Only experience can tell when to use what.

Specifically talking on .NET my rule of thumb is if I expect a layer to be replaceable with another equivalent code, I create an assembly for that. So my repository implementation might change in the future , thus I create an assembly for that particular layer. If not I would lean towards a more monolithic design. Is this my only criteria no ? For a plug-in like system again you have to create assemblies so that you can load them on runtime without stopping your main executable. Finally an assembly like Forkwind.Test should be seperate. Because it doesn't belong to code. It is ony useful for testing. It has no business within the production environment to create excessive code. So for optional components again I create an assembly. Finally when there are issues of versioning, or a different security setting is concerned I create an assembly for that again. The rest really depends on your taste.

What about namespaces ?
From time to time, I see some novice developers are confused about a namespace and the assembly name. This is due to mainly relying on Visual Studio's intellisense. Namespaces and assemblies has nothing to do with each other actually. They are apples and oranges. A namespace's solely purpose is to prevent Class name clashes. It is NAME-SPACE ! An assembly is more like a module. And just because you can use a namespace like System.Configuration appears with intellisense in Visual studio, it doesn't mean that you are actually making use of the System.Configuration assembly. In deed, all you see is the System.Configuration namespace within System assembly!

One exception to this , namespaces have another use in C# 3.0 which allows resolution for extension methods.

So that's it for part 2. No new code in this part. But we will get our hand very dirty in next part:
* Forkwind Part 3: Creating the domain model

Stay tuned!!!

Forkwind Part 1: Creating skeleton of the application layers as . net assemblies

This is the first part of our forkwind implementation. If you are not aware of the master thread and forkwind, please here first

As being pragmatic without diving into deep theoretical discussions we first create our project skeleton.


As seen in the picture our forkwind implementation consists of 8 projects which are also assemblies. If you are unfamiliar with assembly concept just hold your breath a while that we will discuss modularity and assemblies in the next part Forkwind: Part 2: Modularity, .NET Assembly and Namespaces.


Let's go through each assembly and discuss why we need them briefly:

Forkwind.Core: Obviously this is our core assembly. We are planning to put most of our business logic , our domain entities service layers here. One key point is Forwind.Core should not depend any other assemblies but be able to self compiled. In this case it only uses Forkw


Forkwind.Repository: The name repository may look unfamiliar to you. But this is simply an evolutioned version of your old data access layers or DAO's or what ever you call it. Why I call it Repository ? The simple answer for now is we have domain objects and one of our aims is to encapsulate data access as internals so that our application is unaware of the datasource. More details will come in following parts. Don't worry about it at the moment.

Forkwind.Presenter: This is our presenter layer. If you are unfamiliar for presenters their main job is to bridge the core layer and the gui. They prevent business logic leaking to UI layer.
It's mostly modeled after Martin Fowler's model view presenter. And again we will discuss it throughly. For the time being it provides a GUI agnostic backend , also enables us to unit test our guis.

Forkwind.Test: This is for unit testing obviously. I will use nunit but anyother unit test framework is ok.

Forkwind.Util: This is for general utility stuff. We can make use of C# 3.0 extension methods here as well. All other assemblies may make use of this assembly.

Forkwind.Web: This is our assembly for the web application (and not web site!!).

Forkwind.Console: This is our assembly for a console application which make uses the same backend. It's mainly demonstrative purposes so that it proves our implementation is GUI agnostic. But you can further improve it as you like


Forkwind.Windows : This is our assembly for a windows application which make uses the same backend. It's mainly demonstrative purposes so that it proves our implementation is GUI agnostic. But you can further improve it as you like.

SharedLibraries: This is not a project but a pile of third party libraries to be used by other projects.

Well that's it. Let's see the dependecy of our assemblies:


For simplicity I removed console from diagram but same as Windows and web. All assemblies except references Util. And Test references all other assemblies.

In old designs typically we have GUI -> Business -> Data Dependency. But this doesn't sound correct to me. If business depends on data then any changes on the data layer may break our business layer as well. This is totaly unacceptable. This is why the dependency is inverted here. And our core assembly is stand alone (except it makes use of util). This way it won't be affected of any changes happening in any other assemblies. We will get into details in the following parts so stay tuned!

Code is attached for this section here


Next part is :
Forkwind: Part 2:Modularity, .NET Assembly and Namespaces


Forkwind: Application Design from Beginner to PRO with .NET and Mono

Introduction:
The purpose of this article is to demonstrate one of the good ways for application design with .NET and Mono. I will be using .NET and C# 3.0 through this but I will be also careful for mono support so your application will be running everywhere. We will develop an application called "Forkwind" which is an imaginary company:). We will do a lot of discussion on the mean while. Feel free to correct me at any point if you disagree with something. Additionally I am not claiming my methodology is the best. It's just something I am happy with it. Lastly this is not my own design. I gathered this information around web. I am inspired Mainly Billy's excellent article
http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx.

But i will slightly diverge from his way and try to do a lot of in depth theoretic discussion. I am expecting this to be a very long series so I'll divde it into some sub parts and , I'll try to implement it every day if I can.

What we are going to do, is to design and code an application called Forkwind. Forkwind does not have to be a web application. The aim is making it so flexible that a console gui or a windows forms will also fit. Forkwind will be a simple crud application but feel free to extend it.

This is the master post for other sub articles so visit this post frequently and I will update and implement articles. Generally I'll first implement the practice then the second post will include the theoretical discussion. Oh yes and I will post real sample code. !!!

Here are the topics:

* Forkwind Part 1: Creating skeleton of the application layers as . net assemblies: (Updated on Jun 17, 2008)

* Forkwind: Part 2: Modularity, .NET Assembly and Namespaces: (Updated on Jun 17, 2008)

* Forkwind Part 3: Creating the domain model : (Updated on Jun 18, 2008)

* Forkwind Part 4: Domain Driven Design and Record Driven Design : (Updated on Jun 19, 2008)

* Forkwind Part 5: A first visit to unit testing: (Not Available at the moment)

* Forkwind Part 6: Why unit testing is so important : (Not Available at the moment)

* Forkwind Part 7: A first visit to persistence and database stuff in Forkwind: (Not Available at the moment)

* Forkwind Part 8: Repository pattern , DAOs and DAL: (Not Available at the moment)

* Forkwind Part 9: What are my persistence options in .net and which one I should use: ( Not Available at the moment)

* Forkwind Part 10: Log4Net putting logging into work: ( Not Available at the moment).

* Forkwind 11: Dependency Injection in Forkwind With Castle Windsor: (Not Available at the moment)

* Forkwind 12: Benefits of Dependency Injection, connecting decoupled pieces: ( Not Available at the moment)

* Forkwind 13: Fowler's Dependency Inversion and Assembly dependence ( Not Available at the moment)

* Forkwind 14: Alternatives to CastleWindsor: Spring .NET, Sturcture Map and unity : (Not Available at the moment)

* Forkwind 15: The need for Service Classes: (Not Available at the moment)

* Forkwind 16: Unit testing revisited ,mocking comes into the scene: (Not Available at the moment)

* Forkwind 17:The GUI: (Not Available at the moment)

* Forkwind 18: Model View Presenter:(Not Available at the moment)

* Forkwind 19: Model View Presenter Continued:(Not Available at the moment)

* Forkwind 20: Unit Testing the GUI:(Not Available at the moment):(Not Available at the moment)

* Forkwind 21: Databinding to ASP.NET:(Not Available at the moment)

* Forkwind 22: A Console and Windows GUI:(Not Available at the moment)

* Forkwind 23: NHibenate in Depth:(Not Available at the moment)

* Forkwind 24: Active Recording With Castle ActiveRecord:(Not Available at the moment)

* Forkwind 25: Active Recording With DB4O:(Not Available at the moment)

* Forkwind 26: AOP and limitations of C# :(Not Available at the moment)

* Forkwind 27: Compacting the application:(Not Available at the moment)

* Forkwind 26: Final Words:(Not Available at the moment)

Monday, June 16, 2008

Some history for ubuntu and worst releases

Canonical releases a new ubuntu every 6 months and time to time it does a LTS (long term support) release which is suppose to be most stable. So far Canonical made 2 LTS releases: Ubuntu 6.06 dapper and 8.04 hardy. Ironically,in my personal experience , they are the worst releases of ubuntu. In detail I am having lots of program crashes in gnome and I am not even telling what happened when I first turned off my computer after upgrading to hardy. In general ubuntu releases have hiccups at very beggining and after 1 week from the release they run quite good. But this didn't happen with hardy. Today, I made a simple google search that verified my thoughts.

I googled ubuntu xxx "worst release" where I put, dapper, edgy, fiesty, gutsy and hardy . I know this isn't a relaible test. But results were almost all telling dapper and hardy worst releases. I saw 1 search result for fiesty.

Dapper actually was the first release that ubuntu maturized. Before dapper ubuntu had 3 releases called: warty , hoary and breezy ( I am not selecting the names!). They were nice but too amateurish (frankly I never used warty but I started with hoary but I guess same applies to warty). Dapper were 2 months late to it's normal schedule. And it was so terrible that canonical released an 6.0.6.1 version. And july 3, 8.04 will give a 8.0.4.1 release. And both of these are LTS and both are terrible.

Earlier I was using Suse 9.3 till it wiped out my disk. When I switch to ubuntu I really like it. They become a major push for innovation in my honest opinion. And I am delighted with its great community. I use Ubuntu since 2005 as my primary desktop machine. I've upgraded my current laptop as 6.10 -> 7.04 -> 7.10 -> 8.04 without formatting almost 1.5 years (which is some achivement compared to windows considering you have to format it every 6 months and pay another licence fee every 3 years for a new version!). However it seems this time I am going to give opensuse 11 (on gnome!!!) another shot.

Saturday, June 14, 2008

C# Glorified : Nemerle!



Nemerle is a CLR based programming language. Just like C#. It works on .NET and mono. It can reuse libraries written with C# and vice versa. Basically it is C# glorified in my honest opinion. I've encountered nemerle a long time ago and it was quite matured since then. As a developer I was looking for more power and nemerle gave me what I want. It is definitely not a newbie language but is very very powerful. It is basically unification of C# and OCALM with enhanced macro support. Here are some features:

* Cross platform: Nermele is an open source CLR based language, it runs on mono / linux and .net platforms.

* C#/Java like syntax (statically typed): The syntax is similar to C#.


* Functional : Nemerle is functional.


* Macros : This is what makes nemerle very powerful. Basically it allows you to invent your own keywords. The language normally does not have constructs as if. But instead they are created as macros.

Here is how or a reverse loop implemented basically:

Code:
macro ReverseFor (i, begin, body)
syntax ("ford", "(", i, ";", begin, ")", body)
{
<[ for ($i = $begin; $i >= 0; $i--) $body ]>
}
then you can use this :

Code:
ford (i ; n) print (i);
You see! "ford" is on our own keyword.


* Type inference with Generics : Unlike C#/Java, this syntax works:
Code:
def d = Dictionary ();
d.Add ("Ala", 7);
foreach (s in args) {
...
}

* Builtin Design By Contract :
Code:
public Substring (startIdx : int) : string 
requires
startIdx >= 0
{ ... }
Here we say startIdx must be =>0 . Contracts are builtin!

Code:
public Length () : int ensures value >= 0
This ensures the property returns >= 0 values otherwise an exception is thrown (we can also customize that exception).


Code:
Class Vector [T] invariant position >= 0
{
private mutable position : int = 0;
....
Here, we say for the life time of this class , position can't be less than zero !

Speed : Ironically nemerle compiler is written with nemerle itself which is CLR language. Because of Runtime JIT'ing the speed is somewhat close to (average about 80% levels) to native C code.

* Interop : nemerle can interop with any CLR language. You can use windows.net libraries or mono libraries, you can intermix your code (in seperate assemblies of course ) with C# or you can reuse your nemerle libraries from C#

For more details go to here: http://nemerle.org/Features

Friday, June 13, 2008

Web development: ASP.NET Webforms versus Rails, Flex, PHP and Java stuff.


Some History:

I am a long time web developer and making a living from it. For my entire programmer life, I looked for perfection for developing applications. I remember back in 2002, I was struggling about if thick clients or web clients were better for typical form processing. At that time richness of thick clients were more attractive than these days since we did not have all ajax goodies, flex, silverlight etc.

Time passed and I decided to go for web apps. and I have no regrets so far. Not that I am claiming it is a better way but I am just happy for my personal development.

Then came the next question: I need to go with some platform/framework etc. I've worked with a lot of technologies: ASP, ASP.NET, PHP, Java frameworks (Wicket, struts, Echo, plain JSP) , Flex, silverilght, Perl CGI. I felt uncomfortable with the number of choices since it is impossible to specialize all of them and it was extremely hard to predict which of these technologies have a future (and even now). Selecting a technology is difficult, you need a very good eye for that. Common sense says: "use right tool for right job". And yes frameworks are tools. But unlike that analogy, these days frameworks are so powerful that most of them claims to be suitable for "every job". For instance, you can write executables with PHP, you can write desktop applications with Flex via AIR and with .NET and Java you can do almost everything you can imagine and even you can write operating systems with them ( SharpOS, Cosmos, Singularity, Jnode ).

I started web programming with Perl /CGI then I quickly moved to PHP and then Java and then as a requirement of my job I first met with ASP.NET 1.1. And I hated it. Then came ASP.NET 2.0. I was extremely impressed with ASP.NET 2.0 at that time. It really seemed to me that
MS really did a good job with it. But after sometime passed, I missed neatness and good design in Java frameworks. ASP.NET 2.0 was very practical but it completely ignores good design practices which leads to unmaintainable crappy code. Specifically talking about webforms since it was the only thing running on ASP.NET.

Finally, I've met Ruby on Rails. I've done some projects with rails and I really really liked it! Everything smells correct with rails. And it is much easier than java or .net. I also like linux so I thought I was finally off the MS lock in. However, later while dealing with ruby, I start to feel uncomfortable on things like dealing HTML manually , unicode problems, and green threads. It was painful to use a multi select html selectbox with rails where you use nested arrays for that and it looks ugly.

Finally I returned back to ASP.NET forms but with a different eye! I quit following MS practices ,instead I applied things that I learn java and rails. I feel much happy now and Webforms is my favorite platform. This article will be comparison of webforms with "others" based on my personal experience. I might be wrong so feel free to correct me.
But first lets dispell some myths:

Myths for ASP.NET Web Forms:

ASP.NET runs only in Windows: This is a major problem to many people. I am a linux fan and I use linux and develop on linux everyday. And we have great Mono project runs asp.net successfully on every platform. It is quite up to date too. Everything works there including Ajax, Ajax control toolkit, asp.net futures, asp.net mvc (although illegal to do so) . The only missing parts is Web parts and the new listview control (listview implementation is underway!).

ASP.NET Web Forms are easy: Unlikely the demos made by MS, dragging and dropping stuff, ASP.NET is extremely complex, but also powerful.

You can only use C# and VB with ASP.NET: You can use C#, VB.NET, IronPython, IronRuby, Boo, Nemerle with ASP.NET. There are possibly others but these are the ones I know working.

Pros for ASP.NET Webforms:
  • It uses .NET platform so entire .NET library is at your command.
  • Extremely well documented and main stream
  • Cross platform. With mono it works everywhere
  • Mono ASP.NET is open source
  • Component and Event Driven, so you are not usually messing with Javascript and HTML
  • Ajax is extremely easy. Use an updatepanel and you are good to go
Cons for ASP.NET Webforms:
  • Can be extremely complex. Loading dynamic controls on runtime , view state issues , custom controls , ASP.NET Page Life Cycle are too complex. I mean it!!!
  • Viewstate! It helps a lot to emulate a stateful web. But it can be a true performance killer if you are not careful
  • Generated HTML : ASP.NET generates complex html that doesn't play with other things easily. You can catch yourself dealing with ctl100_xxx_yyy type of Id's. CSS and Javascript can be painful too. But ASP.NET webforms philosophy is different. you have to get it really!!!
  • Hard to unit test. I was really puzzled for this. Unit testing is important. I invented my own Model View presenter pattern to get around this issue.
Even though that cons I still like ASP.NET Webforms best. It is extremely powerful if you know how to use it correctly.

And now the comparisons:

ASP.NET WebForms versus Rails:
I really think asp.net is superior to rails. Firstly, when you develop an n-tiered web application, it doesn't have to be a web application at all in future. That's why we have n-tieres. We could replace the UI layer with any other thing. You can convert it to a thick client application a socket server or what ever you like. Rails is a web framework period! You develop a web application and you have to live with it. Most of the time this is not a big deal since your purpose is developing a web application anyway. But I like the flexiblity of n-tiers.

Secondly, Rails, actually ruby has no real threads and it is 200x slower than C code. In fact,this has never annoyed me in practice but I feel more relaxed that I could use real threads with .NET. Additionally, unicode is breeze with .NET where rails fail miserably.

Rails use a template approach that if you intended to generate html pages, which gives you a nice clean seperation of your ui from controllers. But you have to type a lot of html and yes I am aware of HAML. ASP.NET allows you to build components and those components can talk each other with events only. This leads to a very good isolated design. Also things like output caching allows you partially cache some parts of your pages. I see no equivalent of this in rails.

Furthermore, Rails' Ajax is not as easy as asp.net. You deal with RJS templates although you can use things like JQuery or Ext or YUI , that way you make a language switch.

Ruby is a better language than C# imho. C#, although 3.0 version is fantastic is a bit verbose compared to Ruby. But I still like C# very much. But if you want power there are much better languages than ruby in .NET/Mono world like Boo and Nemerle. They are extremely powerful and you can develop asp.net apps. with them.

And for backend, Rails has ActiveRecord but so does ASP.NET: Castle ActiveRecord.
And even with .NET you have something better than Activerecord . Enter DB4O!
No more mapping , with db4o you can truely ignore you persistance layer and store your objects as they are which is difficult to implement with rails.

Another point is internationalization, and multi langauge applications are very easy with asp.net via Resources. Rails has globalize plugin for that and works well but it creates some messy tables in the db.


ASP.NET WebForms versus PHP:
I am sorry for PHP fans but syntax is really ugly. PHP doesn't feel like an OO language. PHP 4 was an hybrid lang and PHP 5 implemented full blown OO stuff. But still I don't feel OO paradigm with PHP. It also suffers the same problem with Rails. Too much dealing with HTML. PHP has rails like or even ASP.NET like libraries. But still too low level for my taste. One good thing about PHP is it's extremely wide-range of library support. Other than that I see no reason to you php except for dealing legacy applications.



ASP.NET WebForms versus Java stuff: JEE versus ASP.NET is a long time debate actually. Java has a lot of decent web frameworks. They are mostly component oriented like asp.net. I can't bash them but ASP.NET Webforms looked much better than JSF, struts. and yes .NET has NHibernate and Spring .NET. Also C# is a better language than Java (just side by side language comparison not runtimes!).


ASP.NET WebForms versus Flex: Flex is extremely powerful. And it archives things that ASP.NET can only dream of. Very componentized, very elegant! The only thing I dislike about Flex and disconnected frameworks like ExtJs or Qooxdoo is that you have to serialize your Domain entities. And if you have bi-directional associations those objects cannot be serialized into JSON or XML. WCF provides a workaround for that but I doubt it will be useful with anything besides .NET. Then you have to build with DTO's. Same problem happens to be with Rails + Flex or Rails + Extjs. Rails creates DTO's on the fly with toXml or toJson thingies.

ASP.NET WebForms versus ASP.NET MVC or MonoRail:
First it is illegal to run ASP.NET MVC on linux so you are locked into Windows. Second ASP.NET MVC and Monorail although can use ASP.NET components they cannot use Postback controls. Then you drop to HTML once more for many things. Ayende "The Great" (that's what I call him), rightfully complains the complexities of WebForms and he prefers MonoRail . I can totally understand him. His points against web forms are valid. But I think this is a matter of a personal preference when you compare pros and cons.

Well this is the end. Feel free to criticize and correct me. Happy web programming !