Pages

Friday, March 26, 2010

Threading and Perception

Today I thought to tell you something on one of the most complex part of .NET Framework I.e. Threading. I was discussing some of the issues with one of our team member on threading today;
from taking inspiration on that conversion; here are the facts of .NET Threading....

.NET Thread object is "ACTUALLY" not created by .NET; its Operating level thread we are just getting a decorated version of that thread. When we talk about Thread; we must remember the thread pool. The thread pool is just a wrapper class of OS Level thread pool which is optimized for faster allocating/deal locating the memory and thread data. While taking back used thread from user application the same class is also responsible to cleared off the data. This is the internal operation; as a user we don't need to care about it.

The second fact is: some of the blogs (NOT MSDN) mentioned that when you write the code something like:

Thread t = new Thread(DoSomething);

Its actually not a part of ThreadPool and its creating new thread; which may be right in a way. But this is not the fully truth. If we believe on the blog for an instance; we may not get duplicate thread ever. Now here i am no going in depth of Allocation thread memory, execution etc. but let me tell you one point; even if you write above statement in .NET; it serves the thread object from Pool only. I know you will not believe this fact.

I have created an example which works on above assumption have a look once.. its interesting to see. I am creating thread using above code and some times i am getting new thread (Displayed in White Font) and some times i get duplicate thread (Displayed in Yellow Font). It proves that internally .NET is keeping a pool of thread.

The second point; In example;I have also set some data on fresh thread each time. Which I am trying to recover when I get the duplicate thread object. And look at the result; The Thread Slot is still there; but .NET erased the data.

In summery you can say that:

1. Thread object never created/destroyed from .NET Managed Env. user always gets the thread object from pool only.
2. The data you associates with thread (In terms of Thread Slots and ThreadStatic variables) are not persisted on the thread when .NET collects the unused thread for pooling.

When Thread Slots are getting cleared off; there is no question to persist the value of ThreadStatic variables.

Now talking about WCF execution; like this example when you open the WCF Service Channel/Port; it takes one of the available thread from same pool and starts the execution of the code using the thread. You can never get the older data associated with associated with thread earlier. So its perfectly safe to use ThreadStatic variables.

This was about console application; lets take ASP.NET application in consideration. .NET takes thread from ThreadPool to execute the request. This thread is persisted in ThreadPool even though the values of ThreadStatic variables are not getting persisted.

Check-out my ASP.NET example and observe thread static behavior in PageLoad method.


In short; make the best use of ThreadStatic without any fear.

Thursday, March 25, 2010

Google says Good Bye to China

Google has executed its first step towards closer of their China Operations (Google Search, Google News and Google Images mainly).

Users visiting Google.cn are now being redirected to Google.com.hk, where google offers uncensored search in simplified Chinese, specifically designed for users in mainland China and delivered via our servers in Hong Kong.

Google.cn is now Google.com.hk


--
Kaushal Patel

Tuesday, March 09, 2010

Playing with Generic List

Generic List a new feature provided by .NET 2.0 and above which can be declared as follow: List<string> lstString = new List<string>();
Creating Generic Object using Reflection
Now; there is nothing now in this. And we all know that the generics are type safe. That means you can not pass Child object's referece (Without type casting) where the base class is expected. In case if you need to create Generic List object dynamically depending upon your business scenarios you can use Reflection API to create generic object.

Lets see how to do this:

public static object CreateGenericObject(Type genericType, Type innerType, params object[] args)

{

System.Type speType = genericType.MakeGenericType(new System.Type[] { innerType });

return Activator.CreateInstance(speType, args);

}


And your client code would be as follows:


object geneticListObject = CreateGenericObject(typeof(List<>),typeof(int));


Now lets see one more feature of .NET 2.0 i.e. Inline functions (anonymous methods):


Lets assume you have a generic collection of objects (lets assume student); and you want to search on Student Name starting with "K". You dont need to make another call to the server for this. Here is the code for the same:


List<Student> localStudentList = mainStudentList.FindAll(delegate(Student student)
{
return student.StudentName.StartsWith("K");
});


the above code will return the list of students (in localStudentList object) whose name starts with K.To extends this you can write various AND and OR conditions. Isn't this good?



--
Kaushal Patel
Contact Me Twitter


Wednesday, March 03, 2010

BCL new features of the .NET Framework 4.0 Beta 2

Visual Studio 2010 and .NET Framework 4 Beta 2 are now available to download. .NET 4 Beta 2 contains various newly introduced BCL features and enhancements in addition to what was included in the earlier version of .NET Framework 4.0 Beta 1. Many of these enhancements were added in large part due to specific feedback and suggestions reported by customers through Microsoft Connect.

New BCL Features in .NET Framework Beta 2.0

  1. Complex Number
  2. Location
  3. Stream Copy (Stream.CopyTo)
  4. IObservable<T>
  5. Enum.HasFlag
  6. String.Connect & String.Join
  7. String.IsNullOrWhiteSpace
  8. TryParse (In Guid, Version and Enum)
  9. Addition Environment.SpecialFolder, Environment.Is64BitProcess and Environment.Is64BitOperatingSystem
  10. Path.Combine with params support
  11. ObservableCollection<T> is now part of System.DLL
  12. Int Pointer operations (IntPtr and UIntPtr Subtraction operators)
  13. StringBuilder.Clear
  14. ServiceInstaller.DelayedAutoStart
  15. StopWatch.Restart


-- Kaushal Patel
Contact Me Twitter

Task Parallel Library Sample is out now!!!

Microsoft .NET Framework 4.0 TPL (Task Parallel Library) sample is out now. This sample has been created in .NET Framework 4.0 Beta 2
Click here to get the newest feature of .NET Framework 4.0

Tuesday, January 26, 2010

Microsoft Blue & Me

Blue&Me is a information & entertainment system that specially designed for Fiat Group cars as a part of Microsoft Auto initiatives and developed in a partnership which was started end of 2004 between Magenti (a Fiat group company) and MSFT. The system is based on modular structure which allows installation and use of uninformed services. The system offers various connectivity options like Bluetooth, USB, Mobile Phones, your personal media player along with hands-free operations allowing you to control all features by voice commands, using speech technology from Nuance Comm With the help of Magneti the system is developed to be compatible with most mobile phones and media players Blue&Me Nav is a next version of the same OS which adds GPS related features.

In india this os and its capabilities are not well known; at the Bologna Motor Show 2009, Fiat presented a new portable navigation unit addition to the Blue&Me system called Blue&Me Map. Exclusive for and to Fiat Professional's light commercial vehicles.

Friday, January 01, 2010

Visual Studio 2010 Beta 2

On the new years eve; microsoft launched its one of the major and popular development studio i.e Visual Studio 2010. Still its early to discuss the features and improvements that VS.NET 2010 provides. But keep watching this space for more on VS.NET 2010 in coming days.

To download VS.NET 2010 with .NET Framework Beta 4.0

Monday, December 28, 2009

Different ways to Implement the Singleton in .NET

Lots of blogs and sites are talking about the ways to implement the singleton in different ways; and surprisingly many of them some times miss the thread safety or the thread sync. According to the "Design Patterns: Elements of Reusable Object-Oriented Software" the implementation of Singleton should be as follow:







The above implementation may work well considering that singleton implementation can be breakable at the first call. In "GetInstance" method we are checking "instance == null" which returns true when 2 requests comes at the same time at the first call. Plus we are not taking the advantage of the .NET language features. Here is the thread safe implementation of Singleton in .NET C# language.






Here you need to watch the usage of volatile (One can consider the implementation of "volatile" exactly opposite of "ThreadStatic" keyword) and static keyword gives the grantee to be thread safe in .NET compilation. (According to Jeffrey Richter).




Wednesday, December 16, 2009

Microsoft Dublin & Velocity

Microsoft Windows Server AppFebric (Dublin and Velocity) is a bundle of integrated technologies which makes easier to develope, extend and manage the web and composite application that runs on IIS.

If you are searching for the Windows Azure platform AppFabric, which helps developers connect apps and services between Windows Azure and on-premises deployments, see the Windows Azure site.

What is Dublin?

Dublin enriches Windows Server to give enhanced hosting and management capabilities for WCF and WF services. Dublin also adds service management extensions to the hosting features of Internet Information Services (IIS) and Windows Activation Service (WAS), and the run-time components and services of the .NET Framework 4. Dublin addresses the challenges of hosting WCF- and WF-based applications by making it easier to deploy, configure, and manage applications.

Typically in Service Oriented Architecture people are building the service for the different operations and exposes these services to the consumer to consume. Since WCF and WF released; the deployment, monitoring and scaling these services never been an easy task. Some times to consuming these service it self a trouble making task. With the help of Dublin we can perform these tasks almost effortless. Dublin can be easily introduced through IIS management console using the Dublin module of Windows Power Shell.

What is Velocity?

Velocity is a highly scalable in-memory caching mechanism using which one can improve the performance of the application with all types of data. For any application one can leverage the Velocity rather then writing new caching schema. Velocity comes with Dublin; the same setup programme installs Velocity and Dublin.


For more details about the architecture details please Click Here!!


Keep watching this space for more technical updates.

Microsoft released Web Platform Installer 2.0

Commonly known as Web PI; a tool that makes user life easier to sync up with the latest updates for the MS products like Internet Information Services (IIS), Visual Web Developer, .NET Framework, SQL Server Express Edition etc. (List goes on and on and on......). The Web PI has Windows Web Application Gallery using which you can users can have pleasant experience whle blogging. It also provides the support for Content Management Activities.
 
 
For downloading Web PI 2.0 Click Here!!
 
For more technical updates and latest technology news keep watching this space,
 

Tuesday, June 30, 2009

All about WCF (Introduction)


Here in my first series of article I will be sharing top to bottom of the WCF (The Indigo).

WCF is the great way to approach large multi-system message based communication. It seamlessly support Transaction Management, Security Implementation, Exception and Fault handling. Concurrency management etc.

Usage of WCF comes with the great amount of flexibilities' to handle. WCF is a framework for services. The user can Create, Configure, Host and consume the services. All the services are mutually agreed on SOAP concept and communicating between WCF based clients.

WCF has mainly two categories of classes:

1. Service Model Class (Handles Service Configurations & Validations).

2. Channel Classes (Handles mode of communication and related functionalities).

Each WCF service can be associated with one ore more service endpoints. One service can be hosted in WCF with different mode of communication channel. Depending upon the usage and target client WCF Service can be configured (I will focus this more on this in my up coming articles).

Configuring endpoints require (A, B & C):

1. Address ('A') = Where?

2. Binder ('B') = How?

3. Contract ('C') = What?

Address: The address means the URL/URI where the service is located. Where is the service located?
Binder:
The mode ofcommunication. How to communicate with the service?
Contract:
The Service. What is my service?

With the XML Based configuration approach OR with the help of coding we can configure the endpoints.

Hosting WCF Service

WCF Service is can be segregated in to two parts normally:

1. Service Contract

2. Service Implementation

Service Contract:
Service Contract is just the collection of functionality that Service will be exposed. In a way you can assume that a Service Contract is just like the interfaces in .NET.

For example

In above example, I have created a sample service with just one operation i.e. MyOperation with one parameter. As you can see i have used Attributes. ServiceContract attributes comes under System.ServiceModel. Including this DLL as in reference list is must for WCF Service Host and WCF Consumer.

You can create multiple operations by using "OperationContract" attribute. By specifying OperationContract attribute means the operation will be available for WCF Service and the WCF client can consume that.

