Archive

Archive for February, 2013

Using ASP .NET Web API with CodeFluent Entities

February 27, 2013 2 comments

This post will guide you in implementing a service layer over HTTP using ASP .NET Wet API and CodeFluent Entities.

WCF is great to expose SOAP based web services and even JSON services. However WCF does not capitalize all the possibilities that the HTTP protocol can provide.

Indeed, HTTP is a real application-level protocol, and while WCF uses HTTP only as a transport protocol (as could be TCP, UDP, named Pipes…) the ASP .NET Web API takes advantage of all the features that the HTTP protocol provides as:

  • Actions defined by verbs: GET, POST, PUT, DELETE.
  • Headers that can suggest extra information like caching, requested content, security.
  • A body that can be used for any kind of content (not only XML like for SOAP web services).
  • URIs that can be used for identify resources and actions.

For this post we will use the CodeFluent Entities demo project ‘CarRental’.

Car Rental Demo Project

Car Rental Demo Project

And we are going to add a Persistence producer (SQL Server 2012 for me), a Business Object Model (BOM) producer and a Service sub producer so we can use the WCF serialization.

Producers

Producers

We will host our services in an ASP .NET MVC 4 web site (ASP .NET Web API can also be hosted as a service), more information here.

MVC 4 Internet Application

MVC 4 Internet Application

The ASP .NET Web API provides a custom ‘Controller’ that handles the HTTP actions (GET, POST, PUT, and DELETE) as well as the content negotiation (XML, JSON, HTML…), this base controller is of type System.Web.Http.ApiController.

As the HTTP services are resource-oriented services we may want to create one Controller per Entity in our model. We will lead this post using only the Entity ‘CarGroup’ of our model. We can create some instances of type CarGroup to have some data to test.

So we first need to create a controller that extends from ‘ApiController’. We will call it ‘CarGroupController’.

CarGroupController

CarGroupController

We can see in the code of our new Controller that some methods have been created. These methods will be associated with the HTTP actions (verbs) GET, POST, PUT and DELETE.

CarGroupController Acitons

CarGroupController Acitons

Besides, adding an Api Controller made a route configuration specific to ASP .NET Web API (App_Start->WebApiConfig.cs), so the routes for our resources will be {base url}/api/{controller}/{id}. For example, we will have http://localhost:21020/api/cargroup.

ASP .NET Web API uses a ‘Convention over Configuration’ approach so the prefix of each method matches a specific HTTP action.

We are now going to implement the Actions.

To get all the instances of type CarGroup :

// GET api/cargroup
public IEnumerable<CarGroup> Get()
{
    return CarGroupCollection.LoadAll();
}

To get one CarGroup by Id:

// GET api/cargroup/5
public CarGroup Get(int id)
{
    CarGroup carGroup = CarGroup.Load(id);
    if (carGroup == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    return carGroup;
}

To create a new CarGroup :

// POST api/cargroup
public HttpResponseMessage Post([FromBody]CarGroup carGroup)
{
    if (carGroup == null || !carGroup.Save())
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
    return Request.CreateResponse(HttpStatusCode.OK, carGroup);
}

To update a CarGroup :

// PUT api/cargroup
public HttpResponseMessage Put([FromBody]CarGroup carGroup)
{
    if (carGroup == null || !carGroup.Save())
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
    return Request.CreateResponse(HttpStatusCode.OK, carGroup);
}

And finally to delete a CarGroup :

// DELETE api/cargroup/5
public HttpResponseMessage Delete(int id)
{
    CarGroup carGroup = CarGroup.Load(id);
    if (carGroup != null && carGroup.Delete())
    {
        return Request.CreateResponse(HttpStatusCode.NoContent);
    }
    return Request.CreateResponse(HttpStatusCode.NotFound);
}

As you can see, we have easily created a Controller able to support CRUD operations. The ASP .NET Web API will manage all the aspects like content negotiation and HTTP verbs (GET, POST, PUT and DELETE).

As we have added a Service Sub Producer to our model, we can use the data contract serialization (System.Runtime.Serialization.DataContractSerializer).

Let us test our Web API Controller, we will use a simple Console Application.

For example to retrieve all our Car Groups:

string uri = "http://localhost:21020/api/cargroup";
HttpWebRequest request = HttpWebRequest.CreateHttp(uri);
request.Accept = "text/xml";//we only accept XML
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    Console.WriteLine(response.StatusCode);
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        string result = reader.ReadToEnd();
        Console.WriteLine(result);
    }
}

And what we get (do not forget to add some instances to your model or you will not have any data):

Web API call test

Web API call test

