Comments Off on Using MVVM in a Reusable UserControl

Using MVVM in a Reusable UserControl

In my Pluralsight Course WPF MVVM In Depth I cover all the fundamentals of the MVVM pattern and show how to handle a wide range of scenarios, including hierarchical MVVM – when you have a nested hierarchy of View/ViewModel pairs containing child Views/ViewModels to form a composite view for the user. In those cases, there is usually explicit knowledge in the parent ViewModel of the child ViewModel(s) so that the parent VM can have a supervisory relationship with its children. I cover that setup in my course and show how the child Views can be rendered based on child ViewModels exposed as properties on the parent ViewModel and the use of DataTemplates.

But one scenario that I did not get into in the course that I want to cover here as supplementary material is when you want to use MVVM inside of a UserControl but the ViewModel should be an implementation detail of the control that is hidden from the user of the control (as in programmer user, not end user – the end user shouldn’t have any idea how the code is constructed of course). You just want to be able to reuse that user control in a number of places in your app, you want to expose some properties on the control to drive its functionality, and you want the code “inside” that control to be well factored, easier to maintain, and possibly unit testable.

If you are trying to encapsulate some layout and presentation of controls and functionality in WPF for small scale reuse instead of large scale general purpose reuse (as in “I’m going to need this in a number of places in this app”, as opposed to “I am writing a control for a component library that will be used in all kinds of scenarios outside my development organization”), a UserControl is a great way to go. Of course if you are trying to address the wide scale general purpose reuse, you should probably consider implementing a true custom control – a class with an associated ControlTemplate that derives directly or indirectly from Control. Doing a true custom control opens the door for the user of that control to provide their own control template, or derive their own control class from yours, two things you can’t do with UserControls.

Justifying Using MVVM Inside the User Control

When doing MVVM in WPF, most views are UserControls, and they have a ViewModel class associated with them. Those are typically just “chunks of screen” – a decomposition of the overall screen full of presentation you want to show the user. But if you want to be able to reuse that chunk of screen in a number of places and be able to pass data into it and possibly get data, events, or commands out of it as a reusable chunk, then you want to think in terms of implementing your view as a UserControl first, and having MVVM just be an implementation choice for how you built that thing.

Doing this requires a good understanding of how data binding and DataContexts work, because if you are going to use that UserControl inside of other MVVM views, the way you are going to feed data, events, and commands in and out of the control is going to be through data binding, probably to properties exposed from the ViewModel of the containing view. But then the DataContext of the UserControl content needs to be its ViewModel to follow the MVVM panel internally. But you don’t want those two different DataContexts to conflict when setting and getting properties on the control through data binding.

To illustrate how I would go about this, I’m going to implement a scenario where I want a control that can show icons that each represent something that a user can click on to take some action in the app. Maybe the action will be to navigate to a detail view for that thing in one view, maybe it will be to show a popup to the user in another view, maybe it will be to let them re-order or delete an item in a data collection in another view. But I want the presentation of those collections of icons in my app to be consistent and I’d like the implementation to be reusable. And I need the containing view to be able to supply the data that causes the icons to be presented and the actions (commands) to be taken when an icon is clicked on.

Now with those requirements as stated I could just satisfy them without necessarily wanting or needing to implement MVVM inside of the control – the UserControl would not necessarily need a ViewModel. But if there is also some interactions that are going to be common across all the presentations of the icon view, there might be cause to put a ViewModel behind that UserControl and implement the data management and interaction handling for the view in the ViewModel following the MVVM pattern.

So in addition to the requirements described above, lets say there is also some functionality I always want present when I am showing one of those icon views – for my example I’ll limit that functionality to being able to sort the icons in ascending or descending order. For some real world usage, you might also have a filter input where you could only show icons that meet some filter criteria. Or maybe it switches between small and large icon views and a details table view like Windows Explorer does. So bottom line there will be some interactions that the user can do inside that UserControl that are common, and the logic that supports those interactions needs to manipulate the data that is driving the presentation of the control.

Here is what the app is going to look like at completion:


The Load button is in the containing View. The blue border is just there to make it very clear where the boundary of the UserControl is. Everything inside the blue border is implemented by the UserControl and its supporting ViewModel. The small up/down icons are controls that are part of the UserControl view itself and support commands to sort the icons ascending or descending. The rest of the icons are the data being presented by this control. You can see in the middle it is also set up so that each icon can present a tooltip that tells the user a little more about what that icon represents.

