Archives

Archives / 2008
  • Contributions to Entity framework community

    If you had been reading my blog, you must be wondering where did he go after publishing such awesome blog entries(jk). I had gotten lot of good feed back on the examples I had done on linq to SQL but like all good things must come to an end so did linq to SQL for me. My company was committed in moving forward with EF so I decided to move forward with Entity framework as well. During the process I learned so much stuff and felt the pain most developers went through with this technology. No doubt EF has a learning curve like any other technology but mapping scenarios offered by EF are simply great.

  • Linq To SQL Optimizes Eager Loading

    If you have read my previous blog posting about the Load operator in entity framework and how it works in terms of lazy loading object regardless if it object has been tracked earlier, you must be keen to know how does this behavior work with Linq to SQL. I must say Linq to SQL has always surprised me in terms of how efficient it is in terms of dealing with retrieving data from the database. When you lazy load a particular entity reference, Linq to SQL will first track its tracking repository to see if it can find the object there. If an object is found it by passes database and simply returns the object from its cache. This is an optimized behavior as compared to how entity framework tackles this problem. For example if I have much of orders and I want to lazy load its customer, Linq to SQL will not make a database call for every Order to get its customer. If those orders belong to a total 5 distinct customers, than only 5 database calls will be made. Below is an example that shows this behavior.

  • Avoiding Roundtrip with Load in Entity Framework

    If you have queries in your classes that you are reusing across your entire business layer, it becomes really hard sometimes to do eager loading of certain child entities on those queries. For example, if you have method that runs a complex linq to entity query to return you a collection of Orders. What if in certain scenarios of your application, you would like to retrieve Customers for those orders as well. Either you can create another method just like your previous method which has that complex query duplicated but along with that query you support the concept of eager loading of Customer entities as well.  Other option you have is if the orders returned from the method are not too many and in manageable size, than you may end up wanting to reuse the method and incur the cost of lazy loading of the Customers. Below is an example that shows how I would lazy load Customers for an Order.

  • Comparing Dates in Linq To SQL

    If you want to compare dates in Linq to SQL query, you are free to use normal operators available in C# and Linq to SQL provider will translate the date comparison into appropriate SQL which makes uses of date functions available on SQL server. To demonstrate the usage of Date functions let's look at an example.

  • Many To Many Mappings in Entity Framework

    So far in my previous blog postings, I have discovered goodness with linq to SQL as I travel the path of migrating from linq to SQL to entity framework. This is not to deny that entity framework also has plus points which cannot be ignored. Among them is support for many to many relationship. Many to Many relationship is a concept that is very common in most OR mappers so one would wonder why it did not make it into the service pack release for sp1 for linq to SQL. I am sure Danny Simmons will have a better answer to this question than me.

  • Entity Framework Does not support object comparison in Queries

    As I continue to migrate my linq to SQL code over to entity framework, I am discovering more constraints that I never faced working with linq to SQL. For instance in one of my linq query, I was able to do object comparison to apply filter to queries. For example, If you wanted to retrieve customers who are in the city of London and also customer that you currently hold in your hand and find out the count of customers that meet this criteria or probably find out how much total sales those customers have given us, you probably want to perform this query on the database. In the past I could apply object comparison in my query rather than applying comparisons  based on column values. You could actually use column values to dictate your filters, but sometimes being explicit on how you are applying a filter puts noise in your code as compared to just saying make sure this customer is also part of the filter.

  • Different Implementation of Cast in Linq To SQL And Entity Framework

    To set the stage of what I am going to blog about, I would recommend that you read by earlier blog posting here where I have talked about how the cast operator works. In short when you use cast operator with Linq to SQL to fetch a particular concrete type, you end up making a call to the database that fetches all records and than cast is performed in memory to cast the objects to the type passed in as a generic type. If the object cannot be cast to the correct type, the object is assigned a null value. The implementation is very similar to as operator in C# where if the object cannot be cast to right type, the reference of the object is set to null. Important point to understand is, even though your Linq query may not give the results you desire, but the query wont crash. However if you were to write the same query in Linq to entities or entity framework, you get a runtime exception stating that a cast is not valid. Below is an example that shows the behavior?

  • Entity Framework does not support Custom Properties in Queries

    As I am starting to learn more and more, I think linq to sql first release is much more mature that v1 release of entity framework. For instance, in linq to sql, if I would create custom property in my partial class, I could actually use that custom property in the projection of my query. One of the obvious reasons for creating custom property is to reuse code functionality such as creating a property called Name which combines, FirstName and LastName. You really don't to write that code all over you class diagram. Exposing the function as a property and being able to use that property in a projection is a valuable functionality added to the framework. Below is the code that shows using custom property in a projection of a query.

  • Changing Namespaces in Entity Framework

    If you are like me, migrating to entity framework from linq to SQL, I must say you have been spoiled. What seemed to be very simple has gotten much more complex. I find that Entity framework solved my persistence ignorance problem but brought me much more complicated problems to deal with. Here is one that took ages to find out

  • MultipleActiveResultSets in EntityFramework

    MultipleActiveResultSets was a feature introduced in the connectionstring with ado.net 2.0. In prior versions of ado.net, you can only execute a single query at a time on a particular open connection. When you set MultipleActiveResultSets to true, you can execute multiple commands on a single open connection, resulting in better performance. It's interesting that when you generate your linq to SQL classes, by default it does not make use of MultipleActiveResultSets in the connectionstring. However when you generate entities using entity framework, the connectionstring added to web.config or app.config has explicit setting for MultipleActiveResultSets = true to enable the feature. If you set MultipleActiveResultSets to false in the connectionstring most of the queries in the entity framework fail. It appears that you have to set MultipleActiveResultSets  to true in the connectionstring if you want to use EntityFramework.

  • Lazy Loading Entities in EntityFramework

    In my previous blog posting we learned how to eagerly load entities in entity framework. Eager loading causes lots of entities to be loaded ahead of time which may not be required and feasible in all scenarios. In those cases you can call Load Method on an entity or collection of entities to lazy load entities on demand. This ensures that you do not bring lots of data from database and only loading entities when you need them. The problem with this approach is, your querying process would be very chatty and you would end up making too many database calls. For example if you have collection of customers and you want to lazy load customer's address, than depending on the number of customers you have in your collection, linq to entities will make that many number of calls to get addresses for all customers in the list.

  • Eager Loading entities in Entity Framework

    As I am starting to move forward with entity framework on all my projects, I am discovering new ways of writing queries that works with entity framework as compared to in the past with Linq To SQL.

  • Migrating from Linq To SQL to Linq To Entities

    I am not sure if it is a sound idea to move all the stuff over to Linq to entities from Linq to SQL. However this current portion of the project that I had started few days ago felt like a really good place to test with Linq to entities. So quickly migrated over my code from Linq to SQL to Linq to entities. Surprisingly except for changing few namespaces and datacontext rest of my Linq queries just complied fine against Linq to entities. After compiling the code, I went ahead and tried to run the application and I met my first exception.

  • Constraints With LoadWith when Loading multiple 1:n relationships

    This problem totally came as a surprise when one of our pages in production was taking too long time to load. Obviously to trouble shoot the problem, I opened up SQL profiler, started looking at the various SQL statements being sent to the database. I was surprised to see that LoadWith operator was not working as advertised when eager loading more than one, one to many relationship. To demonstrate the problem, let's start with a bare bone example where I eager load Orders for the customers in the city of London.

  • Peculiarity With Cast Operator in Linq To SQL

    As I have mentioned in my previous blog postings, Linq provides a great querying model which hides the complexities of different domains such as Linq to objects, Linq to SQL and Linq to XML. However it is important to understand how a particular query behaves and runs on a particular domain.

  • Using Embedded Expressions in XML to Replace String.Format And StringBuilder

    If you have been using StringBuilder or String.Format to build strings, they provide nice syntax to replace placeholders such as {0}, {1} etc with the values passed in the second parameter to the method. Although I have been using this syntax to print and create customized displays, I still feel that there are sometimes harder to read because of the noise the method and placeholders add to the code. With the awareness of XML into the vb language, you can leverage embedded expression to build customized strings from XML by calling the Value property on the XML literal. Below is an example that demonstrates this usage.

  • Creating XDocument using Data from Database

    With Vb, building an XML Document on the fly from a list in the database is very simple. Vb supports the concept of embedded expressions which is similar to asp.net concept of embedding code expressions in aspx page. This allows you to build you XML file as it should look when its opened. XML literals also allows you to replace sections of the file with data from anything that is IEnumerable. Example below builds an XML document from a list in the database.

  • How To Make XElement An XDocument

    This is a cool trick that I discovered in Vb when working with XML. Vb has full support for XML in the language so much so that you can type in XML write in the code and IDE would do color highlighting to differentiate it from the code in the page. It would also do correct indenting of the code so XML is more readable. By default when you type in XML in Vb.net code, it is inferred as XElement. Below example shows this behavior.

  • Assign DataLoadOptions just before executing the linq query

    If you have been making use of DataLoadOptions to eagerly load 1 to 1 entity or 1 to many entities such as child collections; you have to make sure that you apply all these operations before assigning the DataLoadOptions to the DataContext. For example, when you use LoadWith method to Load Oders for a customer, you need to ensure that you call LoadWith method before you assign DataLoadOptions variable to DataContext. Any changes you make to the DataLoadOptions after it has been assigned will result in runtime exception by the compiler. Example below shows the exception raised by the compiler in an correct usage of the datacontext.

  • Linq To SQL Provider Rewriting My Queries!

    From the title of the blog posting, readers must be thinking, I have already given away control of writing SQL to Linq providers. Now do I get to loose control over writing my Linq queries?  Well in reality not. What I meant is Linq provider analyzes the queries and if it finds repetitive filters or duplicate checks or even for that matter finds that a query can be written efficiently based on the data available at runtime which was not be available during compile time, Linq providers will fix the query and translate the fixed version of the query to SQL to be sent to the database.  Below is an example that demonstrates Linq provider's ability to modify Linq queries for better performance and less redundancy.

  • Linq To SQL Query plans not being reused

    When you use Linq to SQL to apply filter, orderby or any other operator, Linq provider translates the query to SQL and sends it to the database. When the query is send to the database, SQL server determines if it can use an existing query plan for this query or create a new query plan. One of interesting point I discovered is, Linq to SQL query plans do not get reused. For instance if I write a Linq query to find customers with Contact Title of Sales Agent, SQL server would generate an query plan which you can see in syscacheobjects table. When I run the query again with a different Contact Title say, Accounting Manager, SQL server, instead of reusing the same query plan generates a new query plan. The problem with this is, dynamic queries have limited caching buffer and once it reaches it max size allocated for the dynamic query buffer, it would start to flush out the old query plans. Since this process would be happening so fast, that it would hard to reuse the same query plan again resulting in a new query plan being created every time. Secondly if you look at syscacheobjects table, there is another column called usecounts which tells how many times this query plan has been used. Most of the time with Linq to SQL query the usecounts never goes past one. Below is an example that shows different queries being send to the database using Linq to SQL.

  • Binding IQueryable Derived class to ListView Raises Exception

    Linq to SQL supports single table inheritance. So if you have an employee table, you can store both Salaried and Hourly Employee in a single table. To identify which employee is what, you can use discriminator column. To map a table that contains multiple derived classes in Linq to SQL, you have to do 3 things. For each derived class, you have to specify what discriminator column to use. Secondly you have specify what value in the discriminator column identifies a particular derived class. Third you have to specify what should be the default derived class in the case where database does not define a value for the discriminator column. In the example below I have an employee class which has two derived classes, SalariedEmployee and HourlyEmployee.

  • IExecuteResult to return data from stored procedures

    When a call is made to a stored procedure or a function that returns a scalar value,  linq to SQL designer generated code calls ExecuteMethodCall which returns an object that implements of  IExecuteResult. IExecuteResult interface has one method and one property. Below is the definition for IExecuteResult interface.

  • Using Stored Procedures In Linq

    Using Linq to SQL, you can use stored procedure to return your entities. If you want to use the designer, you can go to the server explorer and drag a stored procedure on an existing entity. This would cause the Linq to SQL designer to generate code for calling a stored procedure that returns your entities. If the stored procedure does not return any particular entity, dragging the stored procedure on the designer would generate a class on the fly which would contain properties that match the columns your stored procedure is returning. If you are using SqlMetal utility to generate your entities, than add /sprocs option to indicate that you want code generated to call stored procs in your database. To better understand what code designer generates, let's take a look at the code generated when calling a simple stored procedure.

  • Using External Mapping File With Linq To SQL DataContext

    By default when you use visual studio to drag tables onto Linq to SQL designer, you get table per entities generated in a single file. Those entities have attributes defined on them that defines how an entity is mapped to a table in the database. Although each of the generated entities are marked as partial, you never have to look at them because if you want to write code in those classes, you have the option to create your own partial class and put your logic in there. This makes your partial classes clean and devoid of any generated attributes which clutters up the code, making it hard to read. However using sqlmetal command line utility you have the option to move those attributes to an external mapping file and read the external mapping file at runtime as one of the parameters to the DataContext's constructor.  Below are some of the examples of different usages of sqlmetal that provides various flexibility in code generation and gives control in how the code is generated.

  • Is Your Linq Query being executed on the database?

    Depending on the approach you take when writing linq query, you may be surprised that some of the operations are getting performed in memory instead of the call being translated to sql and executed on the database. When you apply aggregate operators on association relationship on an entity in the context of a query syntax, the aggregations is performed on the database. However the same syntax when executed outside of the query syntax would force the entire association relationship to be brought from the database and aggregate operation performed in memory. In figure 30, I have two different version of the same query that returns the customerId, Total number of orders they have placed and TotalAmount they have spent on orders so far. In the first query, I am using association relationship Orders available on customer to get the total orders placed. To get the total amount spent, I first used the association relationship Orders on the customer and for each order, I navigate to its order Details association to calculate the cost of each Order. Since I am using association relationship inside of a linq query, the entire query is converted to sql and send to the database for execution. Second query in Figure 30, uses the same association relationship on the customer entity to perform calculations. Since the calculations are not part of an existing query, linq to sql has to bring all the orders for the customer and for each order bring down all its OrderDetails to calculate the Sum and Count operation. Bringing all the Orders and OrderDetails for a customer is an expensive operation which need not to be performed if all you are want ing to do is get the count and sum. Those operations can easily be done on the database. As a developer, it is important to understand the tradeoffs and know which option may be better suited for your scenario. For instance if you already have the order and OrderDetails for a customer in memory, than it may be more efficient to perform these operations in memrory instead of making a database call to the server.

  • Using AsQueryable With Linq To Objects And Linq To SQL

    AsQueryable is a method that allow the query to be converted to an instance of IQueryable. When you use AsQueryable operator on an existing query and apply further transformations such as applying a filter or specifying a sort order, those lambda statements are converted to Expression trees. Depending on the provider you are using,  expression trees will be converted into the domain specific syntax and than executed. In the case of Linq to SQL provider, the expression tree would be converted to SQL and executed on SQL server. However if you use AsQueryable operator on a query that does not implement IQueryable<T> and only implements IEnumerable<T>, than any transformations that you apply on the query would automatically fall back on IEnumerable<T> specification. What this means is by tagging a query with AsQueryable you get benefits of both Linq to SQL and Linq to object implementation. If your existing query happens to implement IQueryable, the query is converted to SQL by the Linq to SQL provider, otherwise the query is executed in memory in the form IL code.

  • Handling Errors in Asp.net Ajax using ScriptManager

    Asp.net Ajax offers variety of ways to handle error that occur when the page is posted back asynchronously. Every time an error occurs in an asynchronous page request, script manager will raise an onasyncpostbackerror event. If you need to customize the error that get sent to the user, you can register with the event and set the a friendly error message on AsyncPostBackErrorMessage property available on ScriptManager. Code below shows an example where I am setting a friendly error message on the AsyncPostBackErrorMessage instead of displaying the exact error thrown on the server side code.

  • TODO comments in Vs 2008 service pack 1

    I have been using TODO comments in visual studio since vs 2003. It helps me keep track of all the items that I eventually want to get to but don't have the time to do it on time to meet my release date.  You can access the todo list from the view menu and clicking Task List. One of problems I had in the past with todo list was, it only showed todo tasks for files that are opened in visual studio. In a big project, it is not feasible to open all the files to see all the the todo tasks for the entire solution. In vs 2008 service pack 1, C# IDE team finally got around to fixing this issue. Now you get todo list for all the todo tasks in your solution regardless if the file is open or not.

  • Navigating Quickly in Vs 2008 Service Pack 1

    In the past, to navigate around bunch of files opened in vs 2008, I tend to use Cntrl + Tab to reach a particular file. It certainly is a good option but when you have large number of files opened in the project, you end up spending enormous amount of time just tabbing through the list of files until you get to the one that you want to open. Recently I discovered that when you use Cntrl + Alt + down array key, a small navigation window pops up at the top. The windows allows you to navigate to all the files opened. The best part about this window that I really like is, you can actually start type in the name of the opened file that you want to reach to and visual studio will automatically highlight the file that matches the name you are typing. Below is a screen that demos the feature.

  • Creating Hello World With Silverlight

    I finally have to embrace Silverlight as my team decided to use silver in building part of our community site. I had been trying to avoid Silverlight since 1.0 version, feeling that my Ajax skills and asp.net concepts would be all I need to do my daily activities. But with the upcoming release of Silverlight which supports .net runtime, world is changing over. We no longer have to program in JavaScript and can be comfortable writing code in our domain specific language such as C# or Vb.net. Today, I decided to begin my journey to learn Silverlight. The best way to learn any technology is to create a hello world application. Below is a step by step tutorial to create a hello world application.

  • Combining Expression Trees

    Today, I was working with expression trees and had the need to combine two expression trees. It appears that when you try to combine two expression trees, it doesn't work. Compiler raises an an exception and does not allow combining two expression trees. Instead you need to convert expression tree into delegate by compiling the expression tree and using the compiled delegate with the existing expression tree to get the new expression tree. Here is an example that C# compiler does not allow.

  • Modifying Expression Trees

    As I have started to play more with expression trees, I decided to learn how to modify expression trees. Well expression trees cannot be modified because they are read only. In order accomplish modification, you have to create a brand new tree, copy the existing expressions that are still valid, replacing the expression that you want changed.  Below is an example that demonstrates changing a constant value from 1 to 3.

  • Sorting Child Collections In Entity Framework

    I made a blog post earlier, where I discussed how to use AssociateWith method on DataLoadOptions to sort child collections on SQL server before they are loaded into memory. This option is only available in linq to SQL. In entity framework, in order to accomplish sorting on child collection, you have to use CreateSourceQuery method. CreateSourceQuery returns an objectquery that gets converted to SQL and send to the database. So if you want your child collections to be loaded differently such as sorted in a different order or apply filter, than you have to get access to ObjectQuery instance that is responsible for loading the child subcollection and modify the query to add ordering before ObjectQuery gets executed.  CreateSourceQuery query method is available on EntityCollection and EntityReference.

  • Ordering Lazy Loaded Child Collections on the database

    I have been working with OR mappers for more than 3 years and had the luxury to work with many different ones such as Wilson, NHibernate, Sonic and Linq. One of the constraints that I have encountered in most ormappers is, there is no clean way to define how to sort child collections based on certain column. For example if I have a customer instance in my hand and I want to get access to its Orders, I can simply navigate to Orders property of the customer. What if I want those orders to be sorted by ShipCity. Well in Linq queries you can apply OrderBy operator on Orders collection for the customer. But does that order by operation gets executed on SQL server. The answer is no. As soon as we access the Orders property of the customer, Linq to SQL fetches all the orders for the customer in memory. From there on any operations you perform will get executed in memory. Below is an example that confirms the behavior.

  • Returning Random Products Using Linq To SQL

    Today at work, I was given a requirement to randomize our featured products on the home page. Basically every time you reload the page, you get different set of products. The maximum number of random products you could display on home page must not be more than 20. I could have done the implementation in C# by bringing more products than I need and randomly picking up 20 from the list. Once I implemented the solution, my results were truly not randomized. I ended up with same records quite often because the randomizer function did not have enough products to randomize and plus I was bringing more data than I needed.  Meaning to randomly pick 20 products, I had to bring 100 products and apply random function on there. After having done that I realized that if I were to do the randomizing on SQL server I truly would get a random behavior. SQL server has a function called NewID that always give you a random generated number. So if I can order my collection by the random generated Id, my top 20 collection of products would always give me random 20 products from products table. Here is the view and a function that returns a random Id.

  • Building Expression Trees from Scratch

    Just out of curiosity i decided to create expression trees from scratch instead of using lambda statements to get my expressions trees. In all my projects, I haven't really found any significant need to create expression trees from scratch. Most of the time lambda statements are sufficient for me to create any complex expressions. However to understand lambda expressions better, it think it is essential to comprehend, how compiler converts lambda statements to expression syntax. In the example below, I am going to create a very simple expression tree that takes two parameters, multiples both parameters and adds two it.

  • Different ways of removing elements from XML

    Linq to XML provides numerous ways of modifying XML which includes adding, updating and deleting nodes. I happen to work on an XML document from which I had to remove some xelments. Surprisingly I found numerous options that facilitate deleting of various xelements from  XML loaded in memory. Depending on where you are in the XML tree, you might find one method easier than the other. Here is a simple example that illustrates various ways I discovered of removing xelements from XML loaded in memory.

  • XElement.ToString returns encoded text

    I am sure people who do XML on a day to day basis would not find surprising but I think it was pretty cool to see that when I call  ToString on my XML, I get back my entire XML with whitespace preserved and also all text is encoded for me automatically. I created my XML using .net 2.0 api and saw the same behavior so I guess this was not a new feature but definitely a good default option to encode your text before outputting it to the user. Here is simple example that illustrates this behavior.

  • Avoid impurities in Linq To SQL

    This problem actually troubled me for hours until I accidentally figured out how to get around it. What I learned is try to avoid impurities in Linq statements. For instance, if you lambda expression's filter is applied by indexing an array value, do not access the array directly inside the lambda value. Instead get the value from the array assign it to a variable and use the variable in the Linq to SQL filter statements. I am not sure why I have to declare a variable to avoid an impurity. But if you do not follow this technique, more than likely you would end up with runtime error in your Linq statement. Even if you get pass the runtime error, you would end up with a wrong filter value being applied on your lambda expressions. Let's take a look at an example to understand the problem I am trying to describe.

  • Applying aggregates to empty collections causes exception in Linq To SQL

    I spent nearly two hours trying to figure out what was wrong with my Linq to SQL query. Basically I was trying to calculate the sum of sales generated by each sales agent. In order to accomplish that I had to travel from employee table to Orders which had the employeeid linked to it. From the Order table I navigated to its order details and calculated the sum of Quantity ordered multiplied by Unit Price. The query works fine when each agent has put in an order in the database. But when there is no order record for an agent the sum operation performed on SQL server returns null. When Linq to SQL tries to assign null values to data types that is not defined as null, it throws an exception. Below is an example that demonstrates this issue.

  • Entity Refs Not getting serialized with WCF service

    In one of the project that I am working on, my client requires me to use WCF service to talk to Linq To SQL datacontext. The infrastructure guys would not open up port for me to access SQL server directly. Therefore I created a WCF project in my solution, added a reference to Business library and exposed my Linq to SQL entities using WCF service. By default you cannot expose your Linq to SQL entities, you have to mark SerializationMode on the datacontext to Unidirectional. Once you configure the datacontext for wcf serialization, the generated entities are marked with DataContract attribute and properties on the entity are marked with Datamember attribute. If Linq to SQL entity have child entities those also get serialized. However child entities do not get lazy loaded, you have to explicitly call LoadWith to immediately load child collections for them to be serialized. Here is a simply example that illustrates the behavior.

  • Automatic entityset mapping in Entity Framework

    As I am starting to do work on both linq to SQL and linq to entities, I am finding lots of subtle differences on both implementations. Some implementations I would consider as being better over the other.

  • Eager Loading child entities in Entity Framework

    Once again I am comparing different behaviors in linq to SQL and entity framework. If you want to eagerly load child entities in Linq to SQL, you would use LoadWith operator available on DataLoadOptions. LoadWith method retrieves related objects for the main object. You have the option to call LoadWith method as many times as you need depending upon how many related objects you want to eagerly load.  If you want to eagerly load related objects in entity framework, you you can call include method. Include takes a path which represents the name of the related entity that you want to load. In the path parameter you can also use traversal by using dot notations. For instance for a particular customer, if you want to load its Orders and for each order want to load its OrderDetails, instead of making of two Include calls you can call include with a traversal like cust.Include("Orders.OrderDetails"). This tells entity framework to load Orders and for each Order load its OrderDetails as well. As with linq to SQL, you also can make more than 1 calls to Include to load multiple entities at the same time. Below is an example that illustrates different usage of eager loading with entity framework and linq to SQL.

  • Lazy Loading child entities in Entity Framework

    It's pretty interesting to see different implementations of lazy loading in both linq to SQL and entity framework. In linq to SQL, if you want to access the Orders collection of a particular customer, all you do is navigate to the Orders Collection Property and linq to SQL will run the SQL in the background and fetch the orders for that customer instance. The operation is pretty implicit. However in entity framework you have to explicitly tell that I intent to load the orders of the customer. The way you would do this is by calling Load on the Orders collection of the customer. If you forget to call load on the Orders Collection for the customer, you would end up with an empty collection of orders. This may be confusing and hard to troubleshoot bug and you would wonder why you have no orders for that customer when you could see orders in the database for the customer. Here is an example that illustrates this behavior.

  • Not All Lambdas can be converted to expression trees!

    It was surprising for me to discover that depending upon how you write your lambda syntax, it may not be able to convert to expression tree. If you are using a body expression in your lambda statements meaning you don't have an explicit return statement and no parentheses, than the lambda expression can be converted to expression tree. However lambda expression with statement body which requires an explicit return statement can only be converted to delegates. Expression trees are important because most providers of linq take expression trees and convert them to their domain specific language where as delegates gets compile into IL code which only Linq To Objects provider can understand. This is why it is important that your lambda statements are convertible to expression trees. Here is an example below which illustrates a lambda  statement that cannot be converted to expression tree and the error compiler raises in regards to that.

  • Different Ways of representing Lambdas

    Today I had some free time at work since my batch process was taking an hour to run. During this time, I was investigating the beauties of lambda expression. I have found lambda expressions to be very flexible and versatile. What I mean is, your lambda expression can be as long and as small as you need it. If you find that in certain portion of your code, it would be much more easier to read if there is less noise from language, than you can use type inference. Places where you feel the code would be easier to read if there is more explicit types declared, should have proper parentheses and return statement than by all means using statement syntax  form of lambda expression. If you find the lambda expressions getting polluted by too much code and thus making it harder to read than by all means point the lambda expression to a method that does all the complicated logic. Here are different ways I have been able to express lambda statements.

  • Compiling Extension Methods on .net 2.0 runtime

    Today, I had to work on a legacy .net 2.0 application and I found a neat little trick one of developers did to get extension methods to work on .net 2.0 runtime. I was pretty amazed because I thought extension methods was a feature available in System.Core assembly that is part of .net 3.5 framework.  In reality that is completely true and Extensions are available only in .net 3.5. However extension methods gets converted into the same IL code that is compatible with .net 2.0 runtime. So the only thing left is to satisfy the Visual Studio compiler that extension methods are valid statements for .net 2.0. On asking the developer who wrote the code, he said that in Visual studio .net 2.0 compiler only checks for an attribute called System.Runtime.CompilerService.ExtensionAttribute to be available for extension methods to work. So he basically added a dummy class of that type that inherits from Attribute class. After adding the ExtensionAttribute class, the compiler was satisfied and the project build fine.

  • Design Time Compilation in Vs 2008 Sp1

    I have been playing around with Vs 2008 sp1 bits and one of the very cool debugging improvements I have noticed is, you don't have to compile the project to see compilation errors. By default C# compiler would put squiggly lines below the code that is causing the problems and when you hover over the squiggly lines it will show the exact error that you would get if you were to compile the project. I think this feature offers a tremendous developer productivity. I cant imagine how many times have I actually compiled the project to see what error the compiler gives me. But now with this feature I will save so much time. All I have to do is hover over the lines that is causing the problem I will get the same error as if I was compiling the project. Hats off to C# team in pulling off this feature. Screen shot below shows this feature in action.

  • Paste XML as Element

    XML in Vb 9.0 has become a first class citizen. You can copy XML content and assign it to Xelment variable and compiler will not complain at all. You can even get intellisence on the XML in Vb if you import XML namespace. C# does not provide all these goodies. But recently when I had to do XML parsing from the data returned by Google mini, I came across this smart paste option that I had not discovered before. Basically you can copy some XML content, go to view menu and select paste XML as Element and it will generate all the XML element code needed to create that markup. This gives you a good start in building up the XML data that you desire. Below is a screen shot that outlines the code generated when I selected Paste XML as Elements in Visual Studio.

  • Source Outline PowerToy For Visual Studio

    I recently came across this power toy add in For Vs 2008 on CodePlex and I must say that its powerful and really makes navigating across methods, searching for methods fairly non trivial. Once you install PowerToy on your machine, you can open it by going to View Menu, Other Windows and clicking Source Outliner Power Toy. This will open up Source outliner as you can see in the screen shot. If you are on a class, that class will be selected by default on Source Outliner and by clicking up and down arrows you can see Visual studio moving the code editor to that method without a breeze. You also have the ability to search and Filter for a method in a class as well entire solution and Outliner will start populating the list as you type. I think Source Outliner is a great tool to navigate and find methods quickly. You can download the tool at

  • Finding All references of a method in Vs 2008

    Once again I am sharing some of the productivity features i have been discovering as I am starting to play more and more with Vs 2008. Not sure if this feature that i am about to discuss was already there is vs 2005 or is simply new to vs 2008. Anyway, in a large code base when I are modifying a method, I am always curious to know how many places in the code this method is being used and to be able to breeze through all the references for the method and get an idea of the context its being used. Pressing SHIFT + F12 will open up reference list window that show you all the reference links where this method is being called. Simply pressing F8 would allow you to navigate to each reference of the method in the list.  Below is a screen shot that shows the feature.

  • Code Definition Window in VS 2008

    Once again I came across a hidden gem inside vs 2008 called Code Definition window. It really is a slick window that lets me see the definition of the class without actually traveling or navigating to the class. Let's say you are inside of class that has method called SaveCustomer which takes customer object. Lot of the times, if I want to see the full definition of the customer class I end up going to the class, looking through it and than have to find my way back to the method I was originally trying to debug. With Code Definition window, I can stay at the method that I am interested and simply but my cursor on the Customer object parameter and in the code window I can easily see the entire definition of the class. Below is a screen shot that demonstrate this feature.

  • Auditing linq to SQL entity classes

    There are many ways to implement auditing on your entity classes. If you are not exposing linq to SQL entities to the presentation layer and prefer to use linq as a data access layer, than you can applying auditing on the linq entities in your business layer. The reason is, you have more control over the persistence and business layer is responsible for retrieving linq entities as well as saving them. However if you have considered that you can get away with using linq entities in your presentation layer because it provides partial classes where you can implement custom business logic than linq to SQL provides various easy ways to implement auditing features.

  • Eager Loading Self referencing table in Linq to SQL

    Today at my work, I had the need to display category and all the nested categories with in it so that its much easier for Google to have a once place where it can follow all the links to our site. I am not by any means SEO expert but our SEO expert said that Google would seem to come back quite often if it can find hard coded links to our categories as compared to crawling query strings on a page.

  • Accessing private properties and methods without Reflection

    This blog post title might be very surprising to the viewers. I am sure people would be thinking how in the word can you access private properties or methods without using reflection. Well in your code you don't have much choice except to use reflection. However if you are debugging, than immediate window lets you access private level properties and method. I thought it was pretty slick and also meant easier and more productive debugging.  In the code below, I have an Employee class which has a private method and a private property. I created an instance of my class, than stopped the debugger in the next line, opened up the immediate window and ran the commands below. Sure enough immediate window allowed me to call the private attributes of a class although intellisence didn't seem to help any in terms of calling private stuff.

  • DataContext.GetChangeSet to find what objects have changed

    When you make changes to object, delete or insert new objects, linq to SQL is tracking the changes and based on the original values, it generates the appropriate SQL statements. DataContext exposes a method called GetChangeSet that contains all the inserted, updated and deleted objects that will be sent to the database when SubmitChanges gets called. You basically have to loop through each collection and find out what objects have been effected.  If you want to know exactly what SQL statement would be sent to the database their is a private method called GetChangeText that you can call using reflection to find out the exact SQL statement that would be sent to the database. Example below shows a change set that contains few updated objects, an inserted object and an object marked for deletion.

  • Lazy Loading Properties in Linq To SQL

    Linq to SQL provides deferred loading of foreign key object such as EntityRef and EntitySet so that you get the best performance and do not end up loading the entire object graph until you need it. However there are situations when you have binary or varchar(max) columns on a table which you do not want to load until you access the property. A real world example for this scenario would be like you are storing images in the product table or product table has description column which is set to varchar(max).  If all you are doing is querying the product table to bring  product collection and wont be touching description or image column than there really is no need to be loading those column ahead of time. If you are going to be using the Visual Studio designer than simply go to the property and set the Delay Loaded to true to turn on Delay Loading. On changing the setting in the properties window, Linq to SQL designer will create a private variable of type System.Data.Linq<T> where T is the type of property  like string, int etc. Here is an example where I have marked description column to be lazy loaded.

  • Synchronizing AutoGenerated Properties After SubmitChanges

    When you insert or update a record in the database, there are certain columns whose values are either generated because they are identity columns, or columns whose value is assigned by SQL server such as timestamp column. You could have triggers that update columns after an insert or update on the table. Those column values are not reflected in your entity. However linq to SQL offers different syncing options to sync properties on your entities with column values generated by the database. You can use AutoSync parameter on your columns and specify when linq to SQL should update those columns such as OnInsert, OnUpdate,Always,Default and Never. I have generated a sample class that show variety of syncing options that you can apply on your properties to sync your entities after insert and update of a record to the database.

  • ExecuteQuery to execute dynamic SQL in Linq To SQL

    If you find that a particular query is hard to represent as a Linq query, you can consider other options such as writing your own SQL statements inside of a stored procedure or a function and than calling the stored procedure and function using Linq to SQL. You can also write dynamic SQL statements using the helper methods provided on DataContext. I am sure some of you may be thinking how is that new or different from ADO.net which always allowed executing dynamic SQL and getting a datareader or dataset back. Well you can achieve the same results by making use of ExecuteQuery<T> method available on the DataContext. ExecuteQuery method on DataContext does a lot more than simply executing a dynamic SQL. First it supports the concept of parameterized queries. You provide parameter like you provide parameters to string.format using placeholders which Linq to SQL converts it to a parameterized query. In traditional ado.net when you execute dynamic SQL, you either get a datareader or dataset. It had always been left to the developer to convert the datareader to customized business object. However ExecuteQuery takes in a generic type that tells the Linq to SQL that a particular SQL statement would return a strongly typed instance of the class passed in as a generic type. You no longer have to worry about converting datareader to object. There are some restriction that you must follow in order to accomplish proper mapping of your columns to properties on your object. First your query columns must contain the column that is defined as the primary key. Second the column names returned by the query should match with the property names defined on your entity class. If the column names do not match than you can use alias in t-SQL to match with the property name defined on your entity. Further more, Linq to SQL does not require that you return all the columns that map to all the properties on your entity. If your query is missing some column, Linq to SQL would assign default value to your property.  Below is an example that illustrates some of this behavior.

  • Executing Aggregates on SQL Server using Linq To SQL

    Linq to SQL support many aggregates such as Sum,Avg, Min, Max and few others but they may not execute on SQL server. Depending upon how you write your queries, you would be surprised the same syntax would actually bring the entire data from the server and execute the aggregate operations in memory. Below is an example where the entire query executes on SQL server and hence very efficient in terms of performance. While the same exact query just written in two steps causes the records to be fetched from SQL server and aggregate be performed in memory.

  • Change Notification In Linq To SQL

    If you have generated your Linq to SQL classes using visual studio Designer or used sqlmetal utility, you would notice that your entity classes implement two very important interfaces for change tracking called INotifyPropertyChanging and INotifyPropertyChanged interface. These interfaces belong to System.ComponentModel namespace and were introduced in .net 3.0 runtime. Although the use of these interfaces are not mandatory for your entity classes but having them make the change tracking process efficient and less memory intensive. If your entities do not implement Notification interfaces, Linq to SQL will keep track of two copies of your objects, one with the original values when you first fetched the object and second object which has changes applied to it. When submit changes is called, Linq to SQL will do a compare of those objects and send only the properties which has changed since the first retrieval. This process which keeps tracks of two copies of the object can cause memory issues when you are managing lots of objects. Therefore Linq to SQL also provides an option where it can allow entities to to participate in change tracking service. Entities can participate in change tracking service by implementing INotifyPropertyChanging interface and INotifyPropertyChanged interface and raise propertychanging and property changed event in the setter of the property. Let's look at some code below to see how our entities can participate change notification service.

  • Sorting eager loaded Child Collections With Linq To SQL

    By default Linq to SQL would lazy load all your child collections like when you have an instance of customer, its Orders are not loaded. ON traversing the Orders collection,  Linq to SQL fetches the Orders for that customer. You can use LoadWith operator to eagerly load the Orders for the customer. But what if you also want to sort that Order collection when your eagerly fetching the Orders. In that case you can use AssociateWith Method and specify the column that you want to order your Orders Collection by. Here is an example that accomplishes that.

  • Understanding Association Attribute

    If you have defined foreign key constraints on your tables in the database, LINQ TO SQL would generate Association attribute on both sides of the entity meaning the parent and child entities. Let's look at the association attribute generated by Linq To SQL on both side of the entities for Customer and its Order Collection.

  • Inheritance in Linq To SQL

    When you are programming in .net, you can apply inheritance and polymorphism concepts on your entity classes to solve your business problems. However when you are saving those objects to the database, there is no clean way to store different child entities having some common properties that they inherit from the base class and some properties that are specific to that child entity. One of the ways to store these objects in the database is by adding all the possible fields available for all the child and base classes and marking them as allow null. Then you simply set appropriate values for only the fields that are applicable to that specific child classes. In order to differentiate each row and identity what child class it is, you can make use of discriminator column.  Let's walk through an example to get a clear understanding of how to structure your inheritance hierarchy in the database.

  • Retrieving AutoGenerated Id from the database

    Most of us don't have to worry about how linq does all the magic in the background of persisting our objects and syncing up our primary keys that are auto generated in the database. However if you are manually creating your class it is good to know what attributes are must and required to be able to save objects to the database and how to sync the auto generated id created by the database with property defined as Primary column in the entity class. If you want to sync up primary key identity column with entity member when you insert an instance of the entity class, you have to set the column defined as Primary Key column and set the column as IsDbGenerated to true. Here is a very simple example of a datacontext and Categories class that has IsDbGenerated set to true for CategoryID column.

  • Using Storage Attribute to bypass property accessor

    For every column in the database, linq to SQL generates a property that maps a particular column in the database to the property defined on the entity class. However if you look at the setter property generated by the designer, it has all the details which raises events that notifies to the subscribers that property has changed. Basically for a property called ProductName, the designer generated code will raise a before and after event. Further more the setter also notifies the tracking service that property has been changed by the end user code. Due to this reason, linq to SQL is able to generate the appropriate SQL statement to send the changes to the database. However, when we fetch an entity from the database, linq to SQL has to go through the same process of assigning the property value by reading the column from the database, which is totally not required. We do not want linq to assign our property using the setter because the values assigned would be tracked and there is no point in tracking the value since it was not changed by the end user code. This is where we can use the attribute called Storage which specified the private level variable that linq to SQL can directly use to by pass property accessors and interacts directly with our field level variable.  By default the designer ensures this for your by making use of Storage Attribute. However there is nothing stopping you from changing this behavior if you want linq to SQL to use property accessors and go through your business logic defined inside your setter. Here is a an example of the code generated by the linq to SQL designer.

  • Table Valued function and Eager Loading Does not work

    Table valued function are nice way to apply further transformations to your linq queries. The reason is, they return IQueryable instead of stored procedure returning IEnumerable. I will not delve into the original problem that I was facing at work, but try to come with an example that identifies the issue I was facing with linq to SQL.

  • Join with Into Clause

    Joins in linq to SQL are not any different than SQL server. Join basically joins the results of two or more table and shows only record that match in the outer sequence  that has rows present in the inner sequence. Here is an example that illustrates that.

  • Defaults In Linq

    There are several query operators available in Linq that supports the concept of Default like SingleOrDefault or FirstOrDefault etc. Default returns the default value for that type. If the type is integer the default would be an int. If the type is string that the default would be a null. However if type is nullable ints than the default value would be nullable<int>. Here is an example of that.

  • Find Overloads of a Method

    Its pretty amazing that querying concept has completely eliminated my use of loops and if statements. Today I was playing around with someone's class library which was pretty big. I decided to print out all the methods and its overloaded versions available. Here is an example of printing out the methods available in int class and the display also shows how many times a particular method is overloaded.

  • All Operator Includes Empty Collection

    If you have not used All operator with LINQ query, you will realize that ALL operator will include collection that meet the criteria condition as well include collection that is empty. So if you have a query where you are trying to find customers who have all orders that are placed in city of London, than your customer results would include orders from city of London as well customers who have not place any orders at all. Let's take a look at an example.

  • Cant Do ServerSide paging With DataPager

    I am pretty sure I checked all my alternatives but I cant seem to find a way to do server side paging with ListView control and DataPager. Most of my existing code base does not use object datasource or LinqDataSource control which exposed a property called SelectCountMethod that gets the value of the total rows available for that select clause. Usually for server side paging you provide the rows which the user can see which is the startrow and maximum rows and than for the DataPager to build its UI, you provide method for SelectCountMethod that retrieves the count of actual rows available. But how do you accomplish this task when you are not using objectdatasource control. Well DataPager exposes a property called TotalRowCount whose value get set by the object datasource or linq datasource control. However this property is only readonly, which you cannot set if you are manually binding the ListView Control. I am not sure why the architecture was done this way which forces the use of a specific control to achieve server side paging.

  • Yield return break;

    The easiest way to end a method call is making a return statement. However when we are using iterators in .net 2.0 we can make use of yield return I to return the next element in the collection. Yield return I does not end the method but returns the next value in the collection and halts the method until the next MoveNext is called. So how do you deal with a scenario where you want to end iteration early based on some reason. Well, you can make use of yield return break which simply breaks out of the method. If you have any finally block declared, those will also get executed. Let's have a look at an example.

  • using TypeName with MasterType directive

    In the past I have only used Virtual Path attribute with MasterType directive. Using the MasterType attribute gives the page a strongly typed master page instead of casting the master page to correct type and accessing the property.  But what happens if you specifying the master page dynamically based on condition. In that case virtual path attribute would not work because you do not know what master page you are going to be inheriting from. The solution is to create a base master page and put your common master page properties in the base class. Now in order to get a strongly typed references to master page properties in your pages, use the MasterType directive with TypeName attribute which you can set to your custom master page class. here is an example.

  • Use Default constructors For Query continuation

    If you would like to build your queries based on existing queries, it is essential that you use object initializer instead of using non default constructor. The reason is non default constructors have no direct translation in SQL server. Therefore you cannot further reuse your queries and you would have to force rest of the query to be executed in memory. Here is an example that illustrates this behavior.

  • Reusing Linq Queries

    Today I was working on a class library(someone else wrote) that used Linq extensively. One of the problems I noticed was, there was no reuse of queries in the class. Every method pretty much return List<T> where T was a custom class that was created by joining three Linq to SQL tables. Here is an example of that.

  • DeleteAllOnSubmit sends individual Delete Statement

    In the application that I am currently working, the user interface allow the end user to select multiple items and mark them for deletion. After marking them for deletion they have to click the submit button to send the changes to the database. Well, I had the those objects in memory so I simply passed those objects to DeleteAllOnSubmit method exposed on datacontext and called submitchanges. I thought that linq to SQL would issue a single statement to the database to delete all those objects but it issued seprate SQL statement to delete each object. Here is an example that illustrates the behavior.

  • Filtering DataSet using linq

    Although DataSet provides some querying capabilities using its Select method but the usage is very limited and the result is not strongly typed. Using Linq to DataSet extensions you can apply unlimited querying capabilities and also transform your DataSet into strongly typed objects. Here is an example where I am returning products collection from a DataSet and also applying a filter on the DataSet to return products rows that belong to category of beverage.

  • Using Linq to Find Items Selected In ListBox

    If you are trying to find items selected in a ListBox, you could do it the old fashioned way by looping through list items and checking to see if item is selected and if the item is selected you grab the selected value and create an instance of the object, assign the selected value to the object and add the object to the collection. However a simple query makes this entire process only 1 liner. Here is the code that I used to grab selected items from a ListBox.

  • Returning Empty Collection

    If you ever wanted to return an empty collection instead of returning null, you can use Enumerable.Empty. The Enumerable.Empty creates an empty collection of correct type specified by the generic parameter. Here is an example of returning generic empty collection.

  • SiteMapPath Control is Screen Reader Friendly

    I was surprised that SiteMapPath control is screen reader friendly. It exposes a property called SkipLinkText whose value defaults to "Skip Navigation Links". When screen reader starts reading the page it will ignore all the links and only read the text specified on SkipLinkText. If you want screen reader to read a different text than what its default to, simply change the text to the content that you want the screen readers to read. The text you specify for SkipLinkText property will not effect you regular html rendering.

  • MasterType directive

    In the past, if I had to access specific property of a master page from my content page, I usually would cast my master page to right type and get access to property but this could lead to runtime errors. Today I discovered that you can apply master type directive on your content page to make your master page reference strongly typed. Once you apply the MasterType directive, you no longer have to cast the Master Page to correct type because it is casted to the right type already. Here is snippet that you can put in your content page.

  • Using ConfirmButtonExtender with ModalPopup Extender

    Today at work, an end user came and ask me that delete button simply deletes the row from the grid and does not give me a confirmation dialog. Can you fix this? I said sure. I simply had to add button extender to my grid view and I can then display the alert popup as soon as user clicks delete button. But obviously the alert box that comes up is pretty boring and there is not much you can do to spice it up. Than after researching a little bit, I realized that I could actually extend my button control extender with modal popup control extender. Button Control Extender has an additional property called displaymodalpopupid where you can reference the id of the modal popup extender. After that I simply added a modal popup extender and specify the targetcontrolid to be the delete button and popup control id to be the panel that will displayed. Here is the markup that creates a customized confirm dialog box.

  • Returning Anonymous Types from WebService to asp.net Ajax

    If your objects do not have complex types, you can have your WebService return an array of anonymous types and .net serializer will correctly serialize your objects to be easily consumable from JavaScript code. In order for you to return anonymous types from your WebService method simply return an array of objects because you do not know what the actual type is? Below is a simple example that demonstrate how to consume an array of anonymous type from asp.net client side.

  • Missing Association Links

    I must have spent good one hour trying to figure out why when I do category and dot, the products collection does not appear. I confirmed in the designer that category and product has an association link but when I open up designer.cs, I don't see Products EntitySet defined in Category class. It's really confusing why the designer shows that there is an association between category and products but the code is not generated. After an hour I finally realized that my category table did not define categoryid as primary key column. So keep in mind that if your table does not have primary key column defined, linq to SQL designer would not generate the code for association relationship.

  • Creating DataBound Control

    The other day at work, I was working with working with collection of data from database and wondered how hard would it be to implement a custom DataBound control. Surely enough on researching, I found out that you can inherit from CompositeDataBoundControl and override CreateChildControls to bind the data to the markup user has specified in ItemTemplate property of the control. Here is an example of a SimpleDataBoundControl class that I have created that inherits from CompositeDataBoundControl.

  • UseSubmitBehavior=false

    Most of the viewers would agree that there are so many gems hidden inside of asp.net that it takes some times years coming across them. Today I discovered SubmitBehavior property on button control. By default all button uses browser's default submit behavior to post the page back to the server. However there are cases when you are building server controls where you need explicit control as well as access to the JavaScript function that causes that button to post the page back to the server. In those scenarios, you can set the SubmitBehavior = false which will cause __doPostback JavaScript function to be attached to the button that will handle the postback for the button. On the server side, if you want to access the JavaScript function that causes the postback for the button you can use GetPostBackEventReference to access the JavaScript function. Here is a simple markup that uses UseSubmitBehavior property and also shows the JavaScript function emitted by asp.net.

  • ASP Namespace

    ASP is the namespace where all the generated code files in asp.net reside. When a request is made to IIS for a page, if it ends in aspx extension, the request gets sent to aspnet worker process where the aspx file is converted to a class with filename_aspx and stored in Temporary Asp.net Files. By default all these generated files are stored in ASP namespace. In fact in visual studio, you can get intellisense of on these files as shown below.

  • ParseChildren in Templated Controls

    Well, I have been spending sometime learning about Templated controls at work. Hence I am slowly getting an understanding of common attributes that you would want to use on Templated controls. If your template control inherits from WebControl than you do not need to worry about setting ParseChildren to true because by default WebControls have ParseChildren set to true. However if your controls inherit from Control class, than in order to get Templates to work you need to set ParseChildren to true. When you set ParseChildren to true, asp.net parser maps the top level tags of the server control to properties on the server control. For e.g

  • Instantiating Templates

    I thought to write a blog post telling what is the correct way to instantiate templates because on researching many blog posts and reading few articles, I saw couple of different usages and one of them is misleading and incorrect. Here is the most common way of instantiating templates for a custom control.

  • Use TemplateInstance.Single to avoid FindControls

    If you have created templated controls, you would be aware that it requires you to implement INamingContainer. Only job of INamingContainer is to ensure that controls are unique within that Naming Container. However sometimes if you are using Templated controls that are not going to be repeated like LoginView Control has anonymous Template which does not have a concept of a repeated template, in those cases you would like to be able to access those controls directly in the page.Templated controls have a requirement that contents with in the templated controls must be instantiated inside of a container that implements INamingContainer. Here is a simple example that illustrates this behavior.

  • When to instantiate templates

    Most of the examples that I saw on the net recommended to instantiate templates inside of CreateChildControls method but it does not work correctly. Basically I marked my Itemplate property to TemplateInstance.Single, so all the controls inside my template are available to the page without using FindControl. This works great but only in design time. In the design mode, I can access all the controls but when the page executes, any controls being accessed that are inside of template causes object reference not set to an instance of an object. For a while I couldn't figure out what was going on. Then I realized that UpdatePanel has pretty much the same implementation I can access all the controls inside of UpdatePanel without any problems. Using Reflector I saw that UpdatePanel was not instantiating the template inside of CreateChildControls, in fact they were instantiating the template inside ITemplate property as shown below

  • Using Pragma to disable warnings

    Lot of times, you have variables declared in your class that are never getting used directly and are accessed and their values altered using reflection. In those cases when you build you solution you get a warning saying that this particular field is never used. Here is a simple example that shows warning for first field in Person class for not being used.

  • Global Namespace in C#

    By default if you do not specify a namespace for a class it will go to default namespace. What happens When you are in particular namespace that has the same class that is also available in default namespace. How do you access the class that is available in default namespace. With C# 2.0, global keyword was introduced which allows you to access class that is available in global namespace. Here is an example that illustrates the problem and how we use global to access class available in global namespace.

  • Callbacks in Asp.net Ajax

    Callbacks provide an ability to call a function passing in additional parameters that your function would need. In the past to achieve this objective, I have created global variables that can be referenced from any where in your code. . Instead using callbacks, you can pass in a context that has the information your function would need. In the example below, I am passing an array of numbers to a callback function which simply writes the array to a label. Here is the markup

  • Moving Divs on the page

    Today I had a need to move my progress bar control on top of any control that was being updated asynchronously. Therefore I had to reposition my progress bar when an update happened. This lead me to investigate asp.net Ajax client side library and see what api it provides me to move a div from one position to another on a page. Sure enough Sys.UI.DomElement provides a method called getbounds which returns the width,height, x and y coordinate of an element on a page. The DomElement object also provides static method called SetLocation that takes 3 parameters. First parameter is the element that you want to move. Second and third parameters specifies the x and y coordinate of the location where the element should be moved to. To demonstrate the usage I have created a simple page which has 2 buttons. First button simply returns width, height,x and y coordinate of an element on the page. Clicking the second button moves the div to new x and y location on the page. X and Y positions are obtained as user input from the textboxes on the page. Here is how the page looks like.

  • Prevent Enter Key using Asp.net Ajax

    Today at work, I had a requirement where I had to prevent user from pressing enter key when they are on a particular textbox because it would cause the page to postback which I wanted to prevent. Using asp.net Ajax, you can register for the keypress event. The key press event gets an argument of type Sys.UI.DomEvent. The DomEvent object has a property called charCode which tells you which key the user has pressed.You can compare the charCode value with Sys.UI.Key.enter to check if the user has pressed enter key. On confirmation that user has pressed enter key, I make use of method exposed on DomEvent class called preventDefault. PreventDefault basically prevents the default action from happening which in my case prevents the enter key from being executed. Here is the code that prevents enter key from being executed by trapping keypress event on textbox.

  • Debug Vs Release Version of JavaScript file

    When you are debugging application it is easier to work with debug version of js file because the code is indented and comments provide better readability. However when deploying it production debugs version would increase the load time of the page. ScriptManager makes it really easy to work with debug and release versions of JavaScript file by using its ScriptMode property. For instance if you are referencing a JavaScript file called Popup.js, in order to get debug and release support from ScriptManager, you need to have two versions of the the js file like Popup.js and Popup.debug.js and depending on the ScriptMode set on the ScriptManager it will pull the appropriate JavaScript file. Here is an example that shows how to reference debug and release version of a JavaScript file.

  • Getting Intellisense in External JavaScript files

    If you are having problems getting Intellisense to work in external JavaScript file, you need to add reference directive with 3 /// comments. If you are pointing to your copy of js file, use Path attribute otherwise use name attribute to reference any JavaScript files outputted by the script manager. Here is the syntax for referencing both kinds of JavaScript file.

  • Authentication and Profile Services in asp.net Ajax

    With .net 3.5 Microsoft introduced authentication and profile services which allows you to authenticate using client side libraries. You also have the ability to update values in your profile using asp.net profile services. To work with this example, you need to set to up Membership ship database by using aspnet_regsql command. Enable form based authentication by changing the authentication mode to Forms. If you have created asp.net 3.5 website project, you will see profile and authentication and role service registered in config section of web.config as follows.

  • Getting entire XML content

    Another hidden jewel in the new XML api is the ToString method. ToString method has been overwritten in XElement. In Dom W3C api if you were to do ToString, you would end up with object type. However ToString in XElement outputs the XML string itself. It is nice to be able to pull a certain fragment of XML once you have obtained the reference to a particular XElement. Here is a simple example that illustrates the nice feature.

  • Getting Node Value using XElement

    If you have used Xml api in previous versions of C#, you must have felt the pain to extract node value and cast it to the correct type. With C# 3.0 new xml api, getting Node value is as simple as casting the node to the right type. You can still use the old fashioned XmlConvert class and convert the value to the right type by passing in the Value property of the node to get to the node value. Here is an example that illustrates how easy it is to convert xml node value to the right type.

  • Using AsEnumerable Hint

    Recently I had a huge query that I wanted to execute on SQL server. However certain portion of query had to be executed in C# as linq to objects because SQL server cannot comprehend regular expression. In trying to figure how I can tell linq to SQL to not execute this portion of the query in SQL server, I discovered AsEnumerable operator. AsEnumerable operator is a hint that tells linq to SQL to execute the portion following it in memory. Here is an example of a query that gets the data for customers from SQL server but applied a regular expression filter in memory. It is not the best solution but illustrates how you can use these hints to drive what gets executed on SQL server.

  • Associations To Joins in LINQ TO SQL

    When your SQL server tables has foreign and primary keys constraint defined, dragging those tables on the linq to SQL designer creates association relationship that can help traverse other related objects. For instance, if you have an order table than you may want to traverse the customer for that order and as well as find out the employee who submitted the order. When you are using the dot operator to do the traversal, linq to SQL uses different join based on the schema defined for the relationship. Let's look at a couple of different traversal to understand what kind of query gets sent to SQL server.

  • Filtering LINQ To SQL using Object comparison

    One of the recent trick I discovered with linq to SQL queries is, when you want to filter records, you do not necessarily have to filter by primary key like CustomerID. Instead you can compare object references and linq to SQL in the background would convert the linq query as comparison based on primary key of that table. For instance if I want to find all the orders for a particular customer, I would write a query like this

  • Handling errors in asp.net Ajax

    The default configuration for asp.net Ajax simply shows an alert box if your asynchronous postback causes an exception. This may not be the appropriate way you want to handle exceptions in your application. Here is a simple markup that illustrates this behavior.

  • Refreshing the page on Interval basis

    If you ever wanted to refresh a portion of your page on a certain interval, it does not get any easier with asp.net Ajax. Simply surround the content with an Update Panel and trigger the update of the Update Panel using the timer control. Here is the markup that illustrates this example.

  • Order of Where Clause Matters in Linq To Objects.

    The order in which you apply where and join in SQL server does not matter too much. One of the reason is that SQL server has its own optimizer built in which knows how to rewrite the query so it is optimized for best performance. However we don' get that luxury with Linq to objects. Therefore it is essential that you understand how to write your query so that it gives you maximum efficiency. For instance apply your filter before joining because filtering would reduce the number of rows returned and as a result there would be fewer rows that you would need to join against. Here is a simple example that illustrates the performance gain that you would get when you apply the where clause before the join statement.

  • Optimizing join queries in Linq to Objects.

    For many years working in SQL server environment and writing dozens of joins, I never cared which table needs to come first and which one comes second. The reason was SQL server would use table statistics to determine best way to join two tables. However we don't get this luxury when we are writing Linq to object queries in C# 3.0. For instance if you have two sequences in memory and you have to join those two sequences, than always use the smaller sequence on the right side of your query and the larger sequence on the left side. It makes a considerable difference in performance. To prove that there is a big difference in the time it takes for the query to execute I will put a small sequence on the right side and run the query to see how long it takes.

  • Order in join clause matters in Linq

    Yesterday I was writing a Linq query that required joining two tables and mistakenly reversed the order of columns being joined. Surely enough compiler complained. I was pretty surprised why my code did not compile. I am sure many of you are SQL gurus and must have written joins and never cared that left column in the join clause must always come from the left table and right column in the join clause must come from right table. SQL server and many other database engines are pretty lenient in it. However Linq flavor requires your key selectors in the join clause must be in proper order. Basically left key of the key selector must come from left sequence or outer sequence. The right key of the key selector should come from right or inner sequence. Here is an example which C# compiler does not like because the order of the key selector is reversed.

  • PageLoad event firing twice

    On one of my projects I had the need to intercept the begin request and pageloaded event of page request manager. Begin request is an event raised by page request manager when a control inside of an UpdatePanel postback to the server. The event is raised just before the request is sent to the server. PageLoad event is a similar event but it gets raised the after the request has been received from the server and appropriate Update Panels have been updated. When I registered for pageloaded event and was manipulating the controls based on the data data received from the server, I was getting weird behaviors after resetting variables I had declared globally. To investigate the matter I put debug statements and sure enough confirmed that PageLoad event was firing twice. Here is an example that displays that behavior.

  • Table Valued Functions in Linq To SQL

    Linq to SQL supports both stored procedures and functions that can return result set. However there is a clear distinction in each approach. When you are using store procedures the data is returned as IEnumerable<T>. What this means is in the Linq query where you are calling the stored procedure, if you want to further apply more query operator meaning further filter the result  than that portion of the query will get executed as Linq to objects without you being aware of it. This could be great bottle neck if your stored procedure returns thousands of record and your applying filter that gets applied in memory instead of being sent as a part of query that gets executed on SQL server. In contrast if you are using table valued functions, data returned is in the form of IQueryable meaning you can further refine your query based on filters that you require. Those filters would become part of the SQL query that gets sent to the SQL server. To demonstrate this behavior I will start of with a table valued function and a stored procedure that returns customers based on city parameter.

  • anonymous types are readonly!!

    This was totally surprising when I learned in the usergroup meeting today that once you initialize an anonymous type you cannot change its properties after that. It is marked as read only. Following code does not compile.

  • Creating Extension methods with same name as instance methods

    I had a really good time at the user group meeting tonight. Learned some new stuff on linq. An interesting point one of my prior co-worker Matt mentioned was if you create an extension method with the same name as the instance level method on the class, the compiler does not raise any exceptions. For a second I didn't believe it and so I went home and tried. Sure enough he was true. I would think that it is illegal to declare an extension method with the same name as instance method because instance method should always take precedence over extension method. Also say if you had an extension method that does some stuff. Later you upgrade to a new framework and the framework also includes a method with the same name. Since C# compiler does not raise compilation error, you wouldn't know that in fact you are actually using the method implementation from the framework than your extension method which may not be the desired behavior. I am curious to know why other people think that C# compiler should not raise a compilation error in this scenario.

  • Using RegisterDataItem on ScriptManager

    Although there are different ways of sending data to client side from asp.net Ajax such as webservice, page methods, ScriptManager.RegisterStartupScript and many other ways. However my specific requirement was a bit different. I simply needed to send a value down to the client when a postback occurs through a button that is inside of an UpdatePanel, basically send additional data via ScriptManager to the client code when its sending the partial changes of the UpdatePanel down to the browser.You would want to use this technique if you are updating or want to update a control that is not part of an UpdatePanel. If the control that you are wanting to refresh is inside of an Update Panel, than simply calling UpdatePanel.Update would be sufficient enough. Here is the markup that shows how to send values down to the client code and updating a label on the client side with the data from the server.

  • Causing Full Postbacks from Inside of UpdatePanel

    Recently I had a need where I wanted to just make one control inside of my Update Panel fully post back to the server with out any asynchronous request. Well my need had to do with uploading a file which is an upload control followed by an upload button. If you have tried like me before you would realize that you cannot upload a file from inside of an Update Panel. It has to go through a regular postback to successfully upload the file to the server. If you have a similar need you can make use of triggers collection and add upload button as part of Postback trigger instead of an asynchronous postback trigger. Here is a simple markup that demonstrate the behavior.

  • Canceling Async PostBack

    Asp.net Ajax can perform at most one Async PostBack at a time. If the user initiates a second PostBack, it automatically aborts the previous request and initiates a new asynchronous PostBack. If this is not the behavior you desire, you have the ability to cancel new request until the existing request completes. In order to cancel new request you will have to register with beginRequest event of the pagerequest manager and check to see if there is an existing request that has not completed. If it is not completed than you can cancel the new request. The reason asp.net Ajax has limitations for only 1 Async PostBack is because of viewstate. If it were to allow more than 1 request than viewstate would get out of sync. If the current request takes too long to come back you can also have a cancel button on the UI and let the user cancel the existing page request. Here is the markup that I have written that displays the behavior.

  • Tracing Asp.net Ajax Client Side Request

    When you add script manager control on the page, it not only goes though page life cycle on the server but the request goes through series of events on the client side. There are two client side objects available in asp.net Ajax; Sys.Application and Sys.WebForms.PageRequestManager object. Sys.Application events are raised because of scriptmanager and PageRequestManager events gets raised only when there are updatePanels present on the page. In order to illustrate all these events I will use tracing feature available in asp.net Ajax. By using Sys.Debug.trace, I will write trace messages to a textarea with id equal to TraceConsole. If you have Firebug extension installed on firebox, the traces get automatically written to the trace console of Firebug. Here is how my markup looks like.

  • Sending script After Async PostBackPostBack

    I am sure many of you have been in a situation where you have a form view or details view control inside of an UpdatePanel and after inserting a successful record into the database you went to send a small JavaScript to the end user saying that your record got successfully inserted into the database. I made use of ItemInserted event of FormsView control and used the Page.ClientScript.RegisterStartupScript to inject the JavaScript into the output stream. Unfortunately this ClientScript on the page object does not work when you are inside of an UpdatePanel. Here is the markup and codebehind of my page.

  • Setting Default Values on Your Custom Control

    Today when I was working with creation of server controls, I realized that I wanted my server controls to work out of the box using default values when you drag and drop the control onto the designer surface. That's when I started digging into what do I needed to do on my server controls to set default values. Sure enough I welcomed the new attribute ToolBoxData in which you can specify default values for the properties of your control when it gets dragged. Here is an example of Address server control in which I am setting default values for the properties address,city, state and zip on my address control.

  • How to avoid cc1 prefix when dragging server controls

    Continuing with my exploration in server controls, i discovered a small nuisance when i you drag your custom controls from the toolbox onto the designer. For some reason visual studio would automatically prefix the server control with cc1 tagprefix as shown in the example below.

  • RenderContents Using enumerations

    Continuing with my discovery of server controls, I have come across few more goodies. As I mentioned in my earlier blog posting that there are two different ways of writing content when you override RenderContents method inside of a server control. Here is an example of two different approaches.

  • Registering Server Controls in web.config

    If you have a custom server control that you are going to use in several different pages. It might be worth while to register the server control in web.config file instead of registering it in several different pages. Here is an example of registering my custom controls library in web.config file.

  • Deploying assemblies to GAC

    This topic may not sound too interesting too people because it is an old story. Basically in order to store anything in gac you have to strongly name an assembly. I don't  happen to put assemblies in GAC too often so I simply forget the process of strongly naming an assembly. This time around I decided to write a blog post so that I would always have something to look back into.

  • Initializing Controls in CreateChildControls

    Once again in my adventure of writing custom controls I have discovered that if you are overwriting custom CreateChildControls to add your own controls to the control collection, you should initialize the controls before adding them to the control collection.  Here is an example where I am setting properties on the link button after I add them to the controls collection. 

  • Using RenderBeginTag

    At my current work, I had my share of custom controls that I have to write. Basically I started to write my html by overriding the render contents. I had been using the old style RenderBeginTag and than add my styling by calling write attribute. It is nice but the problem that I have with is at the end I have to know which tag to close which is sometimes a pain. Therefore when I found this new method called RenderBeginTag, I thought it was nice because when I have to close the tag I simply have to say RenderEndTag and it automatically figures out the tag I have to close. Here is a simple code showing two different ways of doing it.

  • Overriding ConnectionString in DataContext

    Today at work, one of my co-workers mentioned an issue that he was loosing ConnectionString every time he would modify the linq to SQL model in the dbml file. What he was essentially doing was getting rid of the default constructor and adding a partial class where in the default constructor based on business rules, he would fetch the right ConnectionString either from web.config, app.config or some other xml file. Obviously the problem here was, you cant have two default constructors. Because every time you would modify the dmbl file any changes you have made to the designer.cs would get lost. But a simpler solution to this would simply be creating your own partial DataContext class and adding the OnCreated partial method which gets called in the default constructor. Here is a simply implementation where I am reading the ConnectionString from web.config ConnectionString section.

  • Working With Expression Trees

    Now I am not going to be talking about expression trees in depth. I will be covering expression trees at basic level. The reason I started playing around with expression tree was not to write a provider but basically to be able express my intent at runtime. Linq is so much at compile time that sometimes it is not feasible for dynamic queries. This is where you can use expression trees that allows you define your intent based on runtime decisions.

  • ConvertAll delegate

    Today I had the need to convert a list of objects in a collection to a list of different objects in a collection. Although its a pretty simple use case which would not require too much manual code to do it. But surely enough I got introduced to a build in method Convert that is available on List<T>. Convert pretty much tells you by name what its purpose is. It converts one collection to another collection by taking a delegate which specifies how to to transform one object to another. Here is an example that shows how to use ConvertAll.

  • Implicit Arrays

    One of new features in C# 3.0 that I am really fond of, is not having to declare what type of array it is. It starts by checking all the values in the array and seeing if they can be implicitly converted to one type. If it can, than it is considered the array type.

  • Var cannot be used as instance level variable

    Today I was playing around with Var and I decided to try to implicitly declared some of my instance level variables. Unfortunately compiler raises an error saying Var can only be used in the scope of local variable. Here is an example.

  • Unique Behavior when querying using primary key column in linq to SQL

    I was working on a query earlier in the day when I came across this behavior when searching for a record using primary key in linq to SQL. Basically when you query for an object the first time using linq to SQL, datacontext caches the object in its tracking service. Therefore next time around when you query for the object again, it retrieves the modified object from the cache. It is worth noting that if you are querying based anything that is not a primary key column than linq to SQL would make a database call the second time around as well. After completing the database call, it will than check with the data tracking service to see if that object is available in its cache. If it is available, it will return the object from its tracking service. However when you are querying based on primary key column, it does not bother making the database call, it simple ask the object from the tracking service first and if it is found it simply returns it. If the tracking service does not have the object than linq to SQL goes and makes a database.

  • Useful tip to infer types in Visual Studio.

    There are times when your linq query would return complex data. If you are not exactly sure what the return type is, than simply assign the result to var and hover over the var to see its exact type. Here are two examples that illustrates the beauty.

  • Partial Methods

    Partial methods is a new feature available in C# 3.0. Partial methods allow hooks into automatically generated code. Partial method basically consist of definition and implementation. Usually you define and declare partial method in one partial class and implement in another. Partial methods are heavily used by code generated from linq to SQL.

  • Static Classes in C# 2.0

    In C# 1.0 if you wanted to ensure that no outside user can create an instance of class and that class user should use static method or properties to use the class,  you would normally mark the class as sealed and make the constructor private. When you make the constructor private, no outside user can create an instance of the class. Marking the class as sealed prevents any outside user to extend the behavior of the class. However the draw back to this approach is having two change two things and secondly you can get away with declaring instance level properties or method without compiler raising an error. Obviously those methods and properties are pretty much useless since no one can create an instance of the class. Here is how you would create the class in C# 1.0.

  • Loading Child Entities With Deferred Loading Turned Off

    If you have a situation where you do not want to risk your code making too many database calls without you knowing about it. You have the ability to turn off deferred loading by setting DefferedLoadingEnabled to false. However when you set it to false, you loose the ability to fetch that object or collection of objects anymore. What you can do is take control of loading those child entities in your query explicitly. Let's look at an example where deferred loading is turned off and the results you get when you access the child collection.

  • Group by multiple columns in Linq To SQL

    Today I was writing a Linq query in which I wanted to applying grouping to query based on more than 1 column and also apply filter on the group more like having clause. After some playing I figured it out. Here is a simple demonstration of grouping by more than 1 column using customer table from NorthWind database.

  • Action delegate in C# 2.0

    I have used in the past predicate delegate, which is used when you want to test for a certain condition. However Action delegate is used when you want to perform certain action on specified value. The specified value could be complex type or value type. It could be printing to console window or modifying the current object or value. Here is simple example in which I am making use of Action<T> delegate.

  • Using Linq To SQL with ObjectDataSource Control

    In my previous blog posting I showed how to use linqdatasource with gridview,detailsview and formview to insert, update and delete records using NorthWind context. Linqdatasource is a nice control to have, however I feel that it forces me to put too much business logic in my aspx file. Not only that, it also forces me to expose my datacontext to my presentation layer. In this small example I making use of ObjectDataSource control to insert,update delete and select records using my business objects.

  • My vacation pictures

    I had a really good time during my vacation at disney. I had been meaning to post my vacation pictures but have been really occupied at work and learning new stuff. Finally i was able to find sometime to get all the pictures uploaded to flick.

  • Using Linq To SQL With WCF Service

    The other day I met someone in the usergroup who asked me if I know how to use Linq to SQL classes in wcf and if Linq to SQL classes were serializable over the wire. I haven't done any wcf except attended quite a few talks on WCF. I decided to research of what I need to do to consume my Linq to SQL classes using wcf service with asp.net as a presentation layer. Here is a small walk through that illustrates an example of that. I am going to be demonstrating the example using Customer class from NorthWind database.

  • Using LinqDataSource for Inserts,Updates and Deletes

    In this small walk through I will demonstrate how to use linq datasource to do insert,update,delete and select using form view,gridview and details view control. I will use Formview control to do inserts and use gridview to do updates and deletes. When you select a row in the grid, the detail record will be displayed in a details view control. The screen shot of the page looks like this.

  • ObjectTrackingEnabled Does not Work!

    Today I was messing around with the datacontext that I created for linq to SQL NorthWind database. One of the ways to improve performance for the datacontext for web scenarios is turn off object tracking on the context. If you are using the context for read only purpose rather than insert update or delete, than you do  not need to bear the heavy cost of object tracking service. But what I have found out recently is, if you turn off object tracking on your datacontext, you loose the ability to traverse relationship. For example, if you traversing one one to one relation like Customer.Address.City than you would get a null reference exception. If you navigate a many to many relationship like Customer.Orders.Count(), you will get 0 despite the fact that a particular customer would have orders.

  • Invoking Generic Methods Using Reflection

    This is by no means any detailed post on how to use reflection. The other day I had the need to use reflection to call a generic method. So after playing around with reflection for few minutes I figured it out.  Here is how the code looks like.

  • Static fields in Generics

    If you have used static fields before you would be aware that no matter how many instances of a class you create, you will always end up sharing the static field among all instances and there will be only 1 value. Changing the static value would effect and reflect the new value for all instances of the class as shown below.

  • How To Hide IntelliSense

    Another neat trick that I learned recently is using the Cntrl key. There are times when you are coding and need to see something that gets hidden behind the intellisense window. Instead of pressing Esc to get rid of the window, I find it easier to hold down the Cntrl key which fades the intellisense as long as you have the key pressed. Nice features that saves some time.

  • Comparison Using Generics

    As I was playing with generics, I found something really interesting in terms of comparing two reference types using generic method. For example, when you compare two reference types using == or !=, you are basically comparing the references of those two objects. However when you compare two strings, you are actually comparing two values to see if they are equal instead of comparing references. This is because string class overloads those operators to define a different implementation of == and != operator. When you apply comparisons in generic methods, you would be using the default implementation of == and != that is defined by the object type. This is because the compiler resolves the method using unbound generic type and does not try to accommodate all the possible method calls based on different generic type which may have overloaded the == and != operator. Because of this limitation you may not get the correct comparison achieved in generic method as shown below.

  • 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.

  • 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.

  • 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.

  • 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.

  • 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.

  • 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.

  • 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.

  • 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.

  • 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.

  • 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!!

  • ThenByDescending Operator Part 16

    ThenByDescending is one of the query operators available in linq. You can use ThenByDescending operator with linq to objects,linq to xml and linq to SQL.ThenByDescending operator is used when you want to sort by more than 1 column or property. You initially start with either orderby or orderbydescending. Since both these operators return IOrderedEnumerable<T>, you cannot reuse these operators again. This where ThenByDescending operator comes into play. ThenByDescending is an extension method which takes a keyselector delegate that returns the key which is used to sort the collection in descending order. The output collection returned from the ThenByDescending operator is of type IOrderedEnumerable<T>. Therefore if you want to sort again in descending order, you can reuse the same operator.

  • OrderByDescending Operator Part 15

    OrderByDescending is one of the ordering query operators available in linq.You can use OrderByDescending operator with linq to objects, linq to XML and linq to SQL. OrderByDescending operator can be used in method or dot syntax as well as query syntax which is more of a SQL like syntax.

  • ThenBy Operator Part 14

    ThenBy is one of the ordering query operators available in linq. You can use ThenBy operator with linq to objects, linq to XML and linq to SQL. You will typically use ThenBy operator to do secondary sort. ThenBy operator is used to sort by more than 1 property. When you want to sort initially you would start with using the orderby operator. Since orderby operator returns IOrderderedEnumerable<T>, you cannot reuse the orderby operator again because it can be only used on sequences that implement IEnumerable<T>.  This is where the ThenBy operator comes into play. ThenBy operator is an extension method that is available on input sequence that implement IOrderededEnumerable<T> and also returns IOrderedEnumerable<T> which allows you to reuse it multiple times if you want to sort by more than 1 column or property. The prototype of ThenBy operator looks like this

  • OrderBy Operator Part 13

    OrderBy is one of the ordering query operators available in linq. In terms of availability, you can use OrderBy query operator with linq to objects, linq to SQL and linq to XML. Unlike many query operators that are only available in method or dot syntax, OrderBy query operator can also be used in query syntax which is sometimes easier to use than method syntax.

  • Union Operator Part 12

    Union is one of the set query operators available in linq. It appends 2 input sequences together ensuring that duplicates are removed and returns a single output sequence. The prototype for union operator looks like this

  • Reverse Operator Part 11

    Reverse is one of ordering query operator. Reverse operator simply returns the input sequence in the reverse order. It does not effect the elements in the input sequence in any way. The prototype of the reverse operator looks like this

  • SequenceEqual operator Part 10

    Sequence operator determines if two sequences are equal to each other.Two collections are considered equal if they have the same number of elements with same values and in present in the same order.

  • Concat Operator Part 9

    Concat is one of the set operators available in Linq. When you work with Linq query operators for sometime, you would notice that there are certain query operators that can all perform a certain job but some operators in certain scenario are easier to work with or more efficient in performing the computation that others. Concat operator allows you to join two sequences together into one single output sequence. You can perform the same operation using selectmany or union operator. The selectmany operator has an advantage that it would allow you to join many sequences into one single sequence.Concat supports joining only two collections and therefore you would have to repeat this operation several times to achieve the same result that selectmany operator would give. Union offers the same functionality with little more power. With union, you can get rid of duplicates that is elements that are common in both sequences. Union uses the default EqualityComparer. If this comparer does not suffice you needs, you have an overloaded option to specify you own IEqualityComparer that defines how to compare two elements to identify if there are same or not.

  • SkipWhile Operator Part 8

    SkipWhile Operator skips elements based on the delegate condition. It continues to skip the elements as long as the predicate returns true. As soon as it encounters false statement, it returns rest of the elements. The prototype of the skip operator looks like this

  • Skip Operator Part 7

    Skip is one of the filtering operators available in linq. Skip operator skips the first count elements and returns rest of the elements in the collection. The prototype of the skip operator looks something like this

  • Take While Operator Part 6

    Takewhile is a partitioning operator available in linq. It starts from the beginning of the series and continues to return the elements from the input sequence as long as condition is validating to true. As soon as it hits the first statement that evaluates to false it skips rest of the collection.

  • Take Operator Part 5

    Take is one of the filtering operator available in linq. It returns first n number of elements and discards rest of the collection. The prototype of Take operator looks like this

  • Select Operator Part 4

    Select operator is one of the projection operator available in LINQ. Select operator allows you to return an output sequence of certain type by transforming the input sequence using the lambda expression. The output sequence could be of same element type or different but the number of elements returned from the Select operator is always same as the number of elements passed in the input sequence.

  • Where Operator Part 3

    Where operator is a restriction operator that allows you to filter collection of objects if the collection implements IEnumerable. If the collection happens to implement IQueryable, where operator gets translated to equivalent SQL server operator and the filter gets applied on SQL server. When using where operator you provide a Func delegate that  returns the element if it matches the condition passed in as a lambda expression.

  • Select Many Operator Part 1

    Select Many Operator is part of the projection query operator supported by linq. SelectMany operator is mainly used for flattening out the hierarchy of collections into one single collection of objects. It merges each item into a single sequence that gets returned by the query results.

  • Delegates in C# 3.0

    Delegates in C# has been around since 1.0. But every occasion when i want to use delegates i end up goggling for an example. so i decided to write a posting  that i can consult every time for its basic usage.

  • Exploring Asp.net Ajax Client Side Library

    Although javascript is truly not an object oriented languange, microsoft with the release of client side framework for ajax, had really made working with javascript much easier. Today i will explore the concepts for javascript intellisense, notifying asp.ne ajax framework of any external client side libraries and how to create classes and use inheritance to extend those classes.

  • Linq to Sql Execution Plan.

    I recently wrote another article on codeproject which talks about linq to sql execution plan. Pretty long but worth the read. Hope you guys will enjoy!

  • My contributions to the community.

    OK its pay back time. Over the last 3 years working as a .NET developer I had made significant progress in my life. It all due to extraordinary developers contributing to our community and teaching us good practices to write and produce better software. I have acknowledged the fact that more you teach other people, the better you get. My journey begins here. There is no better way to serve the community than to participate in writing blogs and converse about new thing that I discover while performing my daily jobs at work. I will strive to write good content to help other fellow developers with my knowledge contribution. This blog will serve as a vessel for my technical thoughts as well as my personal ones.
     
    Obviously there are certain trade offs I would have to make in order for me to dedicate more time to writing blog entries. However I see embarking on this opportunity as a way to improvise my communication skills and be more lucid in expressing my thoughts. Asp.net has not only been my profession but a drive that motivates me to develop myself everyday as a software developer. I will endeavor to make good impact on the software community with my share of knowledge in .net. So wish me best of luck in making the most intricate change in my life!