WCF: Instrumentation: Parameter Inspector

November 22, 2010 WCF 4 comments

Let’s take a look how we use one of the instruments of the WCF, called Parameter Inspector.
Here below we see how message request goes between Client and Service.
image
Let’s now imagine that we have some kind of calculator on service side, that has method string Execute(int a, int b, string operation). Client should be very careful in passing parameters to the service, because service is developed by some other team, and after you pass incorrect parameters it fails.
It turns out that with WCF services we are not required to implement such logic before calling method. It can be applied to your request when passing to service. Either just before passing it to channel stack at client or at dispatcher after it came from network on server.
On the picture below we see more closely what is at proxy layer, and 3 points where you can inject your logic.
image So moving forward I’m going to implement Parameter Inspection for my calculator example.
Here is implementation of my calc service. Please take a look that for this naive example, I’m killing process when operation is not available. Of course in standard situation with WCF we would probably throw fault exception and catch it on client side. But for now, lets assume that there is some super logic on service and we cannot change calculator code – it stops working is we pass wrong operation string.
    public class CalculatorService : ICalculatorService
    {
        public int Execute(int a, int b, string operation)
        {
            Console.WriteLine("Received request: ({0}{2}{1}=?)", a, b, operation);

            int result = -1;
            switch (operation)
            {
                case "+":
                    result = a + b;
                    break;
                case "-":
                    result = a - b;
                    break;
                case "*":
                    result = a * b;
                    break;
                case "/":
                    result = a / b;
                    break;
                default:
                    Console.WriteLine("Our calc executed hara-kiri.");
                    Process.GetCurrentProcess().Kill();
                    break;
            }
            return result;
        }
    }
Client is the most standard, that you can imagine, it asks calculator for answer by passing parameters entered in console in while loop.
                        var res = calculatorServiceClient.Execute(a, b, op);
                        Console.WriteLine(res);
Now let see how calc crashes on ‘@’ operation:
image We want to execute parameters verification before calling method on server, and if parameters do not satisfy us, we abort calling calculator. For this I simply surround call to the service in my client in following way:
                    try
                    {
                        var res = calculatorServiceClient.Execute(a, b, op);
                        Console.WriteLine(res);
                    }
                    catch (ArgumentException exception)
                    {
                        Console.WriteLine(exception.Message);
                    }
So how do we get ArgumentException on client? We add custom behavior to the client endpoint.
            using (var calculatorServiceClient = new CalculatorServiceClient("WS2007HttpBinding_ICalculatorService"))
            {
                calculatorServiceClient.Endpoint.Behaviors.Add(new CustomEndpointBehavior());

                calculatorServiceClient.Open();
                
                // ... 
So custom behavior allows us add operation, message and parameter inspectors. In my example I will only add parameter inspector. See below:
    public class CustomEndpointBehavior : IEndpointBehavior
    {
        public void Validate(ServiceEndpoint endpoint)
        {
            return;
        }

        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
            return;
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            return;
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            foreach (var clientOperation in clientRuntime.Operations)
            {
                clientOperation.ParameterInspectors.Add(new OpParameterInspector());
            }
        }
    }

    public class OpParameterInspector : IParameterInspector
    {
        public object BeforeCall(string operationName, object[] inputs)
        {
            switch (operationName)
            {
                case "Execute":
                    VerifyExecuteParams(inputs);
                    break;
            }

            return null;
        }

        private void VerifyExecuteParams(object[] inputs)
        {
            if (new string[]{"+", "-", "*", "/"}.Where(x => x == (string) inputs[2]).Count() == 0)
            {
                throw new ArgumentException("Your operation should belong to folowing list: '+', '-', '*', '/'. Please verify and try again.");
            }
        }

        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {
            return;
        }
    }
And as result of our work we got parameters validation, not completely in client code and not on server, but somewhere in the middle (yeah, it is still client, but validation is postponed to next step in WCF pipeline – Proxy).
image
While learning WCF I wonder how many different extensions and flexibility it allows. Not sure if it all is needed, but if you have doubts if WCF can or cannot do something, be sure – it can.


4 comments


Book Review: GREAT BOSS DEAD BOSS

November 22, 2010 Book Reviews No comments

image I had awesome chance to read book called “Great boos dead boss”, ‘cause one of my wisdom bosses have recommended it. Probably he was driven to do this by latest law of tribe. Tribe? Yeah, I spelled it correctly. Latest law states that each good leader has teacher who knows and can achieve more than his apprentice. First of all, I want to thank my manager very much for suggesting this book.

“So what was there about tribe?” – I hope you have this question in your mind. Let us answer for this question one by one, but I will not give you complete answer for this, because you have to read book to understand completely and to be part of the tribe of readers of this book :)

Greg, main hero of the book, got new job at big microprocessors plant and as usual in such novels there is huge customer with deadline, that cannot be achieved by applying any kind of normal and standard improvements to production of processors. Even more, people at plant are completely exhausted being bombarded with dozen of improvements and built-in administrative control. Greg felt huge confrontation between him and employees, he felt stuck with this tough situation. He ran for help to leader of another company where each employee felt complete comfort and happiness working, each of them was highly motivated and enthusiastic. Greg started to build his own tribe, using hints given to him by leader, who was colonel in army and still likes hunting in Africa. Whole story finishes with triumph of project completed before deadline and with wisdom, that was absorbed by main hero.

Really extraordinary about book is that it shows collaboration between people, their motivation, emotions and acts in light of the most ancient social grouping – tribe. Book really convinces us that when people have common enemy, common ideas and symbols they are motivated to fight and be the best company in their field. Book is concentrated on People not at the process, because process can be improved by people. You only have to find something to trigger people.

I highly recommend you read this book if you are interested to hear some good ideas about management in another light.



No comments


Command

November 15, 2010 Design Patterns 4 comments

You have a boss, who doesn’t care who will be doing some work or how it will be done, he just want it to be started and completed at some point of time, say after customer signed contract. Since you are at high position you were asked to form team A that will be working at some project X, you also got list of high-level requirements from your boss. You should be ready to start all work at the moment your customer signs contract.

COMMAND

So you are Command – you encapsulate receiver team A and parameters to start work (project and requirements). Team and requirements are given to you by your boss – Client.

You are able to delegate all work to team A and provide requirements at the moment customer triggers process. Your customer is Invoker, they have contact to you, so can use you as they want.

Command – is design pattern that allows us encapsulate request, tune it with parameters as needed and then execute at one point of time, without knowing how actually executes work.

Client code

Here is how story looks from code perspective. Taking a look at client code (boss):

            var customer = new Customer();

// for some reason boss always knows that company has money
// only for team Z
var team = new Team("Z");
// he also managed to get high-level list of requirements for you
var requirements = new List<Requirement>() { new Requirement("Cool web site"), new Requirement("Ability to book beer on site") };
// you should be ready to be invoked by Customer
ICommand commandX = new YouAsProjectManagerCommand(team, requirements);

customer.AddCommand(commandX);

// there is also here developer who can code at light speed
var heroDeveloper = new HeroDeveloper();
// boss decided to give him project A
ICommand commandA = new HeroDeveloperCommand(heroDeveloper, "A");

customer.AddCommand(commandA);

// when customer signs contract with boss
// your team and hero developer start executing their job
customer.SignContractWithBoss();

Command

Now lets take a look on two concrete commands:

    public interface ICommand
{
void Execute();
}


public class YouAsProjectManagerCommand : ICommand
{
public YouAsProjectManagerCommand(Team team, List<Requirement> requirements)
{
Team = team;
Requirements = requirements;
}

public void Execute()
{
// implementation delegates work to concrete receiver
Team.CompleteProject(Requirements);
}

protected Team Team { get; set; }
protected List<Requirement> Requirements { get; set; }
}

public class HeroDeveloperCommand : ICommand
{
public HeroDeveloperCommand(HeroDeveloper heroDeveloper, string projectName)
{
HeroDeveloper = heroDeveloper;
ProjectName = projectName;
}

protected HeroDeveloper HeroDeveloper { get; set; }
public string ProjectName { get; set; }

public void Execute()
{
// implementation delegates work to concrete receiver
HeroDeveloper.DoAllHardWork(ProjectName);
}
}

Receiver

Team and HeroDeveloper are receivers of work that should be done.

Invoker

Customer simply aggregates many commands and without knowing how those commands were built by boss. Customer as true invoker simply triggers work using Execute method:

    public class Customer
{
public Customer()
{
Commands = new List<ICommand>();
}

public void AddCommand(ICommand command)
{
Commands.Add(command);
}

protected List<ICommand> Commands { get; set; }

public void SignContractWithBoss()
{
foreach (var command in Commands)
{
command.Execute();
}
}
}

Output

User Story (Cool web site) has been completed

User Story (Ability to book beer on site) has been completed

Hero developer completed project (A) without requirements in manner of couple of hours!

UPDATE: Nov 18, 2010

UML-Diagram

Here below I added diagram showing two commands exactly as in example. Please take into account that for simplicity you can remove one pair HeroDeveloperCommand-HereDeveloper. Also take into consideration that in our example concrete commands are aggregating receivers, but this is not common situation. In most cases receiver is some another system.

image


4 comments


Book Review: MCTS exam 70-503 Windows Communication Foundation Training Kit

November 14, 2010 Book Reviews, Certification, WCF No comments

imageSo accordingly to my Career Plan for Software Engineer, I want to pass some Microsoft exams. Next one (see end of 2010) is 70-503 – WCF. Which I already scheduled for 26th November.
Now few words about book itself. It indeed covers all core of WCF and huge set of WCF features/usages. What I liked is explanation of various bindings/enumerations/settings because they are showed in structured order. Yeah, from some point of view it is boring to read tables describing some of the features, but now I know that I can refer to this book as to good catalog of all WCF features.
I’ve been working with WCF for about 1 year or so, but did not understand all in depth. First of all the most difficult was to keep an eye on all that complex configuration on server and client for whole bunch of our services. But now I see that if I would have read this book before I would have much better understanding of things and would be more efficient in configuring and implementing services.
I’m also planning to perform second (first here) “developer’s meeting” for my team on features of WCF. This time it should be Advanced course. It might be difficult to talk about WCF in depth, because not all guys here work with it and it might require for them to try out basics at first, but I believe in them and in my capabilities to show all ready-cooked on the plate.


No comments


Bridge

November 8, 2010 Design Patterns 2 comments

Imagine that you own huge building company. It builds houses and apartment blocks all around your city. Building are of two types – either built with concrete blocks or with bricks. Since you are boss when you were deciding how to divide work you have decided that all crews will have same operations like BuildFoundation, BuildRoom, BuildRoof. But because houses are of two types you had to always keep two teams (aka. two concrete).
Once it turned out that couple of buildings were of mixed type where you had to build some rooms with concrete blocks and some with bricks. For this reason you had to move whole teams from one part of the city to another. You got many complains from your employees, they suggested moving only that part of team that is specialized in building rooms, so you can easily move small crew of workers and reassign it easily to any team instead of having two separate teams. And that is idea.

BRIDGE

Bridge is design pattern that allows you decouple realization from its abstraction, therefore your realization can be changed separately from abstraction because does not implement it directly.
In other words, our IBuildingCompany might have two concrete realizations like NearSeeBuildingCompany and CityBuildingCompany, each of them does probably something different for their foundation and roof, but at the same time we can easily and quickly reassign WallCreator crew for each of those companies to build either brick or either concrete walls.

Let say we have BuildingCompany as below:

    internal interface IBuldingCompany
    {
        void BuildFoundation();
        void BuildRoom();
        void BuildRoof();

        IWallCreator WallCreator { get; set; }
    }

    internal class BuldingCompany : IBuldingCompany
    {
        public void BuildFoundation()
        {
            Console.WriteLine("Foundation is built.{0}", Environment.NewLine);
        }

        public void BuildRoom()
        {
            WallCreator.BuildWallWithDoor();
            WallCreator.BuildWall();
            WallCreator.BuildWallWithWindow();
            WallCreator.BuildWall();

            Console.WriteLine("Room finished.{0}", Environment.NewLine);
        }

        public IWallCreator WallCreator { get; set; }

        public void BuildRoof()
        {
            Console.WriteLine("Roof is done.{0}", Environment.NewLine);
        }
    }

So what is so interested about it? Answer is property WallCreator, which is exactly our bridge to implementation.

Usage code

Let see this in action:

            // We have two wall creating crews - concrete blocks one and bricks one
            var brickWallCreator = new BrickWallCreator();
            var conctreteSlabWallCreator = new ConcreteSlabWallCreator();

            var buildingCompany = new BuldingCompany();
            buildingCompany.BuildFoundation();

            buildingCompany.WallCreator = conctreteSlabWallCreator;
            buildingCompany.BuildRoom();

            // Company can easily switch to another wall crew to continue building rooms
            // with another material
            buildingCompany.WallCreator = brickWallCreator;
            buildingCompany.BuildRoom();
            buildingCompany.BuildRoom();

            buildingCompany.BuildRoof();

Isn’t it awesome? Output should be intuitive, but since I did not show implementations of BrickWallCreator and ConcreteSlabWallCreator I’m going to list it below:

Foundation is built.
Concrete slab wall with door.

Concrete slab wall.

Concrete slab wall with window.

Concrete slab wall.

Room finished.
Brick wall with door.

Brick wall.

Brick wall with window.

Brick wall.

Room finished.
Brick wall with door.

Brick wall.

Brick wall with window.

Brick wall.

Room finished.
Roof is done.

UML diagram illustrates how this pattern looks like and why it is called bridge.

image
My design patterns table


2 comments


Throw yourself out of comfort zone

November 8, 2010 Opinion, Success 2 comments

Some time ago I twitted “To be successful throw yourself out of comfort zone”. I had this idea long time ago, but did not write about it. I see that I have to post something about this, since I’m becoming lazy and I do not like this at all.

Fascinating Uncle Bob

Yesterday I listened Uncle Bob’s thoughts on “Pragmatic Podcast”. (Who doesn’t know Uncle Bob is Robert Martin). That was “fascinating”, he is “fascinating” person and I was inspired by this episode. He has that much energy after being in computer field for about 40 years he is still interesting in everything new. He talks about new and old programming languages he understands software development deeply. What inspired me the most is his attitude to all of this and his bright energetic view on programming. He reads science fiction, rides his bicycle every day and has extended family. This all helps him be in good shape. I would recommend to listen to this podcast – just download and listen when you have time.

Yesterday I complained to my girlfriend about my situation and not satisfaction of what I’m doing now. She stated that I do not have enough activities outside of my work. Yes, but my blog is my 3-rd place where I’m trying to find myself. But I also did not post lot in recent time. This means that something is wrong. So here in this post I would like to talk a bit about this “something wrong”.

Finishing tasks in latest moment

I guess this is not a big secret that many people tend to do everything in the last moment. Working in the last moment is hard, but very productive. Many of us extremely enjoy when they have finished something well and when in the last moment you triumph. I had many of such moments and they made me happy.

Of course there are techniques called “time management” where ideologists try to address this issue. At least in one of the techniques it is mentioned about separating all the tasks you have to do into 4 sets. The most important and best known is one where you have important but not immediate tasks. Books on  management recommend to work in this set continuously time to time and soon you will have all tasks that are important but not immediate completed before it is becoming hot. What can I say about this idea? It is indeed good and awesome, but it doesn’t work for me at all, and probably it doesn’t work for many of us.

In recent time I had some posts talking about my future plans, like reading 24 book till end of the year, passing couple of ms exams, becoming senior developer, etc. Yeah, I did huge portion of these, but there is only two months left till the end of year and I still wait for the latest moment when I can pass yet another milestone. For example I’m reading training kit for wcf exam and it goes so slowly that you cannot even imagine. But when I had exam on winforms and I knew that only 1 month is left to it and reading was much more rapid. Same shall be done to wcf exam, I think. Just schedule and this will force me to read and train. Today I gonna schedule my exam for the end of this month.

We have to make us busy

Many of us are very busy at work, we are even often working from home. This is tremendously helpful in moving forward in your career and if this is accordingly to your plan, you are fine. But I guess you have too many other plans that you would love to accomplish. Where do you have them located? In list with lowest priorities? Not written somewhere at all? Anyway unless you have some deadline for task X you are not really hurrying to accomplish it. If you have also tasks Y and Z and you see them “nice to have” you probably will not do them since X will be done in latest moment. What about Y and Z then?

So what do I propose to do? Have external visibility of your progress. If you are person with high responsibility you will do your best to accomplish all of your tasks because you are sure that others keep an eye on you. In my case I can schedule exam and write blog post on this. I will know that you readers are keeping eye on my. Even if this is not so important for you, it is very important for me.

Doing easy or doing complex tasks

When I started learning my university I had extremely strict teacher. He had banished out of university many students (1/3 of my academic group in 2 years); receiving high rates was incredibly hard as well. This challenge forced everyone to intensive learning. Never in my life I had that painful learning. With other guys we spent nights and days on learning, we slept about 4-6 hours for couple of weeks before exams. (I guess there are people reading blog that have finished my university as well: I’m talking Fedyk). If software developers would sharpen their skills and other engineers would work in their field that intensive, we would have artificial intelligence already up and running on the streets :).

So if you feel that you are currently in lucky situation, because you do not have lot of work and you can work relaxed, something is wrong with your attitude to work and your busyness. If indeed that is the case, use that time for your personal development for career and etc. But first please check why you do not have that much work, maybe you are lazy ass.

I also see this to be the way to teach new junior developers. I guess it is great to give them challenging work. It is not always easy to find such work, but that is the greatest you can do for them. In recent time I’ve got new apprentice, if you will. I see it would be hard for him to fit our team and start working effectively in manner of one month term. I have to try different approaches to quickly coach him – kinda throwing him out of comfort zone and then managing stress as one book recommended.


2 comments


I spoke again about DDD at Lviv JUG

November 5, 2010 Uncategorized 4 comments

Here in Lviv we have awesome Java User Group and yesterday I had chance to speak there and again about DDD. So I probably have nothing to add about presentation itself. Presentation has only this icon on the top as a difference:

image

But I have something to add about the group itself and performance. Group is slightly different from .NET one. It is smaller – about 15 people were listening to me. But guys in group have much more solid experience in developing software. They all are in their late 20th and some in 30th I guess. They ask slightly another scope of questions. All of the them know how to build complex software and they know a lot of design patterns. That is why I guess listening about DDD was not something special and absolutely new for them, since I see DDD as some (new) set of (existing) design patterns and (existing) approaches to build software starting from model.

After my presentation, very enthusiastic person Zenyk talked about one of the approaches of using Amazon could. For me it was very interesting and exciting, since it was first time I’ve heard about more or less complete solutions based on many Amazon services.

BTW, Zenyk does great job on keeping software developers community site, all in Ukrainian:

rozrobka.com

Group is not sponsored by Oracle, as .NET group is sponsored by Microsoft. They do not have that many presents, but they do their best in keeping their own library of books.

Looking forward to hear from guys, who listened to me.


4 comments


TSQLUnit – testing logic in database? Should logic be there?

November 1, 2010 Opinion, SQL 6 comments

Today I’ve been on technical meeting where TSQLUnit was discussed as approach of testing database.

From what I understood it looks like this is very powerful and great tool for testing stored procedures and other execution code inside of SQL Server. It allows easily create setup for each test with minimal database schema, needed exactly for some particular stored procedure. After test got executed it rolls back to state before running test. Cool!

From my point of view this is really good thing to test stored procedures in isolated environment, as any good UT does with testing code. There is also question about integration of those tests with changes in real database and one great mind have produced using schemabindings in SQL Server.

It should be also possible to integrate TSQLUnit with CI by using NAnt.

Why?

There is only one thing I kept in my mind and did not talk about it during meeting. It is question: why do we still write lot of stored procedures? Yea, I understand that sometimes they are really needed and that there are some reporting projects that might require fetching lot of data at once. But during the meeting it looked like guys are going to use it for many other projects. Hm… From my point of view, this kind of tests should be written in regular programming language, executing some code and fetching needed data as it will be used further, after roll-backing inserted data – therefore we have integration tests. All them should run separately. And as per me this should be fine unless you have logic in database – I agree, that in this case we have to come to some database testing tools. Why should we have logic it in database unless there are some special requirements?

I still feel a bit frustrated, because for me it is quite hard to answer for the question of having logic in code or having some heavy portion of it in database. I vote for first variant, but maybe I do not have enough experience to understand why it is great to have logic in database. Who knows?

What do you think?


6 comments


Lviv .NET UG, 7-th meeting took place

November 1, 2010 DDD, Opinion, PublicTalks, Success No comments

 

I had chance to speak at yet another Lviv .NET UG meeting. This time I spoke about Domain-Driven Design. It looks like people got interested in this topic.

You can read my feedback post about this event at Lviv .NET UG site by the link “Зустріч #7. Враження, враження, враження…” (it is in Ukrainian).

I will write almost the same here and add some own opinions, so it would be interested not only for those who doesn’t know Ukrainian, but for those who would like to hear my personal opinions.

How it was

It was really great that we’ve got more than 80 people registered for this event. And if company where we hosted this event would provide us with bigger meeting room, we would probably have over 50 near 60 people attending. So as you understand because there was lack of physical room some people just turned around and went home. Crap! I would love to have them all listening to me.

Getting Scrum

Event has two speakers, me and Igor Racyborynsky. Ihor talked about “Getting Scrum”. We all played scrum and formed following product backlog:

PA295635[1] 

It was really interesting, at least not as usual presentation. But he has not covered all about the scrum and at least key concepts. Although it went extremely good.

Domain-Driven Design

I talked about Domain-Driven Design for the 5th time. Yeah! I even don’t need any time to get prepared.

PA295689[1] 

It was late in the evening, so many people got tired, especially me talking over 1 hour bombarding with new and new terms and mentioning lot of information about known concepts and patterns.

This time I’ve got many different cool presents:

  1. Yet another VS2010 bag (exactly as one I already have)
  2. IE9 T-Shirt
  3. Pen and notebook

Do you know what I like about delivering presentation to huge audience? – I always get couple of people that are excited about my speech and interested in my. They then come and talk with me as I’m an expert. I feet bit scary and nervous to show that I’m not that cool :)

Beer

As usual we have small beer party in the end. This time it probably wasn’t that small. You decide:

PA295665[1]

Speaking at JUG about DDD

Today I was invited to Java User Group meeting to talk about DDD again. Thank you guys.


No comments


What the hack is NuPack

October 17, 2010 Uncategorized No comments

 

NuPack is package manager for .NET introduced to help developers easily work with 3rd party libraries.

Here is great post on NuPack, I would recommend to read.

But as I promised in twitter to have blog post called “What the hack is NuPack”, I need to post this.

So,… downloading…

image

After it get downloaded and installed, we have one additional menu item in same place where we do have “add reference”:

image

So what does “Add Package Reference” do?

It takes a look on the feed for packages, where you see 3rd party you can add. On the picture below I just added AutoMapper, by clicking “Install”.

SNAGHTML65533ec

I can easily search for other components and install them. On the picture below I easily searched for my favorite ORM – Nhibernate and installed it. But if you ever worked with it you know that it depends on few other 3rd party, such as log4net, etc. Great news! They all get installed automatically.

SNAGHTML658fe5c

Physically it puts config file within your project and locate all your components under folder ”packages” along with your solution file, like below:

image

After that I got interested to know how it behaves with couple of solutions all in SAME folder, and figured out that it works just fine – it puts everything into same folder.

Everywhere I read about nupack they all declare that it is solution related, so I have one folder for solution. But as you may know I work with enterprise project and we keep all 3rd party in separate location where dozen (20-30) solutions are looking for references. And it looks that I do not have possibility to configure NuPack to put “packages” folder in another place. Or I’m missing something. Please let me know.

EDITED (Oct 17, 11:39PM): I already got an answer for my question:

image

So to shortly summarize:

NuPack allows you easily fetch whole range of different 3rd party components and momentarily add references to your projects without need to manually go and download them, then unpack and reference. Also NuPack allows you easily manage all of your components, allowing you update them and do other cool stuff. Go and check it out!


No comments