Archive

Archive for August, 2012

Exploring the CodeFluent Runtime: ZipFile

August 24, 2012 1 comment

Since the day it was born, the CodeFluent Entities Runtime embarks a cool ZipFile class that allows you to create .ZIP files from other files, directories and streams, and extract from .ZIP files files, directories of files and streams!

The class is found in the CodeFluent.Runtime.Compression namespace and is very easy to use:

using CodeFluent.Runtime.Compression;

namespace ZipTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // compress
            using (ZipFile file = new ZipFile("newzip.zip", ZipFile.Mode.Overwrite))
            {
                file.AddFile(myFile1);
                file.AddFile(myFile2);
                file.AddDirectory(myDirectory); // recursive, keep relative paths in
            }

            // decompress
            using (ZipFile file = new ZipFile("newzip.zip", ZipFile.Mode.Read))
            {
                file.GetFiles(myOutputDirectory); // recursive, keep relative paths out
            }
        }
    }
}

For CPU performance and memory usage reasons, and contrary to other popular .NET zip implementations (http://www.icsharpcode.net/opensource/sharpziplib/, or http://dotnetzip.codeplex.com/), CodeFluent Entities’ ZipFile implementation is unmanaged.

It means you will have to copy a native Windows DLL (that is shipped with the product) named “CodeFluent.Runtime.Compression.dll” in the bin directory of your application for this to work. Since it’s unmanaged, there are two versions of this dll, one for X86 processes, and another for X64 processes.

It’s fun to see Microsoft has finally taken the same unmanaged route for ZIP handling, this year, in 2012, as we did 7 years ago, when we shipped our first version of CodeFluent Entities :-)

The CodeFluent Runtime is available in two flavors:

Happy zip-ing!

The R&D team.

Introducing CodeFluent Entities PostgreSQL Producer

August 20, 2012 Leave a comment

CodeFluent Entities 2012 – Build 060809 introduced a new Persistence layer producer: the PostgreSQL Producer!

The producer supports PostgreSQL 8.4 and above (8.3 is soon to be discontinued) and relies on the ADO.NET data provider Npgsql 2.0.11. The producer will try to load dynamically the Npgsql assembly. (You might need to copy the Npgsql.dll and Mono.Security.dll in your CodeFluent Entities installation directory if you don’t want to register Npgsql in the GAC).

Please also note the PostgreSQL Producer also requires the liboss-uuid library to be installed on your server. On Windows, this library is shipped with the standard Windows packages of PostgreSQL 8.4+, and on Unix/Linux, you may need to install the postgresql-contrib package and its dependencies like libossp-uuid16, for the producer to be able to deploy the generated script on your server.

Getting started

The producer is available in the Persistence Layer Producers section of the Add New Producer window:

as well as directly from the Starter Wizard:

This is how you can set the connection string (in the Wizard pages):

A first model

I created a new project with the Start Wizard and design this very simple two-entity model:

Basically all the employees have a first name, a last name, a birth date, and a job. Each job has salary – of type currency, a name and employees. I added two instances to the model: an employee named John Doe, born on June 12th, 1974 with a job named CEO and which salary is 30,000.

I just set the Target Version of the PostgreSQL Producer to version 9.0 which the version I am currently running on my computer, and built the project.In the output window I can see the result of the generation process; the PostgreSQL producer generated 11 files and succeeded:

All the automatically generated .SQL script files are available in the Persistence project of the solution:

If I connect to my database with an administration tool I can see that a new database has been created with the named I specified in the Connection String, and populated with my model and instances:

And I haven’t written a line of code yet!

Consuming the generated persistence layer

Consuming the PostgreSQL generated database is as easy as configuring the right connection string in the client project. In my case I created a Console Application Project named MyCompany.Management.Client.

To prepare it, I had to reference my BOM Project – in my case MyCompany.Management – that was automatically created by the Starter Wizard, Npgsql.dll and CodeFluent Entities runtime, i.e. CodeFluent.Runtime.dll and CodeFluent.Runtime.PostgreSQL.dll. Note that you might need to set the Copy Local property to True for the Npgsql.dll reference if the dll is not registered in the GAC.

I also had to change the target framework of the project from .NET Framework 4.0 Client Profile to the full .NET Framework 4.0.

As I am using the PostgreSQL Producer I have to set the correct Connection String in App.config file:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="MyCompany.Management" type="CodeFluent.Runtime.CodeFluentConfigurationSectionHandler, CodeFluent.Runtime" />
  </configSections>
  <MyCompany.Management persistenceTypeName="PostgreSQL" connectionString="Server=localhost;Database=MyCompany_Management;User Id=postgres;Pwd=password" />
