Archive

Author Archive

Using Specification Pattern with ASP.NET MVC, Repository Pattern–Part 3

May 20, 2011 Leave a comment

In the Part 1, I discussed the basics of Specification Pattern. In Part 2, I discussed about utilizing the power of LINQ and Expression Trees to implement this pattern. In this post, I am going to walkthrough an ASP.NET MVC application which will use Specification pattern with Repository Pattern. I am going to use AdventureWorks database for the sample. You can download the sample database from here.

Step 1: Create a ASP.NET MVC project

We will start by creating new ASP.NET MVC 3 project using File-New Project menu command.

image

We’ll use the “Internet Project” template – which will provide us with a default starter template for our application.  I am also going using Razor view engine for the sample.

image

Step 2: Create a EF Model from AdventureWorks database

Add a new ADO.NET Entity model item by right clicking Model folder and select Add-> New Item menu command.

image

Let us name the model as AdvWorksModel.edmx.

image

Now it will pop-up another window, from which we need to generate the model from AdventureWorks database. Let us just select the Product table from the list of tables as show below.

image

Now you can see the Product entity is generated and shown in the EF designer.

image

Step 3:  Implementing Specification Pattern

We will need to implement the specification pattern as a core component (Typically it should be part of Domain core assembly but I am just adding a folder in this sample application) before implementing Repository Pattern. If you are not familiar with Repository pattern, you can read about the Repository Pattern here. Briefly the Repository Pattern helps to decouple Persistence logic away from your domain. It is key component of your infrastructure plumbing code.

First, we will expand the Specification abstract class that we defined in Part 2. We are going to add Add, Or and Not operations to the Specification abstract class to support composite specifications. Soon you will understand how we are going to use composite specification in querying database.

The modified Specification class:

image

Next we are going to implement AndSpecification, OrSpecification and NotSpecification. There are critical classes required to apply composite specifications for a LINQ query.  Please note that it is not straight forward to implement ‘And ‘ and ‘Or’ specifications. I have borrowed the utility classes used in this post to implement because we have to actually do AND’ing and OR’ing the expression trees.  These classes are implemented in ExpressionBuilder.cs and ParameterRebinder.cs. Please refer to the sample code.

I am going just show you the AndSpecification. ‘Or’ is quite similar and ‘Not’ is easy to implement.

image

 

If you note the last line of code return left.And(right), it is actually called the extension method in ExpressionBuilder class to perform the And of left and right side expressions.

Step 4: Implementing Repository Pattern

Let us turn our focus to implement the repository pattern. We are going to implement the generic repository class which will have method specific to database operations for entities.

image

If you look at the generic repository implementation above, it have just one method which accepts a specification object to execute the query against the database. In real world implementations, you will be ideally adding many more methods like Add, Delete, Update etc. to this repository class. I also have created a specific repository class for Product, called ProductRepository which has the method called FindProducts.  It is actually not necessary to create such concrete class unless you are implementing methods which are very very specific to Product Entity. You actually need to include all the common database methods in generic repository.  I have included this class just for illustration purposes only.

Step 4: Concrete Specification Classes

Now we need to implement couple of concrete Specification classes which will have business logic to query the database.  I have added to classes here, one is ProductPriceSpecification which takes min and max list price, should return Products between these prices.

Another specification is ProductSafetyStockLevelSpecification which takes the stock level as a parameter to compare against the product stock level. The implementations of both of these classes are straight forward.

image

image

 

Step 4: Implementing the ASP.NET MVC Controller

If you are using ASP.NET MVC 4 Tools Update, you can easily create the controller class and respective razor views using Data Scaffolding feature. It just take couple of minutes to do that. I have used this feature to create the controller class and the corresponding views (razor).  You can read this post to understand how to use the Data Scaffolding feature of ASP.NET MVC 3.

Let us implement the Index method of ProductController class. Please note that I have removed other other methods created by the data scaffolding generator for simplicity.

image

If you note that, we are not using the Specification objects to query the database yet. We have just returns the top 25 of the result set. Let see what we got on the screen:

 

image

Now let us do some filtering of Product records for SafetyStockLevel and ListPrice columns using our concrete Specifications. We need to modify the Index method to do this. Please note that in real world you probably will have a Services layer at the controller level which will coordinate the call to repository etc..

 

image

We are using our Specification objects to filter by records by SafetyStockLevel = 500 and ListPrice is between 50 – 100.   Let us see what we got in the result:

 

image

Great, we have successfully used the specification objects to filer the records. I hope you now have the understanding of how to implement Repository and Specification pattern.

Summary

In this post, I have shown how to implemented all the core classes required for Specification along with Repository pattern. I have also showed how to use this in an ASP.NET MVC application.

Hope this helps.

Categories: Windows Azure

Understanding Specification Pattern (with LINQ) –Part 2

May 11, 2011 Leave a comment

I have covered the basics of Specification pattern in Part1. A specification is basically used as filters to query database and each specification filter is implemented as objects. Actually it should be also implemented as immutable objects.

If you think deeply, using specification objects as filters require that first we need to query the database to retrieve the results as list of objects. And then apply the specification filter on those list of objects. This may work for small applications but would be problem for application handling large amount of data. For example, think about a scenario where you need to apply a specification filter for customer list which may have millions of rows.

There is an implementation that can be done using double dispatch pattern. But better yet is to harness the power of LINQ and Expression Trees for efficient implementation. The idea is to use the expression tree as predicate that the specification object encapsulates.

The expression tree provides a method to translate executable code into data. The O/R mappers like Entity Framework, LLBLGen Pro and LINQ to SQL have the ability to traverse the expression tree and transform that into SQL statements. I recommend you must read the basics of Expression Tree. Now I believe you are getting a feel of how to utilize the power of expression trees.  Let us now modify the ISpecification interface that we created in Part1.

If you refer back the Part1, we have implemented the interface like this:

1

We will change the IsSatisfiedBy (to IsSatisfied) method to return an generic Expression Tree as shown below. We will also create a Specification abstract class which implements ISpecification interface.

image

We will now do necessary changes to EligibleForDiscountSpecification class.

image

Note the property setter is private. This is because as per pattern design, the specification object should be immutable.

Let us now see how to use the EligibleForDiscountSpecification. Please note that I am using AdventureWorks database for the demo. I have created EF model which consists of Product and Customer table.

image

I guess now you can understand the power of expression and how to use that with Entity Framework.

Summary

I covered how to implement Specification pattern using Expression tree and LINQ. In the next part of the series, we will expand the Specification interface to implement composite specification.  In future post, I will run through a ASP.NET MVC application which will explain how to use Repository pattern with Specification pattern.

Understanding Specification Pattern–Part 1

May 8, 2011 Leave a comment

Introduction

I would like to mention couple of terms before getting into details of Specification Pattern. This is simply because some developers may not aware of these. The first is DDD. Domain Driven Design is an approach for developing software by creating model that is closely matching the domain of the core business. The second is SRP (Single Responsibility Principle).It states that object should have only one reason to change. In other words, an should have just one responsibility. The Specification Pattern encapsulates just one piece of logic. It is recommended to read these posts. The Specification Pattern is mostly used in DDD based projects.

Mostly developers implement the business logic in the entity itself. This is not an ideal option because as we put more and more logic in the entity, it becomes unmaintainable.  The Specification Pattern, implemented as an Object, enable entities to split the business logic in its own. The Specification Object typically have an IsSatisfiedBy method that takes a domain object and return a Boolean value.

For example, we have a Product entity, and we need to be able to check if this product is eligible for discount between certain dates.

Implementing Specification Pattern

Let us look at the basic implementation of the pattern.

public interface ISpecification<T>
{
        bool IsStatisfiedBy(T candidate);
}

Let us know implement the discount specification class.

public class EligibleForDiscountSpecification : ISpecification<Product>
  {
      public bool IsStatisfiedBy(Product prod)
      {
          return (DateTime.Now.Date >= prod.SaleStartDate && DateTime.Now.Date <=

                prod.SaleEndDate );
      }
  }

Now you can just pass the Product object to EligibleForDiscountSpecification.IsSatisfiedBy method and this clearly separate the logic from Product entity. Here is how you can use this Specification object:

var spec = new EligibleForDiscountSpecification();

If(spec.IsSatisfiedBy(product))

{

       ….

}

Typically you use this Specification pattern to select items from the collection. For example, if you want to find the list of products currently on sale, you can do like this:

public IEnumerable<Product> GetAllProductsInSale(IList<Products> products,

ISpecification<Product> spec)

{

          foreach(var prod in products)

         {

              if (spec.IsSatisfiedBy(prod))

                         yield return prod;

        }

}

 

Chaining Specifications

We can actually chain specifications to create composite specifications. This is very powerful method to create complex business rules that involve several rules to that could be nested together. Let us now see how to implement this.

public interface ISpecification<T>
{
        bool IsStatisfiedBy(T candidate);

        ISpecification<T> And(ISpecification<T> other);                                                       

        ISpecification<T> Or(ISpecification<T> other);

        ISpecification<T> Not();
}

 

