A day with .Net

My day to day experince in .net

Archive for June, 2014

New vending machine at office and Builder Design Pattern

Posted by vivekcek on June 28, 2014

Strong tea is my weakness, I tried all variations of tea’s described in the book ‘A Nice Cup of Tea’ by George Orwell.I recommend a strong tea over beer.

OK come to story, I was looking for a real world example for builder pattern.

So what is this Builder pattern according to GOF.

“Separate the construction of a complex object from its representation so that the same construction process can create different representations.”

Ok so builder pattern deals with construction of objects, that means its a Creational pattern.

I went through some diagrams in internet and found this one useful.

build1

So what you understand from the above image, The definition of builder pattern says we have to reuse the mechanism to construct a complex object.

In the above image the complex object is product, and Director is responsible for creating this product.

So we have to design in such a way to reuse the Director to create different complex objects.

I was looking for a practical example to explain this to my readers. Then my friend Krishna and Mankunnu Subash came to my desk and said there is new vending machine installed at our office. Basically i don’t like the tea or coffee from such machine, because i am a fan of manually prepared tea. Anyway i go out with them.

Woww this is the machine.

build2

Krishna clicked the coffee switch, he got coffee,I think subash clicked the tea button.I selected Cappuccino, It was ok.

Then a bulb blown above my head, yes this machine can be used to explain builder pattern.

I would like to present this machine as a drink preparing machine, So the end product is a drink, which may be either tea or coffee.

build3

First of all our end product drink can be represented by the below class.

class Drink
{
    string _label;

    public Drink(string label)
    {
        this._label = label;
    }

    public override string ToString()
    {
        return this._label;
    }
}

Now i will define an interface.Which represent the process for building a drink.
A tea can be made by mixing hot water and tea powder, coffee can be made by mixing hot water and coffee powder.

interface IDrinkBuilder
{
    void AddWater();
    void AddPowder();
    Drink Drink { get; }
}

Now we will create a concrete tea builder as below.

class TeaBuilder : IDrinkBuilder
{

    Drink drink;

    public TeaBuilder()
    {
        drink = new Drink("Tea");
    }

    public void AddWater()
    {

    }

    public void AddPowder()
    {
        //Tea Powder
    }

    public Drink Drink
    {
        get { return drink; }
    }
}

Then a concrete coffee builder.

class CoffeeBuilder : IDrinkBuilder
{
    Drink drink;

    public CoffeeBuilder()
    {
        drink = new Drink("Coffee");
    }

    public void AddWater()
    {

    }

    public void AddPowder()
    {
        // Coffee powder
    }

    public Drink Drink
    {
        get { return drink; }
    }
}

Now we will design our Director, which can be reused to build a tea or coffee.

class DrinkMaker
{
    public void MakeDrink(IDrinkBuilder builder)
    {
        builder.AddWater();
        builder.AddPowder();
    }
}

You can use the above class in your main as below.

class Program
    {
        static void Main(string[] args)
        {
            DrinkMaker maker;
            IDrinkBuilder builder;

            Console.WriteLine("Enter 'T' for Tea and 'C' for coffee.");
            maker = new DrinkMaker();

            while (true)
            {
                string input = Console.ReadLine();

                if (input == "T")
                {
                    builder = new TeaBuilder();
                    maker.MakeDrink(builder);
                    Console.WriteLine(builder.Drink.ToString() + " is ready.");
                    Console.ReadLine();
                }
                else if (input == "C")
                {
                    builder = new CoffeeBuilder();
                    maker.MakeDrink(builder);
                    Console.WriteLine(builder.Drink.ToString() + " is ready.");
                    Console.ReadLine();
                }
                else
                {
                    Environment.Exit(0);
                }
            }

        }

    }

}

Posted in Design Patterns | Tagged: , , | Leave a Comment »

Caching in ASP.NET MVC with Repository Pattern and WCF

Posted by vivekcek on June 25, 2014

In this post i will show you, how to implement caching in an asp.net mvc application.
This MVC application use repository pattern and consumes a WCF service.

1. Define an interface for our caching provider.

 public interface ICacheProvider
    {
        object Get(string key);
        void Set(string key, object data, int cacheTime);
        bool IsSet(string key);
        void Invalidate(string key);

    }

2. Implement this interface, dont forget to add reference for System.Runtime.Caching

 public class DefaultCacheProvider : ICacheProvider
    {
        private ObjectCache Cache { get { return MemoryCache.Default; } }

        public object Get(string key)
        {
            return Cache[key];
        }

        public void Set(string key, object data, int cacheTime)
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);

            Cache.Add(new CacheItem(key, data), policy);
        }

        public bool IsSet(string key)
        {
            return (Cache[key] != null);
        }

        public void Invalidate(string key)
        {
            Cache.Remove(key);
        }
    }

3. In your repository add this code.

public class DVDRepository : IRepository
    {
        protected DVDStoreService.DVDServiceClient serviceClient;
        protected ICacheProvider cache;
        public DVDRepository(DVDStoreService.DVDServiceClient client, ICacheProvider cache)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }
            serviceClient = client;
            this.cache = cache;
        }

        public List<DVDStoreService.Movie> GetAll()
        {
            List<DVDStoreService.Movie> movies = cache.Get("movies") as List<DVDStoreService.Movie>;
            if (movies == null)
            {
                movies = serviceClient.GetAllData().ToList();
                cache.Set("movies", movies, 60);
            }
            return movies;
        }
      }

Posted in MVC, WCF | Tagged: , , | Leave a Comment »

Using AutoMapper with WCF

Posted by vivekcek on June 24, 2014

1. Create WCF application.

2. Through Nuget add AutoMapper.

3. Now we will create a bootstrap class to initialize automapper.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;
using MoviesLibrary;

namespace DVDService
{
    public class AutomapBootstrap
    {
        public static void InitializeMap()
        {
            Mapper.CreateMap<Movie, MovieData>();
            Mapper.CreateMap<MovieData, Movie>();
            
        }
    }

}

4. To call this bootstrap when you call the service, we will create a service behavior attribute.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Web;

namespace DVDService
{
    public sealed class AutomapServiceBehavior : Attribute, IServiceBehavior
    {
        public AutomapServiceBehavior()
        {
        }


        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,
            Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
            AutomapBootstrap.InitializeMap();
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {

        }

        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {

        }

        
    }

}

5. Now decorate your service with this attribute.

[AutomapServiceBehavior]
    [ServiceErrorBehavior(typeof(ElmahErrorHandler))]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class DVDService : IDVDService
    {
        MovieDataSource dataSource = null;

        public List<Movie> GetAllData()
        {
            try
            {
                List<MovieData> movies = dataSource.GetAllData();
                List<Movie> mappedMovies = Mapper.Map<List<MovieData>, List<Movie>>(movies);
                return mappedMovies;
            }
            catch (Exception ex)
            {
                throw new FaultException(ex.Message);
            }
        }

Posted in WCF | Tagged: | 1 Comment »

WCF Logging with ELMAH

Posted by vivekcek on June 24, 2014

In this post, i will show you how to use ELMAH for WCF logging.

1. Create a WCF application.

2. Through Nuget add ELMAH EveryWhere. (Link)

3. Download ELMAH’s SQL Script and create a database. (Link)

4. Create a class ElmahErrorHandler which implementIErrorHandler.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Dispatcher;
using System.Web;

namespace DVDService
{
    public class ElmahErrorHandler : IErrorHandler
    {
        public bool HandleError(Exception error)
        {
            return false;
        }

        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            if (error == null)
            {
                return;
            }
            if (HttpContext.Current == null)
            {
                return;
            }
            Elmah.ErrorSignal.FromCurrentContext().Raise(error);
        }
    }
}

5. Create a Service behaviour attribute ServiceErrorBehaviorAttribute.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Web;

namespace DVDService
{
    public class ServiceErrorBehaviorAttribute : Attribute, IServiceBehavior
    {
        private readonly Type errorHandlerType;

        public ServiceErrorBehaviorAttribute(Type errorHandlerType)
        {
            this.errorHandlerType = errorHandlerType;
        }
        
        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            IErrorHandler errorHandler;
            errorHandler = Activator.CreateInstance(errorHandlerType) as IErrorHandler;
            if (errorHandler != null)
            {
                foreach (ChannelDispatcherBase dispatcher in serviceHostBase.ChannelDispatchers)
                {
                    ChannelDispatcher cd = dispatcher as ChannelDispatcher;
                    cd.ErrorHandlers.Add(errorHandler);
                }
            }
        }

        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            
        }
    }
}

6. In Web.config just after add the below tags. Update your connection string.

<configSections>
    <sectionGroup name="elmah">
      <section name="errorLog" requirePermission="false"
                                           type="Elmah.ErrorLogSectionHandler, Elmah"/>
    </sectionGroup>
  </configSections>
  <connectionStrings>
    <add name="elmah" connectionString="Data Source=.\sqlexpress;Initial Catalog=ELMAH;Integrated Security=True"/>
  </connectionStrings>
  <elmah>
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah"/>
  </elmah>

7. In Web.config under add the tags below.

<handlers>
      <add name="ELMAH" verb="POST,GET,HEAD" path="elmah/default.aspx" type="Elmah.ErrorLogPageFactory, Elmah"/>
    </handlers>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
    </modules>

8. Under make sure this is correct.

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

9. Now implement your service

 [ServiceErrorBehavior(typeof(ElmahErrorHandler))]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class DVDService : IDVDService
    {
      public List<Movie> GetAllData()
        {
            throw new ApplicationException("TEST");
        }
    }

10. To view your exceptions http://localhost/YourService.svc/elmah/default.aspx

Posted in WCF | Tagged: , , | Leave a Comment »