November 25, 2010 WCF No comments
November 25, 2010 WCF No comments
Sessions and Instances
Per Call*
On each request to service (each time we use service method) new instance of Service implementation will be generated. Often this is not suitable for us when we want some to keep track of actions (transactions) or when we access some critical resources.
Per Session*
Is default Session mode. (BTW book on preparation to 70-503 has mistake mentioning that PerCall is default). In this case client knows that Service provides sessions. We can also highlight requirement of using sessions by marking contract with SessionMode.Required. Session is kept with identifier assigned to you proxy class, that you use at client.
We also have possibility to share same instance of service by passing additional identifier in message header that goes from Client. For that we would need to implement IInstanceContextProvider.
Singleton
Is more rarely used Session mode, but it might be useful when we access one super-critical resource. Plus to that that one plus in using this session mode – possibility to create instance of service even before service host has been created.
* Pictures, but not text below, were taken from training kit book for ms exam 70-503: Link
November 23, 2010 Design Patterns No comments
Did you ever think why so many things around us have tree-similar structure? Top management of your company can delegate some work to middle management, and it can delegate it to your direct manager, who will ask you and your colleagues do something. In one of your tasks you had to gather data for some customer into xml. XML has also tree-similar structure. Why? Because it is the best way to serialize data, that can have data, that can… You got that! Now imagine that you want to gather data for some document part by part.
Composite is design pattern that provides us tree-similar structural representing of classes, this allows us work uniformly with parents and Childs.
So interface that defines common requirements for parents and kids:
public interface IDocumentComponent { string GatherData(); void AddComponent(IDocumentComponent documentComponent); }
And here we see some leaf component implementation. It is Customer Component, which gathers some data about customer basing on id provided to the class.
public class CustomerDocumentComponent : IDocumentComponent { private int CustomerIdToGatherData { get; set; } public CustomerDocumentComponent(int customerIdToGatherData) { CustomerIdToGatherData = customerIdToGatherData; } public string GatherData() { string customerData; switch (CustomerIdToGatherData) { case 41: customerData = "Andriy Buday"; break; default: customerData = "Someone else"; break; } return string.Format("<Customer>{0}</Customer>", customerData); } public void AddComponent(IDocumentComponent documentComponent) { Console.WriteLine("Cannot add to leaf..."); } }
And not-leaf implementation of the component below. Please take into account that it simply loops through Childs and executes GatherData method.
public class DocumentComponent : IDocumentComponent { public string Name { get; private set; } public List<IDocumentComponent> DocumentComponents { get; private set; } public DocumentComponent(string name) { Name = name; DocumentComponents = new List<IDocumentComponent>(); } public string GatherData() { var stringBuilder = new StringBuilder(); stringBuilder.AppendLine(string.Format("<{0}>", Name)); foreach (var documentComponent in DocumentComponents) { documentComponent.GatherData(); stringBuilder.AppendLine(documentComponent.GatherData()); } stringBuilder.AppendLine(string.Format("</{0}>", Name)); return stringBuilder.ToString(); } public void AddComponent(IDocumentComponent documentComponent) { DocumentComponents.Add(documentComponent); } }
Gluing parts to be some kind of document:
var document = new DocumentComponent("ComposableDocument"); var headerDocumentSection = new HeaderDocumentComponent(); var body = new DocumentComponent("Body"); document.AddComponent(headerDocumentSection); document.AddComponent(body); var customerDocumentSection = new CustomerDocumentComponent(41); var orders = new DocumentComponent("Orders"); var order0 = new OrderDocumentComponent(0); var order1 = new OrderDocumentComponent(1); orders.AddComponent(order0); orders.AddComponent(order1); body.AddComponent(customerDocumentSection); body.AddComponent(orders); string gatheredData = document.GatherData(); Console.WriteLine(gatheredData);
Output is somewhat similar to XML. At least I tried to keep it similar.
<ComposableDocument>
<Header><MessageTime>8:47:23</MessageTime></Header><Body>
<Customer>Andriy Buday</Customer>
<Orders>
<Order>Kindle;Book1;Book2</Order>
<Order>Phone;Cable;Headset</Order>
</Orders>
</Body>
</ComposableDocument>
Also GoF guys suggest having Remove(Component) and GetChild(int) methods in your Component, so you might want to add them. Just don’t limit yourself with any kind of explanations. You might have some unique need.
November 22, 2010 WCF 4 comments
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; } }
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; } }
November 22, 2010 Book Reviews No comments
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.
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.
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.
November 14, 2010 Book Reviews, Certification, WCF No comments
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.
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.
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:
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:
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.
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?