Archive

Posts Tagged ‘WCF’

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

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

ScreenShot051

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");
            Console.ReadKey();

            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)
            {
                Console.WriteLine(c.Trace());
            }
        }

    }
}

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())
    {
        try
        {
            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();

                Console.WriteLine(errorText);
            }
            throw;
        }
    }
}

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:
[{“EntityKey”:”1″,”EntityDisplayName”:”info@softfluent.com”,”RowVersion”:[0,0,0,0,0,0,7,209],”Id”:1,”EmailAddress”:”info@softfluent.com”,”Password”:null,
“FirstName”:”Thib”,”LastName”:”Nes”,”FullName”:null,”BirthdayDate”:”\/Date(-62135596800000)\/”,”LoyaltyProgramMember”:false,”LicenseNo”:null,”HasPreAccidents”:false,
“Age”:0,”AddressId”:-1,”Rentals”:[],”PaymentType”:0,”EntityState”:1}]

From deserialized content:
[Id=1,EmailAddress=info@softfluent.com,Password=,FirstName=Thib,
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;
        try
        {
            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();

                Console.WriteLine(errorText);
            }
            throw;
        }
    }
}

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!

Cheers,

Thibault NESTOR

Generating a WPF Smart Client using the Smart Client Producer

October 22, 2012 Leave a comment

Hello!

In a previous posts, we showed you the output of the WPF Smart Client Producer. In this post we’ll show you how to generate a WPF smart client. It will be a WPF application consuming WCF services thanks to a proxy and the data will be stored in a database Smile.

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 WCF service’s contracts. Add it a folder called “ServicesConfig” that will be used to store your WCF service’s configuration files.

Add a new Class Library project named “ContactManager.Proxy” to your solution. It will be used to host the generated files corresponding to the proxy.

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 WPF application project named “ContactManager.SmartClient” to your solution. It will be used to host the generated files of your WPF application. Remove the MainWindow.xaml file since we are going to generate our own. 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 the target to .NET Framework 4 in order to use the standard libraries.

image

Adding the producers

The Business Object Model Producer

To generate your Business Objects model, add the Business Object Model Producer to your CodeFluent Entities project by clicking “Add new producer” on the “Producers” folder in Visual Studio’s Solution Explorer, expand the Business Layer Producers node and select it:

image

In the Target Directory field, select your Class Library project called ContactManager.

image

Click OK.

The SQL Server Producer

To generate your persistence scripts, add the SQL Server Producer (or the one that suits your configuration) to your CodeFluent Entities project by clicking “Add new producer” on the “Producers” folder in Visual Studio’s Solution Explorer, expand the Persistence Layer Producers node and select it:

image

In the Connection String field enter your connection string used to connect to your SQL Server. Also in the Target Directory field, select your SQL Server Database project called ContactManager.Persistence. Finally in the Target Version field, select your SQL Server version.

The Service Object Model Producer

To generate your WCF service and your proxy, add the Service Object Model Producer to your CodeFluent Entities project by clicking “Add new SubProducer” on your  “Business Object Model” producer in Visual Studio’s Solution Explorer, expand the Business Layer Producers node and select it:

image

In the Target Directory field, select your Class Library project called ContactManager.Proxy and click OK.

The Template Producer

Note: The Template producer is not mandatory. However, it is really handy if you want to be able to quickly run and test your WCF service using the CodeFluent Entities Hoster.

Lets now generate the configuration files of your WCF service. Add the Template Producer to your CodeFluent Entities project by clicking “Add new producer” on the “Producers” folder in Visual Studio’s Solution Explorer, expand the Utility Producers node and select it:

ScreenShot032

In the Source Directory field select the “Server” folder located at “CodeFluent Entities installation folder > Modeler >Templates > ServiceModel”. And in the Target Directory field, select the folder called ServicesConfig located in your Class Library project called ContactManager, then click OK.

The WPF Smart Client Producer

Then, to generate your WPF smart client, add the WPF Smart Client Producer to your CodeFluent Entities project by clicking “Add new producer” on the “Producers” folder in Visual Studio’s Solution Explorer, expand the Application Producers node and select it:

image

In the Target Directory field, select your WPF application project called ContactManager.SmartClient and click OK.

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

image

Building and running the application

At this stage, your application has been generated and is almost ready to be built and run. Since your WPF application uses the Proxy you need to add your Class Library project called ContactManager.Proxy as a reference to your WPF application project called ContactManager.SmartClient project.

Now you can build your solution, then run your WCF service as you usually do or thanks to the CodeFluent Entities Hoster using your generated service configuration files. Finally start your WPF application.

Tip: If you use the CodeFluent Entities Hoster, a quick and easy way to ensure the executable is automatically copied to the output directory is to add a reference to it. This is absolutely not required to compile your Business Object model (your Class Library called ContactManager), it’s just a shortcut to have the executable in the output directory without having to create post-build events.

And tadaaa! You’ve created your 100% functional WPF smart client without a single line of code!

SmartClient (1)

SmartClient (2)

Enjoy!

Thibault Nestor

CodeFluent Service Host

October 11, 2012 1 comment

CodeFluent Entities is shipped with a very handy tool called the CodeFluent Service Host.

CodeFluent Service Host is a command line tool that enables you to easily host Windows services as well as Windows Communication Foundation (WCF) services. It takes care of all the plumbing: service registration, start, stop, multi threading, log and so on… It supports CodeFluent Generated services as well as other manually coded services.

Another sweet thing about it is that you can either use it in Console mode as well as in Windows Service mode. As a developer I found the Console mode very convenient since it allows me to quickly test my own services without having to install/uninstall them after each modification. Besides, you can print your traces and exceptions directly on the console! It also embeds a special out-of-the-box WCF exception handler that is capable of displaying WCF server errors without using any other external tool like the Service Trace Viewer.

The CodeFluent.Runtime.ServiceHost.exe can be found in your CodeFluent Entities installation directory. In order to work it needs only the following:

  • The hosted assembly containing the service(s) and its referenced assemblies
  • A standard .NET configuration file indicating the host which service to host.
    Note that if you use the Service Object Model Producer (provided out-of-the-box by CodeFluent Entities) to generate your services, it will automatically create the configuration file needed by CodeFluent Service Host. Thus to start your service in Console mode you’ll just have to run CodeFluent.Runtime.ServiceHost.exe.
    Here is an example of how to use CodeFluent Service Host in Windows Service Mode:

First we need to install the service. Here is the content of the InstallService.bat that will do it for us (This batch file can also be generated by the Service Object Model Producer):

CodeFluent.Runtime.ServiceHost.exe /i /name:MyServiceName 
/displayName:MyServiceDisplayName 
/description:"This service is a WCF services host"

Running the batch file will install your service. Then you’ll be able to manage your service as any other windows services thanks to the Windows Administration Services console:

CodeFluent Service Hoster - Windows Service

More info in the documentation can be found here.

Note in the latest builds, CodeFluent Service Host is available in 4 editions:

  • CodeFluent.ServiceHost.exe 32-bit (CLR2)
  • CodeFluent.ServiceHost4.exe 32-bit (CLR4)
  • CodeFluent.ServiceHost.exe 64-bit (CLR2)
  • CodeFluent.ServiceHost4.exe 64-bit (CLR4)

Of course, if you use a .config file, it will have to follow the .exe name, sor for the CLR4 versions, the config file will have to be named CodeFluent.ServiceHost4.exe.config.

Cheers,

Thibault Nestor

CodeFluent Entities is not an ORM

March 20, 2012 1 comment

CodeFluent Entities is a unique product integrated into Visual Studio 2008/2010/vNext which allows you to generate components such as scripts (e.g. T-SQL, PL/SQL), code (e.g. C#, VB), web services (e.g. WCF, ASMX) and UIs (e.g. ASP.NET, SharePoint, WPF).

The code generation process is model-first and continuous: from your declarative model, a meta-model will be inferred which code generators will then translate into code. Over 20 code generators (a.k.a. “producers”) are provided “out of the box” and can be combined to create your own application following your desired architecture, using your desired technologies.

For instance, adding an instance of the SQL Server Producer to your project will translate your model into a database (schemas, tables, stored procedures, views, constraints, etc.):

Adding an instance of the Business Object Model Producer will translate your model into .NET classes (C# or VB.NET) consuming the persistence layer:

Adding a WCF Producer will generate WCF services, contracts and proxies exposing your .NET classes:

Adding a WPF Smart Client Producer will generate a WPF application consuming the WCF services thanks to the generated proxy:

And that’s just an example of what you can do: you can also build ASP.NET web sites, SharePoint apps, Windows Forms apps, Silverlight apps, etc.

Your application is layered following best practices, all its business logic is in the middle-tier (the Business Object Model generated by the Business Object Model producer), and supporting a new technology gets down to adding a new producer or creating screens on the generated code.

Last but not least, you can create your own producer which translates this inferred meta-model into what you need.

 

Cheers,

Carl Anderson

CodeFluent Entities Webcast – December 6th 2011: Follow-up

December 16, 2011 Leave a comment

CodeFluent Entities Webcast – December 6th 2011

December 9, 2011 2 comments

In this webinar a product team member demonstrates CodeFluent Entities.

Watching this webcast you’ll see:

  • How to generate entire .NET applications from scratch
  • How to absorb functional changes smoothly thanks to continuous generation
  • How to decouple your business logic from technology
  • How to import an existing database

Technologies featured in this product demonstration are:

  • CodeFluent Entities,
  • Visual Studio 2010,
  • Microsoft SQL Server,
  • .NET (C#),
  • .NET Console Application,
  • Windows Communication Foundation (WCF),
  • Windows Presentation Foundation (WPF),
  • ASP.NET MVC,
  • Microsoft Access

Here’s a recording of the full webcast:

CodeFluent Entities Webcast (2011-12-06)

Note: Watch the video in HD by selecting the 720p option instead of the default 360p on the bottom right section of the player.

CodeFluent Entities introduces JSON/REST native support

September 9, 2011 2 comments

Here’s a quick post regarding JSON/REST support in CodeFluent Entities which was introduced in the latest developer build (603).

Starting from this build, the Service Object Model sub-producer which generates the complete WCF-based communication layer (service, contracts, and proxy) now supports natively JSON/REST. Enable the JSON support, and it will automatically generate WCF services decorated with the proper attributes to be consumed in JSON/REST.

Here’s how to enable the feature:

JSONOptions

Once you configured this sub-producer and built your model over again here’s the kind of code you should see:

public partial interface ICustomerService
{
(…)
[System.ServiceModel.OperationContractAttribute()]
[System.ServiceModel.Web.WebInvokeAttribute(UriTemplate="LoadAll", ResponseFormat=System.ServiceModel.Web.WebMessageFormat.Json, RequestFormat=System.ServiceModel.Web.WebMessageFormat.Json, BodyStyle=System.ServiceModel.Web.WebMessageBodyStyle.Wrapped)]
Sample.CustomerCollection LoadAll();
(…)

As you can see, each method:

  • has its own URI corresponding to its name (defined by the UriTemplate attribute) (e.g. to call the LoadAll method we will call the following URL: http://server/EntityName.svc/LoadAll),
  • expects JSON objects as parameters (RequestFormat), so the content-type of our requests will always be application/json,
  • will send a JSON object as a response (ResponseFormat),
  • will wrap the response in an object (BodyStyle). This object will have one only field named [MethodName]Result,
  • expects to be called with the Http POST method (this is the default value of the WebInvoke “Method” parameter).

To expose those services on a web server use ".svc" files such as the following:

<%@ServiceHost language="C#" Debug="true" Service="Sample.Services.CustomerService" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>       

This allows, without a single line of code behind nor any particular configuration, to call the appropriate service from a URL.
From the client’s point of view you’ll then be able to call the service using the following ways.
For instance, to load all customers from our customer service, the client must call:
- URI: http://localhost/JsonSample/Services/Sample.Customer.svc/LoadAll,
- With the http POST method and the header Content-Type set to application/json,
- With an empty content parameter.
And the client will receive a JSON object such as this one: {“LoadAllResult”:[{…CustomerJsonObjects…}]}.

Note: in this example my web application is hosted in IIS, in a “JsonSample” virtual application in my default site. Moreover, my .svc files are all placed in a "Services" sub-folder. The url will of course differ depending on where you’re hosting your web application.

Here’s an implementation example in an ASP.NET web page using JQuery:

(…)
<script type="text/javascript" src="scripts/jquery-1.6.3.min.js"></script>
(…)
    <div id="Container">
        <div id="Content">
            <p>
                Hello!<br />
                Here’s a sample page calling the LoadAll method of the customer service and printing the results returned by the service using JQuery:
            </p>
        </div>
        <div id="CustomerBlock">
            <div id="CustomerContent">
            </div>
        </div>
    </div>
(…)
<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            type: "POST",
            url: "http://localhost/JsonSample/Services/Sample.Customer.svc/LoadAll&quot;,
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data, textStatus, jqxhr) {
                $(‘#CustomerContent’).html("<p>" + jqxhr.responseText + "</p>");
            },
            error: function(jqxhr, errorText, ex) {
                $(‘#CustomerContent’).html("<p>Error: " + ex + "</p>");
            }
        });
    });
</script>

Consuming methods with parameters is almost the same.
For instance to load a customer of Id=1, the client must call:

And the client will receive a response like: {"LoadResult":{…CustomerJsonObject…}}.

Enjoy Smile

Follow

Get every new post delivered to your Inbox.

Join 52 other followers