Friday, December 09, 2005

C# Coding Standards

Writing C# code is very easy now days. Having few months of experience and you can write a code, which compiles and runs. But developing a good application is not all about writing a code, which compiles and runs. Writing an efficient code or what we call "Production Quality" code requires having some coding standards in place.

These are the two C# coding standards which I liked. I am not saying everyone should use this but can have a look before making C# coding standards for their applications.

The C# coding standard as defined by Philips Medical Systems - Software / SPI

C# Coding Standards and Best Programming Practices On Code Project

Tuesday, October 04, 2005

2005 Nobel Prize for Physics

This years noble prize for Physics have been awarded to Roy J Glauber and John L Hall of USA and Theodor W Hänsch of Germany.

Glauber : Theoretical description of the behaviour of light particles. (quantum theory of optical coherence)

Hall and Hänsch : Laser-based precision spectroscopy, that is, the determination of the colour of the light of atoms and molecules with extreme precision (optical frequency comb technique).

The Nobel Prize in Physics 2005

The Nobel Prize in Physiology or Medicine 2005

Tuesday, August 30, 2005

Setting accessibility for get and set of a Property in c# 2.0

In c# 1.0 there was no way you can set the accessibility qualifiers for get or set inside a property.

C# 2.0 allows you to set different accessibility qualifiers for your get and set of a property. This feature is useful when you want to have different accessibility for your get and set.





public class Employee
{
private string _employeeName;

public string EmployeeName
{
public get { return _employeeName; }
protected set { _employeeName = value; }
}
}



Refrence Chris Breisch

Thursday, August 25, 2005

ASP.NET Articles

More than 100 good articles on ASP.NET are available at ftp online for ASP.NET developers.

Below are few articles, which are helpful in day-to-day programming.

IIS 7.0

  • A First Look at IIS 7.0

  • Componentization and ASP.NET integration are among the many new features coming up in the next version of Internet Information Services.

Visual Studio 2005

  • Customize Sites With Web Parts

  • Customizing site with web parts. The Visual Studio 2005 Toolbox features a tab called WebParts, which includes a dozen Web Part infrastructure controls that make up the Web Part framework.

ASP.NET 2.0

  • The New ASP.NET 2.0 Code-Behind Model

  • The New ASP.NET 2.0 Code-Behind Model.  This article explains the working of new partial classes in ASP.NET 2.0.

  • Manage Users Fast

  • Add a new user to your system using ASP.NET 2.0's rich API for manipulating users and roles.

  • Master pages

  • ASP.NET 2.0's master pages can help you develop consistent Web apps without the additional overhead of include files, user controls, or third-party add-ins.

  • Techniques for managing client state

  • Working with and understanding how client state is used in your app is critical to putting a good design into practice. Examine three techniques for managing client state.

  • Manage Session State

  • Manage Session State on the Server

  • Client-Side Script

  • Add Client-Side Script Code

Web Services


  • Use Custom .NET Collections

  • Create and use .NET custom collection classes to pass containers of data in your Web services projects.

  • Stateful Web services

  • This article illustrates a programming technique that let’s you deliver better-performing, stateful Web services by supporting ASP.NET. I'll also show you how to use Simple Object Access Protocol (SOAP) headers to implement additional features, such as custom authentication and authorization, and create more flexible Web services that send and receive additional data that doesn't map to method arguments.

ASP.NET controls

ASP.NET 2.0 performance


ADO.NET

Please note that you need to register on ftp online to read complete articles.    

Wednesday, August 24, 2005

Cyclomatic Complexity

Cyclomatic Complexity helps to find the complexity of code. Cyclomatic Complexity verification has been added in latest version of FxCop. I found this feature of great help while doing code review with the help of FxCop.

This is good article on Code Review and Complexity by Michael Swanson (Senior Consultant,Microsoft Corporation). This article also explains the advantages of McCabe's Cyclomatic Complexity as:


  • It is very easy to compute
  • Unlike other complexity measurements, it can be computed immediately in the development lifecycle (which makes it Agile-friendly)
  • It provides a good indicator of the ease of code maintenance
  • It can help focus testing efforts
  • It makes it easy to find complex code for formal review




This is a good presentation on Taming the Software
Development Process
by Michael Swanson (Senior Consultant,Microsoft Corporation). This presentation also explains the cyclomatic complexity and its advantages.

Tuesday, August 16, 2005

Rob Caron's Blog

I like and read the articles on "Rob Caron's Blog A Team System Nexus". He has listed a suggested readings for Team Systems which is great.

Rob Caron's Blog A Team System Nexus

Wednesday, August 03, 2005

Microsoft Windows Vista

Microsoft has named its new windows as Vista and they just released its Beta1.
Check out this site for windows vista
Windows Vista .

Monday, July 18, 2005

Using Configuration Files in NUnit

Using configuration file for NUnit is similar to web.config file in ASP.NET web application and application.config for executables.

What will you do when NUnit requires a .DLL assembly and your code has been written to use a configuration file? The answer is that you will create a configuration file for testing using NUnit J.

NUnit creates an instance of the AppDomain for the .DLL you are testing. One of the other things it does is to manually look for an assembly.dll.config file. Thus, if you need configuration options for your application, copy those settings into a .config file for testing. In our example, such a .config file would be MyDll.dll.config, placed in the same directory as the test DLL loaded by NUnit.

Lets say I have a method bool IsNum(string val) in my MyDLL class (MyDll.dll) which takes a string as parameter and if the string is a number is will return true else false.

What I want is that I create generic test using NUnit and different values passed to my IsNum method to test should be read from the config file. The test should be performed as many times as there are test values in my configuration file. So tomorrow if I want to pass a new value to see if my method is working correctly or not I just need to add a new entry in the config file.

This is my sample MyDll.dll.config file:




Place this config file with your test dll.

Now my Test method will look like:

[Test]
public void ValidateNumberTest()
{
NameValueCollection nvc = (NameValueCollection) ConfigurationSettings.GetConfig("ValidateNumberTest");
MyDll d = new MyDll();
string val = "";
for(int i=0;i< nvc.Count;i++)
{
val = nvc.Get(i);
Assert.AreEqual(true,d.IsNum(val));
}
}

I know this sample is not a great one but I think it gives a fair Idea how we can use a configuration file with NUnit.

Tuesday, July 12, 2005

Cracking .NET Assemblies

Today one of my friends send me a link of an article describing how to crack a .NET assembly. I liked this article very much and thought to put that link in my blog :).

http://www.grimes.demon.co.uk/workshops/fusionWSCrackOne.htm

This article describes how to crack and tamper a .NET assembly. It aslo explains the process of strong naming of an assemble and how to crack strong named .NET assemblies.

But the good news is that the approach explained in this article to crack and tamper .NET strong named assemblies does not work in new version of .NET i.e. this has been corrected in new version of .NET.

Tuesday, June 28, 2005

Large Number of DLLs and circular dependencies

I think every one should read this thread on gotDotNet message board about too many DLLs.
http://www.gotdotnet.com/Community/MessageBoard/Thread.aspx?id=301653

"Try grouping things by application type/usage. Keep in mind that there is an issue when creating circular references. If DLL A references DLL B, DLL B can't reference DLL A because it would create a circular dependency. This means that you will want to carefully plan which classes go into which DLL's/class libraries. This is an artifact of assembly metadata. Circular references are possible in code using reflection. ".

Visual Studio does not allow adding circular dependencies if you have all your projects in a single solution and add refrence to projects.

While it's true that circular references should be avoided and indicate questionable design, it should be mentioned that this is not always feasible or possible. Real life can get ugly. I don't have much idea when in real life we will have to use circular dependency. If some one can help me understand and let me know in what circumstances we should allow circular dependencies and what precautions should be taken in these cases it would be a great knowledge for me.

Thursday, June 16, 2005

Linking Code File to more than one project and GlobalAssemblyInfo.cs in VS.NET 2003

Today I downloaded and installed Microsft Enterprise Library and while going through the code I found the GlobalAssemblyInfo.cs file. Two things which were new for me were:

1. GlobalassemblyInfo.cs
2. Linking same GlobalassemblyInfo.cs to all projects in the solution.

I found out that there is a "link File" button hidden under the "open" button when adding an existing item to a project which can be used to share a code file between two projects, or a "Solution Item" in multiple projects.

GlobalAssemblyInfo.cs is used to provide the same versioning information to all dlls. You can delete the attributes from AssemblyInfo.cs and stick these in GlobalAssemblyInfo.cs. Then link this GlobalAssemblyInfo.cs to all projects in the solution.

