EF5 Code First with Multiple Databases

This turned out to be fairly simple, but it took me a while to figure out what was going on. I have two databases configured for one application. One is an authentication, authorization, and loggging datbase – it makes use of the default security framework with ASP.NET MVC 5 projects. In addition it utilizes NLog for logging. The second database is for application data.

So essentially I have two connection strings:

 

I have the default IdentityDbContext (included by default as part of the IdentityModels.cs file ) from an “out-of-the-box” MVC 5 application (with individual user accounts). To this, I added a new class “Log”, and included it in the context by simply adding a new DBSet to the properties of the context object.

In addition I added a new DbContext subclass, AppDataContext, with my two initial objects (very early in this project).

So my goal here was to simply be able to keep both contexts alive, and use package manager to add-migration(s) and update-database(s) for each connection string. However, out of the box this immediately runs into issues. Once you enable migrations for one, you must rename it before you can enable migrations for the other, because it wants to create the file with the default template, and you already have a configuration.cs file. To the credit of the product, they don’t let you do this without warning. However, that is not the desired result for me. I need to have both alive and well.

So I simply renamed Configuration.cs to IdentityConfiguration.cs, then enabled migrations again specifying the AppData context. And I got my second file. For the sake of consistency I renamed it as well, to AppDataConfiguration.cs. However, this is not sufficient. Because now, when trying to add migrations, the first one adds fine. The second, however, insists that you apply the first before you can continue.

Of course this made sense, since with EF Code First you have to apply a migration before you can add another. So I simply popped into the package manager and ran update-database providing the -configurationTypeName pointing to my IdentityConfiguration.cs file. This worked swimmingly, so I went back to add my migration for the AppDataConfiguration, when I was told that it was necessary to apply a pending migration. Since I’d just applied my only pending migration, this didn’t sit well with me. So I turned to the internet and found a thread on Stack Overflow (a site I highly recommend), which helped me resolve the root issue.

Even though I’d changed the names of both files, and classes, I had kept them both in the same namespace. Apparently, for EF CF Migrations, this is not cool. So I changed the namespaces and class names (to make it easier) from

AND

To:

AND

Respectively.

This was the trick, it all works fine, and as I’d expected, once you put everything into the distinct namespaces. While it is an annoying issue, at least it’s a very simple work around. By applying this fix you can have many database connections managed by EFCF.

Converting Image Hotlinks to Azure Storage Images

While working on a current project, I found myself with a need to cache media that I was collecting from various websites to my Azure Storage account. Then utilize the storage as somewhat of a Content Delivery Network (CDN) for my images and media.

I found a good article online about how to configure the storage account as a CDN. Which told me very quickly how to set it all up and configure it for my purposes. So the only challenge was to implement the logic to pull the images in there.

The following function pretty much does it all. First there is a field that is included in my model called “MediaUri”. This field is populated on the view with a URL for an image out on the web, say from Wikipedia for example. However this function, will convert that hotlink URL into a cdn.monkeyboxtech.com URL after downloading and caching the image to the CDN storage area.

Note this example relies on the Azure SDK tools being installed.

Then, in my web.config file for this application I have an app settings key that helps connect the cloud storage account. Of course you’d replace the <omit> with the actual values.

That is pretty much all there is to it. By using the Azure SDK tools for .NET, caching an image for later hosting from your storage account couldn’t be much easier.

Standard MVC 5 Web Application Using the Facebook JS SDK

While working on a current project — which is very much Facebook integrated, but not so much Facebook centric — the decision was made to not use the Facebook template, but instead use the standard MVC template, with the Facebook JS SDK. Here are a few things about the application you should understand before we continue:

  • It is a Facebook game, so if you come in from Facebook, it’s hosted in the Canvas
  • It is also a stand-alone app, and can be accessed by a standard URL. If you come in this way, It still needs to support login via Facebook, but is not canvased.
  • I wanted to to use the standard OWIN security for login, but automatically login when coming into the application from the Facebook Canvas.
  • By clicking a link from a wall post, a friend can play the same game you just played.
  • I wanted to test with both sandbox and non-sanbox modes.

Setting up the Environment

There are many and more articles on the web about how to setup a Facebook application. I will not bother rehashing it, but suggest you read an article about it, like this one, or search Google for it.

I also, in order to get out of the sandbox for some extra testing, had to get SSL working on my dev box. I use IIS Express and was able to follow this handy guide provided by Scott Hanselman and it was painless and quick.

Now that the application is ready, and my environment is setup, then it’s just a matter of writing the code.

Creating the Landing Page

For the landing page, I started out by simply adding an action to an existing controller.

There really is not much going on there, it just preps everything before rendering the view. The view then does all of the work. This landing page is configured as the Canvas Url in the Properties on the Facebook Application Dashboard. Note the “game” being pulled from the QueryString. This is to support the scenario where a user has accepted a challenge and is being brought in to play the exact same game as their friend. Facebook has some outstanding documentation on how to post a challenge to the user’s wall using the Feed Dialog. I just augment the link that I’m sending into the dialog to include the ?game=xxx GET parameters.

The view for this landing page is some very basic HTML wrapping the more important JavaScript so that it can handle everything that Facebook may throw at it.

First, I had to set it up to handle executing an external login using the existing /Account/ExternalLogin action (part of the default Account Controller). So to accomplish this, I simply set up a form with all hidden components. When the time is right it will be submitted via JavaScript.

Note that I’m passing the ReturnUrl from my controller so once the user is logged in, they proceed to the appropriate action. Also notice the <div id=”fb-root”></div>. This is important for Facebook, but they made their script smart enough to write it in if you leave it out.

Next I added the magic Facebook Script. This too is well documented in the Facebook developer portal. It breaks up into 3 parts. The code offered on the documentation (linked above) covers parts 1 and 3, it’s up to you as the developer to create the middle part.

Part 1 is the call to initialize the Facebook SDK

Part 3 is the bit that actually loads up the SDK itself

The middle part however, is where it gets fun. This is where the meat of the Facebook integration comes into play. Part two also, in my case, included an additional method in my controller that takes an HTTP Post and persists the user’s Facebook information to session state. While this article will not make use of it, you will see a call to it in the code below.

First I set up the subscription for the auth.authResponseChange event. When this connects successfully, I get the user’s uid and access token fed back to me. Then I pop up a friendly little bootstrap modal to tell the user I’m connecting them to Facebook, just before authorizing their information back to my server.

At this point, if everything is OK then we simply handle the complete promise for the ajax call in the snippet above. Notice that I am using the ReturnUrl that we stuffed into the ViewBag earlier in this code as well.

Also notice that I’m handling the scenario where the user may have already been signed into my game, but not authorized via Facebook before. I did this by nestling the value of User.Identity.IsAuthenticated as a lower case string into a JavaScript variable. Next I simply check that value, and if they are not authenticated, I submit my form – The one I mentioned in the beginning of the article.

If they are authenticated, then we should be golden. Redirect them if they asked to be, and if not, then simply hide the “Connecting to Facebook” popup.

This code only shows the handling of the “complete” promise, but of course we handle the failure and error promises too. For these I simply hide the dialog (if it’s not already hidden) and post an alert for the user. I do not show this in the code samples, but it’s as simple as it sounds.

Posting the Challenge

I’ve also included my code for posting the challenge to a user’s Facebook wall. Note your application has to be configured to support the correct permissions for this activity. The page that is posting the message also has parts 1 and 2 of the Facebook JS SDK setup. The only other code it requires is a single method call.

Summary

It took a little time and some trial and error to get it all figured out, but integrating a web app with the JavaScript SDK is pretty easy. Facebook already provides you with big chunks of code. Using those — along with some creative utilization of the tools afforded to you by MVC — you should find that working through a non-facebook-template site can still be tacked in pretty effectively.