SOLID Principles

Disclaimer:
The data in this site is for personal use only. It may contain the images,text etc from other site and credits go to their respective sites:
csharpconer
DotnetCurry

Why need for SOLID principles?
The following are the design flaws that cause the damage in software, mostly.
Putting more stress on classes by assigning more responsibilities to them. (A lot of functionality not related to a class.)
Forcing the classes to depend on each other. If classes are dependent on each other (in other words tightly coupled), then a change in one will affect the other.
Spreading duplicate code in the system/application.

Solution
Choosing the correct architecture (in other words MVC, 3-tier, Layered, MVP, MVVP and so on).
Following Design Principles.
Choosing correct Design Patterns to build the software based on its specifications.
Now we go through the Design Principles first and will cover the rest soon.

Intro to SOLID principles

SOLID principles are the design principles that enable us to manage with most of the software design problems. Robert C. Martin compiled these principles in the 1990s. These principles provide us ways to move from tightly coupled code and little encapsulation to the desired results of loosely coupled and encapsulated real needs of a business properly. SOLID is an acronym of the following.

  • S: Single Responsibility Principle (SRP)
  • O: Open closed Principle (OSP)
  • L: Liskov substitution Principle (LSP)
  • I: Interface Segregation Principle (ISP)
  • D: Dependency Inversion Principle (DIP)

    S: Single Responsibility Principle (SRP)

    SRP says “Every software module should have only one reason to change”.
    This means that every class, or similar structure, in your code should have only one job to do. Everything in that class should be related to a single purpose. Our class should not be like a Swiss knife wherein if one of them needs to be changed then the entire tool needs to be altered. It does not mean that your classes should only contain one method or property. There may be many members as long as they relate to the single responsibility.

    The Single Responsibility Principle gives us a good way of identifying classes at the design phase of an application and it makes you think of all the ways a class can change. A good separation of responsibilities is done only when we have the full picture of how the application should work. Let us check this with an example.

 

  1. public class UserService
  2. {
  3.    public void Register(string email, string password)
  4.    {
  5.       if (!ValidateEmail(email))
  6.          throw new ValidationException(“Email is not an email”);
  7.          var user = new User(email, password);
  8.          SendEmail(new MailMessage(“mysite@nowhere.com”, email) { Subject=“HEllo foo” });
  9.    }
  10.    public virtual bool ValidateEmail(string email)
  11.    {
  12.      return email.Contains(“@”);
  13.    }
  14.    public bool SendEmail(MailMessage message)
  15.    {
  16.      _smtpClient.Send(message);
  17.    }
  18. }

It looks fine, but it is not following SRP. The SendEmail and ValidateEmail methods have nothing to do within the UserService class. Let’s refract it.

  1. public class UserService
  2. {
  3.    EmailService _emailService;
  4.    DbContext _dbContext;
  5.    public UserService(EmailService aEmailService, DbContext aDbContext)
  6.    {
  7.       _emailService = aEmailService;
  8.       _dbContext = aDbContext;
  9.    }
  10.    public void Register(string email, string password)
  11.    {
  12.       if (!_emailService.ValidateEmail(email))
  13.          throw new ValidationException(“Email is not an email”);
  14.          var user = new User(email, password);
  15.          _dbContext.Save(user);
  16.          emailService.SendEmail(new MailMessage(“myname@mydomain.com”, email) {Subject=“Hi. How are you!”});
  17.       }
  18.    }
  19.    public class EmailService
  20.    {
  21.       SmtpClient _smtpClient;
  22.    public EmailService(SmtpClient aSmtpClient)
  23.    {
  24.       _smtpClient = aSmtpClient;
  25.    }
  26.    public bool virtual ValidateEmail(string email)
  27.    {
  28.       return email.Contains(“@”);
  29.    }
  30.    public bool SendEmail(MailMessage message)
  31.    {
  32.       _smtpClient.Send(message);
  33.    }
  34. }

O: Open/Closed Principle

The Open/closed Principle says “A software module/class is open for extension and closed for modification”.
Here “Open for extension” means, we need to design our module/class in such a way that the new functionality can be added only when new requirements are generated. “Closed for modification” means we have already developed a class and it has gone through unit testing. We should then not alter it until we find bugs. As it says, a class should be open for extensions, we can use inheritance to do this. Okay, let’s dive into an example.
Suppose we have a Rectangle class with the properties Height and Width.

  1. public class Rectangle{
  2.    public double Height {get;set;}
  3.    public double Wight {get;set; }
  4. }

