Zeeshan Hirani

Senior .net Developer

April 2008 - Posts

Type Inference in Generics

If you are using generic method, you can call the method without explicitly specifying the type arguments. Their are certain cases where the compiler cannot infer the type based on the values passed in the parameters, in those cases you can explicitly specify the type argument. Depending on the scenario,it might be concise syntax but may not be readable to another developer. Here is an example of using generic method with and without explicitly specifying the type.

image

 

In the above example I have a generic method which is constrained to have a parameter of type T that needs to implement IComparable<T>. By enforcing this constraint, I can make sure that the argument passed in can be checked against compareTo method to compare two parameters. As far as using the method, in the first case I pass in integers. The first example shows that I am not specifying the type of parameters passed in. In fact compiler is using type inference to determine the exact type of variables being passed. Further down I pass in strings where in the first case I don't specify the type and let compiler determine the type and than I also illustrate the usage in which I am explicitly specifying the type. Some readers may find specifying the type to be more readable because it shows the intent of the programmer even though the compiler can infer the type. The scenario where type inference will fail for generic method, would be where certain parameters can be inferred where as other cant. In those cases type inference would completely fail. It has to be all or none.

Linq to SQL Debug Visualizer

I have been learning Linq for sometime. However I always had some difficulty figuring out what SQL statement got generated for my Linq query. Although there are numerous ways to find the SQL statement that get generated but none of them were with out code or having to leave visual studio environment. Last week I discovered a really good tool called Linq to SQL Visualizer which allows me look at my Linq query in a Visualizer that exactly shows the SQL statement generated. It also allows you to execute your query from there as well.

You can download Linq to SQL Visualizer over here

http://www.scottgu.com/blogposts/linqquery/SqlServerQueryVisualizer.zip

Unfortunately Linq to SQL is not part of visual studio 2008. The Visualizer has to be downloaded separately.

Once you have downloaded and extracted the sqlQueryVisualizer, you have to copy SqlServerQueryVisualizer.dll from bin/debug directory onto

C:\Program Files\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers

Before copying the dll, make sure that you have all instances of visual studio shutdown.

After copying the dll, when you hover over  Linq to SQL query, you will get a magnifying glass and clicking on it will open the SQL Visualizer. Here is how the screen shot looks like.

 SQL Server Query Visualizer

 

You also have the option of executing the query from there and also seeing the results.

How To Find Which Control Raised PostBack

There are times in asp.net when I really want to know which control in the page raised caused the page to post back. An easy way to find this is to register an event with the control that raises PostBack and cast the sender property to the appropriate control as shown below.

image

image

As shown in the above code I am casting the sender property to the appropriate control to find out which control raised the PostBack.  Although finding which control raised the event from the click event handler is nice, but sometimes that is too late in the page life cycle. In a scenario where you have to create controls dynamically, you cannot create controls no later than page load event . In this case, it becomes mandatory for you to know which control raised the PostBack and depending on the situation you may decide to perform certain action. The code shown below shows you how to find which control raised PostBack in page load or earlier events.

image

The code above is basically broken apart into two conditions. If the PostBack is done from any control that is not rendered as submit button for instance linkbutton, or checkbox control, than asp.net will populate __eventtarget property in the request collection to the id of the control that raised the PostBack. However if the PostBack happened because of a submit button, than one of ids in the form collection would represent the id of the button that raised the PostBack.

In the small example above, I illustrated how to get the control that raised the PostBack early in the page life cycle. This will be beneficial mostly when you want to create controls dynamically based on what control caused the PostBack.

Delay Loaded Property

I recently discovered while playing with the linq OR designer that each property on a class has a property called DelayLoaded. It allows you to delay the loading of that column from the database until the user accesses that property on the object. Only when you access that property is when linq to SQL server makes a fetch to the database to get that column value. It comes handy in scenarios where you storing XML data type or pictures in a database column which you don't really need until user request for the data. Here is how the screen shot looks like.

image

 

By default the Delay Loaded is set to false which means as soon as this object is retrieved from the database, all the columns will be fetched for that record in the table. When you set the Delay Loaded to True, linq to SQL provider only fetches columns which are marked as Delay Loaded = False.

Creating Private Auto-Implemented Property

I have been using auto implemented property for a while but did not know that you can control the acessor for getter and setter. Basically I can use public at the property level and set private or protected at either getter or setter. I cant set acessor at all 3 levels meaning I cant have public defined at the property level, than set protected at the getter level and set private at the setter level. The acessor defined at the property level must be inherited by at least either getter or setter and the one left over can be separately defined as follows.

image

The acessor defined at the getter or setter must be more restrictive than the acessor defined at the property level.

Comparing Anonymous Types

C# 3.0 allows you to create anonymous types which is basically a handy way to use a class without defining a class. It is really a nice feature when you are building linq queries which does not return fixed number of columns depending on the query you write. When you write an anonymous class, compiler in the background creates a auto generated class with those properties. If you define two anonymous types with the same property name and data type and in the same order, compiler will only create 1 anonymous type in the background and it will reuse that auto generated class in both those anonymous declarations.However if the definition of the anonymous type changes compiler will generate a new class. Because of the reuse of class, you have the ability to compare to generic classes having the same structure. Not only can you compare two anonymous classes but can also do assignment when two anonymous classes have the same structure. Let's have a look at an example that illustrates this behavior.

image

CWindowssystem32cmd.exe (2)

