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

Comments Off

VSLive! Chicago Sessions

Had a great week presenting at VSLive! Las Vegas last week and am already looking forward to presenting again at VSLive! Chicago next. You can register for that conference with this link http://bit.ly/CHSPK22_Reg. In Chicago I’ll be presenting the following:

Full day workshop: Data-Centric Single Page Apps with Angular, Breeze, and Web API

Build Data-Centric HTML5 Single Page Applications with Breeze

Build Maintainable Windows Store Apps with MVVM and Prism

Zero to Connected with Windows Azure Mobile Services

Hope to see you there!

Comments Off

Programmatic WPF Bindings and Chaining CollectionViewSource

In my Pluralsight course WPF Data Binding in Depth, I barely covered using bindings from code behind, mainly because where bindings really shine is in XAML. But there are occasions where you need to set a binding from code behind. I got a question on my course discussion about an example I showed where I show how to chain CollectionViewSources (CVSs) to get a Master-Details presentation of parent and child collections and how you could do that from code behind. So rather than answer there, I’ll do it here where it is a little easier to show code and explanation.

First off, to chain the CVSs, you set them up as Resources like so:

<Window.Resources>

    <CollectionViewSource x:Key="customerViewSource" />

    <CollectionViewSource x:Key="customerOrdersViewSource" 

       Source="{Binding Orders, Source={StaticResource customerViewSource}}"/>

    <CollectionViewSource x:Key="customerOrdersOrderItemsViewSource" 

       Source="{Binding OrderItems, Source={StaticResource customerOrdersViewSource}}"/>

</Window.Resources>

In my course, I show how you can get all this done through simple drag and drop using the Data Sources Window. Here I will just focus on the code.

In this case, I am chaining two levels deep, from a Customers collection, to the Orders for each Customer, to the OrderItems for each Order. You can see that the key is to set the Source property of the child CVS to the parent CVS through a binding.

Then naturally there are UI elements, typically DataGrids, whose ItemsSource property gets bound to each CVS to present that level in the hierarchy:

<DataGrid x:Name="ordersDataGrid" 

ItemsSource="{Binding Source={StaticResource customerOrdersViewSource}}" ...>

 

So how would you do this from code behind? First you need to create the CVS instances:

private CollectionViewSource _customerViewSource = new CollectionViewSource();

private CollectionViewSource _customerOrdersViewSource 

  = new CollectionViewSource();

private CollectionViewSource _customerOrdersOrderItemsViewSource 

  = new CollectionViewSource();

 

Then you need to create the bindings for the child (and grandchild) CVS in code in the constructor or Loaded event:

var ordersBinding = new Binding("Orders");

ordersBinding.Source = _customerViewSource;

BindingOperations.SetBinding(_customerOrdersViewSource, 

    CollectionViewSource.SourceProperty, ordersBinding);

 

var orderItemsBinding = new Binding("OrderItems");

orderItemsBinding.Source = _customerOrdersViewSource;

BindingOperations.SetBinding(_customerOrdersOrderItemsViewSource, 

    CollectionViewSource.SourceProperty, orderItemsBinding);

 

FrameworkElement derived types have their own SetBinding method on them. For normal DependencyObjects like a CVS, you use the BindingOperations class to set a binding programmatically, passing it the object you want to set the binding on, the dependency property that will be the target on that object, and the binding you want to set it to.

Finally, since the XAML won’t have access to those CVSs (unless you expose them through a property you can bind to), you can set the bindings for the DataGrids in the code behind as well.

ordersDataGrid.SetBinding(DataGrid.ItemsSourceProperty, 

    new Binding { Source = _customerOrdersViewSource });

orderItemsDataGrid.SetBinding(DataGrid.ItemsSourceProperty, 

    new Binding { Source = _customerOrdersOrderItemsViewSource });

Then you need to set the root collection on the root CVS Source property (after loading the data from somewhere naturally).

_customerViewSource.Source = Customers;

Then you are off and running.

Again, I rarely set bindings programmatically like this. Most of the time it is better to keep your bindings in the XAML. But if you need to, there you go.

You can download a full sample here.

Comments Off

Passing Complex Query Parameters with Breeze

In my course Building Data-Centric Single Page Applications with Breeze, I cover Breeze’s ability to pass parameters when you execute a query. The basics of that are that there is a withParameters method on the EntityQuery object that lets you pass in a JavaScript object with key/value pair properties that will be turned into a query string parameter by breeze and passed along to the service. You need to make sure the resource you are querying has a corresponding method on the target controller that takes those parameters.

So lets say I executed a query on the client side like this:

var em = new breeze.EntityManager("breeze/Zza");

var queryWithParams = breeze.EntityQuery

    .from("ProductsWithSimpleParams")

    .withParameters({ name: "foo", description: "bar"});

em.executeQuery(queryWithParams, function (data) { products(data.results); });

Based on the set up of the EntityManager, I am targeting a BreezeController called ZzaController. Whatever I pass to the .from call is interpreted as the Resource that I want to query. Breeze will append that to the URL path requested, and based on the default action-based routing of Breeze, that means I will need to have a method called ProductsWithSimpleParams that responds to HTTP GET requests on my controller. Because I used the .withParameters call, passing a JavaScript object literal with properties name and description on it, Breeze will add these as query string parameters with their values on the request. When I execute the query, I get an HTTP GET request with a URL of:

GET /breeze/Zza/ProductsWithSimpleParams?name=foo&description=bar

To handle this call, I will need a method on the controller that looks like this:

[HttpGet]

public IQueryable<Product> ProductsWithSimpleParams(string name, string description)

{

    // Do something with params...

    return _ContextProvider.Context.Products;

}

A combination of the action-based routing of Breeze and the model binding system of ASP.NET Web API kicks in here and the method is selected by name based on the URL, and the parameters are matched against the query string parameters by name and case, so the call gets dispatched into this method with the parameters populated. Couldn’t be simpler.

However, what might not be so obvious is what if you need to pass more complex parameters to your queries from the client side, including complex types and/or collections of parameters.

Lets take the case of complex types as discrete parameters first. Say that on the server side, you want to take in a single complex object as a parameter:

public class ComplexParam

{

    public string name { get; set; }

    public string description { get; set; }

}

 

[HttpGet]

public IQueryable<Product> ProductsWithSingleComplexParam(ComplexParam param)

{

    // Do something with params...

    return _ContextProvider.Context.Products;

}

With model binding in ASP.NET this won’t work by default for a query method because it expects complex types to be in the HTTP body, and a GET request can’t have a body. So what can we do? Well, we know Breeze is going to put parameters in the query string anyway, so we just need to tell ASP.NET model binding where to look. If we use a [FromUri] attribute on the parameter, it will look to what it finds in the query string to try to come up with a ComplexParam object to pass in:

public IQueryable<Product> ProductsWithSingleComplexParam([FromUri] ComplexParam param)

Basically once you do that, ASP.NET will create a new ComplexParam object and try to populate any of its properties from query string parameters. So the same client side code that we were using before (other than the resource name changing to “ProductsWithSingleComplexParam”) that put name and description in the query string will now be use to populate the name and description properties of the ComplexParam object instead.

Note that there is case sensitive matching going on here, so that is why I non-conventionally defined my property names camelCase instead of the norm in .NET of PascalCased. You can work around this by using the Breeze camelCase convention to get that conversion to happen automatically on the client side, or you can use the JSON.NET convention conversion to do it on the server side. That is a separate subject, so I will just make sure my client and server are using the same casing for the samples I show here.

What if you want a signature that has multiple complex types in it, such as:

[HttpGet]

public IQueryable<Product> ProductsWithTwoComplexParams([FromUri] ComplexParam param1,

    [FromUri] ComplexParam2 param2)

{

    // Do something with params...

    return _ContextProvider.Context.Products;

}

where ComplexParam2 looks like:

public class ComplexParam2

{

    public int Age { get; set; }

    public string Comments { get; set; }

}

In this case if we change our query on the client side to this:

var queryWithTwoComplexParams = breeze.EntityQuery

    .from("ProductsWithTwoComplexParams")

    .withParameters({ name: "foo", description: "bar", age: 42, comments: "hello" });

em.executeQuery(queryWithTwoComplexParams, function (data) { products(data.results); });

Now model binding will create the two separate objects, ComplexParam and ComplexParam2 and will pull values for their properties out of the individual query string values from the client side.

What if you want to treat them as separate objects on the client side as well, to keep more of a 1:1 object model? Breeze withParameters still wants a single root JavaScript object to be passed to it, but that object can have nested objects. if our parameters on the server side are named param1 and param2 as shown above, then we just need to make sure the structure of the root object we pass matches that parameter naming:

var queryWithTwoComplexParamsAsObjects = breeze.EntityQuery

    .from("ProductsWithTwoComplexParams")

    .withParameters({ param1: { name: "foo", description: "bar" }, param2: { age: 42, comments: "hello" } });

em.executeQuery(queryWithTwoComplexParamsAsObjects, function (data) { products(data.results); });

Here I am hard coding the objects for demonstration purposes, but those param1 and param2 objects could be variables that point to an object that was originally returned from a query that brought back ComplexParam and ComplexParam2 objects.

Finally, what if you want to be able to pass a collection of objects as parameters to the server side? Well, again you are constrained by the fact that Breeze wants a single root object that you pass to withParameters, but that object can certainly contain a property that is an array of objects. To understand what to do here, we just need to drop back to the fundamentals of what is going to happen on each end of the wire. Breeze withParameters is going to take the JavaScript object you pass it and turn it into a JSON representation and put it into the query string with each root property of the JavaScript object as a separate parameter. On the server side, you need to use the [FromUri] to get that complex object representation deserialized into a server object that you can use in your service method.

So say we had a structure to the collection (array) of JavaScript complex objects that we wanted to pass like this:

var params = [{ propName: "Name", value: "foo" }, { propName: "Description", value: "bar" }];

var queryWithCollectionOfParams = breeze.EntityQuery.from("ProductsWithCollectionOfParams").withParameters({ values: params });

em.executeQuery(queryWithCollectionOfParams, function (data) { products(data.results); });

What ends up on the wire is a GET request like this:

GET /breeze/Zza/ProductsWithCollectionOfParams?values%5B0%5D%5BpropName%5D=Name&values%5B0%5D%5Bvalue%5D=foo&values%5B1%5D%5BpropName%5D=Description&values%5B1%5D%5Bvalue%5D=bar

Now that is a little hard to read with the URL encoding, so lets look at the decoded query string:

values[0][propName]=Name&values[0][value]=foo&values[1][propName]=Description&values[1][value]=bar

We can see that because we passed a root object with with a property named “values” that points to the array of JavaScript objects, Breeze broke that down and turned each array entry and each property for each entry into its own query string parameter. So what do we need to have that read back in to some strongly typed objects on the server side? First we need a model object corresponding to each entry object:

public class CollectionItem

{

    public string propName { get; set; }

    public string value { get; set; }

}

Then we need an array argument named values for our service method of those CollectionItems:

[HttpGet]

public IQueryable<Product> ProductsWithCollectionOfParams([FromUri] CollectionItem[] values)

{

    // Do something with params....

    return _ContextProvider.Context.Products;

}

Now we are good to go even with passing a collection of complex objects to the server side.

If you need to go beyond that, my first instinct is to recognize that not every service call from your JavaScript client that happens to be using Breeze MUST use Breeze for every data related call. Ultimately your BreezeController is a Web API controller with an action-based route. You can call any method in your controller (or any other controller for that matter) with simple AJAX calls through JQuery. So if you have highly complex parameter passing and return type requirements that Breeze seems to be getting in the way of accomplishing, just get it out of the way and make those calls as normal AJAX calls yourself.

Also be aware the Breeze Labs has a sample of how you can take control of POST requests to put whatever you want in the request body here: https://github.com/IdeaBlade/Breeze/tree/master/Breeze.Client/Scripts/Labs.

Hope you find this helpful for understanding some of the options in passing more than simple parameters to a query method through Breeze.

You can download the full sample here.

Comments Off

Yet Another Podcast – Breeze Roundtable

Want to get to know more about Breeze and where it fits into HTML client and Single Page Application development? This discussion that we had as a round table podcast discussion on Jesse Liberty’s Yet Another Podcast is a great place to start:

http://jesseliberty.com/2014/02/10/yet-another-podcast-120-breeze-roundtable/

Comments Off

Speaking at Microsoft Maniacs 18 March 2014

I’m going to give a talk at a new user group in Sterling Virginia on March 18: Designing RESTful Services with ASP.NET Web API. You can find all the details and sign up to attend here:

http://www.meetup.com/Microsoft-Maniacs/events/166143782/

Hope to see you there, come out and support this new group at their inaugural meeting!

Comments Off

Hello World Podcast with Shawn Wildermuth

Shawn recently started a new podcast called Hello World that is not your typical geek talk podcast. This one lets you get to know a little of the back story behind some of the authors, speakers, and trainers that you might have seen at conferences or heard talk on other podcasts.

So last week was my turn at bat.

I’ve got a pretty atypical history for a software guy in that I didn’t go right into computers from an early age. I was into surfing growing up in the San Diego area, then went off to the U.S. Naval Academy and had a successful first career as a Naval Officer and F-14 Radar Intercept Officer. So if you want to hear how the heck someone flying planes manages to switch careers to become a software architect who teaches other people deep topics on software technology, listen in!

http://wildermuth.com/hwpod/4_BrianNoyes

Comments Off

