Sharpoverride

The road to becomming a good programmer is paved with bad scripts


News

Windows Mobile 6.5 is out

 

Hello, this is the 6th part of the IoC Containers series. This is the last container I’ll explore. I’ve been using it at work because it’s got the “Made by Microsoft” insignia and it seems the policy is that anything done at Microsoft is good for use. Bet that happens to you also.

I’ve downloaded what I hope is the latest version from codeplex.

Our Bootstrapper code is now

public class Bootstrap
    {
        public static IUnityContainer Components()
        {
            IUnityContainer container = new UnityContainer();
            container.RegisterType<IClearScreen,
                ConsoleClearScreen>(
                 new ContainerControlledLifetimeManager());
            container.RegisterType<IWriteString,
                ConsoleWriteString>(
                 new ContainerControlledLifetimeManager() );

            container.RegisterType<IFunctionState,
                AlarmFunctionState>("Alarm");
            container.RegisterType<IFunctionState,
                NewLineFunctionState>("NewLine");
            container.RegisterType<IFunctionState,
                CalculatorFunctionState>("Calculator");

            container.RegisterType<IConsoleInputService,
                ConsoleInputServiceImpl>( 
                 new ContainerControlledLifetimeManager()    );

            return container;
            
        }
    }

The ContainerControllerLifetimeManager is Microsoft’s way of saying this is a singleton instance. If we don’t specify nothing then a new instance will be created always.

The service retrieve through a simple call to container.Resolve<TInstance>.

The container also supports xml configuration.

Next we’ll se how our App.config file looks like

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
    </configSections>
    
    <unity>
        <typeAliases>
            <!-- Lifetime manager types -->
            <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
        </typeAliases>
        <containers>
            <container>
                <types>
                    <type
                        type="IoCContainers.Components.Services.IWriteString, IoCContainersUnity"
                        mapTo="IoCContainers.Components.Services.ConsoleWriteString, IoCContainersUnity">
                        <lifetime type="singleton" />
                        
                    </type>
                    <type
                        type="IoCContainers.Components.Services.IClearScreen, IoCContainersUnity"
                        mapTo="IoCContainers.Components.Services.ConsoleClearScreen, IoCContainersUnity">
                        <lifetime type="singleton" />

                    </type>
                    
                    <type name="Alarm"
                        type="IoCContainers.Components.Functions.IFunctionState, IoCContainersUnity"
                        mapTo="IoCContainers.Components.Functions.AlarmFunctionState, IoCContainersUnity" />

                    <type name="NewLine"
                        type="IoCContainers.Components.Functions.IFunctionState, IoCContainersUnity"
                        mapTo="IoCContainers.Components.Functions.NewLineFunctionState, IoCContainersUnity"/>

                    <type name="Calculator"
                        type="IoCContainers.Components.Functions.IFunctionState, IoCContainersUnity"
                        mapTo="IoCContainers.Components.Functions.CalculatorFunctionState, IoCContainersUnity"/>
                    
                    <type
                        type="IoCContainers.Components.Services.IConsoleInputService, IoCContainersUnity"
                        mapTo="IoCContainers.Components.Services.ConsoleInputServiceImpl, IoCContainersUnity">
                        <lifetime type="singleton" />
                        <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,Microsoft.Practices.Unity.Configuration">
                            <constructor>
                                <param name="functionStates" parameterType="IoCContainers.Components.Functions.IFunctionState[], IoCContainersUnity">
                                    <array>
                                        <dependency name="Alarm"/>
                                        <dependency name="NewLine"/>
                                        <dependency name="Calculator"/>
                                    </array>
                                </param>
                            </constructor>
                        </typeConfig>
                        </type>
                </types>
            </container>
        </containers>                
    </unity>
</configuration>

You won’t escape that easy though, you still need to tell the bootstraper to configure the container like this

IUnityContainer container = new UnityContainer();
            
            UnityConfigurationSection section = (UnityConfigurationSection)
                ConfigurationManager.GetSection( "unity" );
            section.Containers.Default.Configure( container );

Hope this is usefull. This is the final IoC Container I wanted to explore with you reader, in the next article I’ll try to lay out some general feelings about this containers.

The code can be donwloaded from codeplex.


 

I blogged a while ago about creating a series of posts on building an ASP.NET MVC application. To be honest I had already built one. It took me three months. And I haven’t touched it for about two months, so I thought at least I can share it with you geek readers.

The main difference between MVC in Rails and MVC in ASP.NET is that Rails generates the infrastructure from the commands you type, as for the ASP.NET MVC part you are responsible for building the infrastructure.

What do I mean when I say infrastructure? Well basically all the plumbing that goes into accessing the database, talking to services, generating rss content etc.

What is Universum? It’s meant to be a community web site where teachers and students can collaborate. And it’s a basic framework on which you can develop applications that are based on article publishing. I am only interested in sharing the code with you, if it helps you good, if not.. well no harm no fowl.

That’s about all the talk, if you have the time please review it and tell me if it can walk the walk.

The application provides simple management for blogs, resources, questions, courses. There are areas where I could improve it, but I no longer have the time.

A bit of info on the database. I decided to use Db4objects. It was pretty nice to tell you the truth, but I hope the Repository pattern I found and used is good enough to accommodate different implementations.

User roles. If you are not authenticated then you are considered an anonymous user and don’t have access to nothing except the main page.

An authenticated user can be – one special user that can register students and teachers, a student or a teacher.

Determining if a user is a student or a teacher is done via regular expression ( that’s how student names are configured at my faculty ). The implementation is easy to change however so that is not a problem.

Indexing articles is done through Lucene.NET. I have to say I had a lot of problems with it, and I’m not sure I solved them all.

Not much testing, there was no time. Usually I have confidence in my coding style, and I tried getting as many things in as possible in a short amount of time.

The project was built as part of my bachelor degree, and I have to admit I whished I didn’t do so much, since in the end it didn’t even matter, 20 minutes to rate three months of work is hard to fit.

If enough people find it interesting I’ll blog about the parts of the application some more, until then download the source code from codeplex, and log in with secretary / asdf1234qwer. In the web.config you can set up the paths the project requires on disk, the sample uses C:\Universum. Also I recommend having IIS7.


 

I have to say this is the part I hate the most: MODELING.

In preparation for the series of blog post I want to write that will cover building a simple 3d game I started downloading different free tools to help me build simple models.

Blender 3D although nice ( it even runs on a remote connection if you can believe that :D ) was and will probably continue to be too much for me to learn.

Truespace 7.6 Still beautifull and free but a bit too much, although I would love to learn it.

And SoftImage XSI Mod Tool that I kind’a like.

Until I learn one of those tools, and get a basic game going.. here’s a quickstart for you at http://blogs.msdn.com/dawate/archive/2008/02/05/building-a-3d-game-in-xna-from-scratch-free-video-tutorial-series-now-available.aspx


 

Hi, nice to have you read this again. This is part 4 of the series I’m doing on the existing .Net IoC Containers that I found interesting. After a brief introduction of what is an IoC in my option, I presented Autofac,,StructureMap and Ninject2.

In this post we’ll be exploring the Spring.NET IoC container. This is a xml configurable IoC by design. I’m using the latest version of it Spring.NET 1.3 RC1, hopefully it’s stable enough and that it brings something new to the table, by new I mean it uses the .NET 3.5 capabilities.

You can get the latest version of Spring.NET from http://www.springframework.net/. You will probably have to complete some kind of a registration form. I know I did.

Before you read any further I have to warn you that Spring.NET is a beast in the sense that is hard to configure and I don’t recommend using it.

Just as you would have done in Java once you get the configuration part out of the way it gets easier to use this framework. There is however a gotcha, after you get a valid IApplicationContext you are forced to use “magic strings” in your program to get to certain registered instances. You could probably define your own wrapper over the default registry methods, but that’s something you should explore on your own.

