RSS Feed

FluentNHibernate , NHibernate–Notes

I m currently implementing some project using the NHibernate. I dont like the mappongs stored in xml files so I am using FluentNhiberante.

 

1. Mapping Whole Assembly.

Before discovering this feature , I created one line foreach mapping defined in the assembly. You can replace this “useless” code with the procedure to map whole assembly. FluentNH  will scan the assembly and look for classes inheriting from ClassMap<>

            return Fluently.Configure().
                Database(MsSqlConfiguration.MsSql2008.ConnectionString
                (“connstring”))
                 .Mappings(x => x.FluentMappings.AddFromAssembly(System.Reflection.Assembly.GetExecutingAssembly()))
                 .ExposeConfiguration(func)
                  .BuildSessionFactory();
 
2. not null fields

If you want to create some fields in the DB as “not null”. use the Not.Nullable() sequence.

Map(x => x.IDCourse).Not.Nullable();
 
3. Reseting Schema for Testing

I don’t know if this is a good approach but when , I am working with NH i create an instance of test database with sample data. Everytime , I am running tests i m reseting schema , filling DB with sample data and then database is erased from memory (SQLite) or the server.

Session Factory Class

In my session factory Class i have methods to reset and update Schema

 public static class SessionFactory
{
    public static ISession OpenSession()
    {
        return GetSessionFactory().OpenSession();
    }
     private static ISessionFactory GetSessionFactory()
     {
        if (_sessionFactory == null)
        {
            _sessionFactory = CreateSessionFactory(UpdateSchema);
         }
         return _sessionFactory;
     }
        private static ISessionFactory _sessionFactory;

        public static void ResetSchema()
        {
            CreateSessionFactory(ResetSchema);
        }

        private static ISessionFactory CreateSessionFactory(Action<Configuration> func)
        {

          return Fluently.Configure().
               Database(MsSqlConfiguration.MsSql2008.ConnectionString
               (“connstring”))
               .Mappings(x => x.FluentMappings.AddFromAssembly(System.Reflection.Assembly.GetExecutingAssembly()))
               .ExposeConfiguration(func)
               .BuildSessionFactory();
        }
        private static void UpdateSchema(Configuration config)
        {
            new SchemaUpdate(config).Execute(true, true);
        }

        public static void ResetSchema(Configuration config)
        {
            new SchemaExport(config).Create(true, true);
        }

 

4. Generic Repository

I am the fan of the repositories used to perform all the CRUD and complex query operations. In the code I have a base repository class and complex repositories deriving from the base class.

public  class Repository<T> : IRepository<T>
        where T : class
    {
        public T GetById(int id)
        {
            T klient;

            klient = GetByFilter(“Id”,id).FirstOrDefault();

            return klient;
        }

        public IList<T> GetByFilter(string parameterName, object value)
        {
            IList<T> returnedList = null;
            using (var session = SessionFactory.OpenSession())
            {
                returnedList = session.CreateCriteria(typeof(T)).Add(Expression.Eq(parameterName, value)).List<T>();
                session.Flush();
            }
            return returnedList;
        }

        protected IList<T> GetByQuery(string query)
        {
            IList<T> returnedList = null;
            using (var session = SessionFactory.OpenSession())
            {
                returnedList = session.CreateQuery(query).List<T>();
                session.Flush();
            }
            return returnedList;
        }

      …..

    }

Simple Repository used for most CRUD operations.

For more complex queries , I just create a new class deriving from the base one.

    public class KlientRepository : Repository<Klient>
    {

