Monday, June 2, 2014

Azure Mobile Services .NET Backend Tips

I've been working with Azure Mobile Services since it was released and until recently only the JavaScript backend was available, built using node.js. Although it is very mature with many options, the community was pressuring for a .NET option and now it is available.

Modeled much like a standard Web API / MVC project at first glance, there may be a few things that you like to take advantage of in these types of projects that throw you for a loop when using the new .NET option. These include Dependency Injection, Entity Framework (Migrations and Relationships), and the help page.

Getting Started

You have two options for getting a project started.

1. Go to the Azure Portal and create a new Azure Mobile Service and download the project

2. Start New Project from Visual Studio 2013 SP2 and choose "Web" -> "Windows Azure Mobile Service"

For this example, I went with option #1 and called it "mytodotips". Download the solution and be sure to build it to get all of the necessary nuget packages and ensure that your environment is set.

Entity Framework, Code First, Migrations, and Relationship Challenges

There are a few items here that may leave you scratching your head here, frustrating you, and depending on your temper perhaps throwing things. So, let me see if I can keep your mouse in one piece.


Do this first! Open Package Manager Console, Tools -> NuGet Package Manager -> Package Manager Console, and type the following command


the result will create a new folder in your solution called "Migrations" containing a file named "Configuration.cs", thus enabling code first migrations when your schema changes. In order to complete the change, open the WebApiConfig.cs file in the "App_Start" folder.

Comment out the Database.SetInitializer(...); line, and you may also comment out or delete the class that is called within the method.  This method drops and recreates the database each time the application is run.

Insert the following code above the SetInitializer(...); line to call the Configurator class just created by "enable-migrations" and explicitly apply the latest migration unless it has already been applied.

var migrator = new DbMigrator(new Configuration());

 The following namespaces will also need to be added to your imports

using System.Data.Entity.Migrations;
using mytodotipsService.Migrations;

Open Package Manager Console and run add-migration init, in doing so sets the initial migration and establishes the migration table.

Now whenever you add to your models, you can run the same Add-Migration "migration name" in the Package Manager Console and then hit F5 to update the local machine database or publish to Azure and run the service to update the Azure SQL Server database.


Relationships are pretty easy, however there are a few maintenance items in the OnModelCreating method I have found that help me get past some errors when running "update-database" or "add-migration".

Each class in Azure Mobile Services that has a table behind inherits from EntityData which implements ITableData. When make FK relationships you may receive errors when indexes are being created/altered. I have found by setting the Id field to be the PK on the table that sometimes these can be alleviated.

     .Where(p => p.Name == "Id")
     .Configure(p => p.IsKey());

Another option I also put on all new model classes is the following, this tells the database that the Id field is auto generated and is not required to be set when creating a new class.

     .Property(m => m.Id)

Now this a simply a personal preference that I'm sure many will disagree with, but I happen to like my tables to be singular.


Dependency Injection

My favorite DI engine for sometime has been AutoFac, and by accident I discovered its baked into Azure Mobile's .NET back end as well.

Now that I have the Entity Framework Code First context all set the way I like, I can now make sure I don't have to new up in every controller.

In our WebApiConfig.cs class, there is a ServiceConfig.Initialize(...) call to kick off the configuration process of the application. It accepts a ConfigBuilder class accepting options for your service, but also has an overload to accept a Func to register your own dependencies which happens to be an autofac container.

Here is how to add the database context, for example, using AutoFac.

  HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options, (configuration, builder) =>
        mytodotipsContext context = new mytodotipsContext();

And now in our ToDoItemController.cs we can add a constructor and alter the Initializer method to the following.

public class TodoItemController : TableController<TodoItem>
mytodotipsContext context;
public TodoItemController(mytodotipsContext myContext)
this.context = myContext;
protected override void Initialize(HttpControllerContext controllerContext)
  // mytodotipsContext context = new mytodotipsContext();
DomainManager = new EntityDomainManager<TodoItem>(context, Request, Services);

Help Page

So, you've got Entity Framework setup with relationships, Dependency Injection going with AutoFac and now you are checking out the help page and getting nothing. What happened?

There are a few issues we want to attack here.
  • Where is the data model?
  • I only want to show JSON
  • and a few more as we fix the top 2

Data Model Missing
This is a common issue with serializers when there are circular properties.  In this case there is a Profile class that has ToDo items that has a Profile property.  See the Code First Mapping here:

modelBuilder.Entity<ToDoItems>().HasRequired(t => t.Profile)
                .WithMany(p => p.ToDoItems)
                .HasForeignKey(t => t.ProfileId);

What happens here is when the JsonSerializer and XmlSerlizer  starts to walk the property tree; they get in an infinite loop and eventually exhaust the maximum errors and exit. In order to fix this, we will add the following to the WebApiConfig.cs class inside the Register method. *note only adding this for JsonFormatters, but can be handled for Xml just as well.

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

Now we can F5, see the help page and the object model represented in Json but the application/xml and text/xml boxes still show with the error.  As mentioned in our to do list above we only wanted to support Json. To do so, add the following to the configuration now.

// Remove default XML handlervar matches = config.Formatters .Where(f => f.SupportedMediaTypes .Where(m => m.MediaType.ToString() == "application/xml" || m.MediaType.ToString() == "text/xml") .Count() > 0) .ToList();foreach (var match in matches) config.Formatters.Remove(match);

And finally, I like to properly case Json.

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 

This single line will make JavaScript devs happy. Instead of seeing the objects like this:

        "Text": "sample string 1",
        "Complete": true,
        "Id": "sample string 3",
        "__version": "QEBA",
        "__createdAt": "2014-06-02T16:40:40.641Z",
        "__updatedAt": "2014-06-02T16:40:40.641Z",
        "__deleted": true

they are cased properly like this:

        "text": "sample string 1",
        "complete": true,
        "id": "sample string 3",
        "__version": "QEBA",
        "__createdAt": "2014-06-02T16:40:40.641Z",
        "__updatedAt": "2014-06-02T16:40:40.641Z",
        "__deleted": true
There are other features such as Notification Hubs and Scheduled Jobs which are awesome additions to any application. Be sure to check these out when leveraging Azure Mobile Services, regardless of whether you are using .NET or JavaScript as your back end of choice.

Leave a comment if you have a tip or trick you like to use or pass on as well.
Read more →

Friday, April 18, 2014

ASP.NET Presentations at DEVIntersection

Had a great time presenting Async Application Development and the Social Authentication options available in ASP.NET this week at DevIntersection.

Building Async Applications in ASP.NET

Async has become much easier over time to code and maintain with the async/await keywords and adding the capabilities in WebForms applications can improve overall page response times if done correctly.

Here are the additional links and the slides from the session.

Bring Your Own Authentication yo MVC

As I mentioned in my session on Social loin integration, adding the capability is very easy through since the addition of OWIN/Katana middleware authentication host plumbing that is out of the box in ASP.NET.  A couple of highlights from the talk:
  • Add social logins where appropriate
    • Enterprise or internal company applications might not apply
  • Leverage test user in Facebook's Developer portal
    • Don't use your own account or your friends and family
    • Add an under 13 account in the test user if you need to support children accounts
Here are the slides and additional links.

Again thanks for coming out and hope to see you in the fall at DEVIntersection and Anglebrackets!
Read more →

Monday, March 17, 2014

DEVIntersection: 3 Days of ASP.NET, Azure, SQL & More!

Come out to DEVIntersection April 13-16 at the JW Marriott in Orlando to get a chance to interact with a number of community experts such as Scott Guthrie, Scott Hanselman, Douglas Crockford and many more.

I'll be giving two talks in the ASP.NET track:

AS12: Building Asynchronous ASP.NET Applications

Learn how to take advantage of the new async/await operations to keep your applications responsive and avoid the performance bottlenecks. In comparison to how async code has been written with callbacks, the new way allows for cleaner more readable debug-able code. In this presentation topics covered WebForms, MVC, EF6 some tooling.

AS11: Bring Your Own Authentication (BYOA) to MVC

Most of us are familiar with the the phrase "Bring Your Own Device", where business users have over time influenced internal IT to move to the users platform instead of vice versa.  Leveraging the social sign on credentials such as Facebook, Microsoft, Twitter etc will not only eliminate the code you need to create, re-create or manage but also ease the sign on process for your potential users. ASP.NET provides the underlying OAuth framework to easily make the connection and manage the integration, this session will walk through leveraging social sign credentials in your applications in a few simple steps. 

Also don't miss out on the co-located <anglebrackets /> at no extra cost where you'll get an opportunity to hear web experts like John Papa, Dan Wahlin, Elijah Manor Rob Eisenberg and more speak about AngularJS, Durandal and other current and emerging web tech you won't want to miss out on.

Use discount code "BOYER" for an additional $50 off registration.
Read more →

Thursday, February 20, 2014

Town Hall Style, Windows 8 Development Shoot or Aim?

Had the first meeting of the year last night for the Orlando Windows Phone / Windows 8 Group and instead of going down the planned presenter lead meeting format it turned more into a "Town Hall" style with some good topics I thought I'd share.

Where does everyone go to learn how to build or develop for Windows 8.1?

As anyone who can use the web, you w ill find a number of popular blogs that have articles written on how to get started using this or that, including my own, but how relevant are they considering how fast Windows 8 development is moving and changing for that matter.  One attendee mentioned the LayoutAwarePage and how it was a thing and now its "just there".  Or how there were only 3 views to deal with and now there are many.

Brian, from the Orlando .NET User Group, likes Microsoft's Virtual Academy and also stated that when looking at blogs the first piece of information is the date the article was posted to know whether or not to keep going. is also another very well known resource for getting up to speed on almost any technology, and their catalog grows daily.

Monetization strategies for apps?

Of course, a very common topic.  How the heck do you make money on your apps?  Charge for them, ads, in app purchases, both, so on and so forth.  There has been a lot of conversation around this topic and sure enough the recent Flappy Bird app incident has everyone in a swirl to find the next big one.

Alex Perez, from Neuralnet, gave some insight into their experience on in app purchases how they attacked the issue.  Free with in app purchases was the most successful way, BUT you have to hook your users and make them want to keep coming back to the app is the key.

I don't this is a big secret, the secret is finding the hook -- right?

Should I build apps for Windows 8.1 now or wait to see what happens after BUILD 2014?

When Windows 8 hit the development community, a lot of the .NET community hit it learning the tools the new stuff throwing apps, blogging it etc. Some even went at the HTML/WinJS framework option reusing the libraries that were available building RSS readers, games, etc.

Then 8.1 hit and the game was changed. Tools got better, controls were added, more views, the OS was smaller, better, faster. Question on the floor - shoot or just aim?  

Strategies for sharing code?

I love the MVVM pattern for mobile development - Windows Phone, Windows 8.* and anything Xamarin supports.  With Portable Class Libraries and the lifted license restrictions and full support through Xamarin there is no reason not use it.  BUT, do not get caught in hours of trying to force something into the pattern simply to put it into the pattern.  Get the product out there, and rev. Refactor and release often.

Apps or Web?

It just depends right? What is the target audience, the device support, does it need connectivity, what is the skill set of the team you have and so on.  There is no right answer. The answer is -> know what questions to ask.

All great discussions, really enjoyed the format.  What are your thoughts on any or all of these issues, and have you tried this format at your local user group? Would you?
Read more →

Tuesday, January 14, 2014

Custom URIs added to I'm Here App

I took a few moments to add custom URI launchers for my I'm Here app on Windows Phone so it could be used in Rob Irving's Car Dash app.  It was a really quick add to the app, however the one are I found to be a pain was testing it.  I actually had to write another phone app to test it. Not that it was a chore, just didn't consider that when I started, I made an assumption I could've just typed i the URI in Internet Explorer or mocked an SMS message like you can in iOS.

If you have a Windows Phone App that offers functionality that other apps can use there is no reason not to offer custom launchers.  It takes about an hour total development time, and the benefit can more than just adding the functionality.

In my case, one I learned how to do it. Two, I get free marketing from another very successful app. Make sure you document your URI on the Nokia page here to let every other developer know for extra exposure. And finally, made a nice connection in the developer community.  Who knows, maybe the next big thing will happen when Rob and I team up...

If you want to use I'm Here in your app here is the simple launcher URI code to do so.

// launch the app
await Windows.System.Launcher.LaunchUriAsync(new Uri("imhere:"));
// launch the app and share location via SMS

await Windows.System.Launcher.LaunchUriAsync(new Uri("imhere://share/text"));
// launch the app and share location via Email

await Windows.System.Launcher.LaunchUriAsync(new Uri("imhere://share/email"));
// launch the app and share location via Social Apps

await Windows.System.Launcher.LaunchUriAsync(new Uri("imhere://share/social"));

// launch the app and share location via WhatsApp application
await Windows.System.Launcher.LaunchUriAsync(new Uri("imhere://share/whatsapp"));

Be sure to checkout my apps and the other links below to take advantage of the custom URIs in you own apps.

Rob Irving on Twitter
Nokia URI Association Schemes List
URI associations for Windows Phone - How To
Reserved file and URI associations for Windows Phone 8
Read more →
Powered by Blogger.
Creative Commons License by Shayne Boyer is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.