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 – http://www.pluralsight.com/courses/extending-xaml-applications-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:     }

   7:  

   8:     public SecureString Password

   9:     {

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

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

  12:     }

  13:  

  14:     public static readonly DependencyProperty PasswordProperty =

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

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

  17:  

  18:  

  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:     }

  30:  

  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:     }

  18:  

  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.

Enjoy!

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:     }

  10:  

  11:     public int Id { get; set; }

  12:     public string Name { get; set; }

  13:  

  14:     public string GetPrivateRefMember()

  15:     {

  16:         return _someRefMember;

  17:     }

  18:  

  19:     public string GetPrivateOtherRefMember()

  20:     {

  21:         return _someOtherRefMember;

  22:     }

  23:  

  24: }

  25:  

  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; }

  40:  

  41:     public string GetPrivateRefMember()

  42:     {

  43:         return _someRefMember;

  44:     }

  45:  

  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;

  16:  

  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;

  27:  

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

  29:  

  30:         ImplicitContractEntity deserializedImpEntity =

  31:             impSerializer.ReadObject(impStream) as ImplicitContractEntity;

  32:  

  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:

2014-09-29_10-06-02

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

Enjoy!

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.

Comments Off

Working with Breeze Lookup Queries

One capability of Breeze that is often overlooked or not fully understood is executing queries that bring back multiple collections of data. These are often referred to as lookup queries because they are a perfect fit for going to the server one time to get back a collection of lists that can be used for populating “lookup lists” – lists of objects that you will use to populate drop down lists or other selection lists in various places in the application. These are often coded lists of allowable values for an enumerated property on some object you are going to be editing, and are usually fairly invariant over time. But you could also use this capability to retrieve multiple collections of interrelated objects in a single shot if you can not achieve the same result through a normal query execution with filtering and expansion.

To execute a lookup query, the server needs to expose an API operation that return a JSON payload with a root object containing each of the collections as a named property. If you were implementing this with an ASP.NET BreezeController, the controller method would look like this:

   1: [BreezeController]

   2: public class ZzaController : ApiController

   3: {

   4:     EFContextProvider<ZzaDbContext> _ContextProvider = new EFContextProvider<ZzaDbContext>();

   5:  

   6:     [HttpGet]

   7:     public string Metadata()

   8:     {

   9:         return _ContextProvider.Metadata();

  10:     }

  11:  

  12:     [HttpGet]

  13:     public object Lookups()

  14:     {

  15:         var orderStatuses = _ContextProvider.Context.OrderStatuses.ToList();

  16:         var productOptions = _ContextProvider.Context.ProductOptions.ToList();

  17:         var productSizes = _ContextProvider.Context.ProductSizes.ToList();

  18:         return new { orderStatuses, productOptions, productSizes };

  19:     }

  20:  

  21: }

 

The resulting wire level format will be a single JSON object at the root of the payload, containing one or more named array properties that contain the lists. For the server method above, addressed as /breeze/Zza/Lookups, the response body would look roughly like this:

{ $id=1, $type=…, orderStatuses = […], productOptions […], productSizes =[…] }

The individual items in the arrays would need to be entity types that are included in the client side metadata and that express their type with additional metadata properties on the returned JSON:

{ $id=2, $type=’Zza.Data.OrderStatus, Zza.Data’, Id = 1, Name=’Ordered’ }

If using the Breeze ASP.NET Web API support to implement BreezeControllers with EntityContextProviders, to get this extra type information associated with the entities you just need to expose a DbSet property from your DbContext for each of the entity types in the collections you return, but you do not need to have a separate query method for those types exposed from your Web API Controller.

   1: public class ZzaDbContext : DbContext

   2: {

   3:     public DbSet<ProductOption> ProductOptions { get; set; }

   4:     public DbSet<ProductSize> ProductSizes { get; set; }

   5:     public DbSet<OrderStatus> OrderStatuses { get; set; }

   6: }

 

To execute the lookup query, you do it like any other query execution with Breeze, you just use the name of your server API operation in specifying the query:

   1: var em = new breeze.EntityManager('breeze/Zza');

   2: var lookupsQuery = breeze.EntityQuery.from('Lookups');

   3: em.executeQuery(lookupsQuery).then(successHandler, errorHandler);

 

The important part to understand is what you will see in the successHandler arguments vs. what will be created in the EntityManager cache. When your successHandler gets called, like for other Breeze queries, the data object that gets passed to your handler will contain a results array just like it does for any other query, but the results will have the single object returned in it. That single item in the array will be the single root object that the server side returned. And that object, as expressed by the server will have the named properties containing each of the arrays returned by the server.

What sometimes trips people up is understanding how that relates to what gets created in the cache so that you can query for those collections in the cache later. The thing to realize is that the collection names produced in the cache have nothing to do with the names of the properties for the collections in the server payload. In the example payload I showed above, I could have named the properties foo, bar, and baz instead of orderStatuses, productOptions, and productSizes. And if I did that, those would still be the names of the properties containing the arrays when received in the client executeQuery successHandler.

But if the types of those entities were OrderStatus, ProductOption, and ProductSize, the names of the resulting collections in the EntityManager cache after the query completes would still be OrderStatuses, ProductOptions, and ProductSizes respectively. So if you were going to write code to retrieve those entities from the cache later, the collection name you would want to use when creating an EntityQuery to query the local cache with executeQueryLocally would be the plural of the entity type name, not the name of the property that contained the collection in the server payload.

Here is client JavaScript that demonstrates that the name of the array property in the successHandler is different from the collection created in the EntityManager cache for the Lookups controller showed earlier, if you changed the orderStatuses local variable name in the server Lookups method to foo:

   1: var em = new breeze.EntityManager('breeze/Zza');

   2: var lookupsQuery = breeze.EntityQuery.from('Lookups');

   3: em.executeQuery(lookupsQuery).then(successHandler, errorHandler);

   4:  

   5: function successHandler(data) {

   6:     var results = data.results[0];

   7:     if (results.foo != null)

   8:         console.log("results contain foo collection");

   9:     var cacheResults = em.executeQueryLocally(breeze.EntityQuery.from("OrderStatuses"));

  10:     if (cacheResults.length > 0)

  11:         console.log("cache contains 'OrderStatuses' collection");

  12: }

 

Notice that the data.results[0] object is the root object returned by the Lookups method, and that still has a foo property for the array of OrderStatus objects. But the collection that is created in the EntityManager cache that you can query for is not based on the names of those arrays in the payload object, they are based on the type of the entities contained in the arrays – in this example OrderStatus. So the resulting EntityManager collection is OrderStatuses.

Hopefully that helps clarify the differences between what you see in the query completion results and what gets put in the cache. If you have questions, ping me on Twitter @briannoyes.

Comments Off

Reusable Async Validation in WPF with Prism 4.2

I recently wrote a post on implementing a reusable validation base class for models and view models in WPF using Prism 4.2 on the Pluralsight blog. You can find the whole article here:

http://blog.pluralsight.com/async-validation-wpf-prism