Defining the Data Model

For my example, I want to be able to provide info to my icon view about what icons to show, and want to be able to leave it to the View/ViewModel that are containing the icon view to supply the info through data binding, as well as letting that code handle when a user clicks on a given icon. I might also want to support some sort of text to go with the icons.

So I need a simple model type that will be the objects I am binding as a collection. For my example, that model type looks like this:

   1: public class IconInfo

   2: {

   3:     public string Label { get; set; }

   4:     public string ResourcePath { get; set; }

   5:     public ICommand Command { get; set; }

   6: }


Defining the UserControl Markup Structure

Depending on which order you want to work in, you can either first define the markup and structure of the UI elements of your UserControl or you could start by defining the properties the underlying ViewModel needs to support. I’m going to start with the markup and work my way down to the ViewModel.

I’ll add a new UserControl, and call it IconView. Pretty standard stuff, hopefully you don’t need a screen shot for that step. Next I’m going to choose to use a WrapPanel as the way I want to layout my icons within the view, but I know I want to drive what items are presented through data binding. Best way to do that is to use an ItemsControl and set its ItemsPanel property to the layout panel that you want as shown below. The code below also contains the StackPanel with the two sort buttons at the top.

   1: <Grid x:Name="rootGrid">

   2:     <Grid.DataContext>

   3:         <local:IconViewModel />

   4:     </Grid.DataContext>

   5:     <Grid.RowDefinitions>

   6:         <RowDefinition Height="Auto" />

   7:         <RowDefinition Height="*" />

   8:     </Grid.RowDefinitions>

   9:     <StackPanel Orientation="Horizontal">

  10:         <Button Command="{Binding AscSortCommand}"

  11:                 Width="16"

  12:                 Margin="3">

  13:             <Image Source="/MVVMUserControls;component/Images/DownArrow.png" />

  14:         </Button>

  15:         <Button Command="{Binding DescSortCommand}"

  16:                 Width="16"

  17:                 Margin="3">

  18:             <Image Source="/MVVMUserControls;component/Images/UpArrow.png" />

  19:         </Button>

  20:     </StackPanel>

  21:     <ItemsControl ItemsSource="{Binding IconInfos}"

  22:                   ItemTemplate="{StaticResource IconTemplate}"

  23:                   Grid.Row="1">

  24:         <ItemsControl.ItemsPanel>

  25:             <ItemsPanelTemplate>

  26:                 <WrapPanel />

  27:             </ItemsPanelTemplate>

  28:         </ItemsControl.ItemsPanel>

  29:     </ItemsControl>

  30: </Grid>


Note that I am setting the DataContext to the ViewModel not on the root UserControl element, but on the first child – the root grid element that contains all the markup. That is so the DataContext on the root element of the UserControl can still be whatever DataContext flowed down to it from the containing View. Otherwise, when you try to set properties on the instance of your UserControl in the containing view like shown below, the DataContext on the UserControl element will be the one that was set by its own implementation, rather than the one of the containing view.

   1: <Window x:Class="MVVMUserControls.MainWindow"...>

   2:     <Window.DataContext>

   3:         <local:MainWindowViewModel />

   4:     </Window.DataContext>

   5:     <Grid>

   6:         ...

   7:         <local:IconView IconInfos="{Binding SourceIconInfos}"

   8:                         IconWidth="32"

   9:                         IconMargin="3"

  10:                         Grid.Row="1"

  11:                         Margin="10"

  12:                          />

  13:         ...

  14:     </Grid>

  15: </Window>


If the IconViewModel is set as the DataContext on the root UserControl element in IconView’s markup, you end up with this error:

System.Windows.Data Error: 40 : BindingExpression path error: ‘SourceIconInfos’ property not found on ‘object’ ”IconViewModel’ (HashCode=48519443)’. BindingExpression:Path=SourceIconInfos; DataItem=’IconViewModel’ (HashCode=48519443); target element is ‘IconView’ (Name=”); target property is ‘IconInfos’ (type ‘ObservableCollection`1’)

Instead of looking for SourceIconInfos on the MainWindowViewModel (the containing View is MainWindow), it ends up looking for it on IconViewModel because that is the current DataContext for that element after construction because it gets set by the UserControl during the parsing process. But by setting the DataContext to the IconViewModel on the root Grid element inside the UserControl, it fixes that problem.

Binding to Properties Exposed By The UserControl

You might want to have some properties exposed by the UserControl that can be set in its use, such as the IconWidth and IconMargin properties you can see in the previous snippet. To use the values of those in the XAML of the UserControl, you will need to use a RelativeBinding to get to them on the root element.

The presentation of each icon in my sample is driven by a DataTemplate in the UserControl markup (you could potentially even expose another property for setting by the User for IconTemplate or something like that). That template looks like this.


   1: <DataTemplate x:Key="IconTemplate">

   2:     <Button Command="{Binding Command}"

   3:             CommandParameter="{Binding Label}"

   4:             Width="{Binding RelativeSource={RelativeSource AncestorType=local:IconView}, 

   5:                     Path=IconWidth}"

   6:             Margin="{Binding RelativeSource={RelativeSource AncestorType=local:IconView}, 

   7:                     Path=IconMargin}">

   8:         <Button.ToolTip>

   9:             <TextBlock Text="{Binding Label}" />

  10:         </Button.ToolTip>

  11:         <Image Source="{Binding ResourcePath}" />

  12:     </Button>

  13: </DataTemplate>


If you remember from the markup of the UserControl structure itself, we have an ItemsControl that is bound to its ViewModel’s IconInfos collection. In the template above that renders each item, you can see that the button command, tooltip, and image source are just bound to the properties of the current IconInfo that the template is being rendered out for. But to get to those properties that were exposed by the control itself for setting by the user, you need to use a RelativeSource binding to “escape” the current DataContext and get to the properties that are defined on the control instance itself.

Defining Custom Bindable Properties on the UserControl

To define those properties (IconInfos at the UserControl level, IconWidth, and IconMargin), you should define DependencyProperties in the code behind of the UserControl.

   1: public partial class IconView : UserControl

   2: {

   3:     IconViewModel _vm;

   4:     public IconView()

   5:     {

   6:         InitializeComponent();

   7:         _vm = (IconViewModel)rootGrid.DataContext;

   8:     }


  10:     public ObservableCollection<IconInfo> IconInfos

  11:     {

  12:         get { return (ObservableCollection<IconInfo>)GetValue(IconInfosProperty); }

  13:         set { SetValue(IconInfosProperty, value); }

  14:     }


  16:     public static readonly DependencyProperty IconInfosProperty =

  17:         DependencyProperty.Register("IconInfos", typeof(ObservableCollection<IconInfo>), 

  18:             typeof(IconView), new PropertyMetadata(null, OnIconInfosSet));


  20:     private static void OnIconInfosSet(DependencyObject d, 

  21:         DependencyPropertyChangedEventArgs e)

  22:     {

  23:         ((IconView)d)._vm.IconInfos = e.NewValue as ObservableCollection<IconInfo>;

  24:     }


  26:     public double IconWidth

  27:     {

  28:         get { return (double)GetValue(IconWidthProperty); }

  29:         set { SetValue(IconWidthProperty, value); }

  30:     }


  32:     public static readonly DependencyProperty IconWidthProperty =

  33:         DependencyProperty.Register("IconWidth", typeof(double), 

  34:             typeof(IconView), new PropertyMetadata(-1.0));


  36:     public Thickness IconMargin

  37:     {

  38:         get { return (Thickness)GetValue(IconMarginProperty); }

  39:         set { SetValue(IconMarginProperty, value); }

  40:     }


  42:     public static readonly DependencyProperty IconMarginProperty =

  43:         DependencyProperty.Register("IconMargin", typeof(Thickness), 

  44:             typeof(IconView), new PropertyMetadata(new Thickness(0)));


  46: }


Note that I have a PropertyChanged handler for the IconInfos property so I can push the value set on the control down into the ViewModel for it to manage and interact with that data. The other two properties (IconWidth and IconMargin) are just consumed by the bindings in the markup.

Finally, the implementation of the ViewModel is straightforward for this simple example:

   1: internal class IconViewModel : BindableBase

   2: {

   3:     private ObservableCollection<IconInfo> _IconInfos;


   5:     public IconViewModel()

   6:     {

   7:         AscSortCommand = new RelayCommand(OnSortAsc);

   8:         DescSortCommand = new RelayCommand(OnSortDesc);

   9:     }


  11:     public RelayCommand AscSortCommand { get; set; }

  12:     public RelayCommand DescSortCommand { get; set; }


  14:     public ObservableCollection<IconInfo> IconInfos

  15:     {

  16:         get { return _IconInfos; }

  17:         set { SetProperty(ref _IconInfos, value); }

  18:     }


  20:     private void OnSortAsc()

  21:     {

  22:         if (IconInfos != null)

  23:             IconInfos = new ObservableCollection<IconInfo>(

  24:                 IconInfos.OrderBy(i => i.Label));

  25:     }

  26:     private void OnSortDesc()

  27:     {

  28:         if (IconInfos != null)

  29:             IconInfos = new ObservableCollection<IconInfo>(

  30:                 IconInfos.OrderByDescending(i=>i.Label));

  31:     }

  32: }


Hope that makes it clear how you can manage having the implementation of a UserControl use MVVM itself, but still act like a fully encapsulated reusable control that exposes bindable properties that can be set in the containing view.

You can find the full source code for the sample here.

Prism.Windows for Windows 10 UWP Initial Port complete

So I finally sliced off some time this 4th of July weekend to do the initial migration of Prism for Windows Runtime to Prism 6 for UWP. Most things came over without any difficulty. If you are not familiar with the core functionality that Prism for Windows Runtime provided, here it is in a nutshell:

  • MVVM support  through an Application base class, Page base c;lass, and ViewModel base class that let you implement the MVVM pattern while still letting your UI logic (that should mostly live in your ViewModels and client side services) manage everything
  • ViewModelLocator for connecting views and viewmodels
    • Ties into the navigation patterns of the UWP platform, allowing your ViewModel’s to be notified when their respective pages are navigated to or from so that they can initialize and clean up the data and processing that support the view.
    • Persistence support for the Suspend-Terminate-Resume application lifecycle of UWP apps. You can simply decorate ViewModel properties with an attribute and they will be persisted and restored when your app gets suspended and then resumed from termination. Likewise there is a SessionStateService that you can inject anywhere and read and write transient data from it that you want to survive a suspend-terminate-resume cycle.

There are a few other features that I need to do a bit more work to get ready for UWP including search and settings support, secondary tiles, and the validation classes from Prism for Windows Runtime. I hope to get all that done this week.

After that, the next priority is to start trying to migrate some or all of the modularity and region functionality of Prism for WPF into Prism for UWP.

So check it out and let us know what you think, any problems you have, or features you would like to see added there:

Comments Off on Building Windows 10 UWP Apps talk

Building Windows 10 UWP Apps talk

Tuesday night I gave a talk at our user group on Windows 10 UWP development. Had a good crowd and a lot of good questions.

Wanted to share my slide deck here in case anyone wants it for reference. Slides

Demos were mostly from the platform SDK samples found here:

And my one converted 8.1 app I showed you can grab here.


WPF: Using PasswordBox in MVVM

One question that often pops up as people start digging into using the MVVM pattern is: “How do I use PasswordBox with MVVM?”

The basis for this question is usually that they tried, but quickly discovered that the Password property on PasswordBox is not a DependencyProperty, therefore it cannot be the target of a Binding, and therefore there is no straightforward way of reading and writing the value through a binding to a property in your ViewModel.

So the first thing you have to ask yourself before you pursue an MVVM-compatible solution is: Am I using PasswordBox just to get the password hiding behavior that is built in from a user experience perspective, or am I using it because I want the password encrypted in memory that the PasswordBox gives me?

If you are not sure why encrypting the value of your password entry in memory is important, I won’t go into the background of what kinds of exploits exist there in detail. The short answer is that if someone (or some code – as in a virus or worm) gets access to your program memory, they could steal your password and impersonate you to that program or system at some point. The chances of that are fairly remote, but bottom line if you want your program to be as secure as possible, it is a fairly easy attack vector to protect against. Let the PasswordBox does what it does, and don’t do something in your code that sits behind it that causes the password to be exposed in memory for long periods of time.

That means even if you could data bind the PasswordBox value into a string property on your ViewModel or Model, you shouldn’t. Because you would be leaving the value just as exposed in memory in your ViewModel property’s backing field as if the PasswordBox did not store it encrypted itself.

So what can you do in the context of MVVM? As long as you are just grabbing a reference to the SecureString that the PasswordBox stores the value in and holding on to that in your ViewModel or Model property, you are still protected. Then the only challenge in terms of MVVM is that there is no straightforward way to do that with a Binding and the properties exposed by the control.

Now you could wire up everything I am going to show here as code behind in the view that has the PasswordBox since this shouldn’t be something you will be doing all over the place in your app. But my intent here is to show you how you can follow the same patterns you do for other fields you are binding in your MVVM screens.

I’m going to show it using a Behavior – a chunk of reusable code that you can wire up easily in XAML. If you want more background on behaviors, check out my Pluralsight course Extending XAML Applications with Behaviors – A behavior is a great way to encapsulate code that bridges between an API on a control that is not conducive to data binding, and exposing that information from the behavior in a way that is conducive to data binding.

So the idea is to create a behavior that listens to the PasswordChanged event that PasswordBox will raise as the user types characters into the PasswordBox and use that to set some property on our ViewModel. To make the behavior reusable, we don’t want to couple it to the ViewModel type at all. So what we can do is expose a DependencyProperty on the behavior itself that can be bound to a property on your ViewModel. Then, when the event fires, we go set the property that the binding points to using the value of the SecurePassword property of the control, which is a reference to the SecureString being managed by the PasswordBox.

Here is what that behavior looks like in code:

   1: public class PasswordBoxBindingBehavior : Behavior<PasswordBox>

   2: {

   3:     protected override void OnAttached()

   4:     {

   5:         AssociatedObject.PasswordChanged += OnPasswordBoxValueChanged;

   6:     }


   8:     public SecureString Password

   9:     {

  10:         get { return (SecureString)GetValue(PasswordProperty); }

  11:         set { SetValue(PasswordProperty, value); }

  12:     }


  14:     public static readonly DependencyProperty PasswordProperty =

  15:         DependencyProperty.Register("Password", typeof(SecureString), 

  16:            typeof(PasswordBoxBindingBehavior), new PropertyMetadata(null));



  19:     private void OnPasswordBoxValueChanged(object sender, RoutedEventArgs e)

  20:     {

  21:         var binding = BindingOperations.GetBindingExpression(this, PasswordProperty);

  22:         if (binding != null)

  23:         {

  24:             PropertyInfo property = binding.DataItem.GetType()

  25:                 .GetProperty(binding.ParentBinding.Path.Path);

  26:             if (property != null)

  27:                 property.SetValue(binding.DataItem, AssociatedObject.SecurePassword, null);

  28:         }

  29:     }


  31: }


You can see that in the OnAttached override, I hook the PasswordChanged event. I also expose a DependencyProperty of type SecureString named Password. Then, the only trick is how to set the underlying property of a Binding that is set on the Password property. We can’t simply set Password from inside the Behavior because that ends up replacing the current value, which is the reference to the Binding, with the new value, thus breaking the link to the underlying property the binding points to. So you have to obtain the binding expression for the property, and use that to go set the underlying property through the binding. You can see the (somewhat obscure) code in the behavior that does that for us.

Once you have that Behavior created, hooking it and the binding up to the PasswordBox is as simple as this:

   1: <PasswordBox Grid.Row="1"

   2:                 Grid.Column="1">

   3:     <i:Interaction.Behaviors>

   4:         <local:PasswordBoxBindingBehavior Password="{Binding Password}"/>

   5:     </i:Interaction.Behaviors>

   6: </PasswordBox>


You will have to add an xmlns namespace for Blend SDK to bring in the Interaction.Behaviors attached property. Easiest way to do that is to build the project, go open the solution in Blend, and drag and drop the behavior from the Behaviors collection in the Assets panel onto the PasswordBox in the designer or the Objects and Timeline panel. I show how to do that in my course. You can see then it is just a matter of Binding the Password property on the behavior to the appropriate SecureString property on the ViewModel and let the behavior take care of transferring the value of the SecureString to the ViewModel property whenever it changes.

Because SecureString is a reference type, you could just set it once but doing so on each change ensures that if the binding hookup happens after the behavior is attached it will still work.

At some point you will have to pull the value out of the SecureString to pass it off to a Login API or validate it. To do that you write code that looks like the following:

   1: public class AuthenticationService : IAuthenticationService

   2: {

   3:     public bool Login(string username, SecureString password)

   4:     {

   5:         IntPtr passwordBSTR = default(IntPtr);

   6:         string insecurePassword = "";

   7:         try

   8:         {

   9:             passwordBSTR = Marshal.SecureStringToBSTR(password);

  10:             insecurePassword = Marshal.PtrToStringBSTR(passwordBSTR);

  11:         }

  12:         catch

  13:         {

  14:             insecurePassword = "";

  15:         }

  16:         return MockServiceProxyCall(username, insecurePassword);

  17:     }


  19:     private bool MockServiceProxyCall(string username, string password)

  20:     {

  21:         if (username == "Brian" && password == "password") return true;

  22:         else return false;

  23:     }

  24: }


The key thing is to leave it in the SecureString as long as possible while the value is at rest in a member variable or field on an object. Only pull out the value into an insecure string as briefly as possible and only in a stack variable (local variable in a method) so that it only lives in an unprotected state in memory on the stack as long as that stack frame (method) is executing.

So that is it, a somewhat straightforward, reusable way to bind WPF PasswordBox controls to properties on an MVVM ViewModel that still keeps the password value protected until you are really ready to use it.

You can download the full sample using this behavior here.

HelloWorld Prism for Windows Runtime 2.0

I put together a short video to supplement my Pluralsight course Building Windows Store Business Apps with Prism because a new release of Prism for Windows Runtime has come out since I created the course and there are some minor differences in where the different classes live within the assemblies and some of the MvvmAppBase virtual method signatures.

You can download or view that video here.

The video walks through creating a HelloWorld app with Prism for Windows Runtime 2.0, including setting up your application class, your first view and view model, using the ViewModelLocator to tie them together, and then adding the Unity container and overriding the default view model factory for the ViewModelLocator.


Comments Off on DevIntersection Slides and Demos

DevIntersection Slides and Demos

Had a great week last week speaking at DevIntersection. Really fun conference that you ought to check out if you have not already.

For those that attended… thanks! For them and anyone else who wants to check out my slides and demos from my sessions, here you go:

Building Azure Mobile Services with ASP.NET Web API Slides Demos
Building Rich Data Web APIs with ASP.NET OData Slides Demos
WPF Data Binding in Depth Slides Demos
Comments Off on Be-Aware of differences in explicit and implicit deserialization with DCS

Be-Aware of differences in explicit and implicit deserialization with DCS

DataContractSerializer (DCS) is the class that is used by WCF to serialize and deserialize messages when you make service calls. It is also sometimes used on its own to read and write objects to a stream, such as inside the WinRT SuspensionManager class. It works great and is very powerful, even being able to handle circular references inside the object graph that you are serializing (such as a parent object having a collection of child objects inside a collection property, and each of the child objects having a parent object reference through a navigation property). The DCS supports several kinds of serialization: based on Serializable/ISerializable, explicit data contract (using [DataContract] and [DataMember] attributes), and implicit data contracts (public type with public properties).

Depending on your point of view and usage, sometimes it is better to use explicit data contracts and sometimes it is better/easier to use implicit data contracts. However, there is a subtle gotcha that you should be aware of in terms of the construction process of the objects when deserializing an implicit vs an explicit data contract.

When an object with implicit data contract on it (public type and public properties involved in the serialization/deserialization) is deserialized, everything happens as you would expect – a new object instance is created, the constructor is called, and it can do any initialization of members that it wants to.

When an object with explicit data contracts on it ([DataContract] on the type, [DataMember] on the properties involved in serialization/deserialization) is deserialized, the constructor does not get called. As a result, any initialization that the constructor normally does (such as initializing private member variables that do not participate in the deserialization) will not be done on deserialization. If you need to do some initialization on deserialization, you can use OnDeserializing/OnDeserialized hooks. That means if you have some common initialization that you want called both when explicitly constructed (new’ed up) and when deserialized, you need to factor that initialization into a helper method and call that from both places to avoid duplication of code.

To see this in action, consider the following two entity types:

   1: public class ImplicitContractEntity

   2: {

   3:     private string _someRefMember;

   4:     private string _someOtherRefMember = "Initialized";

   5:     public ImplicitContractEntity()

   6:     {

   7:         Console.WriteLine("Constructor of ImplicitContractEntity called");

   8:         _someRefMember = "InitializedName";

   9:     }


  11:     public int Id { get; set; }

  12:     public string Name { get; set; }


  14:     public string GetPrivateRefMember()

  15:     {

  16:         return _someRefMember;

  17:     }


  19:     public string GetPrivateOtherRefMember()

  20:     {

  21:         return _someOtherRefMember;

  22:     }


  24: }


  26: [DataContract]

  27: public class ExplicitContractEntity

  28: {

  29:     private string _someRefMember;

  30:     private string _someOtherRefMember = "Initialized";

  31:     public ExplicitContractEntity()

  32:     {

  33:         Console.WriteLine("Constructor of ExplicitContractEntity called");

  34:         _someRefMember = "InitializedName";

  35:     }

  36:     [DataMember]

  37:     public int Id { get; set; }

  38:     [DataMember]

  39:     public string Name { get; set; }


  41:     public string GetPrivateRefMember()

  42:     {

  43:         return _someRefMember;

  44:     }


  46:     public string GetPrivateOtherRefMember()

  47:     {

  48:         return _someOtherRefMember;

  49:     }

  50: }

You can see that the first is an implicit data contract (no DataContract or DataMember, all public properties will be serialized) and the second has explicit data contracts. You can also see that they have exactly the same structure including:

– Inline initialization of one private member variable
– Constructor initialization of another private member variable
– Console output when constructor is called
– Accessor functions for the private member variables

Now lets look at some code that serializes and deserializes these types with DCS:

   1: static void Main(string[] args)

   2: {

   3:     Console.WriteLine("Constructing initial entities");

   4:     ExplicitContractEntity expEntity = new ExplicitContractEntity { Id = 42, Name = "Fred" };

   5:     ImplicitContractEntity impEntity = new ImplicitContractEntity { Id = 43, Name = "Wilma" };

   6:     DataContractSerializer expSerializer = new DataContractSerializer(expEntity.GetType());

   7:     DataContractSerializer impSerializer = new DataContractSerializer(impEntity.GetType());

   8:     Console.WriteLine();

   9:     using (MemoryStream expStream = new MemoryStream())

  10:     {

  11:         expSerializer.WriteObject(expStream, expEntity);

  12:         expStream.Position = 0;

  13:         Console.WriteLine("Deserializing explicit contract entity.");

  14:         ExplicitContractEntity deserializedExpEntity = 

  15:             expSerializer.ReadObject(expStream) as ExplicitContractEntity;


  17:         if (deserializedExpEntity.GetPrivateRefMember() == null)

  18:             Console.WriteLine("Explicit contract private member null");

  19:         if (deserializedExpEntity.GetPrivateOtherRefMember() == null)

  20:             Console.WriteLine("Explicit contract other private member null");

  21:     }

  22:     Console.WriteLine();

  23:     using (MemoryStream impStream = new MemoryStream())

  24:     {

  25:         impSerializer.WriteObject(impStream, impEntity);

  26:         impStream.Position = 0;


  28:         Console.WriteLine("Deserializing implicit contract entity.");


  30:         ImplicitContractEntity deserializedImpEntity =

  31:             impSerializer.ReadObject(impStream) as ImplicitContractEntity;


  33:         if (deserializedImpEntity.GetPrivateRefMember() == null)

  34:             Console.WriteLine("Implicit contract private member null");

  35:         if (deserializedImpEntity.GetPrivateOtherRefMember() == null)

  36:             Console.WriteLine("Implicit contract other private member null");

  37:     }

  38:     Console.WriteLine("Hit any key to exit");

  39:     Console.ReadKey();

  40: }

As you can see it first constructs an instance of each entity type, then it serializes and deserializes each, with some console output along the way to indicate the stages and to check whether the deserialized version of the objects has null values in its private member variables (through the accessor functions).

The console output proves the difference in lifetime:


Notice that the constructor of the ExplicitContractEntity does not get called during the deserialization, but the ImplicitContractEntity constructor does, and as a result both the inline initialized variable and the one initialized in the constructor are null in the ExplicitContractEntity after deserialization whereas the ImplicitContractEntity ones are intact.

So the bottom line?

1. Be aware of the differences in construction / initialization between the two kinds of data contract

2. Be very careful about going and changing code that was using implicit data contracts to start using explicit data contracts. It is too easy to forget or to miss that things that were happening in the constructor during deserialization before are going to stop being called as soon as you switch to explicit data contracts.

If you want to learn more about the fundamentals of WCF, please check out my WCF Jumpstart course on Pluralsight.

You can download the full source code for this article here.

Comments Off on NYC Code Camp Slides and Demos

NYC Code Camp Slides and Demos

Had a great time speaking at the NYC Code Camp this weekend at the Microsoft Offices in Times Square. For those that attended or others who just want the goods, below are the slides and demos I presented there.

Build Data-Centric HTML5 Client Apps with Breeze:   Slides   Demos

AngularJS JumpStart:   Slides   Demos