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