Total Pageviews

Monday, December 10, 2012

Single Responsibility Principle



            In this context a responsibility is considered to be one reason to change. This principle states that if we have 2 reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and on future if we need to make one change we are going to make it in the class which handle it. When we need to make a change in a class having more responsibilities the change might affect the other functionality of the classes. The Single Responsibility Principle is a simple and intuitive principle, but in practice it is sometimes hard to get it right.
Intent
A class should have only one reason to change.
Example
            Let's assume we need an object to keep an email message. We are going to use the IEmail interface from the below sample. At the first sight everything looks just fine. At a closer look we can see that our IEmail interface and Email class have 2 responsibilities (reasons to change). One would be the use of the class in some email protocols such as pop3 or imap. If other protocols must be supported the objects should be serialized in another manner and code should be added to support new protocols. Another one would be for the Content field. Even if content is a string maybe we want in the future to support HTML or other formats.
If we keep only one class, each change for a responsibility might affect the other one:
Ø  Adding a new protocol will create the need to add code for parsing and serializing the content for each type of field.
Ø  Adding a new content type (like html) make us to add code for each protocol implemented.
// single responsibility principle - bad example
interface IEmail {
            public void setSender(String sender);
            public void setReceiver(String receiver);
            public void setContent(String content);
}
class Email implements IEmail {
            public void setSender(String sender) {// set sender; }
            public void setReceiver(String receiver) {// set receiver; }
              public void setContent(String content) {// set content; }
}
We can create a new interface and class called IContent and Content to split the responsibilities. Having only one responsibility for each class give us a more flexible design:
Ø  adding a new protocol causes changes only in the Email class.
Ø  adding a new type of content supported causes changes only in Content class.
// single responsibility principle - good example
interface IEmail {
            public void setSender(String sender);
            public void setReceiver(String receiver);
            public void setContent(IContent content);
}
interface Content {
            public String getAsString(); // used for serialization
}
class Email implements IEmail {
            public void setSender(String sender) {// set sender; }
            public void setReceiver(String receiver) {// set receiver; }
            public void setContent(IContent content) {// set content; }
}
Conclusion
            The Single Responsibility Principle represents a good way of identifying classes during the design phase of an application and it reminds you to think of all the ways a class can evolve. A good separation of responsibilities is done only when the full picture of how the application should work is well understand.

Open Close Principle


          The Open Close Principle states that the design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code. The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged.
Intent
Software entities like classes, modules and functions should be open for extension but closed for modifications.

Open to Extension

New behavior is added in the future

Closed to Modification

Changed to source or binary code are not required
Example
Below is an example which violates the Open Close Principle. It implements a graphic editor which handles the drawing of different shapes. It's obviously that it does not follow the Open Close Principle since the GraphicEditor class has to be modified for every new shape class that has to be added. There are several disadvantages:
•        for each new shape added the unit testing of the GraphicEditor should be redone.
•        when a new type of shape is added the time for adding it will be high since the developer who add it should understand the logic of the GraphicEditor.
•        adding a new shape might affect the existing functionality in an undesired way, even if the new shape works perfectly
// Open-Close Principle - Bad example
 class GraphicEditor {
            public void drawShape(Shape s) {
                        if (s.m_type==1)
                                    drawRectangle(s);
                        else if (s.m_type==2)
                                    drawCircle(s);
            }
            public void drawCircle(Circle r) {....}
            public void drawRectangle(Rectangle r) {....}
 }

 class Shape {
            int m_type;
 }
 class Rectangle extends Shape {
            Rectangle() {
                        super.m_type=1;
            }
 }
 class Circle extends Shape {
            Circle() {
                        super.m_type=2;
            }
 }
// Open-Close Principle - Good example
 class GraphicEditor {
            public void drawShape(Shape s) {
                        s.draw();
            }
 }

 class Shape {
            abstract void draw();
 }

 class Rectangle extends Shape  {
            public void draw() {
                        // draw the rectangle
            }
 }
Conclusion
            Like every principle OCP is only a principle. Making a flexible design involves additional time and effort spent for it and it introduce new level of abstraction increasing the complexity of the code. So this principle should be applied in those area which are most likely to be changed.

Tuesday, December 4, 2012

How Requests Are Processed by the Thread Pool In IIS

On the web server, the .NET Framework maintains a pool of threads that are used to service ASP.NET requests. When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is busy while the request is being processed, and that thread cannot service another request.



This might not be a problem, because the thread pool can be made large enough to accommodate many busy threads. However, the number of threads in the thread pool is limited (the default maximum for .NET 4.5 is 5,000). In large applications with high concurrency of  long-running requests, all available threads might be busy. This condition is known as thread starvation. When this condition is reached, the web server queues requests. If the request queue becomes full, the web server rejects requests with an HTTP 503 status (Server Too Busy). The CLR thread pool has limitations on new thread injections. If concurrency is bursty (that is, your web site can suddenly get a large number of requests) and  all available request threads are busy because of backend calls with  high latency, the limited thread injection rate can make your application respond very poorly.  Additionally, each new thread added to the thread pool has overhead (such as 1 MB of stack memory). A web application  using synchronous methods to service high latency calls where the thread pool grows to the .NET 4.5 default maximum  of 5, 000 threads would consume approximately 5 GB more memory than an application able the service the same requests using asynchronous methods and only 50 threads. When you’re doing asynchronous work, you’re not always using a thread. For example, when you make an asynchronous web service request, ASP.NET will not be using any threads between the async method call and the await.  Using the thread pool to service requests with high latency can lead to a large memory footprint and poor utilization of the server hardware.

Monday, December 3, 2012

Globalization(Do and Don't) In .NET


       String Comparison
Do
 string str1 = "Apple"; string str2 = "Æble"; int result1 = String.Compare(str1, str2, CultureInfo.InvariantCulture,                                                  CompareOptions.IgnoreCase);

Don't
  string str1 = "Apple";
  string str2 = "Æble";
  int result1 = String.Compare(str1, str2);

 Do

   const string input = "interesting";
   bool result =input.Equals("INTERESTING",            StringComparison.InvariantCultureIgnoreCase);

 Don't

    const string input = "interesting";
    bool comparison = input.ToUpper() == "INTERESTING";
               
 Do            
    string newString =     s.ToUpper(CultureInfo.InvariantCulture);

 Don't      

    string newString = s.ToUpper();
    
                String Sorting
 Do
     StringComparer invCmp = StringComparer.InvariantCulture;
     var str=new List<string> {"a", "b", "c"};
     str.Sort(invCmp);

 Don't 

     var str=new List<string> {"a", "b", "c"};
     str.Sort();


Number Formatting
 Do
     int i = 100;
     string res = i.ToString(CultureInfo.InvariantCulture);
     string res2 = Convert.ToString(CultureInfo.InvariantCulture);

 Don't

      int i = 100;
      string res = i.ToString();
      string res2 = Convert.ToString();

  Do

       double number = 123.456;
       string convertToString =    Convert.ToString(number,  CultureInfo.InvariantCulture);
       string numberToString = number.ToString(CultureInfo.InvariantCulture);
       string stringFormat = String.Format(CultureInfo.InvariantCulture, "{0}",          number);
 Don't              
        double number = 123.456;
        string convertToString = Convert.ToString(number);
        string numberToString = number.ToString();
        string stringFormat = String.Format("{0}", number);
                                               
Calendar Differences
Date Formatting

  Do
        string s1 = "10/31/2012";
       DateTime date = DateTime.Parse("10 / 31 /  2012",  CultureInfo . InvariantCulture);     
       
 Don't
        string s1 = "10/31/2012";
        DateTime date = DateTime.Parse("10 / 31 / 2012");

 Do

        string datenew = Convert.ToDateTime("10/31/2012", CultureInfo.InvariantCulture).ToString();           

Don't
        string datenew = Convert.ToDateTime("10/31/2012").ToString();                 
 Do
        DateTime datenew = Convert.ToDateTime("10/31/2012", CultureInfo.InvariantCulture);     
       
 Don't
         DateTime datenew = Convert.ToDateTime("10/31/2012");


Time Formatting

             The easiest and most efficient way of doing time formatting in the .NET world is to take advantage of theDateTime structure that provides methods such as DateTime.ToString and DateTime.Parse. These methods allow you to perform culture-sensitive operations on a DateTime object.
 Do
      string conv = DateTime.Now.ToShortTimeString();
      DateTime newDate = DateTime.Parse(conv, CultureInfo.InvariantCulture);
Don't
      string conv = DateTime.Now.ToShortTimeString();
      DateTime newDate = DateTime.Parse(conv);


Currency Formatting

     Do
      string conv2 = "12,34,56,789.00";
      decimal newd = Convert.ToDecimal(conv2,CultureInfo.InvariantCulture);
    Don't
       string conv2 = "12,34,56,789.00";
       decimal newd = Convert.ToDecimal(conv2);

Read text file using Powershell


Run the following command in powershell. You get the contents from the text file in to the variable $b
$b = get-content -path C:\ValidatorReport\status.txt