Bind two values into one text box

February 10, 2011 Silverlight 4 comments

Today I’ve spent some time on playing with some piece of code that had to ensure that on screen in some NumericTextBox depending on situation we show one of the two values – either one automatically calculated or either another user entered.

If value was automatically calculated we show it in that text box, but if user changes it we still keep calculated value untouched (double? CalculatedMileage) but work with another value (double? EnteredMileage). As you see we cannot bind any of these directly to the view.

So, how do we bind two sources (fields) to one target (textbox) on the UI?

I came to some solution with which I’m not completely satisfied, but at least I like it much more than it was before my changes.

Here is binding (I did not change it):

<UserControls:NumericTextBox AllowDecimals=”True”
                             Minimum=”0″ UseMinimum=”True”
                             Maximum=”999.999″ UseMaximum=”True”
                             MaxLength=”6″
                             Value=”{Binding Mileage, Mode=TwoWay}”


Now, Mileage property that I’m binding to the view has backing field _mileage, so I always get value for displaying by using simple getter. But on set I’m actually populating two fields _mileage and EnteredMileage like below:
        private double? _mileage;
        public double? Mileage
        {
            get
            {
                return _mileage;
            }
            set
            {
                _mileage = value;
                EnteredMileage = value;
                RaisePropertyChanged("Mileage");
            }
        }
This means that once I used setter I touched EnteredMileage.
What I display is _mileage and I when I display is when RaisePropertyChanged gets called. So keeping this in mind I do following stuff on screen setup:
 _mileage = EnteredMileage.HasValue ? EnteredMileage : CalculatedMileage;
 RaisePropertyChanged("Mileage");

If user initially entered some value we start operating with it and don’t touch calculated one, but if he did not, then we show calculated at first.
I may be bothering you, but I’m wondering if you know/see some more elegant solution for this stuff. I guess there must be some. And if there is no such, then use mine…


4 comments


Book Review: “3.5–ADO.NET Training Kit” and passing 70-561 exam

February 10, 2011 Book Reviews, Certification, Success No comments

Training Kit

imageSo I finally finished reading training kit for ADO.NET exam. It is easy to read book with many topics that you probably know or at least heard about if you are using .NET. But besides of standard topics on DataSets, Data Querying, LINQ there are few that represent much more interest at least for me. For me these are chapters about Synchronization Framework, Entity Framework and Data Services (REST). I read them with great pleasure. But unfortunately in book they are covered briefly. Also Data Services are not even included into exam questions. I would also say that unless you are going to pass 561 exam, don’t read this training kit, better find some good tutorials on each of the themes, use MSDN and try everything out.

Exam 70-561: TS: Microsoft .NET Framework 3.5, ADO.NET Application Development

I passed 70-561 exam with score 700 out of 1000 with needed 700 for passing. Yeah, that is damn near to failure. But what is also interest that the more I fill overconfident about the exam the worse score I get. Maybe that is why I failed WinForms for the first time, but passed ASP. Who knows.. This rule probably doesn’t apply to WCF exam. I was confident about it and passed with high score.

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

Nearest certification plans

My current certification situation is as following:
image
So I’m very close to my certification goal which is “MCPD: Enterprise Application Developer 3.5” and I already scheduled 565 exam for Friday Feb 18. As for preparation I really hope that couple of years of experience in Enterprise project are in help for me. Also I pick up “Microsoft Application Architecture Guide” for my reading. I read about first 30 pages and I’m impressed by this book. It is real glue. I like very much things that I read from very first pages. Will see how it goes and be ready for review next week. I believe it will be more comprehensive, since this is not kind of training kit book.


No comments


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