My talk at #kievaltnet about NHibernate internals

December 4, 2011 Conferences, NHibernate, Presentation, Success 2 comments

Friday I’ve been in Kiev, the capital of Ukraine. At the beginning of the day me with my wife visited couple of shops to buy some special things my wife makes. And than we went to have a good sit in small restaurant till 7 PM. I had to finish up my presentation…
Recently I’ve mentioned that I will be speaking at Kiev ALT.NET. So this post is about it.

Kiev ALT.NET

Kiev ALT.NET is great group of smart people willing to learn interesting things in .net but maybe from deeper standpoint than standard .net user groups do. I’ve been having good conversations in twitter with @chaliy and once we met at UnetaPlus in Kharkiv where he invited me as speaker to the @kievaltnet. Peliminary we agreed on something about NHibernate.

The topic

I knew that I have to prepare something interesting on NHibernate. But what? There are dozen of articles on it, there are many videos available. Topic just came itself. You might know that I’ve been working with NH for long time already and that I’ve written something similar to ORM so I decided that getting some insight into NHibernate’s guts would be really interesting.

Presentation delivery

So before 7 PM I got to the Ciklum office (building on the left). Landscapes from the 20th floor are astonishing, especially at night.
image
Not sure if I was enough prepared, but at least I felt that guys were listening to me very-very attentively. Some of them twitted simultaneously (@alexbeletsky, @skalinets, @korneliuk) and had good laugh. At least I invented term “swiss breakpoint” (aka. conditional breakpoint with cross).
image
More photos can be seen on facebook’s page here of the Kiev ALT.NET group.
Also I tried to joke much, but it didn’t go as well as I expected it to, guess because of sleepless night and general tiredness. Also I spoke with accent (as per them o_O. Never thought I have any kind of accent of my native language).

Presentation itself

View more presentations from Andriy Buday.
I would like to thank all guys, who came to listen to me and other presenters. Thanks for having me at Kiev ALT.NET. It had been great time and I would like to be there once again despite reason (to speak or to listen).


2 comments


I have written another ORM: customorm.codeplex.com

November 29, 2011 Uncategorized 5 comments

Yes, that’s truth. World now has yet another ORM system written in .NET. Again someone (me) reinvented the wheel. Why?
Before you started abusing me, let me provide you with some insight.

Of course there was need for this ORM to be born

I’ve been working with NHibernate for manner of couple of years. I would say team got used to it. Few months ago we’ve got challenge to integrate some of our code with legacy system. It is written in Delphi, but exposes some .NET stuff. Underlying data provider was legacy cache system (relational) covered with Delphi and bit exposed in .NET, also cache was capable of switching to SQLServer when in connected mode. When we decided to integrate our system with this legacy code we had to come up with solution that utilizes existing WCF (!) entities for mapping, solution that can call legacy code with correct select sql statements depending on connect mode and can handle update/insert/delete for the object graphs utilizing legacy interfaces.

Long story short, we ended very much with these three methods. Some other methods are also available, but I’m showing this for more rush:

object InsertUpdateRow(string tblName, IEnumerable fields, IEnumerable fldsValues, IEnumerable keyFlds);
void DeleteRow(string tblName, IEnumerable fieldsList, IEnumerable fieldsValues, IEnumerable keyFields);
DataTable SelectSQL(string selectSql);
This doesn’t look like exposing a lot of possibilities. We had option to go with naked SQL, than mapping from DataTables to entities reading data with DataReader. And all manual. Isn’t it boring and too-oo-oo much code?

It is fun to work on ORM, so why not take it further

For me it was really nice work to make that whole reflection and data access working smoothly. So I tried to have my code as much abstract as I can so it can be isolated somehow from that legacy and separated code for my personal project very early. Some of the features I had to recode at work, some at home. Instead of “IntegrationDataAccess” I wrote simple AdoDataAccess over mine IDataAccess and got it more or less completed.

I think it is part of my learning curve, to write this project. I’m learning what it means to start something open source, how to use yet another source control. Playing with hardcore reflection and other not-business logic code is real fun.

Another thing why I would like to make it open to the world and not mine home-hidden project is being exposed to more job opportunities. When you are at interview you often have no code to show, because all you’ve written is production and you signed papers forbidding you to show that code.

So… here it is – CustomORM

CustomORM is tiny ORM system written in .NET. CORM is slightly bigger than so-called micro-ORMs and much smaller than NHibernate. It has its uniqueness.

Features at glance:

  • POCO (real POCO without any “virtual” constraints or attributes)
  • Mapping much like FluentNH
  • Very light, thus faster
  • No syntaxes to learn (nothing like complex criteria or another version of sql)
  • Source code in your project you can debug, and change quickly

Now, let me show you some code

Sample fetch

Here is how select works:
           Criteria criteria = CreateCriteria(typeof(Customer), "c")
                .AddEntity(typeof(Order), "o")
                .AddEntity(typeof(Employee), "e")
                .AddSQL(
                        @"left join Orders o
                        on c.[Customer ID] = o.[Customer ID]
                        left join Employees e
                        on e.[Employee ID] = o.[Employee ID]
                        where c.[Customer ID] = @customerId")
                .AddParameter("@customerId", customerId);

            List<Customer> customers = ExecuteCriteria<Customer>(criteria);
As you can see you add type of entity to take part in join, assign alias to it and then write old known SQL. In the end you get nice collection of objects. No root transformations to be applied.

Sample save

Here is code you might write for the save:
        public Customer SaveCustomer(Customer customer)
        {
            var transaction = BeginTransaction();

            Customer savedCustomer = null;
            try
            {
                savedCustomer = Save(customer);
                transaction.Commit();
            }
            catch (Exception)
            {
                transaction.Rollback();
            }
            
            return savedCustomer;
        }

Mappings

All this above will work after small setup and mappings for your objects.
    class CustomerMap : EntityToTableMapper<Customer>
    {
        public CustomerMap()
        {
            Table("Customers");
            Id(x => x.CustomerID, "Customer ID")
                .UseAssignedValue();
            Map(x => x.CompanyName, "Company Name");
            Map(x => x.ContactName, "Contact Name");
            Map(x => x.ContactTitle, "Contact Title");
            Map(x => x.City, "City");
            HasMany(x => x.Orders, "Customer ID");
        }
    }

Get started code

To get started all setup you need is basically two things: derive you own Repository class from RepositoryBase and add bootstrap code at start of your app similar to this:
// Let CORM know where your mappings live and that's mostly it
MagicMapper.ScanForMappers(Assembly.GetExecutingAssembly());

// Initialize AdoDataAccess or (advanced) implement your own IDataAcces 
var s = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"];
var ceDataAccess = new AdoDataAccess(s.ConnectionString, s.ProviderName);

// You are ready to use you repository, it already has Fetch<T>, Save, Delete 
var customerRepository = new CustomerRepository(ceDataAccess);
Hope it doesn’t look like much code.

What is at codeplex now and what’s next?

As for now I have CRUD operations tested on Northwind SqlCe database. I verified that fetching 91 customers (2000 db records) is 2-3 times faster than NHibernate.

Project still lacks very much in transactions/sessions/concurrency and completely doesn’t have caching (I don’t think it should ever have).

Project has bad code coverage and probably isn’t ready for community review until I polish it. But anyway sharing this with you because someone has to kick-me-off.

If you still would like to take a look at some code please start with CustomORM.Examples => Program for usage code and for engine code go to CustomORM where most of the heavy logic lives in RepositoryBase and EntityToTableMapper.

Depending on feedback and my mood I will decide if it worth investing more of mine time or not.


5 comments


Mobile Professional Days in Kharkiv – it was fun time

November 21, 2011 Conferences No comments

Passed weekend I’ve been at Mobile Professional Days conference in Kharkiv (again).
mpdays2011_Logo
Shortly conference worth time I spent for it, but not that much because of the information I got there, but rather more because spending lot of time with my friends. We had to travel overall about 40 hours. We had two laptops (one air), two kindles two iPads, one iPhone and one HTC wp7 to play with. True geeks in occasionally-connected environment, called train, and then not so starry hotel as it should have been. Reading books while travelling and tweeting much during conference itself brought feeling of not wasting time. Ah, and of course tasty coffee-breaks were awesome.
Really nice and modern monument at the entrance of Kharkiv university hosting conference. Cool!
WP_000014
Some other photos from conference itself can be seen here.

My thoughts on each presentation

Now, let’s be more serious. I will be critical in this post, so don’t share this with speakers :).
I will list only those presentations I’ve attended. (Also as conference was in Russian, I’m translating titles of presentations so sorry if I translated not as you like.)
1. Flexible methodologies for Mobile projects
Honestly it was completely not I wanted to hear here. It was simply well organized presentation about usual methodologies used in every day that can be applied to any project. Distributed teams, scrum, team work and people motivation are general topics not specific to Mobile. Only one thing I liked was about having phones for each developer.
2. iOS development, first steps
Ok, this one was about its topic and overall very interesting despite I didn’t know a lot of things about iOS.
3. Mobile games – development is just half of the deal
Great presentation and great presenter. Real game publisher talked around pitfalls and other stuff you have to overcome to make your game successful in your marketplace. There were some real examples, statistics. Was really very interesting to listen to this man.
4. Game “Stay alive in mobile”
Blonde (Olga, sorry) went though good and bad examples of design for applications. She let everyone know that you have to take into account dozen of variables to create really usable application. You should even think about length of users nails. I think this presentation was great and easy for consumption.
5. Best of the XCode 4.2 and iOS 5.0 from the developers view
I didn’t get this presentation. Definitely because I know nothing about iOS and XCode. Anyway, at least it is useful to feel myself a stupid idiot time to time.
6. How to make good and mobile in one bottle
Guy from JetBrains, discussed different design approaches for the iOS and Android phones. He touched many interesting aspects of designing good applications. I was bit disappointed that he didn’t say much about new metro style in wp7. I think it is great and not everyone caught it yet.
7. RESTfull iOS with RestKit
This sucked! No, really. I understand that another person had to substitute original presenter, but why wasn’t he ready and why slides had tons of code. Crap, not presentation. Message to presenter: don’t be disappointed by what I said, you had hard time so you know next time you have to perform 100 times better. I’ve been in similar situation and it sucked as well, but I had auditory 10-20 times smaller.
8. Evolution of mobile apps. Though Could and Social into Mobile 2.0
This presentation was as manna from the heaven after REST-laugh. I got a lot of interesting information on social integration. Auditory had some fun when on slide appeared app for gays.
9. Guidelines isn’t limitation
How getting slightly away from official UI guidelines can take you out of the crowd of the other apps. Presenter showed great examples when new awesome design was born because of this. Also he gave good feedback about metro design for wp7 and well-documented guidelines.
10. How to speed up and reduce the cost of developing mobile apps
Maybe the best presentation and delivery. It was smooth and easy to listening to. At this presentation I got some feeling of HTML 5 as the future for the mobile development.

Fun with tweets

Great that there was twitter board. It kept good mood even when it started to be boring. To help you feel general atmosphere during the #mpdays2011 below are my tweets chronologically (you have to be able to read Ukrainian):
At #mpdays2011 in Kharkiv. Hope it worth trip over 1000 km.
#mpdays2011 Перекличка. Я #wp7! Хто ще?

#mpdays2011 Не хочу бути занудою але всі ці речі загальні для будь якого типу розробки. Де спицифіка розробки під мобільні платформи. #q
@caxarock #mpdays2011 Scrum це гнучка методологія. :)
#mpdays2011 О! Останній слайд із пляжем мені сподобався.
@UkrDaddy А не по кількості людей? Там цікаво про #wp7? #mpdays2011
Ситуація із кнопкою не того розміру або не там дуже знайома. #mpdays2011
За якоюсь історією мало бути 42 а не 7. #mpdays2011
А нашим клієнтам радять тримати телефон на зарядці в автомобілі поки вони виконують роботу. :) #mpdays2011
Таке враження що на #mpdays2011 одні студенти. А де бородаті дядіньки?
@eGoOki ти мене заплутав. Я #wp7 прийнов на #ios і був певен, що там цікавіше. #mpdays2011 хм…
Хочу побакланити презентацію по restkit. Що за слайди із тууучою коду? І що він там говорить… КАПУТ!#mpdays2011
#mpdays2011 Презентеру влаштували інтерв’ю. Таке враження, що ті хто запитують знають відповіді. Тупо фейл…
Музику врубали, щоб блондинка із першого ряду станцювала. Єуех… Давай! #mpdays2011
Про #cloud і #social цікаво. Принаймні Тарас доповідає впевнено! #mpdays2011
@Alokard #mpdays2011 Якщо доповідач толковий, то твітеряни це помічають. Не було б сміття в ленті.
At #mpdays#2011 I understood that the coolest platform is #wp7 not because of presentations, but because of using actual phone here!
Listening to #iOS UI guidelines. I think #metro in #wp7 is much better. #mpdays2011 (I know ’cause I’m using it & it rocks.)
Нас зомбують 25тим кадром із сіськами :) #mpdays2011
Man called C# a bubble! O_o Java isn’t bubble than? #mpdays2011 Crap is it going to be HTML and JS?

Thanks for reading…


No comments


Speaking at Kiev ALT.NET

November 18, 2011 Conferences No comments

I’m going to speak at Kiev ALT.NET preliminary at 2 of December.
I would like to share some of my knowledge and findings around NHibernate from its inner perspective.

NHibernate from inside

“I have been working with NHibernate for manner of couple of years and I never seriously thought about how it is built from inside, what is the architecture of NH, how much it depends on ADO.NET, how they made reflection to work fast, how high code quality is, which people worked on it and what was the history of it. The other day, I had chance to start mine own small ORM project and all of this questions raised for me. Thus I will do my best to share everything I discovered in NHibernate surgery.” – Andriy Buday

NHibernate зсередини

“Вже декілька років я працюю із NHibernate і ніколи серйозно не задумувався як він побудований зсередини, яка його архітектура, наскільки сильно він використовує ADO.NET, яким чином уся рефлекція працює швидко, на скільки якісним є код, які люди працювали над ним та яка була його історія. Надавно я мав шанс розпочати невеличкий ORM проект і всі ці питання згадані вище стали надзвичайно цікавими для мене.
Тому буду викладатися на максимум, щоб поділитися усіми відкриттями хірургії нутрощів NHibernate.” – Андрій Будай
Лінк на профіль такий: http://andriybuday.com


No comments


Leaving my first job – it was awesome time

November 15, 2011 Career 17 comments

*** NOTE: I’m not mentioning surnames of people and any trademarks or company names directly, you have to guess or just know ***
Today is going to be my last day with my current employer. I worked for this company for more than 3.5 years. During this time I worked with many great people and I absorbed unique experience. In this post I would like to express some of my thoughts about these years and to thank to many people surrounding me during my journey.
Don’t read this paragraph! What do I feel about leaving SS? Nothing special, like if this is something usual. But it is not! For some reason cannot believe this is reality and honestly maybe I feel myself bit stupid at the moment, I just had a glass of whisky for kick-off and I continue to write to finish this up. I feel that I will manage this if I continue writing. Definitely! …or I will get drunk. No way! I have code to commit today!
 

I BEFORE

It all started one day at University, when I took part in programming competition. I often took part in such events, because I love programming, but that day was different, not because we had difficult or simple problems to solve and not because we won or lose, but because of banal reason – sponsor of that competition was SS. I even didn’t understand what the hack is software company. They only asked to fill-in simple form and me as “real” student filled it with all the “rules”, knowledge in C# 10 out of 10, VS 10 out of 10 and other stuff and I wouldn’t even put 6 now.
Some time passed and I got e-mail in which I was kindly asked if I’m not interested in passing interview for developer position. I just said to myself like good American could have said “Why not?”.
I guess mine interviewer was in good mood that day or either, I was too much emotional talking about the applications I wrote in University about the “game of life” completely written in WinAPI, and especially about the database management system written in C#. Anyway somehow I intrigued him. He asked me what I like the most about programming. I don’t why but I said that databases are great thing (stupid me?).. anyway that answer decided where I spent next 3.5 years.
At that moment I was student and additional 350$ for me was a big sum to get each month (not to say that I had good scholarship, and during master’s year it was about 100$ and I managed to live for those 100$ easily). After I had some conversation with parents. They didn’t want me to work while I’m still student. They were worrying much about my future studying and asked me if I’m not willing to postpone this decision, but nevertheless I was mine decision and in the end it turned to be very and very good decision.
 

II THE BEGINNING

I was promised flexible time. During my first 3 months I got trainings on the product team was working on (I have to say this product is damn huge enterprise solution to set of complex problems). After 3 months nightmare started I had to work 8 hours a day and I did my best each minute, I was so worrying about completing everything in time. Everything was new to me – source control, team work, issue tracking, testing, and scary super-smart people everywhere. Honestly I was just very scared. I had girlfriend at that time, I’m now married on, very often she was called by me and often I said to her that I simply cannot solve something and I worry very much and that I probably worth nothing, and that it probably cannot be solved easily. I used to spend extra-time on solving something that now looks ridiculous for me.
First real tasks assigned to me were simple bugs and tiny enhancements to existing reports/assessments.
I was given contact to clients at that moment and first person from clients I talked with was Johnathan. In our conversation I was stupid enough to mention that I’m still student, finishing university. But he was wise enough to understand and he said (sorry cannot remember that precisely) “You started a big journey and I’m one to help you”. At that moment I understood that my clients are my friends. Thank you, Johnathan, for this.
I worked hard on everything assigned to me. Not me one, I thought that everyone around is just insane about making everything the best he/she can. I was inspired.
Than New Year came (2009) and we had celebration in some restaurant. I got an award there – “Rookie of the year 2008”. Below you can see me (sorry for my blackness “he-he”) and my manager.
It was my first work award and I’m really proud of it, because at that moment I realized I worked hard for something more valuable than money, I worked for respect of other people and I worked for our clients and for myself.
 

III CONTINUATION

After that I continued to work for the same company and for the same clients. Sub-projects only slightly changed. I had a chance to work with great people, with people who inspired me even more, especially as software developer. Derik was another person I really appreciate. I learned a lot from him. He gave me many advices that were very helpful and completely new for me from the root. Those advices were, and are, tremendously terrific.  Thank you.
I clearly remember Ant as wise and supporting product owner, I learned many things from you as well. Things were more personal and people-oriented not so “techi”, but I want to thank you for this.
I worked with different people during 2009 and 2010, some of them were very smart some not, some were extremely responsible and some not, some people didn’t know what they want from work and life and some knew. I just had been watching all that and learning and learning. I wanted to be like someone else and didn’t want to be like someone else.
During those two years I managed to be promoted twice up to senior developer, I started this blog at October of 2009, I showed myself as responsible, knowledgeable and  reliable developer but my learning curve started to be more domain related than technology related. See below.
Black line corresponds to my domain knowledge which continuously grew and red line corresponds to what I learned from tech perspective (at the beginning I got trainings on application along development started and then I started to learn less from technology than from domain). Thus I decided to change something.
 

IV NEAR THE END

I went to the Mobile team. It still the same company and still the some client, but just another project – mobile solution for same set of problems. But I think this was the best period of me being in this company.
I think Mobile team is the best team I ever worked with. Almost everyone is self-organized, motivated and very responsible. I really see fire in eyes of each person working with me in the “war-room”. We cook the best meat for the end-users which is friendly usable and “sexy” mobile application.
Taras, another TL (not usual team that had two TLs of course), very emotional person who knows his point of view, but always manages his and teams work the best. I especially enjoyed working with you. We had more conversations I had with other guys at SS ever.
Andriy, Olena, Pavlo, Roman, Sasha, Volodya, Yuriy (hope alphabet works this night) you are great people. Each of you has something special, each different, but all of you spent part of your life for this project, each worried about the work you do/did and I hope everyone enjoyed great collaboration we had.
Diana, Iryna, Oksana, Taras, Zhanna and many others who covered the stuff developers created or still need to create. Thank you very much for the great work and contribution. We all can create something brilliant only together.
And of course many thanks to our clients. In reality everyone I worked with from clients side were just amazing people. I know stories from other developers from other companies and completely other teams, they often complain at their clients. I think that you can only dream about clients my “big team” has. They understand you and they try to work collaboratively to produce the best results. Sheryl and Mark Mobile team loves you!
I would also like to mention that I had very good management above me. They are people who think wide, clearly and who see far-far into the future. They are people who kept me motivated and oriented for achieving goals. Vitaliy, Sania and Alex, thank you very much.
Whole “big team” as I call my unit of company is great family. Many people work here for 5 and more years, some more than 10 years. I hope I was somewhat part of this family for these 3.5 years.
 
I MISS YOU ALL!

I’M PROUD I’M SS!
 
——————————————————————————————-

V THE END

In Mobile team I simply continued to do my best just at another level of abstraction, doing some of the activities as technical leader, performing some bit more complex tasks, that I think could have been achieved by others. Sad, but as per me worst thing about this was this graph below. My red line didn’t grow up above black one.
I’m developer from my very inside. I’m not ready to shift my career to another direction and I cannot continue to learn domain I’m not ready to accept as my native. I want to continue as technical guy, but that is not the whole story.
Of course SS has opportunities for me. I bet they have opportunities to many of you. I wouldn’t leave this company if someone proposes me bit more money or bit more interesting project, because all this I can get here. So…
 

VI THE FUTURE

I cannot say much about it, because I’m not completely confident in its direction. I can only say that I have opportunities in another country (Western Europe) and I will start there as intermediate developer. They looked for talented developer, and I hope I’m such developer. They ensured me that I will have much-much to learn and I’m extremely glad because of this and and also I’m glad that I will have opportunity to live in another country to learn something absolutely different from life perspective. Also if everything goes well I will learn one language more – German additionally.
I didn’t waste my past time. I’m excited and scared about the future, but I’m looking forward it!


17 comments


Hackathon “WP7 Rocks!” – we won

November 1, 2011 Success, WP7 6 comments

I would like to share some of my experience and impressions of taking part in “Windows Phone 7 Rocks!” Hackathon in Lviv.

An amazing event

 
First of all, many thanks to the organizers of this event and to the sponsors. Event was really great. Everyone got presents, food and joy of playing kinect at free time and of course tons of intensive coding. Hackathon started with helpful and resourceful presentations delivered by organizers. Two of them were about stuff I think wp7 developer must know – metro design and publishing to marketplace. And I would like to correct myself by replacing “developer” with “Ukrainian developer”, thing is, it is not easy for my country to be appreciated by Microsoft. Other two were about working with data in Mango and augmented reality. Ah.. and forgot to mention that everyone got styling wp7 t-shirt, finally I’ve got one! Awesome!

Hackathon is programming, team, fun and creativity

I hardly remember any other day when I had such intensive programming time. Not to say that I didn’t have sleepless all-night coding, but I was somewhat relaxed, making tea time to time surfing internet when realizing that copy-paste is no longer working. It was different, it was team play.
As you may know at the moment I work on enterprise WP7 project and my team has 8 developers. 6 of us took part in the Hackathon which formed 2 Hackathon teams. I cannot express well enough how much this night made us more closer to each other and how extreme team-building it was. But I strongly ensure you that it worth each minute we spent together coding two great ideas to be presented next day. During the night we did 125 commits to the source-control (4:59PM first commit and 11:22AM last commit). Can you imagine such productivity of the hired people? Never. Of course no one can work such intensive for long time.
So here we are:
6 most closest people. Sorry for two of them not looking at you and for me also – I’m busy.
On Monday our scrum master sent congratulation to us and here is how it looks like:
Hold on for a second. Winners? Yeap! But wait for a second. First things first.

Applications developed

At the moment there are no presentations available in the internet or video, so I cannot say much about other teams. Hopefully I will update this blog post soon. But I can remember many great applications developed by others, such as handy cartoon-creator, quest generator and player, travel places logger, guitar tuner, ball game, and many other nice applications. 3 of us created “real-problem” solving application – “WC Emergency”, which by it’s idea exploded auditory: when you really have “need”, you start app and answer 2 basic questions “How long can you wait?” and “How fast can you run?” after which you get the most reachable WC.  Some other team even managed to create 3D game, to the last moment I thought they will take first place. For the complexity they probably deserve first place, but…

Winners!

image

We managed to create something more exciting. We invented pure FUN. So other 3 of us created mini-game “Face 2 Face”. Splashscreen below:

 
After which you get selection for the single player or multiplayer mode:
 
For the single player you can play with blue-red balls or can load images instead of blue or read ones. Here single player simple mode:
 