Use {x:Type} with WPF Implicit DataTemplates

I have burned myself with this little thing so many times, I’m long overdue for a simple blog post as a reminder to myself for the future.

When you use Implicit DataTemplates in WPF, you need to specify the DataType property using the {x:Type} markup extension. In Silverlight and later XAML technologies that support implicit DataTemplates this changed because there was no x:Type markup extension, you just specified the type like so.

        <DataTemplate DataType="local:ExplicitDataTemplatesViewModel">
            <local:ExplicitDataTemplatesView/>
        </DataTemplate>

But in WPF it needs to look like this:

        <DataTemplate DataType="{x:Type local:ExplicitDataTemplatesViewModel}">
            <local:ExplicitDataTemplatesView/>
        </DataTemplate>

Otherwise, the data templates won’t match up. Now that I have written this maybe I will never burn myself with this stupid little thing again….

Comments Off

Migrated dasBlog -> WordPress!

I’ve been wanting to get my blog moved over from dasBlog that I started using just over 10 years ago to WordPress for all the flexibility that WordPress offers – countless themes and plug ins, tools,etc. and now I am finally there. I want to thank the folks at hipinspire.com for the help in getting it done – they have been a fantastic resource us, both for this small little task and for getting our web site together at http://www.solliance.net.

Part of my inertia in not blogging lately has been feeling like I would just be adding more content that would have to be migrated. But mostly it has been the fact that I have been so damn busy with projects at Solliance, authoring Pluralsight courses, and speaking at conferences (always keep an eye over there ==>> for where and when).

But I am going to try to use this switch as a motivator to get into a more regular cadence of publishing more useful content here. We will see how that goes.

Comments Off

Demos from DEVIntersection

It has been a great but quick week at DEVIntersection in Las Vegas this week. The show goes on today and tomorrow, but I’m headed home after finishing my talks yesterday. I wanted to share the code from my demos with anyone who wants to check it out.

I gave four sessions this week:

Building Windows Store Business Applications with Prism – This one covered the capabilities of Prism for Windows Runtime for structuring your application with MVVM, using it to help with navigation and application state management in the suspend-terminate-resume lifecycle of Windows 8, and using the client and server side validation mechanisms of Prism. For this one I used the Quickstarts and main sample app (Reference Implementation) from Prism for Windows Runtime (AdventureWorks Shopper). The Prism team is in the process of migrating Prism for Windows Runtime from 8.0 to 8.1, so I used the latest drop containing the current 8.1 bits that you can find here:

http://prismwindowsruntime.codeplex.com/

Building Rich Data HTML Client Apps with Breeze – This talk covered the fundamentals of Breeze.js for implementing the CRUD data access via services needed from HTML/Javascript (possibly Single Page) applications.  I covered a little bit about the SPA architecture in general, and spent most of the time walking through a demo that showed how to use Breeze to issue rich LINQ-like queries from the client side that get executed on the server side, editing the data on the client side and getting change tracking and caching, and saving the changes to the back end. I also showed how to leverage the built in validation of Breeze and how you can work with OData services as well as Breeze Controllers. This one is a condensed version of my Pluralsight Course “Building Data-Centric Single Page Applications with Breeze”, so if you have Pluralsight access, definitely check that out for a lot more detail and demos. But here is the code for the demos I showed at DEVIntersection:

https://dl.dropboxusercontent.com/u/7366831/downloads/Conferences/DevIntersection/Noyes_AS07_BreezeDemos.zip

Designing RESTful Services with ASP.NET Web API – This talk covered the concepts behind what the REST architectural style really involves and how you can use Web API to achieve it to whatever degree you want to . I covered some of the fundamentals of exposing Web APIs with ASP.NET, then talked through the definition of REST and the architectural constraints that you have to satisfy to truly be doing REST. Unfortunately this was a short one hour session and I didn’t get to show all the demos I had planned, but here is the code so you can check them out for yourself.

https://dl.dropboxusercontent.com/u/7366831/downloads/Conferences/DevIntersection/Noyes_AS06_DesigningRESTfulServicesDemos.zip

Zero to Connected with Windows Azure Mobile Services – This talk covered the fundamentals of Mobile Services, discussed all the current capabilities of Mobile Services and when you might choose to use it (or not in some cases). I demoed how to set things up in the portal, how to call the services from a Windows 8 client, how to use identity and notifications. Based on the audience I did not demo but do have demo code for a simple iOS and HTML client using the same service. You can download that code here.

https://dl.dropboxusercontent.com/u/7366831/downloads/Conferences/DevIntersection/Noyes_AS18_MobileServicesDemos.zip