AJ’s blog

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,
AJ.NET

kick it on DotNetKicks.com

October 3, 2009

Silverlight Bits&Pieces – Part 6: Application Configuration

Filed under: .NET, .NET Framework, C#, Silverlight, Software Development — ajdotnet @ 4:53 pm

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

Configuration of ASP.NET applications is quite potential. Simple application settings, database connection strings, complex configuration data. All editable by the administrator after deployment.

Configuration of SL applications is virtually non-existent.

While a Silverlight application may have less need for configuration than a web application – part of the logic still remains server side in respective services anyway – it’s not as if there is no need at all.

The service URLs (or a base URL) themselves, for example. Service proxies are created with the very URL that was used to provide the meta information baked into the code. Since this is probably a local address on the developers machine it needs to be adjusted during runtime. And preferably the administrator should be able to reconfigure the SL application if the service URL changes.
Other use cases include the usual: Whatever you want to put in some appSettings replacement. Enabling debug features. Just have a look at your last web application’s configuration and you’ll probably find some good candidates.

Silverlight configuration

Looking at the object tag for a Silverlight control on a web page (the ASP.NET server side control we had with SL2 is gone with SL3), there is some technical parameterization available:

You can find a complete list of available parameters here and below.

Of particular interest right now is the initParams property. It allows me to pass arbitrary information to the SL client. It is however not suited to be maintained by an administrator, as I certainly don’t want him to mangle my web page. However nobody says I cannot provide code that reads the information from somewhere else, like so:

and the respective code, obviously intended to read in the contents of a config file:

That config file is a simple analogon to the standard ASP.NET appSettings:

 

Note: I could have returned the web.config appSettings section. Yet using a separate file helps keeping client and server configuration cleanly separated.

So, what’s left is the actual implementation of that InitParams class, I’ve been using…

Implementation

The InitParams class is merely a little helper, providing a fluent interface over a dictionary and convenience methods, as I needed them:

Reading the config file is equally simple with XLinq at our disposal:

And I will complement that with additional helpers in upcoming posts.

What’s it worth?

So now I have the ability to provide configuration to my client, the information readily available to be picked up during the startup event or anytime from Application.Host. For simple values I have the configuration file, for other information I can extend my helper class anytime I want (and I will!), the infrastructure is there.

Could that have been done otherwise? Well, a respective services would have been another option. But providing the information via the initparams has the advantage of being readily available to the client without delay. And configuring the configuration service via the configuration service…? Well.

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

August 30, 2009

Silverlight Bits&Pieces – Part 5: Service Call Basics

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

This time, building on the last post, I’m going over the basics of getting data to the client. The order of the day is just get it working, I’ll come back later to address some issues.

The Service

I have to provide the service first. This is easiest done by adding a Silverlight-enabled WCF service, located in the “Create New Item” dialog, under the Silverlight group. It comes with the necessary configuration, ready to use. After defining the EF model, a first service operation delivering recently acquired books may look like this:

Note the Sleep. I like to stress the asynchronous nature of the SL client and I want the client code to handle this properly, thus the Sleep makes the time lag very apparent.

Note: This way I know very early where I should provide visual feedback, or disable controls. This is especially important considering that on my development machine I will hardly spot any delay, but once the application goes into production and network performance and latency demand their toll, this will likely change.
Thus I recommend you do the same, perhaps surrounding with #if DEBUG and making it configurable.

Calling a service

After running the web application, Cassini provided a live version, which I needed to create the client side proxy. This generates respective code, of course including the data defined in the contract. Those classes already (by default) implement INotifyPropertyChanged and use ObservableCollection<T>. It certainly will give you a head start if you can use these classes as your model.

For every service operation there is a respective MyOperationAsync() method that initiates the asynchronous call and a MyOperationCompleted event that delivers the result. (No synchronous version by design!)

One hint: Creating the client proxy also created a ServiceReferences.ClientConfig file in the service assembly. This file is needed in the UI project to be available for the client. It works quite well to include it in the UI project be setting a reference, rather than just copying the file (“add existing item”, “add as link”), and this way you won’t have to keep a copy in sync.

Wiring it Together

The idiom is documented well enough, thus without further ado, my first version looks like this:

The client instance is also used to detect whether the last call is still under way, and to suppress further calls.

The UI includes a button to trigger the server call (just for now, in this case the call will eventually be made from the c’tor), and the DataGrid to present the result:

The respective event handler is trivial as well:

Now, running the app looks like this:

Clicking the button… waiting… that’s why I put the Sleep in… . Oh, and I can click the button as I like? … Finally the result appears:

Regarding the “I can still click the button…”, I wanted to make this point specifically, because I have already seen people ignore that time lag too easily. It no only makes your application “feel unresponsive” in case of longer operations, because the user doesn’t get any indication whether the application has actually accepted his button click. It also may makes your logic more complex if it had to deal with multiple calls at the same time. My code simply ignored them, but there is no reason why they shouldn’t be processed as they come in. Even canceling the previous call may make sense, because it may be obsolete due to changed parameters (most operations are certainly not as simple as the one used in this example). You may want to cancel if the criteria actually changed and ignore the subsequent call if the criteria stayed the same… . See? Quickly the complexity adds up. The easy way around is disabling the button and making the user experience a sequential one.

Providing visual feedback

So, the logical step is to add a respective property CanLoadBooks and use it for the binding…

After that, disabling the button can be done via data binding the IsEnabled property:

And nicely my application provides visual feedback and at the same time prevents the user from redoing what he did:

The stage…

This post sort of completes the initial setup of the stage for my Silverlight application. I have a solution, the basic layout is in place, the general application architecture and data binding strategy is set up, and with this post I can talk to the server.
From here I will go exploring various aspects, probably at random, but now I have the means to do so.
And there is a lot of aspects to cover anyway. The services part I addressed in this post is by no means covered exhaustively, neither is data binding. Other topics haven’t yet been mentioned at all, like basic application services, visual state manager, navigation, or configuration.

Anyway, I will have to work on it before I can write about it. So this series is certainly not coming to an end, however further posts may take some more time. And I have a small by-project running, some mischief I’m up too ;-)

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

August 27, 2009

