PageRenderTime 210ms CodeModel.GetById 2ms app.highlight 199ms RepoModel.GetById 1ms app.codeStats 1ms

/articles/store-mongolab-web-sites-dotnet-store-data-mongodb.md

https://github.com/deaquino/azure-content
Markdown | 449 lines | 355 code | 94 blank | 0 comment | 0 complexity | 8e227214d29d34b6b7c963ab098cd734 MD5 | raw file
  1<properties linkid="develop-net-tutorials-website-with-mongodb-mongolab" urlDisplayName="Website with MongoDB on MongoLab" pageTitle="Create a Website that uses MongoDB on MongoLab (.NET)" metaKeywords="" description="Learn how to create an Azure website that stores data in MongoDB hosted by MongoLab." metaCanonical="" services="web-sites" documentationCenter=".NET" title="Create a C# ASP.NET Application on Azure with MongoDB using the MongoLab Add-On" authors="eric@mongolab.com" solutions="" manager="" editor="mollybos" />
  2
  3<tags ms.service="web-sites" ms.workload="web" ms.tgt_pltfrm="na" ms.devlang="dotnet" ms.topic="article" ms.date="01/01/1900" ms.author="eric@mongolab.com" />
  4
  5
  6
  7# Create a C# ASP.NET Application on Azure with MongoDB using the MongoLab Add-On
  8
  9<p><em>By Eric Sedor, MongoLab</em></p>
 10
 11Greetings, adventurers! Welcome to MongoDB-as-a-Service. In this tutorial, you will:
 12
 131. [Provision the Database][provision] - The Azure Store [MongoLab](http://mongolab.com) add-on will provide you with a MongoDB database hosted in the Azure cloud and managed by MongoLab's cloud database platform.
 141. [Create the App][create] - It'll be a simple C# ASP.NET MVC app for making notes.
 151. [Deploy the app][deploy] - By tying a few configuration hooks together, we'll make pushing our code a breeze.
 161. [Manage the database][manage] - Finally, we'll show you MongoLab's web-based database management portal where you can search, visualize, and modify data with ease.
 17
 18At any time throughout this tutorial, feel free to kick off an email to [support@mongolab.com](mailto:support@mongolab.com) if you have any questions.
 19
 20## Quick start
 21If you've already got an Azure application and website that you want to work with or you have some familiarity with the Azure Store, use this section to get a quick start. Otherwise, continue to [Provision the Database][provision] below.
 22 
 231. Open the Azure Store.  
 24![Store][button-store]
 251. Purchase the MongoLab Add-On.  
 26![MongoLab][entry-mongolab]
 271. Click your MongoLab Add-On in the Add-Ons list, and click **Connection Info**.  
 28![ConnectionInfoButton][button-connectioninfo]  
 291. Copy the MONGOLAB_URI to your clipboard.  
 30![ConnectionInfoScreen][screen-connectioninfo]  
 31**This URI contains your database user name and password.  Treat it as sensitive information and do not share it.**
 321. Add the value to the Connection Strings list in the Configuration menu of your Azure Web application:  
 33![WebSiteConnectionStrings][focus-website-connectinfo]
 341. For **Name**, enter MONGOLAB\_URI.
 351. For **Value**, paste the connection string we obtained in the previous section.
 361. Select **Custom** in the Type drop-down (instead of the default **SQLAzure**).
 371. 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**.
 381. Set up a hook in your code to obtain your MongoLab connection URI from an environment variable:
 39
 40        using MongoDB.Driver;  
 41        ...
 42        private string connectionString = System.Environment.GetEnvironmentVariable("CUSTOMCONNSTR_MONGOLAB_URI");
 43        ...
 44        MongoUrl url = new MongoUrl(connectionString);
 45        MongoClient client = new MongoClient(url);
 46Note: Azure adds the **CUSTOMCONNSTR\_** prefix to the originally-declared connection string, which is why the code references **CUSTOMCONNSTR\_MONGOLAB\_URI.** instead of **MONGOLAB\_URI**.
 47
 48Now, on to the full tutorial...
 49
 50<h2><a name="provision"></a>Provision the database</h2>
 51
 52[WACOM.INCLUDE [howto-provision-mongolab](../includes/howto-provision-mongolab.md)]
 53
 54<h2><a name="create"></a>Create the app</h2>
 55
 56In 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 website, write a note, and view all the notes that have left.
 57
 58You'll perform this development in Visual Studio Express 2012 for Web.
 59
 60### Create the project
 61Your sample app will make use of a Visual Studio template to get started. Be sure to use .NET Framework 4.0.
 62
 631. Select **File > New Project**. The New Project dialog displays:    
 64![NewProject][dialog-mongolab-csharp-newproject]
 651. Select **Installed > Templates > Visual C# > Web**.
 661. Select **.NET Framework 4** from the .NET version drop-down menu (*note: Framework 4.5 does not work at this time*).
 67
 68    ![ProjectFramework][dotNet-framework-four]
 691. Choose **ASP.NET MVC 4 Web Application**.  
 701. Enter _mongoNotes_ as your **Project Name**. If you choose a different name, you will need to modify the code provided in throughout the tutorial.
 711. Click **OK**. The Project Template dialog displays:  
 72![ProjectTemplate][dialog-mongolab-csharp-projecttemplate]
 731. Select **Internet Application** and click **OK**. The project is built.
 741. Select **Tools > Library Package Manager > Package Manager Console**. At the PM Console, type **Install-Package mongocsharpdriver** and press **Enter**.  
 75![PMConsole][focus-mongolab-csharp-pmconsole] 
 76The MongoDB C# Driver is integrated with the project, and the following line is automatically added to the _packages.config_ file:
 77
 78        < package id="mongocsharpdriver" version="1.8" targetFramework="net40" / >
 79
 80### Add a note model
 81First, establish a model for Notes, with simply a date and a text content.
 82
 831. Right-click **Models** in the Solution Explorer and select **Add > Class**. Call this new class *Note.cs*.
 841. Replace the auto-generated code for this class with the following:  
 85
 86        using System;
 87        using System.Collections.Generic;
 88        using System.Linq;
 89        using System.Web;
 90        using MongoDB.Bson.Serialization.Attributes;
 91        using MongoDB.Bson.Serialization.IdGenerators;
 92        using MongoDB.Bson;
 93                
 94        namespace mongoNotes.Models
 95        {
 96            public class Note
 97            {
 98                public Note()
 99                {
100                    Date = DateTime.UtcNow;
101                }
102                
103                private DateTime date;
104        
105                [BsonId(IdGenerator = typeof(CombGuidGenerator))]
106                public Guid Id { get; set; }
107        
108                [BsonElement("Note")]
109                public string Text { get; set; }
110        
111                [BsonElement("Date")]
112                public DateTime Date {
113                    get { return date.ToLocalTime(); }
114                    set { date = value;}
115                }
116            }
117        }
118
119### Add a data access layer
120It'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.
121
1221. Right-click the **mongoNotes** project in the Solution Explorer and select **Add > New Folder**. Call the folder **DAL**.
1231. Right-click **DAL** in the Solution Explorer and select **Add > Class**. Call this new class *Dal.cs*.
1241. Replace the auto-generated code for this class with the following:  
125
126        using System;
127        using System.Collections.Generic;
128        using System.Linq;
129        using System.Web;
130        using mongoNotes.Models;
131        using MongoDB.Driver;
132        using System.Configuration;
133
134        namespace mongoNotes
135        {
136            public class Dal : IDisposable
137            {
138                private MongoServer mongoServer = null;
139                private bool disposed = false;
140        
141                private string connectionString = System.Environment.GetEnvironmentVariable("CUSTOMCONNSTR_MONGOLAB_URI");
142                MongoUrl url = new MongoUrl(connectionString);
143        
144                private string dbName = "myMongoApp";
145                private string collectionName = "Notes";
146        
147                // Default constructor.        
148                public Dal()
149                {
150                }
151           
152                public List<Note> GetAllNotes()
153                {
154                    try
155                    {
156                        MongoCollection<Note> collection = GetNotesCollection();
157                        return collection.FindAll().ToList<Note>();
158                    }
159                    catch (MongoConnectionException)
160                    {
161                        return new List<Note>();
162                    }
163                }
164        
165                // Creates a Note and inserts it into the collection in MongoDB.
166                public void CreateNote(Note note)
167                {
168                    MongoCollection<Note> collection = getNotesCollectionForEdit();
169                    try
170                    {
171                        collection.Insert(note);
172                    }
173                    catch (MongoCommandException ex)
174                    {
175                        string msg = ex.Message;
176                    }
177                }
178        
179                private MongoCollection<Note> GetNotesCollection()
180                {
181                    MongoClient client = new MongoClient(url);
182                    mongoServer = client.GetServer();
183                    MongoDatabase database = mongoServer.GetDatabase(dbName);
184                    MongoCollection<Note> noteCollection = database.GetCollection<Note>(collectionName);
185                    return noteCollection;
186                }
187        
188                private MongoCollection<Note> getNotesCollectionForEdit()
189                {
190                    MongoClient client = new MongoClient(url);
191                    mongoServer = client.GetServer();
192                    MongoDatabase database = mongoServer.GetDatabase(dbName);
193                    MongoCollection<Note> notesCollection = database.GetCollection<Note>(collectionName);
194                    return notesCollection;
195                }
196        
197                # region IDisposable
198        
199                public void Dispose()
200                {
201                    this.Dispose(true);
202                    GC.SuppressFinalize(this);
203                }
204        
205                protected virtual void Dispose(bool disposing)
206                {
207                    if (!this.disposed)
208                    {
209                        if (disposing)
210                        {
211                            if (mongoServer != null)
212                            {
213                                this.mongoServer.Disconnect();
214                            }
215                        }
216                    }
217        
218                    this.disposed = true;
219                }
220        
221                # endregion
222            }
223        }
2241. Note the following code above:  
225            
226        private string connectionString = System.Environment.GetEnvironmentVariable("CUSTOMCONNSTR_MONGOLAB_URI");
227        private string dbName = "myMongoApp";  
228Here, 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".  
229  
230  Also set your database name. Specifically, set the **dbName** value to the name you entered when you provisioned the MongoLab Add-On.
2311. Finally, examine the following code in **GetNotesCollection()**:  
232
233        MongoClient client = new MongoClient(url);
234        mongoServer = client.GetServer();
235        MongoDatabase database = mongoServer.GetDatabase(dbName);
236        MongoCollection<Note> noteCollection = database.GetCollection<Note>(collectionName);
237  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()**:  
238
239        collection.FindAll().ToList<Note>();
240
241For more information about leveraging the C# MongoDB driver, check out the [CSharp Driver QuickStart](http://www.mongodb.org/display/DOCS/CSharp+Driver+Quickstart "CSharp Driver Quickstart") at mongodb.org.
242
243### Add a create view
244Now you'll add a view for creating a new note.
245
2461. Right-click the **Views > Home** entry in the Solution Explorer and select **Add > View**. Call this new view **Create** and click **Add**.
2471. Replace the auto-generated code for this view (**Create.cshtml**) with the following:  
248
249        @model mongoNotes.Models.Note
250        
251        <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
252        <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
253        <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
254        
255        @using (Html.BeginForm("Create", "Home")) {
256            @Html.ValidationSummary(true)
257            <fieldset>
258                <legend>New Note</legend>
259                <h3>New Note</h3>       
260                <div class="editor-label">
261                    @Html.LabelFor(model => model.Text)
262                </div>
263                <div class="editor-field">
264                    @Html.EditorFor(model => model.Text)
265                </div>
266               <p>
267                    <input type="submit" value="Create" />
268               </p>
269           </fieldset>
270        }
271
272### Modify index.cshtml
273Next, drop in a simple layout for viewing and creating notes on your website.
274
2751. Open **Index.cshtml** under **Views > Home** and replace its contents with the following:  
276
277        @model IEnumerable<mongoNotes.Models.Note>
278        
279        @{
280            ViewBag.Title = "Notes";
281        }
282        
283        <h2>My Notes</h2>
284
285        <table border="1">
286            <tr>
287                <th>Date</th>
288                <th>Note Text</th>      
289            </tr>
290        
291        @foreach (var item in Model) {
292            <tr>
293                <td>
294                    @Html.DisplayFor(modelItem => item.Date)
295                </td>
296                <td>
297                    @Html.DisplayFor(modelItem => item.Text)
298                </td>       
299            </tr>
300        }
301        
302        </table>
303        <div>  @Html.Partial("Create", new mongoNotes.Models.Note())</div>
304
305### Modify HomeController.cs
306Finally, your HomeController needs to instantiate your data access layer and apply it against your views.
307
3081. Open **HomeController.cs** under **Controllers** in the Solution Explorer and replace its contents with the following:  
309
310        using System;
311        using System.Collections.Generic;
312        using System.Linq;
313        using System.Web;
314        using System.Web.Mvc;
315        using mongoNotes.Models;
316        using System.Configuration;
317        
318        namespace mongoNotes.Controllers
319        {
320            public class HomeController : Controller, IDisposable
321            {
322                private Dal dal = new Dal();
323                private bool disposed = false;
324                //
325                // GET: /Task/
326        
327                public ActionResult Index()
328                {
329                    return View(dal.GetAllNotes());
330                }
331        
332                //
333                // GET: /Task/Create
334        
335                public ActionResult Create()
336                {
337                    return View();
338                }
339        
340                //
341                // POST: /Task/Create
342        
343                [HttpPost]
344                public ActionResult Create(Note note)
345                {
346                    try
347                    {
348                        dal.CreateNote(note);
349                        return RedirectToAction("Index");
350                    }
351                    catch
352                    {
353                        return View();
354                    }
355                }
356        
357                public ActionResult About()
358                {
359                    return View();
360                }
361        
362                # region IDisposable
363        
364                new protected void Dispose()
365                {
366                    this.Dispose(true);
367                    GC.SuppressFinalize(this);
368                }
369        
370                new protected virtual void Dispose(bool disposing)
371                {
372                    if (!this.disposed)
373                    {
374                        if (disposing)
375                        {
376                            this.dal.Dispose();
377                        }
378                    }
379        
380                    this.disposed = true;
381                }
382        
383                # endregion
384        
385            }
386        }
387    
388    
389<h2><a name="deploy"></a>Deploy the app</h2>
390
391Now that the application has been developed, it's time to create an Azure Website to host it, configure that website, 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 website 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.
392
393### Create a New Website and Obtain the Publish Settings File
394Creating a website in Azure is very easy, especially as Azure auto-generates a publish profile for Visual Studio.
395
3961. In the Azure portal, click **New**.  
397![New][button-new]
3981. Select **Compute > Website > Quick Create**.  
399![CreateSite][screen-mongolab-newwebsite]
4001. Enter a URL prefix. Choose a name you prefer, but keep in mind this must be unique ('mongoNotes' will likely not be available).
4011. Click **Create Website**.
4021. When the website creation completes, click the website name in the website list. The website dashboard displays.  
403![WebSiteDashboard][screen-mongolab-websitedashboard]
4041. Click **Download publish profile** under **quick glance**, and save the .PublishSettings file to a directory of your chice.  
405![DownloadPublishProfile][button-website-downloadpublishprofile]
406
407### Get the MongoLab connection string
408
409[WACOM.INCLUDE [howto-get-connectioninfo-mongolab](../includes/howto-get-connectioninfo-mongolab.md)]
410
411### Add the connection string to the website's environment variables
412
413[WACOM.INCLUDE [howto-save-connectioninfo-mongolab](../includes/howto-save-connectioninfo-mongolab.md)]
414
415### Publish the website
4161. In Visual Studio, right-click the **mongoNotes** project in the Solution Explorer and select **Publish**. The Publish dialog displays:  
417![Publish][dialog-mongolab-vspublish]
4181. Click **Import** and select the .PublishSettings file from your chosen download directory. This file automatically populates the values in the Publish dialog.
4191. Click **Validate Connection** to test the file.
4201. Once the validation succeeds, click **Publish**. Once publishing is complete, a new browser tab opens and the website displays.
4211. Enter some note text, click **Create** and see the results!  
422![HelloMongoAzure][screen-mongolab-sampleapp]
423
424<h2><a name="manage"></a>Manage the database</h2>
425
426[WACOM.INCLUDE [howto-access-mongolab-ui](../includes/howto-access-mongolab-ui.md)]
427
428Congratulations! 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](mailto: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!
429
430[screen-mongolab-sampleapp]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/screen-mongolab-sampleapp.png
431[dialog-mongolab-vspublish]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/dialog-mongolab-vspublish.png
432[button-website-downloadpublishprofile]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/button-website-downloadpublishprofile.png
433[screen-mongolab-websitedashboard]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/screen-mongolab-websitedashboard.png
434[screen-mongolab-newwebsite]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/screen-mongolab-newwebsite.png
435[button-new]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/button-new.png
436[dialog-mongolab-csharp-newproject]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/dialog-mongolab-csharp-newproject.png
437[dialog-mongolab-csharp-projecttemplate]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/dialog-mongolab-csharp-projecttemplate.png
438[focus-mongolab-csharp-pmconsole]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/focus-mongolab-csharp-pmconsole.png
439[button-store]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/button-store.png
440[entry-mongolab]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/entry-mongolab.png 
441[button-connectioninfo]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/button-connectioninfo.png
442[screen-connectioninfo]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/dialog-mongolab_connectioninfo.png
443[dotNet-framework-four]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/focus-dotNet-Framework4-mongolab.png
444[focus-website-connectinfo]: ./media/partner-mongodb-web-sites-dotnet-use-mongolab/focus-mongolab-websiteconnectionstring.png
445[provision]: #provision
446[create]: #create
447[deploy]: #deploy
448[manage]: #manage
449