Free trial *Internet Service Required

Create a C# ASP.NET Application on Windows Azure with MongoDB using the MongoLab Add-On

By Eric Sedor, MongoLab

Greetings, adventurers! Welcome to MongoDB-as-a-Service. In this tutorial you will:

  1. Provision the Database - The Windows Azure Store MongoLab add-on will provide you with a MongoDB database hosted in the Windows Azure cloud and managed by MongoLab's cloud database platform.
  2. Create the App - It'll be a simple C# ASP.NET MVC app for making notes.
  3. Deploy the app - By tying a few configuration hooks together, we'll make pushing our code a breeze.
  4. Manage the database - Finally, we'll show you MongoLab's web-based database management portal where you can search, visualize, and modify data with ease.

At any time throughout this tutorial, feel free to kick off an email to support@mongolab.com if you have any questions.

Quick start

If you've already got a Windows Azure application and web site that you want to work with or you have some familiarity with the Windows Azure Store, use this section to get a quick start. Otherwise, continue to Provision the Database the Database below.

  1. Open the Windows Azure Store.
    Store
  2. Purchase the MongoLab Add-On.
    MongoLab
  3. Click your MongoLab Add-On in the Add-Ons list, and click Connection Info.
    ConnectionInfoButton
  4. Copy the MONGOLAB_URI to your clipboard.
    ConnectionInfoScreen
    This URI contains your database user name and password. Treat it as sensitive information and do not share it.
  5. Add the value to the Connection Strings list in the Configuration menu of your Windows Azure Web application:
    WebSiteConnectionStrings
  6. For Name, enter MONGOLAB_URI.
  7. For Value, paste the connection string we obtained in the previous section.
  8. Select Custom in the Type drop-down (instead of the default SQLAzure).
  9. In Visual Studio, install the Mongo C# Driver by selecting Tools > Library Package Manager > Package Manager Console. At the PM Console, type Install-Package mongocsharpdriver and press Enter.
  10. Set up a hook in your code to obtain your MongoLab connection URI from an environment variable:

    using MongoDB.Driver;  
    ...
    private string connectionString = System.Environment.GetEnvironmentVariable("CUSTOMCONNSTR_MONGOLAB_URI");
    ...
    MongoServer server = MongoServer.Create(connectionString);

    Note: Windows Azure adds the CUSTOMCONNSTR_ prefix to the originally-declared connection string, which is why the code references CUSTOMCONNSTR_MONGOLAB_URI. instead of MONGOLAB_URI.

Now, on to the full tutorial...

Provision the database

You can subscribe to an Azure-hosted, fully-managed MongoDB database in the Windows Azure Store. To do so, follow these steps: 1. Log into the Windows Azure Management Portal.

  1. Click New.
    New
  2. Select Store.
    Store
  3. Select MongoLab. You can find us in the App Services category, as well as under All.
    MongoLab
  4. Click Next.
    Next
    The MongoLab store entry displays.
    NewMongoLab
  5. Select your desired Subscription option.

  6. Enter a Name for your database. Your name can only contain alphanumeric characters, dashes, dots, and underscores. MongoLab also requires that this name be unique, so you may be asked to re-submit your request if the name is taken.

  7. Select your desired Region.

  8. Click Next.
    Next

  9. Review your store purchase information and click Purchase to confirm.
    Next
  10. The toolbar progress button provides your provisioning status.
    ProgressButton
    A success message displays when provisioning completes.
    SuccessMessage

Congratulations! MongoLab has just provisioned a MongoDB database in the Windows Azure region you selected. You now have access to our management UI and 24/7 support.

Create the app

In this section, you'll cover the creation of a C# ASP.NET Visual Studio project and walk through the use of the C# MongoDB driver to create a simple Note app. You want to be able to visit your web site, write a note, and view all the notes that have left.

You'll perform this development in Visual Studio Express 2012 for Web.

Create the project