If you want to get a specific CarGroup (id=1 for example) we only need to modify the URL (GET method):

string uri = "http://localhost:21020/api/cargroup/1";

If we want to test our other methods we only need to set the right HTTP method (verb), the right parameters (if needed) and the body data (if needed).

For example to update a CarGroup (PUT HTTP method):

CarGroup carGroup = //retrieve a CarGroup instance
carGroup.DailyRate++;//update the instance

string uri = "http://localhost:21020/api/cargroup";
HttpWebRequest request = HttpWebRequest.CreateHttp(uri);
request.Accept = "text/xml"; //we only accept XML
request.Method = "PUT";
request.ContentType = "text/xml; charset=UTF-8";//we will send XML
string bodyData = "";

//----- serializing data --------------
DataContractSerializer serializer = new DataContractSerializer(typeof(CarGroup));
using (MemoryStream stream = new MemoryStream())
{
    serializer.WriteObject(stream, carGroup);
    stream.Seek(0, SeekOrigin.Begin);
    using (StreamReader reader = new StreamReader(stream))
    {
        bodyData = reader.ReadToEnd();
    }
}
//----- writing data in to the request --------------
request.ContentLength = bodyData.Length;
using (StreamWriter requestWritter = new StreamWriter(request.GetRequestStream()))
{
    requestWritter.Write(bodyData);
}

//----- reading the response
string result = "";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    Console.WriteLine(response.StatusCode);
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        result = reader.ReadToEnd();
    }
}

//----- deserializing the response
CarGroup updatedObject = null;
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(result)))
{
    updatedObject = (CarGroup)serializer.ReadObject(stream);
}

This works great with XML, and if we want to use JSON we only need to specify it in our request.

request.Accept = "text/json"; //we only accept JSON
request.ContentType = "text/json; charset=UTF-8";//we will send JSON

We can even send XML and ask for JSON or send JSON and ask for XML.

We need to tell ASP .NET Web API to use the WCF JSON serializer.

In the App_Start->WebApiConfig.cs file:

JsonMediaTypeFormatter jsonFormatter = (JsonMediaTypeFormatter)config.Formatters.FirstOrDefault(f => f is JsonMediaTypeFormatter);
if (jsonFormatter != null)
{
    jsonFormatter.UseDataContractJsonSerializer = true; // use WCF serializer
}

More about serialization for ASP .NET Web API here.

Well, we have manually built an Api Controller for one entity in our model. It will be great to create automatically an Api Controller for each one of our entities.

We can achieve this by making a Template, but this will be your “homeworkSmile.

You can find some information in building templates here or here.

Regards.

Pablo Fernandez Duran

How to work with existing database tables with CodeFluent Entities

February 15, 2013 Leave a comment

Did you know that you could use CodeFluent Entities to work with existing database tables, such as the sys.object table for example, with zero code, and without modifying them?

In this post, we will demonstrate how to display a list of all tables in your SQL database. To follow this demo, you need to be familiar with CodeFluent Entities, and understand concepts such as entities, CFQL and raw methods.

The first thing is to create a CodeFluent project (DemoRaw.Model), a class library project for our bom (DemoRaw), and an empty MVC3 web project (DemoRaw.Web) to display our list. Then, we need to add 3 producers:

  • the BOM producer
  • the SQL Server producer
  • the MVC3 producer

If you need help with creating a CodeFluent Entities project, you may need to look at other articles on this blog before continuing.

Next, we create an entity called SysObject, and add three properties:

  • ObjectId (int)
  • Name (string)
  • Schema (string)

New CodeFluent Project

In our entity, let us add a CFQL method called LoadMyObjects. We use load raw in our stored procedure to return a collection of SysObject. Our stored procedure retrieves three properties from our sys.object table. You need to make sure that the fields name match the ones of our entity in the CodeFluent model. That way, the mapping will be handled automatically. The SQL stored procedure is like this:

select name as [SysObject_Name], object_id as [SysObject_ObjectId], schema_name(schema_id) as [SysObject_Schema] from sys.objects

Raw Method

Now, we need to update three settings before generating our model:

1. Because we do not need to create the SysObject table in SQL, we need to set the Produce Table property to false.

Settings

2. Our table does not need to have the tracking properties enabled, so we can remove them using the Tracking Modes property. Let us remove the User and Time from the list.

Settings

3. Last, we need to disable the concurrency mode. Let us set the Concurrency Mode to none.

Settings

Our model is ready to be built. Let us build it! Do not forget to add the DemoRaw reference to your DemoRaw.Web project before running it! Your default web browser opens, click on Sys Object, then Load My Objects, and you should see the list of tables!

Table List

This is how you can retrieve data from a specific SQL table, map them to a collection of objects, and display them on a webpage, all of this in a few minutes. If you want to go further, you can add more methods to manipulate the object. Happy CodeFluenting!

Vincent Patry

Navigate To… is now supported by CodeFluent Entities

February 13, 2013 Leave a comment

 
I don’t know you, but one of my favorite (and useful) commands in Visual Studio is the “Navigate to…” command (VS 2010 or higher), Menu->Edit->Navigate to… Or Ctrl+, (coma). This is one of my top most used commands in Visual Studio.
 

The Navigate To Command

The Navigate To Command


 
I find very useful to find all kind of custom symbols (classes, enums, attributes, properties, methods, events…) within my Visual Studio solution.
 
Once you have made a search, a list of results is displayed. At the left of each result you can see an icon that represents the type of the matched item (class, property, method…), you can find the entire list of icons here.
 
I have seen other kind of techniques to perform a symbol search. For example, some people do a simple search (string search) at the solution (or project) level Edit->Find and Replace->Find in Files or (Ctrl+Shift+F).
 
Find And Replace Command

Find And Replace Command


 
This works fine but it would not be as accurate as the “Navigate to…” search. Indeed, a global search will also search in string definitions, encapsulated variables and within all kind of files (if the file type has not been specified).
 
Find And Replace Results

Find And Replace Results


 
Well, good news every one! Now the CodeFluent Entities model (Designer Surface and XML representation) is integrated in to the “Navigate to…” search results.
 
Navigate To Results with CodeFluent Entities integration

Navigate To Results with CodeFluent Entities integration


 
Is not that great? On the search results we can distinguish the CodeFluent Entities concepts like Entities, Properties, Relations and even Instances. You can easily identify the CodeFluent Entities related concepts by the suffix [of Entity ‘EntityName’].
 
You may only want to search within the CodeFluent Entities concepts, well this is possible by typing “_cfe ” before the search term. For example, if I type “_cfe Artist” I will only get CodeFluent Entities results.
 
Searching only within CodeFluent Entities concepts

Searching only within CodeFluent Entities concepts


 
You can even search for entities instances. Imagine I have in my model an instance of type “Artist” called “The Police” (value of the Name property), if I type “The Police” in the “Navigate to…” window I will also get results related to the instances in my model matching this term.
 
Searching for instances

Searching for instances


 
Finally, when you choose to navigate to a search result, a nice zoom effect will take you directly to the related entity on the CodeFluent Entities Modeler Designer.
 
Navigating to the Result

Navigating to the Result


 

Hint: if you press “Shift” when navigating to a search result (OK button or Enter key) you go directly to the XML definition (CodeFluent Entities parts).

 

Navigation to the XML definition

Navigation to the XML definition


 

This feature is available since build number (1.0.61214.701), you can download the latest version here or find some information on how to update your CodeFluent Entities version in this post.

 
If you want to know more about the navigation in the modeler you may appreciate this post.
 
I know you will find this feature useful.
 
Regards.
 
Pablo Fernandez Duran

Generating JSON web services from an existing database with CodeFluent Entities

February 6, 2013 Leave a comment

This article posted on CodeProject will show you how to generate a JSON base web service layer from an existing database using CodeFluent Entities. We will also generate a web client back office following an “Import wizard”.

A common scenario

 

Let us say that we are facing the following scenario:

  • We have a database that we want to expose via a JSON based web service layer, providing CRUD (Create, Read, Update and Delete) operations.
  • We also need to build a back office in order to manage and administrate the data coming from our database.
  • We may need, on a future, to access in a different way our database, for example from a Smart Client or expose a SOAP based web services layer (there are always new ideas).
  • We need to deploy this system as soon as possible.

Let us start, what we need to do is:

  • Build a data access layer capable to load data, create new data, update and delete existing data (and make sure it works).
  • Manage validation data (and make sure it works).
  • Build a JSON based web service layer:
    • Build every needed service contract and operations.
    • Configure our service contracts to support JSON.
    • Host our services.
    • Make sure it works
  • Build a web based client (and make sure it works).
  • Lay the foundations so any possible evolution and additional architecture can be supported including mobile access through different smartphone devices.
  • And everything I have missed.

    Or…. We can use CodeFluent Entities to do the plumbing and being sure that it works.

    In the starter wizard, we can see some of the possible built-in architectures that can be generated by CodeFluent Entities, and of course you can imagine your own architecture by creating a custom CodeFluent Entities project with your relevant set of producers.

    clip_image002

    The scenario we mention here is developed "step by step" in the full article on CodeProject