Structure Map even cooler delayed resolving

December 3rd, 2012 No comments

Yesterday I wrote a post about nice feature of StructureMap that using no container specific syntax indicate that class dependency should be lazy resolved not construction time resolved. I showed it behaves reasonably when injected type is configured as a singleton.

Today when I was writing some dynamic container reconfiguration changing code (for QA testing purposes) I got concerned. What if such lazy loaded type mapping changes?

The question can be stated as unit test:

[Test]
public void LazyResolveReconfigured()
{
    ObjectFactory.Initialize(
        container =>
        {
            container.For<IFoo>().Use<Foo>();
            container.For<IBar>().Use<Bar>();
        });

    var foo = ObjectFactory.GetInstance<IFoo>();
    foo.DoSth();

    var anotherBar = new AnotherBar();
    ObjectFactory.Configure(container => container.For<IBar>().Use(anotherBar));

    foo.DoSth();
    Assert.IsTrue(anotherBar.DidSth);
}

We resolve IFoo implementation as previously. It depends on IBar, but lazily delivered. We then rewire our container to use AnotherBar for this interface and finally call the IFoo method that depends on the IBar. Would above test pass?

It will! Also if one change the mapping to be singleton like. You must make sure tough that you use Configure to further extend configuration. If you use Initialize then the unit test will fail. Apparently it loses information on the root type and “forgets” to re-wire it.

A quick peek into what exactly is being passed as Func<IBar> brought me to StructureMap.Pipeline.LazyInstance. Yet need to investigate it deeply, but in StructureMap source code I found quite a lot of different Instance implementations – EnumerableInstance in particular. This lead me to the following passing test:

[Test]
public void Enumrable()
{
    ObjectFactory.Initialize(
        container =>
            {
                container.For<ISomething>().Use<Something>();
                container.For<IBar>().Use<Bar>();
                container.For<IBar>().Use<AnotherBar>();
            });

    var something = ObjectFactory.GetInstance<ISomething>();
    Assert.AreEqual(2, something.BarCount);
}

public class Something : ISomething
{
    public Something(IEnumerable<IBar> somethings)
    {
        this.BarCount = somethings.Count();
    }

    public int BarCount
    {
        get; set; 
    }
}

The full example (including test cases from previous post) can be found on Gist. Definitely need to debug through StructureMap this weekend to understand this behavior better!

Categories: Software Tags:

Structure Map cool delayed resolving

December 2nd, 2012 No comments

It has been a while since I have wrote last time. Many topics should have been covered during this period for sure. I hope to get a chance describing them soon. But as I found a little while this evening, I decided to describe something interesting I recently run into.

I had to configure some DI container recently in a new project. The choice was Structure Map, as it happened to be the default one for most of our current projects. One piece I had to make resolving through the container was WCF service proxy. I added interceptors to it (via DynamicProxy) – one for authorization passing and the second one for automatic disposal after single method call. I did that many times in projects where WCF was being used as a facade to business logic server. However this time it was being used to integrate with third party and the calls where from within business logic, so I was quite sure I need to avoid direct service locator like calls to ObjectFactory.GetInstance there. On the other hand (due to above mentioned automated disposal) I had to make sure we get a fresh instance for each call, which is not so simply as one could imagine – proxy is being passed through constructor and the class dependent on it is meant to be singleton.

I was thinking how to redesign this for a while, but fortunately the wild idea got into my mind. What about putting Func<T> in constructor instead T directly? Surprisingly (at least to me) it worked!

The bellow, contrived example, shows two things. First that Structure Map will wire fabricating method for you when you ask for it explicitly by wrapping desired interface in Func. Secondly that still if one decides to make the interface you ask for Singleton it will take precedence over what you are asking for locally (you will still get Func<T> but it will be producing the same T instance on each call).

namespace StructureMapFun
{
    using System;

    using NUnit.Framework;

    using StructureMap;

    [TestFixture]
    public class StructureMapFunTest
    {
        public interface IFoo
        {
            void DoSth();

            void DoSthElse();
        }

        public interface IBar
        {
            void DoSth();
        }

        [Test]
        public void LazyResolve()
        {
            ObjectFactory.Initialize(
                container =>
                    {
                        container.For<IFoo>().Use<Foo>();
                        container.For<IBar>().Use<Bar>();
                    });

            var foo = ObjectFactory.GetInstance<IFoo>();
            foo.DoSth();
            foo.DoSthElse();
        }

        [Test]
        [ExpectedException(typeof(InvalidOperationException))]
        public void EnforceSingleton()
        {
            ObjectFactory.Initialize(
                container =>
                {
                    container.For<IFoo>().Use<Foo>();
                    container.For<IBar>().Singleton().Use<Bar>();
                });

            var foo = ObjectFactory.GetInstance<IFoo>();
            foo.DoSth();
            foo.DoSthElse();
        }


        public class Foo : IFoo
        {
            private readonly Func<IBar> barResolver;

            public Foo(Func<IBar> barResolver)
            {
                this.barResolver = barResolver;
            }

            public void DoSth()
            {
                this.barResolver().DoSth();
            }

            public void DoSthElse()
            {
                this.barResolver().DoSth();
            }
        }

        public class Bar : IBar, IDisposable
        {
            private bool disposed;

            public void DoSth()
            {
                if (this.disposed)
                {
                    throw new InvalidOperationException();
                }

                this.Dispose();
            }

            public void Dispose()
            {
                this.disposed = true;
            }
        }
    }
}

Categories: Software Tags:

Simplicity is the ultimate sophistication

August 7th, 2012 No comments

I don’t like cooking. Complex, bloated, time-consuming recipes are not for me. Simple, fast yet still surprising food is what I like best. OK – I can probably spend more time cooking than an average guy and still enjoy it. However I find the best revenue in the ultimate simplicity – the product itself, its taste. More basic, the more compelling. Bread. Structured, sweet and crispy. Cheese. Solid, grainy and salty. Pear jam. Sweet and a little sour, fruity and fuzzy. Basil, sharp, herbal and ethereal. Those together blend in a perfect match. Quality food when used leaves you thinking about it long enough after the last bite. And still it does not require endless transformation process in your kitchen. Just a few minutes are needed – pure fun – like in a fast food restaurants. But who things of a burger after leaving a restaurant?

Actors of this performance:
• Vandemoortele Venezia bread
polish Bursztyn cheese (if you haven’t tried it – you must do it – go and buy it immediately) from Spomlek
• St. Dalfour pear jam
Warmiak – polish dark unpasteurized beer from Kormoran brew house – the second dark beer in my top-list (the first one is Schwarzer Abt from Neuzeller Kloster Brau)
• fresh Basil
Saro Cosentinoones and zeros album

Categories: Cooking Tags:

Lightweight approach to project documentation

May 22nd, 2012 No comments

There are various documentation types you may want to create for a software project. Quite often I write deployment guides for administrators and technical guides for new developers, so they can learn system more efficiently. Till last project my default approach was to use Microsoft Word. It seems to make sense given specification is usually provided in such format. It is quite easy to edit and looks acceptable when printed out. However it comes with some issues in the package:

  • No source control repository support (diffs can be done but from Word itself not SVN or Git, hence it is hard to cooperate on)
  • WYSWYG nature can be distraction, what I want to focus on is the content not formatting
  • Requires license purchase for all team members in order to cooperate

On the other hand we have Wikipedia style of editing – it is something that I liked and appreciated since the very first article I updated there. Thanks to its plain text nature of the page source code it is easy to track and maintain (as you are not forced to take care of final visual rendering). As the format is plain text you can use your regular editor or IDE. In fact you can find quite a lot projects that use wikipedia-like mark down approach to maintain documentation – github being in particular on of the examples.

The tool that facilities all this and adds some useful features around the concept is AsciiDoc. I had a chance to use it in one of recent project and it worked really well (and yes, the rest of the team agrees on that). In this particular project the initial documentation stub has been created by me but then individual developers documented their code pieces design choices, which was a great help for me. Thanks do source control support collaboration was not a problem this time.

For the example document and its HTML rendering, please look into this post’s attachment. It also includes batch script to produce HTML output from the plain text definition. However before you are able to produce the output on your own you would need to proceed with the following installation steps (for Windows):

  • Install Python – http://www.python.org/ftp/python/2.7.2/python-2.7.2.msi
  • Install Graphviz (for diagrams) – http://www.graphviz.org/pub/graphviz/stable/windows/graphviz-2.28.0.msi
  • Install AsciiDoc – http://freefr.dl.sourceforge.net/project/asciidoc/asciidoc/8.6.6/asciidoc-8.6.6.zip
  • Install Easy Install (needed for synytax colouring pygments installation):
    • (32-bit) pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11.win32-py2.7.exe#md5=57e1e64f6b7c7f1d2eddfc9746bbaf20
    • (64-bit) Download http://peak.telecommunity.com/dist/ez_setup.py and execute “python ez_setup.py”
  • Obtain Pygments via `easy_install.exe pygments`
  • Make python (including main and Scripts folders) and graphviz binaries available by prepending their paths into PATH system environment variable.

Here are advantages of using such approach:

  • Straight forward syntax for document hierarchy ,tables, source code inclusion etc.
  • Easy to collaborate on thanks to direct support in source control systems
  • Ability to embed various pre-processors (like graphviz for diagrams and graphs)
  • Several output formats support (HTML, PDF, …)
  • Can be easily integrated with your continuous integration process

For further reading I encourage you too look into official user manual http://www.methods.co.nz/asciidoc/ (which on itself is written in AsciiDoc of course).

Attached Files:

  • zip ASCIIDoc example

    Example of ASCIIDoc formatted document, generation script and the result of the transformation to HTML.

Categories: Software Tags: ,

PowerShell V2 slow start-up time

March 20th, 2012 1 comment

While for sure PowerShell is a great tool that makes any developer life easier and more productive, I was not very fond of it due to quite long start-up time it has. One can argue that those 10-15 seconds (on my box) are perfectly OK for the value it provides but I was much more willing to execute Cygwin/Mingw bash shells or even just a simple command line prompt in the first place knowing it will be brought to me instantly.

However as it often happens the project I started working on already used PowerShell automation for several pieces I had to use on regular basis, so I decided to find out the solution to the above problem.

Quick search over the web showed that there is a known issue with V1 due to load of some dependencies for which native images has not been generated. V2 should though be free from this issue and this is the version that comes preinstalled with Windows 7 (BTW. who on earth decided to put V2 under %SystemRoot%\system32\WindowsPowerShell\v1.0 folder)? Also running the script provided under the above link confirms it won’t help here.

I was digging for the solution for reasonable while but found no description of the same issue I am experiencing. I was surprised. Doesn’t anyone have a problem with the long start-up? I asked couple of folks in my company and they observe similar behavior. Some of them directly some through NuGet console within Visual Studio that uses PowerShell internally.

Maybe this is only me that don’t accept waiting those extra couple of seconds per day… but if you don’t like this either there is really simple solution I come up with: as this is only on the first PowerShell “warm it” before the first chance you need to run it. There are many ways to implement this I chose the following one (as I translated from my native Windows language version there may be minor differences if you use English one).

  1. Go to task scheduler in Control Panel
  2. Create and task from action menu
  3. Name your task as you wish, mark it as hidden too
  4. In triggers tab choose “when logging in”
  5. In actions tab choose run new applicaton/script: %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe, with arguments:
    -Command ""
  6. In constraints uncheck the option to suppress execution when power cord is not connected.

Enjoy!

Categories: Software Tags:

Beware of InProc session state provider

August 25th, 2011 No comments

The short version is: forget about InProc use SessionState by default for both development and production ASP.NET environments.

This may be obvious for some of you, but till quite recently I was fooled myself. Even though I knew all the base facts, connecting them was not straight forward for me. Most probably because Microsoft decided to default to this provider. I guess they did it like that as it does not require any additional service running nor additional configuration.

The main problem with it is as it runs within your application domain you may lose session stored data due to regular administrative tasks (like modifying web.config or touching anything under bin) or even IIS itself may decide to restart application pool for you (when it sees memory usage is too high, or even on scheduled basis – in fact by default new app pool is configured to restart automatically every 1740 minutes).

The second issue is this particular provider is the only one built-in (and probably the only reasonable one at all) which:

  1. do not require your objects to be serializable
  2. gives you direct reference to the object when requesting it from session
  3. triggers Session_End event

All those differences may cause that switching to another provider won’t be trivial and may require application code rewrite. The first one is obvious. The second one is depicted with the following code snippet.

 
Session[‘s’] = new Student() { Name = ‘John’ };    
…
var john = Session[‘s’];
// with InProc the following line updates object instance on Session
john.Name = ‘Thomas’;  
// while in any other provider this line is required to achieve this
Session[‘s’] = john;      

Finally the last one can fool someone to relay on the mechanism, which won’t be supported on production and the expected code will silently fail to accomplish its job. For me the above differences make InProc session useless. It is obviously not well prepared for production use. As it differs significantly from the other session providers I find it useless for development as well.

I would say built-in StateServer should be used on developers’ boxes as default one. It will be already preinstalled as a service on your box if you have .NET environment. You only need to enable it (and probably configure it to start automatically) If needed on production it may be deployed as a separate node to be reused by several load balanced IIS boxes (without sticky session flag).

Categories: Software Tags:

DotNetMeeting.pl

March 6th, 2011 No comments

Local .NET passionates user-group is organizing community event called DotNetMeeting to be held in Torun, Poland on 26th March this year. The conference is intended to be yearly requiring event touching the most exiting new Microsoft stack related technologies out there. This year main topics are Windows Phone 7 mobile development platform and game development using XNA and CUDA frameworks. The conference team is working hard to get the best content for you. Thanks to our sponsors we will be able provide free lunch for all participants and many valuable prizes (including $19 worth prize for first 100 registered participants). The event won’t be able to take place without tremendous support from our local university CS department.

Having a chance to put some personal note here – I would like to thank all involved in organizing the conference and all those companies and organizations that support us. On the other side – I encourage you to participate in the conference. There is no entry fee but registration is required to join the event. All lectures will be conducted in polish. You can find more details (agenda, speakers bios and so on) on the conference site.

Categories: Software Tags:

Cystic fibrosis

February 27th, 2011 No comments

The 28/02-06/03 is nationwide cystic fibrosis week in Poland. There is no cure for this rare disease. While there are some treatments they are expensive and hard to get especially in Poland. MATIO foundation tries to help those suffering from this disease and they families by direct help but also spreading the knowledge about it. You can find more information on their site (in polish).

Attached Files:

Categories: Misc Tags:

Baking pizza

January 14th, 2011 No comments

I would like to share with you the best pizza recipe I’ve learnt so far. It comes from Peter Reinhart’s “The Bread Baker’s Apprentice” book. The recipe is also available on 101 Cookbooks blog (which is great by the way), hence I am not going to repeat it here.

Although this recipe is great it results with a dough that I am not comfortable with tossing. It seems to be too stretchy for this. Still as it ends up very good (crispy and tasty), so I don’t really bother and I just stretch it carefully on the counter and then gently transfer to the pizza blade.

For toppings less is more generally. But for cheeses I make the exception. I use up to 3 types of those mixed. Before putting into oven I sprinkle pizza with blue type cheese like Gorgonzola. After couple of minutes in the oven I add Mozzarella torn into small pieces. Once pizza is done I grate Parmigiano-Reggiano or another type of hard, aged cheese on top of it (I really encourage you to try polish aged cheese Bursztyn if you have such possibility). The time separation is crucial as each of those cheeses melts differently.

Categories: Cooking Tags:

Ciabbata bread baking

December 13th, 2010 2 comments

This was busy weekend. Searching Christmas gifts may be overwhelming. Yet I finally found some time to try a recipe from recently bought Peter Reinhart‘s book “The Bread Baker’s Apprentice“. This book is I awesome by the way, worth buying for its every page but  ”Deconstructing bread: The Tutorial” chapter especially. Finally I was able to go through theory of  the whole bread making process and learn a little bit of chemistry behind it. I highly recommend this book.

Back to the topic though. For the first bread formula I’ve chosen poolish based Ciabatta. Poolish is kind of dough pre-ferment, which enriches the taste and helps the final dough to develop better. Worth noting it is named is after Polish bakers, who are supposed to discover it around 1840. The formula for poolish is very simple (I’ve converted all units from ounces to grams and Fahrenheit degrees to Celsius ones for your convenience or inconvenience depending on where you live):

  • 319g unbleached bread flour (I used Manitoba)
  • 340g water at room temperature
  • 8.5g instant yeast

Mix all the ingredients until dough is smooth (it should be like thick pancake batter). Cover the bowl with plastic wrap and ferment at room temperature for 3-4h until bubbly and foamy. It can be used immediately (and this is how I proceeded) but it is recommended to refrigerate overnight to develop even more flavor.

Once you have the above accomplished, you can proceed to Ciabatta dough preparation.

You will need:

  • poolish from the above
  • 383g unbleached bread flour
  • 12.5g salt
  • 4.8g instant yeast
  • 85g – 170g of lukewarm water

If you refrigerated poolish keep it in room temperature for 1h before proceeding. Mix all the ingredients one by one starting with lower bound for water. Mix by hand for 5-7 minutes until smooth. If there is some flour left add some more water. Dough should be soft but remain sticky. Then move dough to the flour sprinkled counter. Stretch each one from both sides to double in length and then fold like letter to form initial rectangle again. Mist with some olive oil and loosely cover with plastic wrap (while still on the counter). Let it rest for half and hour and then apply the above procedure once more (including mist with an olive oil). Ferment on the counter for 1.5h – 2h. After that remove the wrap and divide the dough into 2-3 or more loaves depending on your bread size expectations. I used the half of the recipe ingredients and made 3 small loaves (or rather buns). Stretch and fold each one envelope style and sprinkle generously each one with left-over flour. Place on linen cloth folded in the way it provides some walls limiting dough from spreading. Mist top of the dough with olive oil. Keep at room temperature for 45-60 minutes. Preheat oven to 260 Celsius degrees with baking stone if you have one (if you don’t go buy one or use top-down flipped baking pan). Tug the dough a little bit and flatten it a bit if it is too high. Place the dough onto the baking stone. Pour 237g of hot water into steaming pan and close door immediately. After 30 seconds open the door and spray the walls of the oven with water (I am still looking for food-grade spay utility, so I just used hands dipped in cold water to mimic that, but of course this is not perfect, not even close). Repeat spraying twice more in 30 seconds intervals. After that lower oven temperature to 232 degrees and bake for 10 minutes. Rotate loaves 180 degrees and bake for another 5 minutes (recipe suggest 5-10 minutes, I used the upper boundary but it was to much in my case, loaves registered over 115 degrees inside, while 96 would be enough up to the recipe). Transfer the bread to the cooling rack (an improvised cooling rack as in my case would work as well). Let it cool and rest at least 45 minutes before slicing and serving.

I must say – the end result was above my expectations (I tried to bake bread a couple of times in the past but never managed to get proper crust and expected flavor). I couldn’t help myself from eating most of the first (small!) loaf by simply dipping it in some extra-virgin olive oil. I kept second one for the next day and refrigerated the last one. Instead refrigerating, once they feel a little stale, cut into thick slices, mist each one, both sides, with olive oil and then brown on grill pan. After that rub with garlic clove cut in half.

On the side note the above garlic grilled ciabatta reminds me of the great recipe for a tomato soup. I discovered a while ago after I ate similar (or even the same) soup in T.G.I. Friday’s. The recipe is thick and full of flavor from tomatoes and herbs. Feta is being used in this recipe instead of cream, which is brilliant combination. I strongly encourage you to try the recipe even if you don’t have much time for own ciabbata baking.

Categories: Cooking Tags: ,