Distributed transactions with NHibernate

January 31, 2011 NHibernate No comments

Most of our current NHibernate saving methods look like below:

        public void SaveCustomer(CustomerEntity customer)
        {
            var transaction = GetActiveTransaction();

            transaction.Begin();
            try
            {
                // some code
                Session.SaveOrUpdate(customer);

                transaction.Commit();
            }
            catch (Exception e)
            {
                transaction.Rollback();
                throw e;
            }
        }

this works great if you need to save just Customer or just Vendor. But in recent time we got kindof challenge to save Customer and Vendor at once in scope of one transaction for piece of functionality, and at the same time method should work for another piece of functionality.
For this we change our methods as following:

        public void SaveVendor(VendorEntity vendor)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Required)) // if there is no transaction scope, new will be created...
            {
                using (var transaction = Session.BeginTransaction())
                {
                    // some code
                    Session.SaveOrUpdate(vendor);

                    transaction.Commit();
                }
                scope.Complete();
            }
        }

Now we can utilize our methods higher in the call stack:

        public void SaveBunchOfInformationAtOnce(CustomerEntity customer, VendorEntity vendor)
        {
            try
            {
                using(var scope = new TransactionScope(TransactionScopeOption.RequiresNew)) // always new transaction will be created
                {
                    CustomersRepository.SaveCustomer(customer);

                    VendorsRepository.SaveVendor(vendor);

                    scope.Complete();
                }
            }
            catch(Exception e)
            {
                // log errors...
                throw;
            }
        }

This all works just fine both for existing method calls and for new one. Hope it helps.
Next thing that I might need to put into place is to distribute transactions through WCF services. That should be fun.


No comments


Woot! That have happened–I’m done with English courses

January 26, 2011 English, Success 4 comments

I attended English courses in my company for about 9 months. For this time I learnt a lot of new stuff, and revisited whole bunch of grammar. Also I slightly increased my vocabulary.

I’ve mentioned many times that English courses are very important for outsourcing company and for me particularly. I even described one of the lessons and recommended some activities to do to learn English.

  • I’ve finished courses with final test result of 92%.
  • My strong areas are: listening, speaking and vocabulary.
  • My weak areas are: grammar, translation.

So this is very good result, but unfortunately my average score is about 80%, so I might not be eligible for next free of charge course. But honestly I do not hurry for being English course’s student for another 9 months. It makes me tired… because I have to allocate additionally 4-5 hours per week and as usual I rob it from my sleep hours. I think that the next most needed thing for me is to practice more and more. Actually I even planned to find someone who would like to talk with me in English all the time. Not my girl – she is more German expert and weak in English, and not my best friend – he is too shy or smth..


4 comments


70-562: TS: Microsoft .NET Framework 3.5, ASP.NET Application Development – PASSED

January 21, 2011 Certification, Success 8 comments

That happened! Passing this exam was the main stone on my road to MCPD Enterprise.

How did I prepare?

I already mentioned that I prepared as usual by reading training kit. But this time I did most of the Labs, because I have really little experience in Web Development.

Honestly for me ASP revealed to be very simple for understanding and easy to work with. I guess because it intersects with other technologies and also because I have more or less good dev experience in other areas.

Also I did not concentrate on learning ASP.NET extremely well. We all know that nothing with ViewState and other aspects of it are now history. ASP MVC should be technology number one for learning web, but I had to pass this exam. Also understanding what is under MVC and from what it all started is good.

Passing Exam

Exam has 45 questions for about 3 hours. I hated answering them. They were long to read and extremely boring. I HATE THIS EXAM QUESTIONS. 2 screens of question is too much, it kills.

I PASSED EXAM with score 907, woot!

You can see my transcript using this information:
https://mcp.microsoft.com/authenticate/validatemcp.aspx
Transcript ID: 904316
Access Code: andriybuday


8 comments


Book Review: “Microsoft .NET Framework 3.5–ASP.NET Application Development”

January 20, 2011 Book Reviews No comments

image

Hello there. For me it is time to pass next exam on the way to MCPD Enterprise Dev. This time it is ASP.NET exam. For me it is the most difficult of the exams, since I have really little experience in web development.

For my training to exam as usually I read training kit. Finally it was not boring for me to read it. Probably because greater part of it was new to me. I also performed most of the ASP.NET Labs. The most interesting was the beginning of the book and its end. And I almost scrolled ado.net chapter, since there was nothing new to me. (Fine that training kit for ado.net exam, which is gonna be my next exam, is about 400 pages only, so I can be calm about reading it.)

I started preparing to exam about 2-3 months ago, but since I’m lazy it was going slowly and because I scheduled exam for 21th Jan… which is… today, I have had to prepare to exam my evenings in recent time, this made me little bit tired and out of schedule with learning more asp stuff. Actually at the moment when I started preparing I had been thinking that I could implement small web site and run thought msdn solidly. Ah.. I did not do this. I’m afraid to fail it as it was with my WinForms exam twice.

Tomorrow Today early morning I will be passing this exam. Wish me good luck.


No comments


Adapter

January 11, 2011 Design Patterns No comments

For some reason I have thought about good example for Adapter design pattern for a long period of time. There might be straightforward example with two classes, one of which has OperationA and other has OpA and we need to adapt them, but there is no analogy in that example. In this case it would not worse reading this post. Also I thought about example in which we have complex objects with many properties and methods, where you would need to perform some real  conversion. But by the way of thinking there was always electricity adapter in my head circling. In Lviv there is still many apartments where old thin sockets exist, to overcome this people buy small adapters, almost as on the picture on the right, except not that cruel.

So we have our notebook charger that easily fits wide European socket. In your apartment all sockets are new, so you get used to it. Your NewElectricitySystem has method MatchWideSocket. But in your friend’s apartment there is still old one and his OldElectricitySystem has only method MatchThinSocket. Unfortunately you cannot drill sockets in someone else’s flat, you have to buy Adapter, that allows you consume the same electricity, but with old system.

ADAPTER

Adapter – is design pattern that allows us use object, which we cannot change, by providing its functionality thought known interface.

    // Adaptee
    class OldElectricitySystem
    {
        public string MatchThinSocket()
        {
            return "220V";
        }
    }
    // known interface in our code
    interface INewElectricitySystem
    {
        string MatchWideSocket();
    }
    class NewElectricitySystem : INewElectricitySystem
    {
        public string MatchWideSocket()
        {
            return "220V";
        }
    }
    // Adapter
    class Adapter : INewElectricitySystem
    {
        private readonly OldElectricitySystem _adaptee;

        public Adapter(OldElectricitySystem adaptee)
        {
            _adaptee = adaptee;
        }

        // All the magic lives here
        // in our adapter we translate from
        // what we (code) cannot use straightway into what we can
        public string MatchWideSocket()
        {
            return _adaptee.MatchThinSocket();
        }
    }

    class ElectricityConsumer
    {
        // Charging device can be used only with new system
        public static void ChargeNotebook(INewElectricitySystem electricitySystem)
        {
            Console.WriteLine(electricitySystem.MatchWideSocket());
        }
    }

    public class AdapterDemo
    {
        public static void Run()
        {
            // We can easily operate with our new system
            var newElectricitySystem = new NewElectricitySystem();
            ElectricityConsumer.ChargeNotebook(newElectricitySystem);

            // We have to adapt to old system using adapter
            var oldElectricitySystem = new OldElectricitySystem();
            var adapter = new Adapter(oldElectricitySystem);
            ElectricityConsumer.ChargeNotebook(adapter);
        }
    }

Yet another name for this pattern is Wrapper. That is because it wraps functionality of some object, representing it in another interface.

Actually we can also implement it slightly differently than I have it here. In the example above we use composition, but our adapter can easily implement two interfaces of the old and new system and then once created by one of the constructors we would use our adapter in both directions.