Your sample app will make use of a Visual Studio template to get started. Be sure to use .NET Framework 4.0.

  1. Select File > New Project. The New Project dialog displays:
    NewProject
  2. Select Installed > Templates > Visual C# > Web.
  3. Select .NET Framework 4 from the .NET version drop-down menu (note: Framework 4.5 does not work at this time).

    ProjectFramework

  4. Choose ASP.NET MVC 4 Web Application.
  5. Enter mongoNotes as your Project Name. If you choose a different name, you will need to modify the code provided in throughout the tutorial.
  6. Click OK. The Project Template dialog displays:
    ProjectTemplate
  7. Select Internet Application and click OK. The project is built.
  8. Select Tools > Library Package Manager > Package Manager Console. At the PM Console, type Install-Package mongocsharpdriver and press Enter.
    PMConsole The MongoDB C# Driver is integrated with the project, and the following line is automatically added to the packages.config file:

    < package id="mongocsharpdriver" version="1.6" targetFramework="net40" / >

Add a note model

First, establish a model for Notes, with simply a date and a text content.

  1. Right-click Models in the Solution Explorer and select Add > Class. Call this new class Note.cs.
  2. Replace the auto-generated code for this class with the following:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using MongoDB.Bson.Serialization.Attributes;
    using MongoDB.Bson.Serialization.IdGenerators;
    using MongoDB.Bson;
    
    
    namespace mongoNotes.Models
    {
        public class Note
        {
            public Note()
            {
                Date = DateTime.UtcNow;
            }
    
    
        private DateTime date;
    
    
        [BsonId(IdGenerator = typeof(CombGuidGenerator))]
        public Guid Id { get; set; }
    
    
        [BsonElement("Note")]
        public string Text { get; set; }
    
    
        [BsonElement("Date")]
        public DateTime Date {
            get { return date.ToLocalTime(); }
            set { date = value;}
        }
    }
    
    
    }

Add a data access layer

It's important that you establish a means of accessing MongoDB to retrieve and save the notes. Your data access layer will make use of the Note model and be tied into your HomeController later on.

  1. Right-click the mongoNotes project in the Solution Explorer and select Add > New Folder. Call the folder DAL.
  2. Right-click DAL in the Solution Explorer and select Add > Class. Call this new class Dal.cs.
  3. Replace the auto-generated code for this class with the following:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using mongoNotes.Models;
    using MongoDB.Driver;
    using System.Configuration;
    
    
    namespace mongoNotes
    {
        public class Dal : IDisposable
        {
            private MongoServer mongoServer = null;
            private bool disposed = false;
    
    
        private string connectionString = System.Environment.GetEnvironmentVariable("CUSTOMCONNSTR_MONGOLAB_URI");
    
    
        private string dbName = "myMongoApp";
        private string collectionName = "Notes";
    
    
        // Default constructor.        
        public Dal()
        {
        }
    
    
        public List&lt;Note&gt; GetAllNotes()
        {
            try
            {
                MongoCollection&lt;Note&gt; collection = GetNotesCollection();
                return collection.FindAll().ToList&lt;Note&gt;();
            }
            catch (MongoConnectionException)
            {
                return new List&lt;Note&gt;();
            }
        }
    
    
        // Creates a Note and inserts it into the collection in MongoDB.
        public void CreateNote(Note note)
        {
            MongoCollection&lt;Note&gt; collection = getNotesCollectionForEdit();
            try
            {
                collection.Insert(note, SafeMode.True);
            }
            catch (MongoCommandException ex)
            {
                string msg = ex.Message;
            }
        }
    
    
        private MongoCollection&lt;Note&gt; GetNotesCollection()
        {
            MongoServer server = MongoServer.Create(connectionString);
            MongoDatabase database = server[dbName];
            MongoCollection&lt;Note&gt; noteCollection = database.GetCollection&lt;Note&gt;(collectionName);
            return noteCollection;
        }
    
    
        private MongoCollection&lt;Note&gt; getNotesCollectionForEdit()
        {
            MongoServer server = MongoServer.Create(connectionString);
            MongoDatabase database = server[dbName];
            MongoCollection&lt;Note&gt; notesCollection = database.GetCollection&lt;Note&gt;(collectionName);
            return notesCollection;
        }
    
    
        # region IDisposable
    
    
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }
    
    
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (mongoServer != null)
                    {
                        this.mongoServer.Disconnect();
                    }
                }
            }
    
    
            this.disposed = true;
        }
    
    
        # endregion
    }
    
    
    }
  4. Note the following code above:

    private string connectionString = System.Environment.GetEnvironmentVariable("CUSTOMCONNSTR_MONGOLAB_URI");
    private string dbName = "myMongoApp";

    Here, you access an environment variable that you'll configure later. If you have a local mongo instance running for development purposes, you may want to temporarily set this value to "localhost".

    Also set your database name. Specifically, set the dbName value to the name you entered when you provisioned the MongoLab Add-On.

  5. Finally, examine the following code in GetNotesCollection():

    MongoServer server = MongoServer.Create(connectionString);
    MongoDatabase database = server[dbName];
    MongoCollection<Note> notesCollection = database.GetCollection<Note>

    There's nothing to change here; Just be aware that this is how you get a MongoCollection object for performing inserts, updates, and queries, such as the following in GetAllNotes():

    collection.FindAll().ToList<Note>();

For more information about leveraging the C# MongoDB driver, check out the CSharp Driver QuickStart at mongodb.org.

Add a create view

Now you'll add a view for creating a new note.

  1. Right-click the Views > Home entry in the Solution Explorer and select Add > View. Call this new view Create and click Add.
  2. Replace the auto-generated code for this view (Create.cshtml) with the following:

    @model mongoNotes.Models.Note
    
    
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    
    
    @using (Html.BeginForm("Create", "Home")) {
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>New Note</legend>
            <h3>New Note</h3>       
            <div class="editor-label">
                @Html.LabelFor(model => model.Text)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Text)
            </div>
           <p>
                <input type="submit" value="Create" />
           </p>
       </fieldset>
    }

Modify index.cshtml

Next, drop in a simple layout for viewing and creating notes on your web site.

  1. Open Index.cshtml under Views > Home and replace its contents with the following:

    @model IEnumerable<mongoNotes.Models.Note>
    
    
    @{
        ViewBag.Title = "Notes";
    }
    
    
    <h2>My Notes</h2>
    
    
    <table border="1">
        <tr>
            <th>Date</th>
            <th>Note Text</th>      
        </tr>
    
    
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Date)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Text)
            </td>       
        </tr>
    }
    
    
    </table>
    <div>  @Html.Partial("Create", new mongoNotes.Models.Note())</div>

Modify HomeController.cs

Finally, your HomeController needs to instantiate your data access layer and apply it against your views.

  1. Open HomeController.cs under Controllers in the Solution Explorer and replace its contents with the following:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using mongoNotes.Models;
    using System.Configuration;
    
    
    namespace mongoNotes.Controllers
    {
        public class HomeController : Controller, IDisposable
        {
            private Dal dal = new Dal();
            private bool disposed = false;
            //
            // GET: /Task/
    
    
        public ActionResult Index()
        {
            return View(dal.GetAllNotes());
        }
    
    
        //
        // GET: /Task/Create
    
    
        public ActionResult Create()
        {
            return View();
        }
    
    
        //
        // POST: /Task/Create
    
    
        [HttpPost]
        public ActionResult Create(Note note)
        {
            try
            {
                dal.CreateNote(note);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    
    
        public ActionResult About()
        {
            return View();
        }
    
    
        # region IDisposable
    
    
        new protected void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }
    
    
        new protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    this.dal.Dispose();
                }
            }
    
    
            this.disposed = true;
        }
    
    
        # endregion
    
    
    }
    
    
    }

Deploy the app

Now that the application has been developed, it's time to create a Windows Azure Web Site to host it, configure that web site, and deploy the code. Central to this section is the use of the MongoDB connection string (URI). You're going to configure an environment variable in your web site with this URI to keep the URI separate from your code. You should treat the URI as sensitive information as it contains credentials to connect to your database.

Create a New Web Site and Obtain the Publish Settings File

Creating a web site in Windows Azure is very easy, especially as Windows Azure auto-generates a publish profile for Visual Studio.

  1. In the Windows Azure portal, click New.
    New
  2. Select Compute > Web Site > Quick Create.
    CreateSite
  3. Enter a URL prefix. Choose a name you prefer, but keep in mind this must be unique ('mongoNotes' will likely not be available).
  4. Click Create Web Site.
  5. When the web site creation completes, click the web site name in the web site list. The web site dashboard displays.
    WebSiteDashboard
  6. Click Download publish profile under quick glance, and save the .PublishSettings file to a directory of your chice.
    DownloadPublishProfile

Get the MongoLab connection string

When you provision a MongoLab database, MongoLab transmits a connection URI to Windows Azure in MongoDB's standard connection string format. This value is used to initiate a MongoDB connection through your choice of MongoDB driver. For more information about connection strings, see Connections at mongodb.org. This URI contains your database user name and password. Treat it as sensitive information and do not share it.

You can retrieve this URI in the Windows Azure Portal using the following steps:

  1. Select Add-ons.
    AddonsButton
  2. Locate your MongoLab service in your add-on list.
    MongolabEntry
  3. Cick the name of your add-on to reach the add-on page.

  4. Click Connection Info.
    ConnectionInfoButton
    Your MongoLab URI displays:
    ConnectionInfoScreen

  5. Click the clipboard button to the right of the MONGOLAB_URI value to copy the full value to the clipboard.

Add the connection string to the web site's environment variables

While it's possible to paste a MongoLab URI into your code, we recommend configuring it in the environment for ease of management. This way, if the URI changes, you can update it through the Windows Azure Portal without going to the code.

  1. In the Windows Azure Portal, select Web Sites.

  2. Click the name of the web site in the web site list.
    WebSiteEntry
    The Web Site Dashboard displays.

  3. Click Configure in the menu bar.
    WebSiteDashboardConfig

  4. Scroll down to the Connection Strings section.
    WebSiteConnectionStrings
  5. For Name, enter MONGOLAB_URI.

  6. For Value, paste the connection string we obtained in the previous section.

  7. Select Custom in the Type drop-down (instead of the default SQLAzure).

  8. Click Save on the toolbar.
    SaveWebSite

    Note: Windows Azure adds the CUSTOMCONNSTR_ prefix to this variable, which is why the code above references CUSTOMCONNSTR_MONGOLAB_URI.

Publish the web site

  1. In Visual Studio, right-click the mongoNotes project in the Solution Explorer and select Publish. The Publish dialog displays:
    Publish
  2. Click Import and select the .PublishSettings file from your chosen download directory. This file automatically populates the values in the Publish dialog.
  3. Click Validate Connection to test the file.
  4. Once the validation succeeds, click Publish. Once publishing is complete, a new browser tab opens and the web site displays.
  5. Enter some note text, click Create and see the results!
    HelloMongoAzure

Manage the database

At any time after provisioning a MongoLab database, you can access the MongoLab web UI for managing that database. We offer convenient single-sign-on (SSO) access through the Windows Azure Management Portal. You can use the MongoLab UI to perform most database tasks, such as inserting and querying for documents, obtaining database statistics, and running useful database commands. To learn more about the MongoLab UI, visit our support page and our blog.

To access the MongoLab UI, do the following:

  1. Select Add-ons.
    AddonsButton
  2. Locate your MongoLab service in your list of add-ons.
    MongolabEntry
  3. Cick the name of your add-on to reach the add-on page.

  4. Click Manage.
    ManageButton
    A new browser tab opens, displaying the MongoLab database home page:
    DbHome

From here you can select a specific collection and drill down to individual documents. Log out when you are finished.

Congratulations! You've just launched a C# ASP.NET application backed by a MongoLab-hosted MongoDB database! Now that you have a MongoLab database, you can contact support@mongolab.com with any questions or concerns about your database, or for help with MongoDB or the C# driver itself. Good luck out there!

Rss Newsletter