Syndicate

News

My name's Marco De Sanctis and I'm an IT professional from Italy. This is my technical blog, about .NET and related application development and design technologies.

Download my Resume (.doc)

Recent Comments

7/28/2008 at 2:46 PM

Hi...What kind of problem are you experiencing?...
by Marco De Sanctis

Read more...

7/28/2008 at 12:59 PM

Very nice concept and can i expect for list box? ,...
by Sudhir Malireddy

Read more...

7/28/2008 at 9:58 AM

In aggregates the rula is: who is the rool element...
by Tommaso Caldarola

Read more...

7/22/2008 at 7:49 PM

Been there too in a past project! I remember this ...
by Mathias

Read more...

7/14/2008 at 11:50 PM

Sure I am... but if you got batches that last for ...
by Marco De Sanctis

Read more...

Recent Posts

Crunch mode is a pure waste of time, energy and money

7/31/2008 at 5:41 PM

Read more...

Double Click on the .sln file doesn't open Visual Studio on Vista

7/27/2008 at 9:02 AM

Read more...

Domain Model & Aggregates: when do master-detail associations happen?

7/22/2008 at 4:08 PM

Read more...

How I Got Started in Software Development

7/14/2008 at 12:16 AM

Read more...

Unleash the power of VisualStateManager with custom states

6/30/2008 at 12:12 AM

Read more...

May 2008 Entries

I was going to reply to a feedback to my last post, but from how much I was writing I realized it could deserve a post on its own.

When we decide to adopt the Domain Model pattern to represent data, we're going to deal with complex object graphs: it means that instead of SomeRelatedEntityId properties, we will have concrete references to related entities, a property of SomeRelatedEntity type in this case

Obviously, when you start a business transaction and you know from the beginning that the property X will be accessed, it could be (not always, read below!) a wise choice to eager fetch it to avoid too many DB round trips. However, I consider LazyLoad very useful in at least two practical cases:

  • n-level Master-Details: for example, a form with a header to edit the master entity, a grid below for its details and a button for each row which opens an AJAX modal popup to edit the detail's details. Without LazyLoad you should execute a huge query on the beginning (or many smaller ones) to fetch everything, and perhaps the user only wants to modify a Master's field. Oh... and what if the 2nd level details have many-to-one associations towards other entities? How big should our join be?
  • There are good chances that the related entity is still in the identity map: let's think about a list of entities with many-to-one association towards the same entity, for example a list of bills of the same customer. Without lazy load, you would fetch the same data many times, with lazy load and identity map, you will have no joins, only one query towards the Customers table, then the same entity will be used for every Bill.

As my Italian friends probably know, I'm a huge NHibernate fan, as I decided to permanently adopt it in many desktop and web apps I've built or designed during the last 2-3 years; dealing with Session life cycle management in ASP.NET apps is pretty simple if you use well known patterns like

  • Session per Request
  • more rarely, Session per Conversation

In other words, you have a session alive and kickin' for the whole business transaction your WebForm is accomplishing and, being the NHibernate Session a Unit of Work implementation, this is absolutely faithful to that pattern definition.

For some reasons, using a similar approach with Linq To Sql's DataContext is not as easy. Let's take a look.

Dealing with detached objects

Let's start saying that associations in L2S are lazy fetched by default, so you need to have a context alive while navigating the entity graph if you don't want ObjectDisposedExceptions to be raised:

image

When adopting a Session per Request pattern, you must frequently detach/reattach the entity versus the current request's DataContext; however, attaching a detached entity in Linq To Sql is not as easy as it's supposed to be, as it isn't a supported scenario. I blogged in Italian a while ago about some strange reattaching behaviors I experienced in Beta2; RTM throws an exception if you try to reattach a persistent entity with associations not yet initialized, at least that's a more consistent behavior, although it doesn't help.

image

In other words, unless you don't want to deal with workarounds, you can't use Session per Request pattern with Linq To Sql.

Moving towards Session DataContext per Conversation

That brings us to the decision of having the same DataContext alive for the whole business transaction. I'm fine with that, although the architecture becomes a bit more complicated because its life should span several postbacks. After chatting a while with my friend Alk, I realized that ASP.NET's Cache is an awesome storage mechanism for DataContexts because:

  • In a perfect world, every business transaction should be explicitely closed. In real world, however, users tend to close their browsers without notice. If we use sliding expiration, the ASP.NET's caching infrastructure takes care itself on getting rid of every pending DataContext that hasn't properly been disposed.
  • Cache's sliding expiration is automatically renewed on every access.
  • Cache provides a callback mechanism, so we can execute custom code when a DataContext has expired.
  • We can configure Cache to not remove DataContexts when the system is in need of memory.

Instead of directly storing the DataContext, it's a better choice to wrap it in a generic UnitOfWork instance; this allows us to inject a bit of additional (and useful) logic:

The Items property, for example, is a string/object dictionary (an idea borrowed from NHibernate.Burrow) used to store custom transaction items that need to last till the transaction ends; I've also provided a Disposing event if the user wants to execute some custom code when a UnitOfWork is closed.

A UnitOfWorkContainer singleton object keeps track of all active UnitOfWorks and provides methods to start, rollback or commit (business) transactions:

image

Thanks to that, building a new UnitOfWork and storing it in the cache repository is only a matter of calling the BeginTransaction<T> (T is the Linq to Sql context's concrete type) of the UnitOfWorkContainer singleton class:

image

That method returns an ID which can be easily stored (f.e. using Viewstate) and will be used to retrieve the current UoW during the future postbacks. Now that a UoW has been created and stored into the container, we can retrieve it very easily

image

and we can use it to interact with the underlying Linq DataContext or with the Items storage as well; for example, the Page_Load method in my example contains the following code:

image

Thanks to this code, in every postback we have a reference to the person currently edited through the entity filed, we can freely navigate its object graph with the DataContext automatically querying the underlying database if it needs to lazily initialize any property, and tracking every change we make to any entity, being it the current Person instance or any associated one. Not bad, isn't it?

After some postbacks, here it comes the end of the conversation, in which the user is asked to say "Ok" and persist the changes, or say "No" and cancel everything; this ends the business transaction and invalidates the UnitOfWork:

image

Few details on what happens behind the curtain

The UnitOfWorkContainer class acts as a repository, providing methods to manage a UoW's lifetime and retrieve it given its Id. Once the user decides to begin a new business transaction, a new UoW is created and added to ASP.NET Cache:

image

Two details to notice here:

  1. The cache item is marked as NotRemovable, so it won't be cleared in case of memory shortage; it will disappear only after a 10 minutes sliding timeout or if explicitely removed.
  2. I've subscribed a CacheItemRemovedCallback to dispose the UoW once it has been removed from the cache (and, therefore, not reachable anymore from the client code)

Obviously this is only a very simple example, something very similar to what I used to do with NHibernate. For those who are interested on it as a starting point for their own apps, source code is available here.

kick it on DotNetKicks.com

In a previous post, I showed how you can directly bind a Binary LINQ type to a WPF Image control implementing an ad-hoc type converter, not so much useful unless you don't have your images already stored on your database. What we need is something that is capable to achieve a two way binding, both displaying images and allowing users to upload their own; what about a brand new, completely skinnable, WPF custom control? So, let's create a new WPF project and add a new CustomControl called ImageUploader and take care of its logic first. As I wrote elsewhere, it's a good practice to design control's behavior (and implement it) without references to any UI element.

First of all, we need a property where to store an ImageSource object; we want it to be two-way bindable, so we are going to build a dependency property instead of a plain CLR one with appropriate FrameworkPropertyMetadataOptions:

image

Next, we need a couple of commands:

  1. a Clear command (we want the user being able to remove the current image)
  2. a Browse command to upload a new picture

If you've read some posts of mine, lately, you should perfectly know how to create custom commands and bind them to handlers smile_regular

image

The ClearImageCommand handler is pretty straightforward:

image

Same for the BrowseCommand handler, although it deserves one little note: we could obviously use the BitmapImage constructor with a URI as argument to directly reference the file; however this approach leaves the file locked for the whole BitampImage lifetime (which unfortunately ends only when GC wants to). Therefore what we do is manually handling its loading, setting the CacheOption property to load the entire image data during its init stage and caching it in a MemoryStream:

 image

Now that our control's logic is completely defined (and, again, without references to any UI element), we can move to creating a default layout on the generic.xaml file; a very simple one could be the following

image

that is not so bad if we add a bit of animation...

Anyway, doing something fancier is only a matter of Blend skills (and mine are awful).

One last note: the BinaryToImageConverter I showed you here is still one-way only. To get it work in both directions, we must implement the ConvertBack method:

image

image Here's the complete source code, obviously released under the "Works on my machine" license smile_wink

Enjoy!

kick it on DotNetKicks.com

Today I saw a post of a friend of mine about WPF lacking some of the controls we used to have in Windows Forms (who said DateTimePicker? or was it DataGrid?). Indeed, there are many Open Source project to fill the gap, like AvalonControlsLibrary or WPF Toolbelt, but beside that, Xceed has an excellent DataGrid (although not so straightforward to use) which has a free express edition that can be used even in commercial apps.

The cool thing is that the package includes a bunch of other useful controls, like a DateTimePicker, a MaskedEditTextbox, and so on, that can be obviously used on their own. Moreover, everything is well documented and with many samples.

Uh... I was almost forgetting, I'm not related in any way to Xceed Software, it's simply what I think could be a good advice.

...it doesn't necessarily mean that there's something wrong with your Xaml: it's thrown for any error during the constructor execution, even though it's caused by a C# line:

image

Technorati tags:

One of the most interesting concepts in WPF is that a control's logic is completely decoupled from its layout: a button is something that reacts when user clicks it raising a Click event, despite of how it looks like. If you think about it, it's definitely a breaking change compared to Windows Forms, and it allows designers to completely reskin UIs, while keeping the behavior intact.

When you create a new custom control, Visual Studio adds two files to your solution:

  • a C# (or VB.NET) file, which is supposed to hold all your control behavior logic
  • a Generic.xaml file, which provides a default control template for its layout.

The Generic.xaml file contains various child UI elements that need to interact with each other and with the underlying behavior logic, and this has to be done without introducing dependencies from the logic to the UI. In my experience building custom WPF control, I've been able to achieve that following three main rules:

  • Triggers (and eventually Binding between UI elements) to encapsulate layout-only logic within XAML
  • Handle data flows (both One-Way and Two-Way) from UI to control logic with Binding
  • React to UI's events using Commands

While the first two points are pretty straightforward, the third deserves a small overview. Let's suppose we're building an "File selector" custom control, similar to the following:

image

The behavior needs to be notified when the user clicks the Browse button to display the standard Windows Open File Dialog. Obviously we could assign the button a unique name

image 

and attach its click event in C# code:

image

That kind of implementation has a couple of serious drawbacks:

  • It works until there's a button named browseButton somewhere in the control template. If a designer reskins our control and doesn't provide a button with that exact name, or if he wants to use some other event, or even a different control type that doesn't inherit from button, our logic stops working correctly;
  • Our logic is so tightly bounded to the UI that we can have one and only one control triggering the opening of our open file dialog.

WPF's Commands infrastructure offer a much more elegant (and simple) solution to all those issues. A Command is the object oriented alter-ego of a functional logic, that can be enabled or disabled, triggered by an input gesture and associated to some code, regardless of what and how many UI elements are bound to it.

So, our first step is to create a proper command, stored in a static readonly field initialized into the control's static constructor. A command is a class that implements the ICommand interface; WPF has several built-in commands for the most common tasks (Cut, Copy, Past, and so on... here there's an exhaustive list). In our case, we can use the already existing RoutedCommand class:

image

Two main details to notice:

  • After building the BrowseFileCommand, you need to bind its Executed event to a proper event handler and register that binding to the CommandManager;
  • The event handler is static, but you can retrieve a reference to the current BrowseFile instance looking at the e.Source property;
  • There's absolutely no reference to any UI element in the code we've just written.

What about the general.xaml file? All we need to do is associating the BrowseFileCommand to the button object with its Command property:

image

Now, our BrowseFile behavior is well encapsulated within the C# class and its BrowseFileCommand custom command; a designer who wants to completely re-invent our control's layout only needs to attach it to the UI elements he prefers; Notice also how easy was to include a context menu with the same behavior, simply reusing the same command.

In a next post, I'll show you how to build a completly skinnable and bindable custom control from scratch.

Cheers.

kick it on DotNetKicks.com

Technorati Tags: ,,

If you need to store images at DB level, Sql Server varbinary type is what you need to hold your data, which is mapped on Linq Binary type once you import your table to a Linq project. How do you display such an image in a Image WPF control? Obviously you cannot directly bind such a data type to the Image.Source property, unless you define a proper value converter from Binary type to ImageSource type.

That said, if you want to implement one, you need to create a class that implements the IValueConverter interface. For the sake of simplicity, let's suppose that we need to support only one-way binding (Data field to Image.Source); our class might be similar to the one displayed below:

image

The logic is pretty simple: Linq's Binary type has a method which returns a byte array; what we need to do is only building a MemoryStream from it and use it to build a BitmapImage which is directly bindable to the Image.Source property.

Now, we can store our converter as a resource and use it to perform our XAML binding:

image

One last note: IValueConverter interface has a ConvertBack method too, which is needed to support two-way binding. In a next post, I'll show you how to create a two-way bindable UserControl with image upload features and we will need to implement the whole IValueConverter interface. For now, it's ok to leave it throwing a NotImplementedException.

image

Update: Here you will find the missing ConvertBack implementation

Technorati tags: , ,

Today I was preparing a demo app which integrates WPF and LinqToSql. The idea is to implement the same pattern I've always used with NHibernate: a Session DataContext per Window, automatically disposed when its owner is closed and shared among all the various UserControls it has.

So, what I did was building my custom window class with an amazing MyDatabaseDataContext property in it

   10 public class PersistentWindow : Window

   11 {

   12     private MyDatabaseDataContext myDatabaseDataContext =

   13         new MyDatabaseDataContext();

   14     public MyDatabaseDataContext MyDatabaseDataContext

   15     {

   16         get { return myDatabaseDataContext; }

   17         set { myDatabaseDataContext = value; }

   18     }

   19 }

Now, every window in my application can access the built in LINQ DataContext simply inheriting from my PersistentWindow custom class:

    1 <classes:PersistentWindow x:Class="MySampleApp.MainWindow"

    2    xmlns="http://...."

    3    xmlns:x="http://...."

    4    xmlns:classes="clr-namespace:MySampleApp.Classes"

    5    Title="Demo Application" Height="450" Width="600">

Pretty easy, isn't it? But often I do love holding a lot of logic and layout inside UserControls, both to keep my home window code simple and to build re-utilizable blocks; and almost always those UserControl need some DataBase access, that's why I need to share PersistentWindow's DataContext among all the UserControls.

If I was in Windows Forms, I probably would have ended shadowing the FindForm method with something like this:

    9 public PersistentForm FindForm()

   10 {

   11     return base.FindForm() as PersistentForm;

   12 }

But WPF has that fantastic DependencyProperty infrastructure, so maybe could be more elegant to leverage its Value Inheritance to achieve our goal. In fact, value inheritance allows property value inheritance across controls logical tree. That means that, if both your parent (window) control and your some-level child (UserControl) have the same property, the parent's property value is forwarded to every child unless they don't redefine their own value.

What we need to do is rewriting our MyDatabaseDataContext property as an AttachedProperty:

   13 public static readonly DependencyProperty MyDatabaseDataContextProperty =

   14     DependencyProperty.RegisterAttached("MyDatabaseDataContext",

   15     typeof(MyDatabaseDataContext), typeof(PersistentWindow),

   16     new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits));

   17 public static void SetMyDatabaseDataContext(

   18       UIElement instance, MyDatabaseDataContext value)

   19 {

   20     instance.SetValue(MyDatabaseDataContextProperty, value);

   21 }

   22 public static MyDatabaseDataContext GetMyDatabaseDataContext(UIElement instance)

   23 {

   24     return instance.GetValue(

   25         MyDatabaseDataContextProperty) as MyDatabaseDataContext;

   26 }

Did you notice that Inherits flag? It's what does all the magic! In fact, having a reference to window's Linq Context from our custom UserControl is simply a matter of writing a property like this:

   11 public class PersistentUserControl : UserControl

   12 {

   13     public MyDatabaseDataContext MyDatabaseDataContext

   14     {

   15         get

   16         {

   17             return this.GetValue(

   18                 PersistentWindow.MyDatabaseDataContextProperty)

   19                 as MyDatabaseDataContext;

   20         }

   21         set

   22         {

   23             this.SetValue(PersistentWindow.MyDatabaseDataContextProperty, value);

   24         }

   25     }

   26 }

Nice, isn't it?

kick it on DotNetKicks.com

Technorati tags: ,

It's 1.00 AM and, after being wondering for a couple of days about opening an English blog, I decided to install Subtext and give life to it.

Why an English blog? Well, honestly because I recently realized that I'm reading more English blogs than Italian ones, and that makes me feel as part of a .NET community that spans worldwide. I got so many visitors from abroad and I thought that the time has come for me to dive into a new challenging experience.

I'm going to talk about Software Design and Programming (which are both my everyday's bread and a great passion): some NHibernate, some WPF, some ASP.NET, some WCF and so on...! Let's see what happens!