Develop and Consume OData Web Services in WCF

What is OData?

OData is an Open Data Protocol used to access data from various sources like Relational databases, file systems, etc. and exposes it to the consumers that can query or update data. OData is based upon Web technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON to provide access to information from variety of data sources. Consumers can query the data using HTTP protocol and get the results in AtomPub and JSON formats. These are the formats through which the service can deliver the requested resources or collection of entities.

OData is released under the Open Specification Promise http://www.microsoft.com/openspecifications/en/us/programs/osp/default.aspx and anyone can freely interoperate with OData implementations.

Developing WCF Service using OData Protocol

Microsoft has first introduced OData support in Visual Studio 2008 SP1 in terms of ADO.Net Data Services (subsequently known as WCF Data Services). Developers can create services on the fly and exposes data using Entity Framework or LINQ 2 SQL ORM tools.

Let’s create a simple WCF Data Service and expose data using Entity Framework.

  1. Start Visual Studio 2010 and create a new WCF Service Application project.


  1. Right click the WCF Service Application project and click on the “Add New Item”, then select WCF Data Service.


  2. If you open the WCF Data Service class file you can see the Class will be derived from the generic DataService class. This is the main entry point for developing WCF Data services. We have to specify the data source class name. In order to proceed further I will add entity framework model which creates the entities model on the fly.
  3. Right click on the Service Project and Add “ADO.Net Entity Data Model” from the dialog.


    When you add ADO.Net Entity Model it will ask you to select the data source, go through the wizard by selecting the data source and finish a dialog.

  4. Now open the .edmx file click on properties.


    Here’s the entity container named as “DDMSEntities”. Just specify the name DDMSEntities in your WCF Data Service base class like below

public class WcfDataService1 : DataService<DDMSEntities>

  1. You can now add the SetEntitySetAccessRule for each entity you want to expose. Default configuration is to deny access to resources. When a service is initialized the access rights must be enabled.

    Sample code snippet below


public static void InitializeService(DataServiceConfiguration config)
{

// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.

config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

config.SetEntitySetAccessRule (“Levels”, EntitySetRights.AllRead);

config.SetEntitySetAccessRule (“NodeTypes”, EntitySetRights.All);

}

In Above code, I have added two tables i.e. Levels and NodeTypes and given permissions as AllRead. There are many permission levels you can set as follows. Below are the enums of EntitySetRights with their description

  • All – Authorize to create, read, update and delete data.
  • AllRead- Authorize to read data.
  • AllWrite- Authorize to write data.
  • None- Denies all rights to access data.
  • ReadMultiple – Authorize to read sets of data.
  • ReadSingle – Authorize to read single data of items.
  • WriteAppend- Authorize to create new data items in the data sets.
  • WriteDelete –Authorize to delete data items from the data sets.
  • WriteMerge – Authorize to merge data.
  • WriteReplace – Authorize to replace data.
  1. Now let’s build a service and test it. Once you hit the web service in a browser, you will see the page as below


    The above feed representing the data as per Atom Syndication format. There are two entity collections namely “Levels” and “NodeTypes”.

                                      http://localhost:32555/WcfDataService1.svc/Levels?filter= LevelTree gt

                                     “gt” is used for greater than where as “lt” is used for less than.

Consuming WCF Data Service in Web Application

  1. Create a new Web Application project in Visual Studio
  2. Add a service reference by right clicking on Add Service Reference and select the newly service created.


  3. Add a button to call the service on its click event.
  4. On the click event you can consume the service like below

Services.DMSEntities.DDMSEntities entities = new Services.DMSEntities.DDMSEntities(new
Uri(http://localhost:32555/WcfDataService1.svc&#8221;));

var lst = entities.Levels.FirstOrDefault();

This will return the first item in the collection. You can execute all CRUD operations depending on the rule set in the Service for that entity.

Hope this helps, happy coding!

Problem loading ASP.Net project after installing VS 2010 SP1

Sometimes developer faces this problem on loading existing web projects that were hosted on local IIS server and using the same port number that has been used by the IIS Express for particular websites. IIS Express installed by default when you apply the SP1 for Visual Studio 2010.

In my case, I installed VS 2010 SP1 to install Silverlight 5 Tools for VS 2010 and when opened my existing web project which was earlier hosted on my Local IIS server using the same port no i.e. 8080, came across this error.

In order to rectify, the simplest way is to change the port no in the applicationhost.config file placed under [Win_Drive]:\Users\[User]\Documents\IISExpress\config folder. When open the applicationhost.config file you will find the <bindings> tag under <site> tag followed with the port no.

Change the port no and don’t forget to save the file. Now try reloading the project and it opens without any issue.

Implementing Repository Pattern with Entity Framework – Code First Model Approach

When working with Entity Framework – Code First model approach, developer creates POCO entities for Database tables. The benefit of using Code First model is to have POCO entity for each table that can be used as either WCF Data Contracts or you can apply your own custom attributes to handle Security, Logging, etc. and there is no mapping needed as we used to do in Entity Framework (Model First) approach if the application architecture is n-tier based.

Considering the Data Access layer, we will implement a repository pattern that encapsulates the persistence logic in a separate class. This class will be responsible to perform database operations. Let’s suppose the application is based on n-tier architecture and having 3 tiers namely Presentation, Business and Data Access. Common library contains all our POCO entities that will be used by all the layers.

Presentation Layer: Contains Views, Forms

Business Layer: Managers that handle logic functionality

Data Access Layer: Contains Repository class that handles CRUD operations

Common Library: Contain POCO entities.

We will implement an interface named “IRepository” that defines the signature of all the appropriate generic methods needed to perform CRUD operation and then implement the Repository class that defines the actual implementation of each method. We can also instantiate Repository object using Dependency Injection or apply Factory pattern.

Code Snippet: IRepository


public
interface
IRepository : IDisposable

{


///
<summary>


/// Gets all objects from database


///
</summary>


///
<returns></returns>


IQueryable<T> All<T>() where T : class;


///
<summary>


/// Gets objects from database by filter.


///
</summary>


///
<param name=”predicate”>Specified a filter</param>


///
<returns></returns>


IQueryable<T> Filter<T>(Expression<Func<T, bool>> predicate) where T : class;


///
<summary>


/// Gets objects from database with filting and paging.


///
</summary>


///
<typeparam name=”Key”>


///
<param name=”filter”>Specified a filter</param>


///
<param name=”total”>Returns the total records count of the filter.</param>


///
<param name=”index”>Specified the page index.</param>


///
<param name=”size”>Specified the page size</param>


///
<returns></returns>


IQueryable<T> Filter<T>(Expression<Func<T, bool>> filter, out
int total, int index = 0, int size = 50) where T : class;


///
<summary>


/// Gets the object(s) is exists in database by specified filter.


///
</summary>


///
<param name=”predicate”>Specified the filter expression</param>


///
<returns></returns>


bool Contains<T>(Expression<Func<T, bool>> predicate) where T : class;


///
<summary>


/// Find object by keys.


///
</summary>


///
<param name=”keys”>Specified the search keys.</param>


///
<returns></returns>

T Find<T>(params
object[] keys) where T : class;


///
<summary>


/// Find object by specified expression.


///
</summary>


///
<param name=”predicate”></param>


///
<returns></returns>

T Find<T>(Expression<Func<T, bool>> predicate) where T : class;


///
<summary>


/// Create a new object to database.


///
</summary>


///
<param name=”t”>Specified a new object to create.</param>


///
<returns></returns>

T Create<T>(T t) where T : class;


///
<summary>


/// Delete the object from database.


///
</summary>


///
<param name=”t”>Specified a existing object to delete.</param>


int Delete<T>(T t) where T : class;


///
<summary>


/// Delete objects from database by specified filter expression.


///
</summary>


///
<param name=”predicate”></param>


///
<returns></returns>


int Delete<T>(Expression<Func<T, bool>> predicate) where T : class;


///
<summary>


/// Update object changes and save to database.


///
</summary>


///
<param name=”t”>Specified the object to save.</param>


///
<returns></returns>


int Update<T>(T t) where T : class;


///
<summary>


/// Select Single Item by specified expression.


///
</summary>


///
<typeparam name=”T”></typeparam>


///
<param name=”expression”></param>


///
<returns></returns>

T Single<T>(Expression<Func<T, bool>> expression) where T : class;


void SaveChanges();


void ExecuteProcedure(String procedureCommand, params
SqlParameter[] sqlParams);

}

Code Snippet: Repository

public
class
Repository : IRepository

{


DbContext Context;


public Repository()

{

Context = new
DBContext();

}


public Repository(DBContext context)

{

Context = context;

}


public
void CommitChanges()

{

 Context.SaveChanges();

}


public T Single<T>(Expression<Func<T, bool>> expression) where T : class

{


return All().FirstOrDefault(expression);

}


public
IQueryable<T> All<T>() where T : class

{


return Context.Set().AsQueryable();

}


public
virtual
IQueryable<T> Filter<T>(Expression<Func<T, bool>> predicate) where T : class

{


return Context.Set<T>().Where<T>(predicate).AsQueryable<T>();

}


public
virtual
IQueryable<T> Filter<T>(Expression<Func<T, bool>> filter, out
int total, int index = 0, int size = 50) where T : class

{


int skipCount = index * size;


var _resetSet = filter != null ? Context.Set().Where(filter).AsQueryable() : Context.Set().AsQueryable();

 _resetSet = skipCount == 0 ? _resetSet.Take(size) : _resetSet.Skip(skipCount).Take(size);

total = _resetSet.Count();


return _resetSet.AsQueryable();

}


public
virtual T Create(T TObject) where T : class

{


var newEntry = Context.Set().Add(TObject);

Context.SaveChanges();


return newEntry;

}


public
virtual
int Delete(T TObject) where T : class

{

 Context.Set().Remove(TObject);


return Context.SaveChanges();

}


public
virtual
int Update(T TObject) where T : class

{


try

{


var entry = Context.Entry(TObject);

 Context.Set().Attach(TObject);

entry.State = EntityState.Modified;


return Context.SaveChanges();

}


catch (OptimisticConcurrencyException ex)

{


throw ex;

}

}


public
virtual
int Delete<T>(Expression<Func<T, bool>> predicate) where T : class

{


var objects = Filter<T>(predicate);


foreach (var obj in objects)

Context.Set<T>().Remove(obj);


return Context.SaveChanges();

}


public
bool Contains<T>(Expression<Func<T, bool>> predicate) where T : class

{


return Context.Set<T>().Count<T>(predicate) > 0;

}


public
virtual T Find<T>(params
object[] keys) where T : class

{


return (T)Context.Set<T>().Find(keys);

}


public
virtual T Find<T>(Expression<Func<T, bool>> predicate) where T : class

{


return Context.Set<T>().FirstOrDefault<T>(predicate);

}


public
virtual
void ExecuteProcedure(String procedureCommand, params
SqlParameter[] sqlParams){

 Context.Database.ExecuteSqlCommand(procedureCommand, sqlParams);

}


public
virtual
void SaveChanges()

{

Context.SaveChanges();

}


public
void Dispose()

{


if (Context != null)

Context.Dispose();

}

}

The benefit of using Repository pattern is that all the database operations will be managed centrally and in future if you want to change the underlying database connector you can add another Repository class and defines its own implementation or change the existing one.

Microsoft Technology Practices User Group

I have created a Meetup group named “Microsoft Technology Practices User Group” that focuses on latest tools and technologies on Microsoft Platform. The vision of this group is to help the developer community to share, explore, learn and develop things on upcoming and latest Microsoft technology stack.

This group is only 2 weeks old, and I believe the more we grow we will get more sponsors which will intimately provide more perks and benefits to the members of this group in terms of links to different training materials and sample projects and subscriptions to paid content. This is completely based on volunteer ship and everyone has to work together to expand and grow. Active members will get opportunities to give presentations, trainings and demo sessions to the developer community time to time which will certainly help them to polish their other i.e. communication, presentation skills as well.

Anyone can join this group but should be passionate of sharing and learning things on Microsoft technologies.

If you want to be a member, please visit the site http://meetup.com/MSTPUG and join!

Hope to see you in the upcoming events.

Handling User Control Events in ASP.Net

Although most of the developers know how to handle events of User Controls, but this will help for those developers who never came across with this before and wants to learn with a simple example that details about handling custom user control events on aspx pages.

What are User Controls?

User controls are just like standard ASP.Net webform with few limitations. It contains a designer view where the user can drag and drop existing controls of ASP.net or third party to structure that user control. In order to learn more about User control you can follow this link http://msdn.microsoft.com/en-us/library/y6wb1a0e(v=vs.100).aspx

Handling custom developed User Control Event

Let suppose we have a user control containing a textbox and a button. And we have an aspx page where we are using that control. Now inorder to handle the button click event of the User control’s button click event on aspx page we will go through the following steps.

Following is a code snippet of User Control named “ctrlCustomUserControl.ascx”

<%@
Control
Language=”C#” AutoEventWireup=”true” CodeBehind=”ctrlMyUserControl.ascx.cs” Inherits=”WebApplication7.ctrlMyUserControl”
%>

<asp:TextBox
ID=”txtBox” runat=”server”></asp:TextBox>

<asp:Button
ID=”btnClickMe” runat=”server” Text=”Click Me!”


onclick=”btnClickMe_Click”
/>

You can see there are two controls placed, one is textbox and the other is button.

Code behind file looks like as follows


public
partial
class
ctrlMyUserControl : System.Web.UI.UserControl

{


public
delegate
void
ClickHandler(object sender, EventArgs e);


public
event
ClickHandler Click;


protected
void btnClickMe_Click(object sender, EventArgs e)

{

Click(sender, e);

}


public
String Text

{


set { this.txtBox.Text = value; }

}

}

 Above code shows that there is a delegate named ClickHandler and I have declare its event named Click. And I have also registered the button click event and called my custom Click event there, which will be registered by the ASPX page will be invoked from this event.

Now, lets look into the “Default.aspx” page where I am using this control.

<%@
Page
Title=”Home Page” Language=”C#” AutoEventWireup=”true”


CodeBehind=”Default.aspx.cs” Inherits=”WebApplication7._Default”
%>

<%@
Register
Src=”~/ctrlMyUserControl.ascx” TagName=”MyControl” TagPrefix=”uc”%>

<form
runat=”server”>


<uc:MyControl
id=”myctrl” runat=”server” OnClick=”myctrl_click”></uc:MyControl>

</form>

Second statement shows the registration of my custom user control on aspx page, tagprefix and tagname values are used to define control tag.

I have used uc as the tagprefix and MyControl as tagname. You can see how I have specified the markup of custom user control. One important thing, you can see that I have specified OnClick event. Actually if you recall the control code behind file there I have an event named “Click” and inorder to register it on any aspx page we have to add a prefix “On” i.e. “OnClick”. This is how we can register custom events of user the control on aspx page.

Code behind of Default.aspx is as follows


public
partial
class
_Default : System.Web.UI.Page

{


protected
void myctrl_click(object sender, EventArgs e)

{

myctrl.Text = “Hello World!”;

}

}

When user click on the button, it will populate “Hello World!” text on the text box.


Happy Coding!