PageRenderTime 60ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/DevCenter/dotNET/Tutorials/tutorial-mongolab-mongodb-csharp-application.md

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