        public Klient GetByImieNazwisko(string imie, string nazwisko)
        {
            return GetByQuery(String.Format(“from Klient k where k.Imie = ‘{0}’ and k.Nazwisko = ‘{1}'”,imie,nazwisko)).FirstOrDefault();
        }

        public IList<Klient> GetByRodzaj(string rodzaj)
        {
            return GetByQuery(String.Format(“from Klient k where k.Rodzaj.Rodzaj = ‘{0}’ “, rodzaj)).ToList();

        }
    }


Generics and Object Casting– Boxing , Unboxing

There are multiple scenarios in which we need to create generic classes for different objects. In this case we have two options. Either we can create generic class and specify the type/types of the object in the code  or ,  we can create a class operating on the System.Object types which are the base for every object / class in the framework.

If we have two options available then  the question is which one is better ?

To test both approaches , I created a simple logic which performs assignment and some kind of operation which returns value. This logic is encapsulated in two classes. ClassGeneric is built with generics built in .Net .You can see that type is represented by “U” letter. ClassObject is based on casting to System.Object.

 

Code:

    class ClassGeneric<U>
    {
        U test;

        public ClassGeneric(U value)
        {
            test = value;
        }

        public void Operation()
        {
            U t = test;
        }
    }

    class ClassObject
    {
        Object test;

        public ClassObject(Object value)
        {
            test = value;
        }

        public void Operation()
        {
            int t = (int)test;
        }
    }

 

Test :

Now lets perform a simple test by creating instances of both classes and performing operation. Stopwatch will be used to check performance.

 

        static Stopwatch sw = new Stopwatch();

        static void Main(string[] args)
        {
            sw.Start();
            for (int i = 0; i < 10000000; i++)
            {
                new Labs.ClassGeneric<int>(1).Operation();
            }
            sw.Stop();

            Console.WriteLine(sw.ElapsedMilliseconds);

            sw.Reset();
            sw.Start();
            for (int i = 0; i < 10000000; i++)
            {
                new Labs.ClassObject((object)1).Operation();
            }
            sw.Stop();

            Console.WriteLine(sw.ElapsedMilliseconds);

            Console.ReadLine();
        }

 

Result :

Generics 471k ticks  -  Objects  710k ticks

Generics 212 ms    Objects 343 ms

Why there is a difference ?

Generics are defined on the runtime.  .Net Framework based on the specified type in the code for example  (Queue<int>) creates a class with the type and stores reference to it. This operation is performed once on the start by the JIT-er (Just in time compiler). This operation is performed once so there is a minimal performance loss.

In case of System.Object class when casting from and to int we are performing Boxing and Unboxing operation. 

Boxing is performed every time we are casting Value Type to the reference Type. Boxing operation wraps our Value Type in a class deriving from the System.Object. This operation requires some cpu work. Same thing applies for the Unboxing operation which is performed when casting from Reference Type to the Value Type.

In this example I am casting int to Object type 1000000 times. This is the cause of the difference in time / performance. Generic classes does not require additional operations.

Boxing , Unboxing and generic interfaces

Understaing when your code perfmors boxing and unboxing is  really important. Check this example. In .Net we can implement various interfaces which are used in the Framework. Some of them are generic. We can define which type will be used.

Here I am implementing IComparable interface , which is usefull when you want to perform Sort operation on the Collection containing your custom Class.

First Class uses the Generic Interface.

    class ClassSort : IComparable<ClassSort>
    {
        public int A {get;set;}

       
        #region IComparable<int> Members

        public int CompareTo(ClassSort other)
        {
          throw new NotImplementedException();
        }

        #endregion
    }

Second class uses default Interface.

    class ClassSortOne : IComparable
    {
        public int A {get;set;}

        #region IComparable Members

        public int CompareTo(object obj)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

As you can see IComparable without generic type forces boxing when comparing objects beacuase we have to cast the objects. CompareTo() method in example with default interface uses object as a parameter while generic interface implements method with specified class as a parameter. Interface with specified generic type doesn’t need boxing and it is faster.

 

Conclusion:

Use generic classes as often as you can. Especially when making a lot of operations with them. Simple casting which causes boxing and unboxing process consumes a lot of processor time.


T4 – Text Template Transformation Toolkit CvsReader

While watching Scot Hansleman presentation about MVC I discovered great feature in Visual Studio 2010. T4 is an code generation engine. It translates template files (“*.tt”) ,  using scripts created in C# or VB ,  to C# , VB , T-SQl , Txt files etc.

You can generate a lot of different things :

– Dynamic classes which are changing based on the settings file

– CRUD procedures which are generated dynamically

– Generated Unit Tests (that would be cool)

I have made a simple template which generates Class that automates reading the CVS files. It’s a simple project created just 4fun.

CVS format file :

ID,Nazwa,Cena,Ilosc,Data,Imie
int,string,decimal,int,DateTime,string
1,Truskawki,100,1,10102010,Michal
2,Pomarancze,200,2,11022011,Stefan

First line defines column names and second line specifies their types.

Template

Templates are stored in “*.tt” files.  Every “*.tt” files starts with a “template” directive containing options. You can specify language used to analyze file . You also need to load the assemblies used by the script blocks in template. I just need System assembly for IO operations.

With Visual Studio 2010 there is a special item type “Text Template”. When you create this item VS will ask you if you want to run the template. T4 engine generates new files every time you save "changes to the “*.tt” file.

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System" #>

Simple Class

Let’s create a simple container class which stores data defined in the CVS . Column name and type is defined in the first two lines.

<#
   string columns = null;
   string types = null;
   System.IO.StreamReader re = null;
   string absolutePath = Host.ResolvePath("Data.cvs"); 

   if(System.IO.File.Exists(absolutePath))
   {
    re = System.IO.File.OpenText(absolutePath);

    columns = re.ReadLine();

    types = re.ReadLine();
   }
#>

This Script loads first two lines from a file and loads them into the columns and types string. As you can see this code is in “C#”.  Every script in the template must be within the “<# #>”.

With column names and types we can start the container class generation. Let’s call it “CvsData”.

using System;
using System.Collections.Generic; 

public class CvsData
{
<#
   string [] columntype = types.Split(‘,’);
   int counter = 0;
   foreach(string s in columns.Split(‘,’))
   {
    Write("\tpublic " + columntype[counter] + " " + s + " {get;set;}\n");
    counter++;
   }
#>
}

Code outside the “<# #>” scope is treated just like simple text. Inside script I m using the Write() function to create text. For each column script generates property.

Write("\tpublic " + columntype[counter] + " " + s + " {get;set;}\n");

Generated “*.cs” file.

using System;
using System.Collections.Generic; 

public class CvsData
{
   public int ID {get;set;}
   public string Nazwa {get;set;}
   public decimal Cena {get;set;}
   public int Ilosc {get;set;}
   public DateTime Data {get;set;}
   public string Imie {get;set;}
}

Now I can compile this file and use the CvsData class.

Simple Reader

I just want to read data and return it  as a List with CvsData objects.

public static class CvsReader
{
   public static List<CvsData> LoadData(string filePath)
   {
      List<CvsData> returnData = new List<CvsData>(); 

      if(System.IO.File.Exists(filePath))
      {
         System.IO.StreamReader re = System.IO.File.OpenText(filePath);
         string line = String.Empty;
         //Miss first two lines
         re.ReadLine();
         re.ReadLine();
         while((line = re.ReadLine()) != null)
         {
            string [] values = line.Split(‘,’);
            returnData.Add(new CvsData(){
            <#
            counter = 0;
            foreach(string s in columns.Split(‘,’))
            {
              Write("\t\t\t\t\t\t"+ s + " =");
              if(!columntype[counter].Contains("string"))
              {
                Write(columntype[counter]+".Parse");
              }
              Write("(values["+counter+"]),\n");
              counter++;
            }
            #>
          });
      }
      re.Close();
    }
  return returnData;
}
}

Generated reader:

public static class CvsReader
{
    public static List<CvsData> LoadData(string filePath)
    {
       List<CvsData> returnData = new List<CvsData>(); 

       if(System.IO.File.Exists(filePath))
       {
          System.IO.StreamReader re = System.IO.File.OpenText(filePath);
          string line = String.Empty;
          //Miss first two lines
          re.ReadLine();
          re.ReadLine();
          while((line = re.ReadLine()) != null)
          {
            string [] values = line.Split(‘,’);
            returnData.Add(new CvsData(){
               ID =int.Parse(values[0]),
               Nazwa =(values[1]),
               Cena =decimal.Parse(values[2]),
               Ilosc =int.Parse(values[3]),
               Data =DateTime.Parse(values[4]),
               Imie =(values[5]),
            });
         }
         re.Close();
        }
      return returnData;
    }
}

This is a very simple example. Created just for fun and to demonstrate basics of T4, Check the Oleg Sych site for more info and tutorials. He has created a bunch of great materials about T4.

I will definitely spend more time playing/learning the T4 engine.

Code was generated with the GeSHI


Testing email logic in .Net with Papercut

Email is a great way to communicate something to the end user asynchronously. You can review the message anytime you want.  As Developers we often need to make some kind of logic which uses emails eg. reminders , alerts etc. While testing it is common to just send an email through smtp server. Receive it , check it etc.

But ?

What to do when you or your client doesn’t have an smtp server [or your admins doesn’t have time to configure it properly] ? Well there is a simple app which creates such a “testing server”

Papercut

 

Papercut is a simplified SMTP server designed to only receive messages (not to send them on) with a GUI on top of it allowing you to see the messages it receives. It doesn’t enforce any restrictions on addresses, it just takes the message and allows you see it. It is only active while it is running, and if you want it in the background, just minimize it to the system tray. When it receives a new message, a balloon message will show up to let you know.

 

Picture

Pic 1. Papercut Options Windows

Testing

Let’s test Papercut with a simple app.

 

static void Main(string[] args) { SmtpClient client = new SmtpClient("192.168.0.128",25); MailMessage msg = new MailMessage("michal.franc@mfranc.pl", "test@test.com",  

         "Testing mail", "Testing Body"); client.Send(msg); }

Papercut works in the background. When the message is received you get a nice popup, and you can check the message.

test

Pic 2. You can check the message.

As you can see it’s a great app which can be useful in many different scenarios.


Learning Linq with the LinqPad

LinqPad is a great tool to learn Linq and test queries

 

While working on the Activity Tracker I had to make a new xml loading logic to be able to load the children’s of the nodes. Previous logic just loaded all the elements without the parent <-> child connection.

Xml logic is using the Linq to xml. In order to learn Linq better I needed to test some of its feature and by try and error create a code. Modifying and creating code all the time is really a time consuming task.

There is a nice application which you can use to play and test Linq really fast.

 

LinqPad

image Pic 1. Main window

 

Simple example :

Reading and querying xml file.

image 

You can write simple code and execute it really fast, just like you would write the code in IDE . To see results you can use the Dump class which executes query and then shows the result.

This is really great and useful tool. Get the LinqPad


Time Is Money 0.2.5 – Activity Tracker Alpha Version

It’s time to show you a simple version of one of the tools in TimeIsMoney project,  Activity Tracker. This early release enables simple tracking of tasks. Design is still very simple, I m working on it.

image Pic 1. Activity Tracker Alpha

Link : ActivityTracker

 

Requirements :

1) .Net 4.0 Framework

2) TODO list file. [At the moment it  only supports this xml format]

 

QuickStart :

1) Load Projects by plus button.

2) Select Project and click Start on Task you want to track.

3) Unload and save changes by clicking minus Button

 

Future Release:

0.2.6

– Better Design – Activity Tracker

– Moving task adding tool from Windows Forms to WPF.


Activity Tracker –WPF Auto Updated Data Binding with INotifyPropertyChanged

After styling and Data binding time has come for the logic implementation. I need a simple counter with a timer. At first I tried to use the Timer class which has an Elapsed event but there were some problems with DataBinding, so I have decided to create my own thread with a one second sleep time. Its main purpose is to increment the counter.

In order to create a better logic, I have decided to create a new class TaskWPF. It wraps the Task class which is used as a simple data container. TaskWPF includes logic used by the Wpf DataBinding mechanism. Task class is used also in other projects, so I have decided to split it.  TaskWPF implements the INotifyPropertyChanged interface. It is needed to implement automatic data binding updates.

Auto Updated Data Binding:

Each second value on TimeSpent is incremented. I want to track this time in real-time. In order to do that we have to redraw the TextBlock. By using the DataBinding, we can do this process automatically every time the bound data is changed. This option is not default. We have to set up few options.

1) First our class which contains bound properties needs to implement the INotifyPropertyChanged interface. We have to implement the method OnPropertyChanged and call it every time we are changing the property which we want to auto update. This call will notify the bound WPF control, in my example TextBlock, that the value has changed and this will force the TextBlock to redraw itself with a new value.

1 public class TaskWPF : INotifyPropertyChanged 2 { 3 .... 4 public void Increment() 5 { 6 AddSecond(1); 7 OnPropertyChanged("TimeSpentString"); 8 } 9 .... 10 #region INotifyPropertyChanged Members 11 12 public event PropertyChangedEventHandler PropertyChanged; 13 14 protected void OnPropertyChanged(string name) 15 { 16 PropertyChangedEventHandler handler = PropertyChanged; 17 if (handler != null) 18 { 19 handler(this, new PropertyChangedEventArgs(name)); 20 } 21 } 22 23 #endregion 24 .... 25 }
 As you can see every time I am calling the increment method I am m also calling the OnPropertyChanged function.  This one notifies the TextBlock that the property has changed.

2) We have to tell the TextBlock to watch out for property updates. There is a special property UpdateSourceTrigger in the Binding segment that specifies how the Binding will behave. . On default, it is set on LostFocus option which updates bound value every time the control losses focus.  In order to auto update on property changed, we have to set it on “PropertyChanged“ option.

1 <HierarchicalDataTemplate x:Key="TaskTemplate" ItemsSource="{Binding Childrens}" DataType="{x:Type data:TaskWPF}" > 2 ... 3 <TextBlock Name="TimeSpent" Text="{Binding Path=TimeSpentString Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/> 4 .... 5  </HierarchicalDataTemplate>

Same technique is used for time estimated limit notification. Right now I have made a simple border which is changing the color when the time spent is greater than estimated time.

image image

Background color of the Border is bound to the property in TaskWPF class.

1 public void IsOverEstimatedTime() 2 { 3 if (_task.TimeSpent > _task.TimeEstimate) 4 { 5 TaskColor = "Red"; 6 OnPropertyChanged("TaskColor"); 7 } 8 }


Every time I am incrementing the counter. I am also checking if the time spent is greater than time estimated. When this is its true color name is changed,  and the OnPropertyChanged method is called. It notifies the Border by the Binding to redraw itself because the value has changed. One important thing to note. Color is specified by a string name because Background property in the Xaml doesn't accept a Color" class.

Next Chapter. Communication with Xml files and TODO List.