Service Implementation:
As named Service implementation is the implementation bin of WCF Service Contract. You can implement this WCF Service Interface in 'N' number of classes.

For example

In above example I have created "HelloIndigoService" which is implementing our "IHelloIndigoService" service interface.

WCF Service can be self-hosted service but to start with we will see simple .NET consol based hosting mechanism.

Attributes of Service Contract

Using declarative model you can apply different parameters (as per your requirements) on WCF Service Contract:

CallbackContract
User can specify the call-back service that represents opposite service contract in duplex message exchange.

ConfigurationName
User can specify the pre-created configuration name which is/are defined in Application's configuration file.

Example

Name:

Name property is impacting on WSDL generation. With the help of this property user can specify XML Root Tag name of WSDL. Unlike the older messaging mechanisms, WCF provides great deal of control over WSDL generation. I will discuss more about forming the WSDL with OperationContract later in this article.

Example

Namespace:

Namespace is also related with WSDL formation. After you generated the proxy of WCF Service; the given namespace will be appear in WSDL Namespace.

Example

ProtectionLevel:

User needs to use ProtectionLevel according to their service requirements and the operations that service will be exposing. There are three different ProtectinLevels are available.

1. None:

2. Sign: The protected part is signed digitally to ensure the temper less submission of data

3. EncryptAndSign: This will encrypt data before sighed it digitally.

More details on ProtectionLevel : http://msdn.microsoft.com/en-us/library/aa347692.aspx

SessionMode:
Specifying the attribute with "Allowed", "NotAllowed" and "Required". As name says "NotAllowed" will not support Session. The main difference between "Allowed" and "Required" is: "Allowed" will support Session persistent if incoming binding supports. Where as "Required" will throw an error in case binding is not supporting.

Friday, March 13, 2009

ASP.NET Cookieless Session [Pros & Cons]

            

Enter Cookieless Sessions

you don't have to change anything in your ASP.NET application to enable cookieless sessions, just enter sessionState cookieless="true" in your web.config.


Internal Implementation of Cookieless Session in ASP.NET

The implementation of cookieless sessions includes couple of runtime modules:

1.   1. SessionStateModule [A standard session HTTP Module]
 2. Aspnet_filter.dll [Works as an executable]

Once the HTTP Request come at the server, a small piece of Win32 code works as an ISAPI filter. HTTP modules and ISAPI filters are in opinion of the same concept, except that HTTP modules are created by the managed code and require ASP.NET and CLR to trigger and work. Classic ISAPI filters like aspnet_filter.dll are invoked by IIS. Both capture IIS events fired during the processing of the request.

When the first request of a new browser session comes at server to process, the SessionStateModule reads about the cookie support in the web.config file [By default “machine.config” specifies cookie enabled session]. If the “cookieless” attribute of the  section is set to true, the module generates a new session ID, twists the URL by appending the session ID just before the requested page name, and redirects the browser to the newly created URL using the “HTTP 302 command”.

When each request reaches at the IIS boundary—far before it is handed over to ASP.NET—aspnet_filter.dll is given a chance to look at it. If the URL appends a session ID in parentheses, then the session ID is extracted and copied into a request header called AspFilterSessionId. The URL is then rewritten to exactly like the originally requested resource and let go. This time the ASP.NET session state module retrieves the session ID from the request header and proceeds with session-state binding.

The cookieless mechanism works great as long as the URL contains information that can be used to obtain the session ID. As you'll see in a moment, this poses some usage restrictions.

Let's review the pros and cons of cookieless sessions.

Advantages of Cookieless Session

In ASP.NET, session management and forms authentication are the only two system features that use cookies under the hood. With cookieless sessions, you can now deploy stateful applications that work regardless of the user's preferences about cookies. As of ASP.NET 1.x, though, cookies are still required to implement forms authentication. The good news is that in ASP.NET 2.0 forms authentication can optionally work in a cookieless fashion.

