.NET

How to add icon for your custom UserControl to the Toolbox

March 19, 2010 .NET, HowTo, WindowsForms No comments

I read about ToolboxBitmapAttribute and while doing my usual work have decided to use it.

First of all I created my UserControl named BufferedControl which should provide double buffering functionality for me. Once I finished with my control I navigated to Toolbox to add new tool like on the picture:

And do you know what happend next? It said to me that there is no controls which could be added to the Toolbox. But why? It is derived from UserControl and looks fine. So in order to see what is the difference I added empty UserControl1 and was able to add it to the Toolbox. I thought that the reason is because I do not have designer file for my control and some specific methods like Initialize(), but after I added them nothing helped. I did more research and finally figured out that I did not have default public constructor. My constructor was like here:

        public
BufferedControl(IBufferedControlController controller)
        {
            Controller = controller;
            BufferContext = new BufferedGraphicsContext();
            SizeGraphicsBuffer();
           
SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
            SetStyle(ControlStyles.DoubleBuffer,
false);
        }

So lets move to adding icon of your UserControl to the Toolbox

1) First add your control and draw the icon. Below is screenshot of what I have for this.

a) Once you done, you should ensure that your control has public default constructor and that OnPaint method will not raise exceptions after it was called on instance created with default constructor.
b) Also go to properties of your icon and set Build Action –> Embedded Resource.

2) Add ToolboxBitmap attribute to your control class declaration. In my case it looks like below:

