Vesko on Performance – LINQ to SQL

четвъртък, 23 юли 2009 г.

Intro
In general some of the biggest performance problems of the applications seen nowadays are found in the database or the data access layer. This combined with ORM framework such as LINQ to SQL which is new for the development team, which encapsulates all of the queries made against the DB (and “of course” not profiled), which is not researched enough, could lead to very “sexy” results. Here I will try to show you a few common mistakes which I have seen through my everyday work with different developers from all over the world as well as the one that our students here at National Academy for Software Development make. At the end of this article you should know how to avoid such mistakes (not only the one that I’m showing here). I will provide you with the toolset along with the practices which do the work for me every day, and will hopefully do the work for you, too!

The Problems
1. GetAll() and GetCount() methods – this is a classical pair of methods. As you know they can have different variation such as GetAllBy[Something]() and respectively GetCountBy[Something](). I have found a lot of developers do the following:

But where is the performance problem? When somebody calls GetAll() the code just retrieves all the SampleObjects from the DB. This seems to be OK and it actually is. But what about the GetCount() method? It firstly fetches all of the SampleObjects in memory and then counts them. As you know the expected way of solving this task is to use the COUNT function in T-SQL. Of course the idea behind this GetCount() is simple – the developer tried to reuse the query defined in the GetAll() method. One would say – “Hm… I thought that LINQ to SQL executes everything possible in the SQL server. Why here it doesn’t do this?!?” The problem is that when you build the expression (assigned to the result variable) it returns value from IQuerable. Up to now this expression is just an expression – it doesn’t execute anything against the SQL server. However on the next line we have a call of the ToList() method which idea is to return list of SampleObjects. Thus here on this line we have a DB query which fetches the requested list.
Here we should solve two problems. The performance one is obvious – we fetch everything from the DB just to count it, which will impact the memory usage as well as the network traffic. The second problem is that we want to stick up to the Don’t Repeat Yourself principle (DRY, also known as Single Point of Truth and Single Point of Maintenance) – we don’t want to have the query for the GetAll() and the GetCount() twice. In practice it will differ only by the Count() method. Keep in mind that we could have more complex queries with filters, skips, orders, etc. so this could be very bad if we don’t obey the DRY principle here. The above snippet tried to solve this second note, but in a wrong way.
The following code snippet shows sample solution for both of the mentioned problems:

It just uses third method, which is private for the class and returns the common part of the expression as IQueriable. The two public methods just appends the query with a ToList() and Count() calls.

2. SelectMethod(…) and SelectCountMethod(…) for paging – this sample is similar to the above, but again is very common mistake.

This implementation totally breaks one of the main reasons of using paging – loading only a part of the whole content. You have enough knowledge from the point 1 both for finding the problem and for solving it.

3. The N+1 query problem – a nightmare from the past. This is a very performance intensive problem which becomes a classical in the software development folklore. The idea behind this problem is very straightforward – imagine that we have a list of SampleObjects and for each list we want to get which is his owner – SampleObjectOwner. Thus one could write one query for retrieving all of the SampleObjects (let’s say that their count is N) and for each object, we ask which is its owner. This means that we will make 1 + N queries for retrieving the needed data.
I will show you an even worst situation, in which we have to find the first object (if such exists) which have particular SampleObjectOwner as an owner.

The mistake here is similar to the above two, but here it’s the worst situation - the method GetByOwner(…) needs as much quires as the number of the sampleObjects + 1. This means that in the future, while your DB grows the performance will become worst and worst. The problem’s fix is so ironically easy – just compare…

The above code produces only a single query.

General advice
We have seen some problems, which weren’t found during the development process. The question is how to prevent ourselves from such things?
Firstly – one should definitely not use technology or framework in production without a good research. As we just have seen the problems have very straightforward and logical explanation. We should confess that not reading enough is a problem of many developers.
Second – as I mentioned in my previous post – use class like DebuggerWritter for profiling every method. Normally such problems could be found very easily just with one testing. Yes – you will need to have at least a vague idea about what kind of SQL statement should be composed by LINQ to SQL but this is a normal requirement for each software developer.
Third – stick up to the techniques shown in the solutions above. They represent a good pattern for writing DAL logic with LINQ to SQL.

