Friday, 27 November 2009

Unity Application Block, using Configuration Files.

Introduction

In my last blog Unity Application Block, I introduced some of the concepts for using the Unity Application Block this blog introduces the added flexibility of using config files. This example will work either Web.Config or App.Config files, however it is possible to use other types of files.

Recap

We have a solution with 4 projects;

  • InterfaceLibrary, this contains all of my interfaces.
  • BusinessObjects, this contains my class file of the Customer Objects which implements the interface
  • ServiceLayer, this populates and returns a BusinessObject
  • FormApplication, this displays the information from the ServiceLayer.

We are using Unity to perform 3 tasks, Object Instantiation, Service Location and Dependency Injection.

Unity is instantiating the Service with the following code;

Code Snippet
  1. var myService = myContainer.GetContainer().Resolve<IsvcCustomer>();

It is determining the location of the service with this;

Code Snippet
  1. container = new UnityContainer()
  2. .RegisterType<ILogger, Logger>()
  3. .RegisterType<IsvcCustomer, svcCustomer2>();

Unity is automatically dealing with the Dependency Injection, that is when svcCustomer2 is instantiated it realises ILogger is required and creates an instance of Logger and passes this into the object.

Config Files

The obvious problem with the service location in the above example is that if the service changes (using the previous example) from svcCustomer to svcCustomer2 we need to do a recompile, which is sub-optimal Smile. The solution is to store this information in a config file.

The first step is to register the configuration in the configSections tag of the xml file.

Code Snippet
  1. <configSections>
  2. < section name="unity"
  3. type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
  4. Microsoft.Practices.Unity.Configuration, Version=1.2.0.0,
  5. Culture=neutral, PublicKeyToken=31bf3856ad364e35 " />
  6. </ configSections>

The configuration is made up of 2 sections the TypeAliases and the Containers.

In TypeAliases we list (amongst the Unity ones) our Types and what we want to call it (Alias) and which Assembly it can be found. Remember that XML is case sensitive.

Code Snippet
  1. <typeAlias alias="SvcCustomer2" type="Service.svcCustomer2, Service" />

The Container section defines the name of the Container and shows the mapping between interfaces and their concrete types

Code Snippet
  1. <type type="ILogger" mapTo="Logger" />

A complete app.config can be found at the end of this post.

Code Change

To enable your application to read the Config file you need to reference the following namespace Microsoft.Practices.Unity.Configuration which can be found in the Microsoft.Practices.Unity.Configuration.dll assembly.

then change the code

Code Snippet
  1. container = new UnityContainer()
  2. .RegisterType<ILogger, Logger>()
  3. .RegisterType<IsvcCustomer, svcCustomer2>();

to

Code Snippet
  1. container = new UnityContainer();
  2. var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
  3. section.Containers["container"].Configure(container);

Which gets the <unity> config section and populates the UnityContainer “container” with “container” section from the <containers> section.

Conclusion

You can now configure your services on the fly, which I think is a more elegant solution than doing it in code.

I do not think this will be my last post on Unity as I would like to look at an example with WCF and take a look at other ways of performing the Dependency Injection.

App.Config for this project

Code Snippet
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. < configuration>
  3. < configSections>
  4. < section name="unity"
  5. type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
  6. Microsoft.Practices.Unity.Configuration, Version=1.2.0.0,
  7. Culture=neutral, PublicKeyToken=31bf3856ad364e35 " />
  8. </ configSections>
  9. < unity>
  10. < typeAliases>

  11. <!-- Lifetime manager types -->
  12. < typeAlias alias="singleton"
  13. type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,
  14. Microsoft.Practices.Unity " />
  15. < typeAlias alias="external"
  16. type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,
  17. Microsoft.Practices.Unity " />

  18. <!-- User-defined type aliases -->
  19. < typeAlias alias="ILogger" type="InterfaceLibrary.ILogger, InterfaceLibrary" />
  20. < typeAlias alias="ISvcCustomer" type="InterfaceLibrary.IsvcCustomer, InterfaceLibrary" />
  21. < typeAlias alias="Logger" type="Service.Logger, Service" />
  22. < typeAlias alias="SvcCustomer" type="Service.svcCustomer, Service" />
  23. </ typeAliases>
  24. < containers>
  25. < container name="container">
  26. < types>
  27. < type type="ILogger" mapTo="Logger" />
  28. < type type="ISvcCustomer" mapTo="SvcCustomer" />
  29. </ types>

  30. </ container>
  31. </ containers>

  32. </ unity>


  33. </ configuration>

Thursday, 12 November 2009

Unity Application Block

Introduction

The Unity Application Block is a lightweight framework which allows/simplifies the implementation of;

· Inversion of control (IoC)

· Service Location

· Dependency injection

See the terminology section for a brief discussion of these concepts.

When to use Unity

these have been compiled from http://msdn.microsoft.com/en-us/library/dd203206.aspx 

  • Your objects and classes may have dependencies on other objects or classes.
  • Your dependencies are complex or require abstraction.
  • You want to take advantage of constructor, method, or property call injection features.
  • You want to manage the lifetime of object instances.
  • You want to be able to configure and change dependencies at run time.

Disadvantages

  • There is a slight performance hit.
  • A lot more class files, interfaces etc are created.
  • Code can be complicated to follow, and sometimes things “just happen” which can be confusing
  • Junior developers need to understand new concepts.

Getting Unity

Unity’s MSDN page can be found at http://msdn.microsoft.com/en-us/library/dd203104.aspx and this example uses version 1.2

There is also a codeplex site at http://www.codeplex.com/wikipage?ProjectName=unity here sample projects and discussions can be found

Code Example

The following code example allows us to switch between two Customer Service Classes, one with logging one without.  I appreciate this is not a realistic example but it does explain the point, it could easily be one uses an SQL Server database the other an Oracle.

I have 4 projects;

  • InterfaceLibrary, this contains all of my interfaces. 
  • BusinessObjects, this contains my class file of the Customer Objects which implements the interface
  • ServiceLayer, this populates and returns a BusinessObject
  • FormApplication, this displays the information from the ServiceLayer.

 

IntefaceLibrary

This has interfaces for the Customer Object, which I call ICustomer.

Code Snippet
  1. namespace InterfaceLibrary
  2. {
  3.     public interface ICustomer
  4.     {
  5.         string FirstName{get;set;}
  6.         string Surname{get;set;}
  7.     }
  8. }

 

And has an interface for the ServiceLayer called IsvcCustomer

Code Snippet
  1. namespace InterfaceLibrary
  2. {
  3.     public interface IsvcCustomer
  4.     {
  5.         ICustomer GetCustomer();
  6.     }
  7. \

 

As you can see neither of these are particularly exciting, you will notice that the GetCustomer method does not return a concrete type but rather the interface.

BusinessObjects

The BusinessObjects has a class which implements the ICustomer interface.

Code Snippet
  1. using InterfaceLibrary;
  2. namespace BusinessObjects
  3. {
  4.     public class Customer : ICustomer
  5.     {
  6.         public string FirstName { get; set; }
  7.         public string Surname { get; set; }
  8.     }
  9. }

 

ServiceLayer

Again a class file which implements an Interface, with a simple piece of code returning a Customer object

Code Snippet
  1. using BusinessObjects;
  2. using InterfaceLibrary;
  3. namespace Service
  4. {
  5.     public class svcCustomer :IsvcCustomer
  6.     {
  7.         public ICustomer GetCustomer()
  8.         {
  9.             return new Customer(){FirstName = "Fred", Surname = "Bloggs"};
  10.         }
  11.     }
  12. \

FormApplication

You will notice that so far there is no unity, this is bog standard if long winded code.  On the form project is where unity starts to come in.

I have designed a form with a button and 2 labels, the button will call the service from unity and then change the text property of the labels with the object properties (FirstName and Surname).

Once we have the form we need to configure Unity.

To do so we get an instance of the unity container.

Code Snippet
  1. var container = new UnityContainer();

Then we Register the types

Code Snippet
  1. container.RegisterType<IsvcCustomer, svcCustomer>();

With this code we are saying that when we ask for IsvcCustomer use svcCustomer in it’s place, it is possible (and probably preferable) to store this mapping in either a Web.Config or App.Config.

To return a customer object we simply use

Code Snippet
  1.             var myService = container.Resolve<IsvcCustomer>();
  2.             var customer = myService.GetCustomer();

container.Resolver returns an instance of svcCustomer.

What is important to note is that at no point do we have a reference to the concrete objects; Customer or svcCustomer.  So as long as we keep the interface we can change these objects.

Changing svcCustomer

As mentioned earlier I now want to amend svcCustomer so it has some logging. Also at this point I am going to introduce Dependency Injection.

To the above project I need to make some the following changes;

  1. Create an ILogger interface and Logger class
  2. Create a new ServiceLayer class
  3. Amend the FormApplication so this new class is called.

ILogger

ILogger has one method, WriteLog which takes a string as a parameter

Code Snippet
  1. namespace InterfaceLibrary
  2. {
  3.     public interface ILogger
  4.     {
  5.         void WriteLog(string message);
  6.     }
  7. \

Logger

Logger implements WriteLog and takes the parameter and chucks it out to the output window.

Code Snippet
  1. using System;
  2. using System.Diagnostics;
  3. using InterfaceLibrary;
  4. namespace Service
  5. {
  6.     public class Logger : ILogger
  7.     {
  8.         public void WriteLog(string message)
  9.         {
  10.             Trace.WriteLine(string.Format("{0}: {1}",
  11.                                           DateTime.Now,
  12.                                           message));
  13.         }
  14.     }
  15. }

 

svcCustomer2

svcCustomer2 implements the existing IscCustomer interface, which has not changed. However on the constructor we now need to pass in the logger class, in GetCustomer  WriteLog is called.

Code Snippet
  1. using BusinessObjects;
  2. using InterfaceLibrary;
  3. namespace Service
  4. {
  5.     public class svcCustomer2 : IsvcCustomer
  6.     {
  7.         private ILogger _logger;
  8.         public svcCustomer2(ILogger logger)
  9.         {
  10.             _logger = logger;                          
  11.         }
  12.         public ICustomer GetCustomer()
  13.         {
  14.             _logger.WriteLog("Method Called");
  15.             return new Customer() { FirstName = "Jane", Surname = "Doe" };
  16.         }
  17.     }
  18. \

 

FormApplication

The only code change we need is to register the logger

Code Snippet
  1. container.RegisterType<ILogger, Logger>();

And then change the mapping to the new service

Code Snippet
  1. container.RegisterType<IsvcCustomer, svcCustomer2>();

Which can all be held in a configuration file, so no code changes.

Dependency Injection

Traditionally to instantiate svcCustomer2 we would need to use a piece of code similar to the one below

Code Snippet
  1. svcCustomer2 svcCustomer2 = new svcCustomer2(new Logger());

which is clearly different to the svcCustomer, which does not have a constructor

Code Snippet
  1. svcCustomer svcCustomer = new svcCustomer();

Unity is clever enough to realise that there is a dependency and because it understands the concept of ILogger and knows to use Logger it does so.

Terminology

Inversion of Control (IoC)

Inversion of Control is a design pattern (http://en.wikipedia.org/wiki/Inversion_of_control). The idea is when you tightly couple your business objects to your application you lose flexibility and opportunity for reuse.

Common implementations of IoC create an interface of your business objects. So the application defines what it needs, and the business objects can implement this interface in anyway. This means different business objects could be created for, say, different data sources. A configuration file will then tell the application which particular implementation to use.

Service Location

Service locator is a design pattern that allows us to define where the business object can be found. So for example it we can define the Service Locator to use a SQL Server based object, rather than an Oracle one.

Dependency Injection

This is a particular form of IoC where the control being “inverted” is the creation of the dependencies. So in a traditional application a Customer object maybe responsible for controlling the lifespan of it’s Address object.  When Dependency Injection is used this control is handed over to the framework (in this case Unity).  All the Customer object has is a method to get an instance of the Address object.

Thursday, 25 June 2009

Entity Framework

Introduction

The entity framework is Microsoft’s offering into the ORM market. Subsequently it maps databases to entities or objects with zero coding. Wikipedia has the following to say here.

Version 1.0 has been released as part of VS.NET 2008 Service Pack 1 and the MSDN pages start here

Although there has been some controversy about the tool, however Microsoft are determined that the Entity Framework is the ORM they are going to continue to develop (as opposed to LinqtoSQL), subsequently there are a lot of enhancements in VS.NET 2010.

There are a lot of guides to how to use the Entity Framework, however there where a number of pain points I came across, and a difference of behaviour depending on whether the object became “detached” or not. This blog discusses these, some of the code is mine some of it is not ;-) Also there is some usage of new features which I hope to reference as we go along.

The code is based on a real world example and subsequently it works! but also the entities in the examples jump around quite a bit, for which I apologise.

Creating the mappings.

Actually creating the mappings to the Database is a simple task, and there is a video here. however it is simply a case of create a new ADO.NET Entity Data Model from the Add Items dialog in Visual Studio.NET 2008. Then navigate the wizard to point it at the database, select the items you want to model and the model will be generated.

If you later need to refresh the model you can do so by right clicking and choosing “update model from the Database.”

It is also advised to change the names of the Entities for example pluralise etc.

You will notice that the Foreign Keys have been converted to “Navigation Properties” . These are quite clever for each navigation property there are 2 properties, one is the Object, and the other is a reference to the object.

Populating Objects

When you import the entities, you generate a class inherited from System.Data.Objects.ObjectContext, this is your object context (almost an equivalent to DataContext in LinqtoSQL). In the examples I am using this is called TimesheetsEntities.

My first lesson or Oh That is Why (pt 1).

So the first pain point I came across, was the time it takes to create and destroy the ObjectContext. Which frustrated me as the examples often showed all of the database work happening inside a Using statement.

To prevent this, I created a Static Property for the ObjectContext so I could reference it without constantly creating and destroying it. Something like below

Code Snippet
  1. private static TimesheetsEntities _timesheetsEntities;
  2. public static TimesheetsEntities timesheetsEntities
  3. {
  4. get
  5. {
  6. if (_timesheetsEntities == null)
  7. {
  8. _timesheetsEntities = new TimesheetsEntities();
  9. }
  10. return _timesheetsEntities;
  11. }
  12. set { _timesheetsEntities = value; }
  13. \
Getting Data.

Populating the objects is relatively simple, the code below returns a Generic list of all of the Users.

Code Snippet
  1. public List<User> GetUsers()
  2. {
  3. return timesheetsEntities.Users.ToList<User>();
  4. \

However if we want to do something a little more funky we can incorporate some Linq, for example an Order by

Code Snippet
  1. public List<Status> GetStatuses()
  2. {

  3. var statuses =
  4. from n in timesheetsEntities.Statuses
  5. orderby n.OrderBy
  6. select n;

  7. return (statuses.ToList<Status>());
  8. \

or if you want to get an item based on a key, again I simple piece of linq this time using a Lambda expression.

Code Snippet
  1. public Status GetStatus(int StatusId)
  2. {
  3. return timesheetsEntities.Statuses.FirstOrDefault(m => m.StatusId == StatusId);
  4. }

Saving Data

This is where the fun starts, and the degree of fun depends on whether the entity is attached to the Object Context or not also whether it is an insert or not.

Inserts

These are easy, as the entity is new it is always unattached.

In the case below I have my context (timesheetsEntities from above) and I want to add my “project” entity so I call the AddToProjects method. An AddTo… method is created for all of the entities you mapped above.

The save routine is clever and if you have an Object Graph, an Object with Child Objects the whole graph is saved. An example would be Invoice with Lines.

Code Snippet
  1. timesheetsEntities.AddToProjects(project);
Updates (attached)

This is a little more complicated. So the object context can determine if and what needs changing you need to get a copy of the current object. Once you have done this you can apply the changes to the Object Context, using the ApplyPropertyChanges method.

Code Snippet
  1. object pObject;
  2. if (timesheetsEntities.TryGetObjectByKey(project.EntityKey, out pObject))
  3. {
  4. timesheetsEntities.ApplyPropertyChanges(project.EntityKey.EntitySetName, project);
  5. \

At the end of this you need to tell the entity frame work to save.

all in all it looks a little like this

Code Snippet
  1. //TODO: this is insert what about update?
  2. if (project.ProjectId == 0)
  3. {
  4. timesheetsEntities.AddToProjects(project);
  5. }
  6. else
  7. {

  8. object pObject;
  9. if (timesheetsEntities.TryGetObjectByKey(project.EntityKey, out pObject))
  10. {
  11. timesheetsEntities.ApplyPropertyChanges(project.EntityKey.EntitySetName, project);
  12. }


  13. }

  14. int changes = timesheetsEntities.SaveChanges();

Updates Detached (Or Oh that is how pt2 – Oh well I lost count)

It as at this point the Entity framework starts getting inconsistent, and I nearly lost a lot of hair.

You can identify if the entity is attached or not by testing it’s entityState property.

Code Snippet
  1. if (timeSheet.EntityState == EntityState.Detached)

The first inconsistency is ApplyPropertyChanges no longer save foreign key constraints. So for example the timesheets entity (above) has a Status (which is a lookup table). If this changes in the Attached model this seems fine, however when you are Detached it is not.

However i found this on the internet, which explains creating an extension method which will update the object for all of the items.

This extension method needs to be placed in a separate static class.

Code Snippet
  1. public static void ApplyReferencePropertyChanges(this ObjectContext context, IEntityWithRelationships newEntity, IEntityWithRelationships oldEntity)
  2. {
  3. foreach (var relatedEnd in oldEntity.RelationshipManager.GetAllRelatedEnds())
  4. {
  5. var oldReference = relatedEnd as EntityReference;

  6. if (oldReference != null)
  7. {
  8. var newReference = newEntity.RelationshipManager.GetRelatedEnd(oldReference.RelationshipName,
  9. oldReference.TargetRoleName) as EntityReference;

  10. if (newReference != null)
  11. {
  12. oldReference.EntityKey = newReference.EntityKey;
  13. }
  14. }
  15. }
  16. \

The second inconsistency is the object graph is not saved. So you need to iterate through each of the child objects and save them individually. This is a bit long winded and I have a lovely selection of error messages that went with it.

So in my Model the Timesheet has lines. As in an update these might have changed, the first stage is, to loop through each of the items and call a save routine. Which sounds straight forward. Except some are new, so we have to differentiate in our save routine.

The next problem I had was “The object cannot be added to the ObjectStateManager because it already has an EntityKey. Use ObjectContext.Attach to attach an object that has an existing key”

The cause of this error was because the Navigation Properties where confusing the Object Context, so for each of the navigation properties I had to remove the Objects and set the EntityKey to the Reference of the Navigation Property.

Code Snippet
  1. if (timeSheetLine.TimeSheetLineId == 0)
  2. {
  3. TimeSheetLine newTimeSheetLine = timeSheetLine.Clone<TimeSheetLine>();

  4. newTimeSheetLine.TimeSheets = null;
  5. newTimeSheetLine.TimeSheetsReference = null;
  6. newTimeSheetLine.TimeSheetsReference = new EntityReference<TimeSheet>();
  7. newTimeSheetLine.TimeSheetsReference.EntityKey = timeSheetLine.TimeSheets.EntityKey;


  8. newTimeSheetLine.Projects = null;
  9. newTimeSheetLine.ProjectsReference = null;
  10. newTimeSheetLine.ProjectsReference = new EntityReference<Project>();
  11. newTimeSheetLine.ProjectsReference.EntityKey = timeSheetLine.ProjectsReference.EntityKey;

  12. timesheetsEntities.AddToTimeSheetLines(newTimeSheetLine);
  13. }
  14. else
  15. {

  16. object pObject;
  17. timesheetsEntities.TryGetObjectByKey(timeSheetLine.EntityKey, out pObject);
  18. timesheetsEntities.ApplyPropertyChanges(timeSheetLine.EntityKey.EntitySetName, timeSheetLine);

  19. timesheetsEntities.ApplyReferencePropertyChanges(timeSheetLine as IEntityWithRelationships, pObject as IEntityWithRelationships);


  20. }

The astute of you will notice the Clone method which is not a method of ArrayList again this is another Extension method. Again I found it on the internet but I am afraid I have lost the reference. The object needed to cloned because you cannot change an object in a foreach, but also this created some reasonably elegant code.

Code Snippet
  1. public static T Clone<T>(this T source)
  2. {
  3. var dcs = new System.Runtime.Serialization
  4. .DataContractSerializer(typeof(T));
  5. using (var ms = new System.IO.MemoryStream())
  6. {
  7. dcs.WriteObject(ms, source);
  8. ms.Seek(0, System.IO.SeekOrigin.Begin);
  9. return (T)dcs.ReadObject(ms);
  10. }
  11. }
  12. \

Conclusion

Although the Entity Framework does cause some headaches, I think it is a good technology with lots of potential. Hopefully this helps solve some of the problems, I have some ideas on how to deal with dirty reads and writes which I will post later.

Wednesday, 18 February 2009

Packaging multiple lists in a single feature

 

The comment at the following site suggests that it is not possible to put multiple lists in a feature.

http://msdn.microsoft.com/en-us/library/ms434306.aspx

Which although is correct, as always Microsoft have another method of doing this.

The procedure is relatively straight forward.

  • Create list
  • Save the list as a template.
  • Save the stp file(s)
  • create a feature in which the Elements.xml file references the stp.

Create List

This is the normal procedure navigate to the create list screen http://yourserver/_layouts/create.aspx

Select Custom List

image 

In the next screen enter the name of the list and description.

You will then be presented with a standard list, go to List Settings

image

Add the additional columns you require.

Save List as Template

When finished select  Save list as template.

and complete the form shown below.

image

Save the stp.

If you go to the List templates (http://yourserver/_catalogs/lt/Forms/AllItems.aspx) your will find your custom list by clicking on the name of the file you will be given the option to save the file. Put this file somewhere safe!

image

At this point to prevent trying to create two templates of the same name, I usually either rename or delete this item.

Create the feature

For this step I use WSPBuilder which can be downloaded from here.  I assume that you can create a basic feature using the WSPBuilder Add-in.

You will need a file structure like this.

image

Then the elements.xml contents will look like this.

image

The Property Value is the name of the list (News Articles in the example above)

You can nest multiple “Module” elements.

The when you build and deploy the wsp you will have a new feature, which when activated will have additional items in the List templates and in the create list screen.