Silverlight Bits&Pieces – Part 4: View Model Basics

Filed under: .NET, .NET Framework, C#, Design Time, Silverlight, Software Development — ajdotnet @ 8:48 pm

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

Displaying and manipulating data on the client – the one and only purpose of any LOB application – includes two things if it comes to Silverlight: a) The asynchronous server calls and b) the client architecture. I will be going over them in a cursory fashion and come back later to address each one in more depth. This time the client architecture.

View Model basics

The client code is largely guided by the employment of the Model-View-ViewModel (M-V-VM, or MVVM) approach, which is the predominant architectural approach used with SL and WPF. The reason probably being that it is a natural counterpart to the WPF and Silverlight data binding features, the two work extremely well together.

Cook book style:

  • For every page (the view) there is a respective class (the view model) that manages the data (the model).
  • For each control on the view that shall be populated dynamically with data, the view model has a corresponding property providing the model.
  • For each control state, such as enabled or visible, that shall be controlled by the logic, the view model has a corresponding property, probably boolean.
  • For each action triggered by the UI the view model has a respective method.

The view model is very closely associated with its view, so there is not much reuse here, but then, it largely consists of properties and forwards to service calls. Or so the theory says. (Subsequent posts will gave deal with the shortcomings….)

Please note that it is debatable whether the data provided by the view model actually is the model. Another approach would be to expose a view related data model, namely view entities. The view model would have to map them to the data model (the model) the lower layer exposes, probably some service proxy.

Both approaches have pros and cons, however you’ll mostly see the former approach, since it’s well supported by the tools (service proxy generation, etc.). Still, it has some cons…

Anyway, the only technical demand for view models in SL is due to the intended use for data binding: Classes subject to fully fledged data binding need to support the INotifyPropertyChanged interface for simple properties, while collections have to support INotifyCollectionChanged. The later one comes for free if you use ObservableCollection<T> consequently. (Please note that data binding works with conventional properties, but only to a limited degree.)

For INotifyPropertyChanged a little base class comes in handy:

Note the generic overload. That’s a little trick to avoid typos in the property name argument.

With this class as base a property implementation usually follows this idiom:

(Without that trick one would have to pass the property name as string. A source of errors due to typos, and a pitfall during refactoring.) 

BookFilter is a data class that, again, follows the same pattern, i.e. it supports INotifyPropertyChanged.

Hint: This begs for a code snippet! :-)

The View Model

Any book shelf has a collection of books, so does my application. The book list page should provide a means to filter the book list (two text boxes), a button to trigger the search, and to show the result (a data grid):

Not especially nice and the grid is a little degenerated for now, but that will change. In XAML:

Thus the first view model implementation may look like this (including some simple test data, the next post will deal with the server call):

Databinding

For the actual binding I need to wire that up with the page. The usually presented manual way looks like this:

The view model class is created in the c’tor, and assigned to the DataContext. A property provides a more convenient access to it. This is already used in the button event handler that triggers the book search.
However, I recommend against this way. Rather I did the data binding in Blend…

Opening the page, selecting the first textbox, finding the Text property in the properties and clicking the text box (or that tiny little dot to the right) brings up the context menu.

Then I choose data binding, the Data Field tab, and the +CLR Object button:

That left finding the view model class and selecting it:

This way I could add various “data sources”, yet I only want one for now, and according to M-V-VM, for ever. Afterwards the dialog lets me browse the class structure and select the property to bind against:

On second thought, I selected the StackPanel which contains the filter textboxes and bound it against the BookFilter property, in order to narrow the available context. Afterwards the textboxes could be bound via the Explicit Data Context tab:

I had to expand the lower area to set the binding to TwoWay.

But I didn’t have to go through the dialog armada for every field. Blend also provides the data tab that lets me browse through the available data sources. Drag’n’drop of field simply works and generally uses the last settings from the dialog, i.e. it includes the TwoWay setting. Also it binds by against the default property, but if I hold the shift key down it lets me choose the property. And some other stuff I leave to you to explore. Really nice.

Anyway, this is what Blend just created for us in markup speak (just the relevant part):

It registered the namespace to locate the view model class, created the view model as resource, set the DataContext of the LayoutRoot element to this resource, and it added the usual binding to the subsequent controls.

Changing the generated prefix to viewModel was all I did. Otherwise I could live very well with that, given that is achieves all I need and it allows me to do my data binding much more efficient and less error prone in Blend. The manual way was opaque to Blend, thus it couldn’t assist me in any way.

The only thing left was removing the manual instantiation from the c’tor and changing the ViewModel property to use the LayoutRoot control. I may have moved the binding to the page instead, but I prefer to work with the tools, not against them.

After running the application and clicking on the button, it shows the respective test data:

The next post will deal with the actual server call.

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

August 21, 2009

Silverlight Bits&Pieces – Part 3: First Layout

Filed under: .NET, .NET Framework, Design Time, Silverlight, Software Development — ajdotnet @ 9:48 pm

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

One thing is as true with SL as it was with HTML and CSS: Starting with a basic layout of the pages and a “site map” really helps a lot. (Trying to work with a style system that you don’t know doesn’t.)

The application created by the template looks like this:

It’s a navigation application with head area (including menu) and remaining work area. It uses a Grid control, yet only as kind of canvas, all controls are placed via margins and alignments. I find this, well, curious, there is a canvas control after all. But the layout doesn’t suit me anyway.

So the first step is to get rid of all styles, i.e. I cleaned Assets/Styles.xaml. That included removing all references to these styles, as in this fragment:

Searching with a little regular expression solves that problem. Now for the intended layout:

I want to have a head area with application title and other information. A left area containing the menu. A bottom line with legal information. And finally the remaining area for our pages. And some space between for some visual separation.

In SL this is done with a Grid. Curiously enough, for this is akin to table layout in HTML. I wonder when the CSS gang will show up and cry wolf ;-)

Most samples show and explain how to write the markup to define rows and columns. But then, most samples are pre-created and reiterated, and I have problems “mind rendering” the markup. With the Silverlight 2 SDK there was at least a kind of preview in VS, but with SL3 that preview does not work (the document outline may help to navigate larger XAML files, though):

So I chose a different way and put Blend to its first use…

Grid layout

Defining the desired Grid layout can be done easily in Blend. Placing rows and columns is just a mouse click away: Clicking on the areas to the left or the top adds new rows and columns. Clicking on the symbols changes the type. If you don’t see them, change the layout mode by clicking in the upper left icon.

 

Once the rough layout is done, it can be saved and one can switch back to VS. The resulting markup is very clean, Blend generally does a good job producing clean markup and at the same time leaving your markup as it was.

Placing the contents

Next step was creating controls for the three areas (head, menu, footer) and move the respective content from the page there (copy & paste in VS). The markup now only contains the navigation frame, which is the working area. Drag & drop and some more mouse jostling in Blend positions that control in the correct cell:

And sizing it correctly:

Also – after recompiling the solution – Blend picked up the user controls and offered them as assets if you select Project. Again some mouse jostling later (and with different backgrounds colors for each user control to distinguish them) the result looks like this:

Blend automatically generated a namespace definition as prefix for the controls, using a veeerrrryyyy long prefix name. But that’s easy to solve and to replace with control. The final markup is, again, very clean:

After some working on the user controls and some styling… alright, it may take some time, but had it ready from some internal application, and besides it was done by a colleague, for if I had done it myself if would probably cause eye cataracts… , the end result looks like this:

This may all seem trivial if you’ve been through this experience once. Bottom line I guess is the way I worked through this (which may or may not work for you). It’s the combination of VS and Blend, working with both tools at the same time. Even if you are a markup guy rather than design time worker in ASP.NET, my recommendation is that you give Blend a chance. It’s far more stable than the ASP.NET designer in VS ever was. I’m not saying you should switch to Blend, just get the best of both, VS and Blend.

The next post will contain some real code, promise ;-)

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

August 19, 2009

Silverlight Bits&Pieces – Part 2: Silverlight Solution

Note: This is part of a series…. Well, it will be ;-)  
You can find the related posts here

Alright, let’s start looking into some Silverlight 3 (SL3) development. Specifically of business applications.

First step is a respective solution. I created a new “Silverlight Navigation Application”, with SL hosted in a web site, and got the typical solution structure. Needless to say, that this structure doesn’t meet my requirements.

First, I’m going to have a bunch more assemblies. And since SL assemblies are different from “ordinary” assemblies – they work against a different runtime and use different libraries – I like to have them clearly distinguishable. I did this a) with respective solution folders and b) with an added namespace part “SL3”.

The Server Part

On the server side I added two assemblies:

One data access assembly. This contains the ADO.NET Entity Framework access to the database. For the purpose of this application, this constitutes the business layer. (A little simplistic, but bear with me, the focus is on the client.)

A “Common” assembly. There will be server side parts of logic that may be reused in other applications.

I also made some adjustments to the web application (project properties/web): I changed virtual path to “/xBookshelf”, I don’t like my web apps to occupy the root. And I set the port to “specific port”. It doesn’t matter which one, it’s just a little annoying to have to update service references when the port is changed by VS every now and then. Speaking of services, I’m going to put them in a separate folder.

The Client Part

My naming convention for SL3 assemblies is Company.Application.SL3 . Specifically I renamed the SL assembly containing the XAML files to SDX.Bookshelf.SL3.UI. Renaming the .xap file affects the web project and the hosting pages. I also changed the pages to have Page as postfix.

And there are a few additional assemblies as well:

SDX.Bookshelf.SL3.Model contains the view models, as I’m going to use the Model-View-ViewModel pattern.

SDX.Bookshelf.SL3.Service contains all service references. Since this is all generated code, I thought it prudent to cleanly separate it.

SDX.SL3.Common is the counterpart to the server side common assembly. It will contain everything that may be reused in other application.

Setting the project dependencies and getting it all to run again is just a bit tedious, especially because the startup project is the web project, but the application in question is the UI project.

Blend

The final test for the reworked solution is opening it in Blend – which may be not as trivial as it sounds :(

You will at least get one warning dialog telling you that blend does not support solution folders. Never mind, that’s of no consequence.

In one project I also run into a serious issue: Blend refused to open the solution with the following dialog:

Also subsequently I got a large message box with an exception stack trace.

To work around this problem, I removed all projects from the solution and added them again in Blend. I was able to provoke that bug by reordering the sequence of the projects within the .sln file, hence it’s probably due to some project dependencies that blend can’t solve correctly.

Anyway, don’t let that bias your perception. Blend may be awkward, and it takes time getting used to – but is worth the effort.

That’s all for now,
AJ.NET

kick it on DotNetKicks.com

August 17, 2009

Silverlight Bits&Pieces – Part 1: Introduction

With Silverlight I was lucky…

  • I never got to look into Silverlight 1, so I avoided the scripting mess ;-)
  • For Silverlight 2 I participated in some research efforts on our company and I worked on a business solution (as in business solution, not just a “simple” control). This did not only include the obvious stuff like drawing and driving the UI, but also some necessary groundwork.
  • Microsoft launched Silverlight 3 officially on Friday, July, 10th; on the following Monday, July, 13th, I was officially in a customer’s Silverlight 3 project. We had just waited for the availability ;-)

And to relay the probably most important experience for me so far: Working with Silverlight 3 and Blend is fun!

It’s easier to get what you want than with web applications, the programming model is much more concise and powerful than ASP.NET, Blend has a far better user experience than the WebForms designers ever had (after being nearly a decade and several versions old!).
For me, working with Silverlight has a thrill factor comparable to what I encountered when I first started to develop with .NET.

Note: From now on, I’ll refer to Silverlight 3 simply as SL.

So, I may have a little head start with SL business applications and their demands, but I’m sure that will wear down over time. Anyway, I thought I might share some of the experiences, insights, and ways I discovered.

This is not going to be me providing a tutorial, or me telling you what to do. It’s about me telling you what worked for me. Some may be outright trivial (especially the first ones, laying the foundation), some may be about the how to do it, rather than the what to do. But then, I also had to tackle a few things that go beyond the usual “My first Silverlight Hello World Application” type of samples.

Disclaimer: This is as much about telling you how I did things as it is a learning experience for me. I may be wrong at times. I may tell you in one post to go left and a few posts later that you had better not listened. No warranties here, sorry.

And I’ll try something different and keep the posts short and to a certain point ;-) (and I admit that this post is already in violation with this intention…).

Preconditions

Just for the record: I’ll base the work on SL as you can get it here. That includes:

  • Microsoft Silverlight Tools for Visual Studio 2008 (includes developer runtime and SDK)
  • Microsoft Expression Blend 3 + Sketchflow

I refrained from using RIA services, because I want to understand the technology bare boned. That being said, I think that RIA services has really great potential and for those interested I recommend Brad’s series. I also haven’t thought about including the control toolkit, yet.

Setting the stage

My way of learning a new technology is usually a) read about it to understand the idea behind it, b) do some technical prototypes to dive into one or the other feature, and c) take a real world example and see how the technology fares. In my experience, point c is the most important, because it goes beyond the usual samples that are built to suit the technology. Rather it stresses the technology’s abilities to meet actual needs. This is usually when you’ll encounter the pitfalls.

My real world example for SL was kind of a library or book management application. At SDX we maintain our books in a simple SharePoint list, so every colleague knows what books are actually available, where to find them, who has borrowed it currently. This list is more intended to keep people informed, than controlling whether they return the books on time. Weren’t our colleagues dispersed at various customers’ sites, a simple bookshelf with no bureaucracy at all would be sufficient. (And I wouldn’t have to go hunting for lost books every now and then ;-) .)

The Database

The database I’m going to use is simple enough. It contains books, information about who borrowed it, and user information:

image

Additionally I like to create views as I need them (rather than using EF for this). For example BookInventory contains all books as well as the related information on the currently borrowed books and employees.

And with these conditions set, we are ready to start. The next post will start at the beginning, stay tuned ;-)

That’s all for now folks,
AJ.NET

 

August 1, 2009

Posting Guards: Guard Classes explained

Filed under: .NET, .NET Framework, C#, Software Developers, Software Development — ajdotnet @ 11:53 am

A colleague writing an article about code contracts recently asked me about some useful links about Guard classes, something I have been advertising for some time. ‘Sure’, I thought — and was taught otherwise.

There are certainly references to Guard classes. For example this one hinting at an implementation from MS Patterns&Practices, although an outdated one and no online documentation available. And this one talking about using Guard classes in combination with LINQ.

Still, nothing explaining the concept, nothing on Wikipedia, nothing anywhere. Can it be that Guard classes are far too simple to be worth mentioning? I don’t think so, because while the implementation certainly is simple, I wouldn’t have had to explain the concept that often if that where the reason.

So, what are Guard classes?

First of all, let’s make sure we’re taking about the same thing. Judging from the name, Guard classes are about guarding against something, but this can mean just about anything. Actually I found two incarnations: One, guarding against concurrent access, i.e. some kind of locks. And two, guarding against the passing of invalid parameters into a method – which is what this post is about. (You may have come across Guard classes by the name of ArgChecker, ArgumentHelper, or something similar, or as single helper methods appearing where they don’t belong.)

Straight to the matter: Have a look at the following example:

IEnumerable<Employee> FindCustomers1(Guid companyID, EmployeeFilter filter)
{
    IEnumerable<Employee> result= null;
    if (companyID!=Guid.Empty) // only hit DB if we have to
    {
        using (DatabaseDataContext context = new DatabaseDataContext())
        {
            result = from e in context.Employees
                         where e.FirstName == filter.FirstName && e.LastName == filter.LastName
                         select e;
        }
    }
    return result;
}

While probably doing its job properly, this method isn’t exactly defensive. The issue should be apparent: What happens if the caller passed null for the filter? Not that he is expected to, quite the opposite, but anyway?

You could try to handle that in code and it would probably lead to some ugly code, as Abby rightly complained about. And to be blunt, that approach is wrong right from the start. If caller is not supposed to pass null values into our method, why should we clutter our code with conditions that aren’t supposed to happen anyway.

The better solution is getting rid of unwanted null values by making them illegal. And not only by politely asking in the documentation (and please RTFM); rather make it unmistakably apparent, punish any violation, make it impossible to bypass. In other words, check the parameter and throw an ArgumentException.

On second thought, the same reasoning applies also to the properties of our filter object, so we may end up writing the following code, prone to becomes ugly itself:

if (filter == null)
    throw new ArgumentNullException(„filter“);
if (filter.FirstName == null)
    throw new ArgumentNullException(„filter.FirstName“);
if (filter.LastName == null)
    throw new ArgumentNullException(„filter.LastName“);

And we actually did expect some content, so why not go ahead and do some other vanity checks:

if (filter.FirstName == „“)
    throw new ArgumentNullException(„filter.FirstName“);
if (filter.LastName == „“)
    throw new ArgumentNullException(„filter.LastName“);

But wait. An empty string is certainly not null. Unfortunately there is no StringEmptyArgumentException. Should we use an ArgumentOutOfRangeException? Or an InvalidOperationException, not an ArgumentException at all? Derive a new one? ArgumentOutOfRangeException may look nicely to me, but my team mate just settled with ArgumentNullException, which is at the least an inconsistency… .

And what the heck, this is way too much code for nothing anyway. And so we end up not checking our parameters and hoping for the best…?

Now consider this code:

IEnumerable<Employee> FindCustomers2(Guid companyID, EmployeeFilter filter)
{
    Guard.AssertNotNull(filter, „filter“);
    Guard.AssertNotEmpty(filter.FirstName, „filter.FirstName“);
    Guard.AssertNotEmpty(filter.LastName, „filter.LastName“);
    
    IEnumerable<Employee> result = null;
    if (companyID != Guid.Empty) // only hit DB if we have to
    {
        using (DatabaseDataContext context = new DatabaseDataContext())
        {
            result = from e in context.Employees
                         where e.FirstName == filter.FirstName && e.LastName == filter.LastName
                         select e;
        }
    }
    return result;
}

We just replaced 5 ugly conditions (10 LOC) with 3 calls. Let me rephrase that: We replaced a bunch of code detailing some implementation with 3 lines revealing the intention – way more readable. Wow! By centralizing the checks, we were able to provide more convenience (putting the null and string empty check in one method), we ensured consistent behavior, we improved the calling code considerably. And finally, we even added some more information to the exception, as you will see in the implementation:

[DebuggerStepThrough]
static public void AssertNotEmpty(string arg, string paramName)
{
    if (arg == null)
        throw new ArgumentNullException(paramName,
            „Argument ‚“ + (paramName ?? „<missing>“) + „‘ should not be NULL!“);

    if (arg.Length == 0)
        throw new ArgumentOutOfRangeException(paramName, arg,
            „Argument ‚“ + (paramName ?? „<missing>“) + „‘ should not be empty!“);
}

You don’t want to put that code in every method. But you do want to call the Guard method, don’t you?

Now that we have established what Guard classes are, let’s look at …

What are Guard classes about?

So far I introduced Guard classes form the coding level, merely as convenient helper classes. But there’s some broader meaning to them, namely in the following areas:

  • Contracting
  • Self preservation
  • Robustness

Contracting.

Contracting as a means has gained attention as important aspect of SOA service design, and also as development approach, namely design by contract. Contracting may be a major undertaking if it comes to SOA services, yet it can also be employed on a much lower level, designing the public interface of a class.

A little simplified, a contract of a class or service consists of

  • Functional contract: Specifies the operations, the semantics, required call sequences, runtime behavior, error conditions and behavior. Some of this may be expressed using code, some may not.
  • Data contract: Details parameters and return values, in other words the data that is exchanged during the operations. It defines the legal shape and values of the data, restricting it first by data types, secondly by additional demands, such as stating which parameter is mandatory, which content is required, and which values it is limited to beyond what the data type mandates. Also interdependencies between fields, and so on.
  • Some other aspects, but that’s not relevant right now.

As you see, the data contract goes beyond what the type system is capable to enforce. And Guard classes may serve as a means to express some of those aspects in code. Thus, Guard classes serve to enforce the contract of a class. And since these calls are that obvious, the code is self-documenting its preconditions quite nicely.

Note 1: Of course this makes only sense with regard to the technical contract that has to be met by the calling code, i.e. the developer, not a business contact that has to be met by the user. See my post on error handling and responsibilities for more on that topic.

Note 2: In terms of design by contract, Guard classes express the preconditions of an operation, something that has been baked into other programming languages right from the start.

Self preservation.

If you are working in a team, you inadvertedly have to work with other team members. Good ones, bad ones. And you may want to protect yourself against the later… .

Face it: If a NullReferenceException arises, the developer who wrote that particular code fragment – mayhap you – is held responsible (shot on first sight, so to speak). Even if it turned out later that the calling code passed some illegal null value… . Well, problem solved, but the stigma sticks, and anyone will only remember that the exception was thrown in your code.

How do you protect yourself against that? Guard classes. If the calling code just passed some crap data – despite you having told that guy what to pass a hundred times – just throw it right back into his face. That’s what ArgumentExceptions are for: complaining loud and clear about someone unduly misusing your code. Be the accusator, not the accused!

BTW: If you’re on the callers side and the method you just called returned a value, you may achieve something similar with Debug.Assert.

For example if you had written that code above, and I knew you to be a sloppy developer, I would certainly check the return value. And if I were as mean as you are sloppy, I would deliberately call it passing Guid.Empty as companyID. And if you dared to hand back that pesky null instead of an empty enumeration I would … .

Well, never mind. You‘re not sloppy, I‘m not mean, and I only put that bug in to stress the fact that Guard classes only work up the call chain, not down. (And yes, it’s a bug to return null in the above case. Methods supposed to be used in a LINQ context have to comply with LINQ demands, which are based on functional programming, which boils down to „no nulls please!“)

Robustness (or: making errors apparent).

Someone passed null or some other unwanted value to a method. There are actually two bad things that might happen:

  1. The application may crash further down.
  2. The wrong value may affect some data, but the application continues to work.

Number one may be bad, but at least the application crashes (which is a good thing!). Still, in this case Guard classes will help you identify the error far earlier, possibly avoiding a situation where you’ll have to hunt for the root cause of a problem. This should at least help diagnosing the problem.

Number two is far worse. It’s actually the very situation that you would want to avoid at any cost: A bug that stays unnoticed. A bug that occasionally produces wrong data, and that lingers around long enough to seriously affect data consistency to a degree that renders all data useless, because you have no way of knowing which data was affected and which not. Technically just a tiny slip, but in the long run these bugs are the most harmful.

To guard against these bugs Guard classes put up another safety net. Make sure the data coming in matches the specification.

Essentially both issues neatly demonstrate what „fail early, fails fast“ is about. Making errors apparent, prevent them from being obscured and from causing damage further down the line.

And that’s it…

Quite some task for a tiny little helper – but really worth the effort. Should you need some kick-start to employ this concept yourself, I posted the code for a Guard class here. Use it, enhance it, employ it to make you life easier.

HIH!

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

July 26, 2009

Playing game…

We’ve defined the problem, we’ve established the rules, now we are ready to actually play the game. In other words: We will employ consistent and sufficient exception management in an ASP.NET application. No less!

Note: What follows is merely a sample implementation, just to drive the ball home, but it should turn my earlier musings into a little more practical advice. And since this is only meant to highlight the principle, not to provide a production ready solution, I’ll keep it simple.

Exception classes

First let’s try to classify our exceptions, depending on the supposed effect. This classification is sort of the driving force behind the strategy: who is responsible, or more to the point how to tell the responsible people…

A quick reminder on what our goal is:

  1. The user has to solve everything that results from his user user interaction in due process. This includes invalid input, insufficient permissions, or other business conditions that interrupt the current functionality.
  2. The administrator is responsible for infrastructure issues. This includes every call into the „outside world“, such as databases, services, file system. Issues here are manifold, including:
    • unavailable database or service
    • errors during some operation, e.g. unexpected a constraint violations
    • erroneous configuration
  3. Everything else: Bugs. Developer. You! ;-)

So consequently:

  • If the user is responsible, we just tell him on the page and let him choose what to do.
  • If the administrator is responsible, we show a general error page, telling the user that the application is not available, and of course we write some event log entry.
  • If the developer is responsible, we do the same, but we tell the administrator explicitly to forward the event log information to the development team.

I’ll spare you the boilerplate exception implementation details, suffice it to say that we have a UserIsResponsibleException for “user exceptions” and a AdminIsResponsibleException for “admin exceptions”, respectively. Names that wouldn’t make it into my production code, but that’s what their intention is, anyway. Oh, and add a ConcurrencyException exception for respective issues, they may or may not be user exceptions, depending on the context.

Now let’s put the handlers in place. These reside in the UI layer, and from there we can work through the architectural layers towards the databases.

User error handlers

User exceptions have to be handled on the page level. Whenever you call into some business layer method, say from a button click event handler, you wrap the call in a try/catch(respective exceptions). The exception is then presented to the user, and eaten, meaning it is not thrown along. Something like this:

protected void btnConcurrentUpdate_Click(object sender, EventArgs e)
{
    try
    {
        BusinessLogic bl = new BusinessLogic();
        bl.UpdateDatabaseWithConcurrencyIssue("some content");
        lblConcurrentUpdate.Text = "did it.";
    }
    catch (UserIsResponsibleException ex)
    {
        // just give feedback and we’re done
        PresentError(ex);
    }
    catch (ConcurrencyException ex)
    {
        // just give feedback and we’re done
        PresentError(ex);
    }
}

The way of presenting the error message is something that has to be decided per application. You could write the message to some status area on the page, you could send some java script to pop up a message box. You could even provide a validator that checks for a recent user exception and works with the validation summary for the feedback.

Statistics:

  • Exception classes: Write once.
  • Presentation: Write once.

The try/catch code is simple enough, yet you have to do it again and again, and should the need for another user exception arise (e.g. some user errors can be handled on the page, some others require leaving the page), the logic is spread across our pages. Thus it makes sense to factor the actual handling into a separate method, in a helper class, or a page base class. Now, catching specific exceptions is still part of our job and that cannot be factored out. To solve this we have three options:

  1. Build the exception hierarchy accordingly and catch the base class for user exceptions.
  2. Catch all exceptions and throw the unwanted exceptions on.
  3. Live with the problem.

I decided against option 1 because I didn’t want the concurrency exception to be derived from some user exception. Option 3 is what we wanted to avoid in the first place. So my solution is number 2, in the name of ease of use and maintenance, but at the expense of language supported exception handling features:

protected void btnConcurrentUpdate_Click(object sender, EventArgs e)
{
    try
    {
        BusinessLogic bl = new BusinessLogic();
        bl.UpdateDatabaseWithConcurrencyIssue("some content");
        lblConcurrentUpdate.Text = "did it.";
    }
    catch (Exception ex)
    {
        // since C# does not support exception filters, we need to catch
        // all exceptions for generic error handling; throw those on, that
        // have not been handled…
        if (!HandleUserExceptions(ex))
            throw;
    }
}

This is boilerplate and unspecific enough to copy&paste it around. The generic handler may look like this:

bool HandleUserExceptions(Exception ex)
{
    if (ex is ConcurrencyException)
    {
        // just give feedback and we’re done
        PresentError(ex);
        return true;
    }
    
    if (ex is UserIsResponsibleException)
    {
        // just give feedback and we’re done
        PresentError(ex);
        return true;
    }
    
    // other errors throw on…
    return false;
}

Statistics:

  • Handler method: Write once.
  • Catching exceptions: Every relevant location, boilerplate copy&paste

Please note that exception filters might make this a little less coarse, but this is one of the rare occasions, where a CLR feature is not available to C# programmers. Anyway, we just factored all logic into a centralized method which achieves exactly what we asked for.

But wait… . Wouldn’t the Page.Error event provide a better anchor? It’s already there and no need to add try/catch around every line of code. Look how nice:

protected void btnConcurrentUpdate_Click(object sender, EventArgs e)

    BusinessLogic bl = new BusinessLogic(); 
    bl.UpdateDatabaseWithConcurrencyIssue("some content"); 
    lblConcurrentUpdate.Text = "did it.";
}

protected override void OnError(EventArgs e)
{
    // raise events
    base.OnError(e);
    
    var ex = Server.GetLastError();
    
    // if we don’t clear the error, ASP.NET
    // will continue and call Application.Error
    if (HandleUserExceptions(ex))
        Server.ClearError();
}

Unfortunately at the time the error event is raised, the exception will already have disrupted the page life cycle and rendering has been broken. It may help in case you need a redirect, but not if the page should continue to work.

“Other” error handlers

So, the page handles user exceptions, what about admin and system exceptions? The page doesn’t care, so they wind up the chain and ASP.NET will eventually pass them to the application, via the Application.Error event, available in the global.asax. This is the “last chance exception handler” or LCEH for short.

One thing we did want to do was writing the exception into the event log. I’ll leave actually writing into the event log to you, just remember that creating an event log source requires respective privileges, e.g. running as admin. Just a minor deployment hurdle.

protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    
    // unpack the exception
    if (ex is HttpUnhandledException)
        ex = ex.InnerException;
    Session["exception"] = ex;
    
    // write detailed information to the event log…
    WriteInformationToEventLog(ex);
    
    // tell user something went wrong
    Server.Transfer("Error.aspx");
}

private void WriteInformationToEventLog(Exception ex)
{
    // an ID as reference for the user and the admin
    ex.Data["ErrorID"] = GenerateEasyToRememberErrorID();
    
    string whatToDoInformation;
    if (ex is AdminIsResponsibleException)
        whatToDoInformation = "Admin, you better took care of this!";
    else
        whatToDoInformation = "Admin, just sent the information to the developer!";
    
    // put as much information as possible into the eventlog,
    // e.g. write all exception properties into one big exception report,
    // including the Exception.Data dictionary and inner exceptions.
    // also include information about the request, the user, etc.

    …
}

As you can see, there are some details to keep in mind. One, the exception has been wrapped by the ASP.NET runtime, and that exception class doesn’t tell you anything worthwhile. Second, passing information to the error page may be a little tricky in cases where the request has not yet (or not at all) established the session state. The easier approach is to let ASP.NET handle the redirection, yet at the loss of information. Three, be careful regarding the requests: depending on the IIS version you may get only .aspx requests, or any request including static resources. Thus, with this simplistic implementation a missing image will send you to the error page depending on the IIS version and registered handlers.

I would also like to encourage you to spend some time on collecting information for the event log message. A simple ex.ToString() doesn’t reveal that much information if you look closely. You should invest some time to add information about the current request (URL, etc.), the user (name, permissions), and server state (app domain name, to detect recycling issues). And use reflection to get all information from the exception, especially including the Exception.Data dictionary. Also go recursively through the inner exceptions. The more information you provide, the better.

I also hinted at an error ID. It is probably a good idea to give the user some ID to refer to when he talks to the admin. This way, the admin will know exactly what to look for in the event log (especially in multiple event logs of a web farm).

Finally, the exception class tells us whether we should include an “Admin, do your job!” or “Kindly forward this issue to your fellow developer, brownies welcome, too.” message.

And by the way: This is the one and only location in our application that writes to the event log!

Statistics:

  • Global error handler: Write once.

Done. We have the handlers in place. Handlers for user exceptions, admin issues, and any other exception that might be thrown. Now we need to take care that error causes are mapped to the respective exception class.

Business layer

The business logic is being called from the UI layer, and calls into the data access layer. Thus it has to check parameters coming in, as well as data handed back from the data source.

Data coming in hast to comply with the contract of the business class, and I’d like to stress the fact that not every data is legal. Meaning the business logic is not expected to accept every crap the UI layer might want to pass. A search method that takes a filter class as parameter? No harm in defining this parameter mandatory and require the UI to pass an instance, even if it is empty. And a violation is not the user’s problem, it’s the programmer’s fault! In these cases we throw an ArgumentException, and that’s it. The LCEH will take care of the rest, blaming the UI developer that is.

public IEnumerable<Customer> SearchCustomer(SearchCustomerFilter filter)
{
    // preconditions have to be met by the calling code
    Guard.AssertNotNull(filter, "filter");
    
    // input values have to be provided by the user
    if (string.IsNullOrEmpty(filter.Name))
        throw new UserIsResponsibleException("provide a filter value");
    
    DatabaseAccess db = new DatabaseAccess();
    return db.SearchCustomer(filter);
}

Any issue with the content of the data, i.e. the information the user provides, is a user issue. Usually this includes data validations and if you follow the rule book you’ll have to repeat everything the UI already achieved via validators. Whether you do that or just provide additional checks, e.g. dependencies between fields, is something I leave to you. Anyway, throw a user exception if the validation fails.

Calling the data access layer may also result in thrown exceptions. Usually there is no need to catch them at all. Period.

Finally the data you get from the database may ask for some interruption. A customer database may tell you that this particular customer doesn’t pay his dues, thus no business with him. In this case you throw a user exception in order to interrupt the current business operation.

And that’s it.

Statistics:

  • Business validations and interruptions: As the business logic demands…

“Uhh, that’s it? And I used to spend so much time on error handlers in my business logic…”. Nice, isn’t it? Just business logic, no unrelated technical demand.

Data access layer

The data access layer is where many exceptions come from. If you call a data source (web service, database, file system, whatever), the call may fail because the service is unavailable. Or it may fail because the called system reports an error (constraint violation, sharing violation, …). It may time out. Some exceptions won’t require any special handling and you can leave them alone. Some need to be promoted to admin or user exceptions, or they may require special handling for some reason. You should  translate those exceptions to respective application exceptions. The reason is  that you don’t want to bleed classes specific to a data source technology (e.g. LINQ 2 SQL exceptions) into the upper layers, introducing undue dependencies.

Luckily all this tends to be as boilerplate as can be. Call/catch/translate. With always the same catches. So, again, we can provide a “once and for all” (at least per data source technology) exception handler, like this one for the ADO.NET Entity Framework:

public IEnumerable<Customer> SearchCustomer(SearchCustomerFilter filter)
{
    try
    {
        using (DatabaseContainer db = new DatabaseContainer())
        {
            //…
        }
    }
    catch (DataException ex)
    {
        TranslateException(ex);
        // any exception not translated is thrown on…
        throw;
    }
}

And the respective translation method:

static void TranslateException(Exception ex)
{
    // database not available, command execution errors, mapping errors, …
    if (ex is EntityException)
        throw new AdminIsResponsibleException("…", ex);
    
    // translate EF concurrency exception to application concurrency exception
    if (ex is OptimisticConcurrencyException)
        throw new ConcurrencyException("…", ex);
    
    // constraint violations, etc.
    // this may be caused by inconsistent data
    if (ex is UpdateException)
        throw new AdminIsResponsibleException("…", ex);
}

Statistics:

  • Translation method: Write once.
  • Catching exceptions: Every relevant location, boilerplate copy&paste

Conclusion:

Done. Let’s sum up the statistics:

  • Write once (at least partly reusable in other applications):
    • Application exception classes
    • Last chance exception handler (LCEH)
    • Handler method for user errors, including presenting the error
    • Exception translation method in DAL
  • Boilerplate copy&paste
    • Catching exceptions in the UI, call handler
    • Catching exceptions in the DAL, call translation
  • Application code that still needs a brain ;-)
    • Business validations and interruptions: As the business logic demands…

And this is all we have to do with regard to exception handling in our application. I’ll let that speak for itself… .

This post concludes this little series about the state of affairs regarding error handling in an application. I do not claim to have presented something particularly new or surprising. Rather the opposite, this or some similar strategy should be considered best practice. The reason to even start this series was the fact that I regularly encounter code that does exception handling … questionably. And I also regularly met people who look at exception handling only in the scope of the current code fragment, not in light of a broader approach that spans the application.

If you need further motivation to employ proper error handling in the first place, look here.
A little more on error management in long running, asynchronous scenarios can be found here.

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

March 29, 2009

Visual Studio 2010 Architecture Edition

Today I’d like to share another left over from the SDX Talk I mentioned earlier: Basically some screenshots from Visual Studio 2010 Architecture Edition (VSArch from now on). Don’t expect something fancy if you already know VSArch, I just couldn’t find all that much information on the Web beyond the two screenshots on the Microsoft site.

The main new things within VSArch include the Architecture Explorer, UML Support, and the Layer Diagram.

Architecture Explorer

Note: To make the following more tangible I loaded a sample project I use regularly as test harness and took respective screenshots while I analyzed it. Click the images for a larger view…

The Architecture Explorer is about getting a better view into existing code. Whether you join a project that is under way, whether you have lost control over your code, or whether you just need to spice up your documentation. Architecture Explorer helps you by visualizing your solution artifacts and dependencies. Artifacts include the classical code artifacts (classes, interfaces, etc.), as well as whole assemblies, files, and namespaces.

Architecture Explorer lets you select those artifacts, display graphs with dependencies, and even navigate along those dependencies and in and out of detail levels.

The following screenshot shows VSArch. The docked pane on the bottom contains the Architecture Explorer that acts as “navigation and control center”. This is where you select your artifacts and visualizations. It could certainly use some improvement from a usability perspective, but it does the job anyway.

vsarch_assemblies.jpg

The screenshot shows two different visualizations of the assembly dependencies in my solution, a matrix view and a directed graph. Just to stress the fact: This was generated out of the solution, by analyzing the project dependencies.

The next screenshot shows a mixture of various artifacts, including classes, interfaces, even files, across parts of or the whole solution.

vsarch_artifacts.jpg

Depending on what filters you set, this graph could give you a high level overview of certain artifacts and their dependencies. For example you could easily spot hot spots, like the one class your whole system depends upon. Or make sure the dependencies are nicely managed via interfaces and find undue relationships. Even spot unreferenced and therefore dead graphs.

Once you go one level deeper, you may want to cluster the artifacts by some category.

vsarch_relationship.jpg

The image shows again artifacts and their dependencies, but this time grouped by the project to which they belong. It also shows what kind of relationship a line represents and lets you navigate along that dependency.

The Architecture Explorer should help getting a better understanding of your code. It helps you to detect code smells or may guide your refactoring.

UML Support

Yes, UML like in, well UML. Not extensively, but it includes activity diagram, component diagram, (logical) class diagram, sequence diagram, and use case diagram. I didn’t spend much time investigating them, just drew some diagrams in order to take the screen shots. Generally I can say that Microsoft can draw boxes and lines (big surprise here) but there is a lingering feeling that those diagram editors may not be finished yet (again, hardly surprising on a CTP).

Creating a new diagram is easy enough. Just create a new project of type “Modeling Project” and add an item:

vsarch_dialog.jpg

Everything starts with a use case, so here is our use case diagram:

vsarch_usecase.jpg

One can draw the diagram as he likes. As you can see from the context menu, there is something being worked on. Namely the “Link to Artifacts” entry shows the Architecture Explorer, yet I couldn’t quite figure out what’s behind this. Also note the validate entries which didn’t do very much, but we’ll see them later in the Layer Diagram.

Next on the list is activity diagrams:

vsarch_activity.jpg

Works as expected, no surprises, no hidden gems that I’ve found.

The same is true for the component diagram:

vsarch_component.jpg

Just a diagram, no surprises.

The logical class diagram gets more interesting:

vsarch_logicalclass.jpg

As you can see, it contains very .NETy stuff like enumerations. It also has these menu entries that hint on more to come in the future — right now the selected menu entry brings up the error message asking for a stereotype, yet I didn’t even find a way to set those. Also the editor may still need some work, e.g. one cannot drag classes in and out of packages.

As a side note: The relation between this logical class diagram and the already existing class diagram escapes me. At least they are a little redundant.

Next on the list is the sequence diagram. Rather than drawing one myself I reverse engineered the existing code:

vsarch_sequence.jpg

Quite nice and again, used this way it can help you documenting or just plain understanding existing code.

Note: If you want to try that yourself, the CTP has a bug: You need to have a modeling project and at least one diagram before the menu entry “Generate Sequence Diagram” appears. And while you will be presented with a dialog asking what call depth to analyze, it usually works only for one level.

Layer Diagram.

Now for the most dreadfully looking diagram (though Microsoft has a more colorful one on its site…): Some boring connected blocks, meant to represent the layers of your architecture.

vsarch_layer.jpg

Actually this is one of the most interesting features for any architect and dev lead: It’s a living beast! :evil:  

You can add assemblies as well as other artifacts to the bleak boxes. Afterwards you can actually validate whether the dependencies between those artifacts match or violate the dependencies implied by the diagram. In the screenshot you can see that I deliberately misplaced an assembly and consequently got a respective error. Using this feature an architect can ensure that all layer related architectural decisions are honored during development.

To conclude…

The Architecture Explorer is certainly a worthwhile feature and I also like the validation feature of the Layer Diagram. That’s certainly something new and not to be found in other products.

Generating sequence diagrams is nice but it remains to be seen whether this will allow roundtrip engineering. The logical class diagram doesn’t yet meet my expectations and it’s not quite clear to me how it will evolve. The other diagrams? Well, they just work. However in this group is nothing exciting for you if you already have another modeling tool like Enterprise Architect (no advertising intended, just happens to be the one I’ve used recently…). And a dedicated tool probably will provide a more complete UML coverage. UML 2.0 has 13 types of diagrams, including state diagrams, which is in my opinion the biggest gap in VSArch UML support.

Anyway, if that caught your attention and your interested in more details there are two options: One, download the CTP and try for yourself. Two, if you want it more condensed and avoid the hassle with a VPC, watch a video with VSArch at work. For that there are two links I can provide:

  1. Peter Provost’s talk at the PDC. Go to the timeline on the PDC site, search for TL15 and you should find “TL15 Architecture without Big Design Up Front”, which is about VSArch, despite the title. His talk was the role model for my analysis of VSArch, yet seeing it live could still give better insights.
  2. Visual Studio Team System 2010 Week on Channel 9 has a bunch of videos, especially the “Architecture Day” ones. “top down” and “bottom up” show VSArch at work.

The final question however will be if all those features are compelling enough to actually buy the … Visual Studio Team Suite (i.e. the “you get everything” package). Why not the Architecture Edition? Well, if you are a developer as well as an architect, the Architecture Edition lacks too much in the other areas. Given that there is usually quite a monetary gap between dev edition and team suite, that gap might very well be used to buy a 3rd party UML tool instead… .

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

Older Posts »

Blog at WordPress.com.