My design patterns table


No comments


Where Do You Want to Be In a Year?

January 8, 2011 Success, YearPlanReport 9 comments

So time for new year resolution has came.
I created similar list last year and wrote why I really think that having list of things you want to do during the year is very important. I listened to many of time management books, especially I like those recommendations that includes all aspects of the life.
Accordingly that their point of view life consists with following set of aspects: health, relations, finances, emotions, work. If at least one of this aspects lame you wouldn’t enjoy your life entirely since other aspects will suffer. I found that in recent time I neglected my health. Yeah, I’m young so I do not feel myself completely crappy, but anyway I don’t like situation in which I’m now. That is why I’m planning to have some activities in list that should help me with my health. In this country you have to work half of your life to get apartments to live in… wtf? yeah, that’s truth, so there have to be some better ways to earn more money, not only sweatshoping work. To enjoy my life it would be perfect to travel abroad with middle-low budget.
Here below is my resolution list for 2011 

  1. Release awesome free Design Patterns book in Ukrainian (somewhen in Spring)
  2. Enterprise certification (finishing with 565 exam, very likely till the end of Winter)
  3. Learn to ski & swim well (I can both, but I want to be good at that)
  4. Show kick-ass performance at work (just MUST do this, I see this as key for moving forward)
  5. Learn WP7 and Silverlight
  6. Start working on some “real” book (just collecting ideas on book)
  7. Read 24 books (this year I will definitely hit this score)
  8. Travel abroad (I’m planning for Europe tourist tour)
  9. Marriage (yeah, this really is in the list “OMG” I’m saying to myself…)
  10. Learn one more programming language (probably everyone heard about learning one language per year, why not?)
  11. Frequent dev meetings (this is hard, because preparing takes lot of time for me)
  12. Karpaty alpinism (again health stuff, want to do this with my girlfriend)
  13. Became known presenter (couple of outside the company presentations)
  14. English (watch films, find guys to talk in English)
  15. Start coffee-and-code in Lviv
  16. Write couple of personal-small programming projects / contribute to open-source
  17. Visit one of the solid conferences
  18. Get money machine / some ideas / investments / whatever
  19. Start some business even small and crappy – but have it to learn
  20. Became better-and-better in planning and achieving, continue growing, etc, etc…

(list above is not ordered in any way…)
Do you have your plan for this year? If you don’t better think about it, because “if you fail to plan, you plan to fail”.
Ok list looks large but fair enough to achieve this in year term. Thank you for reading my resolutions and please share yours!


9 comments


What has been done during last year?

January 5, 2011 Revision of my activity, Success, YearPlanReport No comments

Looking back at my “Where Do You Want to Be In a Year?” blog post for the Jan 2, 2010 I want to  summarize for myself if I stand where I wanted to stand and what else could be done to improve my position. I would recommend to all of you to execute same reviewing and realize if you are moving in the right direction or not.
For the previous year I wrote 156 blog posts, read many books, performed dozen presentations, became Senior developer, passed few ms exams, decided to start my first book and did many other hopefully right things.
Remember, life is limited in time, so if you don’t move in the right direction you might waste it entirely.

So the list I had in the beginning of 2010:

By the end of 2010 I want:

1.
Get Microsoft Certification:
  * MCTS (Exams: 70-536 and 70-505) SUCCESS
  * MCPD 70-563 and 70-565 (this one is big fish, but I need such!) FAIL
Ok, so I went very good with this item. I successfully passed 536, 505 and 503 exams, they lead me for passing exam 565, passing which credits Enterprise Application Developer 3.5 certification.

2. Read at least 24 books. 62,5% SUCCESS :) 37,5% FAIL
Ok, so counting only programming-related books I have 15 books read. You can see their reviews on my blog just follow this link.
I do not think that I’ve completely failed this item, since I have couple of books in progress and their review will reveal shortly on this blog.

3. Become known employee in my company, sharing knowledge and doing presentations, so will have much more authority among co-workers. SUCCESS
I took few good steps here. I performed company-wide presentation on Domain-Driven Design and of course I performed many so called developers meetings for my guys from my division.
I also performed 4 presentations outside of my company – two at Lviv .Net UG, one at Java UG and one at IT-Jam in Kharkiv.
Visited MS SWIT Conference in Kyiv.

4. Familiarize with Java and contribute research and development work to Kohonen Maps world. SUCCESS
By this link you can find out that I did some research on this matter and I’m almost 100% sure that I was first in the world who wrote parallelized algorithm for Kohonen maps with .net framework version 4.0. I even utilized some of the new concepts introduced regarding multithreading in .net 4.0. Along with this I spent some time writing same project with Java.

5. to be Senior Developer and continue growing… SUCCESS
Done! Read Friday 13th blog post. As of growing I slowed down slightly as per me. Maybe I got tired, but I developed my career plan.

6. Improve my English skills to have at least upper-intermediate strong level (according to my company graduating) SUCCESS
Definitely improved my English skills. My official level as of now is “upper-intermediate”. It might be that shortly will get “+strong” since my English course is not finished yet. But honestly I feel that I lack a lot to speak fluently. But now I can easily watch films without translation, listen podcasts, etc…

7. Gather good capital and looking for investments of money. SUCCESS
Ah! This progresses hardly, but I do a lot here. At least I got higher salary rate because of my promotion, but I started spending more money. I have to work on this more. Btw, my blog earned 4,81$ for the year, but we all know that it pays me differently.

Next thing I will create blog post “Where do you want to be in a Year?” for the 2011.
Till next time.


No comments


Facade

January 4, 2011 Design Patterns No comments

Do you like skiing? I do. I even spent two previous days in mountains skiing. Imagine, you decided to spend your weekend very actively in mountains, for this you would need to go and book room in hotel for good night accordingly to your wishes, then you would also need to rent ski, boots and poles. For renting you would be asked questions about your weight and proficiency, then you would be letting them know your height and feetsize for boots, and again height for pole. With all of this on your back you go to ticket office and buy ski pass for one day. Honestly I don’t like this kind of mess. What I would love in this situation is to come to one point, terminal or smth. answer for all questions, pay bill and immediately get your skis, boots, poles, ski pass and room keys. Of course if I have all equipment (I really do) I can take only ticket and go out there.

FACADE

Facade is design pattern that provides us with one entry point to subsystem, simplifying its usage and understanding.

In our example facade would be terminal-serving station (SkiResortFacade), subsystem would be whole bunch of renting buildings, paydesks, hotels. Of course we can go all around the resort, if we like this, but if we take a look from software development point of view if devs will walk all around and use as they wish, it will not lead to positive consequences. And skiers-newcomers will never know where they should go for the first time.

    internal class SkiRent
    {
        public int RentBoots(int feetSize, int skierLevel)
        {
            return 20;
        }
        public int RentSki(int weight, int skierLevel)
        {
            return 40;
        }
        public int RentPole(int height)
        {
            return 5;
        }
    }

    internal class SkiResortTicketSystem
    {
        public int BuyOneDayTicket()
        {
            return 120;
        }
        public int BuyHalfDayTicket()
        {
            return 60;
        }
    }

    internal class HotelBookingSystem
    {
        public int BookRoom(int roomQuality)
        {
            switch (roomQuality)
            {
                case 3:
                    return 250;
                case 4:
                    return 500;
                case 5:
                    return 900;
                default:
                    throw new ArgumentException("roomQuality should be in range [3;5]","roomQuality");
            }
        }
    }

    public class SkiResortFacade
    {
        private SkiRent _skiRent = new SkiRent();
        private SkiResortTicketSystem _skiResortTicketSystem = new SkiResortTicketSystem();
        private HotelBookingSystem _hotelBookingSystem = new HotelBookingSystem();

        public int HaveGoodOneDayRest(int height, int weight, int feetSize, int skierLevel, int roomQuality)
        {
            int skiPrice = _skiRent.RentSki(weight, skierLevel);
            int skiBootsPrice = _skiRent.RentBoots(feetSize, skierLevel);
            int polePrice = _skiRent.RentPole(height);
            int oneDayTicketPrice = _skiResortTicketSystem.BuyOneDayTicket();
            int hotelPrice = _hotelBookingSystem.BookRoom(roomQuality);

            return skiPrice + skiBootsPrice + polePrice + oneDayTicketPrice + hotelPrice;
        }

        public int HaveRestWithOwnSkis()
        {
            int oneDayTicketPrice = _skiResortTicketSystem.BuyOneDayTicket();
            return oneDayTicketPrice;
        }
    }

    public class FacadeDemo
    {
        public static void Run()
        {
            var skiResortFacade = new SkiResortFacade();

            int weekendRestPrice = skiResortFacade.HaveGoodOneDayRest(175, 60, 42, 2, 3);

            Console.WriteLine("Price: {0}", weekendRestPrice);
        }
    }

This design pattern in some way represents very important encapsulation principle but just on higher level. On this level we encapsulate whole subsystem instead of class. Big systems usually consist with many subsystems that communicate between each other by using facades. Space station connects to another station using one mechanism, not with gluing together hundreds of wires and tubes. Also an good way to develop software would be to have some kind of facade (it might be set of known interfaces) inside of each assembly, so it can be used easily from other parts of your application.
Thank you.
My design patterns table


No comments


Abstract Factory

December 27, 2010 Design Patterns 2 comments

Ok, let’s imagine that you came into toys shop (playing role of Santa) and you want to buy dozen of toys for kids (not necessary for your kids). One kid likes teddy toys, she often goes to bed with them. Other kid prefers solid toys, like wooden or metal. This kid often breaks toys, so you also would prefer to buy something durable. Both of them definitely want a bear and cat toys, they also might want other toy-animals. Fortunately shop is huge and you bought everything. You put wooden toys into one sack and teddy toys into another sack.

Thus when you came to the girl, who likes soft toys, you started getting teddy bear, then teddy cat and other teddy animals requested by kid. When you came to boy you did the same but with another sack, fetching wooden bear and wooden cat out.

ABSTRACT FACTORY

Abstract Factory is design pattern that provides you with interface for creating families of objects without specifying their concrete types. (oh… almost repeated word-by-word GoF guys)

In our example family is toys of some specific type, family consists with Bear and Cat. Abstract Factory is sack. One of the factories returns wooden toys and other teddy toys. Thus when kid asks for cat he/she gets cat appropriately to selected sack.

I hope that analogy example is good. Let’s take a look at some code?

Abstract factory and concrete implementations

Abstract Factory defines interface that returns instances of Bear or Cat (through base class). Concrete factories return concrete implementations of members of the family.

     // abstract factory

public interface IToyFactory
{
Bear GetBear();
Cat GetCat();
}
// concrete factory

public class TeddyToysFactory : IToyFactory
{
public Bear GetBear()
{
return new TeddyBear();
}
public Cat GetCat()
{
return new TeddyCat();
}
}
// concrete factory

public class WoodenToysFactory : IToyFactory
{
public Bear GetBear()
{
return new WoodenBear();
}
public Cat GetCat()
{
return new WoodenCat();
}
}

This is quite obvious, that once we have instance of factory we are ready to produce members of the families. Let’s take a look on usage:

            // lets start with wooden factory

IToyFactory toyFactory = new WoodenToysFactory();

Bear bear = toyFactory.GetBear();
Cat cat = toyFactory.GetCat();
Console.WriteLine("I've got {0} and {1}", bear.Name, cat.Name);
// Output: [I've got Wooden Bear and Wooden Cat]

/*--------------
somewhere else in the code...

----------------*/

// and now teddy one
IToyFactory toyFactory = new TeddyToysFactory();

Bear bear = toyFactory.GetBear();
Cat cat = toyFactory.GetCat();
Console.WriteLine("I've got {0} and {1}", bear.Name, cat.Name);
// Output: [I've got Teddy Bear and Teddy Cat]

Two snippets of code are almost identical, except of concrete sack.

If you are still interested in realization of animals-toys just take a quick look on this:

    public abstract class AnimalToy
{
protected AnimalToy(string name)
{
Name = name;
}
public string Name { get; private set; }
}
public abstract class Cat : AnimalToy
{
protected Cat(string name) : base(name) { }
}
public abstract class Bear : AnimalToy
{
protected Bear(string name) : base(name) { }
}
class WoodenCat : Cat
{
public WoodenCat() : base("Wooden Cat") { }
}
class TeddyCat : Cat
{
public TeddyCat() : base("Teddy Cat") { }
}
class WoodenBear : Bear
{
public WoodenBear() : base("Wooden Bear") { }
}
class TeddyBear : Bear
{
public TeddyBear() : base("Teddy Bear") { }
}

Abstract factory is very widely used design pattern. Extremely good example would be ADO.NET  DbProviderFactory class, i.e. abstract factory, which defines interface for getting DbCommand, DbConnection, DbParameter  and so on. Concrete factory SqlClientFactory returns appropriately SqlCommand, SqlConnection…

Thank you for reading this post till the end.

 My design patterns table


2 comments


Allow set in your POCO or write crappy resolvers for AutoMapper or what?

December 20, 2010 AutoMapper, NHibernate 2 comments

In my project we are using NHibernate and Automapper to automatically map heavy database objects to light DTO object that we send across the wire. This works just fine, unless you have to map light object received to the POCO class.

Accordingly to all normal recommendations and just good common sense. You would not expose properties of your database objects with setter. Because ORM should fetch object graph in consistent state. And when you want to set Customer for Order you would probably use SetCustomer() method for better visibility and in

    public class Order
    {
        private Customer _customer = new Customer();
        public virtual int OrderId { get; set; }
        public virtual DateTime OrderDate { get; set; }
        public virtual Customer Customer { get { return _customer;}}
    }

and in mapping you would write something similar to this:

    public class OrderMap : ClassMap
    {
        public OrderMap()
        {
            WithTable("`Order`");

            Id(x => x.OrderId);
            Map(x => x.OrderDate, "OrderDate");

            References(x => x.Customer)
                .Access.AsCamelCaseField(Prefix.Underscore)
                .WithForeignKey("CustomerId");
        }
    }

as you can see, we set value for Customer using reflection deep inside of NHibernate. Also this approach ensures us that newly created Order will have default Customer object. But when we come to mapping OrderModel, which looks like below:

    [DataContract]
    public class OrderModel
    {
        [DataMember]
        public virtual int OrderId { get; set; }
        [DataMember]
        public virtual DateTime OrderDate { get; set; }
        [DataMember]
        public virtual CustomerModel Customer { get; set; }
    }

OrderModel.Customer simply doesn’t map to Order.Customer, since AutoMapper doesn’t have access to write into that value. Sadly, but AutoMapper doesn’t have any convention like NHibernate                 .Access.AsCamelCaseField(Prefix.Underscore), which means that it will look for _customer.

And now! AutoMapper is much smarter than NHibernate. You don’t need any conventions you can simply put private set and you are good! So I did:

    public class Order
    {
        private Customer _customer = new Customer();
        public virtual int OrderId { get; set; }
        public virtual DateTime OrderDate { get; set; }
        public virtual Customer Customer
        {
         get { return _customer;}
         private set { _customer = value;}
        }
    }

Honestly I wouldn’t write this post if I had knew about this possibility before I started writing it. But since I wrote more than half of what you see I decided to finish the story. Enjoy or blame me. Anyway for myself I took following: sniff around features and components you are using, some of them have better ideas than others, your task is to absorb the best!


2 comments