Archive

Author Archive

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

CodeFluent Entities and the Localization Aspect: how to show localizable properties in the design surface

April 12, 2013 Leave a comment

Using CodeFluent Entities, you can use “Member Format Expressions” (a.k.a “MFEX”) to customize the way names of entities and properties are formatted. We already have blogged about that feature here:

http://blog.codefluententities.com/2012/01/12/codefluent-entities-member-format-expressions-part-1/

http://blog.codefluententities.com/2012/01/13/member-format-expressions-part-2/

In this post, we’re going to explain how to create an MFEX that will display this on the surface when selected:

As you clearly see, I have defined two localized properties on my model (on the Name property of the Campaign entity, and on the Name property of the Space entity). But wait! A red ‘Localizable’ text is appended to the right of the property name. How do I do this?

Let start with this expression, demonstrated in the previous blog post:

<font condition=IsKey color=’red’>{#Name}<else/><font color=’blue’>{#Name}</font></font>

With this expression, key properties will be shown in red and other properties will be shown in blue. The condition syntax is in fact a .NET expression. IsKey is a property (of Boolean type) of the CodeFluent.Model.Property class. If I was writing C# code, I could do this ‘if (myProperty.IsKey)’ etc… But MFEX conditions also support “dot navigation”, so you could write this:

<font condition=Rules.Count color=’red’>{#Name}<else/><font color=’blue’>{#Name}</font></font>

In this case, we are navigating on the Rules property of the CodeFluent.Model.Property class, and on the Count property of the CodeFluent.Model.RuleCollection class. Count is of type Int32 and the condition evaluator needs a Boolean, so it just tests the resulting Int32 against 0, so the condition is equivalent to “Rules.Count > 0″. So this expression will show in red all the properties that have CodeFluent Entities rules defined on it.

Well, it turns out MFEX also supports (partially) methods in conditions. So, here is how to display localized properties:

{Name} <font color="red" condition="'true'=Element.GetAttribute('localizable','http://www.softfluent.com/codefluent/patterns/localization/2008/1')">Localizable</font>

Note : it’s important to respect the difference between the single quote and the double quote characters here.

So, the condition is an expression with an operation. = is the ‘equality insensitive’ operator. It means it uses equality but is case insensitive in the case of string comparison. Here is the list of available operators:

  • == or = : Equal
  • != or <> : NotEqual
  • [=CS] : EqualCaseSensitive
  • [!=CS] : NotEqualCaseSensitive
  • >= : GreaterThanEqual
  • <= : LesserThanEqual
  • > : GreaterThan
  • < : LesserThan
  • [StartsWith] : StartsWith
  • [StartsWithCS] StartsWithCaseSensitive
  • [EndsWith] : EndsWith
  • [EndsWithCS] : EndsWithCaseSensitive
  • [Contains] : Contains
  • [ContainsCS] : ContainsCaseSensitive

The condition will compare the literal string ‘true’ with the result of a method call that starts on the Element property of the CodeFluent.Model.Property class, which is of System.Xml.XmlElement type. XmlElement has a method called GetAttribute that simply gets an XML attribute given it’s local name (without a prefix if it’s in a specific XML namespace) and the XML namespace.

So, with this condition, we are accessing the XML element underlying the CodeFluent Entities Property concept. When a property is marked as localized, the corresponding XML text (in memory) is just modified like this:

  <Campaign namespace="SoftFluent.Advertising1" >
    <Id />
    <Name _loc:localizable="true" />
  </Campaign>

Happy MFEXing!

The CodeFluent R&D Team.

Categories: Uncategorized

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

Retrieve SQL Output parameters in your BOM with CodeFluent Entities

March 27, 2013 Leave a comment

 
 
Let’s say you have an existing stored procedure that uses OUTPUT parameters to retrieve some data and you want to access it in your Business Object Model (BOM) as an object method.
 
If you can modify your procedure you might want to use a more OOP (Object Oriented Programming) approach. It will be more flexible and it is what CodeFluent Entities follows.
 
But let’s suppose you don’t have the possibility to modify your stored procedure.
 
We will use an existing model to illustrate this post. We will work with the ContactManager demo project available within the CodeFluent Entities project templates in Visual Studio.
 
This is how our existing stored procedure looks like, it has 2 OUTPUT parameters.
 

CREATE PROCEDURE [dbo].[legacy_procedure]
(
@param1 [int] OUTPUT,
@param2 [nvarchar] (256) OUTPUT
)
AS
BEGIN
--some interesting code here
select @param1 = 42
select @param2 = 'answer'
END
GO

 

We create a method called “LegacyProcedure” related to the entity Contact

Add a method to an entity

Add a method to an entity

 

Name the method

Name the method


 
We need to create a “raw” method and specify the parameters for our method.
 
As we want to use an existing stored procedure we leave the body empty.

Defining our method

Defining our method


 
As we will work with an existing stored procedure we need to tell our method to use our existing stored procedure, and not to create his own persistence stored procedure.

 
In the method advanced properties at the “persistence” level we set “Persistence Name” (it must be the same name as the stored procedure).

Set the persistence method name

Set the persistence method name


 
Now we tell the persistence producer not to produce the stored procedure.
To do that we go to the “Aspect and Producer Properties” of our method and set the “Produce” value to False.

Persistence Produce Property

Persistence Produce Property


 
Finally we need to define the parameters that are used in our method.

The method parameters

The method parameters


 
The parameter names must be the same as those declared in our method (as well as the type).

Parameter names

Parameter names


 
Now we need to set the persistence parameter direction. Displaying the advanced properties, in the persistence group we set the direction to “Output”.

Parameter persistence direction

Parameter persistence direction


 
Supposing that you have a “Persistence producer” and a “Business Object Model producer” (BOM) we build the CodeFluent Entities project.
 
If you have a CodeFluent Entities version former to the Build 1.0.61214.707, then you will have a compile error while building the generated BOM project.

Output parameters are not handled

Output parameters are not handled


 
The solution would be to disable the generation of our method and code it by hand in a partial class.
 
But, since Build 1.0.61214.707 CodeFluent Entities now supports the “out” and “ref” parameters in persistence methods.
 
After installing the new version, we build the CodeFluent Entities project. If we take a look at our generated method we will see that the “out” parameters are now handled by our BOM.

Out parameters are handled

Out parameters are handled


 
 
Regards,
Pablo Fernandez Duran

Generate ASP .NET Web API Controllers using Templates

March 20, 2013 Leave a comment

 

In a precedent post we have shown how to build an ASP .NET WebAPI Controller to access the generated Business Object Model (BOM).
 
We saw how to implement manually a Web API Controller for one entity of our model.
 
Now, we are going to see how to build a Template in order to automatically generate a Web API Controller for each one of the entities in our model.
 
We are going to use the “CarRental” demo project included with CodeFluent Entities. It was the same sample project that we used when we created the Web API Controller.
 
The first thing we have to do is create our template file.

 

Templates location

Templates location

 

Our template must be prefixed by “[Template]” and have an extension of type “.tpl”.

 
Before writing our template let’s create a producer for our template.
 

Template Producer

Template Producer


 
The “Source Directory” is the location of our template folder and the “Target Directory” is where our files will be generated, in my case I have a folder called “ApiControllers” in my MVC 4 Web Application project.
 
At the bottom of our template we fix some parameters.

[%@ template
enumerable="Producer.Project.Entities"
enumerableItemName="entity"
enumerableTargetPathFunc='Path.Combine(Path.GetDirectoryName(TargetPath), entity.Name) + "Controller.cs"' %]

 
That means that we are going to iterate through all the entities in our project (Producer.Project.Entities). Inside the template we can access the current enumerated entity by the name “entity”. And the name of the generated file (for each entity) will be “[EntityName]Controller.cs”.
 
Now we can write the content of our Api Controller. Let’s start by creating only the Controller class.

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by the Template Producer.
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace [%=entity.Namespace%].Web.ApiControllers
{
	using System.Collections.Generic;
	using System;
	using System.Net;
	using System.Net.Http;
	using System.Web.Http;

    public class [%=entity.Name%]Controller : ApiController
    {
    }
}

 
If we build our CodeFluent Entities project we must see our Api Controllers appear.
 

Generated API Controllers

Generated API Controllers


 
Now let’s implement the Api Controller methods. We will use almost the same implementation as we did in the post “Using ASP .NET Web API with CodeFluent Entities”.

// GET api/[%=entity.Name%]
public IEnumerable<[%=entity.Name%]> Get()
{
    return [%=entity.SetFullTypeName%].LoadAll();
}

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

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

 

For the Delete and Get (for a single element) methods we need to do some work to manage the entity keys. Indeed, it is possible that some entities have multiple keys.

// DELETE api/[%=entity.Name%]/*ids
public HttpResponseMessage Delete(string ids)
{
	ids = ids.Replace('/', '|');
    [%=entity.ClrFullTypeName%] value = [%=entity.ClrFullTypeName%].LoadByEntityKey(ids);
	if(value != null && value.Delete())
	{
		return Request.CreateResponse(HttpStatusCode.NoContent);
	}
	return Request.CreateResponse(HttpStatusCode.NotFound);
}

	// GET api/[%=entity.Name%]/*ids
public [%=entity.Name%] Get(string ids)
{
	ids = ids.Replace('/', '|');
    [%=entity.ClrFullTypeName%] value = [%=entity.ClrFullTypeName%].LoadByEntityKey(ids);
	if(value == null)
	{
		throw new HttpResponseException(HttpStatusCode.NotFound);
	}
	return value;
}

 
We use a feature in MVC (and Web API) routes that allows us to handle a variable number of segments in a URL pattern.
 
So we will need to make some changes in our routing configuration. I have registered my routes for the Web API in a separate file called “WebApiConfig” (cf. Using ASP .NET Web API with CodeFluent Entities). The trick lies in the “*” before the parameter name (*ids).

config.Routes.MapHttpRoute(
                           name: "DefaultApi",
                           routeTemplate: "api/{controller}/{*ids}",
                           defaults: new { ids = RouteParameter.Optional }
                          );

 

For example, in order to retrieve a specific instance of the entity “InventoryDetail” we need three keys, so the URL to get an instance of “InventoryDetail” will be: http://server/api/InventroyDetail/1/2/3.

 
If we build our CodeFluent Entities project and take a look at the inside of a Controller we will see the complete implementation.
 
Now we only have to test our Controllers. We can use the same tests that we have done in the precedent post related to the ASP .NET Web API.

 
Regards.
 
Pablo Fernandez Duran

Manipulating NTFS alternate data streams in C# with the CodeFluent Runtime Client

March 14, 2013 1 comment

Have you already heard about NTFS alternate streams? Also known as named streams or ADS (Alternate Data Streams).
Well it is a useful feature in NTFS storage systems. It expands the concept of file and data streams.

Alternate Data Streams

Alternate Data Streams

When working with NTFS files, the main data stream (or unnamed stream) is the central element of the file. When you create a file, a main stream is created. When you create an alternate stream and the main stream does not exist it is created, if you delete the main stream the whole file is deleted (so the existing alternate streams).
When you read a file or you write in to a file you are working with the main stream by default.

Alternate streams follows the syntax: “filename.ext:alternateName”

You can store any kind of data in an ADS (as you can do it with the unnamed stream), so you can store binary data, text data, an image, a video and even an executable file.

Let’s make quick test.

Open a command line console (cmd.exe).
Create a text file and write some content in it:

Writing in to the main data stream

Writing in to the main data stream

Let’s read the content:

Reading the main stream

Reading the main stream

Nothing extraordinary, we get the main data stream from our file.
Now let’s try to write in to an alternate data stream (this will create the alternate stream if it does not exist).

Writing in to an Alternate Data Stream

Writing in to an Alternate Data Stream

You have created an alternate data stream called “hide” right on our file “test.txt”, this will not have any incidence with your main data stream.
To ensure that our alternate data stream “hide” has been correctly created we will try to read it.

Reading an Alternate Data Stream content

Reading an Alternate Data Stream content

And to prove that our main data stream is still there, let’s read the main stream.

Reading the main stream

Reading the main stream

We have made some tests only with “text” streams but a stream can be also an image, an executable file and all other kind of stream a file container can host.
What about manipulating Alternate Data Streams with C#?
Well, this feature is unfortunately not available in .NET, we would need to call native methods if we want to manipulate alternate data streams.
So we can build some nice native method wrappers in order to manipulate alternate data streams or we can use the CodeFluent Entities Runtime Client.
CodeFluent Runtime Client is a free library that provides very useful and powerful helpers like:

  • XML utilities
  • IO utilities
  • Type conversion helpers
  • JSON utilities
  • … and many other

You can easily install the CodeFluent Runtime Client from Nugget.

PM> Install-package CodeFluentRuntimeClient

Using the CodeFluent Entities Client Runtime to manipulate alternate data streams is as easy as manipulate all well-known file streams.
We will use the NtfsAlternateStream class which is located in the CodeFluent.Runtime.BinaryServices namespace, it provides some static helper methods to manipulate alternate streams as they were “regular” streams (open, create, read, write, enumerate, delete…).
Let’s take a look to some useful methods to manipulate alternate data streams (ADS):

//Create a stream supporting ADS syntax
FileStream stream = NtfsAlternateStream.Open("test.txt:hide", FileAccess.Write, FileMode.OpenOrCreate, FileShare.None);
stream.Close();

//Writing in to an ADS
NtfsAlternateStream.WriteAllText("test.txt:hide", "Secret content");

//Reading data from an ADS
string text = NtfsAlternateStream.ReadAllText("test.txt:hide");

//Enumerating all the ADS in test.txt
IEnumerable adsStreams = NtfsAlternateStream.EnumerateStreams("test.txt");
foreach (NtfsAlternateStream ads in adsStreams)
{
    Console.WriteLine(ads.Name);
}

//This will not delete the test.txt file
NtfsAlternateStream.Delete("test.txt:hide");

A concrete example of how ADS are used in Windows is when you download a file from the Internet. When I open a file downloaded from the Internet with Word (2013) I receive a warning telling me that the file might not be secure.

Word Protected View

Word Protected View

How does Word know that I downloaded the file from the Internet? Well, every time you download a file, Windows set an ADS called “:Zone.Identifier” containing some data related to the origin of the file. Let’s confirm that.

string altFileName = @"C:\Users\pablo\Downloads\someDoc.docx:Zone.Identifier";
string content = NtfsAlternateStream.ReadAllText(altFileName);
Console.WriteLine(content);

What we get is:

ZoneTransfer ZoneId

ZoneTransfer ZoneId

This value “ZoneId=3” means that the file has “Internet” as origin.

If we delete the “:Zone.Identifier” ADS from the file:

string altFileName = @"C:\Users\pablo\Downloads\someDoc.docx:Zone.Identifier";
//this will not delete the file
NtfsAlternateStream.Delete(altFileName);

Now we don’t receive a warning when trying to open the file, Word has no information from the file origin.
Alternate data streams are nice but they have some limitations. As we have said, ADS are only supported in NTFS file storage systems so what happen if you copy a file containing ADSs to another file system (FAT file system, USB drive, CD/DVD, network transfer…)? Well, you will lose all your ADS!

Avoid writing important or critical data to alternate data streams. ADS are not supported in not NTFS file systems.

Some ideas where ADS might be useful:

  • If you are writing a program to edit images it will be nice to keep the original image (or even all the modification history) so the user can undo some changes. Instead of keeping separate files you can write all the image versions in the same file using ADS, e.g. image.jpg:original, image.jpg:v1
  • You can store thumbnails for graphical files.
  • Imagine you wrote a “reader” application, you can keep some information like: font size, current page, background color… in the file itself.

I am sure you can image other practical and fun uses for Alternate Data Streams, it would be great if you share it with us Winking smile.

Regards.
Pablo Fernandez Duran

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

How to work with existing database tables with CodeFluent Entities

February 15, 2013 Leave a comment

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

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

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

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

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

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

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

New CodeFluent Project

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

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

Raw Method

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

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

Settings

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

Settings

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

Settings

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

Table List

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

Vincent Patry

Follow

Get every new post delivered to your Inbox.

Join 700 other followers

%d bloggers like this: