Deploying an MVC Code First application to Windows Azure

Deploying an Entity Framework Code First application to Azure can be confusing. Maybe this is just my opinion but hey, it’s my blog.  I recently had to do this for a project and I found a lot of pieces of information that helped, but few complete tutorials or guides on how all the pieces fit together.  Hopefully this will help someone out.  Basic working knowledge of MVC, Entity Framework, and Azure are assumed.

Initially my main point of confusion was the number of moving parts – Entity Framework, a local and remote database, an Azure website, Azure accounts, connection strings, publishing profiles etc.  Let’s take a closer look at how all these work together.

Since there are a lot of steps I will try to number them so you don’t skip anything when you inevitably start skimming rather than reading (we all do it).  I have tried to break them into 10 logical steps that are fairly easy to remember.

1) Go ahead and create a blank MVC Application in Visual Studio.  Choose No Authentication so we can go through the process of creating and deploying a database ourselves with Entity Framework rather than using pre-built code.

2) Add Entity Framework to your solution by right clicking on your project References and saying “Manage Nuget Packages”.  Install the latest Entity Framework…at the time of this writing its 6.1 but the version doesn’t really matter for this tutorial as long as you’re on a version that supports Code First Migrations.  For me Entity Framework was the first choice on the Packet Manager pop up.

3) Next we need to create a couple classes that will serve as Models – something that will map to database tables.  Create a Book class and an Author class in the Models folder, as shown below:

Model-Entities

4) Next we need to create our DbContext class, which sort of acts as a window into our database and its tables.  We’ll call it LibraryContext.cs and create a DbSet for the Author and Book class – just add the class to the top level of your project.

Library Conext

5) Create a connection string with the same name as the DbContext class.  This is important.  There are a number of ways to configure a connection from Entity Framework to a database, but I like this one because it avoids hard coding strings and is easier to spot in the web.config.  For now just point it to your local database and give the initial catalog the name of Library.  It doesn’t matter if you use localdb or SQLExpress or full SQL.

<connectionStrings>

    <add name=”LibraryContext” connectionString=”Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Library.mdf;Initial Catalog=Library;Integrated Security=True” providerName=”System.Data.SqlClient” />

  </connectionStrings>

6) Next we need to write code that actually accesses our database so that Entity Framework creates it on demand.  Modify your home controller so that it looks like this:

Data Access

Make sure to add the code to the About action that actually retrieves a book you have saved – this will come in handy later when we want to verify our database was updated on Azure.

7) Run your application and make sure it created the database by connecting to localdb with server explorer and expanding the tables.

LocalDB Database

8) Next we have to enable migrations in Entity Framework.  This will allow code to update or create the schema of our database.  This is necessary for Azure, which will not create a database on demand with Code First, so you have to provide it with explicit miration code that will recreate the tables and schema in an existing, empty database.

From the Package Manager Console (Tools -> Library Package Manager) run the following commands:

Enable-Migrations

Visual Studio will think for a moment – after it’s complete run this:

Add-Migration “initialcreate”

These commands will enable Code First Migrations and add a Migrations Folder to your solution.  If you (carefully) peek inside of this you will see a configuration.cs file and another InitialCreate.cs file.  The configuration file appropriately assigns some general settings, and the InitialCreate.cs file defines some code to create the necessary tables in our database.  This is basically code that explicitly performs the operations Entity Framework does behind the scenes locally when you first create a database that doesn’t exist.

This is most of what we have to do in Visual studio, so its time to head to Azure.  We’re almost done!

9) Sign into Azure with an administrator account and create a new custom database by pressing the big +New button in the bottom left.  You can also create the website first but I find it easier (and more logical) to create the database first.  If you are new to Azure you may also need to create a database server, which is easy to do through the UI. Call the database Library like we did in our connection string for simplicity, though this isn’t imperative.  It’s important that you use an account with full database permissions – preferably the account that created the server.

Create Database-1

8) Create a new custom website using the same button in the lower left and call it whatever you want.  Choose Library as the database and enter in your database server credentials.  Make sure you name the connection string the same as you did in Visual Studio – in our case this is LibraryContext

Create Website

10) After both of these have been created you will have a blank website hooked up to a blank database. Fun stuff!  Now download the Publishing Profile from the dashboard of the website.  If you open it up you will see that it is a regular XML file.  If you view it in a formatted text editor you will see that it just includes various information about the application and can actually be edited pretty easily.

Inside Visual Studio, right click on your project and select “Publish”.  In the dialog box that pops up,choose Import and import the file you just downloaded.  You can browse the tabs to see all the info it brought in.  There are a couple changes we need to make.  Leave the Profile and Connection tabs alone and go to Settings.  Make sure you choose “Release” configuration.  Under Databases, choose the Library connectino string from the drop down.  Make sure both “Use this connection string at runtime” and “Execute Code First” are checked.  Execute Code first is unchecked by default – make sure you select it.

Under the Preview tab there isn’t much to see but if you hit Start Preview you can see what files Visual Studio will deploy.  This is more useful for when deploying updates than it is for initial deployments.

As a side note, after you run this wizard Visual Studio will create a Publishing Profiles folder under the Properties section of your project.  Here you can edit the profile XML files.  There are a few useful settings in here that can’t be edited through the wizard, such as whether to deploy the App_Data folder.

Publishing Profile

Finally, click publish!.  Visual Studio will go through its deployment process and then open up to your website.  With any luck, the code should have run and created your database!

There are two easy ways to verify the database schema and data were created.  The first is by connecting to the database through Sql Management Studio using the database server name you find on the Azure dashboard and the login you used in your connection string.  You can also verify it by navigating to the About page on your site – if you see your book title it means it was retrieved from the database successfully.  Remember, this is why we added the code to retrieve the book.

That wasn’t so bad, right?

Once you understand all the pieces, deploying these types of applications from Visual Studio is actually much nicer and less painful than other types of deployments and hosting configurations.

Updating Posted Form Values on Postback with MVC – Fixing “Cached” Values

While working on a project I encountered a strange issue.  I created a simple registration form that posted back to my controller method, which received a view model as a parameter.  In my method I needed to update the values on this View Model before passing it back to the user through the same View.  However, this is where I encountered “strange” results.  Despite the correct data binding, correct code updating the model values, and the correct model being passed into the view, front-end users still received the old form values they initially posted.

This was initially puzzling, because I could see that the model I was passing in was correctly updated.   At first I assumed it was some kind of caching issue and tried a number of options, but to no avail.  Eventually I figured out the problem was coming from the Razor Helper I was using – specifically the EditorFor method (although this applies to any Razor helper method).

Let’s take a closer look.

Serving up Orchard Content Using Web API

Web Services seem to be all the rage right now, and for good reason – they are easy to work with if architected correctly and can interface with a huge range of platforms, which is very important nowadays.  Web API is Microsoft’s most recent effort at a light weight service platform, at least for HTTP based services, and I really enjoy working with it.

Orchard has historically done a great job of keeping up with the latest and greatest, and now supports full Web API integration.  This is actually a really powerful feature of that platform that I don’t see a lot of people using for whatever reason.  You can serve up literally any piece of content from Orchard as JSON through the Web API, so let’s take a look at how this works.  There are other examples out there on this topic, but I have found most of them to be very trivial in nature and don’t provide any kind of useful example.

This isn’t an in depth tutorial on Web API, it’s assumed you have at least a basic understanding of how it works but I’ll try to cover the main points to get you up and running.

General Thoughts on Passing Exam 70-486 (MVC Web Applications)

It’s a beautiful day!

This week I was fortunate enough to pass the Microsoft Certification Exam 70-486, which focuses on web application development with MVC and Azure.  Due to the non-disclosure agreement I signed (digitally) I can’t reveal and specific questions or example from the test, but I can offer some general thoughts and guidance for preparation.

Personally I thought this was a very difficult test, but I admit that I don’t have real world experience with a number of topics the exam covers.  I have worked fairly extensively with MVC, so I thought I would have a great shot at passing.  However, I may have mislead myself a bit.  MVC may be in the title of the exam, which I think led me to believe it would be very MVC centric, but this is not entirely true.  The exam focuses very heavily on related topics like Azure, Authentication methodologies, security, and IIS concerns like routing.  This is no secret – if you look at the official Microsoft exam guide it will tell you as much – but I just want to remind people that straight MVC (views, models, controllers, actions, filters, routing, etc.) is only part of this test.  Subconsciously it’s easy to gravitate towards studying topics you’re already familiar with.

Long story short: The exam has MVC in the name but that’s really only a fraction of the test.

Including Javascript and CSS files on Orchard Admin pages

Recently while working on an Orchard module I needed to include some script and CSS files on a custom admin page.  I initially searched Google to see how to do this but the documentation/information out there seemed a little sparse.   I ended up just digging into other modules that used similar admin pages to see how they did it.  I thought I’d share my findings – it’s not that complicated but hopefully this post will save you a few minutes of searching or troubleshooting.  This method should also work for public facing pages as well.

To include scripts or styles from your plugin, add a ResourceManifest.cs class to the root of your module project.  Inside this plugin you define the scripts and styles you need.  In my case it was as simple as this:

Orchard 1.8.1 released!

Orchard 1.8.1 was released today!  I have been eager for this release due to a number of annoying bugs in 1.8.  Overall I thought 1.8 was a great step for Orchard but I have a couple sites waiting to upgrade due to these bugs.

Most notably for me, the following bugs have been fixed:

Caching errors – This would cause problems with form validation – messages would not be displayed on postback because Orchard was serving up a cached version.  The flag to tell Orchard not to show a cached version on postback is now working again.

Lists are now working properly – the issues with paging and disappearing lists in the Admin area should now be resolved.

Media gallery issues – images not displaying due to characters and some other small points have been fixed.

Overall 1.8.1 doesn’t bring a lot of new functionality but it cleans up some of the great features of 1.8.  It feels mostly like a bug patch, but that makes sense for a minor release.

You can see the full release report and bug fix list below.  Did any of these bugs cause issues for you?

Check it out here.

Overriding and Adding Views With a NopCommerce Plugin

While recently working on a NopCommerce project I needed to override a few different views from a theme and the Nop core. I was also looking for a way to include new views without having them be compiled into the plugin DLL, meaning they are actual files on the file system that get served up in the usual MVC fashion.

I quickly came across this blog post.  It provides an overview of different ways to include views in a plugin, so thank you to Woon Cherk Lam.  The section labeled The Advanced Method – “Custom View Engine” is what we are going to expand on here.  Basically it shows you how to use a custom view engine to serve up view files and avoid compiling them into the DLL.  This is a great concept but it did not solve my specific problem.  The code in Woon’s blog post doesn’t prioritize the plugin’s views in all situations – sometimes you will want to be greedy and make sure your plugin’s views always take priority.  This is what we will look at here.

Basically, the problem (in my situation) involved one line of code from Woon’s article:

System.Web.Mvc.ViewEngines.Engines.Add(new CustomViewEngine());

The issue with this line of code is that the “Add” method appends the custom view engine to the end of the ViewEngines list, meaning it gets evaluated after the other view engines.  ASP.NET comes with two view engines out of the box – razor and the legacy aspx engine.  If either of these engines finds a view before your custom engine, those will be given priority.  Since neither of these view engines search your plugin directories, they will never find your views first.  Woon’s article shows how your custom view engine will have your plugin added as a search location, but if it is the last to search, some of your views will still never be found.

Side Note: Why doesn’t razor find views in your plugins? NopCommerce plugins are created as additional projects of the Class Library type. By default the razor view engine won’t search these types of new projects.  Razor will only search projects added as MVC Areas.

The fix for this is simple – just change the line of code above to:

System.Web.Mvc.ViewEngines.Engines.Insert(0, new CustomViewEngine());

The insert method allows you to prioritize your custom view engine by explicitly adding it at the front of the list. This is of great significance, because it means all of NopCommerce will search your plugin’s views directories first every time it looks for a view.

This idea of a custom view engine that always gives your plugin priority when searching for views is a big deal in Nop.  Woon does a good job explaining some of the benefits of this, but I want to expand and reiterate a few points on why this is valuable.

It allows you to override partial views without overriding the parent view.

This is a big deal.  In MVC, partial views are fairly static razor files that get included into a parent view.  Unlike Html.Action, Html.Partial does not hit a controller action in order to serve up a view.  This creates a problem in Nop because there is no controller method or route to override.  In order to override a partial view in Nop, you must first override the entire parent, and then change the call to the partial inside of that parent.  For example, if you want to override the download button view that exists on a product details page, you have to override the entire product template that references it.  However, with this custom view engine you need only drop your new version of the download button into the views directory of your plugin and you’re good to go.

