March 2007 - Posts

How to determine time difference in VB.Net

I had to write a utility to calculate the time difference between the time an error log was updated on a file server and the current time. VS.Net exposes some nifty functionality which can be leveraged to do just that. This is a small but useful utility in a programmers day to day life. Please see the code snippet below:

Private myFilePath as String = "c:\MyApp\Error.Log"

If File.Exists(myFilePath) Then

'get the time stamp
Dim dtStartTime As DateTime = File.GetLastWriteTime(myFilePath)
Dim tsEndTime As TimeSpan = DateTime.Today.Now.Subtract(dtStartTime)

If tsEndTime.TotalMinutes >= 15 Then

 'Send an Email out to IT Support
 Dim sRecipient As String = ";"
 Dim sMessageBody As String = "Log has not been updated in more than 15 minutes"

 SendEmail("", sRecipient, "Error with my Program", sMessageBody)
End If

End If

Public Sub SendEmail(ByVal sFromEmailAddress As String, ByVal sToEmailAddress As String, _
                                 ByVal sEmailSubject As String, ByVal sEmailBody As String)

      Dim objMail As New MailMessage

         SmtpMail.SmtpServer.Insert(0, "MY_EXCHANGE_SERVER")

         objMail.From = sFromEmailAddress
         objMail.To = sToEmailAddress
         objMail.Subject = sEmailSubject
         objMail.Body = sEmailBody
         objMail.BodyFormat = MailFormat.Text

         objMail.Fields.Add("", "0")

      Catch ex As Exception
         Throw ex.InnerException
      End Try

   End Sub


Obi Oberoi



Scripting Sql Server - with caution!

Couple days ago, our development team scripted the entire development database (including all the objects i.e. tables, views, stored procs, functions etc.). While this exercise seems trivial enough, a word of caution is warranted here.  We overlooked Table Scripting Options to script indexes and primary keys.  As a result, when we tried to populate our tables, it just took forever. So much so, that it came to a point where the server could not handle the excessive load and literally came to a screeching halt.  To get a better perspective, a couple thousand records took up to 15 mins.  It was only later that we realized the flaw and corrected the problem by assigning a clustered index to the primary key column.  The advantage with using a clustered index is that even the disordered records are displayed in sequence by SQL.  In other words, adding a clustered index to the table physically reorders the data pages, putting them in physical order based on the indexed column. 

A nonclustered index on the other hand is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows. So e.g. for a table which contains a single row is a good candidate for non-clustered index.  Remember, while clustered-indexes enhance performance for large tables, but there is an overhead on the server.


Obi Oberoi


Orcas comes with goodies

Orcas which is slated to be released sometime this year comes with a plethora of new language features and improvements for both C# and VB developers. The CTP version of Orcas was shipped just recently.  Language features like Automatic Properties, Object Initializers, Collection Initializers just to name a few will likely enhance the development experience and increase productivity and take less time to type the code.

New C# Language Feature: Automatic Properties

As a C# developer today, you are probably quite used to writing classes with basic properties like the code-snippet below:

public class Person {

private string _firstName;
        private string 
        private int 
        public string 
FirstName {

get {
return _firstName;
set {
= value;

public string LastName {

get {
return _lastName;
set {
= value;
public int Age {

get {
return _age;
set {
= value;

Note about that.. we aren't actually adding any logic in the getters/setters of our properties - instead we just get/set the value directly to a field.  This begs the question - then why not just use fields instead of properties?  Well - there are a lot of downsides to exposing public fields. Two of the big problems are:

  1. You can't easily databind against fields.
  2. If you expose public fields from your classes you can't later change them to properties (for example: to add validation logic to the setters) without recompiling any assemblies compiled against the old class. 

For example, using automatic properties, the above code can now be re-writen as below:

public class Person {
public string FirstName {
get; set;

public string LastName {
get; set;
public int Age {
get; set;


Or to make it even more concise, you can write as follows:

public class Person {
public string FirstName { get; set; }
public string LastName  { get; set; }        
public int    Age       { get; set; }


New C# and VB Language Feature: Object Initializers

Types within the .NET Framework rely heavily on the use of properties.  When instantiating and using new classes, it is very common to write code like below:

   Person person = new Person();
person.FirstName "Obi";
person.LastName "Oberoi";
person.Age 35;

Have you ever wanted to make this more concise (and maybe fit on one line)?  With the C# and VB "Orcas" compilers you can now take advantage of a great "syntactic sugar" language feature called "object Initializers" that allows you to-do this and re-write the above code like so:

  Person person = new Person { FirstName="Obi", LastName="Oberoi", Age=35 };

The compiler will then automatically generate the appropriate property setter code that preserves the same semantic meaning as the previous (more verbose) code sample above.

In addition to setting simple property values when initializing a type, the object initializer feature allows us to optionally set more complex nested property types.  For example, assume each Person type we defined above also has a property called "Address" of type "Address".  We could then write the below code to create a new "Person" object and set its properties like so:

   Person person = new Person {
Age 35,
= new Address {
"25 Kingsbridge Garden Circle",

New C# and VB Language Feature: Collection Initializers

Object Initializers are great, and make it much easier to concisely add objects to collections.  For example, if you wanted to add three people to a generics-based List collection of type "Person", you could write the below code:

  List<Person> people = new List<Person>();
people.Add( new Person { FirstName "Obi", LastName "Oberoi", Age 35 } );
people.Add( new Person { FirstName "Sia", LastName "Oberoi", Age } );
people.Add( new Person { FirstName "Sunita", LastName "Oberoi", Age 35 } );

Using the new Object Initializer feature alone saved 12 extra lines of code with this sample versus what you'd need to type with the C# 2.0 compiler.

The C# and VB "Orcas" compilers allow us to go even further, though, and also now support "collection initializers" that allow us to avoid having multiple Add statements, and save even further keystrokes:

   List<Person> people = new List<Person> {
new Person { FirstName "Obi", LastName "Oberoi", Age 35 },
new Person { FirstName "Sia", LastName "Oberoi", Age },
new Person { FirstName "Sunita", LastName "Oberoi", Age 35 }

When the compiler encounters the above syntax, it will automatically generate the collection insert code like the previous sample for us.


Obi Oberoi


Top 10 most influential People in the .Net space

Below, please see a list that of top 10 lists most influential people around (i.e. top 10 greatest IT people, etc). This list was compiled by DNR based on the experiences and impressions of fellow colleagues in .NET development. Thus, perhaps it would be more appropriate to rename it "Top 10 Really Influential People in the .NET World for everyday .NET users".  The criteria are as follows: It was mostly rated on the amount of public exposure individuals got and their impact on the .NET community (whether it is awareness raising, teachings or production of tools). So while you may think that purely technical evangelists would flood this list, it was not the case.

1. Anders Hejlsberg - Creator of C# Language

He is what James Gosling is for Java and  Bjarne Stroustrup's for C++. You can read about the C # design process. And now, most recently, Anders gets this nod for his contribution on LINQ (formerly C Omega), something not seen in other strongly typed languages. You will also be able to see Anders in the public eye through Channel 9 videos.

2. Scott Guthrie - One of the creators of ASP.NET and the General Manager, .NET

Pretty obvious choice eh? What is cool is the progressive career path he has taken at Microsoft. This is a guy who rose through the ranks. You have him to thank for not having to do any more new development in classic ASP. And he is another individual that pops up on Channel 9.

3. Charles Petzold - .NET books/publications

Talk about hardcore, this guy even has a windows tattoo. Quality writer who even made a book available for free for veterans entering the .NET world from C/C++. ( He deserves to be on this list for his windows tattoo, his early entry into authoring .NET books (focusing on the windows forms side of things as opposed to ASP.NET) and quality of his work. Does Visual Studio Rot the Mind?

4. Miguel de Icaza - Creator of Mono (Open Source .NET for Unix/Linux)

He deserves to be on the list for for bringing .NET to the Penguin community. While it is questionable whether he should be behind Charles on this list, to the best of my knowledge, he is lacking that Windows tattoo. An interview of his can be read here.

5. Richard Campbell and Carl Franklin - DNR show, DNRtv, blogs and producing HanselMinutes podcast

Yes, they came as a pair. Part of the criteria was based on the impact individuals had on the .NET community through drawing excitement out of the masses. The evangelism and excitement these two draw out of .NET community is impressive. In fact, even if you are not a .NET Developer, you may feel re-energized about your job in the technical field after listening to these guys.  For helping shape the dot net culture today, they certainly deserve to be on the list. I was fortunate enough to attended a talk by Richard Campbell before. Like their show, they make .NET rock.

6. Paul Wilson - WilsonDotNet with WilsonORMapper and other tools

While it is free to use, the source comes at a price of $50, which is really a bargain. He is a technical blogger. He's authored books (ASP.NET Developer's Cookbook) on .NET and contributed to MSDN Libary articles. He came out with Master pages before ASP.NET 2.0 introduced this.He's also got a couple open source projects that he hosts.

7. Dino Esposito - All the Microsoft Press books written and contributions on MSDN

A lot of people coming into the ASP.NET and .NET development world become familiar with this guy's work. Just look at the number of Microsoft Press books he's published and his work on MSDN magazine.

8. Nikhil Kothari - Architect on ASP.NET team

For his informative and really cool blog entries. Although he could probably earn this spot for being an architect on the ASP.NET team. He has had roles on the server controls framework, Ajax Framework and even come up with his own tools: ScriptSharp, Web Development Helper. He was also one of the individuals who helped to bring ASP.NET Web Matrix to fruition (free IDE for web developers). This all happened before the Express Edition of MS tools these days. Apparently, he was also involved with the development of IIS7.

9. Tom Hollander - Patterns & Practices Product Manager

His work on Enterprise Library, etc has led to the continual guidance and aid of .NET Developers. Enterprise Library was certainlly being used at the last workplace. And I was fortunate enough to attend the Microsoft Design for Operations for Developers Workshop. Check out the new "Validation Application Block" from a blog entry of his.

10. Lutz Roeder - Creator of Reflector

One of the most talked about tools when ppl enter the .net community. Although he is involved with Microsoft Expression, he deserves to be on this list simply for coming out with free tools that are the talk of the .NET community

Honorable Mentions:

Mark Anders - Co-creator of ASP.NETand PUM of .NET Framework.

The guys who created CodeProject - Until now with codeplex, this is still a great source (pun intended) for .NET resources.

John Lam - work on RubyCLR and will be joining Microsoft in Jan 2007.

Sean Walker - DotNetNuke, an open source CMS written in VB.NET. Many technical sites (i.e. Vancouver Code Camp - now renamed Vancouver Tech Fest) were set up on this. DNN has also spawned a plethora of book publications for DNN extensions, etc.

Jim Hugunin - Creator of IronPython (which is now moved to CodePlex)

Brad Abrams - Co-author of "Framework Design Guidelines" and frequent technical blogger at

Scott Watermasysk - Creator of .Text and currently works at Telligent Systems, makers of Community Server, which has become an instrumental social networking (blogs, photo galleries, rss feeds, tagging) platform for people to set up. Professional sites from Microsoft (such as and many personal blogs use this.

Rob Conery - Creator of Subsonic

Eric J. Smith – Creator of CodeSmith

Rockford Lhotka - Creator of CSLA.NET

Andrew Lin - Group Program Manager IIS

James Newkirk - Creator of NUnit (yes, there is Team System Unit Testing tool, but this was the free precursor). Also, he was part of the Patterns and Practices team and is now involved with the CodePlex effort.

Soma Somasegar - Corporate Vice President, Developer Division Microsoft, and regular blogger.

(edit: realized that Patrick Dussud started blogging...he should be an honorable mention as one of the founders of the CLR. Always interesting to read about the roots here and here).


Obi Oberoi


Creating a Deployment Package in VS.Net 2003

I'm sure, many of you use 'Click Once Deployment' feature of VS.Net 2005. However, it's not surprising that some projects still require msi files to be created using the traditional 'Setup and Deployment'. So here's how:

  1. Add a Deployment project to the existing project. Make sure to specify the correct folder in the location field. i.e. the folder in which the deployment project is being added. If not sure, click the 'Browse' button and pick the folder.
  2. Set the name as the project name + setup. i.e. MyProjectSetup
  3. Right click on the Deployment Project node and View - File System.
  4. Right click on the Application Folder, Add, Project Output. Select the project name from the Project drop down window.
  5. Highlight the Primary Output, select 'Release.Net' from the configuration and click OK. (This will build and add all the assemblies)
  6. Right click on the Deployment Project node and click 'Properties'.
  7. Click 'Configuration Manager'.
  8. Select 'Release' from Active Solution Configuration drop down window. Check the SetupProject and hit Close.
  9. Highlight 'Application Folder' under the File System on Targe Machine and view its properties or simply press F4 key.
  10. Change the following properties: Always Create - True; Default Location: C:\MyProjectFolder\Programs\MyProjectName\
  11. Build the Setup Project.
  12. Make sure to change to Release mode prior to building the solution.
  13. You are done.


Obi Oberoi