Friday, May 6, 2011

[Tutorial] Common Design Patterns in C# 4.0
Part4: Factory Method Pattern

Pattern Name:
Factory Method

Short Description: 
Create instances of derived classes

Usage:
Frequently used, fairly easy to implement and useful for centralizing object lifetime management and avoiding object creation code duplication

Complexity:
1 / 5

UML Class Diagram:

image

Explanation:

  • The abstract creator implements a factory method that returns an objects. It also contains a method for testing purposes that serves to validate the design.
  • Each concrete creator overrides the abstract factory method and returns a specific object concerning on the context.
  • In this example the factory method is used internally to set a property but it could also be used in an external context for creating objects when needed.

image

  • The abstract class defines the interface and class structure for all objects that get build by the specific concrete creators via their factory methods.

image

  • There is also the possibility to create a C# specific solution that uses generics which also results in a valid factory method.

image

image

  • In the last step we add some code to test the software design and the Factory Method implementation in the language agnostic and in the C# specific versions.

image

  • When running the example you can see that everything is working as expected and that the correct classes are instantiated during runtime.

image

Source Code:
http://csharpdesignpatterns.codeplex.com/


Share/Save/Bookmark

Thursday, May 5, 2011

[Tutorial] Common Design Patterns in C# 4.0
Part3: Builder Pattern

Pattern Name: 
Builder Pattern

Short Description:
Separate representation and  object construction

Usage: 
Rarely used, only useful if complex objects consisting of multiple parts need to be constructed (composite objects for example)

Complexity:
1 / 5

UML Class Diagram:

image

Explanation:

  • The director (ComputerShop) implements a method that is responsible for the sequence of steps of an object creation process. It takes an abstract builder class as input parameter and delegates the real creation to it.
  • The abstract builder class defines the interface that all inheriting concrete builders will use for object creation.

image

  • The concrete builder implementations contain the parts that are assembled and that build the objects.

image

image

image

  • The final object contains all different parts that get assembled by the concrete builder classes. Those may differ from each other depending on the implementations.
  • A method was added that prints out the characteristics of the different parts to be able to validate the design.

image

image

  • In the last step we add some code to test the software design and the Builder implementation.

image

  • When running the example you can see that everything is working as expected and that the correct classes are instantiated during runtime.

image

Source Code:
http://csharpdesignpatterns.codeplex.com/


Share/Save/Bookmark

Wednesday, May 4, 2011

[Visual C# 5.0] CTP-SP1: Refresh of the new Async features containing optimizations, additions and bugfixes

Microsoft recently released a new version of the async features in a CTP-SP1 version. The goal remains the same: enable developers to write asynchronous code in an easy way, so that they do not need to learn any new skills and writing asynchronous code gets as straightforward as writing synchronous code.

The initial pattern of using Task<T> (class that was introduced in .NET 4 with the parallel features) is still the basis for the new async features. Nothing changed concerning that and allover there are no major changes. There are however multiple optimizations, additions and bugfixes (close to 400 bugs were found in the first CTP).

New features and modifications:

  • Visual Studio 2010 SP1 compatibility (the previous CTP only worked with Visual Studio 2010)
  • Support for Windows Phone 7 development
  • The old pattern of using GetAwaiter | BeginAwait | EndAwait was replaced with the new pattern GetAwaiter | IsCompleted | OnCompleted | GetResult that provides better performance and makes fast path more efficient

Some of the bugfixes concern:

  • Possible race conditions in finally blocks
  • Equality tests with Nullables could sometimes evaluate the operands more than once
  • Wrong behavior when accessing the base.property in an async method
  • Several Visual Basic .NET specific bugs

Start using it in your incubation projects to see how you can integrate it into your developments (especially Phone developments). Try it out !! But mind that this is still a CTP version that might evolve and change until the final version and that there is no support. So using it in any production projects is not advised.

You can find the download of the CTP-SP1 here:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=4738205d-5682-47bf-b62e-641f6441735b&displaylang=en


Share/Save/Bookmark

Sunday, May 1, 2011

[Tutorial] Common Design Patterns in C# 4.0
Part2: Abstract Factory Pattern

Pattern Name:
Abstract Factory Pattern

Short Description:
Create instances of classes belonging to different families

Usage:
Very frequently  used and very useful

Complexity:
1 / 5

UML Class Diagram:

image

Explanation:

  • The abstract factory class defines the abstract methods that have to be implemented by concrete factory classes. It serves as interface and contract definition.
  • The concrete factory classes contain the real implementation that define which classes are created during run-time.
  • Note that the methods return values are also defined by abstract classes, this allows a high flexibility and independence, leading to methods that must only be implemented once.
  • The returned classes are however specific to each concrete factory class (you will see their implementation below).

image_thumb1[2]

  • Here you see the abstract classes that are used during the creation process (a method was added that serves to prove the validity of the design).
  • Based on the abstract classes some real example implementation are created, those will be instantiated during run-time, depending on the concrete factory that creates them.

image_thumb5[1]

  • When implementing the associations between the Driver class, the abstract factory class and the abstract classes you may either use the common language agnostic approach using only private members (which is the most memory efficient one).

image_thumb3[1]

  • Or you may use the C# language specific approach where everything is wrapped using private properties. This allows adding logic when accessing or changing the private members but might be a little overkill.

image_thumb11[1]

  • You may also use another C# language specific solution that uses generic classes to create objects and that is also a valid implementation for the abstract factory pattern.

image

  • In the last step we add some code to test the software design and the Abstract Factory implementation.

image

  • When running the example you can see that everything is working as expected and that the correct classes are instantiated during runtime.

image

Source Code:
http://csharpdesignpatterns.codeplex.com/


Share/Save/Bookmark

Saturday, April 30, 2011

[C# - PRISM 4.0] Building highly flexible and modular applications

I already showed you some time ago how to create good and efficient code by using the S.O.L.I.D. design principles. This time I would like to focus on PRISM 4.0 and its features.

The goal for good software architecture is always the same : produce code that is flexible, highly modular, easy to maintain, simple to extend and overall as independent as possible.

This can very well be achieved by applying best practices and having good programming skills but it will get even more powerful when using existing frameworks that already contain all foundations and have all necessary patterns in place. One of the most mature and advanced frameworks is PRISM 4.0 (patterns & practices) which will allow you to be much more productive when correctly used.

image

Prism 4.0 provides guidance to help easily design and build rich, flexible, and easy-to-maintain applications. It works with Microsoft .NET Framework 4.0 and Silverlight 4, the latest technologies currently available.

It especially works well with the following project types:

  • Silverlight Applications
  • WPF Applications
  • Windows Phone 7 Applications

Furthermore it support MVVM and MEF and is open for usage with different dependency injection containers (by default it uses Unity). It is build from ground up using Design Patterns that favor separation of concerns and loose coupling which allow Composite Applications.

The goal is to partition applications into a number of discrete, loosely coupled, semi-independent components and modules that can be individually developed, tested, and deployed by different subteams.

image

PRISM 4.0 helps to achieve a very clean separation between UI and Business Logic. Efficient reuse of existing functionalities and a clean separation of concerns between horizontal capabilities (logs, custom authentication, etc…) can be very quickly attained. When using MEF it is also extremely easy to create modular applications where functionalities can be dynamically added (even during runtime).

The existing classes and functionalities really help very much and provide a robust basis on which you can build on. The concentration can really be on the business functionalities and not the surrounding shell.

image

image

Needless to say that you will have to familiarize yourself with the framework and look into examples on how to use it correctly. You should also decide if you really need to be so modular and if you will have an added value because for monolithic and simple applications it might not be advisable to have such an approach. And surely you could also build everything yourself but you might take a look and evaluate if it is usable in your context. Did I mention that it is free ? So don’t hesitate and look for yourself and try it out, it might help you to build better applications quicker, with less stress and for less money !


Share/Save/Bookmark

Thursday, April 28, 2011

[C# and Language] DevLabs Website

Microsoft is working constantly on new incubation projects to extend existing language features and add new ones. Some of the early versions of those new features can be tested on the DevLabs website. When they are considered to be accepted and they have finished their incubation period they are moved to the respective product sections (as it was done for the Reactive Extensions) or are directly integrated into the corresponding products such as Visual C#.

image

Currently there are the following incubation projects available:

  • TC Labs: Solver Foundation (build and solve real optimization models)
  • TC Labs: TPL DataFlow (extensions to the .NET 4.0 TPL addressing additional scenarios)
  • TC Labs: Dryad (process large volumes of data in many types of applications and enable LINQ on HPC systems)
  • TC Labs: Sho (connect IronPython scripts with compiled .NET code for fast and flexible prototyping)
  • Doloto (AJAX Download Time Optimizer)
  • Code Contracts (extensions to the existing .NET 4.0 version)
  • Axum (parallel applications development based on the actor model)
I am personally currently looking into TPL DataFlow, CodeContracts and Axum (since some time already) and will take some time to give you feedback on my experience in the next weeks.


Share/Save/Bookmark

Thursday, April 14, 2011

[Tutorial] Common Design Patterns in C# 4.0
Part1: Introduction Gang of Four Design Patterns

Design Patterns provide standardized and efficient solutions to software design and programming problems that are re-usable in your code. Software Architects and developers use them to build high quality robust applications.

However, you have to take care to select the right pattern for the right problem. If you need to modify the initial pattern too much, this may indicate that it is not adapted to your needs and may in the worst case lead to unmaintainable, complex and inefficient code. The opposite of what you intend when using Design Patterns !!

You may also create your own custom Design Patterns. Whenever you come up with a certain solution that is reusable in a vast majority of your projects, you may decide to abstract a design pattern out of it. Then you may create your own library of patterns and share them within your whole company, thus creating standards and ameliorating maintainability.

In this series of blog posts I am going to show you how to use the well known Gang of Four (GoF) Design Patterns in C# 4.0 code. Those patterns will work well in any project that uses C# but especially in WPF, WCF, WinForms, ASP.NET projects.

The GoF Design Patterns are divided into 3 categories : Creational Patterns, Structural Patterns and Behavioral Patterns. In my following blog posts I am going to explain each GoF Design Pattern in detail and will show you examples of how to write good C# 4.0 code that implement those patterns.

Creational Patterns

  • Abstract Factory: Create instances of classes belonging to different families

  • Builder: Separate representation and  object construction

  • Factory Method: Create instances of derived classes

  • Prototype: Clone or copy initialized instances

  • Singleton: Class with only one single possible instance

Structural Patterns

  • Adapter: Match interfaces of classes with different interfaces

  • Bridge: Separate implementation and object interfaces

  • Composite: Simple and composite objects tree

  • Decorator: Dynamically add responsibilities to objects 

  • Facade: Class that represents subclasses and subsystems

  • Flyweight: Minimize memory usage by sharing as much data as possible with similar objects

  • Proxy: Object that represents another object

Behavioral Patterns

  • Chain of Responsibility: Pass requests between command and processing objects within a chain of objects

  • Command: Encapsulate a method call as an object containing all necessary information

  • Interpreter: Include language elements and evaluate sentences in a given language

  • Iterator: Give sequential access to elements in a collection

  • Mediator: Encapsulates and simplifies communication between objects

  • Memento: Undo modifications and restore an object to its initial state

  • Observer: Notify dependent objects of state changes

  • State:Change object behavior depending on its state

  • Strategy: Encapsulate algorithms within a class and make them interchangeable

  • Template Method: Define an algorithm skeleton and delegate algorithm steps to subclasses so that they may be overridden

  • Visitor:  Add new operations to classes without modifying them

There are also many other types of pattern such as: Parallel Patterns, SOA Patterns, Enterprise Architecture Patterns, etc… So if you work in the respective area don’t hesitate to look up patterns that may help you to be more efficient and build better applications.


Share/Save/Bookmark

Thursday, April 7, 2011

[MVP Nomination] Happy to be awarded as MVP Visual C# !!!

Beginning of the month I got an email from Microsoft containing that I am awarded Microsoft MVP Visual C#. After working in the industry since soon more than 14 years I am very happy and honored for being selected and proud to call myself MVP !!!

MVP

I want to take some time and thank Loic Baumann (MVP Visual Studio ALM) and Michel Perfetti (MVP Visual Studio ALM) for their support as well as my MVP Lead for having me nominated.

Also a big thank you to Microsoft for putting their trust in me. I will do my best and continue sharing my knowledge with the community. So be prepared for many new blog posts and articles in the technical press on Software Architecture & Design, Visual C# and Windows Azure, which are my main interests. I will also concentrate on speaking much more at conferences so I would be glad to see you at any Microsoft events (TechDays, MS Days, etc…).

Who knows, I may even write a book on Software Architecture if I find the time. I really would love to do that. So stay tuned and continue following me if you like this Blog !


Share/Save/Bookmark

Friday, February 25, 2011

[Certifications] MCPD: Windows Developer 4, MCPD: Web Developer 4 and MCPD: Azure Developer 4

Just to let you know that I passed the upgrade exams 70-521 and 70-523 to upgrade my MCPD: Enterprise Application Developer 3.5 certification lately.

I am happy to announce that I am now certified MCPD: Windows Developer 4 & MCPD: Web Developer 4 !

I also received the information that I have passed the BETA exam “71-583 PRO: Designing and Developing Applications for Windows Azure” that I did in November 2010.

So I am MCPD: Windows Azure Developer certified as well !!

image


Share/Save/Bookmark

Thursday, December 30, 2010

[Publication] Article in French Programmez Magazine on Windows Azure AppFabric and Windows Server AppFabric

You can find an article of 4 pages concerning Windows Azure AppFabric and Windows Server AppFabric in the French Programmez magazine No.137 written by me and Jean-Luc Boucho.

programmez_137

First Page and Second Page (low resolution)

Second and Third Page (low resolution)

The article is written in French but as always I will write some English articles on my Blog in the next weeks. So stay tuned if you are interested in knowing how Windows Azure AppFabric compares to Windows Server AppFabric.


Share/Save/Bookmark

Friday, December 17, 2010

[Visual C# 5.0] Asynchronous Programming Exception Handling

In my last posts I showed you the new features of C# 5.0 concerning asynchronous programming based on the CTP of October. In this article I am going to focus on exception handling in such an asynchronous environment.

So how would you add exception handling to something that is executed asynchronously? Well in C# 4.0 this was very difficult to achieve. In C# 5.0 it is much more straightforward because you just have to wrap the asynchronous function call with a standard try/catch block.

Adding Asynchronous Exception Handling

Lets take the asynchronous function call which I introduced last time and add some exception handling by wrapping it as explained with a standard try/catch block.

AsyncCSharpe5Exceptions_1

Additionally I added code to throw a simulated exception within the function that calculates the factorials. We will then be able to analyze what happens when this function throws an exception.

AsyncCSharpe5Exceptions_2

When executing the application we see that everything is working correctly. The exception is caught and we may look in detail what properties values it contains.

AsyncCSharpe5Exceptions_3 

The CTP added some new exception language features that you can now see in action. Looking at the exception details and the stack trace you may note that the Source is the AsyncCtpLibrary and that the TargetSite/ReflectedType is System.Runtime.CompilerServices.TaskAwaiter.

AsyncCSharpe5Exceptions_4

AsyncCSharpe5Exceptions_5

Conclusion

You see that the CTP adds features that greatly simply asynchronous exception handling. Exceptions get more comprehensible and easier to exploit in such an environment. Developers do not have to learn any new methods or use complex workarounds to handle exceptions correctly. There is no difference for them between synchronous and asynchronous code which is a great help!


Share/Save/Bookmark

Thursday, December 16, 2010

[Visual C# 5.0] How-To: Asynchronous Programming (2/2)

My last article introduced the new asynchronous features in C# 5.0. I took an easy development example that calculates factorials for showing you how you may implement it in a synchronous and asynchronous C# 4.0 environment - a time consuming and not so easy task for the common developer.

In this article I am going to explain how you could do it when using the latest C# 5.0 features that were released with the current CTP. You will see the code necessary to make your synchronous code asynchronous and how simple and comprehensible it is done when using the new async / await language features!

Factorials Asynchronous Code in C# 5.0

For being able to develop the C# 5.0 version of the code you need to have the CTP October Release installed and to reference the “AsyncCtpLibrary.dll”. Then you are ready to test the new features.

The main function gets a new section that calls the asynchronous C# 5.0 code. All three cases can now be executed from the main function for being able to compare the results.

AsyncCSharp5_1

Now we need to implement the calling function that will start the asynchronous processing and wait for the asynchronous result. There are already changes in the function prototype since you need to add the async keyword before the function return type to mark the function to be asynchronous.

Furthermore you can see that I use the new await keyword in front of the function call which is done inside the function body. This will assure that the code inside of this function below this line is only executed when the asynchronous processing is finished. A calling function must have at least one and can have multiple await keywords.

AsyncCSharp5_2

The main differences exist in the implementation of the function that will execute the factorials calculation code. You already see that the keyword async is used before the return type (similar to the function above).

But if you look carefully you can see that the Task<T> class which was introduced in C# 4.0 for Parallel Programming is used as return type. Knowing that all asynchronous functions have to either return Task or Task<T>, this indicates that the new asynchronous features work hand in hand with the TPL.

Within the function body we create an execute a new Task<T> and define the code that should run asynchronously, which is exactly the same that was used in all examples before.

Please also note the await keyword after the return statement that indicates that the return will only be done when all asynchronous operations within the function are completed.

AsyncCSharp5_3

When executing the application the part that handles the asynchronous call makes that the factorial calculation is done in the background and the result is displayed when it is finished (similar to the example I presented in my last blog post).

Each step is marked in the logical order they are executed :

  • Step1: Enter User Data
  • Step2: Result of the calculation
  • Step3: Exiting the function call
  • Step4: Do some other stuff

When starting the application and entering a valid value you see that there is no more delay getting the output for Step3 and Step4 (as you have already seen for the C# 4.0 example). The application is not blocked by the processing which is done in Step2. When the asynchronous processing in Step2 is finished the result is written to the Command Line. That is why the execution order is different from the logical order.

AsyncCSharp5_4

So the behavior is exactly the same but the code is much leaner, more elegant, easier to maintain and to understand. The async / await keywords greatly help to facilitate the migration of you synchronous code to its asynchronous version. No more hassle with synchronization contexts, delegates, events or wait handles. No more spaghetti code that has CallBacks allover the place where you may get very confused during design and even during runtime.

A developer may take this code and easily see what happens in which order. He may maintain or extends this kind of code very quickly. So in the end it leads to a higher productivity of developers who may concentrate once more on generating applications with high business value.

Conclusion

This article described the new features in C# 5.0 which will help to develop asynchronous code in a much quicker and cleaner way than it was possible before. Please take care that those functionalities are currently in CTP state so their final implementation may differ slightly from what I have shown you above. I will continue posting about those very interesting features and will give you updates if there are any changes in the final version of C# 5.0 which may still take some time to be released.

You can download the source code from the source code section of my Blog:


Share/Save/Bookmark

Wednesday, December 15, 2010

[Visual C# 5.0] How-To: Asynchronous Programming (1/2)

Most of todays applications are developed to work sequentially. Developers are quite used to the sequential approach since it is easy to be implemented and easy to understand. But it makes no sense to always respond to development problems by using this approach. Furthermore, the user has to wait until each of the sequential operations have finished until the next ones can be processed. Sometimes this means waiting for a result on the user side – and users don’t like to wait!

There are multiple reasons why developers may want to structure their code in an asynchronous way. Sometimes it is to allow a better user experience (not waiting anymore) or better perceived performances and sometimes it is due to technical restrictions (such as for Silverlight for example).

The current version of C# 4.0 integrates everything necessary to implement asynchronous code manually. But as you might already know asynchronous code quickly gets unreadable and hard to maintain. But this is going to change in the future version of C# which will include a new abstraction layer that will greatly ease asynchronous programming.

I will take the example of calculating factorials in a Command Line project during these blog posts. But you may take any other code that you want to render asynchronous.

In the first step I am going to write the synchronous C# 4.0 version of the code. I will then show you how you could modify your code in C# 4.0 and C# 5.0 to make the same code asynchronous.

Factorials Synchronous Code in C# 4.0

The main function in the example project contains the user input code as well as the synchronous function call. I did not add any error nor exception handling for simplicity purposes.

SyncCSharp4_1

The synchronous function contains the main application logic: factorials calculated via a for loop (no recursion for simplicity purposes). I also added a Thread delay to simulate calculation time.

SyncCSharp4_2

Each step is marked in the logical order they are executed:

  • Step1: Enter User Data
  • Step2: Result of the calculation
  • Step2: Exiting the function call

If we start this application and enter a valid value you can see that there will be a certain delay until you will get the output for Step2 and Step3. This is completely normal and due to the synchronous calling.

SyncCSharp4_3

So the processing is blocked until all operations in the synchronous order are completely finished. If you don’t like this behavior then look carefully at the next sections!

Factorials Asynchronous Code in C# 4.0

The next step consists of extending the existing project by adding some new functions and modifying the existing main function. In the main function a new asynchronous function call is added.

AsyncCSharp4_1

To render the code asynchronous we need to add a delegate which will be used to decouple the function call. In my example I also use a CallBack function and a AsyncOperation. You could do this differently but I choose this approach to show how complex it can get when migrating you code to be asynchronous in the current version of C#.

AsyncCSharp4_2

The function with the application logic is the same as in the synchronous version of the code. The only difference will be that it won’t be called directly but by using the delegate that was defined above.

AsyncCSharp4_3

The callback function contains the business logic that is applied when the asynchronous call is completed.

AsyncCSharp4_4

I added also some logic to be able to get informed via an event when the CallBack function has finished (not used anywhere in my code however). But you might need to be informed when the asynchronous operation has been terminated.

AsyncCSharp4_5

When executing the application the part that handles the asynchronous call achieves that the factorial calculation is done in the background and the result is displayed when it is finished.

Each step is marked in the logical order they are executed :

  • Step1: Enter User Data
  • Step2: Result of the calculation
  • Step3: Exiting the function call
  • Step4: Do some other stuff

When starting the application and entering a valid value you see that there is no more delay getting the output for Step3 and Step4. The application is not blocked anymore by the processing which is done in Step2. When the asynchronous processing in Step2 is finished the result is written to the Command Line. That is why the execution order is different from the logical order.

AsyncCSharp4_6


Share/Save/Bookmark