Our app needs the ability to calculate the total area of a collection of Rectangles. Since we already learned the Single Responsibility Principle (SRP), we don’t need to put the total area calculation code inside the rectangle. So here I created another class for area calculation.

  1. public class AreaCalculator {
  2.    public double TotalArea(Rectangle[] arrRectangles)
  3.    {
  4.       double area;
  5.       foreach(var objRectangle in arrRectangles)
  6.       {
  7.          area += objRectangle.Height * objRectangle.Width;
  8.       }
  9.       return area;
  10.    }
  11. }
    Hey, we did it. We made our app without violating SRP. No issues for now. But can we extend our app so that it could calculate the area of not only Rectangles but also the area of Circles as well? Now we have an issue with the area calculation issue, because the way to do circle area calculation is different. Hmm. Not a big deal. We can change the TotalArea method a bit, so that it can accept an array of objects as an argument. We check the object type in the loop and do area calculation based on the object type.
  12. public class Rectangle{
  13.    public double Height {get;set;}
  14.    public double Wight {get;set; }
  15. }
  16. public class Circle{
  17.    public double Radius {get;set;}
  18. }
  19. public class AreaCalculator
  20. {
  21.    public double TotalArea(object[] arrObjects)
  22.    {
  23.       double area = 0;
  24.       Rectangle objRectangle;
  25.       Circle objCircle;
  26.       foreach(var obj in arrObjects)
  27.       {
  28.          if(obj is Rectangle)
  29.          {
  30.             area += obj.Height * obj.Width;
  31.          }
  32.          else
  33.          {
  34.             objCircle = (Circle)obj;
  35.             area += objCircle.Radius * objCircle.Radius * Math.PI;
  36.          }
  37.       }
  38.       return area;
  39.    }
  40. }
    Wow. We are done with the change. Here we successfully introduced Circle into our app. We can add a Triangle and calculate it’s area by adding one more “if” block in the TotalArea method of AreaCalculator. But every time we introduce a new shape we need to alter the TotalArea method. So the AreaCalculator class is not closed for modification. How can we make our design to avoid this situation? Generally we can do this by referring to abstractions for dependencies, such as interfaces or abstract classes, rather than using concrete classes. Such interfaces can be fixed once developed so the classes that depend upon them can rely upon unchanging abstractions. Functionality can be added by creating new classes that implement the interfaces. So let’s refract our code using an interfacepublic abstract class Shape
    {
       public abstract double Area();
    }
    Inheriting from Shape, the Rectangle and Circle classes now look like this:
  41. public class Rectangle: Shape
  42. {
  43.    public double Height {get;set;}
  44.    public double Width {get;set;}
  45.    public override double Area()
  46.    {
  47.       return Height * Width;
  48.    }
  49. }
  50. public class Circle: Shape
  51. {
  52.    public double Radius {get;set;}
  53.    public override double Area()
  54.    {
  55.       return Radius * Radus * Math.PI;
  56.    }
  57. }
    Every shape contains its area with its own way of calculation functionality and our AreaCalculator class will become simpler than before.
  58. public class AreaCalculator
  59. {
  60.    public double TotalArea(Shape[] arrShapes)
  61.    {
  62.       double area=0;
  63.       foreach(var objShape in arrShapes)
  64.       {
  65.          area += objShape.Area();
  66.       }
  67.       return area;
  68.    }
  69. }
    Now our code is following SRP and OCP both. Whenever you introduce a new shape by deriving from the “Shape” abstract class, you need not change the “AreaCalculator” class. Awesome. Isn’t it?

    L: Liskov Substitution Principle

    The Liskov Substitution Principle (LSP) states that “you should be able to use any derived class instead of a parent class and have it behave in the same manner without modification”. It ensures that a derived class does not affect the behavior of the parent class, in other words that a derived class must be substitutable for its base class.

    This principle is just an extension of the Open Close Principle and it means that we must ensure that new derived classes extend the base classes without changing their behavior. I will explain this with a real world example that violates LSP.

    A father is a doctor whereas his son wants to become a cricketer. So here the son can’t replace his father even though they both belong to the same family hierarchy.

    Now jump into an example to learn how a design can violate LSP. Suppose we need to build an app to manage data using a group of SQL files text. Here we need to write functionality to load and save the text of a group of SQL files in the application directory. So we need a class that manages the load and saves the text of group of SQL files along with the SqlFile Class.

  70. public class SqlFile
  71. {
  72.    public string FilePath {get;set;}
  73.    public string FileText {get;set;}
  74.    public string LoadText()
  75.    {
  76.       /* Code to read text from sql file */
  77.    }
  78.    public string SaveText()
  79.    {
  80.       /* Code to save text into sql file */
  81.    }
  82. }
  83. public class SqlFileManager
  84. {
  85.    public List<SqlFile> lstSqlFiles {get;set}
  86.    public string GetTextFromFiles()
  87.    {
  88.       StringBuilder objStrBuilder = new StringBuilder();
  89.       foreach(var objFile in lstSqlFiles)
  90.       {
  91.          objStrBuilder.Append(objFile.LoadText());
  92.       }
  93.       return objStrBuilder.ToString();
  94.    }
  95.    public void SaveTextIntoFiles()
  96.    {
  97.       foreach(var objFile in lstSqlFiles)
  98.       {
  99.          objFile.SaveText();
  100.       }
  101.    }
  102. }
    OK. We are done with our part. The functionality looks good for now. After some time our lead might tell us that we may have a few read-only files in the application folder, so we need to restrict the flow whenever it tries to do a save on them.OK. We can do that by creating a “ReadOnlySqlFile” class that inherits the “SqlFile” class and we need to alter the SaveTextIntoFiles() method by introducing a condition to prevent calling the SaveText() method on ReadOnlySqlFile instances.
  103. public class SqlFile
  104. {
  105.    public string LoadText()
  106.    {
  107.    /* Code to read text from sql file */
  108.    }
  109.    public void SaveText()
  110.    {
  111.       /* Code to save text into sql file */
  112.    }
  113. }
  114. public class ReadOnlySqlFile: SqlFile
  115. {
  116.    public string FilePath {get;set;}
  117.    public string FileText {get;set;}
  118.    public string LoadText()
  119.    {
  120.       /* Code to read text from sql file */
  121.    }
  122.    public void SaveText()
  123.    {
  124.       /* Throw an exception when app flow tries to do save. */
  125.       throw new IOException(“Can’t Save”);
  126.    }
  127. }
    To avoid an exception we need to modify “SqlFileManager” by adding one condition to the loop.
  128. public class SqlFileManager
  129. {
  130.    public List<SqlFile? lstSqlFiles {get;set}
  131.    public string GetTextFromFiles()
  132.    {
  133.       StringBuilder objStrBuilder = new StringBuilder();
  134.       foreach(var objFile in lstSqlFiles)
  135.       {
  136.          objStrBuilder.Append(objFile.LoadText());
  137.       }
  138.       return objStrBuilder.ToString();
  139.    }
  140.    public void SaveTextIntoFiles()
  141.    {
  142.       foreach(var objFile in lstSqlFiles)
  143.       {
  144.          //Check whether the current file object is read only or not.If yes, skip calling it’s
  145.          // SaveText() method to skip the exception.
  146.          if(! objFile is ReadOnlySqlFile)
  147.          objFile.SaveText();
  148.       }
  149.    }
  150. }
    Here we altered the SaveTextIntoFiles() method in the SqlFileManager class to determine whether or not the instance is of ReadOnlySqlFile to avoid the exception. We can’t use this ReadOnlySqlFile class as a substitute of its parent without altering SqlFileManager code. So we can say that this design is not following LSP. Let’s make this design follow the LSP. Here we will introduce interfaces to make the SqlFileManager class independent from the rest of the blocks.
  151. public interface IReadableSqlFile
  152. {
  153.    string LoadText();
  154. }
  155. public interface IWritableSqlFile
  156. {
  157.    void SaveText();
  158. }
    Now we implement IReadableSqlFile through the ReadOnlySqlFile class that reads only the text from read-only files.
  159. public class ReadOnlySqlFile: IReadableSqlFile
  160. {
  161.    public string FilePath {get;set;}
  162.    public string FileText {get;set;}
  163.    public string LoadText()
  164.    {
  165.       /* Code to read text from sql file */
  166.    }
  167. }
    Here we implement both IWritableSqlFile and IReadableSqlFile in a SqlFile class by which we can read and write files.
  168. public class SqlFile: IWritableSqlFile,IReadableSqlFile
  169. {
  170.    public string FilePath {get;set;}
  171.    public string FileText {get;set;}
  172.    public string LoadText()
  173.    {
  174.       /* Code to read text from sql file */
  175.    }
  176.    public void SaveText()
  177.    {
  178.       /* Code to save text into sql file */
  179.    }
  180. }
    Now the design of the SqlFileManager class becomes like this:
  181. public class SqlFileManager
  182. {
  183.    public string GetTextFromFiles(List<IReadableSqlFile> aLstReadableFiles)
  184.    {
  185.       StringBuilder objStrBuilder = new StringBuilder();
  186.       foreach(var objFile in aLstReadableFiles)
  187.       {
  188.          objStrBuilder.Append(objFile.LoadText());
  189.       }
  190.       return objStrBuilder.ToString();
  191.    }
  192.    public void SaveTextIntoFiles(List<IWritableSqlFile> aLstWritableFiles)
  193.    {
  194.    foreach(var objFile in aLstWritableFiles)
  195.    {
  196.       objFile.SaveText();
  197.    }
  198.    }
  199. }
    Here the GetTextFromFiles() method gets only the list of instances of classes that implement the IReadOnlySqlFile interface. That means the SqlFile and ReadOnlySqlFile class instances. And the SaveTextIntoFiles() method gets only the list instances of the class that implements the IWritableSqlFiles interface, in other words SqlFile instances in this case. Now we can say our design is following the LSP. And we fixed the problem using the Interface segregation principle by (ISP) identifying the abstraction and the responsibility separation method.

    I: Interface Segregation Principle (ISP)

    The Interface Segregation Principle states “that clients should not be forced to implement interfaces they don’t use. Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one sub module.”.

    We can define it in another way. An interface should be more closely related to the code that uses it than code that implements it. So the methods on the interface are defined by which methods the client code needs rather than which methods the class implements. So clients should not be forced to depend upon interfaces that they don’t use.

    Like classes, each interface should have a specific purpose/responsibility (refer to SRP). You shouldn’t be forced to implement an interface when your object doesn’t share that purpose. The larger the interface, the more likely it includes methods that not all implementers can do. That’s the essence of the Interface Segregation Principle. Let’s start with an example that breaks ISP. Suppose we need to build a system for an IT firm that contains roles like TeamLead and Programmer where TeamLead divides a huge task into smaller tasks and assigns them to his/her programmers or can directly work on them.

    Based on specifications, we need to create an interface and a TeamLead class to implement it.

  200. public Interface ILead
  201. {
  202.    void CreateSubTask();
  203.    void AssginTask();
  204.    void WorkOnTask();
  205. }
  206. public class TeamLead : ILead
  207. {
  208.    public void AssignTask()
  209.    {
  210.       //Code to assign a task.
  211.    }
  212.    public void CreateSubTask()
  213.    {
  214.       //Code to create a sub task
  215.    }
  216.    public void WorkOnTask()
  217.    {
  218.       //Code to implement perform assigned task.
  219.    }
  220. }
    OK. The design looks fine for now. Later another role like Manager, who assigns tasks to TeamLead and will not work on the tasks, is introduced into the system. Can we directly implement an ILead interface in the Manager class, like the following?
  221. public class Manager: ILead
  222. {
  223.    public void AssignTask()
  224.    {
  225.       //Code to assign a task.
  226.    }
  227.    public void CreateSubTask()
  228.    {
  229.       //Code to create a sub task.
  230.    }
  231.    public void WorkOnTask()
  232.    {
  233.       throw new Exception(“Manager can’t work on Task”);
  234.    }
  235. }
    Since the Manager can’t work on a task and at the same time no one can assign tasks to the Manager, this WorkOnTask() should not be in the Manager class. But we are implementing this class from the ILead interface, we need to provide a concrete Method. Here we are forcing the Manager class to implement a WorkOnTask() method without a purpose. This is wrong. The design violates ISP. Let’s correct the design.Since we have three roles, 1. Manager, that can only divide and assign the tasks , 2. TeamLead that can divide and assign the tasks and can work on them as well, 3. Programmer that can only work on tasks, we need to divide the responsibilities by segregating the ILead interface. An interface that provides a contract for WorkOnTask().

    1. public interface IProgrammer
    2. {
    3.    void WorkOnTask();
    4. }

    An interface that provides contracts to manage the tasks:

    1. public interface ILead
    2. {
    3.    void AssignTask();
    4.    void CreateSubTask();
    5. }

    Then the implementation becomes:

    1. public class Programmer: IProgrammer
    2. {
    3.    public void WorkOnTask()
    4.    {
    5.       //code to implement to work on the Task.
    6.    }
    7. }
    8. public class Manager: ILead
    9. {
    10.    public void AssignTask()
    11.    {
    12.       //Code to assign a Task
    13.    }
    14.    public void CreateSubTask()
    15.    {
    16.    //Code to create a sub taks from a task.
    17.    }
    18. }

    TeamLead can manage tasks and can work on them if needed. Then the TeamLead class should implement both of the IProgrammer and ILead interfaces.

    1. public class TeamLead: IProgrammer, ILead
    2. {
    3.    public void AssignTask()
    4.    {
    5.       //Code to assign a Task
    6.    }
    7.    public void CreateSubTask()
    8.    {
    9.       //Code to create a sub task from a task.
    10.    }
    11.    public void WorkOnTask()
    12.    {
    13.       //code to implement to work on the Task.
    14.    }
    15. }

    Wow. Here we separated responsibilities/purposes and distributed them on multiple interfaces and provided a good level of abstraction too.

    D: Dependency Inversion Principle

    The Dependency Inversion Principle (DIP) states that high-level modules/classes should not depend on low-level modules/classes. Both should depend upon abstractions. Secondly, abstractions should not depend upon details. Details should depend upon abstractions.

    High-level modules/classes implement business rules or logic in a system (application). Low-level modules/classes deal with more detailed operations; in other words they may deal with writing information to databases or passing messages to the operating system or services.

    A high-level module/class that has dependency on low-level modules/classes or some other class and knows a lot about the other classes it interacts with is said to be tightly coupled. When a class knows explicitly about the design and implementation of another class, it raises the risk that changes to one class will break the other class. So we must keep these high-level and low-level modules/classes loosely coupled as much as we can. To do that, we need to make both of them dependent on abstractions instead of knowing each other. Let’s start with an example.

    Suppose we need to work on an error logging module that logs exception stack traces into a file. Simple, isn’t it? The following are the classes that provide functionality to log a stack trace into a file.

    1. public class FileLogger
    2. {
    3.    public void LogMessage(string aStackTrace)
    4.    {
    5.       //code to log stack trace into a file.
    6.    }
    7. }
    8. public class ExceptionLogger
    9. {
    10.    public void LogIntoFile(Exception aException)
    11.    {
    12.       FileLogger objFileLogger = new FileLogger();
    13.       objFileLogger.LogMessage(GetUserReadableMessage(aException));
    14.    }
    15.    private GetUserReadableMessage(Exception ex)
    16.    {
    17.       string strMessage = string. Empty;
    18.       //code to convert Exception’s stack trace and message to user readable format.
    19.       ….
    20.       ….
    21.       return strMessage;
    22.    }
    23. }

    A client class exports data from many files to a database.

    1. public class DataExporter
    2. {
    3.    public void ExportDataFromFile()
    4.    {
    5.    try {
    6.       //code to export data from files to database.
    7.    }
    8.    catch(Exception ex)
    9.    {
    10.       new ExceptionLogger().LogIntoFile(ex);
    11.    }
    12. }
    13. }

    Looks good. We sent our application to the client. But our client wants to store this stack trace in a database if an IO exception occurs. Hmm… okay, no problem. We can implement that too. Here we need to add one more class that provides the functionality to log the stack trace into the database and an extra method in ExceptionLogger to interact with our new class to log the stack trace.

    1. public class DbLogger
    2. {
    3.    public void LogMessage(string aMessage)
    4.    {
    5.       //Code to write message in database.
    6.    }
    7. }
    8. public class FileLogger
    9. {
    10.    public void LogMessage(string aStackTrace)
    11.    {
    12.       //code to log stack trace into a file.
    13.    }
    14. }
    15. public class ExceptionLogger
    16. {
    17.    public void LogIntoFile(Exception aException)
    18.    {
    19.       FileLogger objFileLogger = new FileLogger();
    20.       objFileLogger.LogMessage(GetUserReadableMessage(aException));
    21.    }
    22.    public void LogIntoDataBase(Exception aException)
    23.    {
    24.       DbLogger objDbLogger = new DbLogger();
    25.       objDbLogger.LogMessage(GetUserReadableMessage(aException));
    26.    }
    27.    private string GetUserReadableMessage(Exception ex)
    28.    {
    29.       string strMessage = string.Empty;
    30.       //code to convert Exception’s stack trace and message to user readable format.
    31.       ….
    32.       ….
    33.       return strMessage;
    34.    }
    35. }
    36. public class DataExporter
    37. {
    38.    public void ExportDataFromFile()
    39.    {
    40.       try {
    41.          //code to export data from files to database.
    42.       }
    43.       catch(IOException ex)
    44.       {
    45.          new ExceptionLogger().LogIntoDataBase(ex);
    46.       }
    47.       catch(Exception ex)
    48.       {
    49.          new ExceptionLogger().LogIntoFile(ex);
    50.       }
    51.    }
    52. }

    Looks fine for now. But whenever the client wants to introduce a new logger, we need to alter ExceptionLogger by adding a new method. If we continue doing this after some time then we will see a fat ExceptionLogger class with a large set of methods that provide the functionality to log a message into various targets. Why does this issue occur? Because ExceptionLogger directly contacts the low-level classes FileLogger and DbLogger to log the exception. We need to alter the design so that this ExceptionLogger class can be loosely coupled with those class. To do that we need to introduce an abstraction between them, so that ExcetpionLogger can contact the abstraction to log the exception instead of depending on the low-level classes directly.

    1. public interface ILogger
    2. {
    3.    void LogMessage(string aString);
    4. }

    Now our low-level classes need to implement this interface.

    1. public class DbLogger: ILogger
    2. {
    3.    public void LogMessage(string aMessage)
    4.    {
    5.       //Code to write message in database.
    6.    }
    7. }
    8. public class FileLogger: ILogger
    9. {
    10.    public void LogMessage(string aStackTrace)
    11.    {
    12.       //code to log stack trace into a file.
    13.    }
    14. }

    Now, we move to the low-level class’s initiation from the ExcetpionLogger class to the DataExporter class to make ExceptionLogger loosely coupled with the low-level classes FileLogger and EventLogger. And by doing that we are giving provision to DataExporter class to decide what kind of Logger should be called based on the exception that occurs.

    1. public class ExceptionLogger
    2. {
    3.    private ILogger _logger;
    4.    public ExceptionLogger(ILogger aLogger)
    5.    {
    6.       this._logger = aLogger;
    7.    }
    8.    public void LogException(Exception aException)
    9.    {
    10.       string strMessage = GetUserReadableMessage(aException);
    11.       this._logger.LogMessage(strMessage);
    12.    }
    13.    private string GetUserReadableMessage(Exception aException)
    14.    {
    15.       string strMessage = string.Empty;
    16.       //code to convert Exception’s stack trace and message to user readable format.
    17.       ….
    18.       ….
    19.       return strMessage;
    20.    }
    21. }
    22. public class DataExporter
    23. {
    24.    public void ExportDataFromFile()
    25.    {
    26.       ExceptionLogger _exceptionLogger;
    27.       try {
    28.          //code to export data from files to database.
    29.       }
    30.       catch(IOException ex)
    31.       {
    32.          _exceptionLogger = new ExceptionLogger(new DbLogger());
    33.          _exceptionLogger.LogException(ex);
    34.       }
    35.       catch(Exception ex)
    36.       {
    37.          _exceptionLogger = new ExceptionLogger(new FileLogger());
    38.          _exceptionLogger.LogException(ex);
    39.       }
    40.    }
    41. }

    We successfully removed the dependency on low-level classes. This ExceptionLogger doesn’t depend on the FileLogger and EventLogger classes to log the stack trace. We don’t need to change the ExceptionLogger’s code any more for any new logging functionality. We need to create a new logging class that implements the ILogger interface and must add another catch block to the DataExporter class’s ExportDataFromFile method.

    1. public class EventLogger: ILogger
    2. {
    3.    public void LogMessage(string aMessage)
    4.    {
    5.       //Code to write message in system’s event viewer.
    6.    }
    7. }

    And we need to add a condition in the DataExporter class as in the following:

    1. public class DataExporter
    2. {
    3.    public void ExportDataFromFile()
    4.    {
    5.       ExceptionLogger _exceptionLogger;
    6.       try {
    7.          //code to export data from files to database.
    8.       }
    9.       catch(IOException ex)
    10.       {
    11.          _exceptionLogger = new ExceptionLogger(new DbLogger());
    12.          _exceptionLogger.LogException(ex);
    13.       }
    14.       catch(SqlException ex)
    15.       {
    16.          _exceptionLogger = new ExceptionLogger(new EventLogger());
    17.          _exceptionLogger.LogException(ex);
    18.       }
    19.       catch(Exception ex)
    20.       {
    21.          _exceptionLogger = new ExceptionLogger(new FileLogger());
    22.          _exceptionLogger.LogException(ex);
    23.       }
    24.    }
    25. }

    Looks good. But we introduced the dependency here in the DataExporter class’s catch blocks. Yeah, someone must take the responsibility to provide the necessary objects to the ExceptionLogger to get the work done.

    Let me explain it with a real world example. Suppose we want to have a wooden chair with specific measurements and the kind of wood to be used to make that chair. Then we can’t leave the decision making on measurements and the wood to the carpenter. Here his job is to make a chair based on our requirements with his tools and we provide the specifications to him to make a good chair.

    So what is the benefit we get by the design? Yes, we definitely have a benefit with it. We need to modify both the DataExporter class and ExceptionLogger class whenever we need to introduce a new logging functionality. But in the updated design we need to add only another catch block for the new exception logging feature. Coupling is not inherently evil. If you don’t have some amount of coupling, your software will not do anything for you. The only thing we need to do is understand the system, requirements and environment properly and find areas where DIP should be followed.

Dependency Injection

What is dependency Injection?

Dependency Injection(DI) means to decouple the objects which are dependent on each other. Say object A is dependent on Object B so the idea is to decouple these object from each other. We don’t need to hard code the object using new keyword rather sharing dependencies to objects at runtime in spite of compile time. If we talk about

How Dependency Injection works in Spring:

We don’t need to hard code the object using new keyword rather define the bean dependency in the configuration file. The spring container will be responsible for hooking up all.

Inversion of Control (IOC)

IOC is a general concept and it can be expressed in many different ways and Dependency Injection is one concrete example of IOC.

Two types of Dependency Injection:

  1. Constructor Injection
  2. Setter Injection

1. Constructor-based dependency injection:

Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.

public class Triangle {

private String type;

public String getType(){
    return type;
 }

public Triangle(String type){   //constructor injection
    this.type=type;
 }
}
<bean id=triangle" class ="com.test.dependencyInjection.Triangle">
        <constructor-arg value="20"/>
  </bean>

2. Setter-based dependency injection:

Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

public class Triangle{

 private String type;

 public String getType(){
    return type;
  }
 public void setType(String type){          //setter injection
    this.type = type;
  }
 }

<!-- setter injection -->
 <bean id="triangle" class="com.test.dependencyInjection.Triangle">
        <property name="type" value="equivialteral"/>

NOTE: It is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. Note that the if we use annotation based than @Required annotation on a setter can be used to make setters as a required dependencies.

—————————————————————————————————

It means that objects should only have as many dependencies as is needed to do their job and the dependencies should be few. Furthermore, an object’s dependencies should be on interfaces and not on “concrete” objects, when possible. (A concrete object is any object created with the keyword new.) Loose coupling promotes greater reusability, easier maintainability, and allows you to easily provide “mock” objects in place of expensive services.

The “Dependency Injection” (DI) is also known as “Inversion of Control” (IoC), can be used as a technique for encouraging this loose coupling.

There are two primary approaches to implementing DI:

  1. Constructor injection
  2. Setter injection

Constructor injection

It’s the technique of passing objects dependencies to its constructor.

Note that the constructor accepts an interface and not concrete object. Also, note that an exception is thrown if the orderDao parameter is null. This emphasizes the importance of receiving a valid dependency. Constructor Injection is, in my opinion, the preferred mechanism for giving an object its dependencies. It is clear to the developer while invoking the object which dependencies need to be given to the “Person” object for proper execution.

Setter Injection

But consider the following example… Suppose you have a class with ten methods that have no dependencies, but you’re adding a new method that does have a dependency on IDAO. You could change the constructor to use Constructor Injection, but this may force you to changes to all constructor calls all over the place. Alternatively, you could just add a new constructor that takes the dependency, but then how does a developer easily know when to use one constructor over the other. Finally, if the dependency is very expensive to create, why should it be created and passed to the constructor when it may only be used rarely? “Setter Injection” is another DI technique that can be used in situations such as this.

Setter Injection does not force dependencies to be passed to the constructor. Instead, the dependencies are set onto public properties exposed by the object in need. As implied previously, the primary motivators for doing this include:

  1. Supporting dependency injection without having to modify the constructor of a legacy class.
  2. Allowing expensive resources or services to be created as late as possible and only when needed.

Here is the example of how the above code would look like:

public class Person {
    public Person() {}

    public IDAO Address {
        set { addressdao = value; }
        get {
            if (addressdao == null)
              throw new MemberAccessException("addressdao" +
                             " has not been initialized");
            return addressdao;
        }
    }

    public Address GetAddress() {
       // ... code that uses the addressdao object
       // to fetch address details from the datasource ...
    }

    // Should not be called directly;
    // use the public property instead
    private IDAO addressdao;

One of the major advantages of dependency injection is that it can make testing lots easier. Suppose you have an object which in its constructor does something like:Basically, instead of having your objects creating a dependency or asking a factory object to make one for them, you pass the needed dependencies in to the constructor or via property setters, and you make it somebody else’s problem (an object further up the dependency graph, or a dependency injector that builds the dependency graph). A dependency as I’m using it here is any other object the current object needs to hold a reference to.

public SomeClass() {
    myObject = Factory.getObject();
}

This can be troublesome when all you want to do is run some unit tests on SomeClass, especially if myObject is something that does complex disk or network access. So now you’re looking at mocking myObject but also somehow intercepting the factory call. Hard. Instead, pass the object in as an argument to the constructor. Now you’ve moved the problem elsewhere, but testing can become lots easier. Just make a dummy myObject and pass that in. The constructor would now look a bit like:

public SomeClass (MyClass myObject) {
    this.myObject = myObject;
}

Most people can probably work out the other problems that might arise when not using dependency injection while testing (like classes that do too much work in their constructors etc.) Most of this is stuff I picked up on the Google Testing Blog, to be perfectly honest…

Dependency Injection is a type of implementation of the “Inversion of Control” principle on which is based Frameworks building.

Frameworks as stated in “Design Pattern” of GoF are classes that implement the main control flow logic raising the developer to do that, in this way Frameworks realize the inversion of control principle.

A way to implement as a technique, and not as class hierarchy, this IoC principle it is just Dependency Injection.

DI consists mainly into delegate the mapping of classes instances and type reference to that instances, to an external “entity”: an object, static class, component, framework, etc…

Classes instances are the “dependencies“, the external binding of the calling component with the class instance through the reference it is the “injection“.

Obviously you can implement this technique in many way as you want from OOP point of view, see for example constructor injection, setter injection, interface injection.

Delegating a third party to carry out the task of match a ref to an object it is very useful when you want to completely separate a component that needs some services from the same services implementation.

In this way, when designing components, you can focus exclusively on their architecture and their specific logic, trusting on interfaces for collaborating with other objects without worry about any type of implementation changes of objects/services used, also if the same object you are using will be totally replaced (obviously respecting the interface).

I found this funny example in terms of loose coupling:

Any application is composed of many objects that collaborate with each other to perform some useful stuff. Traditionally each object is responsible for obtaining its own references to the dependent objects (dependencies) it collaborate with. This leads to highly coupled classes and hard-to-test code.

For example, consider a Car object.

A Car depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the Car object.

Without Dependency Injection (DI):

class Car{
  private Wheel wh= new NepaliRubberWheel();
  private Battery bt= new ExcideBattery();

  //The rest
}

Here, the Car object is responsible for creating the dependent objects.

What if we want to change the type of its dependent object – say Wheel – after the initial NepaliRubberWheel() punctures? We need to recreate the Car object with its new dependency say ChineseRubberWheel(), but only the Car manufacturer can do that.

Then what does the Dependency Injection do us for…?

When using dependency injection, objects are given their dependencies at run time rather than compile time (car manufacturing time). So that we can now change the Wheel whenever we want. Here, the dependency (wheel) can be injected into Car at run time.

After using dependency injection:

Here, we are injecting the dependencies (Wheel and Battery) at runtime. Hence the term : Dependency Injection.

class Car{
  private Wheel wh= [Inject an Instance of Wheel (dependency of car) at runtime]
  private Battery bt= [Inject an Instance of Battery (dependency of car) at runtime]
  Car(Wheel wh,Battery bt) {
      this.wh = wh;
      this.bt = bt;
  }
  //Or we can have setters
  void setWheel(Wheel wh) {
      this.wh = wh;
  }
}

Source: Understanding dependency injection

Credits:
http://stackoverflow.com/questions/130794/what-is-dependency-injection

Singleton Pattern

Sample 1:

Singleton pattern falls under Creational Pattern of Gang of Four (GOF) Design Patterns in .Net. It is pattern is one of the simplest design patterns. This pattern ensures that a class has only one instance. In this article, I would like share what is Singleton pattern and how is it work?

What is Singleton Pattern?

Singleton pattern is one of the simplest design patterns. This pattern ensures that a class has only one instance and provides a global point of access to it.

Singleton Pattern – UML Diagram & Implementation

The UML class diagram for the implementation of the Singleton design pattern is given below:

The classes, and objects in the above UML class diagram are as follows:

  1. Singleton

    This is a class which is responsible for creating and maintaining its own unique instance.

C# – Implementation Code

  1. //eager initialization of singleton
  2. public class Singleton
  3. {
  4. private static Singleton instance = new Singleton();
  5. private Singleton() { }
  6.  
  7. public static Singleton GetInstance
  8. {
  9. get
  10. {
  11. return instance;
  12. }
  13. }
  14. }
  15.  
  16. ////lazy initialization of singleton
  17. public class Singleton
  18. {
  19. private static Singleton instance = null;
  20. private Singleton() { }
  21.  
  22. public static Singleton GetInstance
  23. {
  24. get
  25. {
  26. if (instance == null)
  27. instance = new Singleton();
  28.  
  29. return instance;
  30. }
  31. }
  32. }
  33.  
  34. ////Thread-safe (Double-checked Locking) initialization of singleton
  35. public class Singleton
  36. {
  37. private static Singleton instance = null;
  38. private Singleton() { }
  39. private static object lockThis = new object();
  40.  
  41. public static Singleton GetInstance
  42. {
  43. get
  44. {
  45. lock (lockThis)
  46. {
  47. if (instance == null)
  48. instance = new Singleton();
  49.  
  50. return instance;
  51. }
  52. }
  53. }
  54. }

Singleton Pattern – Example

Who is what?

The classes and objects in the above class diagram can be identified as follows:

  1. Singleton – Singleton class

C# – Sample Code

  1. /// <summary>
  2. /// The ‘Singleton’ class
  3. /// </summary>
  4. public class Singleton
  5. {
  6. // .NET guarantees thread safety for static initialization
  7. private static Singleton instance = null;
  8. private string Name{get;set;}
  9. private string IP{get;set;}
  10. private Singleton()
  11. {
  12. //To DO: Remove below line
  13. Console.WriteLine(“Singleton Intance”);
  14.  
  15. Name = “Server1”;
  16. IP = “192.168.1.23”;
  17. }
  18. // Lock synchronization object
  19. private static object syncLock = new object();
  20.  
  21. public static Singleton Instance
  22. {
  23. get
  24. {
  25. // Support multithreaded applications through
  26. // ‘Double checked locking’ pattern which (once
  27. // the instance exists) avoids locking each
  28. // time the method is invoked
  29. lock (syncLock)
  30. {
  31. if (Singleton.instance == null)
  32. Singleton.instance = new Singleton();
  33.  
  34. return Singleton.instance;
  35. }
  36. }
  37. }
  38.  
  39. public void Show()
  40. {
  41. Console.WriteLine(“Server Information is : Name={0} & IP={1}”, IP, Name);
  42. }
  43.  
  44. }
  45.  
  46. /// <summary>
  47. /// Singleton Pattern Demo
  48. /// </summary>
  49. ///
  50. class Program
  51. {
  52. static void Main(string[] args)
  53. {
  54. Singleton.Instance.Show();
  55. Singleton.Instance.Show();
  56.  
  57. Console.ReadKey();
  58. }
  59. }

Singleton Pattern Demo – Output

When to use it?

  1. Exactly one instance of a class is required.
  2. Controlled access to a single object is necessary.

Sample 2:

Singleton

 


 

Definition

Ensure a class has only one instance and provide a global point of access to it.

 

Frequency of use:
Medium high


 

UML class diagram

 


 

Participants

 

The classes and objects participating in this pattern are:

  • Singleton   (LoadBalancer)
    • defines an Instance operation that lets clients access its unique instance. Instance is a class operation.
    • responsible for creating and maintaining its own unique instance.


 

Structural code in C#

 

This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created.

  1. using System;

  2.  

  3. namespace DoFactory.GangOfFour.Singleton.Structural

  4. {

  5.   /// <summary>

  6.   /// MainApp startup class for Structural

  7.   /// Singleton Design Pattern.

  8.   /// </summary>

  9.   class MainApp

  10.   {

  11.     /// <summary>

  12.     /// Entry point into console application.

  13.     /// </summary>

  14.     static void Main()

  15.     {

  16.       // Constructor is protected — cannot use new

  17.       Singleton s1 = Singleton.Instance();

  18.       Singleton s2 = Singleton.Instance();

  19.  

  20.       // Test for same instance

  21.       if (s1 == s2)

  22.       {

  23.         Console.WriteLine(“Objects are the same instance”);

  24.       }

  25.  

  26.       // Wait for user

  27.       Console.ReadKey();

  28.     }

  29.   }

  30.  

  31.   /// <summary>

  32.   /// The ‘Singleton’ class

  33.   /// </summary>

  34.   class Singleton

  35.   {

  36.     private static Singleton _instance;

  37.  

  38.     // Constructor is ‘protected’

  39.     protected Singleton()

  40.     {

  41.     }

  42.  

  43.     public static Singleton Instance()

  44.     {

  45.       // Uses lazy initialization.

  46.       // Note: this is not thread safe.

  47.       if (_instance == null)

  48.       {

  49.         _instance = new Singleton();

  50.       }

  51.  

  52.       return _instance;

  53.     }

  54.   }

  55. }

  56.  

 

Output
Objects are the same instance


 

Real-world code in C#

 

This real-world code demonstrates the Singleton pattern as a LoadBalancing object. Only a single instance (the singleton) of the class can be created because servers may dynamically come on- or off-line and every request must go throught the one object that has knowledge about the state of the (web) farm.

  1. using System;

  2. using System.Collections.Generic;

  3. using System.Threading;

  4.  

  5. namespace DoFactory.GangOfFour.Singleton.RealWorld

  6. {

  7.   /// <summary>

  8.   /// MainApp startup class for Real-World

  9.   /// Singleton Design Pattern.

  10.   /// </summary>

  11.   class MainApp

  12.   {

  13.     /// <summary>

  14.     /// Entry point into console application.

  15.     /// </summary>

  16.     static void Main()

  17.     {

  18.       LoadBalancer b1 = LoadBalancer.GetLoadBalancer();

  19.       LoadBalancer b2 = LoadBalancer.GetLoadBalancer();

  20.       LoadBalancer b3 = LoadBalancer.GetLoadBalancer();

  21.       LoadBalancer b4 = LoadBalancer.GetLoadBalancer();

  22.  

  23.       // Same instance?

  24.       if (b1 == b2 && b2 == b3 && b3 == b4)

  25.       {

  26.         Console.WriteLine(“Same instance\n”);

  27.       }

  28.  

  29.       // Load balance 15 server requests

  30.       LoadBalancer balancer = LoadBalancer.GetLoadBalancer();

  31.       for (int i = 0; i < 15; i++)

  32.       {

  33.         string server = balancer.Server;

  34.         Console.WriteLine(“Dispatch Request to: “ + server);

  35.       }

  36.  

  37.       // Wait for user

  38.       Console.ReadKey();

  39.     }

  40.   }

  41.  

  42.   /// <summary>

  43.   /// The ‘Singleton’ class

  44.   /// </summary>

  45.   class LoadBalancer

  46.   {

  47.     private static LoadBalancer _instance;

  48.     private List<string> _servers = new List<string>();

  49.     private Random _random = new Random();

  50.  

  51.     // Lock synchronization object

  52.     private static object syncLock = new object();

  53.  

  54.     // Constructor (protected)

  55.     protected LoadBalancer()

  56.     {

  57.       // List of available servers

  58.       _servers.Add(“ServerI”);

  59.       _servers.Add(“ServerII”);

  60.       _servers.Add(“ServerIII”);

  61.       _servers.Add(“ServerIV”);

  62.       _servers.Add(“ServerV”);

  63.     }

  64.  

  65.     public static LoadBalancer GetLoadBalancer()

  66.     {

  67.       // Support multithreaded applications through

  68.       // ‘Double checked locking’ pattern which (once

  69.       // the instance exists) avoids locking each

  70.       // time the method is invoked

  71.       if (_instance == null)

  72.       {

  73.         lock (syncLock)

  74.         {

  75.           if (_instance == null)

  76.           {

  77.             _instance = new LoadBalancer();

  78.           }

  79.         }

  80.       }

  81.  

  82.       return _instance;

  83.     }

  84.  

  85.     // Simple, but effective random load balancer

  86.     public string Server

  87.     {

  88.       get

  89.       {

  90.         int r = _random.Next(_servers.Count);

  91.         return _servers[r].ToString();

  92.       }

  93.     }

  94.   }

  95. }

  96.  

 

Output

Same instance

ServerIII
ServerII
ServerI
ServerII
ServerI
ServerIII
ServerI
ServerIII
ServerIV
ServerII
ServerII
ServerIII
ServerIV
ServerII
ServerIV


 

.NET Optimized code in C#

 

The .NET optimized code demonstrates the same code as above but uses more modern, built-in .NET features.

Here an elegant .NET specific solution is offered. The Singleton pattern simply uses a private constructor and a static readonlyinstance variable that is lazily initialized. Thread safety is guaranteed by the compiler.

  1. using System;

  2. using System.Collections.Generic;

  3.  

  4. namespace DoFactory.GangOfFour.Singleton.NETOptimized

  5. {

  6.   /// <summary>

  7.   /// MainApp startup class for .NET optimized

  8.   /// Singleton Design Pattern.

  9.   /// </summary>

  10.   class MainApp

  11.   {

  12.     /// <summary>

  13.     /// Entry point into console application.

  14.     /// </summary>

  15.     static void Main()

  16.     {

  17.       LoadBalancer b1 = LoadBalancer.GetLoadBalancer();

  18.       LoadBalancer b2 = LoadBalancer.GetLoadBalancer();

  19.       LoadBalancer b3 = LoadBalancer.GetLoadBalancer();

  20.       LoadBalancer b4 = LoadBalancer.GetLoadBalancer();

  21.  

  22.       // Confirm these are the same instance

  23.       if (b1 == b2 && b2 == b3 && b3 == b4)

  24.       {

  25.         Console.WriteLine(“Same instance\n”);

  26.       }

  27.  

  28.       // Next, load balance 15 requests for a server

  29.       LoadBalancer balancer = LoadBalancer.GetLoadBalancer();

  30.       for (int i = 0; i < 15; i++)

  31.       {

  32.         string serverName = balancer.NextServer.Name;

  33.         Console.WriteLine(“Dispatch request to: “ + serverName);

  34.       }

  35.  

  36.       // Wait for user

  37.       Console.ReadKey();

  38.     }

  39.   }

  40.  

  41.   /// <summary>

  42.   /// The ‘Singleton’ class

  43.   /// </summary>

  44.   sealed class LoadBalancer

  45.   {

  46.     // Static members are ‘eagerly initialized’, that is,

  47.     // immediately when class is loaded for the first time.

  48.     // .NET guarantees thread safety for static initialization

  49.     private static readonly LoadBalancer _instance =

  50.       new LoadBalancer();

  51.  

  52.     // Type-safe generic list of servers

  53.     private List<Server> _servers;

  54.     private Random _random = new Random();

  55.  

  56.     // Note: constructor is ‘private’

  57.     private LoadBalancer()

  58.     {

  59.       // Load list of available servers

  60.       _servers = new List<Server>

  61.         {

  62.          new Server{ Name = “ServerI”, IP = “120.14.220.18” },

  63.          new Server{ Name = “ServerII”, IP = “120.14.220.19” },

  64.          new Server{ Name = “ServerIII”, IP = “120.14.220.20” },

  65.          new Server{ Name = “ServerIV”, IP = “120.14.220.21” },

  66.          new Server{ Name = “ServerV”, IP = “120.14.220.22” },

  67.         };

  68.     }

  69.  

  70.     public static LoadBalancer GetLoadBalancer()

  71.     {

  72.       return _instance;

  73.     }

  74.  

  75.     // Simple, but effective load balancer

  76.     public Server NextServer

  77.     {

  78.       get

  79.       {

  80.         int r = _random.Next(_servers.Count);

  81.         return _servers[r];

  82.       }

  83.     }

  84.   }

  85.  

  86.   /// <summary>

  87.   /// Represents a server machine

  88.   /// </summary>

  89.   class Server

  90.   {

  91.     // Gets or sets server name

  92.     public string Name { get; set; }

  93.  

  94.     // Gets or sets server IP address

  95.     public string IP { get; set; }

  96.   }

  97. }

  98.  

 

Output

Same instance

ServerIV
ServerIV
ServerIII
ServerV
ServerII
ServerV
ServerII
ServerII
ServerI
ServerIV
ServerIV
ServerII
ServerI
ServerV
ServerIV

Credits:
http://www.dotnet-tricks.com/Tutorial/designpatterns/L2KL080613-Singleton-Design-Pattern—C#.html
http://www.dofactory.com/net/singleton-design-pattern

For More Design Patterns:
http://www.c-sharpcorner.com/UploadFile/sathvik/DesignPatterns11012005085547AM/DesignPatterns.aspx

Facade Design Pattern

Sample 1:
Facade pattern falls under Structural Pattern of Gang of Four (GOF) Design Patterns in .Net. The Facade design pattern is particularly used when a system is very complex or difficult to understand because system has a large number of interdependent classes or its source code is unavailable. In this article, I would like share what is facade pattern and how is it work?

What is facade Pattern

Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system.

This pattern involves a single wrapper class which contains a set of members which are required by client. These members access the system on behalf of the facade client and hide the implementation details.

The facade design pattern is particularly used when a system is very complex or difficult to understand because system has a large number of interdependent classes or its source code is unavailable.

Facade Pattern – UML Diagram & Implementation

The UML class diagram for the implementation of the facade design pattern is given below:

The classes, interfaces and objects in the above UML class diagram are as follows:

  1. Complex System

    A library of subsystems.

  2. SubsystemA, SubsystemB, SubsystemC

    These are classes within complex system and offer detailed operations.

  3. Façade

    This is a wrapper class which wrapper class which contains a set of members which are required by client.

  4. Client

    This is a class which calls the high-level operations in the Façade.

C# – Implementation Code

  1. class SubsystemA
  2. {
  3. public string OperationA1()
  4. {
  5. return “Subsystem A, Method A1\n”;
  6. }
  7. public string OperationA2()
  8. {
  9. return “Subsystem A, Method A2\n”;
  10. }
  11. }
  12. class SubsystemB
  13. {
  14. public string OperationB1()
  15. {
  16. return “Subsystem B, Method B1\n”;
  17. }
  18.  
  19. public string OperationB2()
  20. {
  21. return “Subsystem B, Method B2\n”;
  22. }
  23. }
  24. class SubsystemC
  25. {
  26. public string OperationC1()
  27. {
  28. return “Subsystem C, Method C1\n”;
  29. }
  30.  
  31. public string OperationC2()
  32. {
  33. return “Subsystem C, Method C2\n”;
  34. }
  35. }
  36.  
  37. public class Facade
  38. {
  39. SubsystemA a = new SubsystemA();
  40. SubsystemB b = new SubsystemB();
  41. SubsystemC c = new SubsystemC();
  42. public void Operation1()
  43. {
  44. Console.WriteLine(“Operation 1\n” +
  45. a.OperationA1() +
  46. a.OperationA2() +
  47. b.OperationB1());
  48. }
  49. public void Operation2()
  50. {
  51. Console.WriteLine(“Operation 2\n” +
  52. b.OperationB2() +
  53. c.OperationC1() +
  54. c.OperationC2());
  55. }
  56. }

Façade Pattern – Example

Who is what?

The classes, interfaces and objects in the above class diagram can be identified as follows:

  1. CarModel, CarEngine, CarBody, CarAccessories – These are subsystems.
  2. CarFacade– Facade class.

C# – Sample Code

  1. /// <summary>
  2. /// The ‘Subsystem ClassA’ class
  3. /// </summary>
  4. class CarModel
  5. {
  6. public void SetModel()
  7. {
  8. Console.WriteLine(” CarModel – SetModel”);
  9. }
  10. }
  11.  
  12. /// <summary>
  13. /// The ‘Subsystem ClassB’ class
  14. /// </summary>
  15. class CarEngine
  16. {
  17. public void SetEngine()
  18. {
  19. Console.WriteLine(” CarEngine – SetEngine”);
  20. }
  21. }
  22.  
  23. /// <summary>
  24. /// The ‘Subsystem ClassC’ class
  25. /// </summary>
  26. class CarBody
  27. {
  28. public void SetBody()
  29. {
  30. Console.WriteLine(” CarBody – SetBody”);
  31. }
  32. }
  33.  
  34. /// <summary>
  35. /// The ‘Subsystem ClassD’ class
  36. /// </summary>
  37. class CarAccessories
  38. {
  39. public void SetAccessories()
  40. {
  41. Console.WriteLine(” CarAccessories – SetAccessories”);
  42. }
  43. }
  44.  
  45. /// <summary>
  46. /// The ‘Facade’ class
  47. /// </summary>
  48. public class CarFacade
  49. {
  50. CarModel model;
  51. CarEngine engine;
  52. CarBody body;
  53. CarAccessories accessories;
  54.  
  55. public CarFacade()
  56. {
  57. model = new CarModel();
  58. engine = new CarEngine();
  59. body = new CarBody();
  60. accessories = new CarAccessories();
  61. }
  62.  
  63. public void CreateCompleteCar()
  64. {
  65. Console.WriteLine(“******** Creating a Car **********\n”);
  66. model.SetModel();
  67. engine.SetEngine();
  68. body.SetBody();
  69. accessories.SetAccessories();
  70.  
  71. Console.WriteLine(“\n******** Car creation complete **********”);
  72. }
  73. }
  74.  
  75. /// <summary>
  76. /// Facade Pattern Demo
  77. /// </summary>
  78. class Program
  79. {
  80. static void Main(string[] args)
  81. {
  82. CarFacade facade = new CarFacade();
  83.  
  84. facade.CreateCompleteCar();
  85.  
  86. Console.ReadKey();
  87.  
  88. }
  89. }

facade Pattern Demo – Output

When to use it?

  1. A simple interface is required to access to a complex system.
  2. The abstractions and implementations of a subsystem are tightly coupled.
  3. Need an entry point to each level of layered software.
  4. The facade design pattern is particularly used when a system is very complex or difficult to understand because system has a large number of interdependent classes or its source code is unavailable

    Sample 2:

    Facade

     


     

    Definition

    Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.

     

    Frequency of use:
    High


     

    UML class diagram

     


     

    Participants

     

    The classes and objects participating in this pattern are:

    • Facade   (MortgageApplication)
      • knows which subsystem classes are responsible for a request.
      • delegates client requests to appropriate subsystem objects.
    • Subsystem classes   (Bank, Credit, Loan)
      • implement subsystem functionality.
      • handle work assigned by the Facade object.
      • have no knowledge of the facade and keep no reference to it.


     

    Structural code in C#

     

    This structural code demonstrates the Facade pattern which provides a simplified and uniform interface to a large subsystem of classes.

    1. using System;

    2.  

    3. namespace DoFactory.GangOfFour.Facade.Structural

    4. {

    5.   /// <summary>

    6.   /// MainApp startup class for Structural

    7.   /// Facade Design Pattern.

    8.   /// </summary>

    9.   class MainApp

    10.   {

    11.     /// <summary>

    12.     /// Entry point into console application.

    13.     /// </summary>

    14.     public static void Main()

    15.     {

    16.       Facade facade = new Facade();

    17.  

    18.       facade.MethodA();

    19.       facade.MethodB();

    20.  

    21.       // Wait for user

    22.       Console.ReadKey();

    23.     }

    24.   }

    25.  

    26.   /// <summary>

    27.   /// The ‘Subsystem ClassA’ class

    28.   /// </summary>

    29.   class SubSystemOne

    30.   {

    31.     public void MethodOne()

    32.     {

    33.       Console.WriteLine(” SubSystemOne Method”);

    34.     }

    35.   }

    36.  

    37.   /// <summary>

    38.   /// The ‘Subsystem ClassB’ class

    39.   /// </summary>

    40.   class SubSystemTwo

    41.   {

    42.     public void MethodTwo()

    43.     {

    44.       Console.WriteLine(” SubSystemTwo Method”);

    45.     }

    46.   }

    47.  

    48.   /// <summary>

    49.   /// The ‘Subsystem ClassC’ class

    50.   /// </summary>

    51.   class SubSystemThree

    52.   {

    53.     public void MethodThree()

    54.     {

    55.       Console.WriteLine(” SubSystemThree Method”);

    56.     }

    57.   }

    58.  

    59.   /// <summary>

    60.   /// The ‘Subsystem ClassD’ class

    61.   /// </summary>

    62.   class SubSystemFour

    63.   {

    64.     public void MethodFour()

    65.     {

    66.       Console.WriteLine(” SubSystemFour Method”);

    67.     }

    68.   }

    69.  

    70.   /// <summary>

    71.   /// The ‘Facade’ class

    72.   /// </summary>

    73.   class Facade

    74.   {

    75.     private SubSystemOne _one;

    76.     private SubSystemTwo _two;

    77.     private SubSystemThree _three;

    78.     private SubSystemFour _four;

    79.  

    80.     public Facade()

    81.     {

    82.       _one = new SubSystemOne();

    83.       _two = new SubSystemTwo();

    84.       _three = new SubSystemThree();

    85.       _four = new SubSystemFour();

    86.     }

    87.  

    88.     public void MethodA()

    89.     {

    90.       Console.WriteLine(“\nMethodA() —- “);

    91.       _one.MethodOne();

    92.       _two.MethodTwo();

    93.       _four.MethodFour();

    94.     }

    95.  

    96.     public void MethodB()

    97.     {

    98.       Console.WriteLine(“\nMethodB() —- “);

    99.       _two.MethodTwo();

    100.       _three.MethodThree();

    101.     }

    102.   }

    103. }

    104.  

     

    Output
    MethodA() —-
    SubSystemOne Method
    SubSystemTwo Method
    SubSystemFour Method

    MethodB() —-
    SubSystemTwo Method
    SubSystemThree Method


     

    Real-world code in C#

     

    This real-world code demonstrates the Facade pattern as a MortgageApplication object which provides a simplified interface to a large subsystem of classes measuring the creditworthyness of an applicant.

    1. using System;

    2.  

    3. namespace DoFactory.GangOfFour.Facade.RealWorld

