Comments Off

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

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

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

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

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


Two Weeks a Windows Phone User

So I decided to make the switch from iPhone to Windows Phone a couple weeks ago, and thought I would share my experiences after two weeks on the platform. Thanks to Nick Landry (@ActiveNick) for giving me the final nudge I needed to make the switch.

This is actually my third try making the switch, but it is going much better than the first two. The very first was when Windows Phone first came out. Back then the platform was pretty raw and there simply were not enough apps. Second try was in the Windows Phone 7.5 days… again, still not enough of the right apps in comparison to iOS at the time even though the platform had matured a lot. This time, overall, I am extremely happy with the platform as a whole and with the apps available. In fact, I would say that a lot of the same apps that I use on my iPhone have a better overall user experience on Windows Phone than on iPhone.

Overall impressions of Windows Phone in general:

  • User experience of the platform (operating system) and apps following the platform design guidelines is way better than iOS. The fluidity of moving from app to app and navigating around within apps and phone level settings and features is awesome. Feels much more modern and well thought out than iOS.
  • Built in apps are great (People hub, news, music, video, photos)
  • Most importantly, every major app I used on the iPhone is available on Windows Phone and most are feature complete in comparison. Some lack minor features and that gets a little annoying (ex: Amazon Kindle allows you to change font size and color on Windows Phone, but lacks the ability to change the font to a different one – i.e. sans serif – whereas the iOS one does allow that), but that is not Microsoft’s fault, just need to put pressure on the app vendors to get feature parity. But all the major apps I use regularly (Pandora, Kindle, WeatherBug, Netflix, Vevo, TripIt, Twitter, Facebook, United, …) are all there and work great.
  • There are also a lot of really great apps just for Windows Phone that I did not use or do not exist on iOS. MetroMail, Nokia apps (Camera, MixRadio, HERE Drive, HERE Maps)
  • Initially my biggest point of frustration as a Gmail user was email, but then I discovered MetroMail (thanks Khaled @ImmortalFeb) and my Gmail life is now complete again on Windows Phone with full labeling and archiving capabilities.

In terms of what hardware I have, I started out with a Lumia 635 because I am an AT&T user and that was the best handset they had that was similar form factor to my iPhone 5s. The overall user experience with that phone was really good, but the stats on it are fairly low end and I was wanting to try a phablet with some more horsepower and screen real estate, so I traded it in for a Lumia 1520 after the first few days.

  • Overall impressions of the Lumia 1520:
    Fantastic performance
  • Great screen, having the extra real estate is wonderful for most things I do on the phone while stationary
  • Excellent camera
  • Long battery life
  • A little hard to use single handed. My hands are not large. My ability to hold in my right hand and navigate with just my thumb is severely diminished, particularly on the go.
  • One big negative: button placement. This is a BIG phone. That means you have to grip it a bit more explicitly than you would a smaller phone to control it. Where do you grip a phone? On the middle to lower sides of it. Where did they put the lock button and camera button? On the middle and lower side of it on the right side. Stupid, stupid positioning in my opinion. Biggest thing I dislike about the phone so far. Constantly accidentally lock the screen when I am reading something or turning on the camera app. The top and bottom have no buttons at all, why could they have not put the lock button on the top where it would have been out of the way and maybe put the camera button upper left?

So overall, I’m very happy with Windows Phone and will probably stick with it this time. I’m keeping my iPhone around for now on another line for development purposes, but find myself missing it very little. The only iOS features I do miss at times are:

  • iMessage – I have a MacBook Pro and iPad and loved the integrated texting across all my devices. But many friends are not on iOS, so could never do that with them anyway.
  • Find my iPhone – my wife and I use this to coordinate our location sometimes without needing to call and describe where we are at. Wish I could find something similar that worked across platforms (wife is not switching for now)
  • Thumbprint password on iPhone 5s. Very handy when mobile to just touch and hold to get past the lock screen.

Bottom line, if you are not already a dedicated iOS or Android user, you will love Windows Phone. Even if you are, you will probably love Windows Phone after getting past the fact that things are a bit different and you have to learn some new patterns of use. The Nokia Lumias are fantastic phones from a hardware perspective and have great apps that accompany them, so they are the perfect fit for the Windows Phone arena.