</configuration>

Note it is important to specify the persistenceTypeName=“PostgreSQL” attribute.

Here is now the code of my console application :

using System;
namespace MyCompany.Management.Client
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create a new employee
      Employee newbie = new Employee();
      newbie.FirstName = "Jane";
      newbie.LastName = "Doe";
      newbie.BirthDate = new DateTime(1990, 01, 15);

      // Persist Jane Doe
      newbie.Save();

      // Load all the employees
      EmployeeCollection employees = EmployeeCollection.LoadAll();
      foreach (Employee employee in employees)
      {
        Console.Write("- {0} {1}, born on {2:MM-dd-yyyy}",
          employee.FirstName,
          employee.LastName,
          employee.BirthDate);

        if (employee.Job != null)
        {
          Console.Write(", is {0} with a salary of {1:C}",
            employee.Job.Name,
            employee.Job.Salary);
        }

        Console.WriteLine();
      }
    }
  }
}

It creates a new employee, saves it, and then loads a list of all the employees. As we can see, there is no specific code about PostgreSQL. Its use is completely transparent at this level.

And here is the result:

And the populated table:

Happy PostgreSQL-ing!

Baudouin Giard

Introducing CodeFluent Entities MySQL Producer

August 16, 2012 Leave a comment

CodeFluent Entities 2012 – Build 060703 introduced a new Persistence layer producer: the MySQL Producer! The producer supports MySQL 5.1 and above and relies on the MySQL Connector for .NET version 6.5.4.0. The producer will try to load dynamically the MySql.Data assembly. You might need to copy the MySql.Data.dll in your CodeFluent Entities installation directory if you don’t want to register the MySQL Connector in the GAC.

Getting started

The producer is available in the Persistence Layer Producers section of the Add New Producer window:

as well as directly from the Starter Wizard:

This is how you can set the connection string (in the Wizard pages):

A first model

I created a new project with the Start Wizard and designed this very simple model composed of two entities:

Basically all the employees have a first name, a last name, a birth date, and a job. Each job has salary – of type currency, a name and employees.

I added two instances to the model: an employee named John Doe, born on June 12th, 1974 with a job named CEO and which salary is 30,000.

I also set the Target Version property of the MySQL Producer to version 5.5, which is the version I am currently using on my computer, and built the project, like any other CodeFluent Entites project. In the output window I can see the result of the generation process. The MySQL producer has generated 9 files and succeeded:

All the automatically generated .SQL script files are available in the Persistence project of the solution:

If I connect to my MySQL database with an administration tool I can see that a new database has been created with the named I specified in the Connection String, and populated with the tables automatically inferred from my model as well as instances:

 

 

 

And I haven’t written a line of code yet!

Consuming the generated persistence layer

Consuming the MySQL generated database is as easy as configuring the right connection string in the client project. I my case, I created a Console Application Project named MyCompany.Management.Client.

To prepare it, I had to reference my BOM Project – in my case MyCompany.Management – that was automatically created by the Starter Wizard, MySql.Data.dll (the MySQL ADO.NET provider) and the CodeFluent Entities runtime, i.e. CodeFluent.Runtime.dll and CodeFluent.Runtime.MySQL.dll. Note that you might need to set the Copy Local property to True for the MySql.Data.dll reference if the dll is not registered in the GAC.

I also had to change the target framework of the project from .NET Framework 4.0 Client Profile to the full .NET Framework 4.0.

As I am using the MySQL Producer I have to set the correct Connection String in App.config file:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="MyCompany.Management" type="CodeFluent.Runtime.CodeFluentConfigurationSectionHandler, CodeFluent.Runtime" />
  </configSections>
  <MyCompany.Management persistenceTypeName="MySQL" connectionString="Server=localhost;Database=MyCompany_Management;User Id=root;" />
</configuration>

Note that it is important to specify the persistenceTypeName=“MySQL” attribute, otherwise we would be using the default persistence layer which is SQL Server. Here is the code of my console application :

using System;
namespace MyCompany.Management.Client
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create a new employee
      Employee newbie = new Employee();
      newbie.FirstName = "Jane";
      newbie.LastName = "Doe";
      newbie.BirthDate = new DateTime(1990, 01, 15);

      // Persist Jane Doe
      newbie.Save();

      // Load all the employees
      EmployeeCollection employees = EmployeeCollection.LoadAll();
      foreach (Employee employee in employees)
      {
        Console.Write("- {0} {1}, born on {2:MM-dd-yyyy}",
          employee.FirstName,
          employee.LastName,
          employee.BirthDate);

        if (employee.Job != null)
        {
          Console.Write(", is {0} with a salary of {1:C}",
            employee.Job.Name,
            employee.Job.Salary);
        }

        Console.WriteLine();
      }
    }
  }
}

