DCSIMG
July 2008 - Posts - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2012 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

July 2008 - Posts

Using Unity Container Hierarchies

Using Unity Container Hierarchies

In Unity Application Blocktoday’s post I’m going to explain why and
how to use the Unity container hierarchies.
As the subject suggest Unity application block
supports nested containers and allow you to
build containers hierarchies.

Why to Use Nested Containers 
There are two reasons to use a nested containers:

  • Control the scope of singleton object instances.
  • Register different mapping for specific types.

Controlling the Scope of Singleton Object Instances 
Singleton objects lifetime is managed by the Unity container. They are
kept in scope as long as the container isn’t disposed. In order to enable the
existence of two separate sets of the objects with different lifetime you
use a container hierarchy and manage each set in a different child container
of the parent container. Just remember that if the parent container is disposed
all its children are disposed as well.
The following code demonstrate how to use child containers to manage the lifetime
of a singleton instance:

   IUnityContainer parentContainer = new UnityContainer();

   parentContainer.RegisterType<ILogger, FileLogger>

      (new ContainerControlledLifetimeManager());

   // Create nested child container in parent container

   IUnityContainer childContanier = parentContainer.CreateChildContainer();

   childContanier.RegisterType<Database, SqlDatabase>

      (new ContainerControlledLifetimeManager());

   // Get an instance of type stored in parent container

   ILogger logger = parentContainer.Resolve<ILogger>();

   // Get an instance of type stored in child container

   Database database = childContanier.Resolve<Database>();

   // Dispose child container

   childContanier.Dispose();

 

   // Dispose parent container

   parentContainer.Dispose();

In the example, after the creation of the database object you can either
use it and also use the logger object. After calling the Dispose method on the
child container you will be able to use only the logger object because
disposing the child container will end the lifetime of its generated objects.

Registering Different Mapping For Specific Types
Sometimes we have different dependency injection requirements for specific objects.
For example throughout the running application I want that ILogger will  be resolved
to FileLogger but in some rare situations I need it to be resolved into DatabaseLogger.
In such cases one solution for the problem can be the use of container hierarchies.
You do it by registering the general mapping in the parent container and registering
the specific mapping in the child container. After the registration faze you’ll call the
Resolve method of the relevant container when needed.
So, what is the gain of using this technique instead of only registering the types with
different names and resolving them by name?
We gain the ability to go up the container chain if the registered type isn’t located in
the child container. That means that if calling the Resolve method on the child container
won’t locate the type needed the child container will send the request to the parent
container to be resolved.
The following code is an example for registering of different mapping to specific types:

   IUnityContainer parentContainer = new UnityContainer();

   var child1 = parentContainer.CreateChildContainer();

   var child2 = parentContainer.CreateChildContainer();

   parentContainer.RegisterType<ILogger, FileLogger>

      (new ContainerControlledLifetimeManager());

   child2.RegisterType<ILogger, CustomLogger>

      (new ContainerControlledLifetimeManager());

   // will result in CustomLogger registered in 

   // child2 container

   var logger = child2.Resolve<ILogger>();

   logger.Log("Test");

   // will result in the FileLogger registered in the

   // parent container

   var logger2 = child1.Resolve<ILogger>();

   logger.Log("Test");

Summary
To sum up the post, the container hierarchy feature is very useful in the
following situations - control the scope of singleton object instances and
register different mapping for specific types. I showed examples of how
to use the container hierarchies in every one of these situations.


Working With Generic Types In Unity Configuration Section

Working With Generic Types In Unity Configuration Section

In my previous post about Unity Unity Application Block
discussed about configuration
files and how to configure Unity with
them. I got a question in the subject
of how to use generic types in the
configuration files. This post will
answer that question.

The Scenario
I have an interface of IValidator which receives a generic type T.

    public interface IValidator<T>

    {

        #region Methods

        void Validate<T>();

        #endregion

    }

Also, I have a class Validator which receives a generic type T and implement
the IValidator interface.

    public class Validator<T> : IValidator<T>

    {

        #region IValidator<T> Members

        public void Validate<T>()

        {

            // do something

        }

        #endregion

    }

Instead of registering them in code I want to write the mapping in the configuration file
How to do it?

The Configuration File
I return to the configuration file that I showed in the previous post. The only difference
is that I added a new type to map – the IValidator type. Also, I added a type alias to that
type. The configuration file:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <configSections>

    <section name="unity"

      type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,

      Microsoft.Practices.Unity.Configuration, Version=1.1.0.0,

      Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

  </configSections>

  <unity>

    <typeAliases>

      <!-- Lifetime manager types should be inserted

          if you need lifetime managers -->

      <typeAlias alias="singleton"

          type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,

            Microsoft.Practices.Unity" />

      <typeAlias alias="external"

          type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,

            Microsoft.Practices.Unity" />

      <!-- User defined type aliases -->

      <!-- An interface for logger implementation -->

      <typeAlias alias="ILogger"

          type="UnityExamples.Common.ILogger,

          UnityExamples.Common" />

      <!-- An abstarct class for database classes -->

      <typeAlias alias="Database"

          type="UnityExamples.Common.Database,

          UnityExamples.Common" />

      <typeAlias alias="IValidator`1"

          type="UnityExamples.Common.IValidator`1,

          UnityExamples.Common" />

    </typeAliases>

    <containers>

      <container>

        <types>

          <type type="ILogger"

                mapTo="UnityExamples.Common.FileLogger,

                UnityExamples.Common">

            <!-- Will be configured as singleton by the lifetime

                manager above -->

            <lifetime type="singleton" />

          </type>

          <type type="IValidator`1"

                mapTo="UnityExamples.Common.Validator`1,

                UnityExamples.Common">

            <!-- Will be configured as singleton by the lifetime

                manager above -->

            <lifetime type="singleton" />

          </type>

          <type type="Database"

                mapTo="UnityExamples.Common.CustomDatabase,

                UnityExamples.Common">

            <typeConfig

              extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,

                Microsoft.Practices.Unity.Configuration">

              <constructor>

                <param name="connString" parameterType="System.String">

                  <value value="connection value..."/>

                </param>

                <param name="logger" parameterType="ILogger">

                  <dependency />

                </param>

              </constructor>

            </typeConfig>

          </type>

        </types>

      </container>

    </containers>

  </unity>

</configuration>

As you can see in order to write a generic type I use the ` sign followed
by the number of generic types that the interface/class receives. In my
example the IValidator interface receives only one generic type and
therefore I use 1.

The Code To Run The Example
The following code will run the configuration file and map the IValidator
to the Validator class with a string input as the generic type the Validator
gets.

   IUnityContainer container = new UnityContainer();

   var section =

      (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

   section.Containers.Default.Configure(container);

   var validator = container.Resolve<IValidator<string>>();

Summary
Lets sum up the post, I showed an example of how to use a Unity
configuration section
with generic types. All you have to remember is the
` sign as the sign for a generic type in the configuration file

Mediator Pattern

Mediator Pattern

Today’s pattern in the design patterns series will describe the mediator pattern.
You can read my previous posts about design patterns here:
Structural patterns
Decorator pattern 
Proxy pattern
Facade pattern
Adapter pattern
Composite pattern
Bridge pattern
Flyweight pattern

Creational patterns
Singleton pattern
Abstract Factory pattern
Prototype pattern
Factory Method pattern
Builder pattern

Behavioral Patterns
Strategy pattern
Iterator pattern 
Template method pattern
Command pattern
Chain of responsibility pattern 

Mediator Pattern
The mediator pattern encapsulate the interaction between a set of objects.
Also it encapsulate the protocol between those objects. The pattern help 
to lose couple the object by keeping them from referring one each other.
 
Use Cases for the Mediator Pattern

You should use the pattern in the following cases:

  • Behavior that is distributed between some objects can be grouped
    or customized.
  • Object reuse is difficult because it communicates with other objects.
  • Objects in the system communicate in well-defined but complex ways.

UML Diagram 
Mediator Pattern  

Example in C#
The following code is an example of how to implement the pattern:

    #region Mediator

 

    public interface Mediator

    {

        #region Methods

 

        void Send(string message, Colleague colleague);

 

        #endregion

    }

 

    #endregion

 

    #region Concrete Mediator

 

    public class ConcreteMediator : Mediator

    {

        #region Properties

 

        public List<ConcreteColleague> Colleagues { get; private set; }

 

        #endregion

 

        #region Ctor

 

        public ConcreteMediator()

        {

            Colleagues = new List<ConcreteColleague>();

        }

 

        #endregion

 

        #region Mediator Members

 

        public void Send(string message, Colleague colleague)

        {

            foreach (Colleague currentColleague in Colleagues)

            {

                if (!currentColleague.Equals(colleague))

                {

                    currentColleague.Recieve(message);

                }

            }

        }

 

        #endregion

    }

 

    #endregion

 

    #region Colleague

 

    public abstract class Colleague

    {

        #region Members

 

        protected Mediator _mediator;

 

        #endregion

 

        #region Ctor

 

        public Colleague(Mediator mediator)

        {

            _mediator = mediator;

        }

 

        #endregion

 

        #region Methods

 

        /// <summary>

        /// Sends the given message

        /// </summary>

        /// <param name="message">The given message</param>

        public abstract void Send(string message);

 

        /// <summary>

        /// Recieves the given message

        /// </summary>

        /// <param name="message">The given message</param>

        public abstract void Recieve(string message);

 

        #endregion

    }

 

    #endregion

 

    #region Concrete Colleague

 

    public class ConcreteColleague : Colleague

    {

        #region Properties

 

        public int ID { get; set; }

 

        #endregion

 

        #region Ctor

 

        public ConcreteColleague(Mediator mediator, int id)

            : base(mediator)

        {

            ID = id;

        }

 

        #endregion

 

        #region Methods

 

        public override void Send(string message)

        {

            _mediator.Send(message, this);

        }

 

        public override void Recieve(string message)

        {

            Console.WriteLine("{0} recieved the message: {1}",

                ID, message);

        }

 

        #endregion

    }

 

    #endregion

As can be seen in the example, I have a mediator object that sends messages
to the concretes of the colleague class. The example is simple but it shows the
concepts that are used in the mediator pattern. With few modifications you
can use the example to build a small chat room application.
The following code was used to test the previous example:

   ConcreteMediator mediator = new ConcreteMediator();

 

   ConcreteColleague colleague1 = new ConcreteColleague(mediator, 1);

   ConcreteColleague colleague2 = new ConcreteColleague(mediator, 2);

 

   mediator.Colleagues.Add(colleague1);

   mediator.Colleagues.Add(colleague2);

 

   colleague1.Send("Hello from colleague 1");

   colleague2.Send("Hello from colleague 2");

 

   Console.Read();

Summary
To sum up the post, I explained the use of the mediator pattern.
When considering to use the mediator pattern you should always remember
that the patten has a performance impact. The performance impact is caused because every
communications pass through the mediator on the way to the
communicated object – which make the mediator a bottle neck in your system. If you don’t
want to use the pattern I suggest the facade pattern instead to wrap your subsystem.
The next pattern in the series will be the memento pattern.

Working With Configuration Files In Unity

Working With Configuration Files In Unity

In the previous posts about Unity I Unity Application Block
discussed basic concepts and
showed how to use Unity
in ASP.NET web forms. 
In this post I’m going to
show how to use Unity with configuration files.

The Unity Configuration Section
In order to start working with configuration files with Unity the first thing
to understand is the configuration section. Lets start with an example of
a Unity configuration section and then discuss the things that can be configure:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <configSections>

    <section name="unity"

      type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,

      Microsoft.Practices.Unity.Configuration, Version=1.1.0.0,

      Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

  </configSections>

  <unity>

    <typeAliases>

      <!-- Lifetime manager types should be inserted

          if you need lifetime managers -->

      <typeAlias alias="singleton"

          type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,

            Microsoft.Practices.Unity" />

      <typeAlias alias="external"

          type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,

            Microsoft.Practices.Unity" />

 

      <!-- User defined type aliases -->

      <!-- An interface for logger implementation -->

      <typeAlias alias="ILogger"

          type="UnityExamples.Common.ILogger,

          UnityExamples.Common" />

      <!-- An abstarct class for database classes -->

      <typeAlias alias="Database"

          type="UnityExamples.Common.Database,

          UnityExamples.Common" />

    </typeAliases>

    <containers>

      <container>

        <types>

          <type type="ILogger"

                mapTo="UnityExamples.Common.FileLogger,

                UnityExamples.Common">

            <!-- Will be configured as singleton by the lifetime

                manager above -->

            <lifetime type="singleton" />

          </type>

          <type type="Database"

                mapTo="UnityExamples.Common.CustomDatabase,

                UnityExamples.Common">

            <typeConfig

              extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,

                Microsoft.Practices.Unity.Configuration">

              <constructor>

                <param name="connString" parameterType="System.String">

                  <value value="connection value..."/>

                </param>

                <param name="logger" parameterType="ILogger">

                  <dependency />

                </param>

              </constructor>

            </typeConfig>

          </type>

        </types>

      </container>

    </containers>

  </unity>