namespace
Som.Application.Grid
{
    [ToolboxBitmap(“Som.Application.Grid.BufferedControl.ico”)]
    public class BufferedControl : UserControl
    {
      //…

3) Navigate to ToolBox and add your control from your assembly:

That’s it!


No comments


Multithreading in CLR

March 14, 2010 .NET, C#, Concurrency No comments

Here I have code that provides some explanations to the multithreading in .NET. Wrote it to refresh what I know on concurrency.

    1 /********************************************************
    2  *
    3  *                CODE IS MY PRESENTATION
    4  *
    5  ********************************************************/
    6 using System;
    7 using System.IO;
    8 
    9 //1. CLR threading is based on Windows threading.
   10 //2. CLR threading is going away from correspondence with Windows threading.
   11 //SO do not use native windows functions if you already writing CLR code
   12 //that is for future, of course Microsoft is not sleeping
   13 
   14 //Let’s start
   15 //This is namespace where Multithreading lives…
   16 using System.Threading;
   17 
   18 namespace TheoryConsole
   19 {
   20     class Program
   21     {
   22         static void Main(string[] args)
   23         {
   24             MultiThreadingInCLR presentation = new MultiThreadingInCLR();
   25 
   26             //presentation.CLRHasPoolOfThreads();
   27             //presentation.UsingThreadPoolForAsynchCalculations();
   28             //presentation.UsingDedicatedThread();
   29             //presentation.PeriodicalCallinOfAsynchOperations();
   30             presentation.AsynchronousProgrammingModel();
   31 
   32             Thread.Sleep(100);
   33             //Console.WriteLine(“Press any key to exit…”);
   34             //Console.ReadLine();
   35         }
   36     }
   37 
   38     public class MultiThreadingInCLR
   39     {
   40         //Many developers uses multithreading too often,
   41         //but it is not cheap.
   42 
   43         //Because
   44         //to Switch context system needs:
   45         // – go to core -> save processor registers ->
   46         // put spin-blocker -> take another thread ->
   47         // unput blocker -> load registers > run thread
   48 
   49         //Pool of Threads
   50         public void CLRHasPoolOfThreads()
   51         {
   52             //Each Process has its oun Pool wich can be used
   53             // in all AppDomains of that Process
   54             ThreadPool.QueueUserWorkItem(DoAsynchWork, 10);
   55 
   56             //If there are no requests to Pool,
   57             //CLR will delete threads from it in about 2 minutes
   58 
   59             // Amount of threads in Pool
   60             // – Do not try to limit amount of threads in Pool
   61             // There are two types of threads: Worker and I/O
   62             int workingThreads = 0;
   63             int completionThreads = 0;
   64             //Get/Set Max/Min Threads
   65             ThreadPool.GetMaxThreads(out workingThreads, out completionThreads);
   66 
   67             //To GetAvailableThreads call it:
   68             //ThreadPool.GetAvailableThreads();
   69 
   70             for (int i = 0; i < 506; i++)
   71             {
   72                 ThreadPool.QueueUserWorkItem(DoAsynchWork, 100);
   73             }
   74 
   75             ThreadPool.GetMaxThreads(out workingThreads, out completionThreads);
   76             workingThreads = 1000;
   77         }
   78 
   79 
   80         public void UsingThreadPoolForAsynchCalculations()
   81         {
   82             //If you do not need I/O operations use Worker type of thread
   83             //For example spell-checker in some editor need to work asynchronously
   84             //
   85             //Most commonly these three methods are called:
   86             //
   87             //static Boolean QueueUserWorkItem(WaitCallback callBack);
   88             //static Boolean
   89             //   QueueUserWorkItem(WaitCallback callBack, Object state);
   90             //static Boolean
   91             //   UnsafeQueueUserWorkItem(WaitCallback callBack, Object state);
   92 
   93             //callBack is delegate with the next signature:
   94             //delegate void WaitCallBack(Object state);
   95             WaitCallBackExample_IDoHardWork(null);
   96 
   97             //Here is how to start doing hard work asynchromously
   98             ThreadPool.QueueUserWorkItem(WaitCallBackExample_IDoHardWork);
   99 
  100             //Use UnsafeQueueUserWorkItem if the time resource is very critical
  101             //Reason: QueueUserWorkItem is verifying
  102             // if the assemblies from Thread stack has permissions
  103             // to access file for example
  104             //SecurityException could be generated if there is no presmissions
  105         }
  106 
  107         #region Dedicated Thread
  108         public void UsingDedicatedThread()
  109         {
  110             //Commonly is used if we need to set some priority to thread
  111             // or if we need to change other properties of Thread
  112             // – we need set some properties to the thread
  113             // – we need set priority to our thread
  114             //        (ThreadPool has one priority for all threads in it)
  115             // – if we want run Thread in foreground
  116             //        (ThreadPoole runs threads in background)
  117 
  118             //please note that here we do NOT create actual thread,
  119             // because thread will be created only
  120             //when we will call our thread object
  121             Thread someNewThread = new Thread(ComputeBoundWork);
  122             //When we call Start method actuall thread is created
  123             // and process starts
  124 
  125             someNewThread.Start(1);
  126             Thread.Sleep(1000);//this imitates some work in main thread
  127 
  128             //Please note!
  129             // that after ComputeBoundWork finished its work,
  130             // actual system thread was deleted
  131 
  132             // this waits while the dedicated thread will finish all its work…
  133             someNewThread.Join();
  134 
  135             // so this is some kind of sysnch of threads..
  136         }
  137         #endregion
  138 
  139         #region Timer
  140         public void PeriodicalCallinOfAsynchOperations()
  141         {
  142             //System.Threading namespace has Timer defined
  143             //it has 4 very similar constructors
  144             //this used only TimerCallback
  145             //Timer timer1 = new Timer(ComputeBoundWork);
  146             Timer timer2 = new Timer(ComputeBoundWork, null, 0, 1000);
  147             // method will be called only once
  148             //Timer timer3 =
  149             //  new Timer(ComputeBoundWork, null, 0, Timeout.Infinite);
  150 
  151             //if you want to change timing behaviour of the timer
  152             // you could use Change() method, or Dispose() to stop…
  153             Thread.Sleep(10000);// this imitates some work here – 10 seconds
  154             timer2.Dispose();
  155 
  156             // Please note that there are 3 different Timers in FCL
  157             // – System.Threading.Timer
  158             //      is most suitable for doing asynch operations
  159             // – System.Windows.Forms.Timer
  160             //      is equivalent to WinAPI SetTimer.. events are added WM_TIMER
  161             // – System.Timers.Timer
  162             //      is some kind of wrapper of the Threading.Timer
  163         }
  164         #endregion
  165 
  166         #region Asynchronous Programming Model
  167 
  168         private IAsyncResult synchResultForFileWriting;
  169         private FileStream fs;
  170         public void AsynchronousProgrammingModel()
  171         {
  172             // Using of the asynchronous operations is the key to big programms :)
  173             // Combination of it with the ThreadPool
  174             //  is way to effectively use all processors of the system.
  175             // Examples where it is used…
  176             // – System.IO.Stream -> FileStream and NetworkStream
  177             //        derived classes has methods BeginRead(), BeginWrite()
  178             // – System.Net.Dns -> BeginGetHostAddresses(),
  179             //        BeginGetHostByName(), and so on…
  180             // – System.Net.Sockets -> BeginAccept(), BeginConnect(), …
  181             // all delegate types has BeginInvoke(), what could be used in APM
  182 
  183             //ok let we see file reading example
  184             fs = new FileStream(
  185                 “test.bin”, FileMode.OpenOrCreate,
  186                 FileAccess.Write, FileShare.None, 35000, FileOptions.Asynchronous);
  187             synchResultForFileWriting =
  188                 fs.BeginWrite(new byte[32738], 0, 32000, CallBackMethod, null);
  189             Console.WriteLine(
  190                 “This is called just after we said to write something to file.”);
  191 
  192 
  193             // There are 3 types of joining threads.. im APM
  194             // 1. Waiting for finish of work
  195             //Int32 readMeFile.EndRead(IAsyncResutl asyncResult)
  196 
  197             // 2. Regualar polling – is not effective method
  198             Stream readMeFile = new FileStream(“film.mp4”, FileMode.Open,
  199                   FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous);
  200 
  201             byte[] fileContent = new byte[450000000];
  202             IAsyncResult ar =
  203                 readMeFile.BeginRead
  204                     (fileContent, 0, fileContent.Length, null, null);
  205 
  206             while (!ar.IsCompleted)
  207             {
  208                 Console.WriteLine(
  209                     “Reading Large Music file operation is not completed…”);
  210                 Thread.Sleep(100);
  211             }
  212 
  213             //please note that this will not stop actuall
  214             //     thread because we were asking for finish above
  215             readMeFile.EndRead(ar);
  216             Console.WriteLine(“We already finished reading large music file.”);
  217 
  218             // 3. Callback!!
  219             // is the most efficient and commonly used joining type
  220         }
  221 
  222         private void UserAlreadyWantsToReadThatFile()
  223         {
  224             fs.EndWrite(synchResultForFileWriting);
  225             //now we are sure that ansynch writing to file has finished its work!!
  226             fs.Close();
  227         }
  228 
  229 
  230         private void CallBackMethod(IAsyncResult ar)
  231         {
  232             //this method will be called when writing to file will finish its work
  233             Console.WriteLine(“We just finished writing to file…”);
  234         }
  235 
  236         #endregion
  237 
  238         public void WaitCallBackExample_IDoHardWork(object hardParameter)
  239         {
  240             //actually if you see my body you know that I do not do work
  241             // I sleep for 2 seconds :)
  242             Thread.Sleep(2000);
  243         }
  244 
  245         public void DoAsynchWork(object miliseconds)
  246         {
  247             Thread.Sleep((int)miliseconds);
  248         }
  249 
  250         public void ComputeBoundWork(object opCode)
  251         {
  252             Thread.Sleep(1000);// this imitates some work…
  253             Console.WriteLine(
  254                 string.Format(“Compuing bound work with param: {0}”, opCode));
  255         }
  256     }
  257 }


No comments


Question about AutoMapper Performance

February 28, 2010 .NET, AutoMapper, Frameworks 4 comments

If you haven’t read my previous article on AutoMapper, please read it first.

After I’ve posted this article one guy was really concerned about the performance of AutoMapper.
So, I have decided to measure execution time of the AutoMapper mapping and manual mapping code.

First of all I have code which returns me 100000 almost random Customers which goes to the customers list.

Measurement of AutoMapper mapping time:

            stopwatch.Start();
            var autoMapperCVI = new List<CustomerViewItem>();
            foreach (var customer in customers)
            {
               autoMapperCVI.Add(Mapper.Map<Customer,CustomerViewItem>(customer));
            }
            stopwatch.Stop();
            Console.WriteLine(string.Format(“AutoMapper: {0}”, stopwatch.ElapsedMilliseconds));

Measurement of the manual mapping time:

            stopwatch.Start();
            var manualCVI = new List<CustomerViewItem>();
            foreach (var customer in customers)
            {
                var customerViewItem = new CustomerViewItem()
                                           {
                                               FirstName = customer.FirstName,
                                               LastName = customer.LastName,
                                               FullName = customer.LastName + ” “ + customer.FirstName,
                                               DateOfBirth = customer.DateOfBirth.ToLongDateString(),
                                               CompanyName = customer.Company.Name,
                                               NumberOfOrders = customer.NumberOfOrders,
                                               VIP = customer.VIP ? “Y” : “N”
                                           };
                manualCVI.Add(customerViewItem);
            }
            stopwatch.Stop();           
            Console.WriteLine(string.Format(“Manual Mapping: {0}”, stopwatch.ElapsedMilliseconds));

I ran my tests many times and one of the possible outputs could be:

AutoMapper: 2117
Manual Mapping: 293

It looks like manual mapping is 7 times faster than automatical. But hey, it took 2 sec to map handrend thouthands of customers.

It is one of the situations where you should decide if the performance is so critical for you or no. I don’t think that there are a lot of cases when you really need to choice manual mapping exactly because of performance issue.


4 comments


I wanna be not so noisy and decoupled to AutoMapper

February 27, 2010 .NET, AutoMapper, Clean Code 2 comments

If you haven’t read my previous article on AutoMapper, please read it first.

I just read an article on the noisiness which could be introduced with AutoMapper.

My Mapping Code is Noisy

Accordingly to that article my code:

   CustomerViewItem customerViewItem = Mapper.Map<CustomerCustomerViewItem>(customer);

is noisy code.

Why?

In few words that is because I’m coupled to the specific mapping engine and because I’m providing too much unneeded information on about how to map my objects.
Take a look on that line once again: we used Customer , but we already have customer, so we can know its type.


What to do to make it not so noisy?


In that article, that I pointed, there is proposition to change my code to:


            CustomerViewItem customerViewItem = customer.Map<CustomerViewItem>();


So, I’ve got interested to apply it to my previous AutoMapper article’s code. As you already caught Map is just extension method for my Customer  class.


Here it is:

    public static class MappingExtentions
    {
        public static TDest Map<TDest>(this Customer customer)
        {
            return Mapper.Map<Customer, TDest>(customer);
        }
    }

Everything becomes simple if you are trying it.


2 comments


Constraints for my Generics

February 26, 2010 .NET, C# No comments

I have never used constraints for my generic classes. So in this article I just want to show how I’ve used it:

So for now I have ICustomer interface:

    public interface ICustomer
    {
        string Name { getset; }
        List<int> GetOrders();
    }

and two implementations like UsualCustomer and VipCustomer.

Also I’m going to have some OrderingProcessor which is supposed to be operating with different types of Customers. But when I want to call GetOrders method I just have not it in my list, like below:

but once I’ve changed the declaration of the OrderingProcess just a little bit, with specifying type of T

    public interface IOrderingProcessor<T>
        where T : ICustomer
    {
        void Process(T objectToProcess);
    }


World has smiled to me and I’m getting what I want, please see:

I expect that you are laughing while reading this post. Maybe because this thing is too simple to write article/post on it if you are familiar with C#/.NET. Yes, but I have never tried it myself. Did you?

To make you laughing not so much loud let us take a look on another architecture:

    public interface IOrderingProcessor<T>
        where T : ICustomer
    {
        void Process(T objectToProcess);
    }
    internal class VipOrderingProcessor<TCustomer> : IOrderingProcessor<TCustomer>
        where TCustomer : IVipCustomernew()
    {
        public void Process(TCustomer objectToProcess)
        {
            var vipCustomer = new TCustomer();
            var orders = objectToProcess.GetOrders();
        }
    }

As you see we can create specific VipOrderingProcessor and we are constraining it to use just VipCustomers or derived classes. This gives us opportunity to specify constraints on different levels of implementation.

But do you know what does another constraint  new() mean?
This constraint specifies that TCustomer objects will have public default constructor, so you can write

            var vipCustomer = new TCustomer();

This could be very useful for implementing Factory Design Pattern. I’m sure that next time I will need to develop whole family of Factories I will use constraints, since code could be much flexible in this case.


No comments


AutoMapper

February 25, 2010 .NET, AutoMapper, Frameworks 4 comments

The Problem

Have you ever faced need to write code, which looks like here:

            Customer customer = GetCustomerFromDB();

            CustomerViewItem customerViewItem = new CustomerViewItem()
                                       {
                                           FirstName = customer.FirstName,
                                           LastName = customer.LastName,
                                           DateOfBirth = customer.DateOfBirth,
                                           NumberOfOrders = customer.NumberOfOrders
                                       };

            ShowCustomerInDataGrid(customerViewItem);

Our scenario could be like:
We have our domain model which has Customer entity and we are going to show Customers in DataGrid, and for that we need much lighter object CustomerViewItem, list of which is bounded to the Grid.

As you see there are four lines of code which are just copying values from one object to another. Could also be that you will need to show up to 10-15 columns in you grid. What then?

Would you like to have something that will do mapping from Customer to the CustomerViewItem automatically?

Of course you do, especially if you have another situation like mapping of heavy data objects into DTO objects which are considered to be send though the wire.

AutoMapper

From the AutoMapper codeplex web page we see that “AutoMapper is an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type. What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper’s established convention, almost zero configuration is needed to map two types.“, so in other words it provides the solution for our problem.

To get started go and download it here. It is standalone assembly, so you should not get difficulties with including reference to it in your project.

So in order to ask AutoMapper do dirty work instead of me, we need to add next line somewhere in the start of our code execution:

            Mapper.CreateMap<Customer, CustomerViewItem>();

Once we have that we are done and we can use pretty nice code to get our mapped object:

            Customer customer = GetCustomerFromDB();

            CustomerViewItem customerViewItem = Mapper.Map<Customer, CustomerViewItem>(customer);

            ShowCustomerInDataGrid(customerViewItem);

Lets take a look on whole code base to see all about what I’m going to talk further:

    class Program
    {
        static void Main(string[] args)
        {
            var program = new Program();
            Mapper.CreateMap<Customer, CustomerViewItem>();
            program.Run();
        }

        private void Run()
        {
            Customer customer = GetCustomerFromDB();

            CustomerViewItem customerViewItem = Mapper.Map<Customer, CustomerViewItem>(customer);

            ShowCustomerInDataGrid(customerViewItem);
        }

        private void ShowCustomerInDataGrid(CustomerViewItem customerViewItem){}

        private Customer GetCustomerFromDB()
        {
            return new Customer()
            {
                DateOfBirth = new DateTime(1987, 11, 2),
                FirstName = “Andriy”,
                LastName = “Buday”,
                NumberOfOrders = 7
            };
        }
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DateOfBirth { get; set; }

        public int NumberOfOrders { get; set; }
    }

    public class CustomerViewItem
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DateOfBirth { get; set; }

        public int NumberOfOrders { get; set; }
    }


   
And proving that all values has been mapped take a look on the picture:

More Complex Example 1 (Custom Map)

So far we know all to have extremely simple mapping. But what if we need something more complex, for example, CustomerViewItem should have FullName, which consists with First and Last names of Customer?

After I just added public string FullName { get; set; } to the CustomerViewItem and run my application in debug I got null value in that property. That is fine and is because AutoMapper doesn’t see any FullName property in Customer class. In order to “open eyes” all you need is just to change a bit our CreateMap process:

            Mapper.CreateMap<Customer, CustomerViewItem>()
                .ForMember(cv => cv.FullName, m => m.MapFrom(s => s.FirstName + ” “ + s.LastName))


And results are immediately:

More Complex Example 2 (Flattening)

What if you have property Company of type Company:

    public class Customer
    {
        public Company Company { get; set; }
        //…
    }

    public class Company
    {
        public string Name { get; set; }
    }


and want to map it into CompanyName of the view class

    public class CustomerViewItem
    {
        public string CompanyName { get; set; }
        //…
    }


How do you think what do you need to change in your mapping to make this work?

Answer: NOTHING. AutoMapper goes in deep of your classes and if names matches it will do mapping for you.

More Complex Example 3 (Custom type resolvers)

What if you have boolean property VIP in your Customer class:

    public class Customer
    {
        public bool VIP { get; set; }
    }


