RSS

Category Archives: C#

Creating a MVC Application using Unit of Work, Repository Pattern and NinJect

Part 1 – Summary of the Solution (Click Here)

Part 2 – The Solution

In this Post I’ll examine the components that make up the architectural solution described in my previous post in more detail up to the API / Controller level.  If you want a copy of the complete code then don’t hesitate to contact me on the About Section of my blog and I’ll send you a copy.

Ok so let’s start at the bottom with the database.  Well there is no database, not yet anyway.  In my example I have used the Code-first approach which allows me to describe my model in code, from which Entity Framework will construct the database.  Knowing this lets have a look at my model project;

The Solution

I am using the common Blog Model.  Keeping it simple, a Blog can contain many Posts and a Post can contain many Comments.

For this tutorial is not necessarily important to know what properties these objects contain but rather that they will reflect tables within our database and act as container objects to pass information around our system.  However here is the code for the Post Class just so you have an idea of how it is constructed:

The Post Model Object

Remember that Entity Framework has the job of trying to convert C# model classes to the database and so it’s wise to give it as much information as possible to give it a helping hand.  I’ve demonstrated this by adding an annotation to the Title Property and creating references back to Parent objects e.g. BlogId, Blog etc. which can be used by Fluent API (Not shown in this post) to enforce relationships between the data objects.  I have also created the Comments collection as Virtual.  This will ensure that the Entity Framework will not initialise the Comments collection until the data is specifically requested, improving performance.

Once we have our model classes we need to implement the repository layer to provide consistent data access.  To provide the consistent data access I created a new project (to contain my interfaces) which contains an IRepository Interface;

IRepository Class

This provides us with a generic interface which will accept an object from our model project and describe the data access actions that will be available to our application, e.g. retrieving records, updating records and adding a new record etc.  By implementing this interface we have a standard set of actions that can be performed on our database model (consistency).  If a model object needs to extend this set of actions, then we just create another repository interface which implements IRepository and includes the extra method signatures.  For example check out IPostRepository in this example which adds an extra method to return the number of comments associated with a Post;

IPostRepository Class

Following on from this we need to create the concrete implementations of the repository classes.  This is done within another project which is essentially our data layer.  I have created a class named EFRepository which implements IRepository.  This will be our base data access class and every object in our model will implement the functionality within this class as a minimum;

EFRepository Class

We will also need implementations for extended repository interfaces such as the IPostRepository created earlier;

PostRepository Class

As in this instance we are using the Entity Framework, the repositories will access the database via the DBContext. You will notice that in the EFRepository class we create an instance of this DBContext in order to perform operations of the database.  When developing against the Entity Framework using the Code-First approach you must create a Context Class which implements DBContext to identify the data objects which will be made available via the DBContext.  Here is an example of the Context class I created for this project named BlogDBContext;

BlogDbContext Class

By now we have described our model objects and created our repositories to allow us to perform data persistence actions on the database objects that these represent.  The next step is to implement the Unit of Work Pattern.  This requires that we create a Unit of Work class which will provide a single point of access to our repositories and a method to persist changes to the database as a single transaction improving efficiency and reducing concurrency problems.

So what does the Unit of work class look like?  Well if we examine its interface it simply exposes the repository objects and a single method to persist any changes back to the database.  That’s it simple.

IWebTemplateUoW Class

And the concrete implementation of the UnitOfWork class would look like this;

WebTemplateUoW Class

The key things to point out here is that firstly when we invoke the Unit of Work class we also create a new instance of our DBContext.  By wrapping the DBContext within the Unit of Work we can submit our changes within a single update request and dispose of the context once the request is complete.  We also have the advantage of performing atomic transactions, for example if one object fails to update when updating multiples objects within the database then we can rollback all objects to their original state reducing data inconsistency issues.

Another important point is that access to all repositories are available within this class and that also our context can be configured from this class.  If there was suddenly a business requirement to move to another database platform which used different data access technologies e.g. nHiberate, then we could create another Unit of Work class and substitute it for this one without breaking the logic and UI layers.  The advantages of a decoupled system!!

The final stage is to implement the Unit of Work into our business layer or in the case of this post our controllers within our API as I created a MVC application.

A sample controller Class using the Unit of Work

In this example I have created a quick controller class which when instantiated creates an instance of the Unit of work.  This in turn will create an instance of our DBContext and out repository classes. As a result we instantly have available all the objects from our model and the operations associated with that model via the repository interfaces e.g. GetAll(), Remove(entity), Add(newEntity) etc. and in the case of the Post object GetCommentCount() which was implemented via the IPostRepository.

The only bit of code in this controller you might be querying is the constructor which seems to accept an instantiated unit of work object, in this case of type IWebTemplateUoW.  This is because the Unit of Work Object is created for the controller using NinJect. NinJect is a technology which allows dependency injection.  In other words it allows the application to choose which concrete implementation of a component to create at run time.

Dependency Injection and NinJect is a large topic so I won’t try to go into it in any level of detail here but essentially I created a NinJect configuration class which tells my application that if it comes across an object of type IWebTemplateUow, then create an instance of WebTemplateUow.

The Ninject Configuration Class

 

 

 

 

 

 

 

 

 

 

 

Advertisements
 

Creating a MVC Application using Unit of Work, Repository Pattern and NinJect

Part 1 – Summary of the Solution

When developing new Web Applications using ASP.NET MVC we always encounter the same questions; where does the business logic layer fit in?, how can we implement Unit Testing?, what if the database changes? How can we make it scalable?

As a result, I set out to create a project template which could be used for future MVC projects and would address the questions above.

After much investigation the best approach I found was to develop the following framework:

 

Solution Component Overview

In this post I will just give an overview of the main components of the solution which is followed by a more detailed technical post of how the solution is put together.

 

Starting at the bottom of the diagram you will notice I have a database and sitting on top of that database I have the Entity Framework.  In the following post you will see how I use the Code-First approach to allow the Entity Framework to construct the database based on the model.

On top of the Entity Framework I am making use of the Repository Pattern to allow access to the objects that make up the model and to enforce the actions associated with these objects.  By making use of the Repository Pattern we prevent needless duplication of Data Access Logic code and enforce a standard set of actions that can be applied to the data objects e.g. Get All(), Find(), Add, Delete() etc.

The Repositories serve up the Model objects to the Unit of Work.  Using the Unit of Work Pattern we allow the higher tier layers to access and modify the data objects via a single class.  This result is a single Commit (operation / transaction) when writing changes made to multiple objects, back to the database allowing for a much more efficient approach and reducing concurrency issues.  Using the Unit of Work Pattern also means we de-couple the higher logic and UI tiers from the Database context which allows us to substitute in alternative Unit of Work classes that may be used for Unit Testing or connecting to alternative databases.

The Unit Of work object is then directly used by the API components or if required a Business Logic Layer which can be slotted between the API / UI layer and the Unit of Work classes to give a further level of separation.  In my example I have used NinJect as my IoC container to instantiate the correct Unit Of Work Objects but you will see more on this in the following post.

Our UI then has access to our data level objects and models without needing to know any detail about the ins and outs of the system which will allow us to build any UI on top of our API service, whether it’s a desktop, Web, Phone, IPad app etc.

Click here to see my real world template

 

 

 

A Simple Defibrillator Class in C#

Timeout Defibrillators are common in the ASP.NET world, where there is often a requirement to keep a session alive during a period of inactivity.  However the same can be said about the windows application domain.  For example, assume that user enters an area of the application which serves up some specific data.  While the user has this screen open, it should be locked to all other users so that the data cannot be modified.  But what happens if the user decides to go to lunch with the screen open preventing all other users from working.

In scenarios like this it would be nice to have a simple class which when invoked starts a timeout process for long periods of inactivity.  When this time out is reached an event is raised to the calling object which allows the application to release the lock.  Additionally there is a method in the class which can be called by the parent object to reset the timer if there is some form of activity on the screen.

Below is my simple Defibrillator class and below that an explanation of the key points of this class and how to use it.

Defibrillator Class

So the basics of this class are:

  • A delegate and event have been created at the top of this page which can be subscribed to by the calling object.  This allows us to raise an event to the parent once the time out has been reached.
  • The constructor allows the user to pass in the time is seconds which should be observed before the timeout is reached.
  • The Start method is called when we are ready to commence the timer.  Note that I have set the Interval between ticks to be 1 second.  The timer object allows us to set a call back method which is invoked after every tick (1 second interval in this case)
  • The Reset method allows us to Reset the timer.  This would probably be called if the parent registers user activity.
  • The TimerProc method is called after every tick of the timer.  Here I am performing a check to see if the timeout has been reached.  If it has the timer is disposed and the event raised back to the Parent.

 

To use the class, simply create a Form which has a reference to the Defibrillator class and add code similar to below:

Invoking the class

Here I am creating an instance of the class with a 10 second timeout.  I am also subscribing to the TimeOut Reached event which will call the method dt_TimeOutReached when the time out completes.

All that’s left is to start the Timer – dt.Start()

 

 
 

Reading an XML file using Linq to XML

A quick and post and more for my own reference but I recently needed to read some elements from an XML document which can be accomplished much easier these days using Linq to XML.

So if I have a simple XML document :

Sample XML document

I can read this using Linq as below (language is C#) :

C# routine to parse the XML document using Linq

In this method I am first loading the XML file into an XDocument Object found under the System.XML.Linq namespace.

I am then using Linq to return a collection of Items which represent the Parent ‘Client’ Nodes, using the Descendants function.

Then we can loop though each Client Node and simply extract the Element Values for the KEY and POSITION Nodes.  Its also worth noticing in this example that I have included an attribute at the CLIENT Node level.  Using Attributes().First() I am requesting the first attribute found attached to my CLIENT object.

Like I mentioned nothing difficult here but a handy little reference

 
Leave a comment

Posted by on June 22, 2012 in C#, Linq, Uncategorized, XML

 

Client Server Progress Bar using SignalR

I am currently involved on a web application project which does some pretty heavy processing on the server side.  The Client makes a request to the Server, and waits patiently for a response once the server side processing is complete.  However in the disconnected world of the web this can prove a problem.  For example The client will make a request and wait for a response until a timeout is reached.  At this point the client will stop waiting for the reponse while the server is still processing the request causing a whole host of performance issues.

So I thought, wouldn’t it be nice if I could keep the Client informed of the progress of the Server.  Maybe a Progress Bar on the client which is updated by the Server at various stages of the process.

Using SignalR I was able to enforce this communication between the Server and Client and created a basic example in this blog so you can do the same.

Step 1 – The Concept

The concept for this example is:

I will create a simple aspx page which will host a progress bar.  The intention being that this progress bar is updated in real time by the server.  To allow the server to update the client I will use SignalR.  I am also using the Twitter Bootstrap framework for my styling and layout although it is not essential.

Step 2 – Setting up the Environement

Open Visual Studio and Create a new ASP.NET Web Application

Using the Package Manager Console, Install the SignalR Libraries using NuGet (This will also ensure JQuery is installed) e.g.

Finally add the Twitter Bootstrap CSS which we will use to give our progress bar a nice styling e.g.

Twitter Bootstrap provides us with out of the box HTML, CSS and Javascript for out user interfaces, is excellent and can be found here http://twitter.github.com/bootstrap/

Step 3 – Server Side Code

For simplicity we are going to create a simple method which invokes a timer and then periodically uses Signal R to pass a message back to the client updating the progress of the progress bar.

Using the Default.aspx.cs our code should look like this:

Here I have created a class called Chat which derives from Hub.  Yep if SignalR is installed correctly its that simple, the rest of the code is conerned with updating the progress bar.

I have created a method called Send() which is created on the Hub Server and will be linked to on the client in step 4.  This method simply creates a timer with a tick interval of 100ms and when each interval elapses calls to the timer_Elapsed event.  This event then evaluates my counter (which starts at 1) and increments is by 1.  If the result has not reached 100, we make a call to any SignalR clients that are listening and invokes the addMessage function on the client.  Once we reach 100 (or 100% in terms of our progress bar) the timer is stopped.

Step 4 – Client Side Code

Out client side code within Default.aspx is slightly more complex but still pretty straight forward:

First add the following script references to JQuery and SignalR

Secondly add a link to the Twitter bootstrap CSS:

then add the following markup to the client page:

Notice the code within the <div> with the class name ‘Container’.  This is where I create a simple Progress Bar using the Twitter Bootstrap Styling.  The Width attribute attached to the ‘bar’ is initially set to 0%.  This will be increased incrementally to 100% from the server.

Also noice out Script section.  Here we are referencing out SignalR class on the server and creating out addMessage method which is invoked from the server.  This method simply uses Jquery to grab our progress bar and increment the Width attibute with the value passed back from the server.

I have also added some code to the click event of the button which invokes the Send Message on the server,

Step 5 – Running the Application

If all the steps have been implemented correctly you should be able to run the application abd click the button to see the progress bar being incrementally increased by the server

 
3 Comments

Posted by on May 17, 2012 in ASP.NET, C#, HTML, web development

 

Step 4 – Querying the WCF Data Service

This post is Step 4 in a Quick Start tutorial on how to create WCF Data Services

In Step 3 we finished exposing our WCF service.  Browsing directly to the Service will display the entities that we are exposing via the service using the AtomPub format.

If we want the data returned as an alternative format e.g. JSON or XML then just modify the Request Header using the ‘Accept’ attribute, so for JSON we could ass the request header:

Accept: application/json

The best way to demonstrate this is to use a free application called Fiddler (http://www.fiddler2.com/fiddler2/)

With Fiddler loaded enter the address of the WCF service into the Composer tab but add the ‘Accept: application/json’ into the Request Headers window.  Click the Execute button and you should have a JSON page returned in the Web Sessions window:

Using Fiddler to modify the Request Header

Click on the Page in the Web Sessions window to view the results.

So far we have queried the WCF service and found out how to return the data in a specific format but what about querying the actual data.

Let’s assume we want to return all records held within the Staff table.  As this was one of the entities exposed by the service (see beginning of this article) then we can just append the href attribute representing this entity to the Service URL e.g.

http://localhost/Location/WCFServiceName.svc/staffs

NOTE: it is case sensitive

JSON returned using Fiddler

Again I am using Fiddler to display the results returned as JSON

Let’s call the same URL but return the results in the raw atompub format so we can analyse exactly what is being returned:

NOTE: Some browsers are automatically set up to view the raw content as an RSS feed.  You may need to disable this feature in order the view the raw response from the data service. 

One important point to remember is that the Data Service is purely exposing data.  The whole concept is based on a RESTful architecture.  This is great if we want to build a client and an alternative language or device but adds a little more complexity when it comes to modelling the relationships and navigational properties of the entities on the server-side.

WCF Data Services do however provide hints on how to navigate around the data it servers to the client.  Notice the Link tags in the XML above.  The first one gives us an exact pointer to the record we are viewing.  You can try this yourself; simply modify the original URL to include the ID of the record you are after in brackets (this URL is also shown in the ID tag in the above XML).  Now try changing the id to return different records.

Now referring back to Step 1 we created the following database structure:

MySQL Table Structure from Step 1

There is a link between Staff and StaffTypes.  This has also been exposed in the XML served up by the data service – See the second Link tag.

So by simply using the ‘href’ supplied to me in this tag I can navigate to the related StaffType record e.g.

Calling http://localhost/WCFSparsMobile/WcfDataService1.svc/staffs(1)/stafftype1

Returns the record:

Ok now for the clever bit.  WCF Data Services are based on OData (Open Data Protocol).  This allows us to query the data using nothing but the URI. This is a massive subject which includes using the URI to query, filter and sort data, too much for this blog post, but I show an example just to get you started.

So let’s take the scenario that we want to return a staff record where the forename is equal to ‘Dan’ (assuming there is a person called Dan in the database!!)

We simply append a filter expression to the URI as follows:

http://localhost/WCFSparsMobile/WcfDataService1.svc/staffs?$filter=forename eq ‘Dan’

This is great as you may have noticed we are returning, navigating and now filtering data without writing any code and so essentially giving the power to the client to request the exact data it requires.

 

Step 3 – Creating the WCF Data Service

This post is Step 3 in a Quick Start tutorial on how to create WCF Data Services

Now for the fun bit, exposing our data using WCF Data Services.

1. Start by creating a new project in the solution using the template – ASP.NET Empty Web Application calling it something like WcfDataService.

2. Add a reference to the data model project we created in step 2.

3. Copy the ConnectionStrings section from the App.Config file in the data model project into the Web.config file of the WcfDataService project that we have just created.

4. Now add a new file file (Add New Item) to the Data Service Project of type ‘WCF Data Service’

WCF Data Service Template

In the Code view of the service we have just added (wcDataService1.svc.cs by default) we need to make the following code modifications:

Modifing the Data Service Class

The first modification lets the service know which data we want to expose, in this case the entities representing our model created in step 2 via the Entity Framework.

The second modifications are relating to security.  This is quite a cool feature as it allows us to specify which parts of our data should be available via the service and to what degree that data should be available e.g. Read only, Read & write etc.

Ok, now to run out service (yep thats it, not much coding to get a service initially set up!!)

Right click the Service in the project and select ‘View In Browser’:

If your service has been created correctly you should see an XML representation of the entity objects we created in step 1 and 2 and exposed via the service earlier in this step.

Results from calling the WCF service

So we have a fully functional WCF Service but it doesn’t really show a lot at the moment.  The next Step in this blog post gives more of an initial insight into the data that is being served up by the service and how to manipulate it.

Step 4 – Understanding the Results