Idea is simple – you keep friends on the battle-field and throw enemies out of it. Physics for two-kinds is different, I will keep it in secret.
But joy begins whey you selected multiplayer, took pictures for your team (faces cropped) here:
 
Found other guy willing to play with you. He takes pictures for his team on his phone (!). Game starts and you both have all pictures. You throw his guys and keep yours, he does the same for his team.
 
That angry bomb also has something to do with the game, but it is secret.
I think me and Taras managed to impress people when we started taking photos of them and playing with those in front of the auditory. Great that we had server-side coverage by Roman.
I bet this gave us new emotions and inspiration for the future. We also got HTC Mozart phone as present.

Thanks

Everyone was really pleased and despite those sleepless-red-eye-faces it was clearly seen that no one was disappointed of spending 24h non-stop coding.


6 comments


WP7 Mango and NUnit from console

October 22, 2011 HowTo, NUnit, UnitTesting, WP7 3 comments

If you are building Windows Phone application you probably have faced… well… not rich support for unit testing. But of course there is one rescuing thing – WP7 is almost the same Silverlight application. Thus you have wider area to search for solution. Awesome… but I wouldn’t write this blog post if everything is that easy. Right?

 

Support for NUnit and command line

Microsoft for some reason doesn’t care about huge community of those who use NUnit for their projects, and believe me not for small projects. So there of course is mstest project template that allows you to run tests inside of the appropriate CLR. There is good Silverlight Unit Tests Framework and here is information on how you can cheat in order to get it working for the phone. Problem with these two frameworks is obvious – they are not supporting console – they run in native for Silverlight environment – either on phone or in web. See pictures (phone and web respectively):

image

I know that there are ways to make it happen from console under (msbuild for example this temporary wp7ci project on codeplex). Hold on… one second. Again something very specific to Microsoft – msbuild. But what if I’m using nAnt?

Of course there is port of the NUnit for the Silverlight (here is how), also you can change tests provider in the “Silverlight Unit Tests Framework” (further SUTF).

Nevertheless summary is simple – no support for running nunit tests for the WP7 from command line.

 

Support for command line – solution

I came up with odd solution to force nunit-console to run unit tests in command line. After I observed it crashing with error TargetFrameworkAttribute I reflected mscorlib and googled a bit to discover this attribute exists in mscorlib of 2.0.5.0 version, but nunit actually targets 2.0.0.0 one (.net 2.0). Thus I decided to download sources of NUnit and recompiled those against .net framework 4.0 (mscorlib 2.0.5.0). Reason for this error is that Silverlight also uses higher version of mscorlib.

Awaiting for NUnit 3.0 which is promising to have support for Silverlight.

 

Support for Mango – problem

Before upgrading to Mango our tests for WP7 were created by testDriven (to be honest – it is what they use inside of their SUTF). We didn’t have support for command line and tests were running only because they are so Silverlight compatible.

With updating to Mango everything just died. Tests projects simply didn’t get loaded into solution. With this message:

image

“Not a big deal” you say. Actually a big deal, because you can get rid of this message by editing project files to have target framework profile set to WP71 and to reference only WP71 assemblies. But in this case you lose all of you compatibility with Silverlight and when you run your tests you start to get weirdest exceptions in the world like this one below:

System.DivideByZeroException : Attempted to divide by zero.
at System.Collections.ObjectModel.ObservableCollection`1..ctor()

At least this brings some more sense:

System.InvalidProgramException : Common Language Runtime detected an invalid program.

 

Support for Mango – solution

Solution I came up with is not 100% right, but at least it works. I just had to pretend that I’m still completely compatible with Silverlight. So I created copy of my project. One is considered to be used from command line and other for usage from VS.

Project 1 is used under VS has correct references directly to WP71 assemblies, like below:

    <Reference Include="System.Windows">
<HintPath>..LibrarySilverlightWP71ReferencesSystem.Windows.dll</HintPath>
    </Reference>

This ensure that VS loads your projects without errors, also you make it think it is WP7 by these:

    <TargetFrameworkProfile>WindowsPhone71</TargetFrameworkProfile>

and this:

<Import Project="$(MSBuildExtensionsPath)MicrosoftSilverlight for Phone$(TargetFrameworkVersion)Microsoft.Silverlight.$(TargetFrameworkProfile).Overrides.targets" />
<Import Project="$(MSBuildExtensionsPath)MicrosoftSilverlight for Phone$(TargetFrameworkVersion)Microsoft.Silverlight.CSharp.targets" />

Project 2 is used for console and is pretended to be pure Silverlight, so it has:

    <Reference Include="System.Windows">
            <Private>True</Private>
    </Reference>

Which in reality copies (because of <Private>) wrong assemblies – from Silverlight, not from phone.

You would need to play a lot with which assemblies you want to get in folder where you run tests. I do have some confidence that Silverlight and WP7 are much compatible thanks to this brilliant explanation of what is WP7 from developer’s view.

 

Results

image

At #1186 I finally got build working and running tests. At #1193 I invented this Silverlight pretending trick. And finally till build number #1196 I ignored couple of incompatible tests and fixed some really failing tests.

Hope this helps someone. At least it is going to help my team.


3 comments


Why am I angry at developers? Is it factory? Is it testable?

October 17, 2011 Design 4 comments

Please take a look at this code snippet. What would you say about it?

    public class TreatmentDataProviderFactory
    {
        private IDataAccess _dataAccess;
        private TreatmentDataProvider _treatmentDataProviderHost;
        private TreatmentDataProviderField _treatmentDataProviderField;

        public TreatmentDataProviderFactory(IDataAccess dataAccess)
        {
            _dataAccess = dataAccess;
        }

        public ITreatmentDataProvider Provider
        {
            get
            {
                if (SomeInteractionSingleton.PluginHost.GetWorkMode() == WorkMode.ConnectedMode)
                {
                    if (_treatmentDataProviderHost == null)
                    {
                        _treatmentDataProviderHost = new TreatmentDataProvider(_dataAccess);
                    }
                    return _treatmentDataProviderHost;
                }
                else
                {
                    if (_treatmentDataProviderField == null)
                    {
                        _treatmentDataProviderField = new TreatmentDataProviderField(_dataAccess);
                    }
                    return _treatmentDataProviderField;
                }
            }
        }
    }

Doesn’t it smell bad a lot?

1) Let’s start with obvious: properties in C# are not intended to be 10-20 lines long and having complex logic. Anyway I won’t wrote post if this was a problem.

2) Now the worst mistake here: how am I supposed to test this code if it uses SomeInteractionSingleton in the if condition. Why should this code be so coupled to SomeInteractionSingleton? I wrote this post because developer didn’t run tests. If he ran the tests, he would see they fail.

3) Now second bad mistake: this code keeps two instances of data providers. We can suppose that this is storage for two providers or something? :) I think GC is designed for something and lifecycle of objects shouldn’t be treated as this. I thought IoC is invented for something like this. At least developers should not keep code that much coupled and deliver creation logic.

4) Another mistake: Is this a Factory Method design pattern? – Almost. At least it has such name and looks like it (a bit). But it doesn’t meet either its original definition or either Parameterized Factory Method definition.

I redesigned this class. See:

    public class TreatmentDataProvider
    {
        protected TreatmentDataProviderHost TreatmentDataProviderHost { get; private set; }
        protected TreatmentDataProviderField TreatmentDataProviderField { get; private set; }
        protected IPluginHost PluginHost { get; private set; }

        public TreatmentDataProvider(IPluginHost pluginHost, TreatmentDataProviderHost treatmentDataProviderHost, TreatmentDataProviderField treatmentDataProviderField)
        {
            PluginHost = pluginHost;
            TreatmentDataProviderHost = treatmentDataProviderHost;
            TreatmentDataProviderField = treatmentDataProviderField;
        }

        public ITreatmentDataProvider Provider
        {
            get
            {
                if (PluginHost.GetWorkMode() == WorkMode.ConnectedMode)
                {
                    return TreatmentDataProviderHost;
                }
                else
                {
                    return TreatmentDataProviderField;
                }
            }
        }
    }

Code above does the same logic, but it delivered control of creation of instances to other parties (IoC), also it now doesn’t have dependency on static methods, so code is less coupled. I didn’t remove this class as we have to keep verification for WorkMode at runtime. I know you might complain about these protected properties, but I like to have it that way for more flexibility when testing.

What are your thoughts? [Sentence removed 10/18/2011]

[Added 10/18/2011]

5) Yet another big mistake: Code reviewer. Guess who he was. When I’ve been reviewing this code by request of developer I just thought “it works, then it should be ok”. Why didn’t I ask about unit tests and why didn’t I took reviewing more scrupulously. I have to be more accurate when reviewing others code. Bad code reviewer.

6) Yet another mistake: writing this blog post. I understand that my criticism might be taken to close, especially if this was read. I also don’t like criticism. No one likes. Man, if you reading this you have to know I didn’t mean to abuse you or something, I just was upset at night about failing tests.


4 comments


Help me select UML for book: hand-drawn or tool-prepared

October 14, 2011 Design Patterns 16 comments

As you may know I’m working on Design Patterns book in Ukrainian and as most of the posts I had on patterns have UML-s, I’m considering having UML diagrams in book as well to be consistent. Thus I can either prepare them in some UML tool or just draw. See yourself.

Drawn by me

FACTORY_NEW

Also drawn by me, but in advanced tool

image

And here how it looks like when on paper

image

image

Why I like hand-drawn option

I would like to use hand-drawn variant because it will make the book look cheery and will make the difference. It might bring some interest like “So what’s is really on that diagram?”. Also I still don’t position book as an “official” book, so I would like to have some bits of unofficially. Especially taking into account that auditory is mostly young starting developers.

Why I don’t like it

I’m of course hesitating, as this variant in its origin is inaccurate (of course I can try harder). Also maintaining such diagrams is bit more difficult, but I don’t see any problem with this.

Please help me choose!

 

[Added later (wasn’t in original post)]

After I posted this friend suggested me to use this online uml generation tool. And it would be great another option to consider, but it generates not really what I want:

image

But it was extremely nice, that to generate picture above I just used this code:

# Abstract Factory
[Cat]^[WoodenCat], [Cat]^[TeddyCat]
[Bear]^[WoodenBear], [Bear]^[TeddyBear]
[IToyFactory]^[WoodenToysFactory], [IToyFactory]^[TeddyToysFactory]
[TeddyToysFactory]uses-.->[TeddyBear]
[TeddyToysFactory]uses-.->[TeddyCat]
[Client]->[IToyFactory]
[Client]->[Cat]
[Client]->[Bear]
[WoodenToysFactory]uses-.->[WoodenCat]
[WoodenToysFactory]uses-.->[WoodenBear]

Nice tool, indeed, but for extremely simple diagrams.

[Added later (15 Oct, after comments)]

After comment by Satomi Joba I tried community edition of another tool, called Astah. Below is what I was able to draw by it. Two things about it: 1) Drawing in this tool is just fabulous, smooth and easy. For me it was more quick and intuitive drawing than in such matured tools as Enterprise Architect for example. 2) Although I’m not sure I like this bold borders and I wasn’t able to quickly change styling of diagram (maybe because of edition I used?).

image

Anyway question is still the same: do I use hand-drawing or do I use tool?


16 comments


Uneta Plus

October 8, 2011 Conferences 2 comments

Week ago I had a chance to be at one of the best Ukrainian conferences for the recent time. Awesome conference, awesome presenters, awesome people, awesome uneta plus.

Andriy Buday at Uneta Plus ConferencePPhoto by Mike Chaliy

Conference was far from my home in faraway city Kharkiv. I’ve been there once, when delivering MEF talk last year at ITJam2010. Even location kept the same:

 

Now more on conference itself. It started with keynote from two maybe most known ms guys in Ukraine – Dmitriy Nikonov and Serhiy Baidachni.

I cannot say that keynote was structured and well organized speech, it was more improvising, but having those two guys rescued it. They definitely are not new in field of presenting something, so auditory listened with attention, and all get acquainted with what’s next. Especially I really enjoyed stuff now available in TFS. It is getting matured over time.

Following presentation I attended was about Silverlight and XNA and how they live together in WP7 Mango. It wasn’t deep dive into things in Silverlight or XNA, but I enjoyed observing small UFO flying thought the auditory (background was transmitted from phone camera).

“Every game consists with 3-4 parts at each level. They are load and unload. Between those is while loop that has two calls – update game world and render game world.” – said Alex Golesh*. Now in WP 7.5 we can render both Silverlight and XNA in same application. I found this msdn page well informative.

Sharepoint for internet sites gives good business solution. I was able to see Sharepoint in action. Marat showed how we can start with file->new project and proceed to completed site, designed in sharepoint designer. Also some bits about authorization and authentication in sharepoint, and I felt like I’m guru in sharepoint… NO! I still think it is complex and not clear, but Microsoft actively pushes this product. Personally I think, that even if it is great product, it is not something that you would want to listen at programmers conference.

Lunch. Oh yeah, I really appreciate guys, who organized this event, as I could eat tasty (no really!) food without leaving conference. I guess money I paid for conference has something to do with taste of food, but believe me – it worth to pay more and get normal food.

I also attended presentation on entity framework, which consisted with two parts and was delivered in English by Diego Vega. Man, if you are reading this, you have to know – you rocked! I found this presentation to be best structured and most fulfilled with information on its topic.

Also I’m bit disappointed that I didn’t saw that amazing luster of Dmitriy Kostylev. Everyone who was in section 2 listening to him were literally excited. Ah… sad I missed that hardcore SQL optimization wisdom.

Another thing made this event different – so called “round table”. All of the speakers were gathered at the scene answering questions from auditory. I enjoyed this part as well, but left before the end, as I had train back to home.

Organizers of even asked few times about feedback. They want to hear more about what can be improved in this event, what was great and what wasn’t that much great. Here are few of my subjective thoughts:

  1. Lower price a bit. I think more people will attend if price would be something more moderate, but who knows… you tried to balance between number of attendees and price, not me. I was frustrated about showroom not being full.
  2. How about more sections, so I can choose if I get overview of sharepoint, tfs, or if I get flood of hardcore wp7 stuff. I just want more clear vision on what I can grasp from one or other presentation, because in some topics I feel myself confident and need advanced level, respectively in some I need introductory level.
  3. Personally I would like to see more foreigners, like Diego. I don’t know if it is hard to have them on event, but if you bring someone like Hanselman, I bet I will visit you even I have to pay more and travel longer.
  4. I’m not sure it worth complaining but why not Kyiv?

Despite of what I listed above uneta plus really was different sort of event of those I visited ever before because of extremely awesome presenters and great organization. Well done!

* This is how I remembered his words. I don’t promise I didn’t misinterpret something.


2 comments