and want to map it into string VIP and represent like “Y” or “N” instead

    public class CustomerViewItem
    {
        public string VIP { get; set; }
    }

   
Well, we can solve this the same way we did for the FullName, but more appropriate way is to use custom resolvers.
So lets create customer resolver which will resolve VIP issue for us.

It looks like:

    public class VIPResolver : ValueResolver<bool , string >
    {
        protected override string ResolveCore(bool source)
        {
            return source ? “Y” : “N”;
        }
    }


And only one line is needed for our CreateMap process:

    .ForMember(cv => cv.VIP, m => m.ResolveUsing<VIPResolver>().FromMember(x => x.VIP));

More Complex Example 4 (Custom Formatters)

What if I want AutoMapper to use my custom formatting of the DateTime instead of just using ToString, when it does mapping from DateTime to String property?
Let say I want use ToLongDateString method to show birth date with fashion.

For that we add:

    public class DateFormatter:IValueFormatter
    {
        public string FormatValue(ResolutionContext context)
        {
            return ((DateTime) context.SourceValue).ToLongDateString();
        }
    }


And making sure that AutoMapper knows where to use it:

                .ForMember(cv => cv.DateOfBirth, m => m.AddFormatter<DateFormatter>());
So, now I’ve got:

Great, isn’t it? BirthDate is even in my native language.

