Tuesday, April 29, 2008

How To Set Default Application Wide CommandTimeout in LINQ to SQL DataContext Subclasses

Sometimes you have written long running stored procedures and you need to invoke the stored procedures through your LINQ to SQL class. By default the SqlCommand has a timeout value of 30 seconds and in some instances you may need a longer value to complete your long running database operations. In a situation like this, if you are using the default time out value, you may encounter the following exception scenario,

Error: System.Data.SqlClient.SqlException: Timeout expired

Today I was looking for a solution after I encountered the above exception. In my project I am using LINQ to SQL classes to execute my stored procedures which sometimes may exceed the 30 seconds timeout value to complete the operations. I wanted to set the default timeout for my LINQ to SQL DataContext subclass generated by Visual Studio 2008 and wanted a clean approach. I came up with the following solution and think it may help some of you with similar needs.

Firstly, I can set the command timeout in the following way,

MyDataContext context = new MyDataContext();

context.CommandTimeout = 300; //Value in seconds

However, if I do it this way, then I need to do it at every place where I want the timeout value to be changed from the default value of 30 seconds. And I wanted to avoid this annoying approach. Fortunately, the auto generated DataContext subclass provides me a very simple way to get around to this problem through partial methods.

If you take a look into the auto generated DataContext subclass's code, you will notice the presence of the following partial methods at the top-

#region Extensibility Method Definitions
partial void OnCreated();

//Some other partial Methods depending on your db


This OnCreated() method is placed to provide you extensibility with the context constructor logic. Anytime you invoke any one of the constructors of your DataContext subclass, this method is called. However, since this is a partial method without a body, this call has no effect unless I define the body myself!

So, we are going to utilize this method. To do so, we will write another partial class along with this generated partial class (the one at the *.designer.cs file) and implement the partial void OnCreated() method in our newly added partial class where we will set our desired CommandTimeout value.

public partial class MyDataContext : System.Data.Linq.DataContext
partial void OnCreated()
//Set the timeout value to 300 = 5 Min.
base.CommandTimeout = 300;

So, we just set the value of CommandTimeout Property of the base DataContext class with just the addition of this new partial class. Also, we got rid of the annoying 'change everywhere' scenario in this approach. Thanks to the creators of the code generator, who were wise enough to foresee our needs, for providing us with a way to take such a clean approach!

By the way, I was interested to see a handy use of the partial method in C# ever since I first learned about it. I am happy that, I found a real life use myself!

Wednesday, April 16, 2008

string.GetValueOrDefault() - A Simple Extension Method

I have found that, I have written codes like the following one in my projects before now at some places.

string myString = someString == null ? string.Empty : someString;

However, with the advent of extension methods in C# 3.0 (.Net 3.5), I have a better way of achieving this goal in my projects. So, I just wrote an extension method as the following one-

public static class StringExtensions
public static string GetValueOrDefault(this string instance)
return instance == null ? string.Empty : instance;

Well, I have just borrowed the name of the method from the Nullable type and think this name means its purpose to the fullest!

However, with this addition, I can now rewrite my code example as the following one-

string myString = someString.GetValueOrDefault();

Happy coding!

Monday, April 14, 2008

Best of Today's RSS from My Daily Feeds

1. If using LINQ gives you a great feeling, then I suggest you to read this post (to make it feel even better) where you learn about a less used keyword called 'let' to make your LINQ queries more readable and human friendly.


Saturday, April 12, 2008

IsNullOrEmpty() - A Handy Extension Method for IEnumerable<T>

Many a time when you are just about to write a foreach loop on your IEnumerable<T> object you need to check whether the object is null or empty in the following manner

if(myEnumerable != null || myEnumerable.Count() > 0)
foreach(<type> item in myEnumerable)

However, with the advent of Extension methods, you can write one custom extension method like the following -

public static class IEnumerableExtensions
public static bool IsNullOrEmpty<T>(this IEnumerable<T> instance) where T : class
return instance == null || instance.Count() == 0;

So, you may write the following code instead of the code example presented earlier -

foreach(<type> item in myEnumerable)
There is simple trick with the Extension Method. That is, extension methods can be invoked even on the objects whose reference is not set to an instance of an object or objects with a null value.
So, its perfectly valid to write -
List<string> myList = null;
Console.WriteLine("myList.IsNullOrEmpty = {0}", myList.IsNullOrEmpty());
because, the IsNullOrEmpty() is an extension method and can be invoked on a null referencing object of its target type.

My Today's best RSS feeds

1. Well, we have a CI in place and we are also very excited to see a new notification message coming to our email inbox on a commit from our team members. CruiseControl.Net really made is fun and so easy to be really continuously integrating our projects.

However, I didn't know of this cool feature until I read this article. I suggest you all CruiseControl.Net cruisers to take a look -


2. Good example of how to use Extension methods to save your efforts when it comes to write custom events and event handlers in your app. I suggest you to read this article for .net 3.5 way to ease in creating events and event handlers -


3. If you are implementing a factory method in your application and not using any dependency injection framework like Spring.Net, Unity you may use this simple code in this link create your light weight object factory easily -


Wednesday, April 09, 2008

Best RSS Feed I have read today

Many a times, if feels great to know about the online users and some more details about them when they are on your website. This article gives you the code example to achieve this in your ASP.Net application.


Tuesday, April 08, 2008

Posts of the day that I liked most

1. The Monostate Pattern - Another way to look into Singleton and some improvement over singleton issues.

Read it Here

2. Another good article on LINQ regarding the grouping queries. Read it Here

Monday, April 07, 2008

Creating Instances of internal classes using Spring.Net

Creating an instance of an internal class using Spring.Net is a little tricky. I know that, you can achieve this by adding an InternalsVisibleTo attribute to your assembly. However, the following solution also works as desired.

Say, you have an namespace named SampleClasses that contains the a public interface named 'IPublicInterface' and also an internal class named 'InternalClass' that implements the IPublicInterface interface and looks like the following -

   1: namespace SampleClasses

   2: {

   3:     public interface IPublicInterface

   4:     {

   5:         string SayHello();

   6:     }

   7: }

   1: internal class InternalClass : IPublicInterface

   2: {


   4:     #region IPublicInterface Members


   6:     public string SayHello()

   7:     {

   8:         return "Hello, World!";

   9:     }


  11:     #endregion

  12: }

And also, you have an xml configuration file named 'SampleClasses.Spring.xml' containing your object definition for InternalClass and looks like the following one -

   1: <objects xmlns="http://www.springframework.net">

   2:   <object id="internalClass"

   3:           type="SampleClasses.InternalClass, SampleClasses"

   4:           >    

   5:   </object>

   6: </objects>

Now, you need to make sure the following are true -

1. 'SampleClasses.Spring.xml is compiled as an embedded resource with the assembly that holds the InternalClass class and also in the same namespace. To ensure this, right click the XML file, select Properties and Select Embedded Resource in the Build Action.

2. In your App.Config (or Web.Config, for web applications), add the following XML declarations to add the embedded XML file -

   1: <configuration>

   2:   <configSections>

   3:   <sectionGroup name="spring">

   4:     <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core, Version=, Culture=neutral, PublicKeyToken=65e474d141e25e07"/>

   5:     <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core, Version=, Culture=neutral, PublicKeyToken=65e474d141e25e07"/>

   6:   </sectionGroup>

   7:   </configSections>


   9:    <spring>

  10:     <!-- Define the context : identify the source from where it gets its resources-->

  11:     <context>

  12:       <resource uri="assembly://SampleClasses/SampleClasses/SampleClasses.Spring.xml"/>      

  13:     </context>

  14:   </spring>

  15: </configuration>

Now, that you have everything ready you can simply write the following code segment to access create an instance of the internal class and hold it through the IPublicInterface as shown below-

   1: string id = "internalClass";            

   2:             IPublicInterface obj = ContextRegistry.GetContext().GetObject(id) as IPublicInterface;

   3:             Console.WriteLine("Hello = {0}", obj.SayHello());

So, you see that its simple way to create an instance of an internal type using Spring.Net given that the internal type is the type of a public Interface. If this assumption is not true, then probably you are not following the best OO designs, where you need to create instances of types that are only supposed to be internal to a namespace.

Wish it helps some of you. Send me a comment if you need the full source code and project.

Logging the LINQ to SQL Generated SQL Queries/Commands

I was looking for logging solutions for the generated SQL in one of my projects where I am using LINQ to SQL. I found that sometimes the the Exceptions and StackTrace information does not say much about what's really causing the problem with LINQ to SQL queries/commands.

To see the actual SQL that's generated from LINQ you may write a code like the following-

  1. SampleDataContext context = new SampleDataContext();
  2. //You may wish to use any subclass of System.IO.TextWriter in place of Console.out
  3. context.Log = Console.Out;
  4. Session session = new Session
  5. {
  6. SessionID = Guid.NewGuid().ToString(),
  7. Site = "Google",
  8. StartTime = DateTime.Now
  9. };
  10. context.Sessions.InsertOnSubmit(session);
  11. context.SubmitChanges();

And when run, a log message like the following will be shown in your console.

INSERT INTO [dbo].[Sessions]([SessionID], [StartTime], [Site], [UserHostAddress]
, [Url], [UserAgent], [UrlReferrer])
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6)
-- @p0: Input VarChar (Size = 36; Prec = 0; Scale = 0) [0522d634-d9e6-43c6-985e-
-- @p1: Input SmallDateTime (Size = 0; Prec = 0; Scale = 0) [4/7/2008 3:28:02 PM
-- @p2: Input VarChar (Size = 6; Prec = 0; Scale = 0) [Google]
-- @p3: Input VarChar (Size = 0; Prec = 0; Scale = 0) [Null]
-- @p4: Input VarChar (Size = 0; Prec = 0; Scale = 0) [Null]
-- @p5: Input VarChar (Size = 0; Prec = 0; Scale = 0) [Null]
-- @p6: Input VarChar (Size = 0; Prec = 0; Scale = 0) [Null]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.21022.8

Well, I know you guys are not just writing Console Applications like me (!) and need something better to be worthy. You may visit the following links for more-

  1. To use Log4Net for capturing the log data, this is a simple yet useful implementation.
  2. As usual, don't forget to take a look at this MSDN page for more on this.

Sunday, April 06, 2008

My First Post Using Windows Live Writer

I came to know about this cool writer very recently and was waiting to take a look at this editor. Now that I am writing a blog entry from this editor, I feel like its really making my life easy.


Well, for a head start, I just hit the print screen button followed by a ctrl-V and this is what you see! It's lot more fun to edit in this editor!

I recommend you all to try this and also let me know if you are using an editor more cool that this :-)