Another common reason advanced against cookies is security. This is a point that deserves a bit more attention.

Cookies are inert text files and as such can be replaced or poisoned by hackers, should they gain access to a machine. The real threat lies not much in what cookies can install on your client machine, but in what they can upload to the target site. Cookies are not programs and never run like programs; other software that gets installed on your machine, though, can use the built-in browser support for cookies to do bad things remotely.

Furthermore, cookies are at risk of theft. Once stolen, a cookie that contains valuable and personal information can disclose its contents to malicious hackers and favor other types of Web attacks.

Disadvantages of Cookieless Session

By looking the advantages of cookieless session we should not reach on any conclusion: Considering security aspect, your cookieless sessions are easier to hack in compare. Session Hijacking can act against this approach.

In brief, session hijacking occurs when an attacker gains access to the session state of a particular user. Basically, the attacker steals a valid session ID and uses that to get into the system and snoop into the data. One common way to get a valid session ID is stealing a valid session cookie. That said, if you think that cookieless sessions put your application on the safe side, you're deadly wrong. With cookieless sessions, in fact, the session ID shows up right in the address bar

With cookieless sessions, stealing session IDs is easier than ever.

Using cookieless sessions also raises issues with links. For example, you can't have absolute, fully qualified links in your ASP.NET pages. If you do this, each request that originates from that hyperlink will be considered as part of a new session. Cookieless sessions require that you always use relative URLs, like in ASP.NET postbacks. You can use a fully qualified URL only if you can embed the session ID in it. But how can you do that, since session IDs are generated at run time?

The following code breaks the session:

Click

To use absolute URLs, resort to a little trick that uses the ApplyAppPathModifier method on the HttpResponse class:

    href= >Click

The ApplyAppPathModifier method takes a string representing a URL and returns an absolute URL that embeds session information. For example, this trick is especially useful in situations in which you need to redirect from a HTTP page to an HTTPS page.

 

Google Talk Hacks



You can edit most settings by opening regedit and by selecting HKEY_CURRENT_USER/Software/Google/Google Talk.
Accounts: This one has subkeys for different accounts that has logged in on the your PC. These keys have different values that store the username, password and connection options.
Options: This is the most interesting part of GTalk, where most of the current hacks should be used.


1. HKEY_CURRENT_USER\Software\Google\Google Talk\Options\show_pin If "1", shows a "pin" next to the minimize button that keeps the windows on top of all the other open windows when clicked.

2. HKEY_CURRENT_USER\Software\Google\Google Talk\Options\view_show_taskbutton If "0", hides the taskbar button, and leaves the tray icon only, when the window is shown


3. HKEY_CURRENT_USER\Software\Google\Google Talk\Options\away_inactive If "1", status will be set as Away after the specified number of MINUTES.

4. HKEY_CURRENT_USER\Software\Google\Google Talk\Options\away_screensaver If "1", status will be set as Away after the specified number of MINUTES.

5. HKEY_CURRENT_USER\Software\Google\Google Talk\Options\inactive_minutes Number of inactive MINUTES to become away if auto-away is on.

Use multiple-identities with GTalk:

1. Right-click on the desktop
2. Select New
3. Select Shortcut
4. Paste this into the text box: ("C:\Program Files\Google\Google Talk\googletalk.exe" /nomutex )
5. Click Next and choose a shortcut name like "GTalk New Instance".
Here you go.... try to execute this newly created short-cut and use your alternate GTalk ID.