It creates a new employee, saves it, and then loads a list of all the employees. As we can see, there is no specific code about MySQL. Its use is completely transparent at this level.

And here is the result:

And the populated table:

 

Happy MySQL-ing!

Baudouin Giard

Quickly Generate SQL Azure Databases with CodeFluent Entities

August 14, 2012 1 comment

CodeFluent Entities ships out-of-the-box with an SQL Azure producer which allows you to generate databases to SQL Azure directly from Visual Studio, based on a CodeFluent Entities model. We’ll see in this post how we can actually do it.

First of all, we have to setup our Azure environment, so we’ll start by login on www.windowsazure.com with the LiveID associated with an Azure subscription. Once we’re logged on, we’ll go directly to the Database section of the portal and we’ll begin by creating a new database server as shown here:

Then you’ll have to choose a region to define where your server will be located. In my case it will be “North Europe”. Once you have chosen a region, you’ll have to provide credentials for the server as shown below:

The next step is very important here, as you’ll have to configure the firewall of your server to allow some IP ranges. The thing is, if you don’t allow your own IP address, you won’t be able to manage the database or generate it with the CodeFluent Entities SQL Azure producer, from the Visual Studio environment:

Once you’ve setup your firewall rule(s), click on finish to validate the creation of you server.

The server is now created, so click on it and you should see that a database has been created by default, the master database. But we’re not able to produce anything on this one, so we’ll have to create a new one. To do that, click on “Create” on the top on the database part of the ribbon, then give a name to your database and select its edition and size. In my case, I chose a 1GB Web edition which I named “MyDatabase”.

Azure Database configuration is now done so let’s open Visual Studio to see how to generate the persistence layer of our application directly on the database we’ve just created. For the purpose of this article I’ll use a sample project provided out-of-the-box with CodeFluent Entities, namely the “Advertising Sales Management Sample Model”. If you open this model, you’ll see it contains 7 entities, 4 enumerations, and different relations (e.g. one-to-one, one-to-many, many-to-many):

Once this project is created, I’ll add a new “SQL Server Database”-type project to my solution, which will be the target project for the CodeFluent Entities SQL Azure producer. I’ll name this project “SoftFluentArticle.Database” as shown here:

Once that’s done, let’s add a new producer to the CodeFluent Entities project, the ‘SQL Azure producer’. It can be found in the “Persistence Layer Producers” category as shown here:

As you can see, if you never used it, it’s pretty similar to the regular CodeFluent Entities SQL Server producer, but you will notice there are are a “Local SQL Server” and an “Online SQL Azure” sections. Moreover, in the “Targets” section, the property “Produce Online SQL Azure” is set to false and the property “Produce Local SQL Server” is set to true.

The reasons are multiple. The most important is simply… the cost for you :-) Because each time your application requests data from your SQL Azure, there is a cost applied to the transaction and you certainly don’t want to pay fees for these transactions while you’re developing/testing your application. That’s why you will use the Local SQL Server most of the time, and switch to the Online SQL Azure when you’re ready. It’s important to note the generated code will always target SQL Azure, even if the local SQL Server is in use, thus avoiding pure SQL Server statements unsupported on SQL Azure.

We now have to specify our SQL Azure connection string, just like a regular SQL Server connection string. To do that just click on the “Connection String” property line, a button will be shown at the extreme right of the line, click on it and you should get the same popup as the one shown below. Fill it with your Database Name, Server Name, Password, and User name. You can now click on test connection to check it works.

Back to our producer configuration, choose the database project we’ve created earlier as the “Default Target Directory” (you can use a sub folder if you want, or the root as it’s shown here):

Click on “Ok” to confirm all that.

Everything is now setup, so let’s build our project and see what happens! As for the SQL Server producer, the SQL Azure produced our scripts in the database project folder we’ve set as the target (see all the .SQL files automatically generated):

Now, let’s open the well-known SQL Server Management Studio tool and connect to our local SQL Server. You should see there the database which has been generated by the SQL Azure producer “diff engine”. Open now you web browser, go to your SQL Azure database address, in my case https://ttmshoc6av.database.windows.net/?langid=en#$database=MyDatabase, and fill-in the form with the server credentials you’ve setup earlier.

When you are logged on, click on the Design button on the bottom left of the screen. You should land on the following screen and, as you can see, there are no tables or stored procedures here, yet:

Why hasn’t my database been generated on SQL Azure? The answer is simple: the property “Produce Online SQL Azure” is still set to false. So let’s go back to Visual Studio. Double-click on the “SQL Azure Producer”, change that property to true, press OK, and build your solution again. Once your solution is built, go back to the SQL Azure portal, click on the Refresh button. All your tables and stored procedures should now appear like this:

Since you’re using CodeFluent Entities, as usual, continuous build is a feature. So, you can change the model and build anytime, this will update all the layers of your application, including your SQL Azure database.

Pretty cool isn’t it?

Aymeric ROLAND.

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

Exploring the CodeFluent Runtime: Reusing a Script Engine (like JScript or VBScript) with .NET

August 6, 2012 Leave a comment

Following our “Exploring the CodeFluent Runtime“ post series, I thought I’d share with you another cool class available in the CodeFluent Runtime which is the ScriptEngine class.

The ScriptEngine class is a which wraps Windows Scripting Engines so you can easily and quickly reuse them with .NET code. The most useful engine is of course JScript which is Microsoft’s JavaScript implementation. JScript is installed on every Windows and is the exact same engine that is used by Internet Explorer. VBScript is also shipped out-of-the-box with every Windows installation and our ScriptEngine class indeed supports it. It should (this has not tested though) also support other scripting engines like ActivePython, ActivePerl, etc.

Here are some simple JavaScript examples that demonstrate how to leverage these engines:

Console.WriteLine(ScriptEngine.Eval("jscript", "1+2+3"));
// will output 6 (of Int32 type)

Console.WriteLine(ScriptEngine.Eval("jscript", "1.2"));
// will output 1.2 (of Double type)

Console.WriteLine(ScriptEngine.Eval("jscript", "1+2+3+'hello'"));
// will output 6hello (of String type)

You can also use external objects with these engines. Here I declare a Customer class (Note the ComVisible attribute set to true, this is mandatory as Script Engines are COM objects):

[ComVisible(true)]
public class Customer
{
    public string Name { get; set; }
}

And I reuse it directly in JavaScript using my ScriptEngine class:

            Customer customer = new Customer();
            customer.Name = "Joe";
            Console.WriteLine(ScriptEngine.Eval("jscript", "MyObj.Name", new KeyValuePair<string, object>("MyObj", customer)));
            // will output Joe (of String type)

You can also pre-parse a script text and run it when you want. This is better in terms of performance since the script will only be parsed once. Here is how you can do it, with a JavaScript method declared in the script source:

            ScriptEngine engine = new ScriptEngine("jscript");
            ParsedScript preParsed = engine.Parse("function MyMethod(arg1, arg2){return arg1*2 + arg2.Name}");
            Console.WriteLine(preParsed.CallMethod("MyMethod", 1, customer));
            // will output 2Joe (of String type)

If you want to externalize business rules (for example tax computation in a LOB app), or if you want to ensure your application supports higher level programming capabilities (like if you’re writing a game that needs some parts to be scriptable), this is a cool way to do it. Just provide an object model (like the Customer class in my example) as a programming facade to your users and they will be capable of programming your app. No need to understand complex Lex/Yacc/BNF syntax, to redefine the JavaScript syntax. Just reference the CodeFluent Runtime and here you go.

The CodeFluent Runtime is available in two flavors:

Cheers,

The R&D Team.

CodeFluent Entities: Import SQLite databases

August 2, 2012 Leave a comment

Starting with CodeFluent Entities 669 available here, you can import SQLite databases into CodeFluent Entities models Smile

Several ways to import your existing database:

  • Option #1: From the Solution Explorer, right-click on your project and click “Import An Existing Database or Model…”,
  • Option #2: From the Server Explorer, drag and drop tables from your database onto your surface (this won’t work for SQLite unless you have added the SQLite Visual Studio tools I guess…),
  • Option #3: From the Visual Studio toolbar (builds 661 and upper), open the “CodeFluent Entities” menu and click on “Import An Existing Database or Model…

Whichever option you choose, the same wizard will open and it now contains a new importer: SQLite.

CodeFluent Entities SQLite Importer

Prerequisites

  • CodeFluent Entities (build 669 or upper),
  • The SQLite NET Data Provider accessible by CodeFluent Entities so it can connect and import the database to your model. To do so place the System.Data.SQLite.dll in CodeFluent Entities’ installation directory (%ProgramFiles(x86)%\SoftFluent\CodeFluent\Modeler). This provider is downloadable from here: http://system.data.sqlite.org. We suggest you take the “Precompiled Statically-Linked Binaries for 32-bit Windows”, bundle version.

Cheers,

The R&D team

Follow

Get every new post delivered to your Inbox.

Join 52 other followers