</configuration>

TypeAliases Element
The first thing to notice is the typeAliases element that holds all the aliases
that you want to give to the type you are going to use with the Unity container.
It can reduce the code in the configuration section of the container itself instead
of using the long type definition. In the example above there are four typeAliases:
singleton, external, ILogger and Database. You can see the use of the aliases in
the container section itself.

Containers Element
The containers section is holding all the containers information that you need to
configure. You can have more than one type of container. The way to distinguish
between the containers is the name attribute that can be assigned to every container.
In the container you can define the types that will be injected in the the dependency
injection
process. Every type is mapped to another type by the mapTo attribute.
The mapTo attribute will inform the container that the registered type will map to the
type that was written in the attribute. Another thing that I show in the example is the
lifetime element of the type element. The lifetime element will instruct the
Unity container how the registered element will be constructed. In the example above
the FileLogger class will be constructed as a singleton.

TypeConfig Element
In the type element we can register a typeConfig element that can help us
to configure the injection to the constructor, method or properties of that type.
In my example I inject a connection string and a logger object to the
CustomDatabase object. The dependency element in the constructor parameter of
the logger instruct the Unity container that the element itself need to be injected with
the registered type of ILogger.

A Note
There are three more elements that can be configured inside the container element
which are instances, extensions and extensionConfig. I’m not going to discuss them
but you can read about them in the Unity documentation.

The Classes I Used in The Example
The abstract Database class:

    public abstract class Database

    {

    }

The CustomDatabase class:

    public class CustomDatabase : Database

    {

        #region Members

 

        private ILogger _logger;

        private string _strConnString;

 

        #endregion

 

        #region Ctor

 

        /// <summary>

        /// Construct a new CustomDatabase object

        /// </summary>

        public CustomDatabase(string connString, ILogger logger)

        {

            _logger = logger;

            _strConnString = connString;

        }

 

        #endregion

    }

The ILogger interface:

    public interface ILogger

    {

        #region Methods

 

        void Log(string message);

 

        #endregion

    }

The FileLogger class:

    public class FileLogger : ILogger

    {

        #region ILogger Members

 

        public void Log(string message)

        {

        }

 

        #endregion

    }

How To Plug The Configuration File To Unity
After a lot of configuration discussion you probably want to see some
real code of how to use the configuration section. The following code
will show you how to do it.

   IUnityContainer container = new UnityContainer();

 

   var section =

      (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

 

   section.Containers.Default.Configure(container);

 

   var database = container.Resolve<Database>();

   var logger = container.Resolve<ILogger>();

First build a new Unity container. Then get the configuration section of
Unity. The last thing to do is to use the Configure method of the relevant
container (in my example the default container) on the container object itself.
After the three steps you can use the container to inject the dependencies
to the types that were written in the configuration file by using the Resolve
method.

Summary
In today post I showed how to use configuration files in order to configure a
Unity container. I showed the main elements in the configuration file and also
showed a code of how to use it in an application. One last thing, the Unity
application block
was released as stand alone dll and also with enterprise library.
I would expected from the patterns & practices team to provide a designer to Unity
like in all the other application blocks. Maybe it will be in the next enterprise library
release…

Guiding a New ASP.NET Group

Guiding a New ASP.NET Group

Today I have started to guide a new ASP.NET group in SRL Group.
As I written in early post, I have guided an ASP.NET group last year.
All the trainees of the last group have succeeded to pass the 070-528
certification
and this is one of the goals for this group as well.
The main goal of the group is to help SRL employees to deeper learn the
basics of ASP.NET. In the meetings I try to give details and guidelines
of web development.

In today’s meeting I talked about the following subjects:

  • IIS internals in short.
  • Specialized web controls with short how to use examples –
    MultiView, Wizard and TreeView.
  • Page life cycle.

The next meeting will occur two weeks from now.

Chain Of Responsibility Pattern

Chain Of Responsibility Pattern

Today’s post will introduce the chain of responsibility pattern.
You can read my previous posts about design patterns here:
Structural patterns
Decorator pattern 
Proxy pattern
Facade pattern
Adapter pattern
Composite pattern
Bridge pattern
Flyweight pattern

Creational patterns
Singleton pattern
Abstract Factory pattern
Prototype pattern
Factory Method pattern
Builder pattern

Behavioral Patterns
Strategy pattern
Iterator pattern 
Template method pattern
Command pattern

Chain of Responsibility Pattern
The chain of responsibility pattern is a way of communication
between objects. As it’s name indicate a chain of handlers is built 
and every handler in the chain is responsible to handle the passing
request or deliver it to the next handler in the chain. In the end of
the process the request is handled with a default or exceptional behavior.
The pattern helps to reduce coupling by freeing the object from knowing
which handler will handle the request in the end.
 
Use Cases for the Chain of Responsibility Pattern
 
You should use the pattern in the following cases:

  • You have more than one object that may handle a request.
  • You have a scenario that you need to pass a request to
    one of several objects without specifying the receiver.
  • You have handlers of a request that should be specified
    dynamically.

UML Diagram 
Chain of Responsibility UML

Example in C#

    #region Abstract Handler Class

    public abstract class Handler

    {

        #region Properties

        /// <summary>

        /// The request limit that the current handler

        /// can process

        /// </summary>

        public int RequestLimit { get; private set; }

        /// <summary>

        /// The next handler in the chain

        /// </summary>

        public Handler NextHandler { get; private set; }

        #endregion

        #region Methods

        public abstract void HandleRequest(int request);

        #endregion

        #region Ctor

        public Handler(Handler handler, int requestLimit)

        {

            NextHandler = handler;

            RequestLimit = requestLimit;

        }

        #endregion

    }

    #endregion

    #region Concrete Handlers

    public class Worker : Handler

    {

        #region Ctor

        /// <summary>

        /// Construct a new worker object with

        /// the given handler

        /// </summary>

        /// <param name="handler">The given handler</param>

        public Worker(Handler handler)

            : base(handler, 10000)

        {

        }

        #endregion

        #region Methods

        public override void HandleRequest(int request)

        {

            if (request < RequestLimit)

            {

                Console.WriteLine("{0} handled a {1} request",

                    GetType().Name, request);

            }

            else

            {

                if (NextHandler != null)

                {

                    NextHandler.HandleRequest(request);

                }

            }

        }

        #endregion

    }

    public class Manager : Handler

    {

        #region Ctor

        /// <summary>

        /// Construct a new manager object with

        /// the given handler

        /// </summary>

        /// <param name="handler">The given handler</param>

        public Manager(Handler handler)

            : base(handler, 20000)

        {

        }

        #endregion

        #region Methods

        public override void HandleRequest(int request)

        {

            if (request < RequestLimit)

            {

                Console.WriteLine("{0} handled a {1} request",

                    GetType().Name, request);

            }

            else

            {

                if (NextHandler != null)

                {

                    NextHandler.HandleRequest(request);

                }

            }

        }

        #endregion

    }

    public class SeniorManager : Handler

    {

        #region Ctor

        /// <summary>

        /// Construct a new senior manager object with

        /// the given handler

        /// </summary>

        /// <param name="handler">The given handler</param>

        public SeniorManager(Handler handler)

            : base(handler, 50000)

        {

        }

        #endregion

        #region Methods

        public override void HandleRequest(int request)

        {

            if (request < RequestLimit)

            {

                Console.WriteLine("{0} handled a {1} request",

                    GetType().Name, request);

            }

            else

            {

                if (NextHandler != null)

                {

                    NextHandler.HandleRequest(request);

                }

            }

        }

        #endregion

    }

    #endregion

The example is simple. I have three types of workers: worker,
manager and a senior manager. Every worker type can handle request
that are lower than the request limit they have. Whenever a request
that is bigger than the request limit arrives the worker type deliver the
request to the next handler in the chain until there is no one who can
handle the request. The following example shows a use case of the example
classes:

    class Program

    {

        static void Main(string[] args)

        {

            // Setup Chain of Responsibility

            SeniorManager seniorManager = new SeniorManager(null);

            Manager manager = new Manager(seniorManager);

            Worker worker = new Worker(manager);

            // Run requests along the chain

            worker.HandleRequest(5000);

            worker.HandleRequest(15000);

            worker.HandleRequest(35000);

            Console.WriteLine();

            manager.HandleRequest(5000);

            manager.HandleRequest(15000);

            manager.HandleRequest(35000);

            Console.WriteLine();

            seniorManager.HandleRequest(5000);

            seniorManager.HandleRequest(15000);

            seniorManager.HandleRequest(35000);

            // Wait for user

            Console.Read();

        }

    }

Summary
To sum up the post, the chain of responsibility pattern isn’t
commonly used. Even so it’s very helpful if you want to send a
request along a chain of objects that may or may not handle the
request. In the next post in this series I’ll explain the mediator
pattern

ASP.NET Server Side State Management – Profile Properties

ASP.NET Server Side State Management – Profile Properties

Today it is the last post in the ASP.NET state management series.Profile Properties
In this post I’m going to describe the profile properties
technique. You can read my previous posts in the
state management subject in the following links:

What is Profile Properties?
The profile properties was introduced as a part of the .Net
framework 2.0
. The technique is based on the ASP.NET profile
mechanism. The technique is very close to the session state and
enables to store user specific data like session state. The main difference
between the two techniques is that the profile properties isn’t lost
when the user session ends. The profile properties are saved in a
persistent location such as database and therefore available after session
end. In order to be able to use the profile properties you need to configure
a profile provider. The default provider available in the .Net framework is
the SqlProfileProvider. You can build and provide your own providers
if needed. Once you define the profile properties, every user will be
automatically associated with a profile and you’ll be able to use it to save 
and retrieve the user data.

Creating The SQL Database
As written earlier, the default behavior of ASP.NET is to use the
SqlProfileProvider. In order to operate the profile properties you
need to create a SQL database to hold the data. You can create the
database by running the Aspnet_regsql.exe -Ap command. The
command can be found in the path:
%windows%\Microsoft .NET\Framework\<version>
After running the command the ASP.NET database will be built in
your SQL server and you’ll be able to start using the profile
properties
. Again, if you don’t want to use the provided database you
can build your own provider.

Configuring Profile Properties
In order to start using the profile properties in your web application
you first need to configure it. In the web.config. You need to describe
every property that you want to save in the profile. The following
configuration shows how to add a user’s gender and user’s marital
status into profile section of the web.config:

  <configuration>

   <system.web>

      <profile>

        <properties>

         <add name="Gender" type="System.Boolean"/>

         <add name="MaritalStatus" type="System.String"/>

        </properties>

      </profile>

   </system.web>

  </configuration>

Even though you don’t need to declare the string type I prefer
to do it (I could leave the MaritalStatus without a type and by
default it’ll be of string type). The properties by default are enabled
only for authenticated users. To enable properties for anonymous
users you need to use the allowAnonymous field like in the following
example:

  <configuration>

   <system.web>

      <profile>

        <properties>

         <add name="Gender" type="System.Boolean" allowAnonymous="true"/>

         <add name="MaritalStatus" type="System.String" 
           
allowAnonymous="true"/>

        </properties>

      </profile>

   </system.web>

  </configuration>

Another thing you can do is to group properties. It can be done
by using the group element:

  <configuration>

   <system.web>

      <profile>

        <properties>

         <group name="UserDetails">

            <add name="Gender" type="System.Boolean"/>

            <add name="MaritalStatus" type="System.String"/>

         </group>

        </properties>

      </profile>

   </system.web>

  </configuration>

  

How To Use Defined Profile Properties
In order to use the defined properties you use the Profile object.

   Profile.Gender = true;

   Profile.MaritalStatus = "Single";

 

   bool gender = Profile.Gender;

   string maritalStatus = Profile.MaritalStatus;

As you can see the use of the Profile is straight forward.
In order to retrieve a grouped element you need to use it’s
father element (in the above example UserDetails). 

   Profile.UserDetails.Gender = true;

   Profile.UserDetails.MaritalStatus = "Single";

 

   bool gender = Profile.UserDetails.Gender;

   string maritalStatus = Profile.UserDetails.MaritalStatus;

Summary
To sum up the post, today I demonstrated the use of the
profile properties state management technique. The technique
was introduced in the .Net framework 2.0 and enables us to save
user data even when the user session is over.
I hope the series helped you to gain knowledge of how to save
state in the world ASP.NET and that I provided enough tools to
think how to do it right.

How To Use Unity Container In ASP.NET

How To Use Unity Container In ASP.NET

Today’s post will explain how to include Unity container  Unity Application Block
in ASP.NET web applications. The details I write
here are based on David Hayden’s screen cast
and therefore the credit is for David Hayden.
Another good example of how to use Unity
container through WCF service can be found in this post.

Building The Container
The first thing to do is to build the Unity container.
We would like to have a persistent container that hold it’s state
during the running of the application. The right place to put the 
is as part of the Global.asax file as a property of the current
running application. 
First build an interface for the container property:

    public interface IContainerAccessor

    {

        IUnityContainer Container { get; }

    }

 

 

 

 

 

 

After the building of the interface implement it in the Global
class in the Global.asax file:

    public class Global : HttpApplication, IContainerAccessor

    {

        #region Members

        private static IUnityContainer _container;

        #endregion

        #region Properties

        /// <summary>

        /// The Unity container for the current application

        /// </summary>

        public static IUnityContainer Container

        {

            get

            {

                return _container;

            }

            set

            {

                _container = value;

            }

        }

        #endregion

        #region IContainerAccessor Members

        /// <summary>

        /// Returns the Unity container of the application

        /// </summary>

        IUnityContainer IContainerAccessor.Container

        {

            get

            {

                return Container;

            }

        }

        #endregion

        #region Application Events

        protected void Application_Start(object sender, EventArgs e)

        {

            BuildContainer();

        }

        protected void Application_End(object sender, EventArgs e)

        {

            CleanUp();

        }

        #endregion

        #region Methods

        private static void BuildContainer()

        {

            IUnityContainer container = new UnityContainer();

            // Register the relevant types for the

            // container here through classes or configuration

            // register the container in the container property

            Container = container;

        }

        private static void CleanUp()

        {

            if (Container != null)

            {

                Container.Dispose();

            }

        }

        #endregion

    }

In the implementation you hold a static container variable which
will be available in the web application through the interface we build.
In the BuildContainer method we do all the work of registering types
and instances to the Unity container. It can be done by code or
by configuration this decision is yours.

How To Inject Dependencies
After you set up your container it’s time to use it. It is done
by building a base page for all the pages in your application.
The injection of dependencies should be done very early in the
page life cycle and therefore implemented in the OnPreInit event.
The base page class can look like:

    public abstract class BasePage<T> : Page where T : class

    {

        protected override void  OnPreInit(EventArgs e)

        {

            InjectDependencies();

            base.OnPreInit(e);

        }

        protected virtual void InjectDependencies()

        {

            var context = HttpContext.Current;

            if (context == null)

            {

                return;

            }

            var accessor = context.ApplicationInstance as IContainerAccessor;

            if (accessor == null)

            {

                return;

            }

            var container = accessor.Container;

            if (container == null)

            {

                throw new InvalidOperationException("No Unity container found");

            }

            container.BuildUp(this as T);

        }

    }

All the checks in the InjectDependencies method are
a guarantee that we have a Unity container. The only interesting
part here is the BuildUp method in the end of the method.
The BuildUp method will ensure that the injection will happen as
required.

Example Of Concrete Page
After building the base page the only thing to do next is to
implement the other pages and inheriting from the base page.
The next example shows how to use the previous BasePage class:

    public partial class _Default : BasePage<_Default>

    {

        #region Properties

        [Dependency]

        private ILogger Logger { set; get; }

        #endregion

        #region Page Events

        protected void Page_Load(object sender, EventArgs e)

        {

            Logger.Log("Something");

        }

        #endregion

    }

Summary
To sum up the post, I showed an example that was suggested
by David Hayden of how to use Unity in ASP.NET application.
This is a very simple example that will help you to get started with
Unity in your web applications. I suggest to see David Hayden’s
screen cast for more details.