/nomutex, which allows you to run more than one instance of GT.
/autostart, when Google Talk is run with this parameter, it will check the registry settings to see if it needs to be started or not. If the "Start automatically with Windows" option is unchecked, it won't start.
/forcestart, same as /autostart, but forces it to start no matter what option was set.
/S upgrade, Used when upgrading Google Talk
/register: registers Google Talk in the registry, includig the GMail Compose method.
/checkupdate: check for newer versions
/plaintextauth: uses plain authentication mechanism instead then Google's GAIA mechanism. Used for testing the plain method on Google's servers.
/nogaiaauth: disables GAIA authentication method. The same as above.
/factoryreset: set settings back to default.
/gaiaserver
domain.com: uses a different GAIA server to connect to Google Talk. Used for debug purposes only, there are no other known GAIA servers.
/mailto
emailid@domain.com: send an email with Gmail
/diag: start Google Talk in diagnostic mode
/log: probably has something to do with the diagnostic logging

To add these, open up your GTalk shortcut, and where it says "Target:" add one or more of these inside the quotations, but after the .exe part




Tuesday, September 16, 2008

CX1 (A super comp from Cray) will have Windows HPC Server 2008

Microsoft and Cray on Tuesday took the wraps off a petite supercomputer that runs Windows HPC Server 2008 and, unlike some other supercomputers, doesn't cost more than a Hummer limo.

In fact, Cray's new CX1 supercomputer is priced starting at a relatively cheap $25,000, not bad for an integrated box that weaves together compute, storage, and visualization functions. Cray has designed the CX1 to remove some of the complexity involved with supercomputing that has hindered its adoption, particular in smaller organizations.

Based on 64-bit Windows Server 2008, Windows HPC Server 2008 can scale to thousands of processing cores and features high end management capabilities that span both Windows and Linux platforms. The CX1 uses up to 8 nodes and 16 Intel Xeon processors, with up to 64 gigabytes of memory per node; and also includes up to 4 terabytes of internal storage.

The CX1 is the first Cray supercomputer to use Intel processors, and is also the first fruit from the pact the two companies announced in April to work together on supercomputing systems and technologies over the next few years.

The CX1 is available through Cray's Website and comes with a three-year warranty that includes next-day, on-site Cray-certified support.

Supercomputers help power research in a wide variety of fields, including aerospace, astrophysics, bioinformatics, chemical physics, climate change prediction, medical imaging and the global ATLAS project, which is investigating the forces that govern the universe.


T-Mobile to announce G-Phone late sept.

T-Mobile USA will become the first company in the world to announce a mobile phone based on Google's Android OS at a New York press conference Sept. 23, the New York Times reports, citing T-Mobile.

The handset was manufactured by Taiwan's High Tech Computer (HTC), the Times said. HTC representatives in Taipei declined to comment on the report.

Several other Web sites are also reporting the Sept. 23 event, including Gizmodo, which is displaying what appears to be an announcement from T-Mobile.

HTC has already said it is developing a mobile phone developed around Google's Android  and plans to call the handset "Dream."

The handset maker may end up being first in the world to put out an Android-based mobile phone, but other companies are also developing handsets around Android, including Samsung Electronics.

HTC's Google handset is just over 5-inches long and 3-inches wide, with a keypad underneath the screen that either slides out or swivels out. The aim of the keypad is for easy e-mail, note-taking and writing Web addresses.

Internet navigational controls are situated below the screen on the handset.

Android is an open source software platform that includes an OS and is designed to take advantage of Internet services for mobility. The software could become a potent new rival to Windows Mobile and other handset operating systems. At the launch ceremony early this year, Google announced that over 30 companies had joined the Open Handset Alliance.

Wednesday, August 13, 2008

Microsoft Introduces Zermatt [A Claim-based identity model]

Most developers are not security experts and many feel uncomfortable being given the job of authenticating, authorizing, and personalizing experiences for users. It's not a subject that has been traditionally taught in computer science curriculum, and there's a long history of these features being ignored until late in the software development lifecycle.

It's not surprising nowadays to see a single company with tens or hundreds of web applications and services, many of which have their own private silo for user identities, and most of which are hardwired to use one particular means of authentication. Developers know how tedious it is to build identity support into each application, and IT pros know how expensive it is to manage the resulting set of applications.

One very useful step toward solving the problem has been to centralize user accounts into an enterprise directory. Commonly it's the IT pro that knows the most effective and efficient way to query the directory, but today the task is typically left up to the developer. And in the face of mergers, acquisitions, and partnerships, the developer might be faced with accessing more than one directory, using more than one API.


In the Microsoft .NET Framework, there are lots of different ways of building identity support into an application, and each communication framework treats identity differently, with different object models, different storage models, and so on. Even in ASP.NET, developers can get confused about where they should look for identity: should they look at the HttpContext.User property? What about Thread.CurrentPrincipal?

The rampant use of passwords has lead to a cottage industry for phishers1. And with so many applications doing their own thing, it's difficult for a company to upgrade to stronger authentication techniques.

What is Zermatt All About?

Zermatt is a set of .NET Framework classes; it is a framework for implementing claims-based identity in your applications. By using it, you'll more easily reap the benefits of claims-based systems described in this paper. Zermatt can be used in any web application or web service that uses the .NET Framework version 3.5.

Download : Zermatt Dev. Whitepaper

Thursday, June 12, 2008

WPF Namespace Poster


.NET Coding Guidelines

1. Tabs & Indenting

Avoid tab characters (\0x09) usage in code. 4 Space charactors should be use unsteade.

2 Bracing

Open braces should always be at the beginning of the line after the statement that begins the block. Contents of the brace should be indented by 4 spaces. For example:

if (someCondition)
{
DoSomething();
}
else
{
DoSomethingElse();
}

"case" statements should be indented from the switch statement like this:

switch (someExpression)
{

case 0:
DoSomething();
break;

case 1:
DoSomethingElse();
break;

case 2:
{
int n = 1;
DoAnotherThing(n);
}
break;
}

Braces should never be considered optional. Even for single statement blocks, you should always use braces. This increases code readability and maintainability of your code.

3 Single line statements

Single line statements can have braces that begin and end on the same line.

public class Foo
{
int bar;

public int Bar
{
get { return bar; }
set { bar = value; }
}

}

It is suggested that all control structures (if, while, for, etc.) use braces, but it is not required.

4 Commenting

Comments should be used to describe intention, logical as well as execution flow, algorithmic overview. It would be ideal, if from reading the comments alone, someone other than the author could understand a function's intended behavior and general operation. While there are no minimum comment requirements and certainly some very small routines need no commenting at all, it is hoped that most routines will have comments reflecting the programmer's intent and approach.

Copyright notice

Each file should start with a copyright notice. To avoid errors in doc comment builds, you don't want to use triple-slash doc comments, but using XML makes the comments easy to replace in the future. Final text will vary by product (you should contact legal for the exact text), but should be similar to:

//-----------------------------------------------------------------------
// <copyright file="ContainerControl.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

Documentation Comments

All methods should use XML doc comments. For internal dev comments, the <devdoc> tag should be used.

public class Foo
{

/// <summary>Public stuff about the method</summary>
/// <param name="bar">What a neat parameter!</param>
/// <devdoc>Cool internal stuff!</devdoc>
///
public void MyMethod(int bar) { … }

}

However, it is common that you would want to move the XML documentation to an external file – for that, use the <include> tag.

public class Foo
{

/// <include file='doc\Foo.uex' path='docs/doc[@for="Foo.MyMethod"]/*' />
///
public void MyMethod(int bar) { … }

}

UNDONE§ there is a big doc with all the comment tags we should be using… where is that?

Comment Style

The // (two slashes) style of comment tags should be used in most situations. Where ever possible, place comments above the code instead of beside it. Here are some examples:

// This is required for WebClient to work through the proxy
GlobalProxySelection.Select = new WebProxy("http://itgproxy/");

// Create object to access Internet resources
//
WebClient myClient = new WebClient();

Comments can be placed at the end of a line when space allows:

public class SomethingUseful
{
private int itemHash; // instance member
private static bool hasDoneSomething; // static member
}

5 Spacing

Spaces improve readability by decreasing code density. Here are some guidelines for the use of space characters within code:

  • Do use a single space after a comma between function arguments.
    Right: Console.In.Read(myChar, 0, 1);
    Wrong: Console.In.Read(myChar,0,1);
  • Do not use a space after the parenthesis and function arguments
    Right: CreateFoo(myChar, 0, 1)
    Wrong: CreateFoo( myChar, 0, 1 )
  • Do not use spaces between a function name and parenthesis.
    Right: CreateFoo()
    Wrong: CreateFoo ()
  • Do not use spaces inside brackets.
    Right: x = dataArray[index];
    Wrong: x = dataArray[ index ];
  • Do use a single space before flow control statements
    Right: while (x == y)
    Wrong: while(x==y)
  • Do use a single space before and after comparison operators
    Right: if (x == y)
    Wrong: if (x==y)

6 Naming

Follow all .NET Framework Design Guidelines for both internal and external members. Highlights of these include:

  • Do not use Hungarian notation
  • Do not use a prefix for member variables (_, m_, s_, etc.). If you want to distinguish between local and member variables you should use "this." in C# and "Me." in VB.NET.
  • Do use camelCasing for member variables
  • Do use camelCasing for parameters
  • Do use camelCasing for local variables
  • Do use PascalCasing for function, property, event, and class names
  • Do prefix interfaces names with "I"
  • Do not prefix enums, classes, or delegates with any letter

The reasons to extend the public rules (no Hungarian, no prefix for member variables, etc.) is to produce a consistent source code appearance. In addition a goal is to have clean readable source. Code legibility should be a primary goal.

7 Naming Conventions

Interop Classes

Classes that are there for interop wrappers (DllImport statements) should follow the naming convention below:

  • NativeMethods – No suppress unmanaged code attribute, these are methods that can be used anywhere because a stack walk will be performed.
  • UnsafeNativeMethods – Has suppress unmanaged code attribute. These methods are potentially dangerous and any caller of these methods must do a full security review to ensure that the usage is safe and protected as no stack walk will be performed.
  • SafeNativeMethods – Has suppress unmanaged code attribute. These methods are safe and can be used fairly safely and the caller isn't needed to do full security reviews even though no stack walk will be performed.

class NativeMethods
{
private NativeMethods() {}

[DllImport("user32")]
internal static extern void FormatHardDrive(string driveName);
}

[SuppressUnmanagedCode]
class UnsafeNativeMethods
{
private UnsafeNativeMethods() {}

[DllImport("user32")]
internal static extern void CreateFile(string fileName);
}

[SuppressUnmanagedCode]
class SafeNativeMethods
{
private SafeNativeMethods() {}

[DllImport("user32")]
internal static extern void MessageBox(string text);
}

All interop classes must be private, and all methods must be internal. In addition a private constructor should be provided to prevent instantiation.

8 File Organization

  • Source files should contain only one public type, although multiple internal classes are allowed
  • Source files should be given the name of the public class in the file
  • Directory names should follow the namespace for the class

For example, I would expect to find the public class "System.Windows.Forms.Control" in "System\Windows\Forms\Control.cs"…

  • Classes member should be alphabetized, and grouped into sections (Fields, Constructors, Properties, Events, Methods, Private interface implementations, Nested types)
  • Using statements should be inside the namespace declaration.

namespace MyNamespace
{

using System;

public class MyClass : IFoo
{

// fields
int foo;

// constructors
public MyClass() { … }

// properties
public int Foo { get { … } set { … } }

// events
public event EventHandler FooChanged { add { … } remove { … } }

// methods
void DoSomething() { … }
void FindSomethind() { … }

//private interface implementations
void IFoo.DoSomething() { DoSomething(); }

// nested types
class NestedType { … }

}

}