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


Resolving WCF object graph cycles and CustomMessageInspector

December 16, 2010 WCF 5 comments

Today I played a little bit with WCF services. Currently in system we have extremely cumbersome and large object graphs.
Long story short we have Order data contract that always has Customer property in it. From other side Customer did not have reference to Order, so today I added property IList<Order> Orders to my customer and to test just called wcftestclient. Of course if you are not new to WCF, you know that it showed me that I probably have cyclic dependencies.

Reason is that if you have cyclic dependencies XmlSerializer anyway tries to serialize whole graph till it reaches stackoverflow.
[EDITED because of complains]  Actual error is something like “SerializationException: Customer contains cycles and cannot be serialized if reference tracking is disabled…

To avoid this problem you would need to mark you data contract with [DataContract(IsReference = true)]. So I did:

 [ServiceContract]
 public interface IDataContractCycles
 {
  [OperationContract]
  CustomerModel GetCustomer();
 }

 [DataContract(IsReference = true)]
 public class CustomerModel
 {
  [DataMember]
  public string Name { get; set; }

  [DataMember]
  public IList Orders { get; set; }
 }

 [DataContract(IsReference = true)]
 public class OrderModel
 {
  [DataMember]
  public string Name { get; set; }

  [DataMember]
  public CustomerModel Customer { get; set; }
 }

And to test I again fired up wcftestclient and it crashed!!! wtf? I had to commit some code to keep guys working so I commented Customer property of my Order. I thought that it would crash in our client the same way.

image

And now meaning of this story: TRUST NO ONE!

I cannot give up that easily, so I wrote ever simple wcf server and client, then added custom message inspector to see actual payload.

For this you would need something like below:

 class Program
 {
  static void Main(string[] args)
  {
   var client = new DataContractCyclesClient();

   client.Endpoint.Behaviors.Add(new CustomEndpointBehavior());

   client.Open();

   CustomerModel customerModel = client.GetCustomer();
  }
 }

 internal class CustomEndpointBehavior : IEndpointBehavior
 {
  public void Validate(ServiceEndpoint endpoint){}
  public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters){}
  public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher){}

  public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
  {
   clientRuntime.MessageInspectors.Add(new CustomMessageInspector());
  }
 }

 internal class CustomMessageInspector : IClientMessageInspector
 {
  public object BeforeSendRequest(ref Message request, IClientChannel channel)
  {
   return null;
  }

  public void AfterReceiveReply(ref Message reply, object correlationState)
  {
   reply.ToString(); // THIS IS ACTUAL PAYLOAD OF THE MESSAGE
  }
 }

I got correct object graph and payload with reference Id-s. See message below. It has Customer marked with z:Ref=”i1″ and then the same Id is used in two orders. This is cool stuff.

<s:Body u:Id=”_0″>

  <GetCustomerResponse xmlns=”http://tempuri.org/”>

    <GetCustomerResult z:Id=”i1″ xmlns:a=”http://schemas.datacontract.org/2004/07/WcfLearningCycles” xmlns:i=”http://www.w3.org/2001/XMLSchema-instance” xmlns:z=”http://schemas.microsoft.com/2003/10/Serialization/”>

      <a:Name>Andriy Buday</a:Name>

      <a:Orders>

        <a:OrderModel z:Id=”i2″>

          <a:Customer z:Ref=”i1″ />

          <a:Name>Kindle</a:Name>

        </a:OrderModel>

        <a:OrderModel z:Id=”i3″>

          <a:Customer z:Ref=”i1″ />

          <a:Name>HTC Cable</a:Name>

        </a:OrderModel>

      </a:Orders>

    </GetCustomerResult>

  </GetCustomerResponse>

</s:Body>

Liked it? Yes? No?


5 comments


Strategy

December 14, 2010 Design Patterns 2 comments

“That’s simple as door” I wrote in Ukrainian, but I’m quite sure that in English another word combination is used to refer to express simple things. When it is raining outside you wear coat and take umbrella, and when it is sweltering you take T-shirt and sunglasses. But instead of taking a look outside to identify the weather and walk to wardrobe and take clothes and then, keeping in mind weather condition walk to bracket and take sunglasses or umbrella, YOU wake up and your wife (or husband, what is less likely) gives everything you need. In other words your wearing strategy for today has been given to you with one shot.

STRATEGY

Strategy – is design pattern that means having family of algorithms that can be used/changed by your code depending on situation.
Lets imagine that in class Myself we have some method GoOutside()  where we chose clothes and accessories and then walking outside.
Method could possibly look like below:
        public void GoOutside()
        {
            var weather = Weather.GetWeather();
            string clothes = GetClothes(weather);
            string accessories = GetAccessories(weather);
            Console.WriteLine("Today I wore {0} and took {1}", clothes, accessories);
        }

        private string GetAccessories(string weather)
        {
            string accessories;
            switch (weather)
            {
                case "sun":
                    accessories = "sunglasses";
                    break;
                case "rain":
                    accessories = "umbrella";
                    break;
                default:
                    accessories = "nothing";
                    break;
            }
            return accessories;
        }

        private string GetClothes(string weather)
        {
            string clothes;
            switch (weather)
            {
                case "sun":
                    clothes = "T-Shirt";
                    break;
                case "rain":
                    clothes = "Coat";
                    break;
                default:
                    clothes = "Shirt";
                    break;
            }
            return clothes;
        }
It doesn’t offend anyone, but once we will need to adapt to snow shower, we would need add one more case in 300 more places. From one point of view that is not difficult, but from another it “can get you” or maybe code with method GoOuside cannot be changed any longer. What’s then?
Hereabove I showed example with switch statement, since Strategy is the most elegant way to get rid of this monster.
    internal class Myself
    {
        private IWearingStrategy _wearingStrategy = new DefaultWearingStrategy();

        public void ChangeStrategy(IWearingStrategy wearingStrategy)
        {
            _wearingStrategy = wearingStrategy;
        }

        public void GoOutside()
        {
            var clothes = _wearingStrategy.GetClothes();
            var accessories = _wearingStrategy.GetAccessories();

            Console.WriteLine("Today I wore {0} and took {1}", clothes, accessories);
        }
    }
As we can see interface has two methods. They are shown below as well as SunshineWearingStrategy implementation:
    public interface IWearingStrategy
    {
        string GetClothes();
        string GetAccessories();
    }

    class SunshineWearingStrategy : IWearingStrategy
    {
        public string GetClothes()
        {
            return "T-Shirt";
        }

        public string GetAccessories()
        {
            return "sunglasses";
        }
    }

All left is to correctly chose strategy and set it for Myself instance. Hm! Anyway someone have to take a look on weather and put right strategy (wife, who woke up in the morning). But we can do this in one different place.

            var me = new Myself();
            me.ChangeStrategy(new RainWearingStrategy());
            me.GoOutside();

Output: “Today I wore Coat and took umbrella”

Yet another example would be changing sorting algorithm depending on list length. We all know that qsort is not best solution for small collections or superlarge, in one case we would use merge or other sorting and in another case we would use heapsort. Having sorting logic separately and changing it depending on the size of collection is good example of Stategy design pattern.

My design patterns table


2 comments


Microsoft SWIT 2010

December 12, 2010 Microsoft, Opinion 2 comments

image

This is going to be blog post about my trip to Microsoft conference in Kyiv. More than week passed since that time, but I still clearly remember that cool event. Just want to share my thoughts and impressions on the trip. Maybe some of you, Dear Readers, would love to hear more about the event. Please ask.

At the moment I’m in very comfortable train to Kyiv. I’ve never been in this kind of train. Finally they have established public transport at some good level. Train has personal lights, general lighting system, different indicators (e.g. indication if toilet isn’t occupied), well-working energy set, so I can plug in my laptop system. And the best – it is relatively quick train.” – I wrote at first night going to conference. Don’t know why would I be so impressed by train, wondering as monkey from zoo, but “hey there gonna be great day tomorrow”, thought I at that night. We were in Kyiv at 7:30 AM and freezing cold met us. It was about ‘–10’ by Celsius (14 by Fahrenheit). Not the best weather for conference and I got sick after those days and then two days in mountains at weekend.

Clouds – our future?

Conference started with kick-off speech from director of Microsoft Ukraine. This guy was extremely nice and knew how to keep audience attention. Main idea of his speech was CLOUD.

image Picture is taken from here: http://keddr.com/2010/12/microsoft-swit-2010-v-fotografiyah/ where you can see many other cool pictures including windows phone and Kinect (controller-girls only :) )

Small and cool gray could. Or even “home” could that can be kept in van where you plug electricity, network and cooling system – that is all you need, plus one cabin for controlling. Of course Microsoft itself has bigger toys, something like on picture below:

microsoft-chicago-containers[1] 

1) Windows Phone 7

The guy who talked about WinPhone 7 is Silverlight MVP Sergii Lutai. I liked the way he talked about the phone, and I would say that I already seen those slides presented here in my company by someone else. But slides doesn’t make difference, unless there is everything written and I read everything, but the presenter makes difference. Sergii knew the material and it was really pleasant to hear him. I listened to basics of WP7 once again – but this time I took a lot for myself.

Ukrainian MVP List

First of all I was surprised that even in Ukraine we have some MVPs (I thought there are only few). Actually I did research and it turns out that there are only/about 15 MVPs in Ukraine, follow this link to see whole list.

2) What’s new in ASP.NET 3.0

Definitely the most energized presentation – Dima as always was in good mood, not taking into account that he had lost his passport before. I really like the way he keeps contact with audience, but I often expect more constructive and detailed talks from him. He hates me for this :) … kidding… just kidding…

3) Entity Framework

CSDL (conceptual schema definition language) SSDL (store schema definition language) MSL (mapping specification language)” – wrote I when was there. It doesn’t make a lot of sense being detached from whole story, but I want to keep it as it was before… Hope many guys know what those things are. Sergiy is really cool and solid presenter, yeah.. he is not that young and fun guy as Dima, but it doesn’t impact his possibility to keep audience interested.

4) Developing web apps with ASP.NET AJAX and JQuery

I did not find this presentation to be as good as others. And topic is too jaded. But anyway it was good to listen to that. I know only this – “I love JQuery” :)

Hotel

Title “Hotel” doesn’t mean presentation, but it is about our hosting in hotel. It was the best hotel I ever been. Ok, that is only second time I was in hotel. imageI do not travel, my family did not have money for that and me either did not have money for trips or something. So maybe supercline, tidy bed, tv, refrigerator, awesome shower and rest room doesn’t make any kind of impression on people. Main thing that was there – wifi. He-he, I showed room to my girlfriend via Skype.

You know what happened after that? – We got drunk. I did not know that people can so phenomenally talk about immortal philosophical, slightly math-physical things after couple of glasses full of Whisky. Was extremely interesting and cognitive.

In the morning I felt myself crappy, but anyway went to the conference. It turned out that Kyiv is also traffic jam city.

5) Modeling UML in VS 2010

was interesting.. pity that it is only in Ultimate” – I thought at that time and still think so. It is really bad that lot of fascinating things live inside of Ultimate version of VS and it is that expensive. Building Sequence diagrams with one shot, keeping class diagrams all the time up to date, and elegant component diagrams – that is amazing.

6) F#

WoW!!! @ddtru you rock! That was really fascinating, hardcore, bit academic exciting presentation about functional programming language running on CLR. I’m not sure about this, but it sounds like he is or was teacher in some university. I would love to be one of his students. Actually if you understand Ukrainian you can go to this page and read about each of the presenters, him including.

7) Parallel programming/ Task Library

Young, bright (in both meanings) guy talked about how we came from “Thread.” to “Task.” and then he mentioned about async and await. Presentation was real threading hardcore – I love threading hardcore. Actually I had my Master Diploma related to multithreading, so I knew almost everything he talked about, but there were lot of things that were out of my attention, and now I refreshed that all in my mind. Also what I liked about this presentation is that it was in Ukrainian. It is really sad, that I live in Ukraine and most of the presentations were in Russian. I have nothing against this language, but I have a lot against ruining Ukrainian nation establishment as separate country. Honestly I see myself in this man, I would prepare similar presentation with same kind of hardcore, only maybe I feel more comfortable in front of big audience. This is something he lacked.

8-9) Testing with Visual Studio 2010

Again, Ultimate version of VS allows us create UI test scenarios, that can run automatically. We can also create multi-machine environment that can be reestablished at some moment of time, then our system deployed to it and completely tested. That is awesome.

Maybe I missed some of the presentations where I’ve been, but I put list of those where I’ve been and what I’ve remembered.

Photos

I found some photos from event, you can proceed to them by clicking on the image below. There is also small bug on the picture, try to find it (talking about myself).

And more photos here: http://msswit.cloudapp.net/Photo.aspx


2 comments


Chain Of Responsibility

December 7, 2010 Design Patterns 2 comments

Imagine that you went to cafe with your friends. Cafe is somewhat weird, there is not enough room, and you have to pass food to other person if it is not for you. Your best friend took place the most closed to end of the table, so he is first who gets order. Cause he slept not enough in the night he dies for at least one cap of something with coffee and a lot of meat, since he did not eat during the day. Next to your friend is you and then your girlfriend near the wall. You want soup and she wants cappuccino. She have none to pass food to.

Chain Of Responsibility

I hope that whole mechanics of the design pattern Chain Of Responsibility is understandable. We have some set or chin of handlers (visitors of cafe), that can handle command (food in our example). If handler cannot process command it passes it to its successor if it exists.

Handler

In our example general interface for handler could be following abstract base class:

    public abstract class WierdCafeVisitor
{
public WierdCafeVisitor CafeVisitor { get; private set; }

protected WierdCafeVisitor(WierdCafeVisitor cafeVisitor)
{
CafeVisitor = cafeVisitor;
}

public virtual void HandleFood(Food food)
{
// If I cannot handle other food, passing it to my successor
if (CafeVisitor != null)
{
CafeVisitor.HandleFood(food);
}
}
}

As we can see by default food is passed to next cafe visitor in chain, if it exists.

Lets now take a look on realization that is more suitable for your persnickety friend:

    public class BestFriend : WierdCafeVisitor
{
public List<Food> CoffeeContainingFood { get; private set; }
public BestFriend(WierdCafeVisitor cafeVisitor) : base(cafeVisitor)
{
CoffeeContainingFood = new List<Food>();
}

public override void HandleFood(Food food)
{
if(food.Ingradients.Contains("Meat"))
{
Console.WriteLine("BestFriend: I just ate {0}. It was testy.", food.Name);
return;
}
if (food.Ingradients.Contains("Coffee") && CoffeeContainingFood.Count < 1)
{
CoffeeContainingFood.Add(food);
Console.WriteLine("BestFriend: I have to take something with coffee. {0} looks fine.", food.Name);
return;
}
base.HandleFood(food);
}
}

Implementations of two other handlers – Me and GirlFriend probably are understandable, but anyway will show realization of GirlFriend visitor:

    public class GirlFriend : WierdCafeVisitor
{
public GirlFriend(WierdCafeVisitor cafeVisitor) : base(cafeVisitor)
{
}

public override void HandleFood(Food food)
{
if(food.Name == "Cappuccino")
{
Console.WriteLine("GirlFriend: My lovely cappuccino!!!");
return;
}
base.HandleFood(food);
}
}

That’s simple: girl wants cappuccino, but since she is last in chain she will not get it before friend will not have his cap of something with coffee.

Usage

Now lets take a look on usage. We create two cappuccinos, two soups and one meat. Then we pass those one by one into BestFriend hands: 

            var cappuccino1 = new Food("Cappuccino", new List<string> {"Coffee", "Milk", "Sugar"});
var cappuccino2 = new Food("Cappuccino", new List<string> {"Coffee", "Milk"});

var soup1 = new Food("Soup with meat", new List<string> {"Meat", "Water", "Potato"});
var soup2 = new Food("Soup with potato", new List<string> {"Water", "Potato"});
var meat = new Food("Meat", new List<string> {"Meat"});

var girlFriend = new GirlFriend(null);
var me = new Me(girlFriend);
var bestFriend = new BestFriend(me);

bestFriend.HandleFood(cappuccino1);
bestFriend.HandleFood(cappuccino2);
bestFriend.HandleFood(soup1);
bestFriend.HandleFood(soup2);
bestFriend.HandleFood(meat);

Output:

BestFriend: I have to take something with coffee. Cappuccino looks fine.
GirlFriend: My lovely cappuccino!!!
BestFriend: I just ate Soup with meat. It was testy.
Me: I like Soup. It went well.
BestFriend: I just ate Meat. It was testy.

As we can see from output girl got only second cappuccino and you have been forced to eat soup without meat :)

What is also interesting is that we can add another one handler after girlfriend, say bag for dog, and everything that none likes will go there.

My design patterns table


2 comments


Observer

November 30, 2010 Design Patterns No comments

Many people like watching box fights. But besides of this, someone have to pay for all of this, and most of the money come from people who put some money on boxers and then lose it. Or… maybe I’m wrong, but for this example, let it be so. Imagine that we have box fight tonight and there are two persons interested in game, so they OBSERVE fight and UPDATE their rates. One of them likes risks, so he always put money on boxer who has less chance to win, and other is very conservative and likes small bird in hand instead of big in the sky.

OBSERVER

Observer is design pattern, that allows automatically update many observers if there was change in state of some subject object.

So, each gambler (Player, Observer) likes to adjust his rates, that is why he has Update() method.

    public interface IObserver
{
void Update(ISubject subject);
}

public class RiskyPlayer : IObserver
{
public string BoxerToPutMoneyOn { get; set; }

public void Update(ISubject subject)
{
var boxFight = (BoxFight)subject;

BoxerToPutMoneyOn = (boxFight.BoxerAScore > boxFight.BoxerBScore) ? "I put on boxer B, if he win I get more!" : "I put on boxer A, if he win I get more!";


Console.WriteLine("RISKYPLAYER:{0}", BoxerToPutMoneyOn);
}
}

public class ConservativePlayer : IObserver
{
public string BoxerToPutMoneyOn { get; set; }

public void Update(ISubject subject)
{
var boxFight = (BoxFight)subject;

BoxerToPutMoneyOn = (boxFight.BoxerAScore < boxFight.BoxerBScore) ? "I put on boxer B, better be safe!" : "I put on boxer A, better be safe!";

Console.WriteLine("CONSERVATIVEPLAYER:{0}", BoxerToPutMoneyOn);
}
}

Here below we have subject which is observed by players:

    public interface ISubject
{
void AttachObserver(IObserver observer);
void DetachObserver(IObserver observer);
void Notify();
}

public class BoxFight : ISubject
{
public List<IObserver> Observers { get; private set; }
public int RoundNumber { get; private set; }

private Random Random = new Random();

public int BoxerAScore { get; set; }
public int BoxerBScore { get; set; }

public BoxFight()
{
Observers = new List<IObserver>();
}

public void AttachObserver(IObserver observer)
{
Observers.Add(observer);
}

public void DetachObserver(IObserver observer)
{
Observers.Remove(observer);
}

public void NextRound()
{
RoundNumber++;

BoxerAScore += Random.Next(0, 5);
BoxerBScore += Random.Next(0, 5);

Notify();
}

public void Notify()
{
foreach (var observer in Observers)
{
observer.Update(this);
}
}
}

Usage, or how we build one-to-many relationship by attaching observer-s:

            var boxFight = new BoxFight();

var riskyPlayer = new RiskyPlayer();
var conservativePlayer = new ConservativePlayer();

boxFight.AttachObserver(riskyPlayer);
boxFight.AttachObserver(conservativePlayer);


boxFight.NextRound();
boxFight.NextRound();
boxFight.NextRound();
boxFight.NextRound();

Output:

RISKYPLAYER:I put on boxer A, if he win I get more!
CONSERVATIVEPLAYER:I put on boxer B, better be safe!

RISKYPLAYER:I put on boxer B, if he win I get more!
CONSERVATIVEPLAYER:I put on boxer A, better be safe!

RISKYPLAYER:I put on boxer B, if he win I get more!
CONSERVATIVEPLAYER:I put on boxer A, better be safe!

RISKYPLAYER:I put on boxer B, if he win I get more!
CONSERVATIVEPLAYER:I put on boxer A, better be safe!

 

Been very short explanation. Just take closer look on interfaces in examples, this should be enough to understand everything.

My design patterns table


No comments


Exam 73-503: TS: Windows Communication Foundation – PASSED

November 27, 2010 Certification, Success, WCF 3 comments

I recent posts I mentioned that I read training kit for ms WCF exam. Of course I did this for some reason. I had this exam scheduled for yesterday as well as presentation on WCF for Thursday, which went extremely well. All that was scheduled because I decided to throw myself out of comfort zone. I now can ensure you that this approach indeed works. So, if you want to achieve something don’t hesitate – just go ahead and put some deadlines for yourself, and make them visible to others so this will be controlling your activity.

How did I prepare?

So I’m completely sure that positive result of this exam was guaranteed by my experience working with WCF. But anyway I read training kit, which brought many interesting aspects and some kind of hints for the exam. Third learning source (after experience and training kit) was MSDN and writing simple applications by my own. I do not like to use examples from training kit, also I found few mistakes in kit. Thursday’s presentation on WCF helped me as well, I strengthen my knowledge in transactions and instancing. Just before exam I tried MeasureUp demo test and got 6 out 6 – never got this at MeasureUp for other exams.

Passing Exam

Exam has 45 questions for 120 min. And I liked answering for them, since I faced dozen of questions related to what I do in my everyday work.

I PASSED EXAM with score 918, this means that I answered correctly on 41 questions. Woo hoo!

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


3 comments


.NET ROCKS said “Hello” to Andriy Buday

November 25, 2010 Personal No comments

As many of you know I listen to many of podcasts. Just use this link. One of my favorite of course is .NET ROCKS.

image

I new that they wanted to be at Sinergija10 so I asked my friend Dmitriy Maleev to take some cool pictures of them. But he did much more – he got this:
Richard Campbell from .NET Rocks greeting me:

NETROCKS_HelloToAndriyBuday_RichardCampbell

I probably have to tweet this hundred times :)
Thank you very much, Dima for this!


No comments


DevMeeting: WCF–Advanced-1

November 25, 2010 DevMeeting, Presentation, PublicTalks, WCF 2 comments

 

Today I performed meeting on WCF. It was continuation of this thread of meetings.

Couple of interesting facts about this presentation:

1) I started preparing at 3AM and continued doing this till actual presentation at 1 PM. (Yeah I of course responded to some of e-mails at work and did some other stuff, but anyway most time spent on preparation)

2) Also I want to my English teacher to forgive my absence on today’s English Lesson. Additional 1,5 hour really helped me. Guys, could you please ensure her that presentation cost all the money?

3) I took to much stuff to talk during 1 hour. Initially I prepared following list:

  • Basics overview
  • Sessions and Instances
  • Transactional Services
  • Concurrency
  • Security
  • Instrumentation
  • Most often troubles you might face using WCF

So I crossed some items, but it turned about that we had time only for two first items in bold.

Regardless of that many people, I’m sure, liked it very much.

4) I did a lot of coding during presentation, I hope guys liked this. Right?

5) I was forgetting about zooming and colors on projector. My bad.

6) There was not enough sit places for guys, many of them simply stand near the wall. Sorry for that. I hope managers will resolve this issue soon. He-he.

7) I kept them all interested in further presentation, since Security was not mentioned at all :-P

8) Main Links from this presentation:

9) You can go and download my presentation (I removed transactions to have something to show next time) using this link.

10) So mainly I talked on Sessions and Instances.

11) But, then I also talked on items listed below:

  • Throttling
  • Quotas
    • MaxReceivedMessageSize
    • ReaderQuotas
  • Demarcating
  • Instance Deactivation

12) Thank you!

Guys, I will appreciate your comments/suggestions/thoughts here!


2 comments