Let’s see how everything worked out. First I got the instance of the IApplicationContext using the line below:

IApplicationContext appContext = ContextRegistry.GetContext("spring.root");

I also configured the App.config file like so:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="spring">
            <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" />

            <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
        </sectionGroup>
    </configSections>

    <spring>
        <context>
            <resource uri="config://spring/objects" />
        </context>
        <objects xmlns="http://www.springframework.net">
            <description>Definitions of objects to be exported.</description>
            <object id="WriteString"
                type="IoCContainers.Components.Services.ConsoleWriteString, IoCContainersSpringNET" />
            <object id="ClearScreen"
                type="IoCContainers.Components.Services.ConsoleClearScreen, IoCContainersSpringNET" />

            <object id="Alarm"
                type="IoCContainers.Components.Functions.AlarmFunctionState, IoCContainersSpringNET" >
                <constructor-arg name="clearScreen">
                    <ref object="ClearScreen"/>
                </constructor-arg>
                <constructor-arg name="writerString">
                    <ref object="WriteString"/>
                </constructor-arg>
            </object>
            <object id="NewLine"
                type="IoCContainers.Components.Functions.NewLineFunctionState, IoCContainersSpringNET" >
                <constructor-arg name="clearScreen">
                    <ref object="ClearScreen"/>
                </constructor-arg>
                <constructor-arg name="writeString">
                    <ref object="WriteString"/>
                </constructor-arg>
            </object>
            <object id="Calculator"
                type="IoCContainers.Components.Functions.CalculatorFunctionState, IoCContainersSpringNET" >
                <constructor-arg name="clearScreen">
                    <ref object="ClearScreen"/>
                </constructor-arg>
                <constructor-arg name="writeString">
                    <ref object="WriteString"/>
                </constructor-arg>
            </object>

            <object id="ConsoleInput"
            type="IoCContainers.Components.Services.ConsoleInputServiceImpl, IoCContainersSpringNET" >
                <constructor-arg name="functionStates">
                    <list>
                        <ref object="Alarm"/>
                        <ref object="NewLine"/>
                        <ref object="Calculator"/>
                    </list>
                </constructor-arg>
            </object>
            
        </objects>
        
    </spring>
</configuration>

Word of caution: The context part of the configuration is mandatory, it will through an error otherwise. The objects section however is referenced in the spring/context using the resource uri=”..” tag

Very disappointing to me was the fact that I had to use the IApplicationContext instance I got from the ContextRegistry like this to get my object instance:

var shortcutService = appContext.GetObject( "ConsoleInput" ) as IConsoleInputService;

One other thing I believe that by default the objects are configured using a Singleton behaviour. I didn’t use this library much outside the Java environment, and I have to say I like the .NET IoC’s that we’ve explored way better than this approach.

On the other hand there is a lot more to Spring than this, so as an enterprise middleware IoC Container it probably shines but that is for you to decide.

As always as posted the source code on codeplex and you can download it here.


 

I wanted to use Ninject 1.0 but I discovered that it didn’t support named binding, and didn’t know how to resolve multiple bindings to an array.

Luckily I found the Ninject 2 post it’s way better than the previous version, and the changes were almost a no brainer.

Hy, this continues the series of posts on IoC Containers in .NET. We are using these continers on a simple console application that autocompletes it’s functions. I’m mostly displaying the configuration part of the IoC, an overview of this tools will follow after we’ll have explored enough of them.

After a brief introduction of what is an IoC, I presented Autofac, and StructureMap.

In this post we’ll explore the Ninject 2 beta IoC that you can download at http://kohari.org/2009/02/25/ninject-2-reaches-beta/.

One thing that Ninject tries to do is free you from having to write an xml configuration file, that means it does not have support for such a configuration type, instead it comes with another nice fluent api.

What I do like about ninject it that it has support for .NET Compact Framework. I’m mentioning this because I had the occasion of writing an app for .NET CF and it helped me a lot. AFAIK this is the single IoC in .NET that has this support.

Instead of a container Ninject uses the notion of a kernel. Another difference is that it requires you to build modules, so I used the Bootstrap as a module, and the Components method returns the IKernel instance.

I didn’t explore the new Ninject deeply I was just happy I could get the application running.

So our Bootstrap class looks like this

public class Bootstrap : Module
    {
        public static IKernel Components()
        {
            IKernel kernel = new StandardKernel( new Bootstrap() );
            return kernel;
        }

        public override void Load()
        {
            Bind<IWriteString>()
                .To<ConsoleWriteString>()
                .InSingletonScope();
            Bind<IClearScreen>()
                .To<ConsoleClearScreen>()
                .InSingletonScope();

            Bind<IFunctionState>()
                .To<AlarmFunctionState>().Named("Alarm");
            Bind<IFunctionState>()
                .To<NewLineFunctionState>().Named("NewLine");
            Bind<IFunctionState>()
                .To<CalculatorFunctionState>().Named("Calculator");

            this.Bind<IConsoleInputService>().To<ConsoleInputServiceImpl>();

        }
    }

Don’t know about you but I like it. Obviously the way I get these values in the Program.cs changed as in the other posts but I didn’t expose that change.

Since Ninject doesn’t provide a Xml configuration you’re stuck with a codebase that nees to be recompiled, luckily that should not take to much.

As always the code can be downloaded here.


 

Hi, this is part 5 of our series on IoC containers in .NET. I’m only using them on a simple console application that provides autocompletion for the functions that the application exposes.

We started with an introductory article, then we used Autofac, StructureMap, Ninject 2 beta and Spring.NET.

In this article I’ll cover CastleWindsor a bit. These files can be found on sourceforge at the following address http://sourceforge.net/projects/castleproject/files/InversionOfControl/.

Like StructureMap it can be configured through code or from an xml configuration. I’ll first show the way to configure the app from code than I’ll go for the xml configuration option.

Using the configuration from code looks like this:

public class Bootstrap
    {
        
        public static IWindsorContainer Components()
        {
            WindsorContainer wc = new WindsorContainer();
            wc.AddComponentLifeStyle<IWriteString,
                ConsoleWriteString>( 
                 Castle.Core.LifestyleType.Singleton );
            wc.AddComponentLifeStyle<IClearScreen,
                ConsoleClearScreen>(
                 Castle.Core.LifestyleType.Singleton );

            wc.AddComponent<IFunctionState,
                AlarmFunctionState>();
            wc.AddComponent<IFunctionState,
                NewLineFunctionState>();
            wc.AddComponent<IFunctionState,
                CalculatorFunctionState>();            

            wc.AddComponentLifeStyle<IConsoleInputService,
                ConsoleInputServiceImpl>( 
                Castle.Core.LifestyleType.Singleton );
            return wc;            
        }
    }

As Jan Stenberg pointed out, there is a better way of configuring the container and it looks like this

WindsorContainer wc = new WindsorContainer();
            wc.Register( Component.For<IWriteString>()
                .ImplementedBy<ConsoleWriteString>()
                .LifeStyle.Singleton )
            .Register( Component.For<IClearScreen>()
                .ImplementedBy<ConsoleClearScreen>()
                .LifeStyle.Singleton )
            
            .Register(Component.For<IFunctionState>()
                .ImplementedBy<AlarmFunctionState>())
            .Register(Component.For<IFunctionState>()
                .ImplementedBy<NewLineFunctionState>())
            .Register(Component.For<IFunctionState>()
                .ImplementedBy<CalculatorFunctionState>())

            .Register(Component.For<IConsoleInputService>()
                .ImplementedBy<ConsoleInputServiceImpl>()            
                .LifeStyle.Singleton)
            ;

You get the container like so

var kernel = Bootstrap.Components();

And the thing I kind-a struggled with is that in order to construct my service I had to declare a dictionary

    var parameters = new Hashtable();
    parameters.Add( "functionStates",
    kernel.ResolveAll<IFunctionState>() );

And pass it in when I resolved the service

var shortcutService = kernel.Resolve<IConsoleInputService>(parameters);

The fact the you have to specify the parameters outside the bootstrapping is a small inconvenient but we can live with it.

The xml part is a bit more simple to comprehend an it’s what you’ll prefer to use in most applications.

Now the Bootstrap class looks like this

public class Bootstrap
    {        
        public static IWindsorContainer Components()
        {
            WindsorContainer wc = new WindsorContainer( new XmlInterpreter() );
            return wc;
                    
        }
    }

And we got the service resolution down to

var shortcutService = kernel.Resolve<IConsoleInputService>(  );
Niiice, isn’t it? As always the source can be found at this adress.

 

In our first part of the series we saw what Autofac had to offer us in order to get the simple console application that provides code completion capabilities.

In this part I’ll use StructureMap and we’ll see how this product does.

First let’s download it from http://sourceforge.net/projects/structuremap/files/. The latest version is StructureMap2.5.3.

StructureMap is configured through a static ObjectFactory class. Usually you end up creating such a global class yourself, at least it comes already bundled with it.

Because StructureMap uses the ObjectFactory class for initialization as well as object retrieval our Bootstrapper now looks like this.

 

public class Bootstrap
    {
        public static void Components()
        {
            ObjectFactory.Initialize( container =>
                {
                    container
                        .ForRequestedType<IClearScreen>()
                        .TheDefaultIsConcreteType<ConsoleClearScreen>()
                        .AsSingletons();
                    container
                        .ForRequestedType<IWriteString>()
                        .TheDefaultIsConcreteType<ConsoleWriteString>()
                        .AsSingletons();

                    container.ForRequestedType<IFunctionState>().AddConcreteType<AlarmFunctionState>();
                    container.ForRequestedType<IFunctionState>().AddConcreteType<NewLineFunctionState>();
                    container.ForRequestedType<IFunctionState>().AddConcreteType<CalculatorFunctionState>();

                    container.ForRequestedType<IConsoleInputService>().AsSingletons()
                        .TheDefault.Is.OfConcreteType<ConsoleInputServiceImpl>()
                        .WithCtorArg( "functionStates" ).EqualTo(
                            ObjectFactory.GetAllInstances<IFunctionState>()
                         );

                } );
        }
    }

On thing you will absolutely notice is that the way we configure it has changed, but it still uses a fluent interface for configuration. One other thing is that it nows to resolve registered instances into an array that can be injected with a constructor argument.

Next I’ll show the same Bootstrapper, but instead of defining it in code I’ll move the part I expect to change into an xml.

public class Bootstrap
    {
        public static void Components()
        {
            ObjectFactory.Initialize( container =>
                {
                    
                    //container
                    //    .ForRequestedType<IClearScreen>()
                    //    .TheDefaultIsConcreteType<ConsoleClearScreen>()
                    //    .AsSingletons();
                    //container
                    //    .ForRequestedType<IWriteString>()
                    //    .TheDefaultIsConcreteType<ConsoleWriteString>()
                    //    .AsSingletons();
                    
                    //container.ForRequestedType<IFunctionState>().AddConcreteType<AlarmFunctionState>();
                    //container.ForRequestedType<IFunctionState>().AddConcreteType<NewLineFunctionState>();
                    //container.ForRequestedType<IFunctionState>().AddConcreteType<CalculatorFunctionState>();

                    container.PullConfigurationFromAppConfig = true;                    

                    container.ForRequestedType<IConsoleInputService>().AsSingletons()
                        .TheDefault.Is.OfConcreteType<ConsoleInputServiceImpl>()
                        .WithCtorArg( "functionStates" ).EqualTo(
                            ObjectFactory.GetAllInstances<IFunctionState>()
                         );

                } );
        }
    }

The PullConfigurationFromAppConfig flag tells structure map to read the configuration file.

Caution: I had to move the IClearScreen and IWriteString to the config file as well since it doesn’t know how to configure the IFunctionState items otherwise.

For this simple example I used the App.config file, you can however configure everything in a StructureMap.xml located in the same directory you would normally put your App.config.

 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="StructureMap" type="StructureMap.Configuration.StructureMapConfigurationSection,StructureMap"/>
    </configSections>
    
    <StructureMap defaultAssembly="IoCContainers">    
        <DefaultInstance
                PluginType  ="IoCContainers.Components.Services.IWriteString, IoCContainersStructureMap"
                PluggedType ="IoCContainers.Components.Services.ConsoleWriteString, IoCContainersStructureMap"
                 Scope="Singleton"  />
        <DefaultInstance
                PluginType  ="IoCContainers.Components.Services.IClearScreen, IoCContainersStructureMap"
                PluggedType ="IoCContainers.Components.Services.ConsoleClearScreen, IoCContainersStructureMap"
                 Scope="Singleton"  />
                 
        <AddInstance Key="Alarm"
            PluginType  ="IoCContainers.Components.Functions.IFunctionState, IoCContainersStructureMap"
            PluggedType ="IoCContainers.Components.Functions.AlarmFunctionState, IoCContainersStructureMap"  />
        <AddInstance Key="NewLine"
            PluginType  ="IoCContainers.Components.Functions.IFunctionState, IoCContainersStructureMap"
            PluggedType ="IoCContainers.Components.Functions.NewLineFunctionState, IoCContainersStructureMap"  />
        <AddInstance Key="Computer"
            PluginType  ="IoCContainers.Components.Functions.IFunctionState, IoCContainersStructureMap"
            PluggedType ="IoCContainers.Components.Functions.CalculatorFunctionState, IoCContainersStructureMap"  />
        
    </StructureMap>
</configuration>

Now we can change values without recompiling the application, this however is error prone, and does not handle class renames to lightly. It’s not big of a deal if you think of it since you know you have it configured so when you rename a class you’ll know to go and rename values from the config file as well.

That was it for know, I’ll choose another IoC for our next post, the code you can get from here.


 

This is an interesting IoC project that I used in a couple of occasions, nothing big, but I sure enjoyed it immensely.

Autofac is wrist friendly so to speak and it tries to solve your configuration problems in a simple and concise manner.

Without further ado go at http://code.google.com/p/autofac/ to get the latest version.

Next I’ll try to create a simple example that I hope we’ll use for the most part of this series.

In learning the inner workings of IoC containers we’ll develop a console application that provides some simple autocomplete for it’s features.

The features of our application are:

  • Autocomplete for internal commands
  • Commands
    • Alert – displays a message box
    • NewLine – goes to the next line
    • Calculator – with support for add

All of this features will be organized under the Components folder as functions and services.

In general you will want the concrete classes to be linked to an interface, and is by default the way I like to handle it.

A lot of voices in the community are against the use of xml files for configuration, and to that regard Autofac offers the option of using a fluent interface for configuring the builder. Although good for contracts that you are not likely to change without recompiling the application, when you need to have functionality similar to that of a plug-in you will prefer to use an IoC capable of reading xml configuration. Obviously Autofac has support for xml files as well.

Note xml configuration support is very limited in Autofac, so I’ll only show the bootstraping for this file

As I said earlier an IoC is just a form of factory, the only real difference is that this is a factory with nice configuration capabilities.

In more complex applications I recommend you use modules for configuring but for this example is sufficient to have everything configured in only one place.

As a preference I always configure the IoC I’m using in a class called Bootstrap in my highest level module ( commonly identified as the assembly containing the Main function, or if in a web app the assembly that contains the Global.asax).

The code for the Bootstrap.cs looks like this:

public class Bootstrap
    {
        public static IContainer Components(){
            var builder = new ContainerBuilder();            
            
            builder.Register<ConsoleClearScreen>().As<IClearScreen>().SingletonScoped();
            builder.Register<ConsoleWriteString>().As<IWriteString>().SingletonScoped();
                        
            builder.Register<AlarmFunctionState>().As<IFunctionState>().Named( "AlarmFunctionState" );
            builder.Register<NewLineFunctionState>().As<IFunctionState>().Named( "NewLineTransition" );
            builder.Register<CalculatorFunctionState>().As<IFunctionState>().Named( "CalculatorTransition" );


            builder.Register<IConsoleInputService>(
                c => new ConsoleInputServiceImpl(
                    new IFunctionState[]{
                        c.Resolve<IFunctionState>("AlarmFunctionState"),
                        c.Resolve<IFunctionState>("NewLineTransition"),
                        c.Resolve<IFunctionState>("CalculatorTransition")
                    } ) );

            return builder.Build();
        }
    }

Autofac uses the ContainerBuilder class to register services and it offers a simple method of directly creating those services through the use of lambda expressions.

For the actual implementation of the app you can download the source code here.


 

Disclaimer: This is a series of posts in which we’ll go through the IoC’s that are used in today’s applications

The most simple answer I can give you is this:

It’s an abstraction over Factory Method.

It helps, in my opinion to think of this as a factory method, because then you know what to expect of it, since it constructs/resolves a specific implementation based on the configuration you provide it.

In a factory method you write, aka “hard code”, the implementation you will be using. In an IoC container you basically do the same except it’s easier to change, if you write it in the xml file since using it in code leaves you with what you started and never got to changing it.

However, an IoC has an additional plus over the hand coded factory, that is “It is able to construct objects  based on the configuration you supplied”.

Does it help ?

Oh yes it helps. There’s a principle in software that states “High level modules should not depend on low level modules, both should depend on abstractions”. And guess what the principle I just stated is the Dependecy Injection Principle, it is an important point to note since IoC containers are often referred  to as Dependency Injectors. So you will probably find the IoC/DI whenever reading about an IoC.

With the help of an IoC you can declare dependencies of you object using abstractions, usually in the form of interfaces and/or base classes.

In the next part will explore a couple of IoC’s that the .NET has to offer as well as from the outside of the .NET ecosistem.

I hope that by the end of this series we can form a summary of benefits and deduct some ground rules for choosing a certain IoC, or deciding if we need it.


 

Usually the style you organize code is just that A MATTER OF STYLE, in javascript however it’s not.

If by any chance you end up writing the following code:

 

var display = function() {
    this.x = 10;
    return
    {
        alert: function(message) {
            window.alert(message);
        }
    }
}

you might be in for a surprise but it won’t return anything because by default the javascript interpreter inserts ; after every line that doesn’t already contain it or }.

Instead you should write:

var display = function() {
    this.x = 10;
    return {
        alert: function(message) {
            window.alert(message);
        }
    }
}

More interesting notes you can find in the next video:

Hope you enjoyed this I sure did :D.


 

The individual features supported in this version (v1.0) of the library are:

  • Windows 7 Taskbar Jump Lists, Icon Overlay, Progress Bar, Tabbed Thumbnails, and Thumbnail Toolbars.
  • Windows 7 Libraries, Known Folders, non-file system containers.
  • Windows Shell Search API support, a hierarchy of Shell Namespace entities, and Drag and Drop functionality for Shell Objects.
  • Explorer Browser Control.
  • Shell property system.
  • Windows Vista and Windows 7 Common File Dialogs, including custom controls.
  • Windows Vista and Windows 7 Task Dialogs.
  • Direct3D 11.0, Direct3D 10.1/10.0, DXGI 1.0/1.1, Direct2D 1.0, DirectWrite, Windows Imaging Component (WIC) APIs. (DirectWrite and WIC have partial support)
  • Sensor Platform APIs
  • Extended Linguistic Services APIs
  • Power Management APIs
  • Application Restart and Recovery APIs
  • Network List Manager APIs
  • Command Link control and System defined Shell icons.

 

More details at : http://code.msdn.microsoft.com/WindowsAPICodePack and http://www.infoq.com/news/2009/08/WIndows-7-DotNET


 

Need to know: In your XNA game by default the framework tries to invoke the Update() method 60 times per frame and the Draw() method as many times as possible.

You can however change this behavior by changing the values of the static properties TargetElapsedTime and IsFixedTimeStep on the Game class and the SynchronizeWithVerticalRetrace property on the GraphicsDevice class.

In your game you can adjust the call to the Update() method like so

this.TargetElapsedTime = TimeSpan.FromSeconds(1.0f / 100.0f);

This tells the XNA framework to call your Update() method 100 times per second.

One other thing you can do is tell the framework to call the Update() method every time before the call to the Draw() method instead at regular intervals

this.IsFixedTimeStep = false;

In some cases you want to call the Draw() method at maximum intensity.

graphics.SynchronizeWithVerticalRetrace = false;

This could help you determine the maximum frame rate for your game

Note: If you instruct your game to call the Update() method 100 times per second it will try to do so at the expense of calling the Draw() method. So be very careful “With great power ..”


 

Disclaimer: This is the first in a series of post from which we'll learn the bare minimum needed to build games by using the XNA framework. The guide assumes you have a good grasp of the C# programming language and some good understanding of the .NET Framework ecosystem.

Before we do anything else we need to go to http://creators.xna.com/en-US/downloads. Here we'll download the XNA Game Studio 3.1.

Note: I have Microsoft Visual Studio Team Edition as part of the Microsoft Student partner program, for those of you using the Express edition of Microsoft Visual Studio some of the functionality may not exist. I apologize in advance and we can continue with the learning.

After download you should start the installer process that will copy all the necessary files to the directory that you specify during the initial steps of the installation.

After the installer finished we can go in our Microsoft Visual Studio environment and by clicking File > New > Project.. (default shortcut CTRL+SHIFT+N).

 

 

 

 

 

After you can select XNA Game Studio 3.1 from the Project types and click on the Windows Game (3.1) Template. Give it a name: XnaQuestPart1.

 

 

 

 

 

 

 

 

 

 

 

 

Note: The hardware you write games on, or test games is very important! I only have a laptop with a basic Intel Integrated Graphics Chipset that can process some pixel shaders and vertex shader 2.0. As a consequence the games will be limited to what I can render on this hardware.

You should be able to press the Debug button and have a simple Graphics context running.

The game project is organized like a basic Console/WinForms application. The only part that differs is the Contents folder.

 

In the Contents folder you can copy/paste or Add New/Existing Items of the following types

  • Images: .gif, .jpeg, .png, .dds
  • 3D models saved in Direct X Format  .x or Autodesk Format .fbx

We have the option of extending the pipeline that handles this files and import additional formats but that is for another post.

 

 

 

 

 

The interesting part we should explore next is the Game1.cs file that the template generated for us.

The game class in Game1.cs is divided into 2 sections:

  • Initialization
  • Handling

In the initialization phase the GraphicsDevice is instantiated and the root directory for the content is set.

In the override of the Initialize() method we'll be able to add extra code for the instances we want to instantiate.

Note: The game framework will also call the Initialize() method of all the registered game components at this stage. About game components we'll discuss a bit later.

In the LoadContent() method you will load images, textures, models etc. If you have some custom content that is not managed by the ContentManager than you'll have to dispose of it in the UnloadContent() method.

There are two types of handling. One deals exclusively with the game logic, and the other one exclusively with the Drawing.

The Update() method should host all the logic for updating the computation (or game) logic. Usually you will find the input logic and the impact it has on the other instances of the game.

The Draw() method should deal exclusively with the parts that render on the screen or send some data to the underlying graphics hardware system.

Note: By default the Update() method is invoked 60 times per frame, and the Draw() method is called as many times as possible per frame. It is something XNA does behind the scenes and you should keep that in mind.

Hope you enjoyed this post and be sure to leave a comment to keep me going about XNA if you  should find this useful. This series of posts are as much for me as they are for you on the quest of learning some XNA and basic game programming stuff.