Conclusion
Hopefully, now you should know more about LINQ to SQL and how to avoid some of the problems, which are commonly seen in the developers’ code. It will be very helpful to add your comments to that topic showing problems that you have had/seen in your work.

Thanks,
Vesko Kolev

Vesko on Performance – New Series of Posts

вторник, 21 юли 2009 г.

Intro
These days I have been working on a very interesting project here at National Academy for Software Development. I had to make a performance audit of a project on which two or three development teams have been working on previously.

The situation:
- The used technologies were .NET Framework 3.5, C# 3.0, ASP.NET 3.5, SQL Server 2005, LINQ and LINQ to SQL.
- 2-tier architecture.
- The coding style – very different (different dev teams from different parts of the world).
- The used practices – hard to find after so many patches.
- The performance – poor.

I’m preparing a short series of posts about the problems, which I could be found in this software as well as in many others. As you will see below not all of the problems could be fixed. However most of them could be and you can think of them as something which you should definitely avoid. I’ll provide you with some set of advices how to find/avoid such problems. They will include tools and practices which will help you to provide more robust and reliable software. I will be very happy to “hear” your comments about the written as well as your personal experience with similar problems.

Let’s start our performance journey with the first topic!



Shit of the Day: DataPager Binds Twice
While I was observing the behavior of one of the pages which seems to have problems, I found something very “interesting”. Firstly, let me give you some necessary info about this particular situation. The page had a ListView control, DataPager associated with it and ObjectDataSource against which the ListView was bound. As you know, the ObjectDataSource provides two properties – SelectMethod and SelectCountMethod which retrieve respectively the items with which the list will be bound as well as their count. Of course the data source should know also which class provides these methods, so there is also property called TypeName. You know that for the paging functionality we should be able to “ask” how many records are there as well as “give me the i-th page”. This in theory means that we should make two DB queries to “ask” these two questions.

But what happened in practice? I found that the select method and the count method were called twice. My first suspicion was that the control was bound twice. I start inspecting the code line by line searching for such thing. After a few minutes of debugging I convinced myself that the list was bound only once. The next step was to review the DAL (Data Access Layer) logic for potential problems. Again - nothing which could cause this behavior…

In such situation the only thing which could be done is googling. I searched for a while and found the following article from a Microsoft’s site – “DataPager double binds when paging using QueryStringField” which was confirmed to be a bug. I’ve quickly checked whether QueryStringField is used in my situation and voila – the problem was dissected.

The short description about this bug is: “When you use the QueryStringField with a DataPager it causes the ListView to bind twice; once as if it was on the first page, and a second time for whatever page is passed via the QueryString (even if it is also the first page). Naturally, this is very bad for performance and completely unnecessary.”

Currently Microsoft hasn’t provided any workarounds for this problem. So just try to avoid using this particular combination in your projects.

General advice
When you are developing particular page/control always check the queries which are made against your database both for loading and storing data. When using ORM frameworks such as LINQ to SQL it is very important to know exactly what queries are executed against your DB. You could use frameworks like Log4Net/Microsoft Enterprise Library Logging Application Block along with DataContext.Log property. You should definitely use (if not already) classes like this for outputting LINQ to SQL queries to the debugger output. These very simple practices will save your live from similar shit of the day.

Stay tuned and have fun!

Inline Scripts in UpdatePanel – Doesn’t Work After Partial Postback

събота, 28 март 2009 г.

Hello, guys!
Last months I have worked on a very interesting project which uses latest .NET technologies as well as some other APIs like Microsoft Virtual Earth and Google Earth. My team and I had a lot of challenging problems to solve some of which I want share with you.

The situation
Imagine that we have a user control called UserControlWithInlineScripts with the following code in it:

As you can see, the only thing which we have on the page is a button, which calls a JavaScript function SayHelo() when clicked. The interesting thing here to note is that the function is declared inline in the .ascx file (we will see later why this is so important).

Now let’s put the control in a sample page like the following:

The ButtonShowControl on the server side only sets the Visible property of our user control to true. From first sight nothing strange – we have just a control which is showed dynamically by a button. If you test this code it will work perfectly well.