In the above example, I start with two anonymous classes with same property names and types and declared in the same order. The next anonymous type is slight different where I change the order of properties declared. This results in compiler generating a new anonymous type in the background. Since sametype1 and sametype2 are same anonymous types, I can compare those two types without compilation error. The reference type compare results in a value of False being outputted to the screen since those types do not have the same reference. However when I try to compare sametype1 and notsame variable, it results in a compilation error since those types are structurally different. In the next portion, you will notice that I was able to assign sametype1 to sametype2 because they were defined as same anonymous types, however when I try to assign sametype1 to notsame, compilation error occurs.

Using Default Values in Generic Method

There are times when you want to assign default values to your variables. For instance if you have a reference type variable the default value will be null. If it is a value type you could assign 0. But how do you check in a generic method if the value the user has passed in is a default value or not. The reason being every type has its own default value, you cant check against null because the user may have passed in value type which cannot be checked against null value. What if the user has passed in datetime data type, in that case the default value would DateTime.Min.

To address this problem C# 2.0 introduced a new operator called default which allows you to get a default value for a variable whose data type is unknown at design time. Let's look at a generic method in which I check to see if the value user has passed in is a default value or not.

image

 CWindowssystem32cmd.exe

In the above example, I am placing a constraint on the generic type that it must implement IComparable<T>. The reason for forcing this constraint is to actually call the compareTo method on IComparable interface to check if two values are greater than, equal to or same. Since we don't know at design time what type we are going to pass, we rely on default operator to get us the right default value based on the type passed in at runtime.

In the first case I pass in 1, an integer which evaluates to 1 because 1 is greater than the default value of 0. In the second case I pass in 0 which is equal to default value of 0 for integer types. In the string value of test, the result evaluates to 1 because the default value for reference type is null and anything that is passed in that is not null is always greater than null. In the last 2 cases I get 1 and 0 because the default value for datetime operator is DateTime.Min so when you pass in DateTime.Min, the value returned is 0.

Notice in order to compare two values, I did not make use of == or != operator and that is because they can only be used with reference type variables. When there is no constraint on the generic type that it must be a reference type, use of == operator will return incorrect results for value type variables.

How To Use Profiler with Linq To SQL Queries

SQL Profiler is one of the very good tools from SQL server products tools that can help you evaluate the kind of SQL statements Linq to SQL is sending to the database. Although datacontext provides you with a log property that allows you to output the SQL statement that gets send to the database, SQL Profiler is other option that helps you understand and see the SQL statements that gets executed.

In the past the problem that I faced when profiling Linq to SQL queries is there were too many things getting logged which defeats the purpose when all you care to look is at the SQL statement. So basically the key idea is to use the right filter so that you can cleanly see the queries that you are looking for. Here is the screen shot that shows you the appropriate filter that you can set to only see the dynamic SQL statements that gets sent to the database.

When you create a new trace in profiler, go to the Event Selection tab and uncheck all the events as shown below.

image

Then select show all events and find the event which says SQL:StmtCompleted and check the column of TextData to be display for that category. The final figure would look something like this.

image

image

The above screen shot shows a sample SQL captured from Linq to SQL execution.

How To do In and Like clause in Linq To SQL

In clause is one of the common querying feature we use in SQL. But there is no clear explanation of how to write a Linq query which allows you to filter the results based on certain items in a list. Well after digging in through some of the query operators I found that there are various operators that you can use to tell a Linq query to filter the items based on items in a list. Let's have a look at few of those examples.

I will start with using the contain operator and show you how Linq to SQL provider converts that into in clause in SQL server.

image

CWindowssystem32cmd.exe

In the above code I am displaying all the customers in the city of London or Paris. Notice I am using the contains method on the cities array to find the right match. The contains clause gets converted into in clause as shown in the output.

Another possibility of in clause can be a like operator with bunch of or statements. For e.g where city like London or city like Paris. Although it's truly not an in statement but with bunch of or statements you can make it work like an in statement. Here is an example of doing that.

image

 

The results are identical except that I am using or and contains statement which Linq to SQL provider converts it into or and like statement as shown in the output window.

CWindowssystem32cmd.exe (2)

Another way in SQL where you can say show me all the customers who has at least one order that has a ship city of Bern is by making use of an exists clause. It is basically an in clause that evaluates to a sub query which selects only those customers who have orders with a ship city of Bern. Let's see how to write that in a Linq query.

image

 CWindowssystem32cmd.exe (3)

 

 

In the above example I am using where clause with a lambda expression that evaluates to true if there are any orders for a customer that has a ship city of Bern. As you can see in the output window, it gets evaluated to an exists clause in SQL server.

You can also use StartsWith and EndsWith operator to force Linq to SQL to use like operator in comparing a value in a query. Here is an example of that.

image

CWindowssystem32cmd.exe (4)

Notice that Linq to SQL provider converted the StartsWith operator with like clause and value is appended with % at the start. Same thing happens with EndsWith except the value is appended with % at the end.

 

If build in operator does not give you the flexibility of comparing the values, you have the options of using SqlMethods which gives you more control in how you like value should look like. In the query below, I have made use of % before and after the value.

image

 CWindowssystem32cmd.exe (5)

vacation time!!

Ok guys, I am going on vacation for a week. Not sure if i would get time or enough strength to come back at night and write something from my hotel room. Yeah i am taking my laptop on vacation, i just can't stay away from computer for too long. I haven't gotten tired of blogging as yet. Hopefully i will force myself to do it enough that it becomes a habit that i get addicted to!!

Enjoy the tutorials!

Posted: Apr 18 2008, 12:07 AM by zhirani |
Filed under:
More Posts Next page »