Blog moved to http://blogs.msdn.com/vipul

Hi,

It has been six months since I joined microsoft. I have moved this blog to a new location. http://blogs.msdn.com/vipul

Please update your bookmarks to the new URL. Link to RSS feed : http://blogs.msdn.com/vipul/rss.xml

 

Posted by Vipul Patel | with no comments

Public readonly string vs. public readonly property

EricGu (Microsoft) has made an excellant post on readonly strings and read-only properties. Check it out

http://blogs.msdn.com/ericgu/archive/2006/03/17/553934.aspx

Posted by Vipul Patel | with no comments

My articles on "Anonymous types" is up

Check out http://www.developer.com/net/csharp/article.php/3589916 for my article on "Anonymous Types", This cool new feature coming in C# 3.0 is surely going to go places.

Codeguru also contains the same article at http://www.codeguru.com/csharp/csharp/cs_misc/designtechniques/article.php/c11551/

Next stop, extension methods.

Guidelines on clean up code

Many a times, we use the catch block inside the try catch block for our clean up code.

Something like

try

{

 // Do something

}

catch

{

    // work failed, clean up code here
}

 

Rather than the above approach of using the catch block, it would be nicer to use the finally block, something like

 

bool workSuccessful = false;

try

{

   // do some work

   workSuccessful = true;

}

finally

{

  if(!workSuccessfull)

  {

    // cleanup code here.

  }

}

 

There is elegance in the latter method and I would certainly recommend that approach, if you cannot use "using". See below for details.

 

PS: Use this approach only if better alternatives are not available. One of the automatic cleanup approaches available with C# is the using construct.

Something like,

using (TextReader tr = new StreamReader("FileName"))

{

  // do my work here.

}

 

The “using” construct automatically clean up the unmanaged resource (TextReader) once the block has completed execution.

In the event that you cannot use "using", the try-finally approach would be the best way.

 

Posted by Vipul Patel | with no comments

When is a static constructor in C# called?

A static constructor is invoked by the first of either of the following conditions:

  • Create an instance of the class.
  • Refer any of the static methods of the class.

Confused ? Read ahead...

Example

class Sample

{

   static Sample()

   {

      Console.WriteLine("static constructor called");

   }

   public static void WriteTime()

   {

            Console.WriteLine("Static method called");

   }

   public static void Main(string[] args)

   {

      Sample.WriteTime(); // call 1

      Sample aNewSample = new Sample(); // call 2

   }

}

In the above example, call to the static method WriteTime first calls the static contructor of the class Sample and then the static method is called.

In your Console.Window , you will see:

Line1: static constructor called

Line2: Static method called

 

If after this, you create an instance of the class, the static contructor is not called, as it is only invoked once per class at its first reference (mentioned above). So, call 2

Sample aNewSample = new Sample(); // call 2

will not invoke the static constructor.

 

On the other hand, if there was no call 1 (call 1 is commented out), the static contructor will be invoked when the first object of Sample class is created (a little before the object is created).

Posted by Vipul Patel | 3 comment(s)
Filed under:

Sql Server 2005 blocking quiz

Check out http://blogs.msdn.com/psheill/archive/2006/02/20/535614.aspx for a fantastic quiz on SQL Server 2005 blocking and verify if you have got your fundamentals right.

Good job, psheill.

Posted by Vipul Patel | 1 comment(s)
Filed under:

Office live site goes live

Office Live (still in beta) website http://officelive.microsoft.com/ went live today.

So what does Office live have for me?

Three categories of services:

1. Microsoft Office Live Basic: Easy to use web site design tool (ala Frontpage online), Free domain name and hosting , 5 personalized email accounts(Office live mail), good data storage and data transfer facilities, and best of all web site traffic analysis and reporting tools, with online support. And all this for free, till the beta period.

