AJ's blog

November 28, 2009

Silverlight Bits&Pieces – Part 9: A MessageBox replacement

OK, let’s put the brand new service provider model to some good use.

Whenever a service call reports an error I want some message box telling me about it (rather than simply swallowing it, which is the default behavior). Whenever the user does something potentially devastating I want some explicit confirmation, read message box, that he knows what he’s doing. MessageBox.Show does all I need (well, it is restricted to OK and OK/Cancel, but one can live with that). Only… these system message boxes are dull, boring, and not at all a shiny example for a Silverlight application. Enter the message box service provider…

Basic implementation of a message box service

The basic implementation will get the infrastructure up and running.

The first step is defining the service contract. Show this and that and a query method. The first (and naive) version looks like this:

The default implementation of our application extension service turned service provider (AES/SP) would use the dull system message boxes to implement that. The code is actually quite straight forward:

Now, I could demand that the app.xaml has this one (or any other service implementing my interface) registered. However, I like to be correct by default, thus my accessor will fall back on this implementation if none is registered – and I can be sure that there will always be a respective service.

All that is left is a search&replace for all calls to MessageBox.Show… E.g. to show an error:

… and to get confirmation, in this case to return a book:

And, of course, it works as expected:

Replacing the Dialog

Second act. Get rid of those dull things.

Create a new “Silverlight Child Window” and style it to look like a message box. I „borrowed“ the images from the Visual Studio Image Library (on my machine under C:\Program Files\Microsoft Visual Studio 9.0\Common7\VS2008ImageLibrary\1033\VS2008ImageLibrary\Objects\png_format\WinVista\) and simply placed all possible images in the dialog. A textbox, two buttons, that’s it. Here is the styled XAML:

Some code is needed for the initialization. The message has to be set, the correct image made visible, etc.. I could probably have done this with less coding, using some tricks and elaborate databinding. But who cares, it’s straight forward and comprehensible (unlike what I probably would have come up with).

Setting the DialogResult property also closes the dialog (sik!).

Finally I need a replacement AES/SP. The main method to show the dialog looks like this:

Great? Great! … GOT YOU! (Fell into the trap myself, actually… :-/ )

Fixing the Bug

Remember that in Silverlight everything is asynchronous? Well, everything except MessageBox.Show? And ‘everything’ includes ChildWindow.Show! Meaning my confirm method will not work this way. To overcome this I decided to pass a delegate to the dialog constructor and made sure it’s called in the OK case:

And to be able to pass the delegate I changed the existing AES as well (and the interface respectively):

Of course I had to adjust the default implementation using a messagebox:

The calling code changes respectively, passing a lambda:

Done. Now my application looks nice, even if it has to show a message box:


This endeavor served actually three purposes:

  • First, I wanted/needed the feature 😉
  • Second, I wanted to see/demonstrate the service provider pattern from a user’s point of view.
  • And third – as you may have noticed from some screenshots – I used this implementation to check out VS2010 beta.

A quick verdict about VS 2010 beta (not really worth a separate post)…

The core system, i.e. the shell, the C# code editor, build system, etc. feels very good. No apparent bugs, quite fast, including intellisense, and close enough to VS2008 to feel familiar. Considering that big parts of this are complete rewrites, this is quite an achievement.

The visual designer for (Silverlight) XAML works nice for user controls. Designing grids, the property pane, and other tasks, is at first glance en par with Blend, but comes in a more familiar „Visual Studio flavor“; still it feels more rich and mature than VS2008.
However, there are some notable gaps. Editing of styles and templates, animations, and visual state manager are not covered. Thus my guess is that Blend will remain a necessary complement to VS, even if one has to switch less often. BTW: Contrary to what Tim wrote, I could work with Blend on VS2010 solutions (the project that cannot be loaded is only the web project), I just refrained from manipulating my project files with Blend.

Other areas I touched briefly have been less satisfying. IntelliTrace didn’t work, but I didn’t spend too much time on that. The architecture and modeling area for example has changed, but is by no means bug free (to the point of “not yet usable”). The profiler has evolved, but IMO still lacks what DevPartner offered nearly 10 years ago: a decent call graph.

Oh, one bright spot for any dev lead: code analysis (FxCop) rules are now maintained in separate files, projects reference these files by name.

Anyway, I have been using VS2010 beta since I installed it and was never compelled to switch back to VS2008. I’m going to have to reinstall my machine anytime soon, and I’m planning on going along with VS2010 beta, not installing VS2008 at all.

That’s all for now folks,

kick it on DotNetKicks.com

November 14, 2009

Silverlight Bits&Pieces – Part 8: Application Extensions

Filed under: .NET, .NET Framework, C#, Silverlight, Software Architecture, Software Development — ajdotnet @ 12:20 pm

Note: This is part of a series, you can find the related posts here

The last post used the new Application Extension Services (AES for short) to include security into the application. This time I’m going to take AES one step further, laying out yet another piece of basic infrastructure.

As a quick recap: An AES is a simple class, implementing a simple interface (IApplicationService) and optionally another one (IApplicationLifetimeAware). It is then registered by the developer via the app.xaml. SL3 instantiates the AES at runtime and calls the respective callback methods on said interfaces, including StartService, StopService, and others. The recommended way to use these services is to maintain a static property and reference the class accordingly.

Basically AES solve one problem: How do I extend the global application class, without actually replacing it, i.e. without providing a derived class?

The problem here is that many libraries need some kind of global anchor and in the past, tool developers often chose to provide this by subclassing the next available central artifact (e.g. the page class or the application). And the next tool developer doing the same rendered those two libraries mutually exclusive, just by employing an adverse implementation strategy.

However, SL3 solves only the providing part of the equation, the part related to the application class and the instantiation of the AES. But look again at the consumer code:

Following the recommendations, I get singleton access to some object. Worse, the calling code is directly and tightly coupled to the AES class. But frankly, do I need SL3 to implement a singleton? Certainly not. Then why use AES in the first place?

What I’d love is to have the consumer code depend on some service (read interface), not on the actual implementation. And the ability to swap those services in and out, without affecting the caller. Matter of fact, the calling code doesn’t and shouldn’t care whether I use a SecurityServiceThatGetsItsInformationFromTheServer or a SecurityServiceThatGetsItsInformationFromWindowsAzure (or google account, open id, whatever).

If I could get that, AES would become a very valuable feature… . 

Introducing Service Providers

OK, what the calling code needs is some service in terms of a contract, say ISecurityService, that it can ask for. And the same is true for any crosscutting concern, such as error reporting, tracing, caching, you name it. And actually .NET has already addressed this need with the service provider pattern. This pattern has been used for example in WF (e.g. to introduce workflow instance persistence), and quite extensively in the Visual Studio design time infrastructure.

OK, I can hear you crying out DI. And the chorus chanting Unity or Ninject (to name just two that support SL). But think again. Would you (or rather a library developer) mandate a specific DI container without reason? And you can always wire your pet container into this pattern by providing a IFactory service using whatever container you like. After all, the pattern handles access to services, not instantiation of them. (Which is what AES does, but again, Microsoft chose not to provide a fully fledged DI container…)

What do I need to make this approach tick? I need a GetService method that iterates all AES – they are available via Application.ApplicationLifetimeObjects. And I need something to attach this method to. Using an extension method I can actually attach it to the application class:

The method iterates all AES, checks whether one implements the requested (interface) type. It also checks whether any AES itself follows the pattern and implements IServiceProvider, and respectively forwards the request if it does. (This allows me to build up a chain of providers.)

That’s it. Long talk, short implementation, all set 😉

Reimplementing the SecurityService

Now I need the rework the SecurityService and the calling code to comply with the pattern. The service interface is simple enough:

And my revised security service looks like this:

The base class ApplicationServiceBase implements the two interfaces with respective empty virtual methods, thus I only had to overwrite StartService. Aside from some reformatting the most notable difference with the previous implementation is the absence of the static Current property to access the service instance at runtime. I also renamed the class to reflect what it does. Since the calling code won’t refer to that name any more, this is now feasible.

Accessing the service at runtime is done – drum roll please – using the service provider pattern. This (admittedly not exactly nice) code can be hidden in a simple static property, adding a little convenience. I did this with a class that provides a static property, but also allows calling an extension method on the Application class:

BTW: Wouldn’t it be nice to have extension properties that I could attach to the application class…?

And the calling code, i.e. the access to the user object changes to:


Now the calling code is completely decoupled from the actual implementation of the security service, meaning I could replace it without affecting the calling code.

A look ahead: Building on the pattern

There are several use cases for this pattern that I will employ (they may or may not be addressed in later posts, but at least this list should give you some ideas):

  • Last chance exception handling: A service will react to the unhandled exception event and gather context information. It will then use another service to report the error.
  • Message boxes: I will need message boxes for errors, information, and confirmation. The system MessageBox is however somewhat dull. A service will cover that and a later implementation will replace the boring system dialogs with nice and shiny replacements.
  • Logging and tracing: At some point I will have to tackle these demands.

I’m sure you can think of other examples, like navigation with parameter passing, global state, caching, …. Anyway, I think this is motivation enough to roll out some additional infrastructure.

As a side note: Actually I had a completely homegrown implementation of this pattern for SL2. When SL3 came out and offered AES I quickly jumped on the bandwagon and threw away most of that code. If only Microsoft had not stopped one step short of my needs… . I’d rather have the platform support that out-of-the-box. And given the simplicity of the remaining implementation this shouldn’t have been too much of an issue.

That’s all for now folks,

kick it on DotNetKicks.com

November 8, 2009

Silverlight Bits&Pieces – Part 7: Application Permissions

OK, back down from vacation – proud about the accomplishment and perhaps with some new perspectives. It really makes you think about the effects of the financial crisis if you happen to work primarily for banks… . Well.

Note: This is part of a series, you can find the related posts here

The last post (pre-Kili ;-)) provided me with the necessary infrastructure to address the next topic: application security.

Silverlight is “secure by design”. It runs in a sandbox, only allowing restricted access to the local machine. Regarding server calls it supports HTTPS and windows authentication for intranets, it restricts URL access and allows only calls to servers explicitly opted in for. From a .NET perspective it has a changed programming model, no longer supporting CAS, but a more simple model that takes the restrictions into account that are already in place. It has the well-known interfaces IPrincipal and IIdentity in place, yet no implementation and no anchor to ask for them, like HttpContext.User in web applications.

Silverlight is so secure, it doesn’t even tell you, who you are.

From a purely technical perspective this is perfectly in order. The services I call are running on the server and it’s their job to make sure no one does something or gets to know something he isn’t entitled to.
On the other hand, many intranet applications need to know the user name, if only to display it. And they need the permissions granted to the user to hide buttons, menu entries or make edit fields read only – none of that for actual security reasons (the server would take care that the user couldn’t do any harm, anyway), but to improve the user experience, not letting him do things and telling him afterwards that he has had no permission to do what he did in the first place.

User and roles are available at the server at the ASP.NET runtime, and one “only” needs to make it available to the client. Matter of fact, ASP.NET provides the necessary service implementation readily available. This is also the way to integrate with ASP.NET forms authentication.

There are two caveats with this approach, though: These ASP.NET services provide roles and all, but they just don’t include the user name. Also, being services, I would have to call them asynchronously, which would incur at least a little time lag after starting the application, that I would have to deal with. A time lag that is unnecessary in intranet applications where the user is determined by windows authentication.

Thus my solution is as follows:

  1. On the server include the information about user name and his roles in the initparams, so that it is available for the SL application right form the start, without any lag.
  2. On the client pick up that information and mimic HttpContext.User to have a similar developer experience.

Of course, someone could fake this data, which might at first glance be a security flaw. But as I said, this information is only used to improve the user experience. Even if someone masqueraded as a different user, the sandbox on the client side still uses the actual user’s restrictions. And the same is true for the services that still have the responsibility to enforcing security anyway. I’m also not revealing sensitive information, since user name and permissions are not exactly protected data. And finally I could load the web page containing this data via HTTPS. Thus, form a security perspective I’m on the save side.

Server side

The server side is easy enough, since the necessary work has already been done. Step one is to include the information in the initparams within the ASP.NET page:

Step to is the respective implementation:


Client side

Mimic HttpContext.User? Well, there is no HttpContext, but we have the Application object which can be seen as a pendant of sorts. (I wouldn’t relate it to the HttpApplication, though, since an application in the ASP.NET sense spans all users.) Yet I’m reluctant to provide a base class to inject my pet feature, because that would bring me into conflict with any other library that may one day choose to do the same.

Luckily SL3 introduced the new concept of Application Extension Services (AES for short). AES have to implement a simple interface and are registered via the app.xaml. SL3 instantiates them and calls the StartService and StopService method to provide the hooks for initialization and shutdown. There will be another post about AES, thus I’ll leave it at that for now. Anyway, here’s the respective implementation:

It’s straight forward, it merely parses the information provided via the initparams. And the registration that will create the service at runtime is quite simple:

This is backed by boilerplate implementations of IPrincipal

… and IIdentity:

From here I can use the user information at leisure, as I need it, and as I’m used to do. For example:


That’s all for now folks,

kick it on DotNetKicks.com

Create a free website or blog at WordPress.com.