Tuesday, April 21, 2009

LINQ Expression tree

Lately I had to implement my own LINQ to SQL "converter" which uses a custom mapping stored in the database. It is even not as difficult as I thought. You have "only" to recursively parse the expression tree and convert it to the correcsponding SQL instructions.
The only thing I had some problems with were local variables or parameters.
Consider the following code:
int a = 3;
Get<Person>(p => p.Age == a);

the class Person
public class Person
{
public int Age { get; set; }
}

and the method
public static void Get<T>(Expression<Func<T, bool>> e)
{
MemberExpression member = (MemberExpression)((BinaryExpression)e.Body).Right;
ConstantExpression constant = (ConstantExpression)member.Expression;
Console.WriteLine(constant.Value.ToString());
}

when analyzing the expression tree then You see that the right expression of the BinaryExpression is of type ConstantExpression. Normally ConstantExpression contain directly a value. But this is not the case here! The console writeline produces the following: "ConsoleApplication1.Program+<>c__DisplayClass0"
The value of the constant expression is an anonymous object which is created on the fly. This object has a field which is named a and that field contains the value.
Therefore I had to do the following:
public static void Get<T>(Expression<Func<T, bool>> e)
{
MemberExpression member = (MemberExpression)((BinaryExpression)e.Body).Right;
ConstantExpression constant = (ConstantExpression)member.Expression;
FieldInfo info = (FieldInfo)member.Member;
Console.WriteLine(info.GetValue(constant.Value).ToString());
}

Instead of evaluating the expression which is associated to the MemberExpression.Expression I used the Member and casted it to a FieldInfo. Then I called the GetValue method passing it the value of the ConstantExpression which is basically the object. In this way I finally got the correct value of a.
The same works also for method parameters. Consider this code:
public static void FromMethod(int a)
{
Get<Person>(p => p.Age == a);
}

there we have exactly the same problem and it can be resolved in the way described above.

Wednesday, March 25, 2009

Bulk insert of data

Recently I faced the problem of inserting a big amount of data into the database. The point is that multiple tables are affected which are connected with foreign keys. After some research I found OpenXML as one possibility. You create a stored procedure where you read your XML string into an "XmlDocument" which you can then query by using XPath and inserting, updating or deleting the tables occordingly.
The other possibility I found is SQLXML which is now available in version 4.1. It is delivered with SQL Server but not with the Express version. If you need it you can download it from here. SQLXML allows you to bulk insert data from an XML file by using a so called annotated XSD schema where the mapping is defined. It is not very difficult to define the schema, only recursion and special cases are a little bit difficult to handle. I was not able to make recursion work with identity values coming from the database. Anyway; I did some performance tests where I had a structure like:
Table A
Table B has a foreign key to Table A
Table C has a foreign key to Table B
which corresponds to the following XML structure:
<root>
<a>
<b>
<c></c>
</b>
</a>
</root>

I created an XML file that contained 100 A's; every A contained 100 B's and every B contained 100 C's. This gives a total of 100 A's, 10.000 B's and 1.000.000 C's. To insert all them and updating the foreign keys it took 84 seconds. This is quite fast for such an amount of data. I think that this is the fastest way to bulk insert data into SQL Server (if I'm wrong You are welcome to coment on this).
If you want to use it with .Net add a reference to "Microsoft SQL Server Bulk Upload" or something like that.
I don't remember the exact name but as soon as I find the link of the code sample I will post it here.

The problem is that SQLXML cannot be used for updates. There exist so called updategrams or diffgrams but I didn't try them.

Very Simple Notes Application

My girlfriend asked me look for a small program wher she can add notes and delete them if necessary. I serached the internet and there are a lot of programs out there to do this, but they are all very complex and offer a huge amount of feautres that she does not need. Since I'm a programmer I decided to write one :-)

As the title says it is a really simple program. Here a screenshot of it:

and this is how it looks with some notes:

Obviously by clicking the trash the note is deleted. All the notes are saved in a simple XML file in the isolated storage of the user. This means that you can run the application from a readonly storage (like a CD) and it saves all Your notes in your user profiles folder.

If someone is interested in this very simple tool You can get it from here.

Thursday, January 29, 2009

No standard mail client

Today I encountered a nasty problem. I clicked on an e-mail address on a web page and instead of opening Thunderbird with a new mail message I got the following error "Der Vorgang kann nicht ausgeführt werden weil der Standard-Mailclient nicht richtig installiert ist.". This means something like "The operation can not be performed because the standard mail client was not correctly installed.".
I told Thunderbird to ckeck if it is the standard mail client under Extras -> Settings -> General -> Standard mail client (I don't know if that is correct because I have a german version); it told me that it is the standard mail client.

Finally to make it work I had to go in the Internet Explorer (7) to Extras -> Internet options -> Programs and there I selected Thunderbird as standard mail client.

Strange thing; but sometimes things stop to work without any obvious reasons :-)

Wednesday, January 21, 2009

Microsoft Certification

Today I passed the microsoft exam 70536 Microsoft .NET Framework - Application Development Foundation. I found it very interesting to prepare myself for this exam because despite that I program every day at work there were a lot of things that I simply didn't know that they exist. Other things I never understood completely and this exam helped me to find out how and why it works in this way. The exam itself was not very easy because the questions are very detailed and sometimes you simply have to have used some classes in order to know if a parameter is passed through the constructor or set with a property. The most difficult are the questions wher you have a list of steps and you have to bring them in the correct order; but not all steps may be needed. I find these kind of questions especially difficult because sometimes there is not only one way to accomplish the specified target. Anyway I am happy that I passed the exam and that now I can prepare myself for the next exam... a never ending story :-)

[Update]
Now I got access to the MCP website from where I also got the logo which I proudly put on the right menu bar :-)

Wednesday, January 7, 2009

Updating App.config

Today I faced the problem to update the App.config. There exist several solutions out there but I was not able to find a simple one. Therefore I decided to try out the new Linq to XML feature of .NET 3.5 and wrote the following method which updates the value of a specific key in the App.config file:

public static void UpdateAppConfig(string key, object value)
{
if (key == null)
throw new ArgumentNullException("key");

if (value == null)
throw new ArgumentNullException("value");

XDocument doc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
var result = (from appSetting in doc.Descendants("appSettings").Descendants("add")
where appSetting.Attribute("key").Value.Equals(key)
select appSetting).FirstOrDefault();

if (result != null)
{
result.Attribute("value").SetValue(value);
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
doc = null;
}
else
{
Console.WriteLine("The application setting with key '{0}' was not found!", key);
}
}

Blog statistics 2008

As I saw it is common to post some statistics about his blog. So also I will follow this "trend" :-)

First of all here the graph of accesse per day. Ultimately there is an average of 25 visits per day. The most visits were on July 1. There were 57 visits :-)



As you can see here most people get directed by a search engine to my page.



The most visitors access from London my page, but there are visitors all over the world.





I wish everybody a happy and good new year 2009 and I would be happy if you continue to visit my blog ;-)