Presentation on coding standards and best programming practices

Challenge:

Luckily, I got sometime to come back on this blog and share something with you!
After getting bit experience, making few mistakes [and obviously learning from them] I thought to write an article on coding standards and best programming practices, I know few of you say there are the lot of articles available on web from big guns on this topic. And I agree with you. But all of them are “document” and I’ve penned down “presentation” which shares the best practices in a lighter way! and obviously “reading document” sounds bit boring and “reading presentation” sounds bit interesting and fun! Thatโ€™s what I think “Coding should be fun!” ๐Ÿ™‚
I had started working on this article, and revised it so many times, got it reviewed from friends, got their feedback and included it in the document. Initially planned to give this presentation to audience in person. But due to one or other reasons this idea didn’t work. PPT was ready and was lying in my folder since so long. Today, I thought that I should share it here. So, It will be available to larger audience.

Solution:

It covers following topics:

  • Naming Conventions and Standards
  • Indentation, spacing and comments
  • Coding Best Practices
  • Database Best Practices
  • ASP.NET Best Practices
  • Exception Handling and Logging
  • Visual Studio IDE Tips and Tricks

You can download it from following links:
C# Coding Standards And Best Programming Practices (PDF)
C# Coding Standards And Best Programming Practices (PPT)
Also you can have a quick look from below and if you find it interesting then only you can download ๐Ÿ™‚
PPT
[scribd id=62747117 key=key-2d4x58u7dizv46r6u1mt mode=list]
PDF
[scribd id=62748045 key=key-9ym8vluqb0fcxwz5ovc mode=slideshow]
Thanks to all of them who provided their invaluable suggestions, feedback, and helped me to proof read this PPT.
Eager to listen your views/suggestions/comments/feedback.
If you really liked it, then please spread it. So, it will be beneficial to everyone!
Happy Coding! ๐Ÿ™‚

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occured because all pooled connections were in use and max pool size was reached.

Challenge:

Have you seen following error?
timeout-expired-the-timeout-period-elapsed-prior-to-obtaining-a-connection-from-the-pool-this-may-have-occured-because-all-pooled-connections-were-in-use-and-max-pool-size-was-reached
Then this post is to solve it!

Solution:

As per the error your code has not closed the opened SqlConnection properly. For example
SqlConnection conn = new SqlConnection(

myConnectionString);
conn.Open();
doSomething(); /*ย  If some error occurs here — Next line will not get called and it will leave connection open */
conn.Close();
Solution:
1.
SqlConnection conn = new SqlConnection(myConnectionString);
try
{
conn.Open();
doSomething(conn);
}
finally
{
conn.Close();ย ย ย  // This line will get called in any case — success/failure
}
So, open your solution in Visual Studio and search in entire solution for all open connections and for all the code implement above suggested solution.
Just a note : If you have written Data Access layer code in code behind file then you are in trouble here. You have to do changes at N number of places. If you would have created separate Data Access layer (Technically Class Library) and Method to do DB operation then your task would have been easy enough!
2) You can raise the connection pool size in the connection string.ย  For example, you can add “Max Pool Size=100” to your connection string to increase the pool size to 100.
Implement above solutions. You should not see any issues any more.
Good to read :
http://blogs.msdn.com/b/tolong/archive/2006/11/21/max-pool-size-was-reached.aspx
Happy DB Access! ๐Ÿ™‚

The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local

Challenge:

I was playing with nice and very useful class TimeZoneInfo in .NET Framework 3.5. Using which we can convert DateTime from SourceTimeZone to DestinationTimeZone by just one line.
[sourcecode language=”csharp”]
<pre>DateTime hwTime = new DateTime(2007, 02, 01, 08, 00, 00);
try
{
TimeZoneInfo hwZone = TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time");
Console.WriteLine("{0} {1} is {2} local time.",
hwTime,
hwZone.IsDaylightSavingTime(hwTime) ? hwZone.DaylightName : hwZone.StandardName,
TimeZoneInfo.ConvertTime(hwTime, hwZone, TimeZoneInfo.Local));
}
catch (TimeZoneNotFoundException)
{
Console.WriteLine("The registry does not define the Hawaiian Standard Time zone.");
}
catch (InvalidTimeZoneException)
{
Console.WriteLine("Registry data on the Hawaiian STandard Time zone has been corrupted.");
}
</pre>
[/sourcecode]
I was playing more with it and suddenly following error popped up when I selected My Source TimeoZone to “(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi” and Destination TimeZone to “(UTC) Dublin, Edinburgh, Lisbon, London”
System.ArgumentException was unhandled
Message=“The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly.ย  For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local.\r\nParameter name: sourceTimeZone”
Source=”System.Core”
ParamName=”sourceTimeZone”
StackTrace:
at System.TimeZoneInfo.ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags)
at System.TimeZoneInfo.ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
at TimeZoneCoverter.Form1.button1_Click(Object sender, EventArgs e) in E:\TestHarness\TimeZoneCoverter\TimeZoneCoverter\Form1.cs:line 69
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at TimeZoneCoverter.Program.Main() in E:\TestHarness\TimeZoneCoverter\TimeZoneCoverter\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:

Solution:

I’ve faced this problem so long back, When I worked on this class for achieving one functionality. But as I haven’t blogged it [Due to deadlines :(] I can’t recall solution easily. But finally I got the solution and without wasting a minute I wrote it down here. So,ย  If in future you/me face this problem we can kill it quickly. So, here you go:
DateTime dateTimeToConvert = new DateTime(dateTimePicker1.Value.Ticks, DateTimeKind.Unspecified);
As shown in above code we’ve provided DateTimeKind to Unspecified. Earlier it as like this:
DateTime dateTimeToConvert = dateTimePicker1.Value; //Error prone code
HTH!
Happy TimeZoneInfo Coding! ๐Ÿ™‚

SharpZipLib is not working When compression is enabled on IIS

Challenge:

Before so many months back I was facing problem related to SharpZipLib. Basically Using SharpZipLib we were zipping a file at runtime and allowing users to save that zipped file at his/her local machine. It works fine on my local box. But when we roll it out on another IIS server it was not working. [General developers problem :)].
When we delved more in to that, then found that another IIS server has been configured for “HTTP Compression“.

Solution:

Okay, so now we were knowing that Issue is due to IIS Server which has HTTP Compression enabled. Unfortunately we can’t disable it as it will affect the performance. So, now we just have one way to make it working which is through code. We tried lot and finally we found a way to do it, it was just one line change in our Response’s ContentType.
Before we see working code, let’s see the code which was having a problem:
[sourcecode languag=”csharp”]
private void DownloadZip(byte[ bufferzip)
{
// Load Zip file
if (bufferzip != null && bufferzip.Length > 0)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.CacheControl = "public";
HttpContext.Current.Response.ContentType = "application/zip"; //This line was causing a problem!
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=\"MyFile.zip\"");
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.BinaryWrite(bufferzip);
HttpContext.Current.Response.End();
}
}
[/sourcecode]
Now, it’s time to see a working code!
[sourcecode languag=”csharp”]
private void DownloadZip(byte[ bufferzip)
{
// Load Zip file
if (bufferzip != null && bufferzip.Length > 0)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.CacheControl = "public";
HttpContext.Current.Response.ContentType = "application/octet-stream"; // This is real Hero!
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=\"MyFile.zip\"");
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.BinaryWrite(bufferzip);
HttpContext.Current.Response.End();
}
}
[/sourcecode]
Now, if you compare the working and non working code you will see the difference. HttpContext.Current.Response.ContentType = “application/zip”; was causing an issue and changing it to HttpContext.Current.Response.ContentType = “application/octet-stream”; solved it!

Reference links:

http://community.sharpdevelop.net/forums/p/10467/28859.aspx#28859
http://www.jlaforums.com/viewtopic.php?t=7295390
http://support.microsoft.com/kb/841120
Happy Coding! ๐Ÿ™‚

What are the differences between .NET 2.0,3.0 & 3.5?

Answer :-

Good Links:
http://dufoli.wordpress.com/2007/09/11/net-framework-11-20-30-35-21/
http://24x7aspnet.blogspot.com/2009/05/difference-between-net-203035-framework.html
In short:
2.0 => framework that shipped with VS 2005 VB 8.0 / C# 2.0
3.0 => same framework as 2.0 + WCF + WPF + WF
3.5 => all the above + LINQ technologies and will ship with the next VS including VB 9.0 and C#
Updated as per Gaurav’s comment.

Generic List Sorting

Generic List has powerful sorting method which too less .Netters are aware of. Today, I would like to show itโ€™s power to you guys!
Here we go..
Suppose, you have a Class called Employee and created collection of employees using Generic List as shown below:
[sourcecode language=”csharp”]
public class Employee
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public Employee(int employeeId, string employeeName)
{
EmployeeID = employeeId;
EmployeeName = employeeName;
}
public override string ToString()
{
return EmployeeID + " :- " + EmployeeName;
}
}
List<Employee> employeeList = new List<Employee>();
employeeList.Add(new Employee(2, "Sachin T"));
employeeList.Add(new Employee(1, "Anil K"));
[/sourcecode]
Now, if you need to sort your employees collection by EmployeeID how will you do it? โ€“ I know i know you will write your logic and do so many things..But hold on how it will be if we can do it in just one line? sounds cool na? Here you go:
[sourcecode language=”csharp”]
Console.WriteLine(">>>>>>>>>>Before Sorting<<<<<<<<<<");
foreach (Employee employee in employeeList)
{
Console.WriteLine(employee.ToString());
}
// Sorting โ€“ Anonymous method
employeeList.Sort(delegate(Employee employee1, Employee employee2)
{ return employee1.EmployeeID.CompareTo(employee2.EmployeeID); });
Console.WriteLine(">>>>>>>>>>After Sorting<<<<<<<<<<");
foreach (Employee employee in employeeList)
{
Console.WriteLine(employee.ToString());
}
/* Output
>>>>>>>>>>Before Sorting<<<<<<<<<<
2 :- Sachin T
1 :- Anil K
>>>>>>>>>>After Sorting<<<<<<<<<<
1 :- Anil K
2 :- Sachin T
Press any key to continue . . .
*/
[/sourcecode]

Links

http://weblogs.asp.net/dwahlin/archive/2007/04/23/The-Power-of-Anonymous-Methods-in-C_2300_.aspx

How to use System.Diagnostics.Stopwatch?

Stopwatch is a good guy provided by MS to accurately measure elapsed time.
[sourcecode language=”csharp”]
System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
// Your Time Consuming Code goes here..
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
[/sourcecode]
Happy Coding! ๐Ÿ™‚

How to get CPU Usage/Memory Usage/Physical Memory

Here are the few functions which will help you out in getting CPU Usage, Memory Usage and Physical Memory Using C#.NET[Proprietor: Yogesh Patel]:
[sourcecode language=”csharp”]
/// <summary>
/// Gets CPU Usage in %
/// </summary>
/// <returns></returns>
private double getCPUUsage()
{
ManagementObject processor = new ManagementObject("Win32_PerfFormattedData_PerfOS_Processor.Name=’_Total’");
processor.Get();
return double.Parse(processor.Properties["PercentProcessorTime"].Value.ToString());
}
/// <summary>
/// Gets memory usage in %
/// </summary>
/// <returns></returns>
private double getMemoryUsage()
{
double memAvailable, memPhysical;
PerformanceCounter pCntr = new PerformanceCounter("Memory", "Available KBytes");
memAvailable = (double) pCntr.NextValue();
memPhysical = getPhysicalMemory();
return (memPhysical – memAvailable) * 100 / memPhysical;
}
/// <summary>
/// Gets total physical memory
/// </summary>
/// <returns></returns>
private double getPhysicalMemory()
{
ObjectQuery winQuery = new ObjectQuery("SELECT * FROM Win32_LogicalMemoryConfiguration");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(winQuery);
double memory = 0;
foreach (ManagementObject item in searcher.Get())
{
memory = double.Parse(item["TotalPhysicalMemory"].ToString());
}
return memory;
}
[/sourcecode]
Please note that on INTERNET there are so many functions available but this is most accurate and perfect. We are using it on our production servers.

Stable Sort with C#

Hi Guys before couple of days only i came to know thatย  the Sort methods used by the .NET collections are unstable. These sort methods, which include System.Array.Sort and System.Collections.Generic.List<T>.Sort, use the Quick Sort algorithm, which is relatively fast but in this case, unstable. However, there may be instances where you require a stable sort, so a custom solution is required. Let me explain you by an example:
Program.CS
[sourcecode language=”csharp”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace GenericSortingDemo
{
class Program
{
static void Main(string[] args)
{
// 19 – May – 1977
Employee empHemang = new Employee(5, "Hemang Shah", DateTime.Parse("05/19/1977"));
// 19 – May – 1987
Employee empDarshak = new Employee(2, "Darshak Shah", DateTime.Parse("05/19/1985"));
// 30 – Jan – 1987
Employee empDevang = new Employee(1, "Devang Udeshi", DateTime.Parse("01/30/1987"));
// 30 – Jan – 1987
Employee empNilesh = new Employee(4, "Nilesh Thakkar", DateTime.Parse("01/30/1987"));
// 19 – Aug – 1987
Employee empKiran = new Employee(3, "Kiran Patil", DateTime.Parse("05/19/1987"));
Console.WriteLine("********************ArrayList***********************");
ArrayList empArrayList = new ArrayList();
empArrayList.Add(empHemang);
empArrayList.Add(empDevang);
empArrayList.Add(empNilesh);
empArrayList.Add(empDarshak);
empArrayList.Add(empKiran);
Console.WriteLine("ArrayList – Before sorting");
foreach (Employee emp in empArrayList)
{
Console.WriteLine(emp.ToString());
}
empArrayList.Sort(new MySorter());
Console.WriteLine(Environment.NewLine);
Console.WriteLine("ArrayList – After sorting");
foreach (Employee emp in empArrayList)
{
Console.WriteLine(emp.ToString());
}
Console.WriteLine(Environment.NewLine);
Console.WriteLine("********************Generics***********************");
// Genercis
List<Employee> lstEmployees = new List<Employee>();
lstEmployees.Add(empHemang);
lstEmployees.Add(empDevang);
lstEmployees.Add(empNilesh);
lstEmployees.Add(empDarshak);
lstEmployees.Add(empKiran);
Console.WriteLine("List<Employee> – Before sorting");
foreach (Employee emp in lstEmployees)
{
Console.WriteLine(emp.ToString());
}
// sort employees in asc order
lstEmployees.Sort(delegate(Employee emp1, Employee emp2)
{ return emp1.EmployeeBirthDate.CompareTo(emp2.EmployeeBirthDate); });
Console.WriteLine(Environment.NewLine);
Console.WriteLine("List<Employee> – After sorting");
foreach (Employee emp in lstEmployees)
{
Console.WriteLine(emp.ToString());
}
}
}
public class Employee
{
public Employee(int employeeID,string employeeName,DateTime employeeBirthDate)
{
EmployeeID = employeeID;
EmployeeName = employeeName;
EmployeeBirthDate = employeeBirthDate;
}
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public DateTime EmployeeBirthDate { get; set; }
public override string ToString()
{
return "Employee ID : " + EmployeeID + " Employee Name : " + EmployeeName + " Employee BirthDate : " + EmployeeBirthDate;
}
}
public class MySorter : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
Employee emp1 = x as Employee;
Employee emp2 = y as Employee;
DateTime dtEmpl = emp1.EmployeeBirthDate;
DateTime dtEmp2 = emp2.EmployeeBirthDate;
int num = dtEmpl.CompareTo(dtEmp2);//by default ascending order
return num;
}
#endregion
}
}
[/sourcecode]

Output

clip_image002
In their original order [Before sorting], Devang (1/30/1987) appears before Nilesh (also 1/30/1987). But because both objects have the same BirthDate, and the List<T>.Sort and Array.Sort method is unstable, the order of equal objects is reversed. Nilesh appears before Devang after sorting.
Q. Why it happens technically?
Ans: The Sort methods used by the .NET collections are unstable. These sort methods, which include System.Array.Sort and System.Collections.Generic.List<T>.Sort, use the Quick Sort algorithm [We all must have learnt in college days ๐Ÿ™‚ DS lectures], which is relatively fast but in this case, unstable. However, there may be instances where you require a stable sort
[Source: http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx], so a custom solution is required. โ€“ And the custom solution is โ€œStable Insertion Sortโ€ โ€“ is the best way to do stable sorting [Source: http://www.csharp411.com/c-stable-sort/]
Happy Stable Sorting!