I hope my article was interesting to read and it gave you ideas how you can utilize this new feature called “AutoMapper”.


4 comments


Lambda Expression or Simple Loop

February 20, 2010 .NET, LambdaExpression, MasterDiploma 6 comments

For my Diploma work I need to calculate distance between two vectors.
For example, Euclidean distance is calculated like:

How could it look if I do have two lists with values?

Something like this:

         public double GetDistance(IList<double> firstVector, IList<double> secondVector)
         {
             double sum = 0;
             for (int i = 0; i < firstVector.Count; i++)
             {
                 sum += (firstVector[i] – secondVector[i]) * (firstVector[i] – secondVector[i]);
             }
             return Math.Sqrt(sum);

But, please take a look how sweet this all could be with Lambda Expression:

         public double GetDistance(IList<double> firstVector, IList<double> secondVector)
         {
             double sum = firstVector.Select((x, i) => (x – secondVector[i]) * (x – secondVector[i])).Sum();
             return Math.Sqrt(sum);
         }

Of course main point of this post is not to show all beauty of LE, but either what did happen after I wrote this Lambda expression. Maniacal interest in what is faster to execute and what is the difference in performance of this two methods appeared in my mind, so I prepared few simple tests.

I’ve ran my tests on 1000000 elements and results were such:

  1. Lambda expressions are quite slower than simple loops.
  2. My test showed that primitive loop is faster in about 15-20%.

Also, I played with VS performance analyzer (Analyze -> Launch Performance Wizard…).
It allows me run one version of code (Lambda) and get detailed report, then run another version of code (Loop) and get another report. After that I’m able to compare results seeing performance improvements. So that is good tool.


6 comments


Managed Extensibility Framework

January 27, 2010 .NET, Frameworks, MEF 4 comments

MEF is the Framework which allows you to load extensions to you application easily. It does discovery and composition of parts you need to be included in your application at run-time. You could extend your behavior simply with adding new Plugin. Managed Extensibility Framework will do everything for you.

Hello MEF World!

Assume we have really simple application and we want it to say “Hello MEF World!“:

    class Program
    {
        static void Main(string[] args)
        {
            var program = new Program();
            program.Run();
        }
        private void Run()
        {
            ProgrammGreeter.SayHello();
        }
        protected IGreeter ProgrammGreeter{ get; set;}
    }
    public interface IGreeter
    {
        void SayHello();
    }
    public class Greeter:IGreeter
    {
        public void SayHello()
        {
            Console.WriteLine(“Hello MEF World!”);
        }
    }

That is absolutely how this look and we want to make this work. The main issue is to have instance in property ProgrammGreeter to be real instance of Greeter.

Lets accomplish this with MEF

In order to do this we need to include reference to System.ComponentModel.Composition.

Accordingly to MSDN: “MEF is an integral part of the .NET Framework 4 Beta 1, and is available wherever the .NET Framework is used. You can use MEF in your client applications, whether they use Windows Forms, WPF, or any other technology, or in server applications that use ASP.NET. In addition, there are plans to add MEF support for Silverlight applications.

Most likely MEF will be included into .NET Framework 4.0, but for now we could download it from codeplex site here.

Once we added reference we could add Import and Export attributes.
Export stands for exposing some capabilities and Import stands for dependency on some other capability.

Our Greeter provides some capabilities so we add Export there:

    [Export(typeof(IGreeter))]
    public class Greeter : IGreeter

We want to use that capability in our Programm class, we depend on that functionality. Add Import:

        [Import]
        protected IGreeter ProgrammGreeter { get; set; }

Usually our capabilities lives in other asseblies, but also they could live in called assembly. Anyway we need to say how to compose all our dependencies to MEF.
This could be done with method Compose which we be calling before we are using capabilities, usually at the start of app:

        private void Run()
        {
            Compose();
            ProgrammGreeter.SayHello();
        }
        private void Compose()
        {
            var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var compositionContainer = new CompositionContainer(assemblyCatalog);
            compositionContainer.ComposeParts(this);
        }

I ran my application and got:

How does Managed Extensibility Framework work?

I think that you are bit concerned/confused regarding that Compose method. Just read comments in code of Compose, which I made more detailed:

        //We need guide MEF how to Compose all we need
        private void Compose()
        {
            //Catalog says where to search for capabilities (Where do exports live)
            var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            //CompositionContainer holds defined dependencies and coordinates creation
            var compositionContainer = new CompositionContainer(assemblyCatalog);
            //CompositionBatch object holds references to all objects that need to be composed
            var compositionBatch = new CompositionBatch();
            //one of such objects is Programm instance (this), it needs to be composed
            compositionBatch.AddPart(this);
            //And finally Container has method called Compose to do actuall Composing
            compositionContainer.Compose(compositionBatch);
        }

In Managed Extensibility Framework there are primitives called ComposablePart which holds extensions to your application grabbed from Catalog. But also it might be that they have Imports which also needed to be composed.

Take a look on this picture from Managed Extensibility Framework wiki page.

More complex Example

In this example we will have application which parses XML file (contains information about some developer). Then when we want to deploy our application to Clients we want that XML to pass some rules, but they could differ from Client to Client. To accomplish this we put rules into separate dll and will work with it as with plugin.

We have two assemblies:

  • MEF.DEMO which declares ISecurityRule and IDataRule.
  • MEF.Rules has implementation of those interfaces.

Like on picture below. I simply don’t want to bore you with explaining of Rules logic. If you want sources just ping me.

Our Programm class wants to load rules from other assembly so we put Imports.

        [Import]
        public ISecurityRule SecurityRule { get; set; }
        [ImportMany]
        public IDataRule[] DataRules { get; set; }
        public void Run()
        {
            Console.WriteLine(“Programm run.”);
            Compose();
            Console.WriteLine(“Composition completed.”);
            var document = XDocument.Load(“developer.xml”);
            Console.WriteLine(document.ToString());
            var passesValidation = SecurityRule.PassesValidation(document);
            Console.WriteLine(string.Format(“Rule {0}: {1}”, SecurityRule.GetType(), passesValidation));
            foreach (var d in DataRules)
            {
                var valid = d.IsValid(document);
                Console.WriteLine(string.Format(“Rule {0}: {1}”, d.GetType(), valid));
            }          
        }

As you noticed we are using ImportMany, name says for itself.

We need to change our Compose method to search for Exports in Directory where execution assembly is located. For that we use DirectoryCatalog.

        private void Compose()
        {
            var catalog = new DirectoryCatalog(Environment.CurrentDirectory);
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }

Put those dlls in one folder, and run MEF.DEMO. You will get:

The goal of MEF is to seamlessly glue together classes which import services from other parts of the application, and some classes which export those services. You could say that MEF is like DI container. Yes it has a lot of it, but Managed Extensibility Framework is concentrated on composition. And that composition could be done at run time at any point of time you want that to happen. Also you could do re-composition whenever you want to do that. You could load capabilities with Lazy technical or add some metadata to your exports. Discovering of dependencies in Catalog could be done with Filtering.

Managed Extensibility Framework is great feature, that Microsoft added to .NET 4.0 Framework.


4 comments


Generics performance vs. non-generics performance

January 22, 2010 .NET, Opinion 7 comments

Today I was reading some book on the .net development and found there interesting thing.

Guy explains “Why to use Generics?
He wrote that Frameworks 1.0 and 1.1 did not support Generics, so developers were using Object.
He says, that generics offers two significant advantages over using the Object class:
1) Reduced run-time errors
That is because type-safety.
2) Improved perfomance
Casting requires boxing and unboxing, which slows performance. Using of Generics doesn’t require casting or boxing, which improves run-time performance.

