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.