PageRenderTime 41ms CodeModel.GetById 2ms app.highlight 34ms RepoModel.GetById 1ms app.codeStats 0ms

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

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