ASP.NET apps referencing GAC assemblies

This is just an FYI.

Regarding ASP.NET applications referencing GAC assemblies, Visual Studio doesn't (easily) let us reference assemblies from the GAC. We need to point to a copy of the assembly in the filesystem. However at runtime application will look for the assembly in the GAC first, providing it can find a match with the right version/culture/public key token.

Wednesday, June 15, 2005

Tuning ASP.NET thread pool

If your application queues requests with idle CPU, you should tune the thread pool.

1. For applications that serve requests quickly, consider the following settings in the Machine.config file: Set maxconnection to 12 times the number of CPUs.

Set maxIoThreads and maxWorkerThreads to 100.
Set minFreeThreads to 88 times the number of CPUs.
Set minLocalRequestFreeThreads to 76 times the number of CPUs.

2. For applications that experience burst loads (unusually high loads) between lengthy periods of idle time, consider testing your application by increasing the minWorkerThreads and minIOThreads settings.

3. For applications that make long-running calls, consider the following settings in the Machine.config file:
Set maxconnection to 12 times the number of CPUs.
Set maxIoThreads and maxWorkerThreads to 100.

4. Now test the application without changing the default setting for minFreeThreads. If you see high CPU utilization and context switching, test by reducing maxWorkerThreads or increasing minFreeThreads.

5. For ASP.NET applications that use the ASPCOMPAT flag, you should ensure that the total thread count for the worker process does not exceed the following value: 75 + ((maxWorkerThread + maxIoThreads) * #CPUs * 2)

For more information and implementation details, see :

1. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag/html/scalenetchapt17.asp

2. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag/html/scalenetchapt06.asp

Singleton Design Pattern in C# and .NET

Singleton design pattern can be defined as to ensure a class has only one instance, and provide a global point of access to it.

In almost all application there is some requirement to have some piece of code which can be globally accessed and maintain some type of data. There are some instances in object oriented systems to have a single instance of a class or to have a predefined number of instances of a class. For example a class to maintain a global counter.


What is required is some mechanism to control how class instances are created and then ensure that only one gets created at any given time. This would give us exactly the behavior we require and free a client from having to know any class details.


Below is a sample c# code to create a singleton class.

class Singleton
{
public static Singleton Instance()
{
if (_instance == null)
{
_instance = new Singleton();
}

return _instance;
}
protected Singleton() {}
private static Singleton _instance = null;
}

The constructor is protected and that the only public method is the Instance method. In the Instance method, there is a control block (if) that checks to see if the member variable has been initialized, and if not creates a new instance. This lazy initialization in the control block means that the Singleton instance is initialized, or created, only on the first call to the Instance() method. For many applications, this approach works just fine. But, for multithreaded applications, this approach proves to have a potentially hazardous side effect.If two threads manage to enter the control block at the same time, two instances of the member variable could be created. To solve this, we use the lock keywork in C#.

Below is the Sample code using lock.

class Singleton
{
public static Singleton Instance() {
if (_instance == null) {
lock (typeof(Singleton)) {
if (_instance == null) {
_instance = new Singleton();
}
}
}
return _instance;
}
protected Singleton() {}
private static Singleton _instance = null;
}

There is still some problem in the above code. Some optimizing compilers can optimize out or reorder the lazy initialization code and reintroduce the thread safety problem. To solve this .NET framework has volatile keyword. Using the volatile keyword on the member variable declaration tells the compiler to not reorder the code and forgo optimization.

Below is the sample code using volatile keyword.

class Singleton
{
public static Singleton Instance() {
if (_instance == null) {
lock (typeof(Singleton)) {
if (_instance == null) {
_instance = new Singleton();
}
}
}
return _instance;
}
protected Singleton() {}
private static volatile Singleton _instance = null;
}

This code takes care of thread safty and compiler re-ordering issues and can be said that is the best way to implement singleton. But although the last example shows a working Singleton class using the .NET Framework and C#, this code can be greatly simplified just by taking better advantage of the .NET Framework itself. The following sample uses .NET, is a minimal Singleton class based loosely on the original GoF pattern, and still gets similar behavior.

Below is the .NET Singleton Example

sealed class Singleton
{
private Singleton() {}
public static readonly Singleton Instance = new Singleton();
}

You might ask about advantages of using lazy initialization and the hazards of multiple threads but if you try to read you can find out that all of the correct behaviors are built into the .NET Framework.

Lazy Initialization:
The Framework, during the JIT process, will initialize the static property when (and only when) any method uses this static property. If the property is not used, then the instance is not created. More precisely, what happens during JIT is that the class gets constructed and loaded when any static member of the class is used by any caller. In this case the result is the same.

Thread-safe initialization:
The Framework internally guarantees thread safety on static type initialization. In other words, in the example above, there is only one instance that would ever be created of the Singleton class.

Adding the sealed class modifier ensures that this class will not be sub-classed.

Below is a sample Singletion Usage

sealed class SingletonCounter {
public static readonly SingletonCounter Instance =
new SingletonCounter();
private long Count = 0;
private SingletonCounter() {}
public long NextValue() {
return ++Count;
}
}

class SingletonClient {
[STAThread]
static void Main() {
for (int i=0; i<20; i++) {
Console.WriteLine("Next singleton value: {0}",
SingletonCounter.Instance.NextValue());
}
}
}

I hope the above example helps you understand singleton design pattern and how c# and .NET makes it easier to implement.

Thanks
Brij

Thursday, June 09, 2005

Microsoft Architecture Resource Center (ARC)

Microsoft has released the Architecture Resource Center (ARC) as a central point for information regarding architecture best practices and prescriptive guidance, etc.

http://www.microsoft.com/architecture/default.aspx?pid=home&abver=E9A00024-3DC1-4B6A-BC20-22716E4D2FEA

Visual Studio .NET Shortcut Keys

This has been valuable for me:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vsintro7/html/vxurfVisualStudio70DefaultShortcutKeys.asp

How to upload a file to FTP through DTS?

To upload file through DTS in SQL server 2000 create a "Execute Process Task" inside a DTS and set win32 properties to "c:\WINNT\system32\ftp.exe" and parameters to "-s:C:\WINNT\Commands.txt".

Through -s command we can pass a file to ftp.exe which executes the commands in the file. Here the name of the file is Commands.txt. The contents of the file will look like this:

open ftpURL
username
password
[cd Folder] -- optional command to change directory
del EmailList.txt -- delete the existing file as put does not replace the existing file
put c:\WINNT\EmailList.txtquit

Tuesday, June 07, 2005

Returning Table from functions in SQL server 2000

There are two ways by which one can return a table data type from a UDF in SQL server 2000. Here we will see the examples of both methods.

Returning a table variable.

This example loops through a comma seperated list of values passed to it and inserts these values in a table variable which is returned.

CREATE FUNCTION dbo.fnGetIDList(@strList VARCHAR(8000))
RETURNS @tblList TABLE ([ID] INT PRIMARY KEY)
AS

BEGIN

DECLARE @intID AS INT DECLARE @CommaPosition INT
SET @intID = 0 IF (RIGHT(@strList, 1) <> ',')
SET @strList = @strList + ','

WHILE LEN(@strList) <> 0
BEGIN
SET @CommaPosition = CHARINDEX(',', @strList)
SET @intID = SUBSTRING(@strList, 0, @CommaPosition)
SET @strList = SUBSTRING(@strList, @CommaPosition + 1, LEN(@strList) - @CommaPosition + 1)
INSERT @tblList VALUES (@intID)
END
RETURN
END

Returning TABLE data type.
CREATE Function dbo.fnGetUserInfo (@UserName as Varchar(20))
RETURNS TABLE
AS
RETURN
(
select Status,Name,CreateDate,Password from sysUsers where Name=@UserName
)
GO

If you can return the table using a single query, it is better from performance point of view to use the second method.

Monday, June 06, 2005

Table Variables in SQL server 2000

Using table variables instead is always faster than using temp tables in SQL server 2000. Below is a sample create table command to create a table variable.

declare @t table
(OrderID int ,
RequiredDate datetime,
ShippedDate datetime)

If you are using a table variable inside a query i.e. if you are writing a query and doing a join on a table variable its always better to have primary keys and constraints on table variable. Below is a sample how you can add primary keys and constraints to a table variable.

declare @t table
(OrderID int primary key,
RequiredDate datetime not null,
ShippedDate datetime null,
unique (RequiredDate, OrderID))

Thats it for today. In the next post we will see how we can return table datatype from a UDF (user defined funcation) in SQL server 2000.