Web hosting details:

  • Free hosting
  • 30 MB of Web site storage
  • 10 GB of bandwidth
  • No setup or hidden fees
  • Online customer support
  • Daily backup (data retained for 30 days)

    2. Microsoft Office Live Collaboration: Shared sites(remember Sharepoint), on demand company applications (like shared calenders, Employee directory, expenses, jobs, hiring, Customer management, sales and marketing), and 50 MB of disk space, backed by enhanced data protection.

    3. Microsoft Office Live Essentials: Microsoft Office Live Basic + Sharepoint + 50 email accounts + Microsoft project.. -- Complete tools to manage your business online... One stop solution for all your needs. (Free domain name and hosting, Easy to use web site design tool (ala Frontpage online).

     

    So lets get started.

  • Posted by Vipul Patel | with no comments

    Application which does not create an entry in Add/Remove Programs

    Do you want your application not in appear in Add/Remove Programs list?

    If yes, ARPSYSTEMCOMPONENT property of the Windows Installer SDK helps.

    Setting this property to 1 prevents the installed application to be displayed in the Add/Remove Programs List.

    More information on this key is available at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/msi/setup/arpsystemcomponent.asp

    On a side note, i fyou want a quick access to Add/Remove Programs List, type appwiz.cpl at your Start > Run prompt.

    Posted by Vipul Patel | 7 comment(s)
    Filed under:

    Visual Studio Service Pack WebSite

    Visual Studio.NET Service Packs are due this year, but their site is up already (The site clearly mentions it is still in process)

    http://msdn.microsoft.com/vstudio/support/servicing/default.aspx

  • Visual Studio 2003 Service Pack 1 ships Q2, 2006
  • Visual Studio 2005 Service Pack 1 ships Q3, 2006
  • Posted by Vipul Patel | with no comments

    .NET Tip - Getting logged in user name in ASP.NET web application

    Frequently we desire to autopopulate some fields on our web form with the current logged in username and domain.

    How to get that information?

    Well, User.Identity.Name comes to the rescue.

    Set the text property of the field to User.Identity.Name and it will show the logged-in username prefixed by the domain information

    Want to work for Microsoft? Send me your resume

    I contract with Microsoft through Volt (www.volt.com) and currently there are lot of contract positions available.

    If you are interested to work with the best brains in the world and love developing challenging products used by millions in the world, send me your resume at vipul_d_patel@hotmail.com . These are strictly contract positions.

    US Citizen, Green card or H1 visa required. My company Volt does not sponsor new H1, but will willingly transfer your existing H1.

    Looking forward to receiving your resumes. Just send me your resume and I will try to find a position bets suited to your skills.

    If you have any questions, feel free to send me an email  and I will reply to you as soon as possible.

    Posted by Vipul Patel | with no comments

    Internet Explorer Beta2 now available

    Check it out. http://www.microsoft.com/windows/ie/ie7/default.mspx
    Posted by Vipul Patel | with no comments
    Filed under:

    Visual Studio Tip of the day - Refactoring - Extracting method

    You notice that you have a chuck of code which could easily be transitioned to a new function. How tdo you do that?

    Again, Visual Studio Refactoring menu comes to the rescue.

    Suppose you have the following code in your function

    public void Myfunc()

    {

       Console.WriteLine("a");

       Console.WriteLine("b");

       Console.WriteLine("c");

       // Do some processing here.

       Console.WriteLine("a");

       Console.WriteLine("b");

       Console.WriteLine("c");

    }

     

    We realize that code containing Console.Writeline is replicated. Select one set of the Console.Writeline instructions and right click > Refactor > Extract Method...

    Type the name of the new function you want to create containing the selected lines and Click OK.

    A new method containing the selected lines is created. So your code will look like

    public void Myfunc()

    {

       NewMethod();

       // Do some processing here.

       Console.WriteLine("a");

       Console.WriteLine("b");

       Console.WriteLine("c");

    }

    private static void NewMethod()

    {

       Console.WriteLine("a");

       Console.WriteLine("b");

       Console.WriteLine("c");

    }

     

    Keyboard shortcut: Ctrl R + Ctrl M

    Cavaet: You will have to delete the second set manually as currently VS editor is not smart enough to replace all the occurances of the selected lines. Maybe in the next version we can get that feature.

     

    Posted by Vipul Patel | with no comments
    Filed under: , ,

    Visual Studio Tip of the day - Refactoring - Changing variable names

    Did you mistype a variable/function/property only to realize it in the code review and are frustrated over the time you will need to spend to correct it across the whole source code?

    Visual Studio 2005 has a new feature called refactoring by which you can rename a property/function/variable at one location and the same will be replicated across all the location where the property/function/variable is referenced.

    To do that, select the property/variable/function you desire to rename and right click and select Refactor > Rename. A Rename window will appear and you can select whether you want to preview the reference changes, or you want to change the entity in the comments also.

    Keyboard shortcut: Ctrl R + Ctrl R

     

    Posted by Vipul Patel | with no comments
    Filed under:

    VB gets a LINQ equivalent

    With the release of the LINQ CTP for Visual Basic, VB matches C# tooth and nail (purely from the LINQ perspective)

    CTP version features Intellisense, Dlinq support, support for XML literals,

    Download link: http://msdn.microsoft.com/vbasic/future and http://msdn.microsoft.com/netframework/future/linq/default.aspx

    Posted by Vipul Patel | with no comments
    Filed under: ,

    Is my webservice really a webservice

    How to tell if your webservice is really a webservice which will interact seamlessly with external entities?

    Well, keep the following in mind

    1. Uses WSDL.  A Web Service should expose its service contract using WSDL.  If it can’t give you a WSDL document, it’s probably just XML over HTTP…

    2. Uses SOAP.  All messages sent from and received by the Web Service must use SOAP formatting.  If it’s not using SOAP it’s probably just XML over HTTP…

    3. Uses XSD.  All data types in the SOAP payload must be XSD compliant.  No platform native types are allowed.  If it’s not using XSD it’s probably just XML over HTTP…

    4. Uses XML.  The underlying messages should of course be formatted using XML.

    5. No Arbitrary Binary Data.  The message payload should 7 bit ASCII and should contain no embedded binary blobs.  Any binary data passed over a Web Service should be sent using either SwA, DIME or MTOM (preferably MTOM).

    6. Transport is likely to be HTTP.  Although not a requirement, the majority of Web Services today use HTTP as the transport.  Compliant Web Services should definitely work over HTTP.

    7. Discovery can be through UDDI.  Again although not a requirement, it should be possible to host the Web Service endpoint using UDDI.

    8. Agreed Versions of Specifications.  The versions of the above specifications (WSDL, SOAP, XSD, XML, HTTP, UDDI) should be in line with the latest version of the WS-I Basic Profile (http://www.ws-i.org) – to ensure Web Service compliance between vendors.

    9. Operations should be Document Style.  Operations to/from a Web Service should be Document/Message Style (e.g. SendOrder(order o)).  RPC style should be avoided (e.g. SetOrderLine1(orderId id)).

    10. Should be compliant with WS-*.  Compliant Web Services should be able to accept WS-* payloads and extensions for Security, Reliability and Transactions (although not all stacks today support these yet).

    Source: http://blogs.msdn.com/smguest/archive/2006/01/26/518020.aspx

    Posted by Vipul Patel | with no comments
    Filed under:

    How to: Determining programmatically if DLL is registered

    Here is a C# code snippet to determine if a particular DLL is registered or not.

     

    [DllImport("kernel32")]

    public extern static int LoadLibrary(string lpLibFileName);

     

    [DllImport("kernel32")]

    public extern static bool FreeLibrary(int hLibModule);

     

    public bool IsDllRegistered(string DllName)

    {

          int libId = LoadLibrary(DllName);

          if (libId>0) FreeLibrary(libId);

          return (libId>0);

    }

     

    Source: http://blogs.msdn.com/asanto

    Posted by Vipul Patel | 1 comment(s)
    Filed under: , , ,

    Visual Studio Tip of the day - Format Document

    Time and again we write code and our brackets get out of visual sync, i.e. they no longer appear as a coherent set even though they may be.

     

    In Visual Studio, there is a feature known as Format Document which will align the code systematically.

     

    It can be invoked by the key combination of Ctrl K + Ctrl D

     

    Suppose you code looks like

     

    namespace LogFileCheck

        {

        class Program

            {

            static void Main(string[] args)

            {

                TextReader sr = new StreamReader("mb20051116_05000600_BAYTRARPT03_k.msn.com_w3svc10000.log", Encoding.UTF8);

                TextWriter writesr =

                    new StreamWriter("mb20051116_05000600_BAYTRARPT03_k.msn.com_w3svc10000_csResult.log",

                    false,              Encoding.UTF8);

                while (sr.Peek()

                    != -1)

                                {

                    string line = sr.ReadLine();

                    if (Regex.IsMatch(line, "&di=78") && Regex.IsMatch(line, @"([^,]*,){19}66"))

                        writesr.WriteLine(line);}

     

                    sr.Close();

                writesr.Close();

            }

        }

    }

     

    Press the magic keys Ctrl K + Ctrl D and voila, all your code looks pretty organized as under:

     

    namespace LogFileCheck

    {

        class Program

        {

            static void Main(string[] args)

            {

                TextReader sr = new StreamReader("mb20051116_05000600_BAYTRARPT03_k.msn.com_w3svc10000.log", Encoding.UTF8);

                TextWriter writesr = new StreamWriter("mb20051116_05000600_BAYTRARPT03_k.msn.com_w3svc10000_csResult.log", false, Encoding.UTF8);

                while (sr.Peek() != -1)

                {

                    string line = sr.ReadLine();

                    if (Regex.IsMatch(line, "&di=78") && Regex.IsMatch(line, @"([^,]*,){19}66"))

                        writesr.WriteLine(line);

                }

     

                sr.Close();

                writesr.Close();

            }

        }

    }

     

    Want to format only a small selected section of the dirty code?  Select the area you want to format and press Ctrl K + Ctrl F.

    Posted by Vipul Patel | 1 comment(s)
    Filed under: ,

    Visual Studio 2005 - A Guided Tour

    Want to learn more about Visual Studio 2005.

    MSDN magazine folks have come  up with a new issue dedicated solely to the new IDE.

    Check it out online at http://msdn.microsoft.com/msdnmag/issues/06/00/default.aspx

     

    Posted by Vipul Patel | with no comments
    Filed under: , , ,
    More Posts Next page »