public abstract class CompositeSpecification<T> : ISpecification<T>
    {
        public abstract bool IsSatisfiedBy(T candidate);

        public ISpecification<T> And(ISpecification<T> other)       

       {
            return new AndSpecification<T>(this, other);
        }

        public ISpecification<T> Or(ISpecification<T> other)       

        {
            return new OrSpecification<T>(this, other);
        }

        public ISpecification<T> Not()       

        {
            return new NotSpecification<T>(this);
        }
    }

 

public class AndSpecification<T> : CompositeSpecification<T>
  {
      private readonly ISpecification<T> left;
      private readonly ISpecification<T> right;

      public AndSpecification(ISpecification<T> left, ISpecification<T> right)
      {
          this.left = left;
          this.right = right;
      }

      public override bool IsSatisfiedBy(T candidate)
      {
          return left.IsSatisfiedBy(candidate) && right.IsSatisfiedBy(candidate);
      }
  }

 

public class OrSpecification<T> : CompositeSpecification<T>
    {
        private readonly ISpecification<T> left;
        private readonly ISpecification<T> right;

        public OrSpecification(ISpecification<T> left, ISpecification<T> right)
        {
            this.left = left;
            this.right = right;
        }

        public override bool IsSatisfiedBy(T candidate)
        {
            return left.IsSatisfiedBy(candidate) || right.IsSatisfiedBy(candidate);
        }
    }

 

 public class NotSpecification<T> : CompositeSpecification<T>
    {
        private readonly ISpecification<T> other;

        public NotSpecification(ISpecification<T> other)
        {
            this.other = other;
        }

        public override bool IsSatisfiedBy(T candidate)
        {
            return !other.IsSatisfiedBy(candidate);
        }
    }

Summary

In this post, I have covered the basics of Specification pattern and provided code snippets. Also I have covered the composite specification and how it is very powerful to implement complex business rules. I will cover some advanced topics in Part 2 of the Specification Pattern which covers how to use this specification pattern with EntityFramework, LINQ.

Understanding Windows Azure Storage–Tables

April 30, 2011 Leave a comment

Windows Azure is the “Operating System for the Cloud” that provides building blocks for developers to write scalable applications. Windows Azure Storage allows developers to store the data in the cloud. The data can be accessed from anywhere at any time, and store any amount of data.  It is important to note that SQL Azure is the different from Azure Storage Services . The SQL Azure is essentially SQL Server in the Microsoft Cloud space (with limitations).

I will be only discussing Tables in this post. I have also provided a walkthrough which covers how to use Table Storage API using an Console application. I will cover Blob and Queue in future posts

Windows Azure Storage Services Overview

The following types of storage are available in Windows Azure Storage Services:

1. Blob – storage for large data items

2. Table – structured storage

3. Queue – asynchronous messages to enable service communication

Tables

It is worth pointing out that Azure Table supports highly scalable tables in the cloud. It supports up to 100 TB of data theoretically. The Tables contain set of Entities. Table names are scoped by Storage Account. We can have many tables for a Storage Account.

Entities (Rows) and Properties (Columns)

The Entities (equivalent to a “row”) are basic data items stored in the table. The Entities contain set of Properties. The Properties (equivalent to a “Column”) are <name,value> pairs. A rich set of data types are supported for Property values. Each Entity has two properties, namely “Partition Key and Row Key”. These two keys form the unique key for the entity.

Storage Account

A valid storage account is required to access Windows Azure Storage.  The account name is part of the host name in the URL. The host name for accessing tables is <accountName>.table.core.windows.net.

PartitionKey and RowKey Properties

It is very important to understand that choosing a PartitionKey is critical for the application to scale. This is because Windows Azure allows tables to scale out to thousands of storage nodes by distributing Entities in the table. When distributing the entities, it is desirable to ensure that a set of entities always stay together on a storage node.  An application controls this set by choosing an appropriate value for the PartitionKey property in each entity

The entities within the same partition are stored together.  This allows efficient querying within a partition.  Furthermore, your application can benefit from efficient caching and other performance optimizations that are provided by data locality within a partition.

As mentioned previously, PartitionKey and RowKey for the unique key for the Entity.

Walkthrough

I will now walkthrough a sample console application in which we are going use Table Services API to create a Entity, and will be adding couple of entities. Before we do that, you need to have valid Windows Azure Account. If you don’t have a account, there are couple of options.

1. You can get a free Windows Azure Pass from here. No credit card required!

2. You could use Storage Emulator. It is important to understand the differences between Windows Azure Storage Emulator and Windows Azure Storage Services.

Create a Console Project

I will first create a Console Project and add necessary references.

1

Once the project is created, go to Project Properties and change the Target Framework from .NET Framework Client Profile to .NET Framework 4 as shown below.

image

Add the following references to the project.

1. System.Configuration

2. System.Data.Services.Client

3. Microsoft.WindowsAzure.StorageClient (note this should be available in C:\Program Files\Windows Azure SDK\v1.3\bin)

Add ExpenseEntity class

Let us now add a new Entity class called ExpenseEntity by using Add->New Item menu. Once the class is created, make the class “public”.  Also add the following ‘using’ statements.

using Microsoft.WindowsAzure.StorageClient;

Now derive the class from Microsoft.WindowsAzure.StorageClient.TableServiceEntity. Note that this TableServiceEntity class have already defined key properties PartitionKey and RowKey. Add the following code snippet into the ExpenseEntity class.

image

As discussed before, choosing the PartitionKey and RowKey is application’s responsibility. I have used month for PartitionKey so that data for each month is in one partition. I have used date + Guid for RowKey.

Add ExpenseDataSource class

Let us now add a new class called ExpenseDataSource by using Add->New Item menu. Once the class is created, make the class “public”.  Also add the following using statements.

using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

In this class, we are going setup the Storage Account, create the table and have couple of methods to query and add Expense Entity.

Add the following variables to the class:

private static CloudStorageAccount storageAccount;                                                         private TableServiceContext context;

Add the following code in the static constructor to initialize the storage account and create the table.

 

2

It is important to understand the FromConfigurationString method. It actually does not directly read from the configuration table. We have to call SetConfigurationSettingPublisher in CloudStorageAccount class to set up the Action<> delegate which will be ultimately called to get the connection string. So we have to place this call in main() method in the Console Application.

We will now setup the TableServiceContext in the constructor.

this.context = new TableServiceContext(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);

this.context.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(1));

Now add the methods to add Expense Entity and select entities.

public void AddExpenseEntity(ExpenseEntity newItem)
      {

          this.context.AddObject("Expenses", newItem);
          this.context.SaveChanges();
      }

      public IEnumerable<ExpenseEntity> Select()
      {
          IQueryable<ExpenseEntity> expenses =  this.context.CreateQuery<ExpenseEntity>("Expenses");
          var results = from g in expenses
                        where g.PartitionKey ==
              DateTime.UtcNow.ToString("MM")
                        select g;
          return results;

      }

Now that we are done with ExpenseDataSource class, let us add some code in main() to add entities and select entities.

Setting up the app.config

Before we do that, it is important to setup the Azure account information in configuration file (app.config). We can an add an entry to <appSettings> to setup the account information.

<appSettings>
    <add key="DataConnectionString"        value="DefaultEndpointsProtocol=https;AccountName=”<accountName>”;AccountKey=”<key"> />  </appSettings>

You need to replace the <accountName> and <key> with the correct data. This key can be retrieved from windows.azure.com. 

Main()

Add the following code in main().

//configure storage account
CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSettingPublisher) =>
                    {
                        var connectionString = ConfigurationManager.AppSettings[configName];
                        configSettingPublisher(connectionString);
                    }

  

//add couple of expense entries
           List<ExpenseEntity> expenses = new List<ExpenseEntity>
           {
               new ExpenseEntity() { Amount=100, Category="Dining", ExpenseDate=DateTime.Now.Date },
               new ExpenseEntity() { Amount=250, Category="Movie", ExpenseDate=DateTime.Now.Date }
           };

As mentioned previously, it is important to call SetConfigurationSettingPublisher at the start to read configuration information. We have then created two sample entity (rows).

Let us now add these entities to the table “Expenses”.

ExpenseDataSource dataSource = new ExpenseDataSource();
           foreach (ExpenseEntity expenseEntry in expenses)
               dataSource.AddExpenseEntity(expenseEntry);

 

Let us know retrieve the inserted entities and display.

foreach (ExpenseEntity item in dataSource.Select())
           {
               Console.WriteLine(string.Format("PartitionKey={0}, RowKey={1}, Amount={2}, Category={3}, ExpenseDate={4}",
                                                item.PartitionKey, item.RowKey, item.Amount, item.Category, item.ExpenseDate));
           }

Now run the application and you can see that we are able to add and retrieve the entities from Windows Azure Table Storage.

image

Summary

In this post, we have seen the basics of Windows Azure Table storage, setting up Storage Account and how to create and add entities to the table. In future posts, I will cover other storages like blob and queues. I will also cover some advanced topics in Table Storage.

Categories: Windows Azure Tags: