Archive

Posts Tagged ‘CodeFluent Entities’

CodeFluent Entities and Syncfusion for an amazing application!

April 15, 2013 Leave a comment

When applications are beautiful, fast and robust at the same time, we qualify them as amazing. If you think it also means a long development process, then you have not seen applications using both SoftFluent and Syncfusion products altogether!

SoftFluent and Syncfusion have partnered to help you build these amazing applications in no time.  CodeFluent makes the application highly functional, while Syncfusion makes the application interface elegant and user-friendly.

CodeFluent Entities is a unique product integrated into Visual Studio which allows developers to generate database scripts, code, web services and UIs in the Microsoft .NET platform. 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.

Syncfusion, Inc. provides the broadest range of enterprise-class software components and tools for the Microsoft .NET platform. With Syncfusion, developers can move beyond simply coding applications to delivering real business innovation—the elegant user interfaces, business intelligence dashboards, and sophisticated reporting that today’s business users need, in the formats they demand.

Whether you need to build applications with WinForms or WPF, or websiteswith WebForms or MVC, SoftFluent and Syncfusion provide all the necessary tools to help you.

To show you how it works, we built a full application using CodeFluent Entities and Syncfusion components. With Visual Studio 2012, we have created a WPF application that consumes web services to communicate with an SQL Server 2008 database. The database we used is a sample database of Microsoft SQL Server, called AdventureWorks.

.

The application can be created in five steps:

.

1. CodeFluent Entities project

Create a CodeFluent Entities project in Visual Studio 2012. You also need a class library project that contains the business-object model, a class library project (Proxy) that contains your web service contracts, and the WPF application.

.

2. Import the AdventureWorks database

If you right-click on the CodeFluent Entities project, you will have the option to import an existing database or model as you can see on the screenshot below.

1

Then follow the instructions to import the AdventureWorks database.

.

3. Set up the producers

Once the database has been imported, you can view the visual model inside the CodeFluent Entities project (Surface > Default) as you can see here:

2

Now that you have your model, you need to add producers. These producers are responsible for generating code for your application.

The first producer is the BOM (Business Object Model) producer, which corresponds to the business logic. The code generated will be classes for each entity of your model. This code is exceptionally readable and can be customized using partial classes, if needed. Also, this producer contains a sub- producer responsible for generating services.

The second producer is the SQL producer responsible for generating SQL scripts, such as tables, views, and stored procedures.

The third producer is the WPF ClickOnce Smart Client, which is responsible for generating UIs. These UIs are generated using templates, located in the CodeFluent Folder. We will discuss this in more detail later.

The fourth producer is the Template, responsible for creating a host for the web services.

The fifth producer is the Command Line Execution producer, responsible for running a batch file that will insert data in your database.

3

.

4. Generation

The model is ready to be generated. In a single click, the CodeFluent Entities project will load your model in memory, and run each of the producers to generate ASP.NET code (C# in this example), SQL scripts and WPF controls. The application is almost ready to run. The last steps are to:

  1. Set up the connection string in your WPF application.
  2. Set up the application that hosts the web services to run at the same time as the WPF application.

That is all you need to do in order to run the application! When you launch the application, you will have a list of all entities, and you will be able to manipulate the data of these entities with generic methods such as load, load all, update, delete, and save. Each of these actions will consume the web services that are being hosted in the other application.

.

5. SyncFusion Components

The full running application uses standard ASP.NET controls for your WPF application. Though these components are functional, they are not always the best-looking ones. This is where Syncfusion comes in to transform a functional application into an amazing application.

CodeFluent Entities generates reusable controls for the application, so that one control can be used in several pages. As a result, the work consists in updating these ASP.NET standards controls by using Syncfusion controls, to end up with a highly functional and beautiful application:

4

Interface displaying the list of departments

.

5

Interface displaying the edition of a department in a popup

.

6

Interface displaying the edition of the SalesTerritory field that corresponds to a list prefilled with a related entity

.

Using the power of CodeFluent Entities to generate functional applications quickly, and the power of Syncfusion’s beautiful components, you can create amazing applications in no time.

.

6. Unlimited possibilities

To go further with CodeFluent Entities and Syncfusion integration, you can reuse Syncfusion components in other applications at no cost. Indeed, CodeFluent Entities uses templates to generate components, such as the view page, the edit form and so on. These templates are available in the CodeFluent folder (where it was installed, usually in \CodeFluent\Modeler\Templates\SmartClient).

Extremely simple to read and to understand, these templates can be modified to produce pages with custom components, such as the ones provided by Syncfusion. By doing so, each CodeFluent Entities project can reuse these templates to produce amazing applications. Although you have developed a WPF application in this example, you can do the same with all other types of applications, such as WinForms, WebForms, MVC, mobile or any combination of these technologies.

.

If you want to download the sample project demo please click here: http://www.softfluent.com/downloads/AdventureWorksReloaded.zip

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

1

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.

2

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.

3

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.

4

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.

5

6

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

7

8

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.

9

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: https://go.microsoft.com/fwLink/?LinkID=257545&clcid=0x40C

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.

10

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;https://sampleadvertising.azure-mobile.net/&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

11

Cheers,

Aymeric ROLAND

Using ServiceStack with CodeFluent Entities

March 6, 2013 Leave a comment

In our last blog post we saw how to create a REST service layer using ASP .NET Web API and a CodeFluent Entities model.

Now we are going to use ServiceStack to expose HTTP web services (JSON and XML) from an existing CodeFluent Entities model.
ServiceStack is a REST Web Service Framework for .NET, it is an open source project that you can find here.
ServiceStack is based on a ‘modular’ architecture and it was built to be used in a simply way, no XML configuration and no code generation.
The ‘philosophy’ behind ServiceStack is to use strong-typed DTOs to define a web service API.
To illustrate this post we are going to use the Car Rental Sample project.

CarRental Sample  project

CarRental Sample project



We will add a Persistence producer (SQL Server 2012 for me) and a Business Object Model (BOM) producer.

Producers

Producers



ServiceStack can be used as a standalone solution or can be integrated on a MVC application, we are going to use it in an empty ASP .NET web application.

ASP .NET Web Application

ASP .NET Web Application



First of all we need to install ServiceStack in our ASP .NET web application project via nugget:

       PM> Install-Package ServiceStack

Now we need to register ServiceStack in our configuration (web.config), we want to host ServiceStack at the root path (‘/’) so we use this configuration:

<system.web>
  <compilation debug="true" targetFramework="4.5" />
  <httpRuntime targetFramework="4.5" />
  <httpHandlers>
    <add path="*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*"/>
  </httpHandlers>
</system.web>

If you want register ServiceStack on a custom path to avoid conflicts with another web framework (eg. ASP .NET MVC) go here.

ServiceStack uses a particular structure for services, a service consists in:

  • A request DTO
  • A service implementation
  • A response DTO

We are going to create a service that handles CRUD operations for the Entity ‘CarGroup’ (you can add some instances to your model so we have some test data).

We start by creating the request DTOs:

[Route("/carGroup", "GET")]
public class GetAllCarGroupRequest : IReturn<CarGroupCollection> { }

[Route("/carGroup/{Id}", "GET")]
public class GetCarGroupRequest : IReturn<CarGroup>
{
    public int Id { get; set; }
}

[Route("/carGroup/{Id}", "DELETE")]
public class DeleteCarGroupRequest
{
    public int Id { get; set; }
}

As you can see we also have associated some routes to our requests.
For the create and update methods (POST and PUT) we will add the request configuration elsewhere because we want to use existing classes as requests (the CarGroup class that will be the object to add or update), we will see this further in this post.
Now we need to create our service and it operations. I will call my service ‘CarGroupService’ and it will inherit from the class ‘ServiceStack.ServiceInterface.Service’.

public class CarGroupService : ServiceStack.ServiceInterface.Service
{
}

ServiceStack will ‘match’ a request to an operation and associate HTTP actions (verbs) to the name of our operations, so our operations must follow some conventions:

public {ResponseDTO} {HTTPVerb}({RequestDTO} request)

Now we can create our operations.

To retrieve all our CarGroup objects:

public CarGroupCollection Get(GetAllCarGroupRequest request)
{
    CarGroupCollection carGroups = CarGroupCollection.LoadAll();
    return carGroups;
}

To retrieve one CarGroup by its id:

public CarGroup Get(GetCarGroupRequest request)
{
    CarGroup carGroup = CarGroup.Load(request.Id);
    if (carGroup == null)
    {
        throw new HttpError(System.Net.HttpStatusCode.NotFound, "Car Group not found");
    }
    return carGroup;
}

To add a new instance of CarGroup or to update an existing instance we will use a common method:

private HttpResult CreateUpdate(CarGroup carGroup)
{
    if (carGroup == null || !carGroup.Save())
    {
        return new HttpResult(System.Net.HttpStatusCode.BadRequest, "Error while saving.");
    }
    return new HttpResult(carGroup, System.Net.HttpStatusCode.OK);
}

And we will call this method for create (POST) and update (PUT) operations:

public HttpResult Post(CarGroup request)
{
    return CreateUpdate(request);
}
<br/>
public HttpResult Put(CarGroup request)
{
    return CreateUpdate(request);
}

Finally, to delete an instance of CarGroup:

public HttpResult Delete(DeleteCarGroupRequest request)
{
    CarGroup carGroup = CarGroup.Load(request.Id);
    if (carGroup != null && carGroup.Delete())
    {
        return new HttpResult(System.Net.HttpStatusCode.NoContent, "Car Group deleted");
    }
    return new HttpResult(System.Net.HttpStatusCode.NotFound, "Car Group not found");
}

We have created all the operations and their associated requests. Now we have to register our web service.

We start by creating an AppHost for our service that inherits from ServiceStack.WebHost.Endpoints.AppHostBase where we can configure our service if we need to, I will use the default configuration:

public class CarGroupAppHost : AppHostBase
{
    //Tell Service Stack the name of your application and where to find your web services
    public CarGroupAppHost() : base("CarGroup Web Services", typeof(CarGroupService).Assembly) { }

    public override void Configure(Container container)
    {
        Routes
            .Add<CarGroup>("/carGroup", "POST")
            .Add<CarGroup>("/carGroup", "PUT");
    }
}

We have added the route configuration for our create (POST) and update (PUT) operations.

Now in the Global.asax.cs file (you need to create it if it does not exist) we initialize our service host:

public class Global : System.Web.HttpApplication
{

    protected void Application_Start(object sender, EventArgs e)
    {
        new CarGroupAppHost().Init();
    }
}

We can found some information about our operations on the url ‘http://server/metadata’, in my case http://localhost:4305/metadata.

Service metadata information

Service metadata information



And that is all, we can test now our service, we will use a Console application.

For example to retrieve all our Car Groups:

string uri = "http://localhost:4305/carGroup";
HttpWebRequest request = HttpWebRequest.CreateHttp(uri);
request.Accept = "application/json";//we only accept JSON
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 we get:

Get all data service result

Get all data service result



Let’s now test the creation of a new CarGroup:

string uri = "http://localhost:4305/carGroup";
HttpWebRequest request = HttpWebRequest.CreateHttp(uri);
request.Accept = "application/json"; //we only accept JSON
request.Method = "POST";
request.ContentType = "application/json; charset=UTF-8";//we will send JSON

string bodyData = "{\"Name\":\"Super Sport\",\"Category\":\"Mega Sport\"}";

//----- 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();
        Console.WriteLine(result);
    }
}

We have just seen how CodeFluent Entities can be easily integrated to ServiceStack.

ServiceStack is a very powerful framework to write Web APIs, you can find more information about ServiceStack and all the features it provides here.

Regards.

Pablo Fernandez Duran

Get started with the CodeFluent Entities API

March 6, 2013 Leave a comment

The CodeFluent Entities API has been around for a while, and this post will help you get started with it! If I tell you that the API is very easy to use and extremely powerful, you will not believe me. Hopefully, you will believe me by the end of this post.

We assume that we have a CodeFluent Entities solution, with its CodeFluent project and its class library for the BOM. We also have created an empty console application.

In this console application, we need to reference 3 libraries:

  • CodeFluent.Model
  • CodeFluent.Model.Common
  • CodeFluent.Runtime

We are now ready to write some code. First we need to load the CodeFluent model, which is a cfp file. This cfp file is an XML file that corresponds to our CodeFluent Entities model:

Project project = new Project();
project.Load(@"c:\path\to\model\myModel.cfp");

The next step is to navigate through the model, and this is where things get easier!

foreach (Entity e in project.Entities)
{
    Console.WriteLine("Entity: " + e.Name);
    foreach (Property p in e.Properties)
    {
        Console.WriteLine(" |- Property: " + p.Name);
        // insert code below here
    }
}

If this code does not try to edit the model, it shows you that the API is very straight forward. In a few lines, the API lets you navigate through every property of every entity of your ALL model! And yes, you can also read every attribute of each property, read the methods, rules…

Now, let us try to modify the model. We will look at the default value of each property, and modify some of them:

if (!string.IsNullOrEmpty(p.DefaultValue))
{
    switch (p.DefaultValue)
    {
        case "MyDefaultTitle":
            Console.Write("DEFAULT VALUE: " + p.DefaultValue + " was changed to: ");
            p.DefaultValue = "Title";
            Console.Write(p.DefaultValue + Environment.NewLine);
            break;
        case "Sample2":
            Console.Write("DEFAULT VALUE: " + p.DefaultValue + " was changed to: ");
            p.DefaultValue = "Sample1";
            Console.Write(p.DefaultValue + Environment.NewLine);
            break;
        case "Sample1":
            Console.Write("DEFAULT VALUE: " + p.DefaultValue + " was changed to: ");
            p.DefaultValue = "Sample2";
            Console.Write(p.DefaultValue + Environment.NewLine);
            break;
    }
}

We are looking for three default values (“MyDefaultTitle”, “Sample1″, “Sample2″) and we are modifying them. There is one last thing to do, which is to save the model.

project.Package.Save();

The save method needs to be inserted at the end of your method, outside the for loops.

In this example, you have learned how to use the API to modify your CodeFluent Entities model. To go further, you could add/edit/delete methods, rules, producers… The possibilities are almost limitless and yet, the API remains very easy to use. Have fun!

Vincent Patry

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

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

Using CodeFluent Entities x64 Tools

January 17, 2013 Leave a comment

In addition to the Visual Studio Integrated Modeler, CodeFluent Entities provides a set of tools in the form of executable files (.exe).

You can take a look in the installation directory of CodeFluent Entities to find these tools.

You will find:

For a more detailed description take a look at this blog post.

Well, these tools come in two versions: the x86 version and the x64 version.

The x86 version tools are located in \Program Files (x86)\SoftFluent\CodeFluent\Modeler while the x64 version in \Program Files (x86)\SoftFluent\CodeFluent\x64.

By Default, the CodeFluent Entities Modeler (integrated to Visual Studio) executes the x86 version tools, but maybe it would be interesting to use the x64 version (for instance, if you have a big model).

If you use the CodeFluent Entities Tools without its integration to Visual Studio you only need to look in to the wanted directory.

On the other hand, if you use the Visual Studio Integrated Modeler you can easily configure the Build Platform from the CodeFluent Entities Options. Check the “CodeFluent Entities Build – 32 Bits” option for a x86 platform or the “CodeFluent Entities Build – 64 Bits” option for a x64 platform.

CodeFluent Entities Options - Build Platform

CodeFluent Entities Options – Build Platform

Maybe you also noticed in the picture above that there is an option “CodeFluent Entities Build – CLR4”. Indeed, some tools are also built on the CLR4 (the rest is built on the CRL2) as:

  • The Builder (CodeFluent.Build4.exe)
  • The Service Host (CodeFluent.Runtime.ServiceHost4.exe)

Using a tool built on the CLR4 allows easier integration for custom assemblies (such as custom Aspects or Producers).

CLR2 tools can also be used with the CLR4 assemblies but it requires .config modifications.

The CLR4 tools exist in the x86 version, as well as in the x64 version.

Finally, using a x86 or a x64 tool has no impact when generating applications, as the product builds platform-agnostic code. You will be able to use “Any CPU”, X86, or X64 at your convenience.

Regards.

Pablo Fernandez Duran

Working with both the cache sub producer and the localization aspect

December 27, 2012 1 comment

Are you planning on using caching and localization for one of your CodeFluent Entities projects? If so, this article is for you.

CodeFluent Entities comes with a sub producer that handles cache in a simple and powerful way. The cache sub producer uses a class called SimpleCacheManager, which is based on the ASP.NET cache. Read more about the SimpleCacheManager class here: http://www.softfluent.com/documentation/BOM_Caching.html.

Also, CodeFluent Entities offers a variety of aspects, including the localization aspect. This localization aspect allows you to select properties that need to handle localized values. Read more about the localization aspect here: http://blog.codefluententities.com/2011/03/25/codefluent-entities-aspects/

At the moment, CodeFluent Entities does not support the use of both of these features at the same time. If you try to use them in a project, you will realize that objects are cached with the same key (this key is used to save/retrieve cached objects), regardless of the current localization.

The following model uses the cache sub producer, as well as the localization aspect. The label property of the Product entity is localized, and the cache sub producer uses the standard SimpleCacheManager class to handle the cache of our application:

<cf:import path="Default.Surface.cfp" />
<cf:pattern path="C:\Projects\sfdev01\CodeFluent\CodeFluent.FX2\CodeFluent.Model\Patterns\SoftFluent.Localization.xml" step="Methods" name="CodeFluent Localization Aspect" />
<cf:entity name="Product" namespace="Locali" categoryPath="/Locali">
    <cfpc:cache typeName="CodeFluent.Runtime.Caching.SimpleCacheManager, CodeFluent.Runtime" enabled="true"/>
    <cf:property name="Id" key="true" />
    <cf:property name="Label" _loc:localizable="true" />
</cf:entity>
<cf:producer name="Business Object Model (BOM)" typeName="CodeFluent.Producers.CodeDom.CodeDomProducer, CodeFluent.Producers.CodeDom">
    <cf:configuration compileWithVisualStudio="true" compile="false" codeDomProviderTypeName="CSharp" targetDirectory="..\LocaliCache" cfx:targetProject="..\LocaliCache\LocaliCache.csproj" cfx:targetProjectLayout="Update">
        <subProducer typeName="CodeFluent.Producers.Cache.CacheProducer, CodeFluent.Producers.Cache, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1bb6d7cccf1045ec" defaultEnabled="true" />
    </cf:configuration>
</cf:producer>
<cf:producer name="SQL Server" typeName="CodeFluent.Producers.SqlServer.SqlServerProducer, CodeFluent.Producers.SqlServer">
    <cf:configuration produceViews="true" targetDirectory="..\LocaliCache\Scripts" createDatabase="true" updateDatabase="true" cfx:targetProject="..\LocaliCache\LocaliCache.csproj" cfx:targetProjectLayout="Update, DontRemove" createDiffs="true" targetVersion="Sql2008">
    </cf:configuration>
</cf:producer>

Let’s use a console application to test this model.

static void Main(string[] args)
{
    Product p = new Product();
    Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
    p.Label = "name of the product";
    p.Save();
    Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR");
    p.Label = "nom du produit";
    p.Save();

    Guid id = p.Id;
    // US localization
    Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
    // first load, not cached
    p = Product.Load(id);
    Console.WriteLine(Thread.CurrentThread.CurrentUICulture.Name + ": " + p.Label);
    // second load, cached
    p = Product.Load(id);
    Console.WriteLine(Thread.CurrentThread.CurrentUICulture.Name + ": " + p.Label);
    // French localization
    Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR");
    // third load, cached
    p = Product.Load(id);
    Console.WriteLine(Thread.CurrentThread.CurrentUICulture.Name + ": " + p.Label);
    // fourth load, cached
    p = Product.Load(id);
    Console.WriteLine(Thread.CurrentThread.CurrentUICulture.Name + ": " + p.Label);
    Console.Read();
}

Running this program will output this:

en-US: name of the product
en-US: name of the product
fr-FR: name of the product
fr-FR: name of the product

While the first product is loaded from the database, the three other products are loaded from cache. Although the localization was changed, the cached products were retrieved from the same (cached) key.

Fortunately, CodeFluent Entities offers full flexibility of the cache sub producer, by letting you select your own cache handler! Let’s now build our own class that will handle the localization. To do so, we will create a class called LocaleCacheManager that extends the SimpleCacheManager class. In this example, a class is added to its own class library project, so that we can add its reference to our BOM project:

using System;
using System.Collections;
using System.Web.Caching;
using CodeFluent.Runtime.Caching;
using CodeFluent.Runtime.Utilities;
using System.Threading;
namespace Locali
{
    public class LocaleCacheManager : SimpleCacheManager
    {
        public override void Add(string domain, string key, object value, IDictionary context)
        {
            if (domain == null)
                throw new ArgumentNullException("domain");
            if (key == null)
                throw new ArgumentNullException("key");
             base.Add(domain, BuildKey(key), value, context);
        }

        public override void Remove(string domain, string key)
        {
            if (domain == null)
                throw new ArgumentNullException("domain");
            if (key == null)
                throw new ArgumentNullException("key");
            base.Remove(domain, BuildKey(key));
        }

        public override object Get(string domain, string key)
        {
            if (domain == null)
                throw new ArgumentNullException("domain");
            if (key == null)
                throw new ArgumentNullException("key");
            return base.Get(domain, BuildKey(key));
        }

        private static string BuildKey(string key)
        {
            return key + ":" + Thread.CurrentThread.CurrentUICulture.LCID;
        }
    }
}

This class overrides three methods and changes the key which is used to save and retrieve cached objects. The key is modified so that the culture (localization) is added to it. This allows one object to have multiple cached versions, depending on its localization.

Now, we need to update our model by modifying the class that will handle our cache:

<cfpc:cache typeName="Locali.LocaleCacheManager, Locali" enabled="true"/>

That’s all we need to do! We can now regenerate the model and run the application. The new output of our application is:

en-US: name of the product
en-US: name of the product
fr-FR: nom du produit
fr-FR: nom du produit

Our own cache sub producer works perfectly with the localization aspect!

What do you think? Any suggestions regarding this LocaleCacheManager class?

Note (2012/2/7): the LocaleCacheManager has been added to the CodeFluent.Runtime.dll (namespace CodeFluent.Runtime.Caching) starting with build 700.

Vincent Patry

CodeFluent Entities Summer Contest

August 7, 2012 Leave a comment

 

You are a developer? A blogger? If so, you may have chance to win one of the packages given away by SoftFluent!

So what’s the catch?

The only thing you have to do is to share your opinion through an article on your blog or on a public platform.

What an easy way to win some money!

The deadline for the contest is the 31st of August. So why are you still reading rather than clicking the following link to get more information!

http://www.softfluent.com/community-support/codefluent-entities/summer-2012-blogger-contest

CodeFluent Entities: new ASP.NET Web Site Web Forms Template sneak peek

July 25, 2012 2 comments

A brand new ASP.NET Web Site Producer (v2) is shipped in alpha in the latest build available (666 and upper).

As mentioned in our Web Platform Roadmap post, this new producer will be shipped with three templates:

Here’s a sneak peek of what gets generated when using this new template (codename: “Airport”) Smile

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

image

 

Clicking on an entity gets you to the entity page:

image

On this 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. Those actions correspond in fact to business methods provided by the entity:

image

 

Unlike the Ajax/JSON template which consumes WCF JSON services, the ASP.NET Web Forms template is built directly on top of your generated .NET Domain Model, skipping this service layer. Yet, the generated .NET Domain Model (a.k.a. .NET Business Object Model) is not specific to ASP.NET and the exact same object model can be used from any other .NET technology such as SharePoint, WinForms, Console applications, services, etc.

 

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

Cheers,

Carl Anderson

Follow

Get every new post delivered to your Inbox.

Join 694 other followers

%d bloggers like this: