Posts Tagged ‘JSON’

What’s new with CodeFluent Entities 769?

April 7, 2014 Leave a comment

As with any previous release, CodeFluent Entities 769 includes numerous new features and bug fixes.

Keeping ahead with the latest technologies is our priority and we are extremely thrilled to announce that CodeFluent Entities now supports Microsoft SQL Server 2014.

Since the beginning of the year, CodeFluent Entities offers a new licensing model. You can try CodeFluent Entities by downloading the 30-day trial version which is unlimited in features and model size. The tool is also available in four registred editions: Personal (free for non-commercial use and limited to 50 entities), Professional, Enterprise and Ultimate.

But what else?


We made some greats improvements to the JsonUtilities:

Pretty-print Json

string json = @"{""name"": ""John Doe"",""age"": 35}";
var obj = JsonUtilities.Deserialize(json);
JsonUtilities.WriteFormatted(Console.Out, obj);

Will output:

  "name": "John Doe",
  "age": 35


JsonUtilities now supports XmlAttribute:

string json = @"{""name"": ""John Doe"",""age"": 35}";
var person = JsonUtilities.Deserialize<Person>(json, 

public class Person
    public string Name { get; set; }
    public int Age { get; set; }

We also added some automatic conversions between types. For example you can deserialize json to a Dictionary<string, decimal>. Values will be converted to decimal if possible. Internally this will use the ConvertUtilities class which I hope you are already using.

Relation UX improvements

We introduce a new ribbon item named Add relation. Of course the concept of relation already exists in the product, but we constantly strive to improve our product. Now there is an item in the ribbon to add a relation. The new form allows to select entities and properties and even create a new property if needed:

Add relations

When you don’t know which option to select (one-to-one, one-to-many, many-to-one or many-to-many) to define the type of relation, just read the description:

Relation Type

In this example, only the second sentence (one Customer has many Orders) is logical. If none of them seem valid, it may indicate that properties are badly named.

Microsoft SQL Server 2014 support

The SQL Server Producer now supports Microsoft SQL Server 2014. Christmas comes early for CodeFluent Entities users :).

SQL Server 2014

A new way to Activate

Last but not least, we provide a new screen to activate the product. With this new form, you can get your license key by connecting to your account directly in Microsoft Visual Studio:

Registered edition

If you are not a current customer, you can always download our free evaluation and see it in action.

Remember that you can follow the latest new features and bug fixes of CodeFluent Entities subscribing to this RSS Feed.

If you have any questions or comments, feel free to share them below.

Happy downloading!

The R&D Team

Create Windows Azure Mobile Services in a few minutes thanks to CodeFluent Entities

April 5, 2013 Leave a comment

You may have heard that a lot of new features were added to Windows Azure during the last few months.

Today we will focus on Windows Azure Mobile Services. First of all, what is it?

Long story short, Windows Azure Mobile Services allows you to expose your data through JSON web services. Microsoft provides SDKs for Windows Store and Windows Phone 8 apps, pre-configured projects for iOS and Android, and JavaScript libraries for HTML.

The SDKs offer a large number of methods that provide access to your data stored in Azure.

So let us create a new CodeFluent Entities project. As an example for this article, we will use the “advertising sample” model. I will also add a class library project which will contain our SQL scripts.

We will not need more for this article since we are just going to generate the SQL Azure database with CodeFluent Entities.

First, we will add the SQL Azure Producer to our project. Regarding the configuration of the producer, we will only set the property “Produce Scripts” of the SQL Azure section to “true”.


Also, and this is really important, we will set the “Produce Schema” property to “true”. This property can be found by clicking on the “Advanced Properties” button as shown in the following screenshot.


You may wonder why this is so important. It is simply because Windows Azure Mobile Services will use the name we are going to define for our service to map it with the schema name of our database tables. So choose it carefully!

In this example, we are going to name our schema “sampleadvertising”. To do so, we have to open the properties of our entities and fill in the schema property as shown below.


Once we have updated the “Schema name” property of each entity we want to expose, we can build our project to produce our database.

When the project has been produced, check the database in SQL Azure to make sure we have our custom schema name on our tables.


Let us go back on Windows Azure to create our mobile service. According to the schema name we used in this example, we will name it “sampleadvertising” and we will associate it with the database created earlier.



Now that our service has been created, click on the “Data” tab of our service to “add a table”. Here we will add tables which names are identical to our database tables; for instance, “Campaign”.



Note: for the purpose of this article we will set the authorization for all CRUD methods to “Everyone”. Do not do the same on production especially if you work with sensitive data.

Those tables are not new database tables, they are only created to associate the tables created thanks to CodeFluent Entities with our mobile service and therefore expose our database data.

Once the table is added, we can access our data from everywhere in a standardized format.


From now on, we will show how to use our data from a sample Windows Store application.

First of all, we need to install the Windows Azure Mobile Services SDK which can be found at this address:

Once the SDK is installed, let us add a new project to our solution, a blank C# Windows Store app, named “SampleAdvertising.App”.

Then add a reference to the SDK we have previously installed.


Let us open the file “App.xaml.cs” to register our mobile service. In our case, we will add the following code:

    <br />public static MobileServiceClient MobileService = new MobileServiceClient(&quot;;);     <br />

In this particular example, we will not need to register the application key since we have set the permissions to “everyone”.

Now that our service is registered, I will show you how to consume our database data.

For instance, we will query our table “Customer” to get the customer “SoftDia”. To do so, we will create an async method that will get our “Customer” table. Then we will use the “ReadAsync” method with a query filter based on our “Customer_Name” column.

Finally, we will get a JsonObject from this IJsonValue and display its content in our Visual Studio output.

Here is the code used:

    <br />GetCustomerByName(&quot;SoftDia&quot;);</p>  <p>private async void GetCustomerByName(string customerName)</p>  <p>{</p>  <p>IMobileServiceTable customerTable = App.MobileService.GetTable(&quot;Customer&quot;);</p>  <p>IJsonValue myCustomer = await customerTable.ReadAsync(&quot;$filter=(Customer_Name eq '&quot; + customerName + &quot;')&quot;);</p>  <p>JsonObject myCustomerObject = myCustomer.GetArray()[0].GetObject();</p>  <p>foreach (var item in myCustomerObject)</p>  <p>{</p>  <p>Debug.WriteLine(item.Key.ToString() + &quot;: &quot; + item.Value.Stringify());</p>  <p>}</p>  <p>}    <br />

And this is what we get from our “Customer” table



Aymeric ROLAND

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.



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’.



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)
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        string result = reader.ReadToEnd();

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()))

//----- reading the response
string result = "";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    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.


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.


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

    CodeFluent Entities and JSON/REST

    November 29, 2012 Leave a comment

    In a previous post we announced that CodeFluent Entities natively support JSON/REST.

    In this post we’re going to see how to take advantage of the generated JSON/REST architecture. Thanks to JSON WCF services we should be able to call server methods from the client of our choice. To illustrate that we’re going to create a back end application exposing JSON WCF services that will be consumed in a console application. As you’re going to see, all the hard work will be done by CodeFluent Entities.

    Creating the solution

    Start by creating a new CodeFluent Project. We’ll use the “ContactManager Sample Model” for the purpose of this article.ContactManagerModel

    • Add a new Class Library project named “ContactManager” to your solution. It will be used to host the generated files corresponding to your Business Object model and JSON WCF service’s contracts.
    • Add a new SQL Server Database project named “ContactManager.Persistence” to your solution. It will be used to host your generated SQL scripts.
    • Add a new Empty ASP.NET Website project named “ContactManager.BackEnd” to your solution and add a reference to the ContactManager project and create a “Services” folder. It will be used to host the JSON WCF Services.
    • Add a new Console Application project named “ContactManager.Client” to your solution and add a reference to the ContactManager project and to CodeFluent.Runtime.dll. We will use it to make some calls via JSON WCF to the backEnd application and display the results in the console. Also, by default, Microsoft Visual Studio 2010 sets the target framework to .NET Framework 4 Client Profile. Go to the property of your project and change its target to .NET Framework 4.

    Adding the producers

    • Add a Business Object Model Producer and set its Target Directory to the ContactManager project. Also add it a Service Object Model Sub Producer and configure it so JSON been enabled and no proxy been produced. This producer will generate the complete WCF-based communication layer (service, contracts) with native JSON/REST support.
    • Add a SQL Server Producer and set its target directory to the ContactManager.Persistence project.
    • Add a Template Producer and set its Target Directory to the the Services folder of your ContactManager.BackEnd project. Also set its Source Directory to “CodeFluent Entities installation folder > Modeler >Templates > ServiceModel > JsonWebServices > Services”.

    Configuring the solution

    Configure your solution so it first start your  ContactManager.BackEnd application and then your ContactManager.Client application.

    Generating code

    Now to start generating code, build your CodeFluent Entities project called ContactManager.Model.

    Here is the visual studio solution you should have by now, each project containing the generated code (your database should have been created too):


    Writing the client

    When the WCF Service Object Model Producer is set to generate JSON web services, it automatically adds two extra operations to the Business Object model and Services:
    1. JsonGet
    2. JsonPost

    As the name suggests, you can use those methods to read (JsonGet) or write (JsonPost) by calling any other operation available on the service.

    So why not use the other operations directly instead?
    Well you can (using HTTP POST method and the header Content-Type set to application/json), but what’s interesting with those JsonGet/Post methods is that they add extra JSON oriented features. One of them being able to wrap .NET exception in a nice and simple JavaScript-friendly object.

    Note: JsonGet and JsonPost methods are not fully documented yet but a new version of the documentation is on its way.

    Here we want to use the JsonGet method in our console application to call the default generated LoadAll method and write the result on the console:

    we can break the task down to the following steps:

    • Set up the URL with all parameters
    • Send a GET WebRequest
    • Receive the Json formatted data
    • Deserialize the object(s)
    • Write the result on the console

    Therefore, our console application should look something like this:

    using System;
    using System.Net;
    using System.IO;
    using CodeFluent.Runtime.Utilities;
    using ContactManager;
    namespace ContactManager.ConsolApp
        class Program
            static void Main(string[] args)
                Console.WriteLine("Type a key to start");
                string url = "http://localhost:62738/Services/ContactManager.Customer.svc/JsonGet?method=LoadAll";
                string jsonContent = GET(url);
                //Let's display the RAW JSON content first:
                Console.WriteLine("JSON Content:");
                Console.WriteLine(jsonContent + Environment.NewLine);
                //Then each Customer:
                Console.WriteLine("From deserialized content:");
                CustomerCollection customers = JsonUtilities.Deserialize<CustomerCollection>(jsonContent);
                foreach (Customer c in customers)

    Notes: the URL should be changed according to your configuration (port number, and service name should be updated);

    The GET method simply downloads and returns the internet string response as follow:

    // Returns JSON string
    private static string GET(string url)
        using (WebClient client = new WebClient())
                return client.DownloadString(url);
            catch (WebException ex)
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                    StreamReader reader = new StreamReader(responseStream, new System.Text.UTF8Encoding());
                    String errorText = reader.ReadToEnd();

    But where do we find the JSON Serializer? Well the CodeFluent Runtime (CodeFluent.Runtime.dll) comes with a very convenient class: JsonUtilities.
    The JsonUtilities class is a simple yet powerful JSON Serializer allowing you to convert your .NET objects into JSON and vice versa. See that post for more information.

    Running the application

    Hitting Ctrl+F5 should build and launch your backend application and then your console application. Typing a key should retrieve all the customers using JSON WCF services and display them on the console as follow:

    Type a key to start
    JSON Content:

    From deserialized content:
    LastName=Nes,FullName=,BirthdayDate=1/1/0001 12:00:00 AM,LoyaltyProgramMember=False,LicenseNo=,HasPreAccidents=False,Age=0,
    Address=<null>,_addressId=-1,Rentals=[Count=0],PaymentType=Cash, EntityState=Unchanged]
    Press any key to continue . . .


    What about saving data? Well, we would use the JsonPost method instead of JsonGet and use the JsonUtilities.Serialize method to serialize our content. The Main method of our console application would look like this:

    static void Main(string[] args)
        string url = "http://localhost:62738/Services/ContactManager.Customer.svc/JsonPost?type=EntitySaveCall";
        Customer c = new Customer { FirstName = "John", LastName = "Doe", Age = 42 };
        string jsonContent = JsonUtilities.Serialize(c);
        POST(url, jsonContent);

    And the POST method to send the data:

    // POST a JSON string
    private static void POST(string url, string jsonContent)
        using (WebClient client = new WebClient())
            string response = string.Empty;
            //We need to specify that we are sending Json contents, or our
            //requests will be rejected by the services
            client.Headers.Add("Content-Type: json; charset=UTF-8");
            client.Encoding = System.Text.Encoding.UTF8;
                response = client.UploadString(url, jsonContent);
            catch (WebException ex)
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                    StreamReader reader = new StreamReader(responseStream, new System.Text.UTF8Encoding());
                    String errorText = reader.ReadToEnd();

    This is it! This post highlighted the fact that we can directly consume JSON WCF services generated by CodeFluent Entities from the client of our choice (for instance for Windows Phone, iOS or Android to name but a few). CodeFluent Entities doing all the hard work for us by generating applications based on REST/JSON architecture in a couple of minutes.

    Hope this helps!


    Thibault NESTOR

    CodeFluent Entities: ASP.NET AJAX/JSON Producer sneak peek

    June 8, 2012 1 comment

    In the previous post we’ve seen how to generate in a few minutes an ASP.NET AJAX/JSON web site using the brand new producer (watch-out it’s pre-release software!), well here’s a sneak peek of what gets generated Smile


    The homepage generated by default lists all namespaces and their contained entities:

    04 - Result


    Clicking on an entity gets you to the entity page:

    05 - EntityPage


    On the entity page you’ll find a screenshot of the entity from which this page was generated. On the left side of the page you’ll find a list of actions available on this entity which correspond in fact to business methods provided by the entity:



    The generated web site uses jQuery to contact JSON web services to retrieve the data, and jQuery UI and jqGrid to display it. By the way, you’ll notice the generated web site supports jQuery UI themes out-of-the-box:

    06 - Themes



    Carl Anderson

    CodeFluent Entities: Generate an ASP.NET Ajax/JSON web site in 5 minutes

    June 8, 2012 2 comments

    A brand new ASP.NET Ajax/JSON Producer is shipped (in alpha) with the latest build available (663 and upper). As we’d love to get some feedback on what you think of it and since it’s for now undocumented pre-release software, here’s a quick guide explaining how to generate an ASP.NET Ajax/JSON web site using this shiny and new UI producer Winking smile

    Warning: this producer is only available with C#, and not with VB.

    In this post I’m assuming you already have CodeFluent Entities up and running (installed, activated, and SQL-DMO installed to generate and deploy SQL Server databases).

    Start Visual Studio, and from the brand new “CodeFluent Entities” menu, select “Starter Wizard”:

    01 - StarterWizard

    This will launch Visual Studio’s “File > New > Project..” window in the section and from which we’ll select “Starter Wizard“:

    02 - StarterWizardProject

    Name our project “Demo.ContactManager” and click “OK” to launch the wizard.

    From there, follow the steps:

    • Select the “Demo.ContactManager” model,
    • Select the “ASP.NET Ajax/JSON” architecture,
    • Select the “C#” language,
    • Keep default client project name to “Demo.ContactManager.Web”,
    • Select “SQL Server” as database,
    • Set-up your connection string
    • And finish the wizard.

    This will create your entire solution (solution, projects, add and configure producers to point to those projects):

    03 - CreatedSolution

    Right-click on the “Demo.ContactManager.Model” project and select “Build “ to build your project:

    • Doing this will generate database scripts and deploy them on your configured database,
    • Generate the .NET classes in the Demo.ContactManager class library and add required references so you can compile right-away,
    • Generate your ASP.NET Ajax/JSON web site!

    Set the “Demo.ContactManager.Web” project to be the start-up project, and hit F5 to start playing with the stuff!


    Any feedback? Share it on this blog, on our forums or on our Facebook page!



    Carl Anderson