Nov 2, 2010

ESE Software Engineering Conference in Zürich – Call for Papers

The international Software Engineering Conference ESE Conference 2011 (12.-14. April) opens the Call for Papers.

image

So, if you are an expert in a technical software topic you can submit your talk until 12. December 2010.

The conference allows the discussion and exchange of experts and participants.

Aug 11, 2010

Silverlight 3 Trap : OneWayToSource

Silverlight is missing some details you may be using in WPF. One of them is the missing data binding mode OneWayToSource. Another one is the missing SelectionChanged command of a ComboBox. Both created a funny behavior in my current project.

image

I have a ViewModel property

public string Selected

{

    get

    {

        return this._selected;

    }

    set

    {

        this._selected = value;

        this.RaisePropertyChanged("Selected");

    }

}

and two ComboBox TwoWay (OneWayToSource does not exist) binding on it with SelectedItem

<ComboBox Name="c1" mycmd:SelectionChangedCommand.Command="{Binding C1SelectionChangedCommand}" ItemsSource="{Binding Selections}" SelectedItem="{Binding Selected, Mode=TwoWay}" />

<ComboBox Name="c2" mycmd:SelectionChangedCommand.Command="{Binding C2SelectionChangedCommand}" ItemsSource="{Binding Selections}" SelectedItem="{Binding Selected, Mode=TwoWay}" />

The funny thing was, that when I made a selection on combo box c1 the command handler of my c2 fired (too) – due to the this.RaisePropertyChanged("Selected") above:

- c1 copies the SelectedItem from the target to the source

- the source property raises the property changed event and

- copies the Selected property value to the other c2 target

- c2 fires the SelectionChanged command

Et voilà, your in the Guatemala City trap…it would be better to have more fine-grained data binding control with OneWayToSource in the first place.

Jul 2, 2010

Silverlight 3 Debugging in Visual Studio 2008: Breakpoint not hit

Today I hit the problem, that I could not any longer debug Silverlight client applications (it worked yesterday).

A lot of solutions have been posted out there, which did not help for me. The most common cause with other people was that the web project had the Silverlight Debugger option unticked. So enable it again.

image

Going back to the source code from yesterday and doing it again, showed me the following screen (“Do you want to enable Silverlight debugging for this project? …” – event when this tick was set!

image

After some time struggling around I found out, that I had to set the “Set as Start Page” again on my .htm page. I looks like this fixes something (btw, even when the start project was set correctly before!).

May 21, 2010

Entity Framework 4 : Cascaded Delete in Parent-Child Relationship?

Extending the previous post, let’s look at cascaded delete

image

[TestMethod]

[ExpectedException(typeof(System.Data.ObjectNotFoundException))]

public void DeleteParentEntity_WithOneToOneChildEntityRelationshipConstraint_ChildIsAutomaticallyDeleted()

{

    // save parent and child (1:1)

    FinanceMinister financeMinister = new FinanceMinister

    {

        Name = "Giulio Tremonti",

        Email = "gt@finanze.it"

    };

    Country country = new Country

    {

        Name = "Italy",

        GDP = 2118.264M, // billions ?

        ForeignDebt = 0M,

        FinanceMinister = financeMinister

    };

    this.target.Add(country);

    this.target.Save();

    int financeMinisterId = financeMinister.Id;

 

    // check if that was done right

    Country reloadedCountry = this.target.GetById<Country>(new Country { Id = country.Id });

    Assert.AreEqual<string>(country.FinanceMinister.Name, reloadedCountry.FinanceMinister.Name);

 

    // delete Country and check that treasurer is also gone

    this.target.Delete(country);

    this.target.Save();

    this.target.GetById<FinanceMinister>(new FinanceMinister { Id = financeMinisterId });

}

throws

image

Now setting the relationship to “cascade”

image

Runs OK, deleting the country and the corresponding finance minister in one go:

image

image

Entity Framework 4 : Delete child from ParentChild Relationship – throws or what?

[topic from a discussion; addressing a colleague]

Imagine the very common situation where you have a parent-child relationship like the following, and you want to delete the child (Currency; or better just remove the relation by setting the parent’s child navigation property to null):

image

Having code (show in an intergration test) like this

[TestMethod]

public void RemoveChildEntityNavigationFromParentEntityProperty_WithManyToOneConstraint_Throws()

{

    // save parent and child with a 1:* relationship constraint

    int dbGeneratedCityId = -1;

    Currency chf = new Currency { Symbol = "CHF", Name = "Schweizer Franken" };

    City city = new City { Code = "ZRH", Name = "Zürich", Currency = chf };

    this.target.Add(city);

    this.target.Save();

    dbGeneratedCityId = city.Id;

 

    // get the parent again from the database and get rid of the child

    City reloadedCity = this.target.GetById<City>(new City { Id = dbGeneratedCityId });

    Assert.IsNotNull(reloadedCity.Currency);

    reloadedCity.Currency = null;

    this.target.Save();

 

    // assert that the child was properly deleted

    City reloadedUpdatedCity = this.target.GetById<City>(new City { Id = dbGeneratedCityId });

    Assert.IsNull(reloadedUpdatedCity.Currency);

}

 

Using SQLProfiler shows that the following queries are emitted for the first code block

image  image

Calling Save() in the second block throws the following exception:

image

Aha, sure, this is due to the “1” in the “1:*” relationship – no cities without a default local currency (not even south european EU contries … sorry, no, not funny).

Let’s change this to “0..1”

image

Running the same test again shows “green”

image

emitting the Update statement.

image

Please note:

  • depending on the constraint, there may be no Delete(chf) necessary
  • relationship constraints violations throw exceptions
  • simply set the parent’s child navigation property to null
  • loosening the constraint to “0..1” leaves the child entity in the database

In comparison we can do the following (with “0..1” relationship):

[TestMethod]

public void DeleteChildEntityFromParent_WithManyToOneConstraint_Throws()

{

    // save parent and child with a 0..1:* relationship constraint

    int dbGeneratedCityId = -1;

    Currency euro = new Currency { Symbol = "EUR", Name = "Euro" };

    City city = new City { Code = "ATH", Name = "Athens", Currency = euro };

    this.target.Add(city);

    this.target.Save();

    dbGeneratedCityId = city.Id;

 

    // get the parent again from the database and get rid of the child

    City reloadedCity = this.target.GetById<City>(new City { Id = dbGeneratedCityId });

    Assert.IsNotNull(reloadedCity.Currency);

   this.target.Delete(reloadedCity.Currency);  // Athens and no more Euro

    this.target.Save();

 

    // assert that the child was properly deleted

    City reloadedUpdatedCity = this.target.GetById<City>(new City { Id = dbGeneratedCityId });

    Assert.IsNull(reloadedUpdatedCity.Currency);

}

and get

image

Setting the constraint back to “1:*” throws too:

DeleteChildEntityFromParent_WithManyToOneConstraint_Throws threw exception:
System.Data.UpdateException: A relationship from the 'CityCurrency' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'City' must also in the 'Deleted' state.

Guessing the same behavior for NHibernate. Can anybody confirm this?

May 17, 2010

Public Interfaces of WCF in Silverlight 4

Microsoft seems to have added some more interfaces to System.ServiceModel in Silverlight 4 (came across a blog post from Dominick Baier). These can be used as WCF extensibility points.

Here is a list of all the public interfaces I found reflecting the assembly:

System.ServiceModel.IDefaultCommunicationTimeouts
System.ServiceModel.ICommunicationObject
System.ServiceModel.Channels.IChannel
System.ServiceModel.Channels.IChannelFactory
System.ServiceModel.Channels.IChannelFactory`1[TChannel]
System.ServiceModel.Channels.IInputChannel
System.ServiceModel.Channels.IOutputChannel
System.ServiceModel.Channels.IDuplexChannel
System.ServiceModel.Channels.ISession
System.ServiceModel.Channels.IInputSession
System.ServiceModel.Channels.IOutputSession
System.ServiceModel.Channels.IDuplexSession
System.ServiceModel.Channels.ISessionChannel`1[TSession]
System.ServiceModel.Channels.IDuplexSessionChannel
System.ServiceModel.Channels.IInputSessionChannel
System.ServiceModel.Channels.IOutputSessionChannel
System.ServiceModel.Channels.IRequestChannel
System.ServiceModel.Channels.IRequestSessionChannel
System.ServiceModel.Channels.IHttpCookieContainerManager
System.ServiceModel.Description.IEndpointBehavior
System.ServiceModel.IExtensionCollection`1[T]
System.ServiceModel.Description.IContractBehavior
System.ServiceModel.IExtensibleObject`1[T]
System.ServiceModel.IExtension`1[T]
System.ServiceModel.Description.IOperationBehavior
System.ServiceModel.IContextChannel
System.ServiceModel.IClientChannel
System.ServiceModel.Dispatcher.IClientOperationSelector
System.ServiceModel.Dispatcher.IParameterInspector
System.ServiceModel.Dispatcher.IClientMessageFormatter

System.ServiceModel.Dispatcher.IClientMessageInspector
System.ServiceModel.Dispatcher.IDispatchMessageFormatter

System.ServiceModel.Channels.IMessageProperty

generated (without Reflector) using

IList<Type> types = typeof(IClientMessageInspector).Assembly

    .GetTypes()

    .Where(t => t.IsInterface && t.IsPublic)

    .ToList();

 

I have not tried them, but the bold ones are interesting for WCF extensibility.

May 3, 2010

Exclude from Code Coverage (Visual Studio 2010)

 

I was working on a library that adds some customer specific functionality to web services and WCF. I decided to have it very highly covered by unit tests. Unfortunately there is some static functionality in WCF (OperationContext) that is hard to be used in unit tests (it throws). So I wrapped this code behind a custom C# interface with a production implementation calling OperationContext and an (independant and fast) unit test implementation/mock. The small and simple production implementation had some negative impact on Visual Studio (instruction) code coverage (being below 100%). I figured out how to exclude this piece of code.

The way to do this is to add the [ExcludeFromCodeCoverage] attribute to class, property, method or event:

namespace MyTrials

{

    // [ExcludeFromCodeCoverage]

    public class NotCoveredClass

    {

        [ExcludeFromCodeCoverage]

        public string NotCoveredProperty { get; set; }

        public string CoveredProperty { get; set; }

 

        [ExcludeFromCodeCoverage]

        public EventHandler<EventArgs> OnNotCoveredEvent { get; set; }

        public EventHandler<EventArgs> OnCoveredEvent { get; set; }

 

        [ExcludeFromCodeCoverage]

        public void NotCoveredMethod()

        {

        }

 

        public void CoveredMethod()

        {

        }

    }

 

    public class CoveredClass

    {

    }

}

Write some more useful unit tests than I did for this post:

[TestMethod]

public void CodeCoverage_ExcludeWith_ExcludeFromCodeCoverage_FromClassMethodPropertyEvent()

{

    CoveredClass target = new CoveredClass();

    NotCoveredClass target2 = new NotCoveredClass();

 

    target2.CoveredMethod();

}

 

to have it excluded:

image

Other ways I’ve seem were to add [System.Diagnostics.DebuggerHidden] or [System.Diagnostics.DebuggerNonUserCode] to methods – but with some side effects!

Apr 12, 2010

Learning Tests

Robert C. Martin brought it into my world in his book “Clean Code – A Handbook of Agile Software Craftmanship” - “Learning tests”.

“Learning tests” (by K. Beck?)

  • are unit tests
  • to explore (learn) a new API or framework
  • that builds a set of tests for regression when a new version of the component is used to validate that your expectations of the API is still fulfilled

For an upcoming training I wanted to use AutoMapper (by J. Bogard) for entity to/from DTO transformations. There is not a lot of documentation around for this open source library and my first trial with the API ended in a strange exception.

So I decided to write some unit tests first (getting them red was rather easy ;-) and investigate on the common use of AutoMapper (www.google.com/codesearch).

Here are some of my tests (please note the method names which should give you an idea about my expectations):

/// <summary>

/// Learning tests for automapper by Jimmy Bogard from http://automapper.codeplex.com/

/// </summary>

[TestClass]

public class AutoMapperTests

{

    [TestInitialize]

    public void TestInitialize()

    {

        Mapper.Reset();

    }

 

    [TestMethod]

    [ExpectedException(typeof(AutoMapperMappingException))]

    public void Map_NoMappingExists_Throws()

    {

        DestinationType destination = Mapper.Map<SourceType, DestinationType>(SourceType.CreateSimple());

    }

 

    [TestMethod]

    public void Map_CreateMap_ReturnsMappingExpression()

    {

        IMappingExpression<SourceType, DestinationType> mappingExpression = Mapper.CreateMap<SourceType, DestinationType>();

 

        DestinationType destination = Mapper.Map<SourceType, DestinationType>(SourceType.CreateSimple());

 

        Assert.IsInstanceOfType(destination, typeof(DestinationType), "must return instance of destination type");

    }

 

    [TestMethod]

    public void Map_CreateMapForOneMember_ReturnsDestinationWithOneMember()

    {

        Mapper

            .CreateMap<SourceType, DestinationType>()

            .ForMember(d => d.Text, c => c.MapFrom<string>(s => s.Text));

        SourceType source = SourceType.CreateSimple();

 

        DestinationType destination = Mapper.Map<SourceType, DestinationType>(source);

 

        Assert.AreEqual<string>(source.Text, destination.Text, "member must be mapped");

    }

 

    [TestMethod]

    public void Map_CreateMapForMembersIgnoreOne_ReturnsDestinationWithoutMember()

    {

        Mapper

            .CreateMap<SourceType, DestinationType>()

            .ForMember(d => d.Text, c => c.MapFrom<string>(s => s.Text))

            .ForMember(d => d.Floating, c => c.Ignore())

            .ForMember(d => d.Number, c => c.MapFrom<int>(s => s.Number));

        SourceType source = SourceType.CreateSimple();

 

        DestinationType destination = Mapper.Map<SourceType, DestinationType>(source);

 

        Assert.AreNotEqual<double>(source.Floating, destination.Floating, "ignored member must not be mapped");

    }

 

    [TestMethod]

    public void Map_CreateMapForChildMembers_ReturnDestinationWithChildMembers()

    {

        Mapper

            .CreateMap<SourceType, DestinationType>()

            .ForMember(d => d.Child, c => c.MapFrom<SourceType>(s => s.Child));

        SourceType source = SourceType.CreateSimple();

        source.Child = SourceType.CreateSimple();

 

        DestinationType destination = Mapper.Map<SourceType, DestinationType>(source);

 

        Assert.AreEqual<string>(source.Child.Text, destination.Child.Text, "child member (reference type) not mapped");

    }

 

    [TestMethod]

    [ExpectedException(typeof(AutoMapperMappingException))]

    public void Map_CreateMapWithoutRecursiveMaps_Throws()

    {

        // map "outer" (root) type

        Mapper.CreateMap<TopSourceType, TopDestinationType>()

            .ForMember(d => d.DestinationType, c => c.MapFrom<SourceType>(s => s.SourceType));

 

        TopSourceType source = TopSourceType.CreateSimple();

        TopDestinationType destination = Mapper.Map<TopSourceType, TopDestinationType>(source);

 

        Assert.Fail("inner (reference type) map not done. Automapper must throw");

    }

 

    [TestMethod]

    public void Map_CreateMapWithRecursiveMaps_ReturnsTreeDestination()

    {

        // map "inner" type

        Mapper.CreateMap<SourceType, DestinationType>()

            .ForMember(d => d.Text, c => c.MapFrom<string>(s => s.Number.ToString(CultureInfo.CurrentCulture)));

 

        // map "outer" (root) type

        Mapper.CreateMap<TopSourceType, TopDestinationType>()

            .ForMember(d => d.DestinationType, c => c.MapFrom<SourceType>(s => s.SourceType));

 

        TopSourceType source = TopSourceType.CreateSimple();

        TopDestinationType destination = Mapper.Map<TopSourceType, TopDestinationType>(source);

 

        Assert.AreEqual<string>(

            source.SourceType.Number.ToString(CultureInfo.CurrentCulture),

            destination.DestinationType.Text,

            "child member (of different reference types) not mapped");

    }

 

    // … and more

}

And here are my tests classes:

/// <summary>

/// Tests-only source type for mapping tests.

/// </summary>

internal class SourceType

{

    public int Number { get; set; }

    public string Text { get; set; }

    public double Floating { get; set; }

 

    public SourceType Child { get; set; }

 

    public static SourceType CreateSimple()

    {

        return new SourceType { Floating = 1.1, Number = 13, Text = Guid.NewGuid().ToString() };

    }

}

 

internal class TopSourceType

{

    public int? Id { get; set; }

    public SourceType SourceType { get; set; }

 

    public static TopSourceType CreateSimple()

    {

        return new TopSourceType { Id = 13, SourceType = SourceType.CreateSimple() };

    }

}

 

/// <summary>

/// Tests-only destination type for mapping tests.

/// </summary>

internal class DestinationType

{

    public int Number { get; set; }

    public string Text { get; set; }

    public double Floating { get; set; }

 

    public DestinationType Child { get; set; }

 

    public override string ToString()

    {

        return string.Format(CultureInfo.CurrentCulture, "Number = {0}, Text = {1}, Floating = {2}", this.Number, this.Text, this.Floating);

    }

}

 

internal class TopDestinationType

{

    public string Id { get; set; }

    public DestinationType DestinationType { get; set; }

}

Mar 16, 2010

Specification Pattern with Func<>

Specification is a pattern (Evans/Fowler) that can be used to apply rules for your domain entities:

Create a specification that is able to tell if a candidate object matches some criteria. The specification has a method isSatisfiedBy (anObject) : Boolean that returns "true" if all criteria are met by anObject.

It defines an interface like

public interface ISpecification

{

    bool IsSatisfiedBy<T>(T candidate);

 

    ISpecification And(ISpecification other);

 

    ISpecification Or(ISpecification other);

 

    ISpecification Not();

}

where IsSatisfiedBy() wraps the business logic (not contained in the entity as OO would suggest).

That allows to write business logic code like

price.And(seats).And(slow.Not())

My car specification:

public class CarSpecification : Specifications.CompositeSpecification

{

    public Func<Car, bool> IsSatisfiedFunction { get; set; }

 

    public CarSpecification(Func<Car, bool> isSatisfiedFunction)

    {

        this.IsSatisfiedFunction = isSatisfiedFunction;

    }

 

    public override bool IsSatisfiedBy<T>(T candidate)

    {

        if (!(candidate is Car))

        {

            throw new ArgumentException("must pass Car entity", "candidate");

        }

 

        if (this.IsSatisfiedFunction != null)

        {

            return this.IsSatisfiedFunction(candidate as Car);           

        }

        return false;

    }

}

The whole code:

public partial class MainWindow : Window

{

    private IList<Car> cars;

    private CarSpecification price = new CarSpecification(c => c.Price <= 40000);

    private CarSpecification seats = new CarSpecification(c => c.Seats >= 7);

    private CarSpecification slow = new CarSpecification(c => c.HorsePower < 140);

 

    public MainWindow()

    {

        InitializeComponent();

 

        this.cars = ApplyRules(Cars.Get());

        this.DataContext = this.cars;

    }

 

    private IList<Car> ApplyRules(IList<Car> cars)

    {

        ISpecification myCarSpecification = price.And(seats).And(slow.Not());

        return cars.Where(c => myCarSpecification.IsSatisfiedBy<Car>(c)).ToList();

    }

}

Definitively this simple example could be written in other ways. More importantly you evaluate your new car ….

image

Linq in a Generic Data Access Layer with EF4

Introduction

Decoupling a data access layer (DAL) from business or service logic has become mainstream for some time now – not only due to testing (mocking) reasons but also because replacing your ageing data access technology or your database (manufacturer) may be a topic.

The Interface

I’ve created a simple repository pattern (CRUD) kind of interface over the last year or two. The methods of the interface are generic

int Add<T>(T entity);

int Delete<T>(T entity);

int Update<T>(T entity);

IList<T> GetAll<T>();

// and more

The implementation was done with NHibernate 2.1 and recently with Entity Framework 4.0 (EF4).

The Domain Model

I had several domain models and object-relational mapping (ORM) definitions. Here’s a simple model to show things:

image

A blog or facebook like system that stores Entry objects allows for people to add Comments or just say they like it (Liker).

Using Linq 

Linq is a powerful language feature that can be used to submit queries from the layers on top of the DAL. It is data access and database independent because it works on the domain model – so no coupling to a particular technology.

For this reason I provided a Linq entry point to the interface. Shown here is the EF4 implementation:

public IQueryable<T> GetLinq<T>()

{

    ObjectContext context = GetObjectContext();

    return context.CreateObjectSet<T>() as IQueryable<T>;

}

Or even easier with NHibernate and the NHibernate Linq provider:

public IQueryable<T> GetLinq<T>()

{

    return this.Session.Linq<T>();

}

Now you can program statements like

l = databaseContext.GetLinq<Entry>().Where(entry => entry.Title.Length > 5).ToList();

emitting SQLExpress 2008 T-SQL:

image

Or more complex

var result = from x in this.databaseContext.GetLinq<Entry>()

             join y in this.databaseContext.GetLinq<Liker>()

             on x.Id equals y.Entry_FK

             select new { x.Title, y.Posted };

producing

image

Clean and optimized! The above seems to work due to lazy evaluation and loading.

Note that you could use GetAll<T>().Where() kind of code, but this would return all (10000+) records and only filter on the result set – so a performance killer.

Jan 15, 2010

Create your own Web Casts with Microsoft Expression Encoder Screen Capture

Have you ever explained a certain topic to a peer or a live audience and wanted to

  • record your computer screen
  • record the audio
  • save this to a file

for later reuse or another audience?

Then the Microsoft Expression Encoder (3) Screen Capture is an application to look at. Screen Capture is included in Expression Studio 3, Expression Web 3 or the Expression Professional Subscription.

Start the application, enable the microphone (and web cam; no tried yet myself) and press the red dot button.

image

Select the screen area to capture

image

Press the red button again to confirm your selection

image

Pausing recording is done with Ctrl+Shift+F11, stopping with Ctrl+Shift+F12.

An .xesc file is now create. To encode this to a more common format (like mp4 or wmv) Microsoft Expression Encoder 3 can be used:

image