    4. {

    5.   /// <summary>

    6.   /// MainApp startup class for Real-World

    7.   /// Facade Design Pattern.

    8.   /// </summary>

    9.   class MainApp

    10.   {

    11.     /// <summary>

    12.     /// Entry point into console application.

    13.     /// </summary>

    14.     static void Main()

    15.     {

    16.       // Facade

    17.       Mortgage mortgage = new Mortgage();

    18.  

    19.       // Evaluate mortgage eligibility for customer

    20.       Customer customer = new Customer(“Ann McKinsey”);

    21.       bool eligible = mortgage.IsEligible(customer, 125000);

    22.  

    23.       Console.WriteLine(“\n” + customer.Name +

    24.           ” has been “ + (eligible ? “Approved” : “Rejected”));

    25.  

    26.       // Wait for user

    27.       Console.ReadKey();

    28.     }

    29.   }

    30.  

    31.   /// <summary>

    32.   /// The ‘Subsystem ClassA’ class

    33.   /// </summary>

    34.   class Bank

    35.   {

    36.     public bool HasSufficientSavings(Customer c, int amount)

    37.     {

    38.       Console.WriteLine(“Check bank for “ + c.Name);

    39.       return true;

    40.     }

    41.   }

    42.  

    43.   /// <summary>

    44.   /// The ‘Subsystem ClassB’ class

    45.   /// </summary>

    46.   class Credit

    47.   {

    48.     public bool HasGoodCredit(Customer c)

    49.     {

    50.       Console.WriteLine(“Check credit for “ + c.Name);

    51.       return true;

    52.     }

    53.   }

    54.  

    55.   /// <summary>

    56.   /// The ‘Subsystem ClassC’ class

    57.   /// </summary>

    58.   class Loan

    59.   {

    60.     public bool HasNoBadLoans(Customer c)

    61.     {

    62.       Console.WriteLine(“Check loans for “ + c.Name);

    63.       return true;

    64.     }

    65.   }

    66.  

    67.   /// <summary>

    68.   /// Customer class

    69.   /// </summary>

    70.   class Customer

    71.   {

    72.     private string _name;

    73.  

    74.     // Constructor

    75.     public Customer(string name)

    76.     {

    77.       this._name = name;

    78.     }

    79.  

    80.     // Gets the name

    81.     public string Name

    82.     {

    83.       get { return _name; }

    84.     }

    85.   }

    86.  

    87.   /// <summary>

    88.   /// The ‘Facade’ class

    89.   /// </summary>

    90.   class Mortgage

    91.   {

    92.     private Bank _bank = new Bank();

    93.     private Loan _loan = new Loan();

    94.     private Credit _credit = new Credit();

    95.  

    96.     public bool IsEligible(Customer cust, int amount)

    97.     {

    98.       Console.WriteLine(“{0} applies for {1:C} loan\n”,

    99.         cust.Name, amount);

    100.  

    101.       bool eligible = true;

    102.  

    103.       // Check creditworthyness of applicant

    104.       if (!_bank.HasSufficientSavings(cust, amount))

    105.       {

    106.         eligible = false;

    107.       }

    108.       else if (!_loan.HasNoBadLoans(cust))

    109.       {

    110.         eligible = false;

    111.       }

    112.       else if (!_credit.HasGoodCredit(cust))

    113.       {

    114.         eligible = false;

    115.       }

    116.  

    117.       return eligible;

    118.     }

    119.   }

    120. }

    121.  
    122.  

     

    Output
    Ann McKinsey applies for $125,000.00 loan

    Check bank for Ann McKinsey
    Check loans for Ann McKinsey
    Check credit for Ann McKinsey

    Ann McKinsey has been Approved

    Credits:
    http://www.dotnet-tricks.com/Tutorial/designpatterns/1N4c140713-Facade-Design-Pattern—C#.html
    http://www.dofactory.com/net/facade-design-pattern

About IIS Application Pool, recycle app pool and Session Timeout

The smps.log can sometimes report sporadic errors indicating that it may have lost a connection to a server running a SiteMinder WebAgent:

[4280/5660][Wed Nov 05 2014 08:32:30][CServer.cpp:2283][ERROR][sm-Server-01090] Failed to receive request on session # 185 : <hostname>/<IP Address>:<Port>. Socket error 10053

If this error is occurring in the smps.log, you can check the webagent log of the server where the webagent is installed.  This can be found by using the <hostname> reported in the smps.log error.  The webagent log will have a correlating timestamp at or near the time of the Socket error reported in the smps.log.

NOTE: You should also keep in mind that the “Date Modified” timestamp of the webagent log can sometimes be different because once the webagent is stopped and restarted, a new log is only created once a request is made for a resource under the default website within IIS7.  If this is an environment where the usage is low, there could be a different between when the error is reported in the smps.log on the policy server and when the webagent is restarted.

One way to confirm that the “Idle Time-Out” threshold is being reached in the DefaultAppPool in IIS7 is to check the Windows Event Viewer.  You will also find that the System Log is reporting the following message:

event_viewer1

event_viewer2

Information about Event ID 5186 can be found at: http://technet.microsoft.com/en-us/library/cc735034(v=ws.10).aspx

Information about configuring Idle Time-out settings can be found at: http://technet.microsoft.com/en-us/library/cc771956(v=ws.10).aspx

By default, IIS7 sets application pools to “time-out” after 20 minutes of inactivity. If you do not have any activity to your site within 20 minutes the application pool will shut down – freeing up those system resources. By doing this, the webagent tied to the default application pool will also be shut down. Then the next time a request comes into the site IIS7 will automatically restart the application pool and serve up the requested pages and in turn, start the webagent.  It will also mean that the first request – the one that causes the application pool to restart will be very slow. This is a result of the process starting, loading the required assemblies (like .NET) and finally loading the requested pages.

To extend the length of the time-out setting, simply change it from the default of 20 (minutes) to the value you choose. You can also adjust the setting to 0 (zero) which effectively disables the timeout so that the application pool will never shut down due to being idle.

To make this change, open Server Manager -> Expand the Roles -> Expand the Web Server (IIS) node. Then click on the Web Server (IIS) node -> Expand the node with your local server name and click on the Application Pools icon. You will then see a list of the application pools that are defined on your server. In the right-hand pane click the option for Advanced Settings.Source: http://bradkingsley.com/iis7-application-pool-idle-time-out-settings/

Restart IIS7 once the changes have been made.  NOTE:  When restarting IIS7, open Task Manager and make sure that the LLAWP.exe process fully terminates before starting IIS7.

DefaultAppPool1

After making the changes and IIS7 has been restarted, monitor the smps.log and the webagent logs to verify changes have taken effect.

———————————————————————————————————————————————————-

Why is the IIS default app pool recycle set to 1740 minutes?

Microsoft IIS Server has what appears to be an odd default for the application pool recycle time. It defaults to 1740 minutes, which is exactly 29 hours. I’ve always been a bit curious where that default came from. If you’re like me, you may have wondered too.

Wonder no longer! While at the MVP Summit this year in Bellevue WA I had the privilege again of talking with the IIS team. Wade Hilmo was there too. Somehow in the conversation a discussion about IIS default settings came up, which included the odd 1740 minutes for the app pool recycle interval. Wade told the story of how the setting came into being, and he granted me permission to share.

As you can imagine, many decisions for the large set of products produced by Microsoft come about after a lot of deliberation and research. Others have a geeky and fun origin. This is one of the latter.

The 1740 story

image

Back when IIS 6 was being developed—which is the version that introduced application pools—a default needed to be set for the Regular Time Interval when application pools are automatically recycled.

Wade suggested 29 hours for the simple reason that it’s the smallest prime number over 24. He wanted a staggered and non-repeating pattern that doesn’t occur more frequently than once per day. In Wade’s words: “you don’t get a resonate pattern”. The default has been 1740 minutes (29 hours) ever since!

That’s a fun little tidbit on the origin of the 1740. How about in your environment though? What is a good default?

Practical guidelines

First off, I think 29 hours is a good default. For a situation where you don’t know the environment, which is the case for a default setting, having a non-resonate pattern greater than one day is a good idea.

However, since you likely know your environment, it’s best to change this. I recommendsetting to a fixed time like 4:00am if you’re on the East coast of the US, 1:00am on the West coast, or whatever seems to make sense for your audience when you have the least amount of traffic. Setting it to a fixed time each day during low traffic times will minimize the impact and also allow you to troubleshoot easier if you run into any issues. If you have multiple application pools it may be wise to stagger them so that you don’t overload the server with a lot of simultaneous recycles.

Note that IIS overlaps the app pool when recycling so there usually isn’t any downtime during a recycle. However, in-memory information (session state, etc) is lost. See this video if you want to learn more about IIS overlapping app pools.

You may ask whether a fixed recycle is even needed. A daily recycle is just a band-aid to freshen IIS in case there is a slight memory leak or anything else that slowly creeps into the worker process. In theory you don’t need a daily recycle unless you have a known problem. I used to recommend that you turn it off completely if you don’t need it. However, I’m leaning more today towards setting it to recycle once per day at an off-peak time as a proactive measure.

My reason is that, first, your site should be able to survive a recycle without too much impact, so recycling daily shouldn’t be a concern. Secondly, I’ve found that even well behaving app pools can eventually have something sneak in over time that impacts the app pool. I’ve seen issues from traffic patterns that cause excessive caching or something odd in the application, and I’ve seen the very rare IIS bug (rare indeed!) that isn’t a problem if recycled daily. Is it a band-aid? Possibly, but if a daily recycle keeps a non-critical issue from bubbling to the top then I believe that it’s a good proactive measure to save a lot of troubleshooting effort on something that probably isn’t important to troubleshoot. However, if you think you have a real issue that is being suppressed by recycling then, by all means, turn off the auto-recycling so that you can track down and resolve your issue. There’s no black and white answer. Only you can make the best decision for your environment.

Idle Time-out

While on the topic of app pool defaults, there is one more that you should change with every new server deployment. The Idle Time-out should be set to 0 unless you are doing bulk hosting where you want to keep the memory footprint per site as low as possible.

image

If you have a just a few sites on your server and you want them to always load fast then set this to zero. Otherwise, when you have 20 minutes without any traffic then the app pool will terminate so that it can start up again on the next visit. The problem is that the first visit to an app pool needs to create a new w3wp.exe worker process which is slow because the app pool needs to be created, ASP.NET or another framework needs to be loaded, and then your application needs to be loaded. That can take a few seconds. Therefore I set that to 0 every chance I have, unless it’s for a server that hosts a lot of sites that don’t always need to be running.

There are other settings that can be reviewed for each environment but the two aforementioned settings are the two that should be changed almost every time.

Hopefully you enjoyed knowing about the 29 hour default as much as I did, even if just for fun. Happy IISing.

Credits:

Clients


http://weblogs.asp.net/owscott/why-is-the-iis-default-app-pool-recycle-set-to-1740-minutes

Contention, poor performance, and deadlocks when you make calls to Web services from an ASP.NET application

Symptoms

When you make calls to Web services from a Microsoft ASP.NET application, you may experience contention, poor performance, and deadlocks. Clients may report that requests stop responding (or “hang”) or take a very long time to execute. If a deadlock is suspected, the worker process may be recycled. You may receive the following messages in the application event log.

  • If you are using Internet Information Services (IIS) 5.0, you receive the following messages in the Application log:
       Event Type:     Error
       Event Source:   ASP.NET 1.0.3705.0
       Event Category: None
       Event ID:       1003
       Date:           5/4/2003
       Time:           6:18:23 PM
       User:           N/A
       Computer:       <ComputerName>
       Description:
          aspnet_wp.exe  (PID: <xxx>) was recycled because it was suspected to be in a deadlocked state.
          It did not send any responses for pending requests in the last 180 seconds.
  • If you are using IIS 6.0, you receive the following messages in the Application log:
       Event Type:     Warning
       Event Source:   W3SVC-WP
       Event Category: None
       Event ID:       2262
       Date:           5/4/2003
       Time:           1:02:33 PM
       User:           N/A
       Computer:       <ComputerName>
       Description:
          ISAPI 'C:\Windows\Microsoft.net\Framework\v.1.1.4322\aspnet_isapi.dll' reported itself as
          unhealthy for the following reason: 'Deadlock detected'.
  • If you are using IIS 6.0, you receive the following messages in the System log:
       Event Type:     Warning
       Event Source:   W3SVC
       Event Category: None
       Event ID:       1013
       Date:           5/4/2003
       Time:           1:03:47 PM
       User:           N/A
       Computer:       <ComputerName>
       Description:
          A process serving application pool 'DefaultAppPool' exceeded time limits during shut down.
          The process id was '<xxxx>'.

You may also receive the following exception error message when you make a call to the HttpWebRequest.GetResponse method:

“System.InvalidOperationException: There were not enough free threads in the ThreadPool object to complete the operation.”

You may also receive the following exception error message in the browser:

“HttpException (0x80004005): Request timed out.”

Note This article also applies to applications that make HttpWebRequest requests directly.

Cause

This problem might occur because ASP.NET limits the number of worker threads and completion port threads that a call can use to execute requests.

Typically, a call to a Web service uses one worker thread to execute the code that sends the request and one completion port thread to receive the callback from the Web service. However, if the request is redirected or requires authentication, the call may use as many as two worker threads and two completion port threads. Therefore, you can exhaust the managed ThreadPool when multiple Web service calls occur at the same time.

For example, suppose that the ThreadPool is limited to 10 worker threads and that all 10 worker threads are currently executing code that is waiting for a callback to execute. The callback can never execute, because any work items that are queued to the ThreadPool are blocked until a thread becomes available.

Another potential source of contention is the maxconnection parameter that the System.Net namespace uses to limit the number of connections. Generally, this limit works as expected. However, if many applications try to make many requests to a single IP address at the same time, threads may have to wait for an available connection.

Resolution

To resolve these problems, you can tune the following parameters in the Machine.config file to best fit your situation:

  • maxWorkerThreads
  • minWorkerThreads
  • maxIoThreads
  • minFreeThreads
  • minLocalRequestFreeThreads
  • maxconnection
  • executionTimeout

To successfully resolve these problems, take the following actions:

  • Limit the number of ASP.NET requests that can execute at the same time to approximately 12 per CPU.
  • Permit Web service callbacks to freely use threads in the ThreadPool.
  • Select an appropriate value for the maxconnections parameter. Base your selection on the number of IP addresses and AppDomains that are used.

Note The recommendation to limit the number of ASP.NET requests to 12 per CPU is a little arbitrary. However, this limit has proved to work well for most applications.

maxWorkerThreads and maxIoThreads

ASP.NET uses the following two configuration settings to limit the maximum number of worker threads and completion threads that are used:

<processModel maxWorkerThreads="20" maxIoThreads="20">

The maxWorkerThreads parameter and the maxIoThreads parameter are implicitly multiplied by the number of CPUs. For example, if you have two processors, the maximum number of worker threads is the following:

2*maxWorkerThreads

minFreeThreads and minLocalRequestFreeThreads

ASP.NET also contains the following configuration settings that determine how many worker threads and completion port threads must be available to start a remote request or a local request:

<httpRuntime minFreeThreads="8" minLocalRequestFreeThreads="8">

If there are not sufficient threads available, the request is queued until sufficient threads are free to make the request. Therefore, ASP.NET will not execute more than the following number of requests at the same time:

(maxWorkerThreads*number of CPUs)-minFreeThreads

Note The minFreeThreads parameter and the minLocalRequestFreeThreads parameter are not implicitly multiplied by the number of CPUs.

minWorkerThreads

As of ASP.NET 1.0 Service Pack 3 and ASP.NET 1.1, ASP.NET also contains the following configuration setting that determines how many worker threads may be made available immediately to service a remote request.

<processModel minWorkerThreads="1">

Threads that are controlled by this setting can be created at a much faster rate than worker threads that are created from the CLR’s default “thread-tuning” capabilities. This setting enables ASP.NET to service requests that may be suddenly filling the ASP.NET request queue due to a slow-down on a back end server, a sudden burst of requests from the client end, or something similar that would cause a sudden rise in the number of requests in the queue. The default value for the minWorkerThreads parameter is 1. We recommend that you set the value for the minWorkerThreads parameter to the following value.

minWorkerThreads = maxWorkerThreads / 2

By default, the minWorkerThreads parameter is not present in either the Web.config file or the Machine.config file. This setting is implicitly multiplied by the number of CPUs.

maxconnection

The maxconnection parameter determines how many connections can be made to a specific IP address. The parameter appears as follows:

<connectionManagement>
    <add address="*" maxconnection="2">
    <add address="http://65.53.32.230" maxconnection="12">
</connectionManagement>

If the application’s code references the application by hostname instead of IP address, the parameter should appear as follows:

<connectionManagement>
    <add address="*" maxconnection="2">
    <add address="http://hostname" maxconnection="12">
</connectionManagement>

Finally, if the application is hosted on a port other than 80, the parameter has to include the non-standard port in the URI, similar to the following:

<connectionManagement>
    <add address="*" maxconnection="2">
    <add address="http://hostname:8080" maxconnection="12">
</connectionManagement>

The settings for the parameters that are discussed earlier in this article are all at the process level. However, the maxconnection parameter setting applies to the AppDomain level. By default, because this setting applies to the AppDomain level, you can create a maximum of two connections to a specific IP address from each AppDomain in your process.

executionTimeout

ASP.NET uses the following configuration setting to limit the request execution time:

<httpRuntime executionTimeout="90"/>

You can also set this limit by using the Server.ScriptTimeout property.

Note If you increase the value of the executionTimeout parameter, you may also have to modify the processModel responseDeadlockInterval parameter setting.

Recommendations

The settings that are recommended in this section may not work for all applications. However, the following additional information may help you to make the appropriate adjustments.

If you are making one Web service call to a single IP address from each ASPX page, Microsoft recommends that you use the following configuration settings:

  • Set the values of the maxWorkerThreads parameter and the maxIoThreads parameter to 100.
  • Set the value of the maxconnection parameter to 12*N (where N is the number of CPUs that you have).
  • Set the values of the minFreeThreads parameter to 88*N and the minLocalRequestFreeThreads parameter to76*N.
  • Set the value of minWorkerThreads to 50. Remember, minWorkerThreads is not in the configuration file by default. You must add it.

Some of these recommendations involve a simple formula that involves the number of CPUs on a server. The variable that represents the number of CPUs in the formulas is N. For these settings, if you have hyperthreading enabled, you must use the number of logical CPUs instead of the number of physical CPUs. For example, if you have a four-processor server with hyperthreading enabled, then the value of N in the formulas will be 8 instead of 4.

Note When you use this configuration, you can execute a maximum of 12 ASP.NET requests per CPU at the same time because 100-88=12. Therefore, at least 88*N worker threads and 88*N completion port threads are available for other uses (such as for the Web service callbacks).

For example, you have a server with four processors and hyperthreading enabled. Based on these formulas, you would use the following values for the configuration settings that are mentioned in this article.

<system.web>
	<processModel maxWorkerThreads="100" maxIoThreads="100" minWorkerThreads="50"/>
	<httpRuntime minFreeThreads="704" minLocalRequestFreeThreads="608"/>
</system.web>

<system.net>
	<connectionManagement>
		<add address="[ProvideIPHere]" maxconnection="96"/>
	</connectionManagement>
</system.net>

Also, when you use this configuration, 12 connections are available per CPU per IP address for each AppDomain. Therefore, in the following scenario, very little contention occurs when requests are waiting for connections, and the ThreadPool is not exhausted:

  • The web hosts only one application (AppDomain).
  • Each request for an ASPX page makes one Web service request.
  • All requests are to the same IP address.

However, when you use this configuration, scenarios that involve one of the following will probably use too many connections:

  • Requests are to multiple IP addresses.
  • Requests are redirected (302 status code).
  • Requests require authentication.
  • Requests are made from multiple AppDomains.

In these scenarios, it is a good idea to use a lower value for the maxconnection parameter and higher values for the minFreeThreads parameter and theminLocalRequestFreeThreads parameter.

Credits:
https://support.microsoft.com/en-us/kb/821268

.NET and ADO.NET Data Service Performance Tips for Windows Azure Tables

We have collected the common issues that users have come across while using Windows Azure Table and posted some solutions. Some of these are .NET related or ADO.NET Data Services (aka Astoria) related. If you have alternate solutions, please let us know.   If you feel we have missed something important, please let us know and we would like to cover them.  We hope that the list helps  🙂

1> Default .NET HTTP connections is set to 2
This is a notorious one that has affected many developers. By default, the value for this is 2.  This implies that only 2 concurrent connections can be maintained. This manifests itself as “underlying connection was closed…” when the number of concurrent requests is greater than 2. The default can be increased by setting the following in the application configuration file OR in code.

Config file:  
  <system.net> 
    <connectionManagement> 
      <add address = “*” maxconnection = “48” /> 
    </connectionManagement> 
  </system.net> 
In code:
ServicePointManager.DefaultConnectionLimit = 48

The exact number depends on your application. http://support.microsoft.com/kb/821268  has good information on how to set this for server side applications.

One can also set it for a particular uri by specifying the URI in place of “*”.  If you are setting it in code, you could use the ServicePoint class rather than the ServicePointManager class i.e.:

ServicePoint myServicePoint = ServicePointManager.FindServicePoint(myServiceUri);
myServicePoint.ConnectionLimit = 48.


2> Turn off 100-continue (saves 1 roundtrip)
What is 100-continue?  When a client sends a POST/PUT request, it can delay sending the payload by sending an “Expect: 100-continue” header.

  1. The server will use the URI plus headers to ensure that the call can be made.
    2. The server would then send back a response with status code 100 (Continue) to the client.
    3. The client would send the rest of the payload.

This allows the client to be notified of most errors without incurring the cost of sending that entire payload.  However, once the entire payload is received on the server end, other errors may still occur.  When using .NET library, HttpWebRequest by default sends “Expect: 100-Continue” for all PUT/POST requests (even though MSDN suggests that it does so only for POSTS).

In Windows Azure Tables/Blobs/Queue, some of the failures that can be tested just by receiving the headers and URI are authentication, unsupported verbs, missing headers, etc.   If Windows Azure clients have tested the client well enough to ensure that it is not sending any bad requests, clients could turn off 100-continue so that the entire request is sent in one roundtrip. This is especially true when clients send small payloads as in the table or queue service. This setting can be turned off in code or via a configuration setting.

Code:  
ServicePointManager.Expect100Continue = false; // or on service point if only a particular service needs to be disabled.  
Config file:
<system.net> 
    <settings> 
      <servicePointManager expect100Continue=“false” /> 
    </settings> 
</system.net> 

Before turning 100-continue off, we recommend that you profile your application examining the effects with and without it.


3> To improve performance of ADO.NET Data Service deserialization
When you execute a query using ADO .Net data services, there are two important names – the name of the CLR class for the entity, and the name of the table in Windows Azure Table.  We have noticed that when these names are different, there is a fixed overhead of approximately 8-15ms for deserializing each entity received in a query.

There are two workarounds until this is fixed in Astoria:

1> Rename your table to be the same as the class name.
So if you have a Customer entity class, use “Customer” as the table name instead of “Customers”.

from customer in context.CreateQuery<Customer>(“Customer”)  
        where a.PartitionKey == “Microsoft” select customer; 

2> Use ResolveType on the DataServiceContext

                public void Query(DataServiceContext context)           
                {
                     // set the ResolveType to a method that will return the appropriate type to create
                     context.ResolveType = this.ResolveEntityType;          
                     …
                }
                public Type ResolveEntityType(string name)
                {
                      // if the context handles just one type, you can return it without checking the
                      // value of “name”.  Otherwise, check for the name and return the appropriate
                      // type (maybe a map of Dictionary<string, Type> will be useful)         
                      Type type  = typeof(Customer);  
                      return type;
                }

 

4> Turn entity tracking off for query results that are not going to be modified
DataServiceContext has a property MergeOption which can be set to AppendOnly, OverwriteChanges, PreserveChanges and NoTracking.  The default is AppendOnly. All options except NoTracking lead to the context tracking the entities.  Tracking is mandatory for updates/inserts/deletes. However, not all applications need to modify the entities that are returned from a query, so there really is no need to have change tracking on. The benefit is that Astoria need not do the extra work to track these entities.  Turning off entity tracking allows the garbage collector to free up these objects even if the same DataContext is used for other queries.   Entity tracking can be turned off by using:

context.MergeOption = MergeOption.NoTracking; 

However, when using a context for updates/inserts/deletes, tracking has to be turned on and one would use PreseveChanges to ensure that etags are always updated for the entities.


5> All about unconditional updates/deletes

ETags can be viewed as a version for entities.  These can be used for concurrency checks using the If-Match header during updates/deletes. Astoria maintains this etag which is sentETags can be viewed as a version for entities.  These can be used for concurrency checks using the If-Match header during updates/deletes. Astoria maintains this etag which is sent with every entity entry in the payload. To get into more details, Astoria tracks entities in the context via context.Entities which is a collection of EntityDescriptors. EntityDescriptor has an “Etag” property that Astoria maintains. On every update/delete the ETag is sent to the server. Astoria by default sends the mandatory “If-Match” header with this etag value. On the server side, Windows Azure table ensures that the etag sent in the If-Match header matches our Timestamp property in the data store. If it matches, the server goes ahead and performs the update/delete; otherwise the server returns a status code of 412 i.e. Precondition failed, indicating that someone else may have modified the entity being updated/deleted.  If a client sends “*” in the “If-Match” header, it tells the server that an unconditional update/delete needs to be performed i.e. go ahead and perform the requested operation irrespective of whether someone has changed the entity in the store. A client can send unconditional updates/deletes using the following code:

context.AttachTo(“TableName”, entity, “*”);   
context.UpdateObject(entity);

However, if this entity is already being tracked, client will be required to detach the entity before attaching it:

context.Detach(entity);  


Added on April 28th 2009
6> Turning off Nagle may help Inserts/Updates

We have seen that turning nagle off has provided significant boost to latencies for inserts and updates in table. However, turning nagle off is known to adversely affect throughput and hence it should be tested for your application to see if it makes a difference.

 

This can be turned off either in the configuration file or in code as below.

 

Code:  
ServicePointManager.UseNagleAlgorithm = false;
Config file:
<system.net> 
    <settings> 
      <servicePointManager expect100Continue=“false” useNagleAlgorithm=”false”/> 
    </settings> 
</system.net> 

Credits:
https://social.msdn.microsoft.com/Forums/azure/en-US/d84ba34b-b0e0-4961-a167-bbe7618beb83/net-and-adonet-data-service-performance-tips-for-windows-azure-tables?forum=windowsazuredata

HTML Doctypes

A Document Type Declaration, or DOCTYPE, is an instruction to the Web browser about the version of markup language in which a page is written.

HTML5 Doctype

A DOCTYPE declaration appears at the top of a web page before all other elements. According to the HTML specification or standards, every HTML document requires a document type declaration to insure that your pages are displayed the way they are intended to be displayed. The doctype declaration is usually the very first thing defined in an HTML document; however the doctype declaration itself is not an HTML tag.

The DOCTYPE for HTML5 is very short, and case-insensitive.

<!DOCTYPE html>

Doctypes from earlier versions of HTML were longer because the HTML language was SGML-based and therefore required a reference to a DTD, but they are obsolete now. With HTML5 this is no longer the case and the doctype declaration is only needed to enable the standard mode for documents written using the HTML syntax.

You can use the following markup as a template to create a new HTML5 document that uses the latest HTML5 doctype declaration.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  •     <title><!-- Insert your title here --></title>
  • </head>
  • <body>
  •     <!-- Insert your content here -->
  • </body>
  • </html>

Note:The doctype declaration refers to a Document Type Definition (DTD). It is an instruction to the web browser about what version of the markup language the page is written in. The W3C provides DTDs for all HTML versions.


HTML 4.01 Different Doctypes

The following section contains the different doctypes from the previous version of HTML. Although using the HTML 4.01 doctypes are still a valid way to create DOCTYPE declaration, but they are no longer considered a best practice.

HTML 4.01 Strict

The HTML 4.01 Strict DTD includes all elements and attributes that have not been deprecatedor do not appear in frameset documents. For documents that use this DTD, use the following DOCTYPE declaration:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
http://www.w3.org/TR/html4/strict.dtd”&gt;

HTML 4.01 Transitional

The HTML 4.01 Transitional DTD includes everything in the strict DTD as well as deprecatedelements and attributes but excludes the frameset content. For documents that use this DTD, use the following DOCTYPE declaration:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;

HTML 4.01 Frameset

The HTML 4.01 Frameset DTD includes everything in the transitional DTD, as well as also allows the use of frameset content. For documents that use this DTD, use the following DOCTYPE declaration:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Frameset//EN” “http://www.w3.org/TR/html4/frameset.dtd”&gt;

Warning:The <frameset> and <frame> elements has been removed from HTML5 and should no longer be used. Therefore, frameset DTD is no longer valid.


XHTML 1.1 Doctype

XHTML 1.1 is the most current finalized revision of XHTML 1.0 Strict, introducing support forXHTML Modularization, which means that you can add modules (for example, to provide Ruby support for Chinese, Japanese, and Korean characters).

For documents that use this DTD, use the following DOCTYPE declaration:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML Basic 1.1//EN” “http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd”&gt;

Tip:Must add a doctype to your HTML/XHTML document and use the W3C’s Validator to check the markup or syntax error before publishing online.

Source credits: http://www.tutorialrepublic.com/html-tutorial/html-doctypes.php

::before and ::after selectors in css

Summary

The CSS ::after pseudo-element matches a virtual last child of the selected element. Typically used to add cosmetic content to an element, by using the content CSS property. This element is inline by default.

Syntax

How to read CSS syntax.

element:after  { style properties }  /* CSS2 syntax */

element::after { style properties }  /* CSS3 syntax */

The ::after notation was introduced in CSS 3 in order to establish a discrimination between pseudo-classes and pseudo-elements. Browsers also accept the notation :after introduced in CSS 2.

Examples

Simple usage

Let’s create two classes, one for boring paragraphs and one for exciting ones. We can then mark each paragraph by adding a pseudo-element to the end of it.

<p class="boring-text">Here is some good old boring text.</p>
<p>Here is some moderate text that is neither boring nor exciting.</p>
<p class="exciting-text">Contributing to MDN is easy and fun.
Just hit the edit button to add new live samples, or improve existing samples.</p>
 .exciting-text::after {
   content:    "<- now this *is* exciting!"; 
   color:      green;
}

.boring-text::after {
   content:    "<- BORING!";
   color:      red;
}

Output

https://mdn.mozillademos.org/en-US/docs/Web/CSS/::after$samples/Simple_usage?revision=691383

Decorative example

We can style text or images in the content property almost any way we want.

<span class="ribbon">Notice where the orange box is.</span>
.ribbon {
   background-color: #5BC8F7;
}

.ribbon::after {
   content:          "Look at this orange box.";
   background-color: #FFBA10;
   border-color:     black;
   border-style:     dotted;
}
 Output

https://mdn.mozillademos.org/en-US/docs/Web/CSS/::after$samples/Decorative_example?revision=691383

Tooltips

The following example shows the use of the ::after pseudo-element in conjunction with the attr()CSS expression and a data-descr custom data attribute to create a pure-CSS, glossary-like tooltip. Checkout the live preview below, or you can see this example in a separate page.

<p>Here is the live example of the above code.<br />
  We have some <span data-descr="collection of words and punctuation">text</span> here with a few
  <span data-descr="small popups which also hide again">tooltips</span>.<br />
  Dont be shy, hover over to take a <span data-descr="not to be taken literally">look</span>.
</p>
    span[data-descr] {
        position: relative;
        text-decoration: underline;
        color: #00F;
        cursor: help;
    }

    span[data-descr]:hover::after {
        content: attr(data-descr);
        position: absolute;
        left: 0;
        top: 24px;
        min-width: 200px;
        border: 1px #aaaaaa solid;
        border-radius: 10px;
        background-color: #ffffcc;
        padding: 12px;
        color: #000000;
        font-size: 14px;
        z-index: 1;
    }
 Output

https://mdn.mozillademos.org/en-US/docs/Web/CSS/::after$samples/Tooltips?revision=691383


::after
is a pseudo element which allows you to insert content onto a page from CSS (without it needing to be in the HTML). While the end result is not actually in the DOM, it appears on the page as if it is, and would essentially be like this:

div::after {
  content: "hi";
}
<div>
  <!-- Rest of stuff inside the div -->
  hi
</div>

::before is exactly the same only it inserts the content before any other content in the HTML instead of after. The only reasons to use one over the other are:

  • You want the generated content to come before the element content, positionally.
  • The ::after content is also “after” in source-order, so it will position on top of ::before if stacked on top of each other naturally.

The value for content can be:

  • A string: content: "a string"; – special characters need to be specially encoded as a unicode entity. See the glyphs page.
  • An image: content: url(/path/to/image.jpg); – The image is inserted at it’s exact dimensions and cannot be resized. Since things like gradients are actually images, a pseudo element can be a gradient.
  • Nothing: content: “”; – Useful for clearfix and inserting images as background-images (set width and height, and can even resize with background-size).
  • A counter: content: counter(li); – Really useful for styling lists until :marker comes along.

Note that you cannot insert HTML (at least, that will be rendered as HTML). content: "<h1>nope</h1>";

: vs ::

Every browser that supports the double colon (::) CSS3 syntax also supports just the (:) syntax, but IE 8 only supports the single-colon, so for now, it’s recommended to just use the single-colon for best browser support.

:: is the newer format indented to distinguish pseudo content from pseudo selectors. If you don’t need IE 8 support, feel free to use the double-colon.

Source Credits:

::before / ::after


https://developer.mozilla.org/en-US/docs/Web/CSS/::after

CSS Selectors

It explains How to use different signs (+,> and ~) in CSS selector and their differences. Before starting, let us take a sample code to understand the signs.

<div id="container">           
   <p>First</p>
    <div>
        <p>Child Paragraph</p>
    </div>
   <p>Second</p>
   <p>Third</p>     
</div>
div#container p{
font-weight:bold;
}

It is the descendant selector. It will target all p tags within container div.

> Sign:

It will target elements which are DIRECT children of a particular element.

1
2
3
div#container > p {
  border: 1px solid black;
}

 Understand +, > and ~ symbols in CSS Selector

It will target all P element which are direct children of container div, not children of child div.

+ Sign:

It is Adjacent sibling combinator. It combines two sequences of simple selectors having the same parent and the second one must come IMMEDIATELY after the first.

1
2
3
div + p { 
   color: green
}

css%20selector%203 Understand +, > and ~ symbols in CSS Selector

It will only select the first element that is immediately preceded by the former selector. In our example, it will target to Second ONLY because the owner P element comes just after Div tag.

~ Sign:

It is general sibling combinator and similar to Adjacent sibling combinator. the difference is that the second selector does NOT have to immediately follow the first one means It will select all elements that is preceded by the former selector.

1
2
3
div ~ p{
background-color:blue;
}

css%20selector%204 Understand +, > and ~ symbols in CSS Selector

It will target both second and third.

@ Symbol in css:
These are all known in CSS as at-rules. They’re special instructions for the browser, not directly related to styling of (X)HTML/XML elements in Web documents using rules and properties, although they do play important roles in controlling how styles are applied.

/* Import another stylesheet from within a stylesheet */
@import url(style2.css);

/* Apply this style only for printing */
@media print {
    body {
        color: #000;
        background: #fff;
    }
}

/* Embed a custom web font */
@font-face {
    font-family: 'DejaVu Sans';
    src: local('DejaVu Sans Regular'), url(/fonts/DejaVuSans.ttf);
}
  • @font-face rules define custom fonts for use in your designs that aren’t always available on all computers, so a browser downloads a font from the server and sets text in that custom font as if the user’s computer had the font.
  • @media rules, in conjunction with media queries (formerly only media types), control which styles are applied and which aren’t based on what media the page is being displayed in. In my code example, only when printing a document should all text be set in black against a white (the paper) background. You can use media queries to filter out print media, mobile devices and so on, and style pages differently for those.

At-rules have no relation to selectors whatsoever. Because of their varying nature, different at-rules are defined in different ways across numerous different modules. More examples include:

An example of @media that might be useful to illustrate it further:

@media screen and (max-width: 1440px)
{
    span.sizedImage
    {
        height:135px;
        width: 174px;
    }
}    

@media screen and (min-width: 1441px)
{
    span.sizedImage
    {
        height:150px;
        width: 200px;
    }
}

This will vary the size of the image conditionally on the size of the screen, using a smaller image on a smaller screen. The first block would address screens up to width 1440px; the second would address screens larger than 1440px.

This comes in handy with things like tabs that float drop or scroll on smaller screens; you can often drop the font size of the tab labels down a point size on smaller screens and have them all fit.

So you learned the base id, class, and descendant selectors – and then called it a day? If so, you’re missing out on an enormous level of flexibility. While many of the selectors mentioned in this article are part of the CSS3 spec, and are, consequently, only available in modern browsers, you owe it to yourself to commit these to memory.

Let’s knock the obvious ones out, for the beginners, before we move onto the more advanced selectors.

The star symbol will target every single element on the page. Many developers will use this trick to zero out the margins and padding. While this is certainly fine for quick tests, I’d advise you to never use this in production code. It adds too muchweight on the browser, and is unnecessary.

The * can also be used with child selectors.

This will target every single element that is a child of the #container div. Again, try not to use this technique very much, if ever.

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

Prefixing the hash symbol to a selector allows us to target by id. This is easily the most common usage, however be cautious when using id selectors.

Ask yourself: do I absolutely need to apply an id to this element in order to target it?

id selectors are rigid and don’t allow for reuse. If possible, first try to use a tag name, one of the new HTML5 elements, or even a pseudo-class.

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

This is a class selector. The difference between ids and classes is that, with the latter, you can target multiple elements. Use classes when you want your styling to apply to a group of elements. Alternatively, use ids to find a needle-in-a-haystack, and style only that specific element.

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

The next most comment selector is the descendant selector. When you need to be more specific with your selectors, you use these. For example, what if, rather than targeting all anchor tags, you only need to target the anchors which are within an unordered list? This is specifically when you’d use a descendant selector.

Pro-tip – If your selector looks like X Y Z A B.error, you’re doing it wrong. Always ask yourself if it’s absolutely necessary to apply all of that weight.

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

What if you want to target all elements on a page, according to their type, rather than an id or classname? Keep it simple, and use a type selector. If you need to target all unordered lists, use ul {}.

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

We use the :link pseudo-class to target all anchors tags which have yet to be clicked on.

Alternatively, we also have the :visited pseudo class, which, as you’d expected, allows us to apply specific styling to only the anchor tags on the page which havebeen clicked on, or visited.

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

This is referred to as an adjacent selector. It will select only the element that is immediately preceded by the former element. In this case, only the first paragraph after each ul will have red text.

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

The difference between the standard X Y and X > Y is that the latter will only select direct children. For example, consider the following markup.

A selector of #container > ul will only target the uls which are direct children of the div with an id of container. It will not target, for instance, the ul that is a child of the first li.

For this reason, there are performance benefits in using the child combinator. In fact, it’s recommended particularly when working with JavaScript-based CSS selector engines.

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

This sibling combinator is similar to X + Y, however, it’s less strict. While an adjacent selector (ul + p) will only select the first element that is immediatelypreceded by the former selector, this one is more generalized. It will select, referring to our example above, any p elements, as long as they follow a ul.

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

Referred to as an attributes selector, in our example above, this will only select the anchor tags that have a title attribute. Anchor tags which do not will not receive this particular styling. But, what if you need to be more specific? Well…

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

The snippet above will style all anchor tags which link to http://net.tutsplus.com; they’ll receive our branded green color. All other anchor tags will remain unaffected.

Note that we’re wrapping the value in quotes. Remember to also do this when using a JavaScript CSS selector engine. When possible, always use CSS3 selectors over unofficial methods.

This works well, though, it’s a bit rigid. What if the link does indeed direct to Nettuts+, but, maybe, the path is nettuts.com rather than the full url? In those cases we can use a bit of the regular expressions syntax.

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

There we go; that’s what we need. The star designates that the proceeding value must appear somewhere in the attribute’s value. That way, this covers nettuts.com,net.tutsplus.com, and even tutsplus.com.

Keep in mind that this is a broad statement. What if the anchor tag linked to some non-Envato site with the string tuts in the url? When you need to be more specific, use ^ and &, to reference the beginning and end of a string, respectively.

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

Ever wonder how some websites are able to display a little icon next to the links which are external? I’m sure you’ve seen these before; they’re nice reminders that the link will direct you to an entirely different website.

This is a cinch with the carat symbol. It’s most commonly used in regular expressions to designate the beginning of a string. If we want to target all anchor tags that have a href which begins with http, we could use a selector similar to the snippet shown above.

Notice that we’re not searching for http://; that’s unnecessary, and doesn’t account for the urls that begin with https://.

Now, what if we wanted to instead style all anchors which link to, say, a photo? In those cases, let’s search for the end of the string.

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

Again, we use a regular expressions symbol, $, to refer to the end of a string. In this case, we’re searching for all anchors which link to an image — or at least a url that ends with .jpg. Keep in mind that this certainly won’t work for gifs and pngs.

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

Refer back to number eight; how do we compensate for all of the various image types: png, jpeg,jpg, gif? Well, we could create multiple selectors, such as:

But, that’s a pain in the butt, and is inefficient. Another possible solution is to use custom attributes. What if we added our own data-filetype attribute to each anchor that links to an image?

Then, with that hook in place, we can use a standard attributes selector to target only those anchors.

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

Here’s a special one that’ll impress your friends. Not too many people know about this trick. The tilda (~) symbol allows us to target an attribute which has a spaced-separated list of values.

Going along with our custom attribute from number fifteen, above, we could create adata-info attribute, which can receive a space-separated list of anything we need to make note of. In this case, we’ll make note of external links and links to images — just for the example.

With that markup in place, now we can target any tags that have either of those values, by using the ~ attributes selector trick.

Pretty nifty, ay?

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

This pseudo class will only target a user interface element that has been checked – like a radio button, or checkbox. It’s as simple as that.

  • IE9+
  • Firefox
  • Chrome
  • Safari
  • Opera

The before and after pseudo classes kick butt. Every day, it seems, people are finding new and creative ways to use them effectively. They simply generate content around the selected element.

Many were first introduced to these classes when they encountered the clear-fix hack.

This hack uses the :after pseudo class to append a space after the element, and then clear it. It’s an excellent trick to have in your tool bag, particularly in the cases when the overflow: hidden; method isn’t possible.

For another creative use of this, refer to my quick tip on creating shadows.

According to the CSS3 Selectors specification, you should technically use the pseudo element syntax of two colons ::. However, to remain compatible, the user-agent will accept a single colon usage as well. In fact, at this point, it’s smarter to use the single-colon version in your projects.

  • IE8+
  • Firefox
  • Chrome
  • Safari
  • Opera

Oh come on. You know this one. The official term for this is user action pseudo class. It sounds confusing, but it really isn’t. Want to apply specific styling when a user hovers over an element? This will get the job done!

Keep in mind that older version of Internet Explorer don’t respond when the :hover pseudo class is applied to anything other than an anchor tag.

You’ll most often use this selector when applying, for example, a border-bottom to anchor tags, when hovered over.

Pro-tipborder-bottom: 1px solid black; looks better thantext-decoration: underline;.

  • IE6+ (In IE6, :hover must be applied to an anchor element)
  • Firefox
  • Chrome
  • Safari
  • Opera

The negation pseudo class is particularly helpful. Let’s say I want to select all divs, except for the one which has an id of container. The snippet above will handle that task perfectly.

Or, if I wanted to select every single element (not advised) except for paragraph tags, we could do:

  • IE9+
  • Firefox
  • Chrome
  • Safari
  • Opera

We can use pseudo elements (designated by ::) to style fragments of an element, such as the first line, or the first letter. Keep in mind that these must be applied to block level elements in order to take effect.

A pseudo-element is composed of two colons: ::

This snippet is an abstraction that will find all paragraphs on the page, and then sub-target only the first letter of that element.

This is most often used to create newspaper-like styling for the first-letter of an article.

Similarly, the ::first-line pseudo element will, as expected, style the first line of the element only.

“For compatibility with existing style sheets, user agents must also accept the previous one-colon notation for pseudo-elements introduced in CSS levels 1 and 2 (namely, :first-line, :first-letter, :before and :after). This compatibility is not allowed for the new pseudo-elements introduced in this specification.” – Source

  • IE6+
  • Firefox
  • Chrome
  • Safari
  • Opera

Remember the days when we had no way to target specific elements in a stack? The nth-child pseudo class solves that!

Please note that nth-child accepts an integer as a parameter, however, this is not zero-based. If you wish to target the second list item, use li:nth-child(2).

We can even use this to select a variable set of children. For example, we could doli:nth-child(4n) to select every fourth list item.

  • IE9+
  • Firefox 3.5+
  • Chrome
  • Safari

What if you had a huge list of items in a ul, and only needed to access, say, the third to the last item? Rather than doing li:nth-child(397), you could instead use the nth-last-child pseudo class.

This technique works almost identically from number sixteen above, however, the difference is that it begins at the end of the collection, and works its way back.

  • IE9+
  • Firefox 3.5+
  • Chrome
  • Safari
  • Opera

There will be times when, rather than selecting a child, you instead need to select according to the type of element.

Imagine mark-up that contains five unordered lists. If you wanted to style only the third ul, and didn’t have a unique id to hook into, you could use the nth-of-type(n) pseudo class. In the snippet above, only the third ul will have a border around it.

  • IE9+
  • Firefox 3.5+
  • Chrome
  • Safari

And yes, to remain consistent, we can also use nth-last-of-type to begin at the end of the selectors list, and work our way back to target the desired element.

  • IE9+
  • Firefox 3.5+
  • Chrome
  • Safari
  • Opera

This structural pseudo class allows us to target only the first child of the element’s parent. You’ll often use this to remove borders from the first and last list items.

For example, let’s say you have a list of rows, and each one has a border-top and a border-bottom. Well, with that arrangement, the first and last item in that set will look a bit odd.

Many designers apply classes of first and last to compensate for this. Instead, you can use these pseudo classes.

  • IE7+
  • Firefox
  • Chrome
  • Safari
  • Opera

The opposite of first-child, last-child will target the last item of the element’s parent.

Let’s build a simple example to demonstrate one possible use of these classes. We’ll create a styled list item.

Nothing special here; just a simple list.

This styling will set a background, remove the browser-default padding on the ul, and apply borders to each li to provide a bit of depth.

Styled List

To add depth to your lists, apply a border-bottom to eachli that is a shade or two darker than the li‘s background color. Next, apply a border-top which is a couple shades lighter.

The only problem, as shown in the image above, is that a border will be applied to the very top and bottom of the unordered list – which looks odd. Let’s use the:first-child and :last-child pseudo classes to fix this.

Fixed

There we go; that fixes it!

  • IE9+
  • Firefox
  • Chrome
  • Safari
  • Opera

Yep – IE8 supported :first-child, but not :last-child. Go figure.

Truthfully, you probably won’t find yourself using the only-child pseudo class too often. Nonetheless, it’s available, should you need it.

It allows you to target elements which are the only child of its parent. For example, referencing the snippet above, only the paragraph that is the only child of the divwill be colored, red.

Let’s assume the following markup.

In this case, the second div‘s paragraphs will not be targeted; only the first div. As soon as you apply more than one child to an element, the only-child pseudo class ceases to take effect.

  • IE9+
  • Firefox
  • Chrome
  • Safari
  • Opera

This structural pseudo class can be used in some clever ways. It will target elements that do not have any siblings within its parent container. As an example, let’s target all uls, which have only a single list item.

First, ask yourself how you would accomplish this task? You could do ul li, but, this would target all list items. The only solution is to use only-of-type.

  • IE9+
  • Firefox 3.5+
  • Chrome
  • Safari
  • Opera

The first-of-type pseudo class allows you to select the first siblings of its type.

To better understand this, let’s have a test. Copy the following mark-up into your code editor:

Now, without reading further, try to figure out how to target only “List Item 2”. When you’ve figured it out (or given up), read on.

There are a variety of ways to solve this test. We’ll review a handful of them. Let’s begin by using first-of-type.

This snippet essentially says, “find the first unordered list on the page, then find only the immediate children, which are list items. Next, filter that down to only the second list item in that set.

Another option is to use the adjacent selector.

In this scenario, we find the ul that immediately proceeds the p tag, and then find the very last child of the element.

We can be as obnoxious or as playful as we want with these selectors.

This time, we grab the first ul on the page, and then find the very first list item, but starting from the bottom! 🙂

Hope, you enjoyed this.

Source Credits:
http://techbrij.com/css-selector-adjacent-child-sibling
Stackoverflow.com
http://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize–net-16048

Building an ASP.NET Web Api RESTful service for Beginners

 

RESTful service

REST acronym stands for REpresentational State Transfer. In the latest years REST is emerging as a predominant Web service design model. AS another alternative we have Web Services built around SOAP.

RESTful services are fully built around the HTTP protocol, and use the basic HTTP commands like: GET, POST, PUT, DELETE in order to define the “action”. In simple terms, a REST Web Service is all about aResource that can be accessed or changed by using the above mentioned HTTP methods.

What do those HTTP commands represent:

GET Retrieves a Resource
POST
  • Updates a Resource: if you are requesting the server to update one or more subordinates of the specified resource.
  • Creates Resource = POST if you are sending a command to the server to create a subordinate of the specified resource, using some server-side algorithm.
PUT
  • Creates a Resource. Use PUT if you are sending the full content of the specified resource (URL).
  • Update a Resource = PUT iff you are updating the full content of the specified resource.
DELETE Deletes a Resource.

Idempotence

Idempotency guarantees that repeated invocations of a service capability are safe and will have no negative effect. The side-effects of N > 0 identical requests is the same as for a single request. The methods GET, PUT and DELETE share this property.

Message Formatting

Usually the main output formats of a restful service are JSON and XML, but obviously this is not the only option as we theoretically could return whatever type of message format we want. For instance, returning a PDF document when doing GET would be absolutely valid.

SOAP based Web Services

Another way of creating web service is by using SOAP message format as the communication between the Client and Server. Both, SOAP based and RESTful services, even though they try to solve the same issues (retrieving and getting data), the approach is very different.
Choosing REST or SOAP based services will depend upon your needs for Security, Speed, Protocols, Extensibility, Legacy Systems, etc. Is not that easy to give a recipe, but in general REST is a great tool when it comes to the AJAX dynamic pages and interoperability as it uses widely known HTTP protocol.

What is: ASP.NET Web Api

ASP.NET Web API is the latest Microsoft framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

ASP.NET Web API is build around (or better say, into) the newest ASP.NET MVC 4 framework and for the time being is the most powerful Microsoft tool when it comes to creating RESTful services. Yes, there are other possibilities as described in the article What technology for building web services in Microsoft.Net.

After this short introduction of very basic concepts, lets do some code.

ASP.NET Web API Installation

There are few ways of installing ASP.NET Web API.

  1. If you are using Visual Studio 2012, ASP.NET Web API is already pre-installed, and there is anything else needed to do.
  2. If you are using Visual Studio 2010, then there are few possibilities:

First steps

As mentioned, ASP.NET Web API is part of the ASP.NET MVC 4 Framework, and as a such in order to start, we need to create a new project by choosing ASP.NET MVC 4 Application project, and then choose the Web API as shown in the picture below:

Visual Studio will create a basic service structure, and I would like to highlight two folders:

ASP.NET Web API Visual Studio Solution Explorer
We may easily delete the HomeController as we are not interested into creating any MVC application in this example.

Routing

WebApiConfig.cs file in the App_Start folder is particularly interesting. It contains the definition of the routing needed for our service to work. As we normally do for the ASP.NET MVC application, we need to define the “route”, or better say the PATH to our service actions.

The code generated by default.

1
2
3
4
5
6
7
8
9
10
11
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Please note the following:

  • routeTemplate starts with “api/”. This will generate urls like: www.agile-code.com/api/product/1. Use “api” keyword to differentiate it from the normal ASP.NET MVC route.
  • {controller} represents the actual controller. Controller in our case would correspond to the part in bold: http://www.agile-code.com/api/product/1
  • There is no “{action}” as we would expect it in ASP.NET MVC. As there are no actions but verbs in form of Post()Get()… methods, there is no need for defining the Action in the route. The “{action}” is automatically known at runtime based on the HTTP verb used in the request.

RESTful service basic code

Visual Studio will take care of creating the basic skeleton of the service itself, as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
 
    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }
 
    // POST api/values
    public void Post([FromBody]string value)
    {
    }
 
    // PUT api/values/5
    public void Put(int id, [FromBody]string value)
    {
    }
 
    // DELETE api/values/5
    public void Delete(int id)
    {
    }
}

In the code above, there are few things to note:
1. ApiController is a new controller that comes as part of the ASP.NET Web API. Every RESTful service should inherit from it.
2. Methods in the service itself have the names as mentioned above as the HTTP methods, and those are bound to the proper verb at runtime by the Web API framework. It is still allowed to have methods that contain something else than the basic HTTP methods mentioned before.

Implementing something more realistic

Lets implement a ProductController, which will represent the Product resource, that for the sake of simplicity will look like:

1
2
3
4
5
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Service Implementation

I will show one by one the methods implementing various HTTP verbs.
Important: you will see that I am using repository keyword. This is simply a class that will keep in memory the list of Products, just for the sake of this example.

GET

GET a list of products

Get is pretty much straightforward. The Method called Get() is defined, and in our case returns a list of Products

1
2
3
4
5
// GET api/product
public IEnumerable<Product> Get()
{
    return repository.GetProducts();
}

for Getting back the data we may simply use the browser as well. So, if we navigate the page (in my case is http://localhost:34133/api/product), I will get back the list of products.

GET a single product

This is the code that will return one single product:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// GET api/product/5
public Product Get(int id)
{
    Product product = repository.GetProduct(id);
 
    if (product == null)
    {
        throw new HttpResponseException(
            Request.CreateResponse(HttpStatusCode.NotFound));
    }
    else
    {
        return product;
    }
}

The important bit in this case is that if the PRODUCT id is not found, we are going to throw an error of type HttResponseException. HTTP REsponse in this case will be “Not Found” message.

This is what happens when we are searching for an existing product:

Get single Product

and in case the product doesn’t exists (for this we will use a debugging tool called Advanced Rest Client which runs in the Chrome browser in order to test the output.).
As you see the status returned is 404 Not found, with the empty content.

POST

In order to create new content, we are going to use the POST mechanism to send the data to the server.
This is the code in the service that would create a new Product

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// POST api/product 
public HttpResponseMessage Post(Product product)
{
    if (ModelState.IsValid)
    {
        // this will set the ID for instance...
        product = repository.AddProduct(product);     
 
        var response = Request.CreateResponse(
                             HttpStatusCode.Created, product);
 
        string uri = Url.Link("DefaultApi", new {id = product.Id});
        response.Headers.Location = new Uri(uri);
        return response;
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}      

Creating a new resource involves few steps:
1. The client should send a POST request to api/product to create the resource.
2. REST Service should then return a 201 Created HTTP response, with the URI of the newly created resource in the Location header.
3. In case of errors “Bad Request” will be returned to the client.

as shown in the image below, the status HTTP 201 Created together with the actual data is returned to the client application.

Posting a new product

Let’s check if the product has been actually created by using the browser:
Get the list with the newly created product

as you may see, the Product with the id 6 is created.

PUT

In order to update an existing product we are going to use the PUT method. Code in the service is defined as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// PUT api/product/5
public HttpResponseMessage Put(int id, Product product)
{
    if (ModelState.IsValid && id == product.Id)
    {
        var result = repository.Update(id, product);
        if (result == false)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
        return Request.CreateResponse(HttpStatusCode.OK);
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}

Note the following:
1. There are two parameters. One is the ID of the product we are going to update, and the second parameter is the actual object itself.
2. If we try to update a non existing object, the HTTP code Not Found will be returned to the client
3. If there is any error happening to the code we return Bad Request
4. If all goes well the HTTP status returned is 200 OK
5. The return parameter is of type HttpResponseMessage. We are only returning the status not the content.
6. Is not needed to return any Location as in the previous example as know it already. The same comes with the content.

Let’s see this visually:

Posting an update to an existing product will look like this. (Note that the Name of the product changed to be “Monitor”).

in case we try to update a non-existing product. Notice in the address bar, we are trying to update a product with the id = 11 that doesn’t exists. In that case we are returning HTTP status of 404 Not found.

DELETE

To delete an already existing object we need to pass only the actual ID, as defined in the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// DELETE api/product/5
public HttpResponseMessage Delete(int id)
{
    Product product = repository.GetProduct(id);
 
    if (product == null)
    {
        return Request.CreateResponse(HttpStatusCode.NotFound);
    }           
 
    try
    {
        repository.Delete(id);
    }
    catch (Exception exc)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
 
    return Request.CreateResponse(HttpStatusCode.OK, product);
}

Note the following:
1. If product we want to delete is not there we return 404 Not found
2. If there is an exception we raise Bad Request
3. In case everything goes well, we return the 200 OK together with the object data, as the client would potentially need to display some information about the product itself.

Product deleted and the status returned as 200 OK.

When trying to delete a non existing resource the status 404 Not Found is returned.
Delete a non existing product.

Complete code

In order to make it easier for you, here is the full source code of the service.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
public class ProductController : ApiController
{
    private readonly ProductContext repository = new ProductContext();
 
    // GET api/values
    public IEnumerable<Product> Get()
    {
        return repository.GetProducts();
    }
 
    // GET api/product/5
    public Product Get(int id)
    {
        Product product = repository.GetProduct(id);
 
        if (product == null)
        {
            throw new HttpResponseException(
                Request.CreateResponse(HttpStatusCode.NotFound));
        }
        else
        {
            return product;
        }
    }
 
    // POST api/product 
    public HttpResponseMessage Post(Product product)
    {
        if (ModelState.IsValid)
        {
            // this will set the ID for instance...
            product = repository.AddProduct(product);
 
            var response = Request.CreateResponse(
                              HttpStatusCode.Created, product);
 
            string uri = Url.Link("DefaultApi", new {id = product.Id});
            response.Headers.Location = new Uri(uri);
            return response;
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }
 
    // PUT api/product/5
    public HttpResponseMessage Put(int id, Product product)
    {
        if (ModelState.IsValid && id == product.Id)
        {
            var result = repository.Update(id, product);
            if (result == false)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }
 
    // DELETE api/product/5
    public HttpResponseMessage Delete(int id)
    {
        Product product = repository.GetProduct(id);
 
        if (product == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
 
        try
        {
            repository.Delete(id);
        }
        catch (Exception exc)
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
 
        return Request.CreateResponse(HttpStatusCode.OK, product);
    }
}

Conclusion

ASP.NET Web API is a very versatile framework that allow us to create RESTful services in a very easy way without going through much pain when compared to the WCF configuration part for example.
The simplicity of HTTP statuses makes the development even more simple.

Note: The above information is provided “As Is” basis. The origal content is from
http://www.agile-code.com