March 19, 2010 .NET, HowTo, WindowsForms No comments
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:
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:
3) Navigate to ToolBox and add your control from your assembly:
That’s it!
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.
February 28, 2010 .NET, AutoMapper, Frameworks 4 comments
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:
Measurement of the manual mapping time:
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.
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<Customer, CustomerViewItem>(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:
Everything becomes simple if you are trying it.
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:
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
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:
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.
February 25, 2010 .NET, AutoMapper, Frameworks 4 comments
The Problem
Have you ever faced need to write code, which looks like here:
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:
Lets take a look on whole code base to see all about what I’m going to talk further:
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:
And results are immediately:
More Complex Example 2 (Flattening)
What if you have property Company of type Company:
and want to map it into CompanyName of the view class
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:
and want to map it into string VIP and represent like “Y” or “N” instead
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:
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:
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”.
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:
But, please take a look how sweet this all could be with Lambda Expression:
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:
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.
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!“:
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:
We want to use that capability in our Programm class, we depend on that functionality. Add Import:
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:
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:
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:
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.
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.
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.
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:
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:
And the result is:
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 :)
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:
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
Next you will probably will want to take a look is ServicesCollection:
ServicesCollection
ServiceElement
As you see it has Messages property which is again collection (similar to ServicesCollection) of MessageElements:
MessageElement
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.