Καλώς ορίσατε στο dotNETZone.gr - Σύνδεση | Εγγραφή | Βοήθεια

Everyday's Software Design

Scribbles on Software Engineering

Παρουσίαση με Ετικέτες

Living with async
I was watching once again The zen of async: Best practices for best performance talk of Stephen Toub’s on //Build and I decided I should blog about how easy is to end up with a deadlock while writing asynchronous code with new C# 5.0 language features (AKA async/await). Here is the quick background first which I was aware of before I watch this talk. The talk that Toub has given was mostly about how you create better reusable libraries with asynchronous language features but there are lots of great information concerning application level code.

When you are awaiting on a method with await keyword, compile generates bunch of code in behalf you. One of the purposes of this is to handle synchronization with the UI thread. The key component of this feature is the SynchronizationContext.Current which gets the synchronization context for the current thread. SynchronizationContext.Current is populated depending on the environment you are in. For example, if you are on a WPF application, SynchronizationContext.Current will be a type of DispatcherSynchronizationContext. In an ASP.NET application, this will be an instance of AspNetSynchronizationContext which is not publicly available and not meant for external consumption. SynchronizationContext has virtual Post method which dispatches an asynchronous message to a synchronization context when overridden in a derived class. When you give this method a delegate, this delegate will be marshaled back to the UI thread and invoked on that UI thread.

The GetAwaiter method (yes, "waiter" joke is proper here) of Task looks up for SynchronizationContext.Current. If current synchronization context is not null, the continuation that gets passed to that awaiter will get posted back to that synchronization context. This feature is a great feature when we are writing application level code but it turns out that if we are not careful enough, we might end up with a deadlock because of this. Here is how:



This is a part of the slide from that talk and shows how we can end up with a deadlock. Task has a method named Wait which hangs on the task till it completes. This method is an evil method in my opinion but I am sure that there is a good reason why it is provided. You never ever want to use this method. But, assume that you did use it on a method which returns a Task or Task<T> for some T and uses await inside it to await another task, you will end up with a deadlock if you are not careful. The picture explains how that can happen but let’s recap with an example.

class HomeController : Controller
{
public ActionResult Index()
{

doWorkAsync().Wait();
return View();
}

private async Task doWorkAsync()
{
await Task.Delay(500);
}
}


The above code has an ASP.NET MVC 4 asynchronous action method (I am using .NET 4.5 here) which consumes the private doWorkAsync method. I used ASP.NET MVC here but everything applies for ASP.NET Web API asynchronous action methods as well. Inside the doWorkAsync method, we used Delay method of Task to demonstrate but this could be any method which returns a Task or Task<T>. inside the Index action method, we invoke the Wait method on the task which we got from doWorkAsync method to ensure that we won’t go further unless the operation completes and the interesting part happens right here. At that point we block the UI thread at the same time. When eventually the Task.Delay method completes in the threadpool, it is going to invoke the continuation to post back to the UI thread because SynchronizationContext.Current is available and captured. But there is a problem here: the UI thread is blocked. Say hello to our deadlock!
When you run the application, you will see that the web page will never come back. Solution to this problem is so simple: don’t use the Wait method. The code you should be writing should be as follows:
class HomeController : Controller 
{

public async Task<ActionResult> Index()
{
await doWorkAsync();
return View();
}

private async Task doWorkAsync()
{
var task = Task.Delay(500);
}
}


But if you have to use it for some weird reasons, there is another method named ConfigureAwait on Task which you can configure not to use the captured context.

class HomeController : Controller 
{

public ActionResult Index()
{
doWorkAsync().Wait();
return View();
}

private async Task doWorkAsync()
{
var task = Task.Delay(500);
await task.ConfigureAwait(continueOnCapturedContext: false);
}
}

Very nice little and tricky information but a lifesaver.
Posted: Τρίτη, 5 Ιουνίου 2012 2:16 μμ από gnikolaropoulos | 0 σχόλια
Δημοσίευση στην κατηγορία: , , ,
WCF or ASP .NET 4.5 Web API
A couple of weeks ago (around Feb. 16) the WCF WebAPIs - a framework for building RESTful/Hypermedia/HTTP services, which was in development over the past 1.5 years as a side-project on CodePlex, has been formally integrated into ASP.NET and its name changed to the ASP.NET Web API.
These past two weeks, there has been a lot of questions among WCF developers: What does it mean that the Web APIs are no longer a part of WCF – is WCF dead? Has SOAP gone bankrupted? is HTTP the new way to go for interoperability?
To get a better understanding of what happened and what is the way to go, we need to answer a couple of questions:
  1. What is the purpose of the WebAPIs?
  2. Why do we need HTTP services? What’s wrong with SOAP-over-HTTP?
  3. Why did the WebAPIs move from WCF to ASP.NET MVC?
  4. Is there still a use for WCF? When should I choose Web APIs over WCF?
What is the purpose of the WebAPIs?
When WCF was conceived back in its Indigo and .NET 3 days, the main goal was to support SOAP + WS-* over a wide variety of transports. However, over time it became clear that although SOAP is wide spread and supported on many platforms, it is not the only way to go when creating services. There is also a need to also support non-SOAP services, especially over HTTP, where you can harness the power of the HTTP protocol to create HTTP services: services that are activated by simple GET requests, or by passing plain XML over POST, and respond with non-SOAP content such as plain XML, a JSON string, or any other content that can be used by the consumer. Support for non-SOAP services was very much needed in WCF back then, mostly because some clients, such as web browsers, were not that suitable to handle SOAP messages (plenty of XML parsing and DOM manipulation).
So in WCF 3.5 we got the WebHttpBinding – a new binding that helped us create this kind of non-SOAP service over HTTP, better known as a RESTful service.
The WebHttpBinding was not enough, and after WCF 3.5 was released, a new set of tools was created – the WCF REST Starter Kit. The REST starter kit was an attempt to enrich the support of WCF 3.5 for HTTP services – add better client-side support for .NET apps, extend the server side support for other content types, enable response and request caching, inspection of messages and so forth. Unfortunately, this great toolkit was never officially released and ended its product cycle as “Preview 2”, although it’s still being used today in some of Microsoft’s products that are built with .NET 3.5.
Although not released, some of the service-side features of the REST starter kit were integrated into WCF 4 – we didn’t get any of the client-side libraries, but we did get most of the service-side features (excluding the new inspectors). Some were well-integrated into WCF while others required the use of ASP.NET (by turning on the ASP.NET compatibility mode).
So with WCF 4 we had some support for “Web” HTTP services, but it wasn’t that perfect – to get some of the features you needed IIS hosting and ASP.NET, not all types of requests were supported easily (ever tried posting HTML form data to a WCF HTTP service?), the overuse of CLR attributes to define the POST/GET/PUT/DELETE was tedious, not to mention the configuration required to create this type of services with all of the endpoint behavior. And even after all of that we didn’t actually get full control over the HTTP messages.
That was the main goal of the Web APIs, known back then as the WCF Web APIs: to stop looking at HTTP through the eyes of WCF - as just a transport protocol to pass requests. Rather, it allows us to look at it as the real application-level protocol it is – a rich, interoperable, resource-oriented protocol. The purpose of the Web APIs was to properly use URIs, HTTP headers, and body to create HTTP services for the web, and for everyone else that wished to embrace HTTP as its protocol and lifelong friend.
Why do we need REST HTTP services? What’s wrong with SOAP-over-HTTP?
The world of SOAP and the world of HTTP services are very different. SOAP allows us to place all the knowledge required by our service in the message itself, disregarding its transport protocol, whether it is TCP, HTTP, UDP, PGM, Named Pipes… But unlike TCP, UDP and the other level 4-5 protocols, HTTP is an application-level protocol, and as such it offers a wide variety of features:
  • It supports verbs that define the action - query information using GET, place new information and update existing using POST or PUT, remove information using DELETE etc.
  • It contains message headers that are very meaningful and descriptive - headers that suggest the content type of the message’s body, headers that explain how to cache information, how to secure it etc.
  • It contains a body that can be used for any type of content, not just XML content as SOAP enforces (and if you want something else – encode it to base64 strings and place it in the SOAP’s XML content). The body of HTTP messages can be anything you want – HTML, plain XML, JSON, binary files (images, videos, documents…) …
  • It uses URIs for identifying both information paths (resources) and actions – the URI templates initiative is catching on and is rapidly becoming the standard way of representing requests for resources and hypermediaURIs.
The use of HTTP has evolved over the years. Application-level protocol architectural styles such as REST Hypermedia APIs have emerged on top of HTTP. These, in turn, harness the power of HTTP to create resource-oriented services, and better define the stateless interaction between clients and services.
The Web APIs therefore were intended to allow all of these approaches – you can use it to create HTTP services that only use the standard HTTP concepts (URIs and verbs), and to to create services that use more advanced HTTP features – request/response headers, hypermedia concepts etc.
So HTTP is a lot more than a transport protocol. It is an application-level protocol, and the fact is that although many platforms know how to use SOAP, many more platforms know how to use HTTP! among the HTTP supporting platforms which do not support SOAP that well are the browsers – probably the most important platforms for web developers (and users). And if you don’t believe me that REST and hypermedia are useful, maybe Martin Fowler can convince youbetter than me.
This, of course, does not mean that SOAP is redundant – SOAP is still useful for building messages when you don’t have an alternative application-level protocol at your disposal, or when you want to use SOAP across the board while considering HTTP as no more than another way to pass messages (for example, use HTTP because it can cross firewalls more easily than TCP).
Why did the WebAPIs move from WCF to ASP.NET MVC?
Back to the story of WCF and the WCF Web APIs (we are still before the merger). Another goal of the WCF Web APIs was to incorporate known concepts that would help developers to overcome some of the drawbacks they faced with WCF, such as huge configurations, overuse of attributes, and the WCF infrastructure that did not support testing well. Thus the Web APIs used IoC, enabled convention-over-configuration, and tried to offer simpler configuration environment.
The problem was that at that point in time there were several approaches for constructing HTTP services:
  1. WCF with the WebHttp binding and REST support.
  2. The new WCF Web APIs, soon to be ASP.NET Web APIs.
  3. A not-so-new framework, ASP.NET MVC, which took a break from being HTML-oriented (getting requests from HTML pages and returning HTML/JSON) to being Resource-oriented – people started realizing that they can consider controllers as services and use the MVC infrastructure to define the control requests, responses, and better control the HTTP message.
  4. Open source frameworks such as OpenRasta and ServiceStack.
In addition to that, as time passed, the WCF Web APIs had a lot of trouble adapting WCF to the “native” HTTP world. As WCF was primarily designed for SOAP-based XML messages, and the “open-heart” surgery that was required to make the Web API work as part of WCF was a bit too much (or so I understand from people who were involved in creating the Web APIs). On the other hand, the ASP.NET MVC infrastructure with its elegant handling of HTTP requests and responses, and its support of easy-to-create controllers seemed like the proper way to go for creating this new type of services.
So the fact was we had too many options and therefore too much confusion. What were we to do? We merge teams! (Kind of reminds us of the time of LINQ-to-SQL and Entity Framework, WCF and Ado.Net Data Services and other such examples). So the WCF team and the ASP.NET team joined forces and created a new framework focused on the world of REST/Hypermedia/HTTP services for the web world and thus came out the ASP.NET Web APIs.
I’m still not so sure about the choice of names, as the new Web APIs can also work outside of ASP.NET with the use of WCF, but I guess that the name “WCF ASP.NET Web API” was a bit long. Maybe “WASP Web API”? “WAWAPI” (Wcf Aspnet Web API)? Or maybe simply call it “Hypermedia Web API”?
So this merger is intended to reduce confusion, not induce it. I guess that if it was explained at that time, it might have caused less confusion over time (see the Silverlight is dead slip of PDC 2010). Does Microsoft need a new DevDiv PR team?
Is there still use for WCF? when should I choose Web APIs over WCF?
Recall my points from before - HTTP is a lot more than a transport protocol; use SOAP across the board and consider HTTP as no more than another way to pass messages.
  • If your intention is to create services that support special scenarios – one way messaging, message queues, duplex communication etc, then you’re better of picking WCF
  • If you want to create services that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transports are unavailable, then you’re better off with WCF and using both SOAP-based bindings and the WebHttp binding.
  • If you want to create resource-oriented services over HTTP that can use the full features of HTTP – define cache control for browsers, versioning and concurrency using ETags, pass various content types such as images, documents, HTML pages etc., use URI templates to include Task URIs in your responses, then the new Web APIs are the best choice for you.
  • If you want to create a multi-target service that can be used as both resource-oriented service over HTTP and as RPC-style SOAP service over TCP – talk to me first, so I’ll give you some pointers.
I hope this helped you removing some of the confusion over this topic.

Next post I will show how to use Castle Windsor with Web API
Small Introduction to NuGet

Not too long ago, Microsoft released, NuGet, an automated packagemanager for Visual Studio.  NuGet makes it easy to download and installassemblies, and their references, into a Visual Studio project.  Theseassemblies, which I loosely refer to as packages, are often open source, andinclude projects such as Nhibernate.In this post, I'll explain how to get started in using NuGet with your projectsto include: installng NuGet, installing/uninstalling Nhibernate via consolecommand, and installing/uninstalling Nhibernate via graphical reference menu.

Installing NuGet
The first step you'll need to take is to installNuGet.  Visit the NuGet site, at http://nuget.org/, click on the Install NuGet button,and download the NuGet.Tools.vsix installation file, shownbelow.

Each browser is different (i.e. FireFox, Chrome, IE, etc),so you might see options to run right away, save to a location, or access to thefile through the browser's download manager.  Regardless of how youreceive the NuGet installer, execute the downloaded NuGet.Tools.vsix toinstall Nuget into visual Studio.

The NuGet Footprint
When you open visual Studio, observe that there is a newmenu option on the Tools menu, titled Library Package Manager. This is whereyou use NuGet.  There are two menu options, from the LibraryPackage Manager Menu that you can use: Package Manager Console and PackageManager Settings


I won't discuss Package Manager Settings inthis post, except to give you a general idea that, as one of a set ofcapabilities, it manages the path to the NuGet server, which is already set foryou.
Another menu, added by the NuGet installer, is ManageNuget packages, found by opening the context menu for either a SolutionExplorer project or a project's References folder or via the Projectmenu.  I'll discuss how to use this later in the post.
The following discussion is concerned with the other menuoption, Package Manager Console, which allows you to manage NuGetpackages.

Getting a NuGet Package
Selecting Tools -> Library Package Manager ->Package Manager Console opens the Package Manager Console. As you can see, below, the Package Manager Console istext-based and you'll need to type in commands to work with packages.


In this post, I'll explain how to use the PackageManager Console to install Nhibernate, but there are many morecommands, explained in the NuGet PackageManager Console Commands documentation.  To install Nhibernate,open your current project where you want Nhibernate installed, and type thefollowing at the PM> Install-Package nhibernate
If all works well, you'll receive a confirmation message,similar to the following, after a brief pause:
Successfully installed ‘nhibernate 3.2.0.4000’.
Successfully added ‘nhibernate 3.2.0.4000’  to MyApplication
Also, observe that a reference to the Nhibernate.dll assemblywas added to your current project.

Uninstalling a NuGet Package
Type in Uninstall-Package Nhibernate and afterbrief pause, you'll see a confirmation message similar to the following:
Successfully removed 'NHibernate 3.2.0.4000' from MyApplication.
Successfully uninstalled 'NHibernate 3.2.0.4000'.
The following package elements are also removed:

  • References in the project. In Solution Explorer,you no longer see the library in the References folder or the bin folder. (Youmight have to build the project to see it removed from the bin folder.
  • Files in the solution folder. The folder for thepackage you removed is deleted from the packages folder. If it is the onlypackage you had installed, the packages folder is also deleted.)
  • Any changes that were made to your app.config orweb.config file are undone.
Graphical Installations
As explained earlier, clicking Manage Nuget packages…,from the context menu for either a Solution Explorer project or a project'sReferences folder or via the Project menu opens the Manage Nugetpackages window. This window will allow you to add a reference a NuGetpackage in your project.


To the left of the window are a few accordian folders tohelp you find packages that are either on-line or already installed.  Justlike the previous section, I'll assume you are installing Nhibernate for thefirst time, so you would select the Online folder and click All
After waiting for package descriptions to download, you'llnotice that there are too many to scroll through in a short period of time. Therefore, use the search box located at the top right corner of the window andtype Nhibernate as I've done in the previous figure. You'llsee Nhibernate appear in the list.
Click the Install button on the Nhibernateentry. If the installation was successful, you'll see a message box display anddisappear quickly (or maybe not if your machine is very fast or you blink atthat moment). Then you'll see a reference to the Nhibernate.dll assemblyin your project's references list.
If you open the Manage Nuget packages windowagain, you'll see Nhibernate listed in the Recent packages folder.


Summary
You can install NuGet via the on-line home page with a clickof a button.  Nuget provides two ways to work with packages, via consoleor graphical window.  While the graphical window is easiest, the consolewindow is more powerful. You can now quickly add project references to manyavailable packages via the NuGet service.

A wonderful weekend

Believe in the community

Last weekend I had a great time. That's thanks to ITPro|Dev Connections conference that took place in Glifada, Greece. It was my first Greek dev conferece as I have only a year and a half that I am back in my country. I never had the chance so far to take a closer look at the community and have a taste of the level and the experience of the developers. I have to admit that I was quite skeptical before going to the event. That's because of my disappointment from the interviews I have conducted for the company I work. There were people that have never heard the term "Design Patterns"!!!

I won't get any deeper to the situation as there are many parts to blame and that is not the point of this post. Maybe I will write one in the future... What I want to point out though is that I have met some people that made me believe once again in the potential of my country. Because these people are GREAT programmers, great entrepreneurs and great minds! I would like to list them here (in alphabetical order) for the world to learn about them and I would like to say to them a huge THANKS as they made me believe once again that coming back to Greece was not a mistake.


Book Read: Clean Coder

Being professional coder is harder than you think...

I have again three books that I am hoping to finish this month,  I will start here with one I just finished. It's the Clean Coder from the famous Uncle Bob. I add it on the Software Engineering Books and in my Highly Recommended list. It is a brilliant read. It is not the technical book one might be looking for. For a more technical approach on how to write clean code please read Clean Code (Robert C. Martin) for which I also have a review.
This books is about what a professional coder is about. What behaviors should he follow on his everyday life as a coder on a big or a small firm. A lot of the content sounds obvious when you read it, but it's put together extremely well and will almost certainly relate to issues that you've had to deal with in your career, be it difficult colleagues or untrusting managers. It's easy to read and will probably open your eyes to becoming a more professional software developer who is better able to take responsibility for their work.

I really wish some of the colleagues I had some time ago have read this brilliant book.
Posted: Τετάρτη, 12 Οκτωβρίου 2011 11:17 μμ από gnikolaropoulos | 0 σχόλια
Δημοσίευση στην κατηγορία: ,
Install Windows 8 Preview in Virtual Machine

Install Windows 8 in VirtualBox

Requirement:

  1. Oracle VM VirtualBox
  2. Windows 8 Developer Preview ISO file (32-bit or 64-bit)
  3. Windows Live ID* (for best testing experience, sign up here if you doesn’t have one)
  4. Internet Connection*
*Nice to have, for best experience
Besides that, also make sure that your computer have the Virtualization Technology (VT-x/AMD-V) activated in the BIOS. Proceed to the installation if you are ready with everything.

Steps:

1. Get the Oracle VM VirtualBox installed in your PC. (VMWare player is not working but you can use VMWare Workstation 8, released two days ago just for Windows 8.)
2. For setting up the Virtual Machine, use the following settings:
Summary of Virtual Machine
3. Below screenshots show all the settings I used for that Virtual Machine:
System
It is important to have the chipset to PIIX3 and to check the Enable IO APIC as the installation will fail.
Display
Storage
This part is easy. The .vdi will be mount as an IDE Controller and all you need to do is to right click on the IDE Controller and "Add CD/DVD Device". There you should select the iso file you have for the Windows 8 Developer Preview. Note that the type of the IDE Controller has to be PIIX4.


Network
4. Once everything is set, start installing Windows 8! The installation process is pretty much similar to the one in Windows 7, so nothing much there. When Windows 8 started up, you will need to enter your Windows Live ID and password.
5. Finally if you have large screen as I do then in order to support your native resolution you will have to type the following on a command prompt window:

First, enter the below text to change the directory:
 cd C:\Program Files\Oracle\VirtualBox
Then, enter the line: 
VBoxManage setextradata global GUI/MaxGuestResolution any
Lastly, manually enter this line (don’t copy and paste since it can have issue with quotation mark):
 VBoxManage setextradata “VM name” “CustomVideoMode1″ “WidthxHeightxDepth
VM name have to be replaced with your virtual machine name. If your virtual machine is named Windows 8, then it should be “Windows 8″.
WidthxHeightxDepth have to be replaced with your desired resolution. Say if you want to have it running at your monitor native resolution at 1920x1080x32, then it should be “1920x1080x32″.
Now you can start your virtual machine, click on the "Windows Explorer" icon and then right click -> Screen Resolution and on the "Resolution" drop-down you will see the newly create resolution which will work just fine!
Now you are ready to enjoy the new Microsoft beast and try your coding skills in Javascript!
Good luck!
New Page, Recommended Books!
After getting some proper rest during my summer holidays and reading quite a few books (once again) I decided that I should publish my list of all time favorite books which I will continuously update from now on. I am a big fan of physical books and I try to buy my favorite books in physical form so that I can have them all in my room's shelves. The last years though I try to also read e-books as they are cheaper and easier to have with me. I am a big fan of apple books and kindle on iPhone although I have to admit that I would be more happy with a bigger screen. I might give a shot to the real Kindle in the future although I am not sure it's worth the money against an iPad. On the other hand, reading pdfs on my pc get's me soooooooo sleepy, I have never managed to finish a single book like that.

I have two simple rules that i try to follow when reading books:

  1. read at most two books per month and 
  2. read them from start to end. Read ALL of them! 
The last one is an old rule that a friend of mine taught me from my university years. I have followed it since then and I recommend it to anyone seriously interested in learning new technologies and keeping up with computer science.

Enough said... You can find the first edition of my reviews here!
It' all about Azure
I have recently discovered two great sites which apart from their rich content they represent a great example of how to build rich Metro-like UI with Silverlight...

Here they are:
1) http://azuredesignpatterns.com/
2) http://azurehandbook.com/

They surely worth a read!
Azure training

Cloud => Azure => The future...

Just a week ago I discovered Windows Azure AppFabric Learning Series! In this learning series you will find short videos that are episodic for easy consumption. These videos are available via Silverlight streaming and available in full-screen and can be easily embedded in blogs, social media outlets, audience marketing campaigns, and upcoming enhancements to AppFabric. Episodes include technical samples, such as database scripts and code, and have all the technical assets available for download on the AppFabric Codeplex (Public) site. If you are seriously interested in Azure you should not miss it!
Moving from WPF to Silverlight (part 2)

Trouble appears when it's least expected.

Continuing from part 1 let’s go into the things that not only will require more coding effort but will also change the whole design of your app. And if you are managing a team then it’s two times more difficult because you have to stand all their whimpering. Let the party begin:
  1. No default button! Long gone the simple WPF property on the Button class that was making it the default one for the page/form. What is even stranger though is that even in the web, typing in a textbox and then pressing Enter is the DEFAULT BEHAVIOUR!I mean why on earth someone wouldn’t provide this functionality on a web framework!
  2. No double click!Let’s say you have a grid for your search results. No you have to click (select) a row on the grid and then move the pointer to another button which will actually get your selection and do something with it! No more double click on a row and get things done.
  3. Focus on a control! So let’s say you move into a new screen and you want to focus on a textbox. It should be as simple as a method call right? m_myTextbox.Focus(). Weeeeeeell, this is probably not going to work!!! Yeah, you see it will work fine on a OOB application but on a browser app you need first to focus on the Silverlight plugin and then focus on your control! So you actually need something like:
    System.Windows.Browser.HtmlPage.Plugin.Focus();
          
    RegularTextBox.Focus();
    Or if it’s that you want to focus something on startup or on Loaded event then you have to call:
               Dispatcher.BeginInvoke(() => input3.Focus());
    Unbelievable right??
  4. No keyboard typing selection in ListBoxes/ComboBoxes! This is another one that makes users’ nerves go high. Usually on both a desktop and a web app when there is a ComboBox on a screen you can start typing something and the ComboBox selects the item which has a text that matches the typed characters. There is no such thing in SL. The only acceptable solution I managed to find is to code a behavior that would select an item but only on the first typed letter. So if a user types three letters fast my behavior will execute three times selecting a different item each time.
  5. Asynchronous world! This is the most serious one and that’s why I left it last. Probably most of you WindowsForms/WPF application designers have thought about pressing a next button, make some operations secretly from the user on another thread and then when that thread comes back actually present the next page. Well I have news for you! It’s not that easy anymore! Since every call to a delegate/callback/web-service/Agatha-rrsl method is ASYNCRHONOUS! What this means is that if you want to calculate something before going to the next screen and you want that calculation to be done on the server side then you have to somehow transform this call into a synchronous one as there is no way it can be inherently synchronous (there are a few very nice solutions out there, but I won’t get into the details). Just think of it for a moment. We are taking about some serious changes here, especially if you have a SOA with any kind of Service bus/WCF/asmx/Queue services talking to each other.
Most of the problems I described in these two posts can be solved with various workarounds. But the point is that most of these things should just work. We are talking about behaviours that are considered DEFAULT for a long time now and users are expecting them from your app.

All in all, I still remember the words of my old colleague about “how easy it should be” and seriously I am laughing! If it’s not a business critical requirement DON’T TRY IT! Just don’t!!! Think about it from the very beginning of the project and make sure you understand your domain and business requirements and of course never listen to an optimistic colleague! ;) 
Moving from WPF to Silverlight (part 1)

Never believe it is as easy as they say...

I used to have a colleague in the team I manage that was sure that moving back and forth from WPF to Silverlight was easy!!! I will dedicate these series to him as reality proves us most of the times wrong. (Research is the only path to knowledge).

So I am the architect of a quite big project and it was originally coded in WPF. But since we wanted to move to a unified architecture where both our users and the clients will have the same user-experience, we decided to move on to Silverlight. There are tons of things that are different and some of them are addressed to Silverlight 5 but still, there is quite a distance.

First things first… When you just copy over the code you will see you xaml getting full of red lines. The exactly same controls are not on the same namespace!!! (WTF?). So let’s say you have a label, well your xaml tag is no more <Label>  but instead it should be <sdk:Label>.

Then I moved on to test my colors and text fonts. Again we had to change most of our resources for the text to render correctly. But the best part is the Reflection capabilities. It was well known that SL will have a minimized API version of .Net and I was prepared that our reflection helper class would have problems. What I did not expect though was that BindingEngine would complain when I was trying to bind on protected properties or even public properties on internal classes! To make myself clear:
We are quite serious about coding standards and framework guidelines in my team so we make all of our classes internal until we need to "open" them. So let’s say we had a page call MyFirstPage and the code-behind file was starting like that:

internal partial class MyFirstPage
{
//...
}

and the xaml code was like that:
<UserControl
         x:Class="MyNamespace.MyFirstPage"
         x:ClassModifier="internal">
//…
</UserControl>

Well in this situation any binding will fail with the message that the BindingEngine could not find the property named “blah” as the reflection mechanism used is unable to resolve internal classes!!! I was seriously disappointed. I mean it's the same class after all! It shouldn’t matter whatever the access modifier is.

Next incompatibility was the fact that we could no longer have multiple windows. I know this is now possible in Silverlight 5 Beta (which I am currently testing) but at that point in time we had to make some serious thinking about how we are going to be user friendly and still present the same amount of information to the user. The problem with child windows - as you may know - is that they don’t let you interact with the background window (the “parent”) and so you are left with one working window at a time.

I won’t talk about MVVM concepts that were not fully supported as I decided to let my team go away from that MVVM buzz-pain-in-the-ass. I have yet to see a real complex business MVVM application (working for portfolio/transaction management in banks or insurance companies).

I will talk though about how frustrating it is to not be able to chrome your OOB (out-of-browser) window any way you like. Well we have managed some pretty neat stuff with our own but it took us a lot of time and effort. And as if these were not enough already, autoupdate needs you to have your code signed for having an elevated trust OOB getting the new version. Moreover, if you dare update the Silverlight version you build against the auto update will fail anyway. And of course you have no control over the whole operation. You just have one method call (to check and download the update, yeah two in one either you want it or not) and an event (just to let you notify the user that the next time he starts the app it will be the new version). That’s it. Period! I really miss ClickOnce

In part 2 of this post I focus on the design changes that one has to make as Silverlight lives in an asynchronous world, has no double clicks, no default buttons and last but not least the focus operation is not as trivial as it used to be.
MVVM frameworks
I have found a very interesting site the other days that would compare various MVVM frameworks from codeplex in terms of popularity, documentation and features. I think it's quite interesting so I decided to share it with people.

http://www.japf.fr/silverlight/mvvm/index.html

P.S. I really like Google bookmarks, I believe it's one of the most useful tools Google has ever given to us!
Posted: Πέμπτη, 10 Μαρτίου 2011 8:23 πμ από gnikolaropoulos | 0 σχόλια
Δημοσίευση στην κατηγορία: , ,
Reflector is dead. Long live Reflector! (or reflector alternatives)

It's sad when great ideas get lost in the name of money and progress


It's sad but it was recently announced that one of the most well known tools for .Net development will cease to be offered for free. I am talking of course for .Net Reflector.Unfortunately in the Greek community I haven't seen to much about it which makes me even more sad about the software development in my country (at least there has been a short discussion here).
Anyway, just for the record, the official announcement of the Reflector going for a price model is here. It's a big change indeed but I think we should have seen it coming. We all are part of a community (.Net) which is used to pay for everything, it's almost as we don't enjoy coding otherwise. Starting from our IDE going all the way to the most "sofisticated" tools - which are usually free in other communities (e.g. Java) - like NHibernate Profiler, NCover, Memory Profilers and many many more. It's amazing that most of these tools are quite often WORSE that their open source alter egos.
Don't get me wrong. Some of these tools are great, and for some of them I am also willing to pay the price but the whole situation is messed up. There has been some breakthroughs in the oss community of .Net the last years with some excellent projects and a great solution to the big problem of package management (call me Codeplex, ALT .Net and Nuget) but still I am sure that developers from other worlds are laughing with us. So here I provide some nice alternatives for Reflector, all of them free and/or open source.


  1. Common Compiler Infrastructure (CCI)
  2. Mono Cecil
  3. ILSpy
  4. Kaliro
  5. Dotnet IL Editor (DILE)
  6. Monoflector
I am personally looking seriously into ILSpy and Monoflector. ILSpy is made from the SharpDevelop team (these guys are just great) and Monoflector uses the Mono Cecil engine with a WPF UI on top of it, it looks quite promising although it's not fully working yet.

Last but not least I got to state that the price RedGate is asking for the old good Reflector is not too much and I am sure that people will appreciate the effort. But being asked to pay for a tool that a)has always been free and b)uses an open source engine (Mono Cecil) in its core... It's getting on my nerves!
Agatha rrsl, WCF and Collection data types

The devil is in the details. Read the documentation of every library you use. Reason about your code.


I have been recently refactoring and reviewing code of a project in order to move it from WPF to Silverlight. (I will make a series of posts on the trouble and horror that I met during this exercise)

In this production LoB system we have chosen to work with Agatha, a request-response service layer sitting on top of WCF that simplifies communication with the back-end, greatly improves modularity and really helps with maintainability (you should definitely take a look in this project if you are serious about your service layer.) Building our messages (classes) for our layer I noticed that we have used interfaces where we needed collections i.e. IList, ICollection etc. It seemed a strange choice from the beginning and down the road but it actually proved terribly wrong.

Suggestion: Always read the documentation.


So the problem lies in the way WCF decides to serialize/deserialize a collection when we use interfaces instead of concrete types. And it's cleanly explained in a simple to read MSDN article. Here is what's really going on:
When you declare, for example, an IEnumerable on your message/class that is going to be sent through the wire then the serialization engine chooses a type that implements the declared interface. So in my case it was choosing the ReadOnlyCollection causing me serious troubles in updating the state of my application on the backend. In general I have serious issues with libraries or practices that make me loose control over my code so I immediately refactored the whole thing.

I later on noticed that the same guys who wrote the code had made another quite strange choice which made me understand how this mess was created. The were using interfaces everywhere (OMG!) even in method return types. Well I don't want to go into the details of basic OO theories like abstraction or polymorphism but I will make a note here: it's considered good practice to have your argument types as generic as possible, i.e. use interfaces and your return types as specific as possible. It's your problem if you tied the calling code to the specific return type instead of using an interface not the method's. Your implementation has a single unit of change, the method body, and your code can be refactored like a charm. The overuse of interfaces is a common misconception of a lot of programmers who just learned about code design...
LINQ Quiz...
Can you guess the output of the following code?
var values = new List<int>() { 100, 110, 120 };
var funcs = new List<Func<int>>();
foreach (var v in values)
funcs.Add(() => v);
foreach (var f in funcs)

Console.WriteLine(f());
If it's not "solved" I will post the answer in the next post...
HTML5 Labs

HTML5 Labs provides research projects from Microsoft that will come to our browsers in the recent future. There are a few interesting things in there... Stay in touch.

It's been a great year 2010 and I am quite excited for the things that are about to come in 2011. One of these things are the new HTML5 labs that Microsoft has recently (21st of December) announced in their interoperability website.

In there there are two new research projects:
1) Indexed DB
2) WebSockets

Since there is no source code given out yet I am exploring these projects with Reflector. I suggest you do the same. IndexedDB is quite interesting as it provides new ideas on a field that there are already a few projects out there. It's a step beyond Silverlight's isolated storage and SterlingDB for Windows Phone. Now for the WebSockets project I am still not sure of their use and of what they provide exactly. There are some subtle differences in the way one has to code for them but all in all they seem just another WCF abstraction layer to me. The future will tell...
Correctly Implementing Equals() in C#
 
It's said that "the devil is in the details". Well I saw some code the other day that reminded me exactly that quote. It is quite common for developers to forget about semantics. In my current project we tend to play a lot with Nhibernate and DDD and we seriously take care of our model. We take it to the extreme where we use every possible aspect defined in DDD, with Components being on of them. It is quite crucial to be careful when dealing with Components especially if ones uses them in a Set. Sets (as know from high-school math) are structures that can have only one instance per object. So we need to be sure that two objects are equal when we try to insert something to our Set (and respectively to the DB.)

I will try to show here the complete implementation of a class that needs to override Equals() as it should be. First we have to remember that in C# the semantics of equality define that two reference-objects are equal if the respective references point to the same object (aka object identity). Well, some people tend to forget that...

Here is how one should implement an object that needs to define its own version of Equals.

public class Foo : IEquatable<Foo>
{
public override bool Equals(Object right)
{
// check null:
// this pointer is never null in C# methods.
if (Object.ReferenceEquals(right, null))
return false;

if (Object.ReferenceEquals(this, right))
return true;
 
if (this.GetType() != right.GetType())
return false;
return this.Equals(right as Foo);
}
#region IEquatable<Foo> Members
public bool Equals(Foo other)
{
// Do your magic here...
return true;
}
#endregion
}

So what is going here? First things first:
Remember that .NET defines two versions of Equals:
public static Boolean Equals(Object left, Object right);
public virtual Boolean Equals(Object right);

Why don't we just use the static method Object.Equals? Well this method will do it's job only if both instances (this and right) are of the same type. That is because the static Equals all it does is a nullability check of both ends and then delegates the equality decision to the instance method Equals method. This is why we actually need to override the instance method and we NEVER touch the static method.

Another thing to note is that Equals should never throw any exception. It just doesn't make much sense. Two variables are or are not equal; there’s not much room for other failures. Just return false for all failure conditions, such as null references or the wrong argument types. Now, let’s go through this method in detail so you understand why each check is there and why some checks can be left out. The first check determines whether the right-side object is null. There is no check on this reference. In C#, this is never null. The CLR throws an exception before calling any instance method through a null reference. The next check determines whether the two object references are the same, testing object identity. It’s a very efficient test, and equal object identity guarantees equal contents. The next check determines whether the two objects being compared are the same type. The exact form is important. First, notice that it does not assume that this is of type Foo; it calls this.GetType(). The actual type might be a class derived from Foo. Second, the code checks the exact type of objects being compared. It is not enough to ensure that you can convert the
right-side parameter to the current type (inheritance bugs can surface if you go this way).

Finally we check if the two instances are of the same type and finally we delegate the decision to the type-safe implementation of Equals that is coming from the IEquatable interface. Overriding Equals() means that your type should implement IEquatable<T>. IEquatable<T> contains one method: Equals(T other). Implemented IEquatable<T> means that your type also supports a type-safe equality comparison. If you consider that the Equals() should return true only in the case where the right-hand side of the equation is of the same type as the left side, IEquatable<T> simply lets the compiler catch numerous occasions where the two objects would be not equal. There is another practice to follow when you override Equals(). You should call the base class only if the base version is not provided by System.Object or System.ValueType.

There are a few other rules that apply to value types but they are beyond the scope of this post which is already huge I think. One last not though just to make sure we all understand where all these semantics and practices come from. Math 101, the base of all our computer lives:


Equality is reflexive, symmetric, and transitive. The reflexive property means that any object is equal to itself. No matter what type is involved, a == a is always true. The symmetric property means that order does not matter: If a == b is true, b == a is also true. If a == b is false, b == a is also false. The last property is that if a == b and b == c are both true, then a == c must also be true. That’s the transitive property. This is common knowledge to every developer, so please try to meet their expectations (even the simpler ones) you handle some code to them ;)

WPF Metro Window

"Metro is an internal code name for a typography-based design language created by Microsoft. It was created as a product of Microsoft's user interface design work on some of their media products like Zune and Windows Media Center, for major utilization in their mobile operating system, Windows Phone 7", wikipedia.org


Continuing with Metro UI I will try to give here a bunch of information that seems to be quite scattered around the web and I will show how easy it is to build a sample window (no resizing) with WPF which will look like Metro.

The first place one should study is the official guidelines of Microsoft. There you will find all the documentation you need about the logic of Metro, design guidelines and Photoshop templates of icons, buttons etc. There is however a better alternative for the icons. Here you can find all the standard Metro UI icons in one zip all in png format, ready to use in your project.

A few other really interesting projects that apply the Metro UI are the following:
http://metrotheme.codeplex.com/
http://nroute.codeplex.com/
http://chronoswpf.codeplex.com/

Another important aspect of the UI in order to look proper has to do with the fonts. In most projects you might find styles that refer to the Segoe WP (from Windows Phone) fonts. While these fonts are also available for your PC and can be easily installed (either standalone or through the WindowsPhone tools) you should avoid it when you are building a WPF application. Segoe UI or Segoe Light render much better, especially for small sizes (below 15).

So going back to our sample window, we will build a simple WPF project from visual studio, and we will make our MainWindow look like a Metro one. Our window's xaml should look something like that:
<Window
x:Class="WpfMetroWindow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="470"
Width="900"
IsTabStop="False"
AllowsTransparency="True"
Background="{x:Null}"
BorderBrush="#FF3F3F3F"
PreviewMouseMove="HandlePreviewMouseMove"
SnapsToDevicePixels="True"
TextOptions.TextFormattingMode="Display"
TextOptions.TextRenderingMode="ClearType"
ResizeMode="NoResize"
WindowStyle="None"
WindowStartupLocation="CenterOwner">
...

So with a no border, no resize, white and transparent window we are ready to begin. The next step is build the shadow around the edges. This can be accomplished easier that one might think. All we need is a border with the dimensions of our window which will have a shadow effect on it.
<Border
x:Name="m_edgeBorder"
x:FieldModifier="private"
Margin="10"
Background="White"
IsHitTestVisible="False"
IsEnabled="False">
<Border.Effect>
<DropShadowEffect
Opacity="0.999"
BlurRadius="16"
ShadowDepth="0" />
</Border.Effect>
</Border>

But since we have the window with no border we have two important issues: we have to find a way to move (drag) the window around and find a button that will close the window. For the first problem we create a rectangle on the top of the window and we attach to it's PreviewMouseDown event.
<Rectangle
Height="28"
VerticalAlignment="Top"
Fill="White"
PreviewMouseDown="HandleHeaderPreviewMouseDown" />
and then we have
private void HandleHeaderPreviewMouseDown(
Object sender,
MouseButtonEventArgs e)
{
m_headerLastClicked = DateTime.Now;
if (Mouse.LeftButton == MouseButtonState.Pressed)
{
DragMove();
}
}

Now for closing the window we create a button with a custom style (we could also create a button template and give it one of the Metro png files we downloaded earlier).
<Button
HorizontalAlignment="Right"
Margin="500,6,8,0"
VerticalAlignment="Top"
Style="{StaticResource ChromeButtonStyle}"
Click="HandleCloseClick">
<TextBlock
TextWrapping="Wrap"
Text="r"
FontFamily="Webdings"
Foreground="#FF919191"
FontSize="13.333" />
</Button>
I know I've chosen a really weird way of showing the "X" on the close button but trust me it works. Here's a sneak peek.

What I finally added, as I wanted my window to work with Caliburn.Micro, is a ContentControl which will host all the screens into this "shell" window.
<ContentControl
x:Name="ActiveItem"
Background="Transparent"
HorizontalAlignment="Stretch"
IsTabStop="False"
Focusable="False"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
VerticalAlignment="Bottom"
Margin="13,0,12,13"
MaxHeight="375" />


So that's all! We will find just one more method on the cs file which I haven't talked about. It's trivial though, just changes our pointer to arrow when moving the window. I haven't also showed the styles that you will also find in the code and the fonts that I use for the sample menu. You can find the code on my google code repository.

P.S. Special thanks to my bro for all his work with styles! He is the man ;)
Windows Events going with Metro UI
This trend with Metro UI is getting quite hot nowadays and I am really interested in it. I find it extremely good looking, clear and IMHO it follows quite well with the rules of simplicity. I will save the details for another post.

At this point I was interested in some problems that a colleague (N.Baxevanis) of mine had when trying to build a Metro UI window for WPF. As you will see in his relative post he was somehow under the impression that the LocationChanged event wasn't triggered. After we solved that he was trying to  find out why another event, LostFocus, didn't fire on a Window level when he was moving his cursor to another application.
To focus or not to focus?

It seems that a lot of people have the same question around the net so I think I can clarify some things about windows in general. It seems to me that people that have no or little Windows API experience struggle when confronted with it's internals and to be honest the whole API can be a little intimidating for the newcomers.
Back to the LostFocus event... 

First of all this event does not fire on "windows forms" level. The respective events are Activated and Deactivated. On a Window level LostFocus has to do only with the windows that belong to the same application thus to the UI thread that are children of our main window. It is the expected behavior not to fire LostFocus when a user changes an application.

So one might ask: "I have seen all these cool effect that MetroTwit and Zune do when you select another applicaiton! How the $##! are they doing it?". Well, there is a nice tool called Reflector which can give you a thorough insight. But since you might not be aware of it, msdn comes to the rescue. There are two ways that can identify you application as the currently activated for the Windows operating system.


The easiest one (special thanks to my brother for this), which will be quite familiar to the high level C# developers, is to capture the LostKeyboardFocus. This event triggers always when a Window/Form/whatever looses the keyboard meaning it will fire not only when you point to another application but also when you point to another child window.

Another WPF solution (and the one I personally like more) would be to capture the Application.Activated and Application.Deactivated events or the respective window level events. I will let the msdn links tell you the rest.

The other solution that can fit our purpose is to capture the Windows events. Off course you will need to import the quite famous "user32.dll" and also have your own code for the following method:
IntPtr WindowProc(IntPtr hwnd, 
                  Int32  msg, 
                 IntPtr wParam,
                 IntPtr lParam, 
                 ref Boolean handled).

The message you are looking for is the WA_INACTIVE. This is the message sent by Windows OS to all the UI threads when one of them is getting activated/set as the foreground one.

I am sure there are a few other ways that you can make this thing work. Any proposals are always welcome!
Couch DB
Cassandra, MongoDB, CouchDB etc...
It's on my to-do list to take a deeper look onto that NoSQL trend but after seeing the following video I think I will change it's priority... (special thanks to N.Baxevanis)

CouchDB looks cool!
Posted: Τετάρτη, 15 Δεκεμβρίου 2010 3:28 μμ από gnikolaropoulos | 0 σχόλια
Δημοσίευση στην κατηγορία:
C# 5, Async Exceptions Mysteries
 

Studying the CTP of C# 5 I discovered that an asynchronous method will throw away anything other than the first exception in an AggregateException thrown by one of the tasks it's waiting for. Reading the TAP documentation, it seems this is partlyexpected behaviour and partly not. TAP claims (in a section about how "await" is achieved by the compiler):

It is possible for a Task to fault due to multiple exceptions, in which case only one of these exceptions will be propagated; however, the Task’s Exception property will return an AggregateException containing all of the errors.
Unfortunately, that appears not to be the case. Here's a test program demonstrating the difference between an async method and a somewhat-similar manually written method.

static async Task ThrowMultipleAsync()
{
   Task t1 = DelayedException(500);
   Task t2 = DelayedException(1000);
   await TaskEx.WhenAll(t1,t2);
}

static Task ThrowMultipleManually()
{
   Task t1 = DelayedException(500);
   Task t2 = DelayedException(1000);
   return TaskEx.WhenAll(t1, t2);
}

static Task DelayedException(Int32 millisecs)
{
   return TaskEx.Run(delegate
   {
      Tread.Sleep(millisecs);
      throw new Exception("Exception thrown after" + millisecs);
   });
}
The difference is that the async method is generating an extra task, instead of returning the task from TaskEx.WhenAll. It's waiting for the result of WhenAll itself (via EndAwait). The results show one exception being swallowed:
Waiting for From async method
Thrown exception: 1 error(s):
Exception thrown after 500

Task exception: 1 error(s):
Exception thrown after 500

Waiting for From manual method
Thrown exception: 2 error(s):
Exception thrown after 500
Exception thrown after 1000

Task exception: 2 error(s):
Exception thrown after 500
Exception thrown after 1000
The fact that the "manual" method still shows two exceptions means we can't blame WhenAll - it must be something to do with the async code. Given the description in the TAP documentation, I'd expect (although not desire) the thrown exception to just be a single exception, but the returned task's exception should have both in there. That's clearly not the case at the moment.
Anyone any ideas? If not then I am going back to my dungeon...
Software Design Patterns and Processes
It is strange how much an architect can understand going through the design process of a system. I have tried a few approaches and I have studied a few more, all in all I am inclined to believe that DDD gets the best out of a software developer.


I won't get into the details of DDD as the reader can get enough info around the web. It hard to get a grip of it though and I would recommend even the average developer to get some books. Thus, I strongly believe that whoever is serious about DDD should get the following:
  1. Domain Driven Design
  2. Applying Domain Driven Design and Patterns using .Net
  3. .Net Domain Driven Design with C#
Is that all though? You wish...
Truth is there are quite a few, brand new design processes. They are not widespread yet but they are gaining a lot of ground and anyone serious about designing large enterprise systems should have a serious look at them. I am going to give a bunch of links here and I will discuss each of them as we go, in new posts.

First we go with BDD or Behaviour Driven Design, an agile approach base on users and clients behaviours, trying to figure out what they want from the system. Then we have STDD (Story-Test Driven Design, which is quite interesting as we try to involve the customer to the whole process. Finally an approach not so high level is CQRS, meaning "Command and Query Responsibility Segregation". I am a bit sceptical about it yet as i think it tries to say the obvious but I won't try to present any conclusions here yet.

It is important for a developer to know why and how it chooses the design process for each project. The ability to learn a domain and quickly design a solution that fits into it separates great developers from great architects. I have met a few people with extraordinary programming skills (seriously!) who when confronted with a complex domain were intimidated. It takes time and a great amount of experience to get a grip on a domain. It is a continuous effort which, unfortunately, not many people are determined to give (especially where I live...).