But what is the actual problem? Just put a wrapping UpdatePanel…
You will have problem if you try to put the content of the page in an UpdatePanel. When you click the button to show the control – it will be shown (as we actually expect). But if you click the button which calls the inline script, the following JavaScript error appears:

As you can see the browser cannot find the function which the button’s click calls. You know that everything with the function and its call should be OK as we have just tested it without the UpdatePanel. Therefore problem obviously is in the panel, but where exactly?

Explanation of the problem
Why this happens? When you update the content inside an UpdatePanel the old content of the panel is replaced by the new content trough the innerHTML property. In general if you set the innerHTML of a DOM element with markup which contains a script block inside it, this doesn’t cause the script to be registered as script in the DOM tree. In other words the browser looks at this new content as pure markup (text). If you want to say to the browser that some string is script (in other words inject a script block into the DOM) you can do this with the method document.createElement(“script”). Another way to evaluate and execute script, which you have as string is to use the eval(string) function, which takes only one string argument – the script to be executed.

There are some interesting static methods into the ScriptManager class which gives you the ability to register startup script, script block, onsubmit statement, etc. They prevent us from this problem if we do not have our scripts as inline and register them trough this methods.

Conclusion
In general it is not a good practice to have your scripts as inline and is better to have them as an external .js files. But the problem with the inline one still exists. You can think of some workarounds of this problem and this is my challenge for you – just share your ideas!

The Book “Introduction to Programming with Java” - Ready for Publishing!

сряда, 31 декември 2008 г.

The book
I am very happy that my last post for this year is this one. I want to share with you the news that the book “Introduction to Programming with Java”, in which I have taken part as an author, is about to be published.

As you probably remember from my previous post, it covers a lot of different topics on the fundamentals of computer programming. The book does not focus on the Java language – it just uses the Java language as a tool for writing the samples. That’s why we believe it will become one of the prime sources of knowledge for beginners in computer science short after it is on the market. There I have written a chapter about one of the most widely used advanced data structures – trees and graphs.
Hopefully one will be able to buy a paper copy of the book in the first months of the New Year. Probably I haven't mentioned, but the book is free - you just buy the paper. It is 920-930 pages! For more information, you can look here. You can download a free copy of the book from here.

Instead of conclusion
This year was very interesting and dynamic. A lot of things were changed. I hope the next year will be very productive and good for all of us!

I wish you all the best, dear readers! I wish you having your dreams came true, but.. not all of them. Lets have some for the years coming, too!

Best regards,
Vesko Kolev

Vesko Kolev - what happened with this guy?

събота, 22 ноември 2008 г.

Hello, folks!
I haven’t blogged for a long time. Do you remember me? Just to be sure that you haven't forgot my face - on the right side is a picture of me ;-). A lot of things happened, a lot of future topics came in my mind trough this period. For sure you will see soon what I am talking about.

I have postponed this post for some time but think that the point at which to write it came.

What happened with me?
Firstly, I have left my previous company. I have been there for more than 2 years. I have worked on and led as a team leader a lot of different .NET projects and had the chance to work with a lot of great professionals from all over the world. My team and I have produced a lot of great functionality to our clients which was our first goal. However my decision to leave was based on some differences in thinking between me and my bosses – there were things, which I just cannot accept. The people, who know me well, will confirm that I am a very principled man. The good news is that this is an old story and is behind in the past. Now only the good memories will persist and of course the great amount of experience piled there.

Meanwhile…
Apart from that – I have joined a team, led by Svetlin Nakov, which started (and soon will finish) writing a book on a software development topic called “Introduction to Programming with Java”. It covers a lot of different topics on the fundamentals of computer programming. The book does not focus on the Java language – it just uses the Java language as a tool for writing the samples. That’s why we believe it will become one of the prime sources of knowledge for beginners in computer science short after it is on the market. There I have written a chapter about one of the most widely used advanced data structures – trees and graphs. You can find more information about the book here.

In the same period I have started to work as a part time .NET trainer at National Academy for Software Development. There have led different courses in some of the cutting edge Microsoft technologies. In my previous company training the new members of the development teams was one of my responsibilities and I liked doing it.

Where am I today?
Later I joined NASD .NET team as a full time employee. My responsibilities there include leading a team of very skilled .NET developers working on variety of different .NET projects using the latest technologies and best practices. Another major part of my job is to train people in advanced concepts of .NET programming. But still - why choosing NASD? I have refused some great offers of other good companies and chose this one, because there one can find one of the best and most popular software engineers in Bulgaria. It is a pleasure for me to work with such guys. Of course meeting new people almost every day at our courses is something which I also highly appreciate.

What you can expect?
You know me… Three months is a lot of time and in this period I have worked on and solved a lot of different problems. I will try to write more frequently sharing with you my everyday experience with the software engineering as a whole. I will be happy to hear from you from time to time about your experience with the same or similar problems which you have.

See you soon!

Algorithms: A real world example

вторник, 12 август 2008 г.

Introduction
Hi guys!
Today we are going to dive into a real world example of using algorithms + data structures. The task is not very hard, but I think it is very useful example how important is one to have an in-depth knowledge of algorithms and data structures.

What is the problem?
These days a friend of mine asked me the following question: “How can we retrieve the different files (in the terms of different names) from given two directories, including the subdirectory files?” In other words the question is how we can get the files from one directory(or in some of its subdirectories) which doesn't exist in the other and the opposite - the files which are in the second directory(or in some of its subdirectories) and does not exist in the first one.
Yes… I know that you can solve this. You can do it even in 5 minutes using whatever data structure you want which has a contains method (or equivalent). But do you think that this approach is going to be the fastest one? Or a more scientific question – is your algorithmic complexity good enough for the needs of your enterprise application?
In general there is uncountable number of algorithmic tasks out there and most of them have more than one good algorithmic solution. I am going to show you a problem with a possible solution.

The algorithm
The approach is based on one classical algorithm. This algorithm merges two given sorted sequences in a new sorted sequence, which contains the elements from both sequences in linear time. On the following picture, you will see two sorted input sequences. The algorithm to get the result sequence is the following:


1)While both sequences are not empty - get the minimum of the two top elements and put it at the end of the result sequence. Remove the element from the input.
2)Now if there are any elements left in the input, they should be in only one of the input arrays. If there are some element left – add them at the end of the new sequence and remove them from the input.

In our case we first have 0 and 1. 0 < 1 therefore we put 0 in the new sequence. The first input sequence will be 3, 3, 15, 19, 76, 89, 99. We are doing this till the moment when the second sequence (which is shorter than the first one) is over. Than we just add the element 76, 89 and 99 to the end of the result sequence.

What is the modification?
You just need to get your both sequence of files in an ascending sorting manner. If the files on the top of the two sequences are equal, then just remove them. If the files are different, then take the one which is name is “less” in the terms of lexicographical order and put it at the end of the result sequence (Note: Here you should check whether the result sequence doesn’t already ends in this filename. Think of a situation in which this is required.). If one of the sequences is not empty, we get its entire elements and put them at the end of the result sequence again taking in mind the above note.

Which are the data structures?
As we saw, we access only the top elements in the input sequences. This is the major feature of the Stack data structure. The result sequence – we add elements at its end and need to peek the last added element. So we can use for example Queue or Linked List depending on the implementation which we are using.

Conclusion
In this post I have tried to show you one problem which can be solved optimally with an elegant algorithm. I have tried not to be bounded to any programming language and not to be clear enough, because want you guys to think of the rest! This is the way in which I believe one should learn to program – with logical thinking and researching.

Hope you learned something new!

Tricks: How to get N random rows from a table in T-SQL

петък, 18 юли 2008 г.

Hi readers!

What is this blog post for?

Today I am going to present you the first post of my second series - Tricks. As I said before I will show "Technology Specific Tricks - short posts about something, which I have researched and which I want to preserve and share with you all."
The first one is about T-SQL


The problem - How to get N random rows from a table?



A little explanation - actually ORDER BY NEWID() sorts the rows in a random way. In our case we just take as much of the first as we need.


Conclusion

You just saw what you can expect from this type of posts.
Hope this helps!

 
Vesko Kolev's Blog : IDeveloper -