It allows you to avoid overriding routes and mimicking folder structures.

With the custom view engine, you don’t need to override a controller method or route.  View Engines do their work after a controller method is executed. If you just want to change which view gets served up in the response and not the logic behind it, you can simply create a new view with the same name and drop it into your plugin.  

It allows you to output views as files on the file system rather than compiling them into the DLL.  

Woon covers this in his post, but I want to reiterate what a great bonus this is, especially if you are doing product development and want to allow customers to edit the HTML and CSS for a view themselves.  It also allows you to release multiple versions of the same view, such as different versions for different themes.

It allows you to not have to use fully qualified view names (no namespaces required).

This one is fairly self explanatory if you’ve read Woon’s article.  You can once again refer to all views in your plugins by their actual name, meaning your controller action methods don’t need to specify fully qualified namespaces, etc.

I have not run into any issues using the custom view engine, as long as you follow the steps Woon provides. In fact, I find this solution more stable because you don’t need to interfere with routing and controller actions as often, which results in cleaner and lighter code. Remember to include the web.config in your views folder!  This whole process makes working with views in Nop a lot easier.  It is not uncommon to create a custom view engine in MVC for very specific tasks, so I don’t consider this a hack, especially since all logic and code is contained within the plugin.

P.S. Thanks again Woon!

Free NopCommerce Slider Plugin! Check out Mega Slider, my latest pet project.

Notice: This plugin is currently unavailable while I finish migrating the site to a new platform and updating the plugin to work with newer versions of NopCommerce.  Please check back soon!  Fill out the contact form if you would like to be directly notified.

My first NopCommerce product – Mega Slider – has been released!  This was a fun product to create and I spent a lot of time on it.  It basically allows you to create content/image sliders for your NopCommerce site and place them almost anywhere you want.  I will probably be creating a tutorial soon to provide a general idea of how to build something like this.  I learned a lot from this project, particularly how to manage image uploads and the new Kendo UI in NopCommerce 3.3. The plugin includes a number of great features and customizeable settings, including:

  • Transition Time
  • Slider Cycling
  • Pause on Hover
  • Two User Control Modes (“Classic” and Panel)
  • Active Color Setting
  • Captions (Title and Description)
  • Custom Display Order
  • Assign to any zone (only supports default NopCommerce zones)
  • Full Localization Support
  • Ajax Admin functionality
  • Responsive Design

Manually Uninstalling a Broken Orchard Theme

I recently ran into a bit of a conundrum when working with an Orchard site.  I installed a theme that ended up being incompatible with my current version of Orchard, which broke the front end of my site.  To make matters worse, I somehow became logged out while experimenting with this.  If you’re like me and end up in this situation, you’ll find that there is no way to log back into your site to remove the broken theme, since you can’t access the login page.  Oops!

There is obviously a way to disable the theme through the database, which we’ll cover here.  It’s pretty simple, really.  If you don’t have access to the database, I’m not sure how you would actually fix this.  Leave a comment if you know!

Open up your database in SQL Server.  There are two tables in particular we want to look at – Settings_ShellFeatureRecord and Settings_ShellFeatureStateRecord.  Delete any rows that have the name of your theme in them. 

Enabling Advanced Search By Default in Nopcommerce

Search functionality is an essential component of any Ecommerce site.  NopCommerce ships with a variety of search features, though the out of the box functionality might not always be what you want.  By default, NopCommerce only searches product titles for the keywords a user entered into the search bar.  For many clients and customers, this is too basic.

Luckily NopCommerce also comes with a handful of advanced search features.  Users can either click on a link to go to an advanced search page, or Nop will suggest advanced search after they have already ran a query.  However, some of the advanced search functionality seems as though it should be enabled by default, such as the ability to search product descriptions and tags.

Through the NopCommerce admin area you can enable full text search as long as you have full text search installed and configured on your database.   However, this still only applies to advanced search.  What if we want to have the default searchbox widget always search in product descriptions and tags without the user having to worry about advanced search?

The solution is actually pretty simple, assuming you’re at least somewhat familiar with NopCommerce development.