Παρουσίαση με Ετικέτες
Όλες οι Ετικέτε... »
C# (RSS)
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.
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:
- What is the purpose of the WebAPIs?
- Why do we need HTTP services? What’s wrong with SOAP-over-HTTP?
- Why did the WebAPIs move from WCF to ASP.NET MVC?
- 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:
- WCF with the WebHttp binding and REST support.
- The new WCF Web APIs, soon to be ASP.NET Web APIs.
- 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.
- 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
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.htmlP.S. I really like Google bookmarks, I believe it's one of the most useful tools Google has ever given to us!
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.
- Common Compiler Infrastructure (CCI)
- Mono Cecil
- ILSpy
- Kaliro
- Dotnet IL Editor (DILE)
- 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!
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 w
hat'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...
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 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:
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...
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 ;)
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:
Another im
portant 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 ;)
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!
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...