2LeggedSpider

ASP.NET Web API Video Series

Posted in Daily Links by Sumit Thomas on March 6, 2012
Tagged with: , ,

Coffee break

Posted in Coffee Break, technology by Sumit Thomas on March 3, 2012
Tagged with: , ,

Coffee break

Posted in ASP.NET, Coffee Break, jquery, Microsoft, MVC by Sumit Thomas on March 2, 2012
Tagged with: , ,

Getting specific with the Specification Pattern

Posted in C#, patterns by Sumit Thomas on March 23, 2011

The idea of Specification pattern according to Martin Fowler is to separate the statement of how to match a candidate, from the candidate object that it is matched against. As well as its usefulness in selection, it is also valuable for validation and for building to order.

In simple terms it means this pattern helps us to check if an object satisfies certain criteria. Well, we do that all the time in our code don’t we? For instance, we check if the data in an object that we send to a web service or database is properly validated against a business rule. We check for certain conditions on an object’s property to fetch subset of objects from a collection using say LINQ etc etc. Since we already do these things, why do we need a separate pattern to do the same?

Well the biggest advantage of Specification pattern is that we can create compartments of criteria definitions and check them against an object wherever the need arises. We then have the flexibility to change the criteria definitions in one single place as per the business requirement instead of changing it all the places where such criteria would had been used, if we didn’t use specification pattern. OK enough theory, lets see how we can implement the Specification pattern to understand it better.

We’ll start by creating the Core framework for the Specification. Lets create an Interface ISpecification with the following definition

public interface ISpecification<T>
{
     bool IsSatisfiedBy(T t);
}

Now as I mentioned earlier, we can check if an object satisfies a certain condition or a set of conditions. In order to make it easy for us we’ll create classes which will help us perform the logical And, Or and Not operations on an object with the available suggestions.

    public class AndSpecification<T> : ISpecification<T>
    {
        private readonly ISpecification<T> spec1;
        private readonly ISpecification<T> spec2;
        public AndSpecification(ISpecification<T> s1, ISpecification<T> s2)
        {
            spec1 = s1;
            spec2 = s2;
        }

        public bool IsSatisfiedBy(T t)
        {
            return spec1.IsSatisfiedBy(t) && spec2.IsSatisfiedBy(t);
        }

    }

    public class OrSpecification<T> : ISpecification<T>
    {
        private readonly ISpecification<T> spec1;
        private readonly ISpecification<T> spec2;
        public OrSpecification(ISpecification<T> s1, ISpecification<T> s2)
        {
            spec1 = s1;
            spec2 = s2;
        }

        public bool IsSatisfiedBy(T t)
        {
            return spec1.IsSatisfiedBy(t) || spec2.IsSatisfiedBy(t);
        }
    }

    public class NotSpecification<T> : ISpecification<T>
    {
        private readonly ISpecification<T> spec;
        public NotSpecification(ISpecification<T> spec)
        {
            this.spec = spec;
        }

        public bool IsSatisfiedBy(T t)
        {
            return !spec.IsSatisfiedBy(t);
        }
    }

Next we will create extension methods that will help us to chain together required specifications.

    public static class SpecExtensions
    {
        public static ISpecification<T> And<T>(this ISpecification<T> s1, ISpecification<T> s2)
        {
            return new AndSpecification<T>(s1, s2);
        }
        public static ISpecification<T> Or<T>(this ISpecification<T> s1, ISpecification<T> s2)
        {
            return new OrSpecification<T>(s1, s2);
        }
        public static ISpecification<T> Not<T>(this ISpecification<T> s)
        {
            return new NotSpecification<T>(s);
        }
    }

That pretty much forms the core implementation of Specification pattern. Now lets get in to the fun part where we will put the specification pattern in use.

Lets assume that you are creating a module for fictional employee management application to determine the qualification of employees in order to promote them to managers. Lets start by creating a Employee class as follows

    public class Employee
    {
        public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int TotalExperience { get; set; }
        public ExcelCompetency ExcelCompetency { get; set; }
        public bool PotentialManager
        {
            get
            {
                if (ExcelCompetency == Domain.ExcelCompetency.High || ExcelCompetency == Domain.ExcelCompetency.Medium)
                    return true;

                return false;
            }
        }
    }

Here ExcelCompetency is an enum with values High, Medium and Low. Assume that the specification provided to you is that only Employees with High or Medium competency in Excel can become Managers. The property PotentialManager checks this condition and returns a boolean based on the value assigned for ExcelCompetency.

Though the property PotentialManager would help us in fetching a subset of employees qualified to be a manager from a list of employees, the actual condition we used inside this property might be used elsewhere in our application. In such cases, if the company decides later that employees with only High ExcelCompetency can become managers then we would have to change the condition wherever it is implemented. That is not ideal. This is where Specification pattern could be used.

Lets start by creating our own implementation of Specification framework.

    public class PotentialManagerSpecification : ISpecification<Employee>
    {
        public bool IsSatisfiedBy(Employee employee)
        {
            if (employee.ExcelCompetency == ExcelCompetency.High || employee.ExcelCompetency == ExcelCompetency.Medium)
                return true;
            return false;
        }
    }

Now our PotentialManager property could be changed to…

        public bool PotentialManager
        {
            get
            {
                var  potentialManagerSpec = new PotentialManagerSpecification();
                if (potentialManagerSpec.IsSatisfiedBy(this))
                    return true;
                return false;
            }
        }

Now the condition for satisfying a requirement will lie independent of the entity object and can be changed anytime without touching the entity.

Now lets assume that the management has laid down a condition that managers should not only have High Excel competency but also should have more than 10 years of experience. To satisfy this condition lets create another specification ManagerRequiredExperienceSpecification

    public class ManagerRequiredExperienceSpecification : ISpecification<Employee>
    {
        public bool IsSatisfiedBy(Employee employee)
        {
            if (employee.TotalExperience > 10)
                return true;
            return false;
        }
    }

We’ll create a test method to test these specifications

[TestMethod]
public void ManagerSelection_Test()
{
Employee abc = new Employee(){ FirstName="ABC", ExcelCompetency = ExcelCompetency.Medium, TotalExperience = 12};
Employee def = new Employee(){ FirstName = "DEF", ExcelCompetency = ExcelCompetency.High, TotalExperience = 11};
Employee qrs = new Employee(){ FirstName = "QRS", ExcelCompetency = ExcelCompetency.High, TotalExperience = 8};
Employee xyz = new Employee(){FirstName = "XYZ", ExcelCompetency = ExcelCompetency.Low, TotalExperience = 10};

IList employees = new List()
{
  abc, def, qrs, xyz
};

PotentialManagerSpecification managerSpec = new PotentialManagerSpecification();
ManagerRequiredExperienceSpecification experienceSpec = new ManagerRequiredExperienceSpecification();

foreach(Employee e in employees){
    System.Diagnostics.Debug.WriteLine(
      "{0} is {1} to be a Manager",
       e.FirstName,
       managerSpec.And(experienceSpec).IsSatisfiedBy(e) ? "qualified" : "not qualified"
       );
}
}

If you run the above test, your Debug trace will show the following output

ABC is qualified to be a Manager
DEF is qualified to be a Manager
QRS is not qualified to be a Manager
XYZ is not qualified to be a Manager

You can see in the line managerSpec.And(experienceSpec).IsSatisfiedBy(e) how we have used the extension method ‘And’.

Based on the requirement we can use the extension methods as follows.

  • managerSpec.And(experienceSpec).IsSatisfiedBy(e) -> Employee satisfies both PotentialManagerSpecification and ManagerRequiredExperienceSpecification
  • managerSpec.Or(experienceSpec).IsSatisfiedBy(e) -> Employee satisfies either PotentialManagerSpecification or ManagerRequiredExperienceSpecification
  • managerSpec.And(experienceSpec.Not()).IsSatisfiedBy(e) -> Employee satisfies PotentialManagerSpecification but not ManagerRequiredExperienceSpecification

As you can see the possibilities are limitless. If you want to create a new specification which handles both PotentialManagerSpecification and ManagerRequiredExperienceSpecification then we can also do so as follows

    public class ManagerSelectionSpecification : ISpecification<Employee>
    {
        public bool IsSatisfiedBy(Employee employee)
        {
            PotentialManagerSpecification managerSpec = new PotentialManagerSpecification();
            ManagerRequiredExperienceSpecification experienceSpec = new ManagerRequiredExperienceSpecification();

            if (managerSpec.And(experienceSpec).IsSatisfiedBy(employee))
                return true;

            return false;
        }
    }

We can also use specifications to perform validation before saving information in database for instance

var managerSelectionSpec = new ManagerSelectionSpecification();
if(managerSelectionSpec.IsSatisfiedBy(employee)
{
      PromoteToManager();
}

Or in LINQ as follows

 var managers = from e in employees
                           where managerSelectionSpec.IsSatisfiedBy(e)
                           select e;

Pretty neat isn’t it? I hope you found it useful as I did.

Some useful links…

Specifications by by Eric Evans and Martin Fowler

Repository, Specification, Unit of Work, Persistence Ignorance POCO with Microsoft ADO.NET Entity Framework 4.0 Beta 2

Learning the Specification Pattern

Visual Studio color schemes – Its time for a makeover

Posted in Tips, Visual Studio by Sumit Thomas on March 23, 2011

http://studiostyl.es/ is a great website where you can browse for hundreds of color schemes to change the background and text colors of your Visual Studio IDE. It works for both Visual Studio 2008 and 2010. You can also create and submit your own scheme or download and rate schemes submitted by others.

Once you have picked your favorite scheme, download it to your Visual Studio settings folder C:\Users\[user_name]\Documents\visual studio 2010\settings

To apply the scheme go to Tools -> Import and Export Settings menu and follow these steps

Once you complete the steps, you will see a brand new color scheme applied to your Visual Studio text editor.

Now don’t be surprised if you find a fellow developer’s Visual Studio with a Barbie girl scheme ;)

StyleCop 4.5 Beta is out!

Posted in C#, Microsoft, Tips, Visual Studio by Sumit Thomas on March 21, 2011

You can download it @ http://stylecop.codeplex.com/releases/view/62209

If you are not aware of StyleCop, it is an open source static code analysis tool from Microsoft which helps developers analyse their C# code for conformance to StyleCop recommended coding styles and it works at the source code level.

For more information on this community driven project visit http://stylecop.codeplex.com/

links for 2010-01-11

Posted in Daily Links by Sumit Thomas on January 11, 2010

Create a custom Outlook holiday file

Posted in Tools by Sumit Thomas on January 8, 2010

Like many of my friends, the first thing I check at the start of the year is the list of public holidays for that year. Outlook’s holiday feature comes really handy as it makes it convenient for me to update my Calendar with a predefined list of holidays.

To add a predefined holiday list to your Outlook calendar go to Tools -> Options -> Calendar Options -> Add Holidays and select your country and click OK.

The predefined holiday list is stored in the file  Outlook.hol which is called as the Outllook holiday file.

You don’t have to stick to the predefined list as you can edit this file and add your custom holidays using a notepad.

A holiday file has the following format…

[Section Name] [Number of Holidays]
Holiday Description, yyyy/mm/dd
Holiday Description, yyyy/mm/dd
Holiday Description, yyyy/mm/dd
and so on..

You can have as many sections as you want.

So what if you want to create your Company specific holiday list? Suppose there is a fictional company ABC, which has branches in Chennai, Bangalore and US. You can create a custom holiday file for this company which can be distributed to all its employees. To do so…

  1. Open notepad and paste the following…
    [ABC Bangalore Office 2010] 15
    Makara Sankranthi    ,2010/1/14
    Republic Day        ,2010/1/26
    Maha Shivarathri    ,2010/2/12
    Ugadi            ,2010/3/16
    Good Friday        ,2010/4/2
    May Day            ,2010/5/1
    Independence Day    ,2010/8/15
    Janmashtami        ,2010/9/1
    Id-ul-fitr (Ramzan)     ,2010/9/10
    Gandhi Jayanti        ,2010/10/2
    Vijaya Dashami        ,2101/10/17
    State Formation Day    ,2010/11/1
    Deepavali        ,2010/11/5
    Bakrid            ,2010/11/17
    Christmas        ,2010/12/25
    
    [ABC Chennai Office 2010] 13
    Pongal            ,2010/1/14
    Republic Day        ,2010/1/26
    Maha Shivarathri    ,2010/2/12
    Good Friday        ,2010/4/2
    May Day            ,2010/5/1
    Independence Day    ,2010/8/15
    Janmashtami        ,2010/9/1
    Id-ul-fitr (Ramzan)     ,2010/9/10
    Gandhi Jayanti         ,2010/10/2
    State Formation Day    ,2010/11/1
    Deepavali        ,2010/11/5
    Bakrid            ,2010/11/17
    Christmas        ,2010/12/25
    
    [ABC US Office 2010] 11
    Memorial Day        ,2010/5/31
    Independence Day    ,2010/7/5
    Labor Day        ,2010/9/6
    Thanksgiving Holiday    ,2010/11/25
    Thanksgiving Holiday    ,2010/11/26
    US Corporate Holiday    ,2010/12/20
    US Corporate Holiday    ,2010/12/21
    US Corporate Holiday    ,2010/12/22
    US Corporate Holiday    ,2010/12/23
    US Corporate Holiday    ,2010/12/24
    New Year's Eve        ,2010/12/31
  2. Save this file as ABC 2010 Holidays.hol

To use this file just double click and select the sections you want to add to your Calendar.

This file can be distributed to all the ABC employees through email or a shared location.

Hope you found it useful!

Tagged with: ,

Spark View Engine for ASP.NET MVC

Posted in ASPNETMVC, MVC by Sumit Thomas on January 5, 2010

There’s been a lot of buzz around the new View Engine for ASP.NET called Spark. Spark is an open-source ASP.NET ViewEngine developed by Louis DeJardin (Listen to the conversation between Scott Hanselman and Louis DeJardin to get some insights on Spark). Spark works for both Monorail and ASP.NET MVC supporting C#, VB, IronPython and IronRuby.

There are other ViewEngines already available as an alternative to the default ASP.NET MVC ViewEngine. Honestly I have not tried anyone of them and I surely don’t have any clue as to whether they are better or worse compared to Spark. Well, I just like everyone else decided to follow the buzz and try out Spark.

I decided to develop a simple RSS Reader using ASP.NET MVC and with Spark as its ViewEngine. I am using the Spark documentation as reference for my experiment.

Lets look at how a Spark View differs from the regular ASP.NET MVC View. Consider the following View which we are familiar with…

 <%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>" %>
 <% if (Model.Count() > 0)
   { %>
<% foreach (var product in Model)
   { %>
<li>
    <%= product.Name %>
</li>
<% } %>
<%}
   else
   {%>
<p>
    No products available</p>
<%} %>

The equivalent Spark View would be…

<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
  <li each="var p in products">${p.Name}</li>
</ul>
<else>
  <p>No products available</p>
</else>

As you can see it is much cleaner and readable than the regular View. Checkout the Spark syntax in detail. Spark makes is really simple to data bind HTML elements to objects from the Controller.

Configuring ASP.NET MVC Project to use Spark ViewEngine

With this background on Spark, lets jump straight in to the task of configuring a ASP.NET MVC Web application to use Spark as its default ViewEngine.

Step 1: Download the Spark binaries from here. Extract the zip file and locate the bin folder.

Step 2: Create a new ASP.NET MVC Web Application and add reference to the assemblies Spark.dll and Spark.Web.Mvc.dll

Spark reference

Step 3: Add Spark to the ViewEngine collection in the Application_Start section of Global.asax

        protected void Application_Start()
        {
            ViewEngines.Engines.Add(new SparkViewFactory());
            RegisterRoutes(RouteTable.Routes);
        }

Your application is now ready for Spark!

Step 4: You may also add the following configuration settings in your web.config

	<configSections>
		<section name="spark" type="Spark.Configuration.SparkSectionHandler, Spark"/>
	</configSections>
	<spark>
		<compilation debug="true"/>
		<pages automaticEncoding="true">
		<namespaces>
                <add namespace="System.Web.Mvc"/>
                <add namespace="System.Web.Mvc.Ajax"/>
                <add namespace="System.Web.Mvc.Html"/>
                <add namespace="System.Web.Routing"/>
                <add namespace="System.Linq"/>
                <add namespace="System.Collections.Generic"/>
		</namespaces>
		</pages>
	</spark>

Another way of providing the Spark Engine settings is by creating an instance of ISparkSettings and passing it to the constructor of SparkViewFactory…

protected void Application_Start(object sender, EventArgs e)
{
    var settings = new SparkSettings()
        .SetDebug(true)
        .AddNamespace("System.Web.Mvc")
        .AddNamespace("System.Web.Mvc.Ajax")
        .AddNamespace("System.Web.Mvc.Html")
        .AddNamespace("System.Web.Routing")
        .AddNamespace("System.Linq")
        .AddNamespace("System.Collections.Generic");

    ViewEngines.Engines.Add(new SparkViewFactory(settings));
}

Thats all you have to do in terms of setting up the MVC Web application to use Spark ViewEngine.

Spark View Layouts

So far we have only configured the application to use Spark ViewEngine. Spark Views have a different extension from the regular ASP.NET MVC Views and as we saw already, they have a different syntax as well. Spark Views have the extension .spark. The way Spark ViewEngine deals with Master pages is also different. Lets look at it…


Master Pages

Application.spark – This is the application wide Master page which will be used by the Spark Engine. It could be place in Views/Layouts folder or Views/Shared folder.

[ControllerName].spark – If you need to use a Master page for individual Controllers then you can create a spark file with the name of the Controller. For instance if you have a HomeController then Views/Layouts/Home.spark or Views/Shared/Home.spark would be Master page for that Controller.

Check the Selecting Layout section in Spark documentation for more details.


Partial Views or User Controls

Any partial view prefixed with an underscore can have its own tag in Spark. For instance if we have a Partial View _LogOnUserControl.spark then we can refer to it in the Spark View as <LogOnUserControl />. If you don’t like this convention then you can remove the underscore and refer to the Partial View as <use file=”LogOnUserControl” />

With these changes in place our Views layout will look like this…

Spark View Layout

Let’s look at the individual Spark Views as to how they differ from the regular Views that you get when you create a new ASP.NET MVC Web Application.


Application.spark (replaces Site.master)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>
        <use content="title">Default title</use>
    </title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="page">
        <div id="header">
            <div id="title">
                <h1>
                    My MVC Application</h1>
            </div>
            <div id="logindisplay">
                <LogOnUserControl" /> // or <use file="_LogOnUserControl" />
            </div>
            <div id="menucontainer">
                <ul id="menu">
                    <li>!{Html.ActionLink("Home", "Index", "Home")}</li>
                    <li>!{Html.ActionLink("About", "About", "Home")}</li>
                </ul>
            </div>
        </div>
        <div id="main">
            <use content="view" />
            <div id="footer">
            </div>
        </div>
    </div>
</body>
</html>

We can create Home.spark as well in the same manner.


Index.spark(replaces Index.aspx)

<content name="title">
       Home Page
</content>
<h2>
    ${ViewData["Message"]}</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">

http://asp.net/mvc</a>.

</p>


_LogOnUserControl.spark(replaces LogOnUserControl.ascx)

<if condition="Request.IsAuthenticated">
    Welcome <b>${Context.User.Identity.Name}</b>!
    [ !{Html.ActionLink("Log Off", "LogOff", "Account")} ]
</if>
<else>
    [ !{Html.ActionLink("Log On", "LogOn", "Account")} ]
</else>

Run the application and you will see the usual ASP.NET MVC Web Application’s home page but rendered using Spark ViewEngine. From what I have seen so far Spark looks promising and would be a great alternative for those who feel the default ViewEngine forces them to go back to the classic ASP days. I haven’t completely gone through all the possibilities in Spark and would like do so in the next few days.

Share your thoughts on Spark or any other ViewEngines you may have used.

Tagged with: , ,

links for 2010-01-04

Posted in Daily Links by Sumit Thomas on January 4, 2010
Follow

Get every new post delivered to your Inbox.