Monday, February 28, 2011

Comparing 2 databases

The comparison of databases are often required if you are dealing with business applications which has frequent change in databases. Most of the time its the difference between data base stored procedures and table schema.There are so many comparers available which even compares the table data!!.

One method is to write queries to find out sql differences.That suitable if we have some special comparison scenarios.Else use any tool which compares the data.

Here is one free database comparison tool which is free and compares the schema
http://dbcomparer.com/Download/Default.aspx

Sunday, February 27, 2011

What is Dynamic Linq Expression and creating DynamicMethods

Before going to details of dynamic concepts lets make our understanding about static more clear.Below is a normal method we all learned when we started programming.

public int Add(int a, int b)
{
return a + b + 10;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show(Add(1, 2).ToString());
}


This is nothing but 2 methods.One is  Add which adds 10 to the sum of the passed arguments.Another is to call the Add method by passing parameters 1,2.The result will be 13.No doubt in that.Lets look at the below code which I will say equivalent of the same but less lines.

private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show(
new Func<int, int, int>((a, b) => a + b + 10)(1, 2)
.ToString());
}


Where is the Add method? You can see it as a lambda expression.The lambda function is executed by passing the arguments 1,2 and displays 13 as result.Don’t confuse on the Func.Its a delegate type not any special keyword.

These are static  : You can see that the execution logic is hard coded at the compile time itself.Or in other words by looking at the code, we can tell that how this is going to execute.Hope the word static is clear.Lets go to the dynamic world.

Dynamic Method

Here the method body is constructed at the runtime.The compiler is not compiling this methos and making any byte code for storing in assembly file. This is implemented through Expression classes available in .Net.

Concepts of Expression

If you had studied the compiler subject in your college days properly, you know that our code is constructed of expressions.If we write a=b in C# ,its an assignment expression.for loop is another type of expression.Try block is again another expression type.In short all the statements which we writing in our code is seen as an expression by the compiler.

That’s fine.Have you ever thought of a scenario where you need to create the code dynamically and compile as a method which should execute on the fly? If yes the System.Linq.Expressions namespace is for you.

Expression allows us to create code blocks dynamically as a expression tree using different types of sub expressions which can be compiled as a delegate object for execution.

We cannot say we are creating C# code ,but the equivalent object structure using classes which are derived from the base class Expression.ie we are creating objects which represent our code statement and relating them as how we write the code.The addition statement (a+b) is represented using an object of BinaryExpression. This has 2 properties Left and Right of type Expression again which are nothing but the parameters(a,b) to the + operator. While evaluating it behaves same as how our normal code runs.

using System.Linq.Expressions

This namespace contains a bunch of classes which helps us to create language expressions through code.The expression types include ParameterExpression, ConstantExpression, TryExpression and even the LambdaExpression. While creating your code expression tree use the appropriate classes and connect them properly as how you write code and finally create the LambdaExpression.LambdaExpression has the Compile method to get the delegate out of it. Execute the delegate to execute the created expression code.

Below is the Expression equivalent of the above static code.



private Delegate GetExpression()
{
ParameterExpression p1=ParameterExpression.Parameter(typeof(int),"a");
ParameterExpression p2=ParameterExpression.Parameter(typeof(int),"b");
ConstantExpression c=ConstantExpression.Constant(10);
BinaryExpression be1=BinaryExpression.Add(p1,p2);
BinaryExpression be2 = BinaryExpression.Add(be1, c);
LambdaExpression lambda = LambdaExpression.Lambda(be2, p1, p2);

return lambda.Compile();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show(GetExpression().DynamicInvoke(1, 2).ToString());
}


I don’t think there will be confusion in creating the Expressions and linking them.There are no constructors.You need to use the factory methods.Once the LambdaExpression is created you can Compile it to get the delegate.Invoke that delegate to execute your dynamic method code.

Expression Tree

By closely observing the object creation we could see the expression objects are linked as a tree structure .The root is the LambdaExpression.This is why it is called as expression tree.

Expression Tree is nothing but an object oriented representation of code.

I hope nobody have doubt on dynamism.By looking at this code we cannot say how the generated method will work.

Applications

There are lot of applications such as creating expression evaluators, even a new programming language of your own!!! According to my understanding the DLR is using these expressions.

If you had started in .Net from its 4.0 version you will say wow! what a feature.But if you are a developer who had worked in earlier versions one question might have popped up in your mind.Do we really need Linq Expression to generate code on the fly where we have CodeDom? Whether you have or not I have this question.Hope I can find the answer soon and share here.

Saturday, February 26, 2011

Concepts of PropertyBag and the ExpandoObject

Need for PropertyBag
Lets consider the scenario of dynamic table creation in your database.User is allowed to create screens dynamically and for those screens they can even customize the business entities including creation of new entities.In this scenario you can’t create your business classes concretely.The reason is simple you don’t know what entities will come and how many properties they will have and their types.

The solution to this problem ie “Handling dynamic tables through business objects” is PropertyBag

What is PropertyBag
Property bag is nothing but a dictionary which keeps the property name and their values.Below is a sample implemenation.

public abstract class EntityBase
{
Dictionary<string, object> _propertyBag;
public object this[string propertyName]
{
get
{
return _propertyBag[propertyName];
}
set
{
_propertyBag[propertyName] = value;
}
}
}


Normally there will be one more checking for the typed properties.If the typed property exists the getter will return the value of the typed property and setter set the same.Dictionary will be used only when there is no typed property.

Using the property bag is through the indexer property.If there is a EntityBase derived Customer class with typed properties Name and Id, we can use this property bag to store a new value as Address property without recompiling the Customer class.


public class Customer : EntityBase
{
public int Id { get; set; }
public int Name { get; set; }
}




Customer cust = new Customer();
cust["Address"] = "Cochin";


Works perfect even though we can’t write like which we prefer.

cust.Address = "Cochin";


But this is type safe and from the view of typed language it should not compile.There should be no exemption for any class from having dynamic properties.


ExpandoObject

The above said story became history with the arrival of the ExpandoObject class in .Net 4.0 which allows dynamic properties.


dynamic  eo = new ExpandoObject();
eo.Joy = "My Name";


Joy is not at all a property of ExpandoObject class.But it compiles and works.The backend implementation is dictionary though.Ok there is one more argument that if we re-write our implementation using the new .net4 dynamic keyword will it work?

dynamic eo = new Customer ();
eo.Joy = "My Name";


Yes I meant the above code snippet only.This will compile.But on execution it will throw an exception of type RuntimeBinderException with the message “'Expression_Test.Customer' does not contain a definition for 'Joy'”.

Ok.Now you might be thinking that we can change the base class of our Customer entity class to ExpandoObject.But we can’t because the ExpandoObject is sealed :-(


DynamicObject class

There is another class named DynamicObject.We need to inherit from this class which implements the IDynamicMetaObjectProvider interface.Change the customer class as


public class Customer : DynamicObject
{
public int Id { get; set; }
public int Name { get; set; }
}


Compile the program.No errors…You may be thinking that its done.But actually not.When you run you will get the same RuntimeBinderException.Why we are getting this even after inheriting from a base class.That class should handle it right? Goto the definition of the DynamicObject class.You can see all the methods are virtual.Mean no code is written to handle the properties.ie property bag is not implemented there.Now what to do? Overriding in each and every entity class and implementing property bag is not possible because in a real business application there will be hundreds of business classes.

Return of the EntityBase class

Come back to EntityBase and inherit it from DynamicObject and override methods and use the same old dictionaryto set and get values.Here is the final code.


public abstract class EntityBase : DynamicObject
{
Dictionary<string, object> _propertyBag;
public object this[string propertyName]
{
get
{ //Code to check typed properties,if exists return that value
return _propertyBag[propertyName];
}
set
{ //Code to check typed properties,if exists set that property
_propertyBag[propertyName] = value;
}
}

public override bool TryGetMember(GetMemberBinder binder, out object result)
{ //Code to check typed properties,if exists return that value
return _propertyBag.TryGetValue(binder.Name, out result);
}

public override bool TrySetMember( SetMemberBinder binder, object value)
{ //Code to check typed properties,if exists set that property
_propertyBag[binder.Name] = value;
return true;
}
}
public class Customer : EntityBase

{
public int Id { get; set; }
public int Name { get; set; }
}


Now the below code will compile and run without any exceptions.

dynamic eo = new Customer   ();
eo.Joy = "My Name";


Unusual relation between Language and Framework SDK

All is well.Now we can write code normally for even non existing properties.How this magic is happening? The compiler doesn’t show any error message because it all done on a variable declared using dynamic keyword.Come to runtime.How the runtime knows that it should call the TryGetMember method? Some understandings between the framework types and the runtime?

Yes.The key is IDynamicMetaObjectProvider interface.If the class has implemented this interface the runtime will call the TryGetMember and accepts the value. Don’t you smell an unusual relation between runtime and the Microsoft classes? You must,if you had worked in any other languages or technologies.

Friday, February 25, 2011

Using keywords as variable or function names

When you are writing a program, you find one of your variables need to be named as volatile because of its nature or some other reason.But you cannot name it as volatile because volatile is a keyword.So what to do?

prefix @ to the variable or the method name and it will allow you to compile.

public int test(int @volatile)
{
return @volatile++;
}
public int @volatile(int index)
{
return index++;
}


Another way is to prefix ‘_’. But if the ‘_’ is reserved for the private class field prefix as per your coding guidelines you cannot use it.

There is one question exists still.If I prefix @ , its no more the the same volatile word.So why can’t I change the variable name to something else such as volatileIndex without the @ char? Then I don’t have any answer.Change the name as you like :-)

Wednesday, February 23, 2011

Handling KeyPress at Form level

I don’t think this will help a experienced Win Forms developer. But it will help a fresher.

Here is the story.One of my colleague is developing a simple tool and he wanted to capture key strokes such as Ctrl+K,C like Visual studio.The plat form is windows forms and he handled the KeyDown event at form Level. But the break point didn't hit because the focus is always on any of the UI controls present in the form. He started seeking help on the title ”The Form is not getting key press or key down if there are any controls”

As usual we started thinking in complicated ways. The reason was concluded as “The form is not getting focus that is why its not able to catch the key press”. One suggestion was to override the ProcessCmdKey and write the code there. Another one went more deeper. Override the WndProc and handle directly.

But after a tea break we could see that there is one property in the Form named KeyPreview and just need to set that to True in order to get the key events.

Moral of the story

You will never think about a completely different solution unless you take a TEA BREAK.There will be always a simple solution.

Thursday, February 17, 2011

Isolating a region from transaction

Transaction in .Net is familiar to everyone and almost all the enterprise applications are using transactions. Our application is not an exception to this.But last week we got one error in the application while reading the DB which is related to Transaction .Flow of the system is little bit complicated and there are a bunch of modules involved in between.So it was very difficult to find out what is the root cause for the issue? And on the top of that we need to deliver a build to QA.

Since it was reading the decision was to isolate that area from the transaction context.Here is the snippet for that.

'Code running in the context of main transaction
'''''
Using New TransactionScope(TransactionScopeOption.Suppress)
'Code which run independent of the transaction context
End Using
''Remaining code

Sunday, February 6, 2011

How to get the calling method name

This is continuation to my last post on finding the name of the method inside the same method. As I told in that post,my original requirement was to find out who is calling one method and handle the call appropriately.After spending some more time ,I was able to find a way.Its nothing but getting the call stack programmatically.Here is the code.

Console.WriteLine(new StackFrame(1).GetMethod().Name);
Console.WriteLine(new StackFrame(1).GetMethod().DeclaringType.FullName);



Now its possible to check the caller method and do operations based on the caller.ie block callers ,return different results etc…



Is there any sense in doing like this where anybody can create an assembly with required name and bypass this



Normally speaking there is no sense.But of course YES based on some scenarios especially in our project.We have a class present for years used to keep the context which we would like to make SingleTon now, to avoid memory leaks and improve performance. There is no chance that we can put a private constructor or rewrite the entire code due to serialization of the context and practicability.If we start rewriting the code we cannot deliver on time.So the last option is to find out the classes which really needs to instantiate the context class and give permission to them only.For other classes expose a static property which returns the current context object.



But if we think from performance aspects, its time consuming as each and every call needs a comparison.



Really speaking I am compromising performance for the practicability.

Saturday, February 5, 2011

How to get the method name inside same method programmatically

You may find it waste.Why somebody need to find out the name of the method by writing code inside the same method? But I have a scenario where I need to find out who is calling one method inside it. In other words from a method’s perspective I need to know who (method name ,class & assembly)called me and based on that I want to do some actions.Something like prevent calls from some particular classes & assemblies.

Still I didn’t get any luck in this.But during the google I found out another thing. How to know the name of the method through the code written inside the same. It was interesting to me and here are the 2 ways.

static void PrintMyName()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
Console.WriteLine(new StackFrame(0).GetMethod().Name);
}



This will display the method name to which the code belongs “PrintMyName”.

Friday, February 4, 2011

Powershell to find version of .net assemblies

Las week we upgraded our application version from 2010 to 2011.This involved a lot of changes in the configuration files along with UI changes such as logos ,images etc...One of the change was in the assembly version and correction of config files to reflect the version. Most of our code is relying on .net reflection so the config files should be updated properly to get the fully qualified name of classes.

Till then everything was fine. We got problems when the build came. The build script failed to build the dlls in the new assembly version. The product have around 400 DLLs and we are not using GAC. How to find out which dll is in wrong version?

One solution is to put the assemblies into GAC and see the version.Another is to open the DLL in reflector and check the version. Since the number of DLLs is somewhat huge ,it is better to write a program to find out the assemblies which are in wrong version.The next question came C# or VB.Net?

But keeping mind the principle of architecture finally decided to write a small windows power shell to find out the version.Code below.

Windows Power shell code to find out the .Net assembly / .dll version

#--------Script to find out .net assembly version mismatches---------
$curDir=$("C:\Binaries")
$pattern=($curDir + $("\*.dll"))
Foreach ($file in Get-Childitem $pattern)
{
$fp=($curDir+"\"+$file.name)

#Load the assembly
$asm=[Reflection.Assembly]::LoadFrom($fp)
$asmName=$asm.GetName()
$ver=$asmName.Version

#Create required version object to compare
$reqVer=new-object Version -arg "
4.0.0.0"

#if the version is not matching show a warning
if($ver -ne $reqVer) {
Write-Warning $fp
Write-Warning $ver.ToString(4)
}
}