February 26, 2010 .NET, C# No comments
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 23, 2010 Errors, IDE, VS2010 4 comments
I have found that not only my project has a lot of stupid bugs with more unexpected fixes, but also some well known products like Visual Studio.
Today I tried to install VS2010 RC on the XP system. Before that I had Beta 1 installed, but now it requires Service Pack 3.
So I installed Service Pack 3, deinstalled Beta 1 and was expecting to install VS2010 RC without any pain.
But what happen was interesting:
Installation process runs… and then just dies without explanations.
Playing with it I’ve got this
Error message:
To help protect your computer, Windows has closed this program. Name: Suite Integration Toolkit Executable
I searched over the internet how to fix this. And I found it:
Go to input languages settings and do the next for each input language you have:
I could not imagine that someone is able to guess such strange fix itself. :)
Of course there are explanations here and here.
February 21, 2010 C#, Java, MasterDiploma 2 comments
Today I committed initial version of my Diploma Work Sources.
And there are few interesting things regarding to my first commit.
Thing One (Language)
I re-wrote all my last year course work from Java to C#.
And I did it all in about 12 hours. Its just amazing how my developing speed differs in eclipse and Visual Studio IDEs. As I remember same took me 50+ hours with Java + eclipse and I did all without enthusiasm.
I hate writing properties in Java
This is one thing where I do think that Java is kind more verbose than C#. There are some others, like “var”, etc. Microsoft works on improving C# language.
C#
public double[] Parameters {get; set;}
Java
private double[] parameters;
public double[] getParamateres(){
return parameters;
}
public void setParamateres(){
return parameters;
}
How important is your knowledge of IDE?
I would say that even more then knowing of language. Nowadays most of the languages are object-oriented, they all have similar principles and ideas and code looks almost the same. If we talk about C# and Java they are extremely alike.
I’m not very familiar with Java, but I can write Java code easily and if there are some Java specific gaps I quickly fulfill them with google search.
But when we talk about my speed of coding in eclipse IDE – it is really outstanding thing where my capabilities suck.
Code refactoring tool
That is another thing that could significantly increase your productivity. I’m using Resharper 5.0 Beta. Having experience of using it, I can think about what I want to have, but not how to type that.
Live templates that generates me unit test method after I just type “test”. Delivering from interface, I just created, without typing class name. Moving initialization of fields to the class constructor with single command. “Alt+Enter” just thing instead of me in contest of where mouse cursor is located and proposes me decisions. — these all are things why I love Resharper. I wrote complex architecture with about 40 classes in about 12 hours. It generates what I think.
Thing Two (Architecture)
I improved my Self-Organizing Maps implementation architecture significantly. What is did is having all implemented in really decoupled interfaces. Main learning processor is just like preparing dinner. You just add component and you do have what you want.
What is the benefit?
Now I’m able easily setup few dependency Profiles and experiment with them. So I can play with different activation, neigbourhood, metric and leaning factor functions, at the same time I can use different topologies like matrix and hexagonal.
Also learning process is now really encapsulated and to add Concurrency implementation should be easily.
Thing Three (I have same results with less effort)
To prove that I have same results I’ve used same application of my Kohonen Maps: classification of animals.
Here is input data list of different animals. Each row describes animal’s properties.
Here is result matrix:
Thing Four (Conclusion)
I’m really sorry that it is boring for me to have my Diploma written on Java. But I really think that my goal is to invent multi-threaded algorithm that could significantly improve SOM calculations. And I feel really comfortable with C#, so I can enjoy research work without spending time on convincing myself that I do need to accomplish all with Java.
But this doesn’t mean that I gave up with learning Java. No – I will continue implementing all GoF Design Patterns on this pretty language – see my table.
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.
February 19, 2010 NHibernate, QuickTip No comments
What do you see to be wrong with this code?
.Add(Restrictions.Eq(“r.Name”, ruleName))
//other restrictions
.List();
return result.Count > 0;
}
At first I did not see any issues with it so I copied it and changed a bit for my another query. But current method is wrong. I discovered this with UTs.
First, Projections.RowCount() generates COUNT(*) in select statement.
This is query, which I got from my new Unit Tests: RuleExists_HitsDatabase_ThereIsNoRule.
Result of this query is number of rows like on picture below:
So, verification return result.Count > 0; is absolutely incorrect.
I’ve chagned it to return (int)result[0] > 0;
Moral:
Do not be lazy to write Unit Tests both for success and failure sceneries.
February 15, 2010 NHibernate, QuickTip No comments
ORDER BY
To add “order by” to your criteria you need this statement.
.AddOrder(Order.Asc(“Priority”))
TOP
To add “top 10” to your criteria you need this statement
.SetMaxResults(10)
Criteria
So code about which I’m talking could look like:
SetResultTransformer or “Why did I get 5 results instead of 10?”
So you expect to have top 10 priority Customers with status Created.
In scope of my current task it was needed to add priority to this query, so I decided to unit test it of course.
In Debug I found that there are actually 5 results in resulting collection.
That is because generated SQL generates result which contains duplicated CUSTOMER_IDs, that is because I have join-s there. But then why did not I get 10 duplicated Customers? Because query has ResultTransformer which is applied after SQL has been ran. (That is 100% since I took a look at generated SQL via NHibernateProfiler).
So .SetResultTransformer(new DistinctRootEntityResultTransformer()) is removing of all duplicated entries of my root entity (Customer).
Good explanation to this you can find here.
February 13, 2010 Design Patterns 2 comments
Imagine that you are game developer. Your game is war stategy. Army has complicated structure: it consists with Hero and three Groups. When King gives decree to treat all soldiers (Hero is also soldier) you want to iterate through all soldiers and call treat() method on each soldier instance. How can this be accomplished easily and without diving into Army structure?
Iterator is the pattern which provides you a way to access all elements in any collection of data without exposing collection implementation.
So in application to our problem. You just don’t want to care about structure of your army – you want some SoldiersIterator to loop through all soldiers in it. Red line is the Iterator (in my mind representation).
Usage
Code below shows usage of iterator. We can loop through all soldiers and increase their health level without thinking of the structure of Army. This should be easy and it is main purpose of Iterator.
Army structure
Army structure has one Hero and could have many Groups which of them could have many Soldiers. So as we see structure of Army is complicated and tree-based. Code below represents instantiating of Army:
Hero is class derived from Soldier and has only one difference – higher health level:
public class Hero extends Soldier {
protected int maxHealthPoints = 500;
public Hero(String name) {
super(name);
}
}
SoldiersIterator
So if we can move through the complicated collection of Soldiers where is that complicity?
Well, it is encapsulated in concrete Iterator class.
private Army _army;
boolean heroIsIterated;
int currentGroup;
int currentGroupSoldier;
public SoldiersIterator(Army army) {
_army = army;
heroIsIterated = false;
currentGroup = 0;
currentGroupSoldier = 0;
}
public boolean hasNext() {
if(!heroIsIterated) return true;
if(currentGroup < _army.ArmyGroups.size())return true;
if(currentGroup == _army.ArmyGroups.size()–1)
if(currentGroupSoldier < _army.ArmyGroups.get(currentGroup).Soldiers.size())return true;
return false;
}
public Soldier next() {
Soldier nextSoldier;
// we still not iterated all soldiers in current group
if (currentGroup < _army.ArmyGroups.size()) {
if (currentGroupSoldier < _army.ArmyGroups.get(currentGroup).Soldiers.size()) {
nextSoldier = _army.ArmyGroups.get(currentGroup).Soldiers.get(currentGroupSoldier);
currentGroupSoldier++;
}
// moving to next group
else {
currentGroup++;
currentGroupSoldier = 0;
return next();
}
}
// hero is the last who left the battlefield
else if (!heroIsIterated) {
heroIsIterated = true;
return _army.ArmyHero;
} else {
// THROW EXCEPTION HERE
throw new IllegalStateException(“End of colletion”);
//or set all counters to 0 and start again, but not recommended
}
return nextSoldier;
}
}
Why my example is not standart and classic?
Because my goal in this article was to higlight the main issue that Iterator solves in such manner that it could be easily understandable. And second reason is that you can read tonns of standard explanations of this Design Pattern.
Main difference between my explanation and others is that classic explanation is more abstrated, it contains abstract Iterator which represents interface for concrete ones, and abstract Aggregate, which creates Iterators needed.
The way I created Iterator looked like
But generally this logic could be hidden under some Aggregate’s method (like GetEnumerator in .NET). For example I could have this:
In .NET world we have IEnumerable<T> and IEnumerator<T> interfaces which provides a lot of help in impementing this pattern:
In Java we have java.lang.Iterable instead of IEnumerable, which is more intuitive naming. I think that Microsoft just wanted to be original in this :).
February 10, 2010 Success, Ukrainian 4 comments
This post is in Ukrainian and is translation to the Things you need to remember to become successful developer
1. Не переставайте вчитися
Я припускаю, що ви навіть б не читали цей пост, якщо б не мали хоча б елементарної освіти, і ви б навіть не хотіли знати як стати успішним програмістом без вищої освіти. То ж якщо ви зараз програміст навіщо зупинятися вчитися?
Це просто недозволено. Одна важлива річ тут: Стояти на одному місці не означає, що ви стоїте на місці – це означає що ви рухаєтеся назад. Просто рухатися вперед не означає що ви рухаєтеся вперед – це лишень означає, що ви не загубилися із невдахами десь в кінці. Щоб просуватися вперед вам слід вчитися постійно – не просто рухатися, а БІГТИ.
Ось мій короткий список, що підпадає під цей пункт:
• Читайте книги
• Підпишіться на RSS і читайте різні статті
• Пробуйте різні мови програмування і речі, про які ви чули
• Ходіть на семінари і готуйте власні презентації
• Вчіть будь-що, що може вам допомогти просуватися
• Вчіть інших, так як це вчить вас
2. Визначте вашу ціль і тримайтеся правильної дороги
Я думаю що важко бігти якщо не знати куди бігти. Основне завдання полягає в тому, щоб чітко уявляти свою ціль. Ваша ціль повинна бути довготермінова і велика. І після того як у вас вже є бачення своєї мети візьміть і розбийте її на дрібні завдання – тобто побудуйте свою карту до успіху. Вам слід скласти список завдань, які ви ПОВИННІ виконати за місяць, або за рік. Як тільки ви його маєте, просто чітко слідуйте за ним.
3. Будь-які проблеми є можливостями
В буденній роботі ви завжди стикаєтеся із різними траблами. Ви отримуєте нові завдання або звіти про баги від тестерів. Ви отримуєте нові проекти від Проджект менеджерів. Ваш співробітник запитує про допомогу. Вам потрібна допомога. Це все приклади проблем. І справді важливе питання тут таке: як ви зустрічаєте їх? Ви можете сказати «Ой, але так я не позбавлюся від дурної надоїдливої роботи». Ви тут абсолютно не праві. Запам’ятайте, що ваші боси будуть раді дати вам більш складну роботі як тільки побачать, що ви справляєтеся із поточними завданнями.
4. Будьте позитивно налаштовані
Ви повинні дивитися на все позитивно. Якщо ви виявили, що зробили помилку просто сприйміть це легко – кожен робить помилки. Вам подобаються люди, які ниють коли у них проблеми? Як ви думаєте ви будете виглядати у чужих очах, якщо ви скажете: «Так, хлопці, я це зробив – я це вирішу, дайте мені хвилинку» і опісля ви повертаєтеся і починаєте фіксати вашу помилку із усмішкою на лиці. Як тільки ви вирішите проблему ви будете просто щасливі.
Ваша дорога є хорошою і ви швидко рухаєтеся вперед. Ніколи, ніколи не думайте що ви не досягнете своєї цілі – ось суть цього пункту.
5. Знайдіть наставника
Це не означає, що вам потрібна людина, яка буде вам допомагати робити вашу роботу – бо це просто вчитель або ж більш досвідчений розробник. Це означає що вам потрібна людина, яка знаходиться там, де ви хочете бути. Вам потрібно брати приклад із цієї людини. Якщо ця людина недостатньо високо – просто знайдіть когось по серйозніше. Також майте друзів які будуть вам допомагати рухатися по шляху. Або просто користуйтеся підтримкою жінки або дівчини.
6. Ставайте відомими
Якщо ви не покажете іншим, що ви крутий і що ви заслуговуєте більше, як вони будуть про це знати? Є просте рішення – почніть вести блог, запитуйте і відповідайте на питання, переконайтеся що гугл знає вас. Поширюйте своє знання у вашій команді і на проекті. Якщо ви вивчили щось нове, то чому б не поділитися цим? Ви забудете ці нові речі, якщо ви не будете їх пробувати.
7. Слідкуйте за виконанням ваших завдань, будьте певні, що ви й досі на шляху
Час від часу слід перевіряти чи ви робите все правильно. Впевніться, що ви виконуєте поставлені задачі. Якщо ні, то швидко знайдіть причини і працюйте над ними. Знайдіть свої слабкі сторони і змагайтеся із ними. Це може звучати смішно, але я знаю хорошого програміста із добрими теоретичними знаннями, але його швидкість набору коду просто жахлива. Чому? Тому що в нього просто жахлива клавіатура і він не хоче провести 10-20 годин за тренажером. Хіба це не тупо? Друже, якщо ти будеш читати цю статтю, пообіцяй що ти переможеш цю слабинку.
8. Робіть гімнастику
Я зробив маленьке само-опитування, коли писав цю статтю. І «Робіть гімнастику» попало у список. Я є досить молодий і проводжу забагато часу за ноутбуком і за іншою машиною на роботі і я не можу заставити себе робити гімнастику. Але це як точіння леза. Є така історія про двох дроворубів які поспорили про те хто зрубає більше дерев. Один дроворуб був здоровий і великий, а інший худий, як я. Сильний був певен, що він переможе, оскільки він рубав дерева всі 8 годин без жодної перерви, а худий робив перериви на 15 хв. кожної години. Але боротьбу виграв худий – він зрубав 150 дерев тоді коли Силач зрубав 100. Секрет полягав у тому, що він точив лезо тоді коли відпочивав. Ваше здоров’я – це ваша сокира і якщо вона буде тупа ви не зможете вирубати собі дорогу до успіху.
Тому нехай всі ваші сокири будуть заточені!
February 3, 2010 NHibernate No comments
I have table CUSTOMER
where CUSTOMER_ID
is primary key.
Table
Mapping
I need to handle assigning of the CustomerID property manually. For
example I created new Customer with CustomerID = 777 and Name
= “Andriy Buday”.
When I call method Session.Save(customer);
I want NHibernate to generate me SQL like this:
Unfortunately I’m getting errors.
Main issue here is that Nhibernate tries to generate ID for me. But I want to save my entity exactly with 777.
Solution
So I need to manually setup my ID property with adding GeneratedBy.Assigned();
Like here: