Archiv der Kategorie: English

Microservices don’t like thinking in conventional entities

I recently had one of these special AHA-moments in a workshop held by Udi Dahan, CEO of Particular. In his example he was using the classic entity of a customer.

To realise microservices means cutting functionality in a clean way and to transfer it into separate pillars (or silos). Each silo has to have the responsibility over it’s own data, on which it builds the respective business processes. So far, so good. But how can we realise this for our typical customer, who’s model is shown in the screenshot? Different properties are needed or changed by different microservices.

If the same entity is used in all pillars, there needs to be a respective synchronisation between all microservices. This results in a considerable impact on scalability and performance. In an application with lots of parallel changes of an entitiy the failing of the business processes will increase – or lead to inconsistencies in the worst case.

Conventional Customer

conventional entity of a customer

Udi suggests the following modelling

New Customer

Customer is modelled with independent entities

To identify which data belongs together, Udi suggests an interesting approach:

Ask the operating department if changing a property has a consequence for another property.

Would changing the last name of customer have an influence on the price calculation? Or on the way of marketing?

Now we need to solve the problem of aggregation, for example if I want to show different data from different microservices in my view. In a classic approach we would have a table with following columns:

ID_Customer ID_MasterData ID_Marketing ID_Pricing

This leads to the following two problems:

  1. The table needs to be extended if a new microservice is added
  2. If a microservice covers the same functionality in the form of data, you would have to add multiple columns for each microservice and allow NULL values as well

An example for the second point could be a microservice which covers the matter of payment methods. In the beginning you could only use credit cards and debit charges. Then Paypal. Bitcoin soon after. The microservice would have different tables on which the respective data for the payment method would be stored. In the aggregated table shown above it would be necessary to fill a separate column for each payment method the customer is using. If he doesn’t use it, a NULL value would be written. As you can see: This sucks.

Another approach is much more convenient for this. Which one this is and how it’s realised technically you can find on the GitHub repository of Particular.

 

Werbung

How to get the PostSharp package running with Paket

Recently, I reported some difficulties that I‘ve experienced with the PostSharp NuGet package when I was using the new package manager Paket. I tracked the problem down to the ‚install.ps1‘ script which is executed by NuGet after adding PostSharp to a project. This PowerShell script (located under packages\PostSharp\tools) patches your project file. Since this behaviour is already proclaimed from the pulpit by NuGet, I hope that PostSharp is going to remove that asap. Until then, you can execute the script manually or patch the csproj-File by yourself.

In order to do that, insert the following 2 snippets at the the position shown in the screenshots:

   1: <DontImportPostSharp>True</DontImportPostSharp>

 

image

 

Don’t forget to change the relative path to your PostSharp package in the following snippet:

   1: <Import Project="..\..\packages\PostSharp\tools\PostSharp.targets" Condition="Exists('..\..\packages\PostSharp\tools\PostSharp.targets')" /> 

   2: <Target Name="EnsurePostSharpImported" BeforeTargets="BeforeBuild" Condition="'$(PostSharp30Imported)' == ''">

   3: <Error Condition="!Exists('..\..\packages\PostSharp\tools\PostSharp.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://www.postsharp.net/links/nuget-restore." />

   4: <Error Condition="Exists('..\..\packages\PostSharp\tools\PostSharp.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://www.postsharp.net/links/nuget-restore." />

 

image

 

I also recommend you to activate the following PostSharp Option in Visual Studio:

image

PostSharp reports broken references when using Paket

If you use Paket instead of NuGet (why? therefore!) you will experience the following difficulties:

imageGiven is the following Solution/Project. It contains a paket.references file containin just one line “PostSharp”, which is

The PostSharp Assembly is added when you your “paket.references” file in the project directory containing just one line “PostSharp”. If you execute “paket install” in your command promt, paket adds PostSharp as reference to the project and modifies the csproj accordingly.

The next time you run a build, PostSharp comes up with this dialog:

postsharp

Since the VisualStudio PostSharp plugin detects a reference to PostSharp.dll, it expects a packages.config which it can’t find. If you don’t agree, the solution builds successfully but the code won’t be modified by PostSharp.

imageIf you agree, PostSharps adds a packages.config and replaces the existing PostSharp reference with the newest stable one (which probably is not the version you have specified in Paket!).

I posted this on Twitter. The Paket maintainers can’t handle this and PostSharp won’t change this behaviour.

image

image

image

So by now, I don’t see any solution except that Paket users can ask PostSharp to change this behaviour.

//Edit: Have a look at the comments. The unsolved problem is that you have to execute the „install.ps1“. Paket doesn’t do that but NuGet will also remove this feature in a future release.

Where YouTrack 6 still lacks

  • Single Sign-on in a Windows Domain: Vote for this here
  • Print sprint cards: Vote for this here (or enhance the whole agile board)
  • Support of Skype IM for notifications: Vote for this here
  • Support of enum type fields as a dop-down in order to implement the Fibonacci sequence: Vote for this here
  • Summarize states into one column in Agile Board so that showing open and reopened issues is possible: Vote for this here

Ready-to-Use C# Enumeration Extension Methods

Bei dem unten stehenden Code handelt es sich um fertige Enum Extension Methods in C#. Damit lassen sich unter anderem

  • die Enum Description
  • der Enum Comment
  • das Enum Value
  • alle Enum Values und
  • gesetzte Enum Flags

auslesen. Der Code ist bereits ein wenig in die Jahre gekommen und einige Methoden habe ich lediglich noch aus Kompatiblitätsgründen drin. Die Tests sind mit Machine.Specifications 0.6.2 geschrieben.

Kopiert euch einfach, was ihr benötigt und passt es nach Belieben an. Über Likes oder Comments, wenn euch der Code Arbeit gespart hat, wäre ich dankbar.

Über gute Alternativen zu Enums könnt ihr hier etwas lesen.

 

Implementierung:

public static class EnumerationExtensions

{

    public static bool ByteIsSet<TEnum>(this Enum bytes, TEnum enumValue)

    {

        if (!Attribute.IsDefined(typeof (TEnum), typeof (FlagsAttribute)) ||

            bytes.GetType() != enumValue.GetType() ||

            bytes.GetType() != typeof (TEnum))

        {

            return false;

        }

 

        return ((Convert.ToInt32(bytes) & Convert.ToInt32(enumValue)) == Convert.ToInt32(enumValue));

    }

 

    public static IList<EnumEntry> GetEnumerationEntries(this Type enumeration)

    {

        var values = Enum.GetValues(enumeration);

 

        var result = new List<EnumEntry>();

 

        foreach (var value in values)

        {

            // ReSharper disable ExpressionIsAlwaysNull

            var desc = (value as Enum).GetEnumDescription();

            var comment = (value as Enum).GetEnumComment();

            // ReSharper restore ExpressionIsAlwaysNull

 

            var name = Enum.GetName(enumeration, value);

            var id = (int)value;

 

            result.Add(new EnumEntry

                       {

                           Name = name,

                           Id = id,

                           DisplayName = desc,

                           Comment = comment

                       });

        }

 

        return result;

    }

 

    public static string GetEnumDescriptionIfExists(this Enum enumeration)

    {

        return GetEnumDescription(enumeration, true);

    }

 

    public static string GetEnumDescription(this Enum enumeration)

    {

        return GetEnumDescription(enumeration, false);

    }

 

    private static string GetEnumDescription(Enum enumeration, bool nullIfNotExists)

    {

        var fi = enumeration.GetType().GetField(enumeration.ToString());

 

        if (fi == null)

        {

            return nullIfNotExists ? null : string.Empty;

        }

 

 

        var attribute = (DescriptionAttribute[])fi.GetCustomAttributes(typeof (DescriptionAttribute), false);

 

        if (attribute.Length > 0)

        {

            return attribute[0].Description;

        }

 

 

        return nullIfNotExists ? null : enumeration.ToString();

    }

 

    public static string GetEnumCommentIfExists(this Enum enumeration)

    {

        return GetEnumComment(enumeration, true);

    }

 

    public static string GetEnumComment(this Enum enumeration)

    {

        return GetEnumComment(enumeration, false);

    }

 

    private static string GetEnumComment(Enum enumeration, bool nullIfNotExists)

    {

        var fi = enumeration.GetType().GetField(enumeration.ToString());

 

        if (fi == null)

        {

            return nullIfNotExists ? null : string.Empty;

        }

 

        var attr = (EnumCommentAttribute[])(fi.GetCustomAttributes(typeof (EnumCommentAttribute), false));

 

        if (attr.Length > 0)

        {

            return attr[0].ResourceComment;

        }

 

        var result = GetEnumDescription(enumeration);

        return nullIfNotExists ? null : result;

    }

 

    public static bool HasValue(this Enum enumeration)

    {

        if (enumeration == null)

        {

            return false;

        }

 

        var type = enumeration.GetType();

        // ReSharper disable once CheckForReferenceEqualityInstead.1

        if (type.Equals(null))

        {

            return false;

        }

 

        var fi = enumeration.GetType().GetField(enumeration.ToString());

        if (fi.Equals(null))

        {

            return false;

        }

 

        return true;

    }

}

 

Contract:

public class EnumEntry

{

    public int Id { get; set; }

    public string Name { get; set; }

    public string DisplayName { get; set; }

    public string Comment { get; set; }

}

Tests:

internal class EnumerationExtensionsSpecs{

    internal class EnumBase

    {

        protected enum DummyEnum

        {

            [Description("Desc1")]

            WithDescription = 1,

 

            WithoutDescription = 2

        }

 

        protected enum DummyEnum2

        {

            [EnumComment("Comment1")]

            WithComment = 1,

 

            WithoutComment = 2

        }

 

        protected enum DummyEnum3

        {

            WithValue = 1,

 

            WithoutValue

        }

 

        protected enum DummyEnum4

        {

            [Description("DisplayName1")]

            [EnumComment("Comment1")]

            Value1 = 1,

 

            [Description("DisplayName2")]

            [EnumComment("Comment2")]

            Value2 = 2

        }

    }

 

    [Subject(typeof (EnumerationExtensions))]

    internal class Wenn_eine_Enum_2_Werte_besitzt_und_diese_aufgelistet_werden_sollen : EnumBase

    {

        private static IList<EnumEntry> _result;

 

        private Establish context = () => { };

 

        private Because of = () => { _result = (typeof (DummyEnum4)).GetEnumerationEntries(); };

 

        private It dann_ergeben_sich_daraus_2_Listenwerte = () => _result.Count.ShouldEqual(2);

 

        private It dann_werden_alle_Daten_von_Wert1_auf_den_Listeneintrag1_gemappt = () => (

                                                                                               _result.First().Id == 1

                                                                                               && _result.First().Name == "Value1"

                                                                                               && _result.First().DisplayName == "DisplayName1"

                                                                                               && _result.First().Comment == "Comment1"

                                                                                           )

                                                                                               .ShouldBeTrue();

 

        private It dann_werden_alle_Daten_von_Wert2_auf_den_Listeneintrag2_gemappt = () => (

                                                                                               _result.Last().Id == 2

                                                                                               && _result.Last().Name == "Value2"

                                                                                               && _result.Last().DisplayName == "DisplayName2"

                                                                                               && _result.Last().Comment == "Comment2"

                                                                                           )

                                                                                               .ShouldBeTrue();

    }

 

    [Subject(typeof (EnumerationExtensions))]

    internal class When_an_Enum_is_decorated_with_a_description_and_null_if_emtpy_is_requested : EnumBase

    {

        private static string _result;

 

        private Establish context = () => { };

 

        private Because of = () => { _result = DummyEnum.WithDescription.GetEnumDescriptionIfExists(); };

 

        private It should_resolve_the_description_text = () => _result.ShouldEqual("Desc1");

    }

 

    [Subject(typeof (EnumerationExtensions))]

    internal class When_an_Enum_is_not_decorated_with_a_description_and_null_if_emtpy_is_requested : EnumBase

    {

        private static string _result;

 

        private Establish context = () => { };

 

        private Because of = () => { _result = DummyEnum.WithoutDescription.GetEnumDescriptionIfExists(); };

 

        private It should_resolve_null = () => _result.ShouldBeNull();

    }

 

    [Subject(typeof (EnumerationExtensions))]

    internal class When_an_Enum_is_decorated_with_a_description_and_name_if_empty_is_requested : EnumBase

    {

        private static string _result;

 

        private Establish context = () => { };

 

        private Because of = () => { _result = DummyEnum.WithDescription.GetEnumDescription(); };

 

        private It should_resolve_the_description_text = () => _result.ShouldEqual("Desc1");

    }

 

    [Subject(typeof (EnumerationExtensions))]

    internal class When_an_Enum_is_not_decorated_with_a_description_and_name_if_empty_is_requested : EnumBase

    {

        private static string _result;

 

        private Establish context = () => { };

 

        private Because of = () => { _result = DummyEnum.WithoutDescription.GetEnumDescription(); };

 

        private It should_return_the_name_of_the_enum_value = () => _result.ShouldEqual("WithoutDescription");

    }

 

    [Subject(typeof (EnumerationExtensions))]

    internal class When_an_Enum_is_decorated_with_a_comment_and_name_if_empty_is_requested : EnumBase

    {

        private static string _result;

 

        private Establish context = () => { };

 

        private Because of = () => { _result = DummyEnum2.WithComment.GetEnumComment(); };

 

        private It should_return_the_name_of_the_enum_value = () => _result.ShouldEqual("Comment1");

    }

 

    [Subject(typeof (EnumerationExtensions))]

    internal class When_an_Enum_is_not_decorated_with_a_comment_and_name_if_empty_is_requested : EnumBase

    {

        private static string _result;

 

        private Establish context = () => { };

 

        private Because of = () => { _result = DummyEnum2.WithoutComment.GetEnumComment(); };

 

        private It should_return_the_name_of_the_enum_value = () => _result.ShouldEqual("WithoutComment");

    }

 

    [Subject(typeof (EnumerationExtensions))]

    internal class When_an_Enum_is_decorated_with_a_comment_and_null_if_empty_is_requested : EnumBase

    {

        private static string _result;

 

        private Establish context = () => { };

 

        private Because of = () => { _result = DummyEnum2.WithComment.GetEnumCommentIfExists(); };

 

        private It should_resolve_the_description_text = () => _result.ShouldEqual("Comment1");

    }

 

    [Subject(typeof (EnumerationExtensions))]

    internal class When_an_Enum_is_not_decorated_with_a_description_and_null_if_empty_is_requested : EnumBase

    {

        private static string _result;

 

        private Establish context = () => { };

 

        private Because of = () => { _result = DummyEnum2.WithoutComment.GetEnumCommentIfExists(); };

 

        private It should_return_the_name_of_the_enum_value = () => _result.ShouldBeNull();

    }

 

    [Subject(typeof (EnumerationExtensions))]

    internal class When_an_Enum_has_a_value : EnumBase

    {

        private static bool _result;

 

        private Establish context = () => { };

 

        private Because of = () => { _result = DummyEnum3.WithValue.HasValue(); };

 

        private It should_return_true = () => _result.ShouldBeTrue();

    }

 

    [Subject(typeof (EnumerationExtensions))]

    internal class When_an_Enum_has_no_value : EnumBase

    {

        private static bool _result;

 

        private Establish context = () => { };

 

        private Because of = () =>

                             {

                                 DummyEnum3? d3 = null;

                                 _result = d3.HasValue();

                             };

 

        private It should_return_false = () => _result.ShouldBeFalse();

    }

 

    internal class When_Enum_is_not_decorated_with_FlagsAttribute

    {

        private static TestEnum_MissingFlagAttribute MyEnum;

 

        private Because of = () => { MyEnum = TestEnum_MissingFlagAttribute.Val2 | TestEnum_MissingFlagAttribute.Val3; };

 

        private It should_return_False1 = () => MyEnum.ByteIsSet(TestEnum_MissingFlagAttribute.Val1).ShouldBeFalse();

 

        private It should_return_False2 = () => MyEnum.ByteIsSet(TestEnum_MissingFlagAttribute.Val2).ShouldBeFalse();

 

        private It should_return_False3 = () => MyEnum.ByteIsSet(TestEnum_MissingFlagAttribute.Val3).ShouldBeFalse();

 

        private enum TestEnum_MissingFlagAttribute

        {

            Val1,

            Val2,

            Val3

        }

    }

 

    internal class When_Enum_is_compared_with_wrong_Enum_type

    {

        private static TestEnum1 MyEnum1;

 

        private Because of = () => { MyEnum1 = TestEnum1.Val2 | TestEnum1.Val3; };

 

        private It should_return_False1 = () => MyEnum1.ByteIsSet(TestEnum2.Val1).ShouldBeFalse();

 

        private It should_return_False2 = () => MyEnum1.ByteIsSet(TestEnum2.Val2).ShouldBeFalse();

 

        private It should_return_False3 = () => MyEnum1.ByteIsSet(TestEnum2.Val3).ShouldBeFalse();

 

        [Flags]

        private enum TestEnum1

        {

            Val1 = 0x01,

            Val2 = 0x02,

            Val3 = 0x04

        }

 

        [Flags]

        private enum TestEnum2

        {

            Val1 = 0x01,

            Val2 = 0x02,

            Val3 = 0x04

        }

    }

 

    internal class When_Enum_contains_enum_value

    {

        private static TestEnum MyEnum;

 

        private Because of = () => { MyEnum = TestEnum.Val2 | TestEnum.Val3; };

 

        private It should_return_False_for_val1 = () => MyEnum.ByteIsSet(TestEnum.Val1).ShouldBeFalse();

 

        private It should_return_True_for_val2 = () => MyEnum.ByteIsSet(TestEnum.Val2).ShouldBeTrue();

 

        private It should_return_True_for_val3 = () => MyEnum.ByteIsSet(TestEnum.Val3).ShouldBeTrue();

 

        [Flags]

        private enum TestEnum

        {

            Val1 = 0x01,

            Val2 = 0x02,

            Val3 = 0x04

        }

    }

}

Meine tägliche Portion Git

Here are some Git Aliases of mine. Just insert them in the "[alias]” section into your global .gitconfig, usually placed in your home directory.

   1: review = log -1 --patch

   2: unstage = reset head

   3: aa = add --all

   4: au = add --update

   5: s = status

   6: p = pull

   7: l = log --oneline -10

   8: k = !gitk --all & --all &

   9: aua = !git add --update && git commit --amend --reuse-message=HEAD

  10: aaa = !git add --all && git commit --amend --reuse-message=HEAD

  11: amend = commit --amend --reuse-message=HEAD

  12: aac = !sh -c 'git add --all && git commit -m \"$1\"' -

  13: aucp = !sh -c 'git add --update && git commit -m \"$1\" && git push' -

  14: aacp = !sh -c 'git add --all && git commit -m \"$1\" && git push' -

From now on, you can type in your git bash

git aacp “commit message”

in order to add all, commit and push your respository.

Castle Windsor – Handy Ruse Part III

In this blog entry I published code for an IoC Initializer. The following container Integration Test tries to create an instance of each registered service that is not of type IAmNotTestable. Definitely an Integration Tests that every application needs!

Integration Test of the container using Machine.Specifications as UnitTesting Framework:

   1: using System;

   2: using System.Diagnostics;

   3: using System.Linq;

   4: using Castle.MicroKernel;

   5: using Castle.Windsor;

   6: using comWORK.Contracts;

   7: using comWORK.Infrastructure.IoC;

   8: using Machine.Specifications;

   9: using Machine.Specifications.Utility;

  10:  

  11: namespace UAR.IntegrationTests

  12: {

  13:     public abstract class ContainerSpecs

  14:     {

  15:         protected static IWindsorContainer CreateContainer()

  16:         {

  17:             return new IoCInitializer()

  18:                     .RegisterComponents()

  19:                     .Container;

  20:         }

  21:     }

  22:  

  23:     [Subject("Container Specs")]

  24:     public class When_the_application_starts_up : ContainerSpecs

  25:     {

  26:         static IHandler[] _handlers;

  27:         static IWindsorContainer _container;

  28:  

  29:         Establish context = () => { _container = CreateContainer(); };

  30:  

  31:         Because of = () => { _handlers = _container.Kernel.GetAssignableHandlers(typeof(object)); };

  32:  

  33:         Cleanup after = () => _container.Dispose();

  34:  

  35:         It should_be_able_to_create_an_instance_of_each_registered_service =

  36:             () => _handlers

  37:                       .Where(

  38:                           handler =>

  39:                           handler.ComponentModel.Implementation.GetInterfaces().Contains(typeof(IAmNotTestable)) == false)

  40:                       .Each(handler => handler.ComponentModel.Services

  41:                                            .Each(service =>

  42:                                            {

  43:                                                Debug.WriteLine(String.Format("{0}: {1}/{2}",

  44:                                                                              handler.ComponentModel.Name,

  45:                                                                              service.Name,

  46:                                                                              handler.ComponentModel.Implementation.Name));

  47:  

  48:                                                if (service.ContainsGenericParameters)

  49:                                                {

  50:                                                    service.GetGenericArguments()

  51:                                                        .Each(argument => argument.GetGenericParameterConstraints()

  52:                                                                              .Each(

  53:                                                                                  constraint =>

  54:                                                                                  _container.Resolve(service.MakeGenericType(constraint))));

  55:                                                }

  56:                                                else

  57:                                                {

  58:                                                    _container.Resolve(service);

  59:                                                }

  60:                                            }));

  61:     }

  62: }

Implementation of IAmNotTestable

   1: public interface IAmNotTestable{}

Notice: I will publish a new version soon that addresses some open problems that i don’t want to mention here.

Castle Windsor – Handy Ruse Part II

In every application you have to initialize the container as part of the bootstrapping process. I moved the bootstrapping logic into a seperate assembly. Here’s the IoC part as fluent API. The code registers all implementations of IWindsorInstaller contained in the folder of the executing assembly. I also have a method “RunStartupConfiguration” that executes the start-method of all components which implement the interface. This could be useful for configuration reason for example.

Implementation of IoCInitializer

   1: public class IoCInitializer : IDisposable

   2: {

   3:     public IWindsorContainer Container { get; private set; }

   4:  

   5:     public IoCInitializer()

   6:     {

   7:         Container = new WindsorContainer();

   8:     }

   9:  

  10:     public void Dispose()

  11:     {

  12:         if (Container != null)

  13:         {

  14:             Container.Dispose();

  15:             Container = null;

  16:         }

  17:     }

  18:  

  19:     public IoCInitializer RegisterComponents()

  20:     {

  21:         var appDomainDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

  22:         var foundAssemblies = FromAssembly.InDirectory(new AssemblyFilter(appDomainDirectory));

  23:  

  24:         Container.Install(foundAssemblies);

  25:  

  26:         return this;

  27:     }

  28:  

  29:     public IoCInitializer RunStartupConfiguration()

  30:     {

  31:         Container

  32:             .ResolveAll<IStartupTask>()

  33:             .ToList()

  34:             .ForEach(x => x.Start());

  35:         return this;

  36:     }

  37: }

 

Implementation of IStartupTask:

   1: public interface IStartupTask

   2: {

   3:     void Start();

   4: }

 

You can call this in your bootstrapping logic this way:

   1: Container = new IoC.IoCInitializer()

   2:     .RegisterComponents()

   3:     .RunStartupConfiguration()

   4:     .Container;

 

Be careful, the container and class modifiers are public! Instead you should make it internal and integrate it into the assembly that is responsible for bootstrapping.

Castle Windsor – Handy Ruse Part I

Today I want to share some implementations that I use every once in a while:

Scenario 1: You have an assembly that contains all WinForm controls or perhaps ViewModel classes instead. You don’t want to adapt your installer again and again, if you create new controls respectively new ViewModels.

The following snippet shows an Installer that registers all ViewModels in a WPF assembly of mine. Of course I need to decorate my ViewModels with an special interface, in this case IAmViewModel:

   1: public class Installer : IWindsorInstaller

   2: {

   3:     public void Install(IWindsorContainer container, IConfigurationStore store)

   4:     {

   5:         container.Register(Components().ToArray());

   6:     }

   7:  

   8:     private static IEnumerable<IRegistration> Components()

   9:     {

  10:         yield return Classes.FromThisAssembly()

  11:             .BasedOn<IAmViewModel>()

  12:             .WithServiceSelf()

  13:             .LifestyleTransient();

  14:     }

  15: }

You can afford the same for WinForms. You don’t even have to create an interface:

   1: private static IEnumerable<IRegistration> Components()

   2: {

   3:     yield return Classes.FromThisAssembly()

   4:         .BasedOn<Form>()

   5:         .WithServiceSelf()

   6:         .LifestyleTransient();

   7: }

 

In some little (!) cases it can be useful to inject the container itself into an object. For that reason you can register the container in itself:

   1: Container.Register(

   2:     Component.For<IWindsorContainer>().Instance(Container)

   3: );

Castle Windsor – Forwarding

As I just noticed, since v3.0 there is a new useful possibility for registering multiple services by one component. Take a look at this page.

   1: Component.For<IFoo, IBar>().ImplementedBy<FooBar>();

You want a sample?

   1: yield return Component

   2:     .For<ICalculateOrderProposals, IShowOrderProposals>()

   3:     .ImplementedBy<ArticleOrderProposals>()

   4:     .LifestyleSingleton();

I wanted to seperate the concerns “calculate order proposals” and “show order proposals” in two interfaces in order have more transparency and directness in the consuming components. But because of cohesion i wanted to implement this in one class.

Nice work guys!

Entity Framework – Nullable Bug

As I experienced today, there’s a bug in the Entity Framework. Let’s have a look at the following scenario:

Screenshot 1

image

 

Screenshot 2

image

 

In Screenshot 1 you can see a table with two datetime columns. One is marked as nullable whereas the other is not. I used Database First approach to generate the Entity Data Model. Screenshot 2 shows you the auto-generated Entity. Take a look at the following properties:

imageimage

Notice the highlighted setting “Nullable” of the generated property “MyNullableDateTime”: It’s none instead of what it should be – true. Nevertheless, the generated code is all fine:

   1: [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]

   2: [DataMemberAttribute()]

   3: public Nullable<global::System.DateTime> MyNullableDateTime

   4: {

   5:     get

   6:     {

   7:         return _MyNullableDateTime;

   8:     }

   9:     set

  10:     {

  11:         OnMyNullableDateTimeChanging(value);

  12:         ReportPropertyChanging("MyNullableDateTime");

  13:         _MyNullableDateTime = StructuralObject.SetValidValue(value);

  14:         ReportPropertyChanged("MyNullableDateTime");

  15:         OnMyNullableDateTimeChanged();

  16:     }

  17: }

  18: private Nullable<global::System.DateTime> _MyNullableDateTime;

Unfortunately, if you change the column in the database to be no longer nullable and furthermore, you refresh your model, this will cause a build error:

>>Error 3031: Problem in mapping fragments starting at line 51:Non-nullable column >>DateTimeTest.MyNullableDateTime in table DateTimeTest is mapped to a nullable entity property.

Accessing Git without VPN/LAN connection

Setting up your Git repository while you’re in your company domain will bring up some trouble because the connection string is stored in your config. Follow these steps:

  • Navigate into the invisible directory “.git” of your repository
  • Open the “config”-File with notepad
  • Search for “[remote "origin"]”
  • Change the value of “URL”

For example, in my case it was git@ci:comwork which works fine, if i have VPN access. If i want to sychronate over the internet, i need to use git@repository.heco.de:comwork.git (notice: the suffix .git is optional; replace repository.heco.de with your address).

Visual Studio 2012 x64

There won’t be a x64 version:

“[…] We plan to continue with this approach of reducing overall resource utilization for the remainder of the product cycle, and will not be investing in an x64 version of Visual Studio at this time.”

Nathan Halstead
Visual Studio Program Manager

Source: http://goo.gl/svmM0

FakeItEasy and Castle.Core conflict

Hey guys, i want to point a FakeItEasy problem out to you. If you use the most current version of Castle.Windsor 3.0.* you will run into an assembly conflict with FakeItEasy as FIE has a dependency on Castle.Core 2.5.*. There is a simple workaround: Don’t use NuGet to install FIE instead download it manually. The download is an ILmerged assembly!

You can find more informations in the according issue.

Adding a new developer to your Git Repository

First of all, this is just a walkthrough for Windows!

 

1. Download and install Git. I prefer the installation without msysGit

image

2. Install Git. Make sure you have admin rights (for example if you’re using the UAC). Here are my recommended settings:

 

image

image

image

 

3. Setup your git config. You should set at least the following two configuration settings:

git config -–global user.name “your name”

git config -–global user.email “your email”

You have to enter this commands in the Git Bash! After finishing, there should be a “.gitconfig” file in your user directory.

image

Here are some recommendations of mine. Feel free to just copy and paste it:

[alias]
    review = log -1 –patch
    unstage = reset head
    aa = add –all
    au = add –update
    s = status
    p = pull
    l = log –oneline -10
    k = !gitk –all & –all &
    aua = !git add –update && git commit –amend –reuse-message=HEAD
    aaa = !git add –all && git commit –amend –reuse-message=HEAD
    amend = commit –amend –reuse-message=HEAD
    aucp = !sh -c ‚git add –update && git commit -m \"$1\" && git push‘ –
        aacp = !sh -c ‚git add –all && git commit -m \"$1\" && git push‘ –
[branch]
    autosetupmerge = true
    autosetuprebase = always
[color]
    ui = auto
    wtf = true
[color "diff"]
    old = bold red
    new = bold green
    meta = bold yellow
[color "branch"]
    current = black green
    local = bold green
    remote = yellow
    plain = bold yellow
[color "status"]
    added = bold red
    changed = bold green
    untracked = bold cyan
    nobranch = red reverse
[color "interactive"]
    prompt = bold green
    error = bold red

4. Generate the RSA Keys by entering the following command in the bash shell:

ssh-keygen –C “your name” –t rsa –v

Be careful: Don’t enter a filename as it won’t generate the needed .ssh directory in your user dir! Read more in this article.

image

If the operation was successful, you will find the private and public keys in your user directory in the invisible direcotry “.ssh”. It’s important that the filenames are “id_rsa” and “id_rsa.pub” because Git is using by convetion these files to access the server.

5. Copy the “known_hosts” file from a co-worker and put it into your .ssh directory.

6. Add your public key to the remote git server. In my case, i have a local copy of the gitolite-admin directory on the server.  So all i have to do is adding the new public key to the “keydir” directory and edit the “gitolite.conf” file in the “conf” directory:

 

image

7. Create a local copy of the development repository:

git clone git@ci:WebDevelopment.git

WebDevelpment.git is the name of the repository and ci is the server name. Make sure you are in the directory where you want to create the clone!

 

8. Some more references

http://help.github.com/win-set-up-git/

http://kylecordes.com/2008/git-windows-go

 

9. Think about using symbolic links for the “.ssh” dir and the “.gitconfig” file. You can use the mklink command from windows. I use this way to sync all my machines.

Fake Implementation of IDbSet

   1: public class FakeDbSet<T> : IDbSet<T> where T:class 

   2:  {

   3:      readonly HashSet<T> _set;

   4:      private readonly IQueryable<T> _queryableSet; 

   5:  

   6:      public FakeDbSet()

   7:      {

   8:          _set = new HashSet<T>();

   9:          _queryableSet = _set.AsQueryable();

  10:      } 

  11:  

  12:      public IEnumerator<T> GetEnumerator()

  13:      {

  14:          return _set.GetEnumerator();

  15:      }

  16:  

  17:      IEnumerator IEnumerable.GetEnumerator()

  18:      {

  19:          return GetEnumerator();

  20:      }

  21:  

  22:      public Expression Expression

  23:      {

  24:          get { return _queryableSet.Expression; }

  25:      }

  26:  

  27:      public Type ElementType

  28:      {

  29:          get { return _queryableSet.GetType(); }

  30:      }

  31:  

  32:      public IQueryProvider Provider

  33:      {

  34:          get { return _queryableSet.Provider; }

  35:      }

  36:  

  37:      public T Find(params object[] keyValues)

  38:      {

  39:          throw new NotImplementedException();

  40:      }

  41:  

  42:      public T Add(T entity)

  43:      {

  44:          _set.Add(entity);

  45:          return entity;

  46:      }

  47:  

  48:      public T Remove(T entity)

  49:      {

  50:          _set.Remove(entity);

  51:          return entity;

  52:      }

  53:  

  54:      public T Attach(T entity)

  55:      {

  56:          _set.Add(entity);

  57:          return entity;

  58:      }

  59:  

  60:      public T Create()

  61:      {

  62:          throw new NotImplementedException();

  63:      }

  64:  

  65:      public TDerivedEntity Create<TDerivedEntity>() where TDerivedEntity : class, T

  66:      {

  67:          throw new NotImplementedException();

  68:      }

  69:  

  70:      public ObservableCollection<T> Local

  71:      {

  72:          get { throw new NotImplementedException(); }

  73:      }

  74:  }

Smart overriding of the SaveChanges-Method of the EntityFramework

 

As part of our refactoring of the persistence layer implemented with the Entity Framework, we developed an approach for some tricky problems. Although i just discuss one specific scenario, the following solution is probably useful for many different issues:

We are using some objects which won’t be deleted in the classic way by removing them from the underlying database table. Instead, we mark them as deleted, set the purge date and the user who initiated the action. The same procedure exists for creating and modifing objects. You surely can imagine why we are doing this. So how can we achieve this behaviour in a transparent, implicit manner.

Step 1: Set up some interfaces like IHaveCreationDate, IHavePurgeDate and IHaveModificationDate.

   1: public interface IHavePurgeDate

   2: {

   3:     void SetPurgeDate();

   4: }

 

Step 2: Now it depends on your engineering strategy: Code First, Model First or Database First. According to your strategy you might using POCOs or you don’t. First of all, you can implement this solution in every single case, but you might change a little of the implementation. Here’s the way like we are using it with our POCOs (take a look at the ADO.NET Team Blog about the usage of POCOs) automatically generated by the EF:

Auto generated code:

   1: public partial class Worker

   2: {

   3:     public int ID_Bearbeiter { get; set; }

   4:     //some properties

   5:     public int deleted_from { get; set; }

   6:     public Nullable<System.DateTime> purge_date { get; set; }

   7:     public bool isDeleted { get; set; }

   8: }

 

Second part of the partial worker implementation in a separate file (don’t adapt the auto generated class!)

   1: public partial class worker : IHavePurgeDate 

   2: {

   3:     public void SetPurgeDate()

   4:     {

   5:         isDeleted = true;

   6:         purge_Date = DateTime.Now;

   7:         deleted_from = currentUser.ID;

   8:     }

   9: }

If you use Code First engineering, you won’t need a seperate file – of course!

 

Step 3: Build your own context or extend the existing one

If you use the auto generated context of the EF, you will have to create one more partial class to extend this context. If you use you’re own implementation, you can add the following code directly to your class:

   1: public override int SaveChanges()

   2: {

   3:     HandleEntries(ChangeTracker.Entries().ToList());

   4:     return base.SaveChanges();

   5: }

   6:  

   7: internal void HandleEntries(IList<DbEntityEntry> entries)

   8: {

   9:     HandleModifiedEntries(entries);

  10:  

  11:     HandleDeletedEntries(entries);

  12:  

  13:     HandleAddedEntries(entries);

  14: }

  15:  

  16: internal void HandleAddedEntries(IEnumerable<DbEntityEntry> entries)

  17: {

  18:     var createdEntities = entries

  19:         .Where(e => e.State == EntityState.Added)

  20:         .Where(e => e.Entity is IHaveCreationDate)

  21:         .ToList();

  22:  

  23:  

  24:     foreach (var dbEntityEntry in createdEntities)

  25:     {

  26:         ((IHaveCreationDate) dbEntityEntry.Entity).SetCreationDate();

  27:     }

  28: }

  29:  

  30: internal void HandleDeletedEntries(IEnumerable<DbEntityEntry> entries)

  31: {

  32:     var deletedEntities = entries

  33:         .Where(e => e.State == EntityState.Deleted)

  34:         .Where(e => e.Entity is IHavePurgeDate)

  35:         .ToList();

  36:  

  37:     foreach (var dbEntityEntry in deletedEntities)

  38:     {

  39:         ((IHavePurgeDate) dbEntityEntry.Entity).SetPurgeDate();

  40:         dbEntityEntry.State = EntityState.Modified;

  41:     }

  42: }

  43:  

  44: internal void HandleModifiedEntries(IEnumerable<DbEntityEntry> entries)

  45: {

  46:     var modifiedEntities = entries

  47:         .Where(e => e.State == EntityState.Modified)

  48:         .Where(e => e.Entity is IHaveModificationDate)

  49:         .ToList();

  50:  

  51:     foreach (var dbEntityEntry in modifiedEntities)

  52:     {

  53:         ((IHaveModificationDate) dbEntityEntry.Entity).SetModificationDate();

  54:     }

  55: }

 

That’s all. Be aware of two more things:

  • This code sample works with a DbContext of EF 4.1, but you can also use the ObjectStateManager of the ObjectContext in EF 1.0/4.0.
  • The order of handling modification and creating/deletion depends on your intended use.

Database First Walkthrough with Entity Framework 4.0

This is just a step by step walkthrough for the database approach with the Entity Framework 4.0, which means that i am using the “old” ObjectContext instead of the “new” EF 4.1 DbContext.

Create a new Console Project

image

 

Add a new Item to your project. Take the “ADO.NET Entity Data Model” template. Choose your prefered name. In my case i take myheco because i want to create an model for a database called myheco.

image

 

Choose “Generate from database” in the upcoming window

image

 

Next, choose your connection. In my example, i decide to save the connection settings in the app.config with the name “myhecoEntities”. This will be name for your context in your code if you don’t create your own implementation of the ObjectContext!

image

 

Choose your tables, views and stored Procedures you want to use and set your prefered options

image

 

Take a look at the Solution. It should look like this

image

 

Let’s try to use our OR-Mapper with LINQ-To-Entities

   1: static void Main(string[] args)

   2: {

   3:     using (var context = new myhecoEntities())

   4:     {

   5:         var item = (from users in context.Users

   6:                     where users.Name.StartsWith("Uli")

   7:                     select users).FirstOrDefault();

   8:  

   9:         if (item != null) Console.WriteLine(item.Name);

  10:     }

  11:  

  12:     Console.ReadKey();

  13: }

 

image

 

If you make changes to your Database Schema, you’ll need to update your model. You can do this by opening the Entity Data Model file (edmx) with a double click. Right click on an empty space and choose “Update Model from Database”

image

 

Choose the “Refresh”-Tab on the upcoming dialog and press “Finish”.

image

Now it depends on your database changes you’ve made if your solution still compiles.

Using an IoC-Container right

I noticed that some people don’t use their IoC-Container in the manner they should to. They inject the container into their objects like this:

   1: public class Foo : IFoo

   2: {

   3:     private IContainer _container;

   4:  

   5:     public Foo(IContainer container) {

   6:         _container = container;

   7:     }

   8:  

   9:     public Boo GetBooForFoo(int id) {

  10:         var boo = _container.Resolve<IMyService>().GetBooById(id);

  11:         return boo;

  12:     }

  13: }

A friend of mine (Web Developer) uses the same approach (not with an IoC but an array) in PHP: He injects an array that contains every dependency. When i asked him why he is doing this that way, he told me that he doesn’t want his API to change when he needs more dependencies.

So why is this a bad decision:

  • Fail Fast Principle: If the requested service IMyService in line 10 is not found, it will raise an Exception (for example an ComponentNotFoundException). In this scenario that’s no fracture of the leg but what if you would have executed some important changes before? You shouldn’t be able call a method without having the a valid starting point. It’s much better and cleaner to get an exception when you instantiating the object Foo.
  • Keep in mind why you are using an container: You want to implement the Inversion of Control principle. It’s not your call that should be in control, it’s your container. It’s paradox to use an IoC-Container when you develop your code to annul the basic principle behind. Another point is that you have a hard coded dependency to a specific container implementation so you’re not able to switch you IoC-Container.
  • And my last consideration is about the benefit that you’re api won’t change: Don’t hide dependencies! If you’re not the only developer that works with that code, you will get big problems because you change the components behaviour without getting errors. A developer that uses this component is wondering why his program is not working correctly any longer. Or – and that would be really upsetting – the calling component works in some cases and in some cases not for example if line 10 would be in a switch statement.

Too make a long story short: Here’s my approach

   1: public class Foo : IFoo

   2: {

   3:     private IMyService _myService;

   4:     

   5:     public Foo(IMyService myService) {

   6:         //you might want to do a null check

   7:         //what's not necessary if you unit tested your IoC right

   8:         _myService = myService

   9:     }

  10:  

  11:     //you should know what to do now

  12: }

Inversion of Control and Entity Framework

Today i want to show you my approach to resolve the requested entity framework object context at runtime. Starting point:

  • First, i want to have just one implementation of an IUnitOfWork to resolve any kind of repository like Repository<Order>
  • Second, my unit of work should autodiscover the proper context for my requested type of domain model as i have different databases and object contexts. For example, Order is a domain object of my domain model (namespace Domain.ComWork) according to the context ‘comwork’, which is mapping to the database ‘comwork’. There’s another domain object like Customer in my domain model (namespace Domain.MyHeco) according to the context ‘myheco’, which is mapping to the database ‘myheco’.

So how can i achieve this? I will use an IoC container like Castle.Windsor. You can add it to your Visual Studio project by the nuget command “install-package Castle.Windsor”. I want to mention that this scenario needs a little bit of advanced IoC techniques because the dependent component has to be resolved at runtime. So you’re not able to register a dedicated component for an interface. Instead you’ve got to use a facility. Allright, so we tell the container that we will register a facility:

   1: container.AddFacility<TypedFactoryFacility>();

 

In line 1 we tell the container that it has to load the necessary infrastructure for facilities. Let’s take a look at the registration process. Here’s my method that will return me an IEnumerable of IRegistration.

   1: static IEnumerable<IRegistration> Components()

   2: {

   3:     yield return Component

   4:         .For<IContextFactory>()

   5:         .AsFactory(c => c.SelectedWith<ContextFactoryHandlerSelector>());

   6:     yield return Component

   7:         .For<ContextFactoryHandlerSelector>();

   8:     yield return Component

   9:         .For<IUnitOfWork>()

  10:         .ImplementedBy<UnitOfWork>();

  11:     yield return Component

  12:       .For<ComWorkContext>()

  13:       .Named("comworkcontext");

  14:     yield return Component

  15:       .For<MyHecoContext>()

  16:       .Named("myhecocontext");

  17: }

 

Here’s the good news: Castle Windsor has an out of the box feature that creates you the needed factory. In other words: The container creates automatically the factory. You’re code is unaware of the container. Take a look at this article. If you want to use this you’ve have to follow some conventions. In my approach i decided to develop my own implementation to follow my own convetions. Take a look at line 5.  With “.AsFactory” i tell the container that i don’t register a concrete implementation for that service (IContextFactory). If i would follow the conventions of Castle.Windsor calling AsFactory() would be enough.

Here’s the code for my own implementation of a TypedFactoryComponentSelector (this would be auto generated by using just AsFactory without parameters):

   1: public class ContextFactoryHandlerSelector : ITypedFactoryComponentSelector

   2: {

   3:     public TypedFactoryComponent SelectComponent(MethodInfo method, 

   4:         Type type, object[] arguments)

   5:     {

   6:         var requestFor = method.GetGenericArguments().First();

   7:         

   8:         var @namespace = string.Format("{0}context", 

   9:             requestFor.Namespace.ToLower()

  10:             .Replace("domain.",""));

  11:         

  12:         return new TypedFactoryComponent(@namespace, method.ReturnType, null);

  13:     }

  14: }

 

My convention is pretty simple: The name of my object context is the same as the namespace of my model without the string “domain.” and with “context” appended.

Sample: Full name of my domain object: “domain.comwork.order”

  • use just the namespace –> domain.comwork
  • replace domain –> comwork
  • add context –> comworkcontext

I have two kind of domain models (domain.comwork and domain.myheco) so i need two contexts (comworkcontext and myhecocontext). Every context is registered:

   1: yield return Component

   2:   .For<ComWorkContext>()

   3:   .Named("comworkcontext");

   4: yield return Component

   5:   .For<MyHecoContext>()

   6:   .Named("myhecocontext");

 

Now we’ve got it: We have a facility that invokes a call to my self implemented factory if a service (defined in the interface IContextFactory) is requested. The factory returns the name of the needed context at runtime. My Interface looks like this:

   1: public interface IContextFactory

   2: {

   3:     ObjectContext GetContextFor<T>();

   4: }

And here’s the generic part. If i call GetContextFor<domain.comwork.order> i will get my comworkcontext. If i call GetContextFor<domain.myheco.customer> i will get my myhecocontext.

The last step is to inject the factory in my UnitOfWork. Nothing easier than that:

   1: public class UnitOfWork : IUnitOfWork

   2: {

   3:     private readonly IContextFactory _factory;

   4:  

   5:     public UnitOfWork(IContextFactory factory)

   6:     {

   7:         _factory = factory;

   8:     }

   9:  

  10:     //here you would return an IRepository<T>

  11:     //this is just a sample code

  12:     public void GetRepository<T>() where T : class 

  13:     {

  14:         Console.WriteLine(_factory.GetContextFor<T>().GetContextName());

  15:     }

  16: }

 

And how can i resolve my concrete UnitOfWork in my program?

   1: static class Program

   2: {

   3:     static void Main(string[] args)

   4:     {

   5:             using (var container = new WindsorContainer())

   6:             {

   7:                 container.AddFacility<TypedFactoryFacility>();

   8:                 container.Register(Components().ToArray());

   9:  

10: container.Resolve<IUnitOfWork>()

.GetRepository<Domain.ComWork.Foo>();

11: container.Resolve<IUnitOfWork>()

.GetRepository<Domain.MyHeco.Bar>();

  12:             }

  13:     }

  14:  

  15:     static IEnumerable<IRegistration> Components()

  16:     {

  17:         //Registrations...

  18:     }

  19: }

How to test static code: Sample with the DateTime-Object

Static Methods are everywhere, especially if the code is from Microsoft. How you work this?

Make an interface with an instance method/member, make a class that implementes the interface an within this instance you can call the static stuff.

Example: The DateTime-object has the member Now, so if you call DateTime.Now, you will get the current time. Unfortunately, can’t test time relevant actions like how long took a print job this way.

First: Declare the interface (VB.NET Code):

   1: Public Interface IClock

   2:     ReadOnly Property Now As DateTime

   3: End Interface

 

Second: Implement it (C# Code):

   1: public class SystemClock : IClock

   2: {

   3:     public DateTime Now

   4:     {

   5:         get { return DateTime.Now; }

   6:     }

   7: }

 

With Fake It Easy you can create a mock like this:

   1: A.Fake<IClock>();

 

Important: Don’t forget to register this in your IoC-Container respectively inject the SystemClock-Object into your object/method that used the DateTime.Now earlier.

Fake It Easy–don’t forget about limiting factors

Today i want to talk about a feature of Fake It Easy that you can need in many cases:

If you have a method that retrieves you job ids that can be processed by the calling method (e.g. a print service with a job id provider that observes the database for new jobs). In my case, if there is no job, the method returns –1. But there are some circumstances in which my providers also returns –1 for example when i stopped my provider (in case of multithreading) or when an expected exception occurs (when the database is down).

So i don’t want to talk about how clean this code is if it acts like the way i told you, instead i want to make clear that this are two kinds of tests you’ve got to write:

  • Case 1: There is no next job in the database
  • Case 2: Any other cases with the same return value but another meaning/behaviour inside your method

The extension methods ‘MustHaveHappened’ and ‘MustNotHaveHappened’ are your friends:

   1: It should_not_query_for_the_next_print_job_id =

   2:     () => A

   3:             .CallTo( () => _dbConversation.Query(A<NextWaitingPrintJob>

   4:             .That.Not.IsNull()))

   5:             .MustNotHaveHappened();

   6:  

   7: It should_return_the_default_job_id = () => _jobId.ShouldEqual(_fakeId);

If you’re wondering about the syntax (It should_…), so take a look here: MSpec

To quote ‘Barney’ from ‘How i met your mother’: “It’s awesome!”

The code above shows the solution for case 2: Though the second assert ensures that the return value is the default value, the first assert is the important one as it guarantees me that there was no read operation on the database

If i want to indicate case 1, i just have to rewrite line 5 into “.MustHaveHappened()”.

%d Bloggern gefällt das: