Saturday, May 18, 2013
New Pluralsight Course & Prism for Windows Runtime Released!
I pleased to announce that my new Pluralsight course Building Windows Store Business Applications with Prism is now live, right on the same day that the subject – Prism for Windows Runtime – is released. How is that for timing? You can read the official word on the release from the team PM Blaine Wastell here. I had the pleasure of working as a vendor on the Prism team (formerly known as the Kona team during development) part time. I was involved with the initial requirements definition for the project, the design of the sample applications and the reusable code libraries, and even wrote some of the code myself. So this is a topic near and dear to my heart. If I had to sum Prism for Windows Runtime up in a short statement (or run on sentence if you are an English teacher), it would be something like this: Prism for Windows Runtime provides samples, reusable code libraries, and documentation that will help Windows Store app developers write their apps so that they are well structured (most likely using the Model-View-ViewModel or MVVM UI separation pattern, but Prism does not mandate that), maintainable, testable, and leveraging the capabilities of the WinRT platform while following the style guidelines of Modern UI Style. Here is a quick rundown of what the course contains. (I’ll just refer to this release as Prism here for short, but not to be confused with Prism 4 which targets WPF and Silverlight). Module 1 – Prism Overview In this module I talk about the overall business application context that Prism is meant to address. I clarify some of the (confusing) branding and terminology around “Windows Store apps” and I go through what is “in the box” in Prism for Windows Runtime. I do an end to end walkthrough of the main sample application of Prism – AdventureWorks Shopper – to point out where all the aspects that Prism tries to provide guidance and sample and reusable code for show up in that application. Then I close out by contrasting Prism for Windows Runtime with Prism 4 in terms of their overlap and their differences. Module 2 – Getting Started Building WinRT Apps with Prism In this module I talk about MVVM and the challenges of doing it with WinRT to get started. Then I cover in concept and in demo the steps involved in setting up a Prism application starting from a Windows Store Blank App project template. After that I talk about the ViewModelLocator, which is part of the reusable code of Prism for Windows Runtime, and demo how it automates the process of getting Views and ViewModels hooked up to each other dynamically at runtime. I show how the ViewModelLocator is convention based by default, and how to override those conventions so that you can provide code that locates ViewModels and constructs them based on whatever convention or process you like if you want to do things differently than the simple starter conventions of Prism. Module 3 – Commands and Dependencies In this module, I talk about the Command Pattern, how it is supported by the WinRT platform, and how it is used to communicate between Views and ViewModels. Then I cover the DelegateCommand class of Prism, which was ported over from Prism 4. Next I get into dependencies, define what a dependency is, how you can do manual dependency injection in Prism for dependencies that your ViewModels have (such as repositories and other client side services), as well as a quick introduction to dependency injection (or IOC) containers, and how to use a container with Prism. Module 4 – Navigation and Application Lifecycle In this module I cover the navigation APIs of WinRT and the styles of navigation that are common in a WinRT application. Then I show how Prism wraps those and makes it so your ViewModels can be in charge of navigation as well as be notified when their respective Page views are navigated to and from so that they can initialize their data and events appropriately and clean them up when they are going to go away because their Page has been unloaded and is going away. Then I talk about the app lifecycle of a WinRT app and how it ties in with both navigation and transient state management. I show how Prism makes it so your ViewModels can declaratively mark properties so they will be automatically persisted and restored across a suspend – terminate – launch/resume lifecycle, as well as how you can do the same thing using a Prism service (SessionStateService) in your repositories and client side services. Module 5 – PubSubEvents and EventAggregator This module covers how to do loosely coupled communications between ViewModels or client side services using the EventAggregator of Prism. This is a port of the EventAggregator from Prism 4 that we moved into a Portable Class Library for this release so this release version can actually be used by any .NET 4 or later, Silverlight 4 or later, Windows Phone 7.1 or later, or WinRT project. I cover the EventAggregator pattern and where it can apply in your MVVM applications, and then demonstrate using it for simple pub/sub events, using weak references, thread dispatching, and filtering. Module 6 – Validation One of the cool things we did in Prism for Windows Runtime is compensate for an important omission in WinRT at the current time, especially in the context of business applications that will probably involve a fair amount of data input instead of being focused mostly on content consumption (like most Windows Store app samples available). Specifically, WinRT has no support in Bindings or in the built in controls for handling validation and displaying it to the user. So this module covers how to leverage the reusable code we put together to allow your Model or ViewModel objects to declare validation rules through the standard System.ComponentModel.DataAnnotations attributes, have those evaluated whenever a property changes, and have them displayed to the user in a simple to hook up way in the UI. Module 7 – Calling Web APIs This module covers some fundamentals of calling Web APIs (or HTTP Services) from Windows Store apps. I do a quick intro to creating services with ASP.NET Web API, show how to use the HttpClient class to make the calls (regardless of the back end platform that is exposing Web APIs), and then get into how to secure the calls. I also cover the approach we took for doing server side validation and returning the validation errors in a standard structured manner to the client based on MVC model validation that is built in to ASP.NET Web API. I show how to use some reusable classes we implemented in Prism to consume those errors back on the client side, and get them hooked back into the client side validation mechanisms we have so that you can display the errors to the user at a field level in the same way the client side errors get displayed. Module 8 – Leveraging WinRT Platform Features I finish off the course with a quick tour through the implementation in the AdventureWorks Shopper application that show how to integrate and leverage platform features including Search charm, Settings charm, Flyout panels, and Live Tiles, but in a way that is properly structured to be managed and controlled by ViewModels in an MVVM application. --- So I hope you will check out the course and enjoy it. If you want to read some articles that don’t go into nearly as much depth but follow a similar structure and material, you can check out my article series on Prism for Windows Runtime here. That link points to Part 1, but there are links to the other parts in the right margin. I’m still working on a few more articles for that series, so be sure to check back over the next month or so for a few more installments.
Friday, April 19, 2013
Kona is Dead, Long Live Prism!
UPDATE: They got the Codeplex URLs updated today, so the new and permanent home for Prism for Windows Runtime is here: http://prismwindowsruntime.codeplex.com. If you have read my blog, seen me speak at conferences or user groups, or read some of my articles lately you might know I have been working with the Microsoft patterns & practices team on guidance for Windows Store Business apps. This guidance has been code named “Kona” up until recently, and I’ve posted and written articles on that in various places. As the team was getting the guidance ready for release, they decided to rename it to “Prism for Windows Runtime”. The names have not all been updated on the Codeplex site or in the downloads yet, but the code has been refactored to the final namespaces and project names that it will ship with. Specifically the guidance is called “Prism for Windows Runtime”, and it is guidance on building loosely coupled, maintainable, testable applications based on the MVVM pattern for WinRT, especially Line of Business or Business to Consumer applications. The guidance contains: - An end to end sample application – AdventureWorks Shopper – that is representative of a real Windows Store application that you might find as a B2C app in the store. It demonstrates all of the aspects of what Prism for Windows Runtime contains, and has actually gone through the same approval processes that a 1st party app (an app produced by Microsoft for the Windows Store) would have to go through.
- Reusable class libraries – Microsoft.Practices.Prism.StoreApps and Microsoft.Practices.Prism.PubSubEvents. The StoreApps library contains all the reusable infrastructure for doing the MVVM pattern on WinRT, including base classes for your Application class, Pages, ViewModels, and model objects, a ViewModelLocator, and stuff to support navigation, app state management, validation, search and settings charms and more. The PubSubEvents library is basically the Prism 4 CompositePresentationEvent pub/sub events code ported to a Portable Class Library (PCL) that can be used in any .NET 4 or later, Silverlight 4 or later, Windows Phone 7.1 or later, or WinRT application.
- Quickstarts – smaller samples that demonstrate getting started (HelloWorld), Validation, and PubSubEvents usage
- Documentation
If you want to learn more, be sure to check out my article series here, and keep an eye out for my Pluralsight Course that will be out in a month or so titled “Building Windows Store Business apps with Prism”.
Thursday, April 11, 2013
DevIntersection Session Wrap Up
I had a great week speaking at DevIntersection this week and already looking forward to the fall show. If you haven’t made it to this conference yet, you ought to try to make it to the next show. Just a fantastic set of speakers and topics all expertly orchestrated by the conference organizers all set in a great conference venue. For those that made it or those that didn’t that are interested in the things I presented, below are the slides and demos for the sessions I gave. Let me know if you have any questions – best to tweet me @briannoyes if you do leave a comment. Building MVVM XAML Client Apps Slides Demos Designing RESTful Services with ASP.NET Web API Slides Demos Rich HTML Client Data Apps with Breeze Slides Demos Expose Data Services with ASP.NET Web API Slides Demos
Saturday, March 9, 2013
AngleBrackets and DevIntersection–A great event you shouldn’t miss!
I’ll be speaking at two co-located conferences in April that a lot of people haven’t heard of but should get to know and make part of their annual training/conference plans and budget AngleBrackets and DevIntersection. Anglebrackets is a brand new conference focused on open web technologies. In this ever expanding world where HTML is the king of UI technologies and developers can less and less be focused on a single platform, this is a conference that embraces that mentality and offers up some great content to get you spun up in that world. The speaker roster is full of top names in web development technologies spanning HTML, CSS, JavaScript and focusing on both the developer and the designer. I’ll be giving a talk there on Rich Data HTML Apps with Breeze. Anglebrackets is co-located with DevIntersection, which itself is a quickly growing conference that is focused on Microsoft development technologies and packed with all the top speakers in that space. I’ll be giving three other sessions there on Designing RESTful Services with ASP.NET Web API, Expose Data Services with ASP.NET Web API, and Building MVVM XAML Applications. Its going to be a great show and I’d strongly recommend you check them out for a great opportunity to build your skill set on the technologies that really matter today.
Wednesday, March 6, 2013
New Pluralsight Course: Building ASP.NET Web API OData Services
My latest Pluralsight course is now out and you can check it out here. This course covers the new OData features that released with the ASP.NET and Web Tools 2012.2 release just a couple weeks ago. Here is a quick rundown of what you will learn in this one. Module 1: ASP.NET Web API Overview, REST, and OData Concepts I go through a thorough overview of what ASP.NET Web API is and how it works for developing HTTP services. I talk about the convention based routing, content negotiation, and processing pipeline of ASP.NET Web API. Then I talk about the REST Architectural Style and how it is different from other service styles such as RPC. I finish off the module by giving a high level overview of what the OData protocol is all about. This module includes an end to end demo of developing a CRUD-oriented Web API that does not use OData, but complies with some of the REST architectural constraints. Module 2: OData Tools and Resources In this module I cover the ecosystem of OData. I talk about the similarities and differences between WCF Data Services and ASP.NET Web API OData, as well as talking a little about the many server and client platforms that support OData. I demo how to build a simple OData service with WCF Data Services as a point of comparison and how to consume it with the WCF Data Services client. I talk about some of the tools out there for consuming and working with OData, and demo using LINQPad and Fiddler. Module 3: Supporting OData Queries in ASP.NET Web API In this module I show you how to start leveraging OData in your Web APIs to just support OData query URLs. I talk about the OData query protocol and what kinds of operators and options there are that you can use to shape queries from the client side. I then talk about and demonstrate how to add the OData NuGet package to your Web API projects and use IQueryables and the [Queryable] attribute to light up query support. I finish off the module by talking about and demonstrating one of the key benefits of supporting OData queries – deferred execution all the way to the database. Module 4: Supporting OData Formatting and Entity Data Models A big part of the OData protocol is using one of several standardized formats for your entities as you query and update via your OData services. This depends on part of the OData spec that delineates how to specify the data model that you are exposing for querying and updating. In this module I show you how to set that up so that you can support the ATOM, JSON-Verbose, and JSON-Light formats of OData for the message bodies of your queries and updates. Module 5: Updating via OData OData is not just about retrieving data – you can issue updates through it as well. In this module I show how to do inserts, updates, and deletes using OData. I also show how to deal with errors and exceptions in an OData compliant way, and how to expose additional OData Actions on your controllers for calls that go beyond the basic CRUD patterns of OData. Module 6: Consuming OData Web APIs from Clients In this module I show you how to use the .NET WCF Data Services client to call OData services (whether implemented with ASP.NET Web API or not) in greater detail than the demo in module 2. I show you how to do updates and queries, as well as how to use the async APIs exposed by the Data Services client proxies and how to wrap it in a Task-based Async Pattern for use with the new async/await keywords of .NET 4.5 and WinRT. Then I switch gears and show how to consume OData from JavaScript clients using JQuery, DataJS, and Breeze.js. So that is it. A good end-to-end coverage of the new OData features of ASP.NET Web API. I hope you will check it out and spread the word! Don’t forget to check out my other Pluralsight courses as well.
Wednesday, February 20, 2013
New Article Series–Windows Store LOB Apps with Kona
For the past 6 months or so, I have been working with Microsoft patterns & practices on a project codenamed “Kona”. It is a set of guidance on building Windows Store (Windows 8, WinRT, Modern UI, etc – the kind of app formerly known as Metro) applications for Line of Business (LOB) scenarios. That guidance is nearing completion, so I figured it was time to start getting some articles out there on what it is about and how to leverage it for building your own applications. The team was composed of several of the same people at p&p that were part of the Prism team that I also worked on. The Kona guidance is specifically geared towards people building Windows Store apps who are not just trying to quickly crank out a fairly small app and get it in the store quickly, but those that are building apps where maintainability, unit testability, and evolability are key considerations. Which usually means you are trying to write an app that will be an integral part of business for a company somewhere. Now there are lots of different definitions for what constitutes line of business. One discriminator I tend to prefer myself is that it is someone’s job to use the app for a significant part of their day. But in the realm of Windows Store apps, especially at the current time, there is a lot more focus on B2C – business to consumer – applications than LOB apps that it is an employee’s job to use as part of their job. So if you look at the primary sample application in Kona (called a “Reference Implementation” or RI by p&p), you may immediately call in to question whether this is for LOB or not. The scenario is a shopping applications for the AdventureWorks company – so more of a B2C scenario than a traditional LOB scenario. This scenario was chosen for a number of reasons, but the key thing is to not get too hung up in whether the sample scenario is truly an LOB scenario, but realize that it doesn’t really matter what scenario you pick if you build the application the way you would for an LOB or B2C app that you expect to have a long life and lots of features, and if that app demonstrates the things you are trying to show. So Kona does that by providing the AWShopper “RI” (sample application) and part of that is a reusable library that encapsulates a lot of the things you need to do to fully participate in WinRT application lifecycle, navigation, platform features like settings and search and so on. I’m not sure exactly how many articles will end up in the series, but probably at least 6-10. There is a lot of good stuff in Kona that any Windows Store app developer can benefit from, especially if they want to do MVVM. So check out part 1 here, and you will find links to the follow on articles in the sidebar as I get them written. http://www.silverlightshow.net/items/Windows-Store-LOB-Apps-with-Kona-Getting-Started.aspx
Saturday, February 16, 2013
Consuming an ASP.NET Web API OData Service with Breeze
One of the last things I figured out to include in my Pluralsight course “Building ASP.NET Web API OData Services” (which should be out in a week or two – all done, just waiting for the editorial process to complete) was how to consume my Web API OData services with Breeze.js. Breeze is a great JavaScript library for including rich service-based data access in HTML 5 / JavaScript applications. It acts as a smart client side repository that can make the retrieve and update service calls for you, caches the data client side so you can avoid unnecessary round trips, does change tracking on the entities so that it knows what to send back for update when you as it to (following a unit-of-work pattern), integrates nicely with Knockout (or other observable-based libraries) and more. Its also capable of consuming both Breeze Web APIs that you can easily set up with their ASP.NET Web API server libraries, or OData services (regardless of what platform those are on). When it comes to integrating with OData, for now Breeze just supports querying (retrieval) data, not updating through the OData mechanisms. But it provides a nice abstraction layer for doing so because it lets you formulate LINQ-like syntax in your JavaScript code for things like “where” (filter operations at an OData wire level), orderby, top, skip and so on. So it was a natural fit for the module in my course on consuming OData from .NET and JavaScript clients. Most of getting it working was totally straightforward, I just followed the great documentation on the Breeze site on setting up the Breeze configuration for OData and making the calls. There was one trick that I sorted out with the help of a little code that Ward Bell and the Web API team had been slinging around. Specifically, take note of the comments in Step 4 below about matching up the EDM namespace and the entity type namespace. So here is a quick walkthrough so others can just take it by the numbers. Step 1: Create your Web API Project File > New Project, Web category, MVC 4 Application, select Web API project type.   Delete the ValuesController that it puts in the \Controllers folder. Step 2: Add the OData NuGet Right click on the project in Solution Explorer, find Manage NuGet Packages.  Search for OData and find the ASP.NET Web API OData package.  Step 3: Define a Data Model I’m gonna use the venerable Northwind Customers table here to keep it simple. Add a connection string to your web.config: 1: <add name="NorthwindDbContext" connectionString="server=.;
2: database=Northwind;trusted_Connection=true"
3: providerName="System.Data.SqlClient"/>
Add a Customers class to the Model folder:
1: public class Customer
2: {
3: public string CustomerID { get; set; }
4: public string CompanyName { get; set; }
5: public string Phone { get; set; }
6: }
And a NorthwindDbContext class (Entity Framework code first approach – could use DB First or any model you want).
1: public class NorthwindDbContext : DbContext
2: {
3: public DbSet<Customer> Customers { get; set; }
4: }
Step 4: Define an EDM
Open the App_Start folder in the project, open WebApiConfig.cs. Add a helper method to define an Entity Data Model:
1: public static IEdmModel GetEdmModel()
2: {
3: ODataModelBuilder builder = new ODataConventionModelBuilder();
4: builder.EntitySet<Customer>("Customers");
5: builder.Namespace = "WebAPIODataWithBreezeConsumer.Models";
6: return builder.GetEdmModel();
7: }
The ODataConventionModelBuilder just needs to know the collections you want to expose. It will reflect on the types, and declare all their properties in the EDM with corresponding EDM types, will follow navigation properties to related entities and declare those, and will infer what the entity keys are.
IMPORTANT: Note line 5 – you need to make sure the namespace of the EDM matches the namespace your entity types are contained in.
Step 5: Add an OData Route
In the Register method, add an OData route for your EDM (line 3 below):
1: public static void Register(HttpConfiguration config)
2: {
3: config.Routes.MapODataRoute("odata", "odata", GetEdmModel());
4: config.Routes.MapHttpRoute(
5: name: "DefaultApi",
6: routeTemplate: "api/{controller}/{id}",
7: defaults: new { id = RouteParameter.Optional }
8: );
9: }
The MapODataRoute extension method takes three arguments: a name for the route, a prefix off the site root address where you can get to the EDM model you will expose, and the EDM model itself.
Step 6: Create an EntitySetController
Add a project folder called ODataControllers. Add a class in there called CustomersController, with a base class of EntitySetController<Customer,string>. Add a Get method to it that uses the NorthwindDbContext to return Customers:
1: public class CustomersController : EntitySetController<Customer,string>
2: {
3: NorthwindDbContext _Context = new NorthwindDbContext();
4:
5: [Queryable]
6: public override IQueryable<Customer> Get()
7: {
8: return _Context.Customers;
9: }
10:
11: protected override void Dispose(bool disposing)
12: {
13: base.Dispose(disposing);
14: _Context.Dispose();
15: }
16: }
Note the [Queryable] attribute on the Get method – this in combination with the IQueryable return type is what enables OData query syntax. The EntitySetController takes care of making sure the OData formatter is used instead of the default JSON formatter, as well as taking care of mapping OData routing scheme to this controller. The default OData format is JSON-Light (as opposed to JSON-Verbose or ATOM XML).
At this point you have a working OData service. You should be able to hit it in the browser with an address of /odata/Customers and you will get back the customers in the default JSON-Light format. If you want ATOM or JSON-Verbose, you will need to use a tool like Fiddler where you can control the headers.

Step 7: Add DataJS and Breeze.js through NuGet
Go back into Manage NuGet Packages from Solution Explorer and search for Breeze. Select the Breeze for ASP.NET Web Api Projects package and install. Then do the same to find and install DataJS.

Step 8: Create an HTML page + JS with JQuery, Knockout, Q, and Breeze
Go into the Views folder of your Web project and find the /Home/Index.cshtml file. Clear out all the HTML in there and add the following scripts to the top (Note: you can do this by dragging and dropping the script file from the /scripts folder (you may need to update the JQuery and Knockout NuGet packages in your project to match these versions).
1: <script src="~/Scripts/jquery-1.9.1.js"></script>
2: <script src="~/Scripts/knockout-2.2.1.js"></script>
3: <script src="~/Scripts/q.js"></script>
4: <script src="~/Scripts/datajs-1.1.0.js"></script>
5: <script src="~/Scripts/breeze.debug.js"></script>
Next we need to start building the JavaScript that will use Breeze to execute a query and put it in a view model we can bind to. First step is to initialize Breeze and tell it we will be dealing with OData:
1: <script type="text/javascript"> 1: 2: var my = {}; //my namespace 3: $(function () { 4: var serverAddress = "/odata/"; 5: breeze.config.initializeAdapterInstances({ dataService: "OData" }); 6: var manager = new breeze.EntityManager(serverAddress); 7: }); </script>
Next we need a simple view model that we will data bind to from our HTML, declared inside the script block:
1: my.vm = {
2: customers: ko.observableArray([]),
3: load: function () {
4: }
5: }
Next the code that calls the load and sets up the data binding with Knockout at the end of our script block, inside the JQuery ready function:
1: my.vm.load();
2: ko.applyBindings(my.vm);
Next some simple Knockout bound HTML to render the customers (outside the script block obviously):
1: <h2>Customers (<span data-bind="text: customers().length"></span>)</h2>
2: <table>
3: <thead>
4: <tr>
5: <th>CustomerID</th>
6: <th>CompanyName</th>
7: <th>Phone</th>
8: </tr>
9: </thead>
10: <tbody data-bind="foreach: customers">
11: <tr >
12: <td data-bind="text: CustomerID"></td>
13: <td data-bind="text: CompanyName"></td>
14: <td data-bind="text: Phone"></td>
15: </tr>
16: </tbody>
17: </table>
Step 9: Query Away!
Now all we have to do is flesh out our load method in the view model. All we need to do is form a query and execute it with the Breeze EntityManager, putting the results where we want them – in this case I loop over the results in a success callback function, pushing them into my observable array in my view model. The really cool thing is that Breeze takes care of downloading the OData metadata for the Entity Data Model and automatically creates observable types for the data objects, so the individual objects I am adding into my array are data binding friendly JS types with observable properties.
1: load: function () {
2: var query = breeze.EntityQuery.from("Customers");
3: manager.executeQuery(query, function (data) {
4: var results = data.results;
5: $.each(data.results, function (i, c) {
6: my.vm.customers.push(c);
7: });
8: });
9: }
We can now run and we should get all customers:

The other cool thing is that now we can start formulating more complicated LINQ-like queries with Breeze. instead of just asking for all customers above, we could change it to ask for customers who’s company name starts with B and order by the CustomerID. Just change line 2 above to:
1: var query = breeze.EntityQuery.from("Customers")
2: .where("CompanyName","startsWith","B").orderBy("CustomerID");
And viola:

Summary
Web API makes exposing OData services a piece of cake and gives you more power and flexibility to integrate your own business logic and data access than you get in WCF Data Services. Breeze makes a great JavaScript client library to query those services, allowing you to write LINQ like code to formulate your queries. Of course Breeze goes way beyond just letting you query – it gives you a really rich experience for binding, editing, validating, going offline, and then pushing changes to the data back to the server. But those things will have to wait for another post…
Please check out my Pluralsight Course “Building ASP.NET Web API OData Services” (due out by end of February) for the full story on Web API and OData.
You can download the full source code for this sample here.
Friday, January 18, 2013
Wednesday, January 2, 2013
Scaling Windows Azure Web Sites from Free/Shared to Reserved
Last week DasBlog freaked out on my blog and pegged the CPU on my Windows Azure Web Sites (WAWS) hosted blog. Because I had it configured as a Shared instance (which allows me to point my custom briannoyes.net and briannoyes.com domains at it from DNS), there are Usage Quotas that kicked in for how much CPU time your site can consume in a given window and my site got suspended for exceeding those quotas. As a result, my blog was down for almost a 24 hour period until the quota gets reset. When I discovered the problem (thanks to @MLaritz for alerting me via Twitter), I thought “well, I can just scale it up to a Reserved instance for a period until the quota gets reset and then can scale back down.” What surprised me was when I tried to do that I got the following warning: "This will upgrade all web sites in the West US region to Reserved mode. This will take several minutes to complete and your sites will keep running during the process." I had two other sites on the same account in the same sub-region, and this made it sound like they were each going to become a Reserved instances (billing out at ~$57/mo instead of ~$10/mo for shared). So I instead opted for waiting and letting my blog be down for a day. I followed up with the Azure team and was pointed to this great post by Brent Stineman. The important subtlety here is that yes, in fact all of my sites would have been moved to a Reserved instance, but they would all be moved to a single instance and it would basically become a dedicated VM acting as a shared host for all of my sites, which I could then scale as appropriate. That means if you have more than 6 sites you would actually save money compared to the shared hosting option. Well, in my case I only had three and it would have been a little more expensive, but no where near what I thought it was telling me – that I would jump to paying 6 X 3 = 18 times as much. So just realize that when you scale from Shared to Reserved mode and you get this notice, it means those sites will be moved together to a single reserved instance, not individual instances.
Thursday, December 20, 2012
Attached Behaviors vs Attached Properties vs Blend Behaviors
Brian Lagunas asked a very good question based on seeing my sample video from my Pluralsight Windows 8 MVVM XAML Apps course, the gist of which was (paraphrased): “Why do you call them Attached Behaviors – won’t that cause confusion with what is an Attached Property and with Blend Behaviors?” My initial answer was along the lines of “because that is what we called them back in the day, long before Blend picked up the concept and created their own behaviors.” http://blogs.msdn.com/b/dancre/archive/2006/03/04/543854.aspx But Brian rightly pointed out that not everyone has as deep of history working with XAML as I do and a lot of people only associated the term behavior with Blend Behaviors. He also asked how to discriminate a simple attached property from an attached behavior. Here is my response: I think the distinction in my mind is this: "normal" attached properties are there as metadata for some other piece of code (i.e. a container control like a Grid or a ToolTip) to modify its own behavior based on the presence of that attached property. When used like that, attached properties are like attributes in C# or VB code - they don't do any work themselves, they are just there to influence behavior implemented somewhere else. When an attached property has a change handler that acts on the exposed API of the DependencyObject to which it is attached, it is an attached behavior - in which case it is much more like an extension method in C# - a chunk of code that can be associated with that object to supplement that object's behavior or functionality without that object's knowledge. A similar discussion also recently came up while working with the Microsoft patterns & practices Kona team on Line-Of-Business guidance for Windows 8. As a result of that discussion, I wrote up a couple page summary with some snippets to compare and contrast Attached vs Blend Behaviors. So I’m including that content here as well. Attached and Blend Behaviors Behaviors are a way of supplementing the functionality, or behavior, of XAML elements. A behavior is a chunk of code you write that can be used in XAML by attaching it to some element through attached properties. The behavior can use the exposed API of the element to which it is attached to add functionality to that element or other elements in the visual tree of the view. In this way, they are the XAML equivalent of C# extension methods. Extension methods allow you to define additional methods for some class in C# without modifying the class definition itself, and they work against the exposed API of the class. Behaviors allow you to add functionality to an element by writing that functionality in the behavior class and attaching it to the element as if it was part of the element itself. Ultimately behaviors package up code that you would normally have to write as code behind because it directly interacts with the API of XAML elements in a way that it can be concisely hooked up to an element in the XAML and packaged for reuse across more than one view or application. They can be used to encapsulate a complex coding pattern of interaction for a given control, do visual tree walks to discover and hook things up throughout a view, and virtually any scenario where you ask yourself “how do I do XYZ?” and the answer is “you write this code behind”. In the context of MVVM, they are a great way to bridge from things that are happening in the view due to user interaction and getting the information and execution into a view model. So you can hook events and properties from a given control type and feed those down into a view model in a standardized fashion. All behaviors are in some sense “attached behaviors” because they use Attached Properties in XAML to hook the behavior in to some element within the XAML. But two styles of implementation for behaviors are dominant. The first is generally referred to as simply an Attached Behavior, and the second as a Blend Behavior. Attached Behaviors Attached behaviors are defined as a static class with one or more Attached Properties defined within it. An Attached Property can define a change callback handler for when the property gets set on some target element, and the callback handler gets passed a reference to the element on which it is being attached (much like the “this” parameter reference in an extension method) and an argument that tells what the old and new values for the property are. The “behavior” comes in when you use that change callback handler to wire up new functionality to the element the property is attached to by manipulating the reference to it that gets passed in. The typical pattern is that the change callback handler will cast the element reference (which comes in as just a DependencyObject) to some known element type that the behavior is designed to enhance. Then it will hook up to events exposed by that element type, modify properties of the element, or call methods on the element to manifest the “behavior” desired. An example would be to cast the reference to the ListViewBase type in WinRT, which is the base class for GridView and ListView, then subscribe to the ItemClick event, and in the handler for that event, make something happen like navigation or invoke a command. The syntax for the behavior would look like this: public static class ItemClickNavBehavior
{
public static string GetDestination(DependencyObject obj)
{
return (string)obj.GetValue(DestinationProperty);
}
public static void SetDestination(DependencyObject obj, string value)
{
obj.SetValue(DestinationProperty, value);
}
public static readonly DependencyProperty DestinationProperty =
DependencyProperty.RegisterAttached("Destination", typeof(string),
typeof(ItemClickNavBehavior), new PropertyMetadata(null,
HookupBehavior));
private static void HookupBehavior(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
ListViewBase lvb = d as ListViewBase;
if (lvb == null) return;
lvb.ItemClick += DoNavigation;
}
private static void DoNavigation(object sender, ItemClickEventArgs e)
{
//...
}
}
And the hookup for the behavior in the XAML like this:
<GridView local:ItemClickNavBehavior.Destination="Home" ...>
Blend Behaviors
The problem with Attached Behaviors as described above is that they are defined entirely through a set of public static variables and methods within a static class. As a result, there is not good encapsulating, and you have to be very careful with unsubscribing from events that you subscribe to at the appropriate time so you do not cause memory leaks. Additionally, they are not easy to use in a visual designer because there is not a visual designer metaphor for dragging and dropping a property onto an element. You can drag and drop objects on other objects to set up a hierarchy, and you can set properties on objects already in the designer through the properties window, but you cannot do the initial hookup through existing interaction patterns in a designer.
As a result, the Microsoft Expression Blend team standardized a new coding structure for defining behaviors that is both design tool friendly, and is better encapsulated. With a Blend Behavior, you define a non-static class as your behavior , derived from a Behavior or Behavior<T> base class. In your behavior you override a base class method called OnAttached, and you have a base class property called AssociatedObject that gives you a reference to the element to which the behavior is attached. The behavior then gets attached to the element through an Attached Property that is a collection of Behaviors. This allows a drag and drop interaction in a visual designer. You drag and drop the behavior onto the element that you want to attach it to, and an instance of the behavior class is created in the Behaviors Attached Property collection on the target element.
With a Blend Behavior, the syntax for defining one for the same scenario as the Attached Behavior shown earlier looks like this:
public class ItemClickNavBehavior2 : Behavior<ListViewBase>
{
public string Destination
{
get { return (string)GetValue(DestinationProperty); }
set { SetValue(DestinationProperty, value); }
}
public static readonly DependencyProperty DestinationProperty =
DependencyProperty.Register("Destination", typeof(string),
typeof(ItemClickNavBehavior2), new PropertyMetadata(null));
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.ItemClick += DoNavigation;
}
private void DoNavigation(object sender, ItemClickEventArgs e) { /* ... */ }
}
And the attaching code looks like this:
<GridView>
<i:Interaction.Behaviors>
<local:ItemClickNavBehavior2 Destination="Home" />
</i:Interaction.Behaviors>
</GridView>
The base classes and the attached property class for Blend behaviors come out of the Blend SDK. Unfortunately this is not available for WinRT yet. There are several community developed replacements for it, such as the WinRtBehaviors project. Those use the exact same syntax and structuring as Blend behaviors, just a different namespace so the code can be portable to a Blend SDK once one is released for WinRT. As a result, I would still refer to these as “Blend Behaviors”.
The Blend SDK also ships with a number of pre-built, general purpose behaviors such as InvokeCommandAction, CallMethodAction, and ChangePropertyAction that can be used in MVVM scenarios. These behaviors actually get attached through a Triggers attached property collection instead of Behaviors because they get defined as a pair of objects – a Trigger object such as an EventTrigger, DataTrigger, TimerTrigger and so on, and the associated Action that will be invoked when the trigger fires.
So in the end, even Blend Behaviors are hooked up with an attached property.
Hope that makes it all clear as mud. 
|








| May, 2013 (1) |
| April, 2013 (2) |
| March, 2013 (2) |
| February, 2013 (2) |
| January, 2013 (2) |
| December, 2012 (3) |
| November, 2012 (1) |
| October, 2012 (1) |
| August, 2012 (2) |
| June, 2012 (2) |
| May, 2012 (3) |
| April, 2012 (1) |
| March, 2012 (2) |
| February, 2012 (2) |
| January, 2012 (1) |
| November, 2011 (4) |
| October, 2011 (1) |
| September, 2011 (2) |
| August, 2011 (1) |
| July, 2011 (1) |
| May, 2011 (5) |
| March, 2011 (4) |
| February, 2011 (2) |
| January, 2011 (3) |
| November, 2010 (4) |
| October, 2010 (1) |
| September, 2010 (5) |
| August, 2010 (5) |
| July, 2010 (6) |
| June, 2010 (8) |
| May, 2010 (2) |
| April, 2010 (2) |
| January, 2010 (1) |
| December, 2009 (3) |
| November, 2009 (2) |
| October, 2009 (3) |
| September, 2009 (3) |
| August, 2009 (2) |
| July, 2009 (3) |
| May, 2009 (3) |
| April, 2009 (2) |
| March, 2009 (1) |
| February, 2009 (2) |
| January, 2009 (2) |
| December, 2008 (1) |
| November, 2008 (2) |
| October, 2008 (5) |
| September, 2008 (4) |
| August, 2008 (2) |
| July, 2008 (1) |
| June, 2008 (2) |
| May, 2008 (2) |
| April, 2008 (3) |
| February, 2008 (6) |
| January, 2008 (3) |
| December, 2007 (1) |
| November, 2007 (1) |
| October, 2007 (5) |
| September, 2007 (1) |
| July, 2007 (3) |
| June, 2007 (8) |
| April, 2007 (2) |
| March, 2007 (4) |
| February, 2007 (1) |
| December, 2006 (2) |
| November, 2006 (9) |
| October, 2006 (5) |
| September, 2006 (3) |
| August, 2006 (2) |
| July, 2006 (4) |
| June, 2006 (5) |
| May, 2006 (10) |
| April, 2006 (4) |
| March, 2006 (2) |
| February, 2006 (12) |
| January, 2006 (7) |
| December, 2005 (2) |
| November, 2005 (15) |
| October, 2005 (6) |
| September, 2005 (7) |
| August, 2005 (3) |
| July, 2005 (10) |
| June, 2005 (11) |
| May, 2005 (7) |
| April, 2005 (8) |
| March, 2005 (6) |
| February, 2005 (2) |
| January, 2005 (6) |
| December, 2004 (3) |
| November, 2004 (5) |
| October, 2004 (2) |
| September, 2004 (5) |
| August, 2004 (13) |
| July, 2004 (6) |
| June, 2004 (14) |
| May, 2004 (17) |
| April, 2004 (12) |
| March, 2004 (8) |
| February, 2004 (10) |
| January, 2004 (14) |
| December, 2003 (9) |
| November, 2003 (13) |
| October, 2003 (3) |
Sign In
|