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:

ANFSCD

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

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

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,
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

 

Blog at WordPress.com.