And then funny thing…
He put a box which looks like:

Real Word
(his name)
I haven’t been able to reproduce the performance benefits of generics;
however, according to Microsoft, generics are faster than using
casting. In practice, casting proved to be several times faster than
using a generic. However, you probably won’t notice performance
differences in your applications. (My tests over 100,000 iterations took only a few seconds.) So you should still use generics because they are type-safe.

OMG! I could not believe in his words. As per me this should be BULLSHIT, unless I 100% missed something there.

Test

I wrote a really quick verification like:

namespace TestGenericsPerfomance
{
    class Program
    {
        internal static void Main(string[] args)
        {
            Stopwatch stopWatch = new Stopwatch();
            //Working with value objects
            //Generic wins 100%
            stopWatch.Start();
            ArrayList nonGenericArrayList = new ArrayList();
            for (int i = 0; i < 10000000; i++)
            {
                nonGenericArrayList.Add(i);//takes Object so boxing is performed here…
            }
            stopWatch.Stop();
            Console.WriteLine(string.Format(“Int32: ArrayList (boxing): {0:0}”, stopWatch.Elapsed.TotalMilliseconds));
            stopWatch.Restart();
            List<Int32> someCustomersIds = new List<Int32>();
            for (int i = 0; i < 10000000; i++)
            {
                someCustomersIds.Add(i);
            }
            stopWatch.Stop();
            Console.WriteLine(string.Format(“Int32: List<Int32> (generic): {0:0}”, stopWatch.Elapsed.TotalMilliseconds));
 
            //Working with reference objects
            //Generic still wins, but not so sure..
            Customer sharedCustomer = new Customer();
            stopWatch.Restart();
            ArrayList nonGenericArrayListCustomers = new ArrayList();
            for (int i = 0; i < 10000000; i++)
            {
                nonGenericArrayListCustomers.Add(sharedCustomer);//no boxing.. jut putting the same reference
            }
            stopWatch.Stop();
            Console.WriteLine(string.Format(“Customer: ArrayList (no boxing): {0:0}”, stopWatch.Elapsed.TotalMilliseconds));
            stopWatch.Restart();
            List<Customer> genericBasedOnInterface = new List<Customer>();
            for (int i = 0; i < 10000000; i++)
            {
                genericBasedOnInterface.Add(sharedCustomer);//just put the same reference in generic list
            }
            stopWatch.Stop();
            Console.WriteLine(string.Format(“Customer: List<Customer> (no boxing): {0:0}”, stopWatch.Elapsed.TotalMilliseconds));
        }
        private class Customer
        {
            public string Name = “Andriy Buday”;
            public string Buy(string what)
            {
                return “I’m glad I bought that.”;
            }
        }
    }
}

And the result is:

Int32: ArrayList (boxing): 2443
Int32: List<Int32> (generic): 294
Customer: ArrayList (no boxing): 586
Customer: List<Customer> (no boxing): 315
Press any key to continue . . .

As you see generics are much faster. Also I searched over internet and found a lot of different stuff that says that generics provide better performance.

My Opinion

You would said what kind of book do I read. Is it “C# for Complete Dummy“?
No, that is Microsoft’s training Kit for exam 70-536.
Even if this was a book “C# for Dummy” it should not contain mistakes. And even if this is a book for kids it should not contain wrong thing. Yea.. it could be very simple, but not wrong!

I thought to write e-mail to that guy, but then decided that there is no need in this.

Just be careful when you read books and others thoughts, even mine :)


7 comments


Complex Custom Configuration

January 19, 2010 .NET 1 comment

Have you ever faced with need to have your custom configuration?

Probably yes, on MSDN you can find a good example on custom configuration here.
That example was not 100% what I need, since I needed few included one in others collections. Like below:

<?xml version=1.0 encoding=utf-8 ?>
<configuration>
  <configSections>
      <section name=ServicesSettings type=RoadMap.CustomConfiguration.ServicesSection, RoadMap.CustomConfiguration/>
  </configSections>
  <ServicesSettings>
    <Services>
      <add serviceName=Greeter isEnabled=true interval=7>
        <Messages>
          <add messageName=Hello/>
          <add messageName=World/>
        </Messages>
      </add>

      <add serviceName=BadBoy isEnabled=false interval=“10”>
        <Messages>
          <add messageName=Go to/>
          <add messageName=Hell/>
        </Messages>
      </add>

    </Services>
  </ServicesSettings>
