# Wednesday, June 5, 2013

TechEd Talks Done!

I’ve completed my talks for TechEd US, which I will also be repeating at TechEd EU in Madrid in a couple of weeks. Turn out was pretty good, but overall interest in building WinRT / Windows Store apps is still slow.

The slides and video for my talk yesterday on Building Windows Store Line of Business apps (with Prism for Windows Runtime) has already posted, the ones for my talk today on Navigation in Window Store Apps should post at end of today.

All the demos in my Prism talk were done from the sample code that comes with Prism, so you can just download the main code for Prism here, and download the Quickstarts here, and you will have all the code I showed.

Today’s navigation session I put together a simple app with some navigation from scratch, so I wanted to make that code available to anyone who wants it as well, so you can download that from here.

Enjoy, and let me know if you have any questions, here in the comments or on twitter @briannoyes. Make sure to check out my Pluralsight course “Building Windows Store Business Apps with Prism” as well as my article series “WinRT Business Apps with Prism”.





Wednesday, June 5, 2013 5:06:50 PM (GMT Daylight Time, UTC+01:00)
Comments [1]  | 


 # Friday, May 24, 2013

Awesome new Prism for Windows Runtime resource - Project and item templates!

One thing that is a little tedious when you are first getting started with Prism for Windows Runtime is setting up a new project and swapping out base classes on the App class and each Page that you create, and cleaning up all the boilerplate code that Visual Studio puts in place. The good news is, you no longer have to, thanks to David Britch (who also wrote all the docs for Prism for Windows Runtime).

You can get the goods for what I am describing in this post here.

Using the Prism for Windows Runtime templates, you can now just do a File > New Project, and select a Prism App from the Windows Store category. You can choose from the Prism App, which uses manual dependency injection to pass client service references to the view model in the App.OnInitialize method, or Prism App using Unity to have it use the Unity container for dependency injection.

5-24-2013 1-33-45 PM

Once you create the project, it will have the App class inheriting from Prism’s MvvmAppBase, and will have one Page view and corresponding ViewModel, placed in the \Views and \ViewModels subfolders (and child namespaces), following the default convention for Prism’s ViewModelLocator.

5-24-2013 1-39-35 PM

Then to add new Views or ViewModels, you just right click on the respective folder and select Add > New Item, and you will see a number of Prism templates in the Windows Store category.

5-24-2013 1-42-19 PM

Nice big productivity boost compared to swapping out the base class in the code behind and XAML of your views and App class manually every time.

If you want a good end to end training on using Prism for Windows Runtime in your Windows Store apps, please be sure to check out my Pluralsight course Building Windows Store Business Apps with Prism. If you are not a Pluralsight subscriber, you should be because it is the best training around for getting up to speed on new technologies, and the price is soooo worth it.  But if you prefer a written introduction, check out my article series on Prism here: http://tinyurl.com/prismrtseries.

Thanks much to David Britch for taking the time to put these templates together. I know I will be using them from now on with my Prism projects.





Friday, May 24, 2013 6:49:59 PM (GMT Daylight Time, UTC+01:00)
Comments [1]  | 


 # 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.





Saturday, May 18, 2013 12:31:00 PM (GMT Daylight Time, UTC+01:00)
Comments [10]  | 


 # 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”.





Friday, April 19, 2013 5:02:34 PM (GMT Daylight Time, UTC+01:00)
Comments [4]  | 


 # 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





Thursday, April 11, 2013 11:02:29 PM (GMT Daylight Time, UTC+01:00)
Comments [4]  | 


 # 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.





Saturday, March 9, 2013 4:03:10 PM (GMT Standard Time, UTC+00:00)
Comments [0]  | 


 # 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, March 6, 2013 10:18:41 PM (GMT Standard Time, UTC+00:00)
Comments [0]  | 


 # 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





Wednesday, February 20, 2013 2:13:47 PM (GMT Standard Time, UTC+00:00)
Comments [4]  | 


 # 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.

Figure1

Figure2

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.

Figure3

Search for OData and find the ASP.NET Web API OData package.

Figure4

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.

Figure5

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.

Figure6

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:

Figure7

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:

Figure8

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.





Saturday, February 16, 2013 11:51:43 PM (GMT Standard Time, UTC+00:00)
Comments [1]  | 


 # Friday, January 18, 2013

Designing RESTful Services with ASP.NET Web API–NYC.net Developers Group

Last night I presented this topic at the NYC.net Developers Group to a packed house. The talk covers the fundamentals of developing HTTP Services or Web APIs with ASP.NET, then gets into the concepts of REST as an architectural style, contrasting it with SOAP and RPC style services and discussing the different levels of compliance that you might choose to have with the full REST architectural style as defined by its author.

I’ll be presenting this same talk in Redmond on 4 Feb, CapArea.net on 26 Feb, and at the DevIntersection conference in Vegas in April, so try to make one of those if you can to get bootstrapped on how to build Web APIs that comply (at least to some degree) with what REST is all about.

Here are the slides and demos for you to check out:

Slides 

Demos





Friday, January 18, 2013 4:02:20 PM (GMT Standard Time, UTC+00:00)
Comments [0]  | 


















June, 2013 (1)
May, 2013 (2)
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
Copyright © 2006-2012 Brian Noyes. All rights reserved.

designed by NUKEATION STUDIOS