The Rain and The Shade

August 17, 2011

Unit Testing Database driven functionality with ADO.Net Entity Framework Code First

Filed under: ADO.Net Entity Framework,Unit Testing — ovaisakhter @ 5:39 am

The basic principal of writing a unit tests is that when you do a transaction you know the “expected” result and then you compare with the actual result that was generated, and if these results match you have a passed unit test. 

It is always interesting to write unit tests for Database services. Usually the problem that comes to mind is how to exactly predict the state of the database at the time when unit tests are running, so that the unit tests know what to expect. Some people may argue that you can mock out all the database functionality (mock the repositories), this idea may be very applicable in some scenarios but I usually do not go this way because of two reasons, 

  • It seems like to much work
  • Our applications are mostly data driven applications so there is not much to test anyway other than database transactions.

One way of knowing the exact state of the database can be to initialize(create) the database every time the unit tests are run. Once the database is created we might want to insert some initial data which is required for the unit tests.

I have been using Entity Framework Code first in my recent projects. Entity Framework provides you a very good way of achieving the two objectives I have mentioned in the previous paragraph.

EF provides a concept of Database initializers, these are implementations which define the strategy of how (rather when) the database will be created using our model (if you are a bit lost then I recommend to watch Code First Development with Entity Framework). These implementations implement an Interface called IDatabaseInitializer. There are some pre-backed strategies for database creation are provided with the EF. The one we are interested here is DropCreateDatabaseAlways. The name says it all, when using this strategy a database will be created every time code is executed(unit tests are run). To use the Initializers all you need to do is to write the following code before your unit tests are executed

System.Data.Entity.Database.SetInitializer<MyDbContext>(new DropCreateDatabaseAlways<MyDbContext>());

(Make sure you are using a local database server(SQL Express), things can really stressed if you are using a shared development server Smile.)

So now our database is created every time unit tests are run, now we need to create some data each time the database is created. For this you can inherit the  DropCreateDatabaseAlways class and override a method called Seed. using this method you add the initial records you want to create every time database is created.

Here is how the code will look like

public class MyUnitTestDatabaseInitializer : DropCreateDatabaseAlways<MyDbContext>
   {
       protected override void Seed(WilkeDbContext context)
       {
  //you can add any data using the context objected provided in the parameter

           context.SaveChanges();
           base.Seed(context);
       }
   }
The seed method is called just after the database is created by the the framework. Now all you need to do it to tell the framework to use your Database Initializer, and that you will do by modifying the code I wrote above.

System.Data.Entity.Database.SetInitializer<MyDbContext>(new MyUnitTestDatabaseInitializer <MyDbContext>());

so here you have it, now you can write the unit tests which are totally predictable and can run on any environment, be it your local machine or your Build Server. 

August 11, 2011

My name is Ovais and ICodeInCSharp , IDoPhotography,IWriteBlogs

Filed under: C# Coding,General Software Archiecture,Modeling — ovaisakhter @ 2:11 pm

 

I am a big fan of interfaces in a object oriented language like C#. I have been using dependency injection (IoC) in most of my previous projects and using DI your model contains many interfaces. I always try to spend some time in naming my model elements be it the name of interfaces, classes, methods or even the variables. When I look at code by other people one thing I usually notice is how they are naming their model elements.

Some days back I was looking into NServiceBus the things I noticed while doing that other than shear brilliance was the way different interfaces were named. for example IHandleMessages or IContainSagaData. This was a bit different way of naming then what I usually use as normally I would use something like IMessageHandler. I thought this is an interesting way of naming something like a class is saving my Name is MessageHandler and I Handle Messages. Sounds more natural more understandable.

I thought I should give this way of naming a try. In one of my projects, I tried to use similar naming.

The first place I need to create Interfaces are the repositories. So I started with names like IStoreData (instead of IRepository sounds boring doesn’t it?), IStoreDataInSql and went on and making names like IStoreStatistics.

Next place was the application controller where normally the interfaces for the services are named as IStatisticsService or IConfigurationService etc the names now became a bit different i.e. ILogStatistics, IManageSiteSurveryConfiguration, INotifyToExecuteAction INotifyWhenSiteSurveyConfigurationChanges.

Thought it was fun way of naming interfaces in some cases it become as stagnant as the old approach like IProvideThis and IHandleThat but in some cases the names become very interesting like INotifyWhenSiteSurveyConfigurationChanges and INotifyToExecuteAction.

August 10, 2011

JIT implementation for PivotViewer featuring Flickr.Net

Filed under: Silverlight — ovaisakhter @ 2:01 pm

I saw a my first demo of PivotViewer by a friend of mine some months back I was very impressed at that time, but then I forgot all about it. Then I saw it again some days back and thought to explore it a bit. As a developer I was not interested in the Excel tools provided by Microsoft. Having interest in photography the first thought that came to my mind was that a Flickr implementation of the PivotViewer could be very exciting. I went on tried googling a Flickr implantation for PivotViewer so that I can download the code run it and call it a day. But to my surprise I was not able to find one. So I thought to try to make one for myself. 

So the question was where to start I knew that there is a very nice library available for accessing Flickr service. The Library can be found here

http://flickrnet.codeplex.com/

and now the part was how can I provide the information to PivotViewer at run time. After a little search I was able to get this information from the following location

http://www.silverlight.net/learn/data-networking/pivot-viewer/just-in-time-sample-code

The sample code comes with prebuilt providers, I really loved the one for Twitter it let you visualize your own twitter feed in a way that you have never imagined, that was the point I became more interested in PivotViewer.

image

so you can filter your twitter feed using the @Mentions that you have done in your tweets and the #hashtags you have used. It kind of gives you a full overview of your thought pattern over a period of time in a very user friendly way.

When you open the solution in the Visual Studio you notice that there are projects in the solution.

PivotServer: This is the web application used to host the Pivot JIT implementation

PivotServerTools: As the name suggests contains all the important Data Objects and tools used in the implementation

SilverlightPivotViewer: The Silverlight project used to host the Pivot.

CollectionFactories: This is the Project we are most concerned with, in the project we have the implementations for different data sources. This is where we will add our very own Flickr implementation.

The Flickr Factory

To start the implementation of a JIT provider first thing you need to do it a bit of thinking. i.e. What are the different dimensions you will like to view your information. These are the dimensions using which you will be able to filter and sort your items. Flickr provides a concept of “Set” where each photo can belong to a set. So I chose the sets to be one of the Dimensions. The other two dimensions are I choose are Date Uploaded and Date Taken. I would have loved to use some of the the exif information as Dimensions but there was not way to get all the pictures and their exif information in one call.

Next thing you will need is an API key from Flickr you can get it from http://www.flickr.com/services/ after logging in.

So now the planning is done. We are ready to make our provider.

First Add a class to the CollectionFactories project and inherit it from CollectionFactoryBase

public class FlickrCollection : CollectionFactoryBase

public   FlickrCollection()
       {
           this.Name = "FlickrPhotos";

           this.SampleQueries = new string[]{
               "flickrUserEmail=ovaisbutt@yahoo.com",
               "flickrUserEmail=daredeagle@yahoo.com",
               "flickrUserEmail=ssatif@yahoo.com"
              
           };
       }

In the constructor you will set the name of your collection and also some of the sample queries that your application can handle. This information will be used to generate the UI by the framework which we will see later on.

To provide the Collection Information you need to override a method of this class i.e. MakeCollection

Now let us get some data from Flickr

First we need to get a Flickr user by the email provided.

FoundUser foundUser;
            var flickr = new Flickr(ApiKey);

            try
            {
                foundUser = flickr.PeopleFindByEmail(emailofUser);
            }
            catch(Exception exception)
            {
                return ErrorCollection.FromException(exception);
            }

flickrCollection.Name = string.Format("photos of {0}",foundUser.FullName);

then we get all the sets of the user

var allsets = flickr.PhotosetsGetList(foundUser.UserId);

now we can iterate through all the sets get picture information in them and start creating the Collection Items

var flickrCollection = new Collection();

foreach (var set in allsets)
            {

                var allPhotosInSet = flickr.PhotosetsGetPhotos(set.PhotosetId,PhotoSearchExtras.DateTaken | PhotoSearchExtras.DateUploaded );               

                foreach (var photo in allPhotosInSet)
                {
                    if (allPhotos.Contains(photo.PhotoId))
                    {
                        continue;
                    }

                    allPhotos.Add(photo.PhotoId);

                    var facetsForFlickr = new List<Facet>
                                              {
                                                  new Facet("Set", set.Title),
                                                  new Facet("Title",photo.Title),
                                                  new Facet("Photo Description",photo.Description),
                                                  new Facet("WebLink",new FacetHyperlink("Link",photo.WebUrl)),
                                                  new Facet("Date Taken", photo.DateTaken),
                                                  new Facet("Date Uploaded", photo.DateUploaded)
                                             };

                  

                    var url = photo.DoesLargeExist ? photo.LargeUrl : photo.SmallUrl;

                    flickrCollection.AddItem(photo.Title, null, photo.Description, new ItemImage(new Uri(url)), facetsForFlickr.ToArray());                    
                    
                }           

            }

the most important thing in this code is the List of Facets this the meta information you will provide about the picture. Once all the items are added to the collection now we need to tell how we want out meta information to be used and displayed.

            flickrCollection.SetFacetDisplay("Set", true, true, false);
            flickrCollection.SetFacetDisplay("Date Taken", true, true, false);
            flickrCollection.SetFacetDisplay("Date Uploaded", true, true, false);
            flickrCollection.SetFacetDisplay("Title", false, true, false);
            flickrCollection.SetFacetDisplay("Photo Description", false, true, false);

 

and finally return the collection.

Run the application and navigate to the following page silverlightPivotViewerTestPage.aspx page and you will see your collection shown in the dropdown

image

 

select one of the options and the Pivot will be rendered for that user (If you have many pictures it may take a while).

Here are some views from the result.

image

 

image

 

image

 

you can see this in action at www.wisdom.pk

August 5, 2011

Injecting Timer into Services

Filed under: Dependency Injection,Modeling — ovaisakhter @ 5:03 am

In the recent days while developing a project I had two services in my ApplicationController which were utilizing a Timer, i.e. they were instantiated with the Application and a timer was started when the services were instantiated and the services performed a certain action on the elapsed event.

I am using Dependency Injection in this project using Unity Container by Microsoft. I use Constructor Injection and define all dependencies in a BootStrapper class hosted present in my Application.

In my refactoring thoughts I came to a conclusion that the timer should be injected from the outside to the services as a Dependency. So I started modeling a Timer. Names like ITmer or ITimerService or even IKeepTime (recently I have been inspired by Udi Dahan’s way of naming interfaces like IDoThis and IHandleThat, fascinating stuff but more on that later). So ITimer was the winner in the end.

I started contemplating well it is merely a wrapper around the normal Timer class so it should just provide the features timer class provides. Then I thought but why should my service have the capability or even knowledge of the interval in which the Timer will elapse it only needs to know when to start the timer when to stop it and when it had elapsed. The Stop feature is only relevant so that the utilizing service can ask the timer to hold on while it is performing a action if it wants to Do one thing at a time (which is generally a good thing we should tell our Classes to do this also) Some may argue that why does Timer needs to know this it should just keep on banging on the door and our service should ignore any such notifications, I agree that this can be a way of thinking but read on I got it cleared for me later. Here is the final interface I came up with,

public  interface ITimer
  {
      void Start();
      void Stop();
      event EventHandler Elapsed;
  }

Now I am all happy made the implementation of the service all set for tomorrow when I will refactor my services to use my newly created model and called it a day. But then I started thinking about it again when I came home (Hope my wife doesn’t read my blog, but this blog is not about a new Chicken Biriayni  recipe so we are all set). I thought that for the services utilizing the Timer do not care that there is a timer running in the Timer service, for them this is a service that notifies them when the they should execute an action, and timer is just a concrete implementation of such a service they can even be a code listening to some event or even a UI sending a click of a button in which case being able to tell the service generating the notifications that the host Service is not entertaining any notifications at the moment may make sense. (may be disable a button during execution). Now let us call our newly thought of service INotifyToExecuteAction and let us change the names of the members to go with the new theme.

public  interface INotifyToExecuteAction
{
    void StartNotifications();
    void StopNotifications();
    event EventHandler Execute;
}

(by the way did I tell you that the renaming feature in Resharper is freaking awesome Ctrl R R on the method names of the interface rename them and it will change the method names in all the implementations also. How kool is that?)

so here we are then

August 3, 2011

Something beautiful while using AutoFixture

Filed under: Unit Testing — ovaisakhter @ 5:39 pm

In one of the projects I have the following class

public class SiteSurveyConfiguration : Entity
    {       
        public string CustomerName { get; set; }

        public string Website { get; set; }

        public string ShortDescriptionOnPopup { get; set; }

        public string HeadlineOnPopup { get; set; }

        public string LabelOfButtonOnPopup { get; set; }

        public int PercentOfUserWhoWillSeePopup { get; set; }

        public string CustomerLogoImageUrl { get; set; }

        public int ClicksByUserBeforePopShown { get; set; }

        public string ColorOfHeadline { get; set; }

        public string ColorOfShortText { get; set; }

        public string ColorOfButton { get; set; }

        public string FontOfPopup { get; set; }

        public int WidthOfPopup { get; set; }

        public int HeightOfPopup { get; set; }

        public bool ShowPopupInIFrame { get; set; }       
    }

While unit testing I needed to create a list containing 10 instances of this class along with different random data in each field.

var ListOfConfigurations = new List<SiteSurveyConfiguration>();
          var fixture = new Fixture();
          fixture.AddManyTo(ListOfConfigurations,10);

So this code created 10 instances of my class, added data to each field and added these instances to my list. I almost had tears of joy in my eyes Smile.

you can get more information about AutoFixture from http://autofixture.codeplex.com/

 

 

Blog at WordPress.com.