</configuration>

As you see I want to get list of services which of them could be enabled or disabled also it could have interval to send one or many messages, which are also configured.

As you see I already added RoadMap.CustomConfiguration.ServicesSection to map ServiceSettings section to my appropriate class:

ServicesSection

using System.Configuration;
namespace RoadMap.CustomConfiguration
{
    public class ServicesSection : ConfigurationSection
    {
        [ConfigurationProperty(“Services”)]
        public ServicesCollection Services
        {
            get { return ((ServicesCollection)(base[“Services”])); }
        }
    }
}

Next you will probably will want to take a look is ServicesCollection:

ServicesCollection

using System.Configuration;
namespace RoadMap.CustomConfiguration
{
    [ConfigurationCollection(typeof(ServiceElement))]
    public class ServicesCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ServiceElement();
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ServiceElement)(element)).Name;
        }
        public bool ContainsKey(string key)
        {
            var element = BaseGet(key);
            return element != null ? true : false;
        }
        public ServiceElement this[int idx]
        {
            get
            {
                return (ServiceElement)BaseGet(idx);
            }
        }
        public ServiceElement this[object key]
        {
            get
            {
                return (ServiceElement)BaseGet(key);
            }
        }
        public void Add(ServiceElement element)
        {
            base.BaseAdd(element);
        }
    }
}

ServiceElement

using System;
using System.Configuration;
namespace RoadMap.CustomConfiguration
{
    public class ServiceElement : ConfigurationElement
    {
        [ConfigurationProperty(“serviceName”, DefaultValue = “Greeter”, IsRequired = true)]
        [StringValidator(InvalidCharacters = “~!@#$%^&*()[]{}/;'”|\”, MinLength = 1, MaxLength = 60)]
        public String Name
        {
            get
            { return (String)this[“serviceName”]; }
            set
            { this[“serviceName”] = value; }
        }
        [ConfigurationProperty(“isEnabled”, DefaultValue = true, IsRequired = false)]
        public bool IsEnabled
        {
            get
            { return (bool)this[“isEnabled”]; }
            set
            { this[“isEnabled”] = value; }
        }
        [ConfigurationProperty(“interval”, DefaultValue = “10”, IsRequired = false)]
        [IntegerValidator(ExcludeRange = false, MaxValue = 100, MinValue = 1)]
        public int Interval
        {
            get
            { return (int)this[“interval”]; }
            set
            { this[“interval”] = value; }
        }
        [ConfigurationProperty(“Messages”)]
        public MessagesCollection Messages
        {
            get { return ((MessagesCollection)(base[“Messages”])); }
        }
    }
}

As you see it has Messages property which is again collection (similar to ServicesCollection) of MessageElements:

MessageElement

using System;
using System.Configuration;
namespace RoadMap.CustomConfiguration
{
    public class MessageElement : ConfigurationElement
    {
        [ConfigurationProperty(“messageName”, DefaultValue = “hi”, IsRequired = true)]
        [StringValidator(InvalidCharacters = “~!@#$%^&*()[]{}/;'”|\”, MinLength = 1, MaxLength = 60)]
        public String Name
        {
            get
            { return (String)this[“messageName”]; }
            set
            { this[“messageName”] = value; }
        }
    }
}

To ensure you that this works as expected just take a look on following screenshots:

We have one Greeter service:

It has two messages and second one is “World”:

Hope you could just copy-paste my code and also add MessagesCollection and you are done, just change naming to your needs.


1 comment