PageRenderTime 35ms CodeModel.GetById 8ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://github.com/deaquino/azure-content
Markdown | 517 lines | 376 code | 141 blank | 0 comment | 0 complexity | 389abfe510f58c121eaf641db733766e MD5 | raw file
  1. <properties linkid="develop-dotnet-website-with-mongodb-vm" urlDisplayName="Website with MongoDB VM" pageTitle=".NET website with MongoDB on a virtual machine - Azure" metaKeywords="Azure Git ASP.NET MongoDB, Git .NET, Git MongoDB, ASP.NET MongoDB, Azure MongoDB, Azure ASP.NET, Azure tutorial" description="A tutorial that teaches you how to use Git to deploy an ASP.NET app to an Azure website connected to MongoDB on a virtual machine." metaCanonical="" services="web-sites,virtual-machines" documentationCenter=".NET" title="Create an Azure website that connects to MongoDB running on a virtual machine in Azure" authors="" solutions="" manager="" editor="" />
  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="" />
  3. # Create an Azure website that connects to MongoDB running on a virtual machine in Azure
  4. Using Git, you can deploy an ASP.NET application to an Azure website. In this tutorial, you will build a simple front-end ASP.NET MVC task list application that connects to a MongoDB database running in a virtual machine in Azure. [MongoDB][MongoDB] is a popular open source, high performance NoSQL database. After running and testing the ASP.NET application on your development computer, you will upload the application to an Azure website using Git.
  5. [WACOM.INCLUDE [create-account-and-websites-and-vms-note](../includes/create-account-and-websites-and-vms-note.md)]
  6. ##Overview##
  7. In this tutorial you will:
  8. - [Create a virtual machine and install MongoDB](#virtualmachine)
  9. - [Create and run the My Task List ASP.NET application on your development computer](#createapp)
  10. - [Create an Azure web site](#createwebsite)
  11. - [Deploy the ASP.NET application to the web site using Git](#deployapp)
  12. ##Background knowledge##
  13. Knowledge of the following is useful for this tutorial, though not required:
  14. * The C# driver for MongoDB. For more information on developing C# applications against MongoDB, see the MongoDB [CSharp Language Center][MongoC#LangCenter].
  15. * The ASP .NET web application framework. You can learn all about it at the [ASP.net web site][ASP.NET].
  16. * The ASP .NET MVC web application framework. You can learn all about it at the [ASP.NET MVC web site][MVCWebSite].
  17. * Azure. You can get started reading at [Azure][WindowsAzure].
  18. ##Preparation##
  19. In this section you will learn how to create a virtual machine in Azure and install MongoDB, and set up your development environment.
  20. <a id="virtualmachine"></a>
  21. ###Create a virtual machine and install MongoDB###
  22. This tutorial assumes you have created a virtual machine in Azure. After creating the virtual machine you need to install MongoDB on the virtual machine:
  23. * To create a Windows virtual machine and install MongoDB, see [Install MongoDB on a virtual machine running Windows Server in Azure][InstallMongoOnWindowsVM].
  24. * Alternatively, to create a Linux virtual machine and install MongoDB, see [Install MongoDB on a virtual machine running CentOS Linux in Azure][InstallMongoOnCentOSLinuxVM].
  25. After you have created the virtual machine in Azure and installed MongoDB, be sure to remember the DNS name of the virtual machine ("testlinuxvm.cloudapp.net", for example) and the external port for MongoDB that you specified in the endpoint. You will need this information later in the tutorial.
  26. ### Install Visual Studio###
  27. Start by installing and running [Visual Studio Express 2013 for Web] [VSEWeb] or [Visual Studio 2013] [VSUlt].
  28. Visual Studio is an IDE, or integrated development environment. Just like you use Microsoft Word to write documents, you'll use an IDE to create applications. This tutorial uses Microsoft Visual Studio 2013, but you can use Microsoft Visual Studio Express 2013, which is a free version of Microsoft Visual Studio.
  29. <a id="createapp"></a>
  30. ##Create and run the My Task List ASP.NET application on your development computer##
  31. In this section you will create an ASP.NET application called "My Task List" by using Visual Studio. You will run the application locally, but it will connect to your virtual machine on Azure and use the MongoDB instance that you created there.
  32. ###Create the application###
  33. In Visual Studio, click **New Project**.
  34. ![Start Page New Project][StartPageNewProject]
  35. In the **New Project** window, in the left pane, select **Visual C#**, and then select **Web**. In the middle pane, select **ASP.NET Web Application**. At the bottom, name your project "MyTaskListApp," and then click **OK**.
  36. ![New Project Dialog][NewProjectMyTaskListApp]
  37. In the **New ASP.NET Project** dialog box, select **MVC**, and then click **OK**.
  38. ![Select MVC Template][VS2013SelectMVCTemplate]
  39. After the project completes, the default page created by the template appears.
  40. ![Default ASP.NET MVC Application][VS2013DefaultMVCApplication]
  41. ###Install the MongoDB C# driver
  42. MongoDB offers client-side support for C# applications through a driver, which you need to install on your local development computer. The C# driver is available through NuGet.
  43. To install the MongoDB C# driver:
  44. 1. In **Solution Explorer**, under the **MyTaskListApp** project, right-click **References** and select **Manage NuGetPackages**.
  45. ![Manage NuGet Packages][VS2013ManageNuGetPackages]
  46. 2. In the **Manage NuGet Packages** window, in the left pane, click **Online**. In the **Search Online** box on the right, type "mongocsharpdriver". Click **Install** to install the driver.
  47. ![Search for MongoDB C# Driver][SearchforMongoDBCSharpDriver]
  48. 3. Click **I Accept** to accept the 10gen, Inc. license terms.
  49. 4. Click **Close** after the driver has installed.
  50. ![MongoDB C# Driver Installed][MongoDBCsharpDriverInstalled]
  51. The MongoDB C# driver is now installed. References to the **MongoDB.Driver.dll** and **MongoDB.Bson.dll** libraries have been added to the project.
  52. ![MongoDB C# Driver References][MongoDBCSharpDriverReferences]
  53. ###Add a model###
  54. In **Solution Explorer**, right-click the *Models* folder and **Add** a new **Class** and name it *TaskModel.cs*. In *TaskModel.cs*, replace the existing code with the following code:
  55. using System;
  56. using System.Collections.Generic;
  57. using System.Linq;
  58. using System.Web;
  59. using MongoDB.Bson.Serialization.Attributes;
  60. using MongoDB.Bson.Serialization.IdGenerators;
  61. using MongoDB.Bson;
  62. namespace MyTaskListApp.Models
  63. {
  64. public class MyTask
  65. {
  66. [BsonId(IdGenerator = typeof(CombGuidGenerator))]
  67. public Guid Id { get; set; }
  68. [BsonElement("Name")]
  69. public string Name { get; set; }
  70. [BsonElement("Category")]
  71. public string Category { get; set; }
  72. [BsonElement("Date")]
  73. public DateTime Date { get; set; }
  74. [BsonElement("CreatedDate")]
  75. public DateTime CreatedDate { get; set; }
  76. }
  77. }
  78. ###Add the data access layer###
  79. In **Solution Explorer**, right-click the *MyTaskListApp* project and **Add** a **New Folder** named *DAL*. Right-click the *DAL* folder and **Add** a new **Class**. Name the class file *Dal.cs*. In *Dal.cs*, replace the existing code with the following code:
  80. using System;
  81. using System.Collections.Generic;
  82. using System.Linq;
  83. using System.Web;
  84. using MyTaskListApp.Models;
  85. using MongoDB.Driver;
  86. using System.Configuration;
  87. namespace MyTaskListApp
  88. {
  89. public class Dal : IDisposable
  90. {
  91. private MongoServer mongoServer = null;
  92. private bool disposed = false;
  93. // To do: update the connection string with the DNS name
  94. // or IP address of your server.
  95. //For example, "mongodb://testlinux.cloudapp.net"
  96. private string connectionString = "mongodb://<vm-dns-name>";
  97. // This sample uses a database named "Tasks" and a
  98. //collection named "TasksList". The database and collection
  99. //will be automatically created if they don't already exist.
  100. private string dbName = "Tasks";
  101. private string collectionName = "TasksList";
  102. // Default constructor.
  103. public Dal()
  104. {
  105. }
  106. // Gets all Task items from the MongoDB server.
  107. public List<MyTask> GetAllTasks()
  108. {
  109. try
  110. {
  111. MongoCollection<MyTask> collection = GetTasksCollection();
  112. return collection.FindAll().ToList<MyTask>();
  113. }
  114. catch (MongoConnectionException)
  115. {
  116. return new List<MyTask >();
  117. }
  118. }
  119. // Creates a Task and inserts it into the collection in MongoDB.
  120. public void CreateTask(MyTask task)
  121. {
  122. MongoCollection<MyTask> collection = GetTasksCollectionForEdit();
  123. try
  124. {
  125. collection.Insert(task, SafeMode.True);
  126. }
  127. catch (MongoCommandException ex)
  128. {
  129. string msg = ex.Message;
  130. }
  131. }
  132. private MongoCollection<MyTask> GetTasksCollection()
  133. {
  134. MongoServer server = MongoServer.Create(connectionString);
  135. MongoDatabase database = server[dbName];
  136. MongoCollection<MyTask> todoTaskCollection = database.GetCollection<MyTask>(collectionName);
  137. return todoTaskCollection;
  138. }
  139. private MongoCollection<MyTask> GetTasksCollectionForEdit()
  140. {
  141. MongoServer server = MongoServer.Create(connectionString);
  142. MongoDatabase database = server[dbName];
  143. MongoCollection<MyTask> todoTaskCollection = database.GetCollection<MyTask>(collectionName);
  144. return todoTaskCollection;
  145. }
  146. # region IDisposable
  147. public void Dispose()
  148. {
  149. this.Dispose(true);
  150. GC.SuppressFinalize(this);
  151. }
  152. protected virtual void Dispose(bool disposing)
  153. {
  154. if (!this.disposed)
  155. {
  156. if (disposing)
  157. {
  158. if (mongoServer != null)
  159. {
  160. this.mongoServer.Disconnect();
  161. }
  162. }
  163. }
  164. this.disposed = true;
  165. }
  166. # endregion
  167. }
  168. }
  169. ###Add a controller###
  170. Open the *Controllers\HomeController.cs* file in **Solution Explorer** and replace the existing code with the following:
  171. using System;
  172. using System.Collections.Generic;
  173. using System.Linq;
  174. using System.Web;
  175. using System.Web.Mvc;
  176. using MyTaskListApp.Models;
  177. using System.Configuration;
  178. namespace MyTaskListApp.Controllers
  179. {
  180. public class HomeController : Controller, IDisposable
  181. {
  182. private Dal dal = new Dal();
  183. private bool disposed = false;
  184. //
  185. // GET: /MyTask/
  186. public ActionResult Index()
  187. {
  188. return View(dal.GetAllTasks());
  189. }
  190. //
  191. // GET: /MyTask/Create
  192. public ActionResult Create()
  193. {
  194. return View();
  195. }
  196. //
  197. // POST: /MyTask/Create
  198. [HttpPost]
  199. public ActionResult Create(MyTask task)
  200. {
  201. try
  202. {
  203. dal.CreateTask(task);
  204. return RedirectToAction("Index");
  205. }
  206. catch
  207. {
  208. return View();
  209. }
  210. }
  211. public ActionResult About()
  212. {
  213. return View();
  214. }
  215. # region IDisposable
  216. new protected void Dispose()
  217. {
  218. this.Dispose(true);
  219. GC.SuppressFinalize(this);
  220. }
  221. new protected virtual void Dispose(bool disposing)
  222. {
  223. if (!this.disposed)
  224. {
  225. if (disposing)
  226. {
  227. this.dal.Dispose();
  228. }
  229. }
  230. this.disposed = true;
  231. }
  232. # endregion
  233. }
  234. }
  235. ###Set up the site style###
  236. To change the title at the top of the page, open the *Views\Shared\\_Layout.cshtml* file in **Solution Explorer** and replace "Application name" in the navbar header with "My Task List Application" so that it looks like this:
  237. @Html.ActionLink("My Task List Application", "Index", "Home", null, new { @class = "navbar-brand" })
  238. In order to set up the Task List menu, open the *\Views\Home\Index.cshtml* file and replace the existing code with the following code:
  239. @model IEnumerable<MyTaskListApp.Models.MyTask>
  240. @{
  241. ViewBag.Title = "My Task List";
  242. }
  243. <h2>My Task List</h2>
  244. <table border="1">
  245. <tr>
  246. <th>Task</th>
  247. <th>Category</th>
  248. <th>Date</th>
  249. </tr>
  250. @foreach (var item in Model) {
  251. <tr>
  252. <td>
  253. @Html.DisplayFor(modelItem => item.Name)
  254. </td>
  255. <td>
  256. @Html.DisplayFor(modelItem => item.Category)
  257. </td>
  258. <td>
  259. @Html.DisplayFor(modelItem => item.Date)
  260. </td>
  261. </tr>
  262. }
  263. </table>
  264. <div> @Html.Partial("Create", new MyTaskListApp.Models.MyTask())</div>
  265. To add the ability to create a new task, right-click the *Views\Home\\* folder and **Add** a **View**. Name the view *Create*. Replace the code with the following:
  266. @model MyTaskListApp.Models.MyTask
  267. <script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")" type="text/javascript"></script>
  268. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
  269. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
  270. @using (Html.BeginForm("Create", "Home")) {
  271. @Html.ValidationSummary(true)
  272. <fieldset>
  273. <legend>New Task</legend>
  274. <div class="editor-label">
  275. @Html.LabelFor(model => model.Name)
  276. </div>
  277. <div class="editor-field">
  278. @Html.EditorFor(model => model.Name)
  279. @Html.ValidationMessageFor(model => model.Name)
  280. </div>
  281. <div class="editor-label">
  282. @Html.LabelFor(model => model.Category)
  283. </div>
  284. <div class="editor-field">
  285. @Html.EditorFor(model => model.Category)
  286. @Html.ValidationMessageFor(model => model.Category)
  287. </div>
  288. <div class="editor-label">
  289. @Html.LabelFor(model => model.Date)
  290. </div>
  291. <div class="editor-field">
  292. @Html.EditorFor(model => model.Date)
  293. @Html.ValidationMessageFor(model => model.Date)
  294. </div>
  295. <p>
  296. <input type="submit" value="Create" />
  297. </p>
  298. </fieldset>
  299. }
  300. **Solution Explorer** should look like this:
  301. ![Solution Explorer][SolutionExplorerMyTaskListApp]
  302. ###Set the MongoDB connection string###
  303. In **Solution Explorer**, open the *DAL/Dal.cs* file. Find the following line of code:
  304. private string connectionString = "mongodb://<vm-dns-name>";
  305. Replace `<vm-dns-name>` with the DNS name of the virtual machine running MongoDB you created in the [Create a virtual machine and install MongoDB][] step of this tutorial. To find the DNS name of your virtual machine, go to the Azure Management Portal, select **Virtual Machines**, and find **DNS Name**.
  306. If the DNS name of the virtual machine is "testlinuxvm.cloudapp.net" and MongoDB is listening on the default port 27017, the connection string line of code will look like:
  307. private string connectionString = "mongodb://testlinuxvm.cloudapp.net";
  308. If the virtual machine endpoint specifies a different external port for MongoDB, you can specifiy the port in the connection string:
  309. private string connectionString = "mongodb://testlinuxvm.cloudapp.net:12345";
  310. For more information on MongoDB connection strings, see [Connections][MongoConnectionStrings].
  311. ###Test the local deployment###
  312. To run your application on your development computer, select **Start Debugging** from the **Debug** menu or hit **F5**. IIS Express starts and a browser opens and launches the application's home page. You can add a new task, which will be added to the MongoDB database running on your virtual machine in Azure.
  313. ![My Task List Application][TaskListAppBlank]
  314. <h2><span class="short-header">Deploy the application to an Azure website</span>Deploy the ASP.NET application to an Azure website</h2>
  315. In this section you will create a website and deploy the My Task List ASP.NET application using Git.
  316. <a id="createwebsite"></a>
  317. ###Create an Azure website###
  318. In this section you will create an Azure website.
  319. 1. Open a web browser and browse to the [Azure Management Portal][AzurePortal]. Sign in with your Azure account.
  320. 2. At the bottom of the page, click **+New**, then **Website**, and finally **Quick Create**.
  321. 3. Enter a unique prefix for the application's URL.
  322. 4. Select a region.
  323. 5. Click **Create Website**.
  324. ![Create a new web site][WAWSCreateWebSite]
  325. 6. Your website will be created quickly and will be listed in **Websites**.
  326. ![WAWSDashboardMyTaskListApp][WAWSDashboardMyTaskListApp]
  327. <a id="deployapp"></a>
  328. ###Deploy the ASP.NET application to the website using Git
  329. In this section you will deploy the My Task List application using Git.
  330. 1. Click your website name in **Websites**, then click **Dashboard**. On the right side, under Quick Glance, click **Set up deployment from source control**.
  331. 2. On the **Where is your source code?** page, choose **Local Git repository**, and the click the **Next** arrow.
  332. 3. The Git repository should be created quickly. Make note of the instructions on the resulting page as they will be used in the next section.
  333. ![Git Repository is Ready][Image9]
  334. 4. Under **Push my local files to Azure** there are instructions for pushing your code to Azure. The instructions will look similar to the following:
  335. ![Push local files to Azure][Image10]
  336. 5. If you do not have Git installed, install it using the **Get it here** link in step 1.
  337. 6. Following the instructions in step 2, commit your local files.
  338. 7. Add the remote Azure repository and push your files to the Azure website by following the instructions in step 3.
  339. 8. When the deployment has completed you will see the following confirmation:
  340. ![Deployment Complete][Image11]
  341. 9. Your Azure website is now available. Check the **Dashboard** page for your site and the **Site URL** field to find the URL for your site. Following the procedures in this tutorial, your site would be available at this URL: http://mytasklistapp.azurewebsites.net.
  342. ##Summary##
  343. You have now successfully deployed your ASP.NET application to an Azure website. To view the site, click the link in the **Site URL** field of the **Dashboard** page. For more information on developing C# applications against MongoDB, see [CSharp Language Center][MongoC#LangCenter].
  344. <!-- HYPERLINKS -->
  345. [AzurePortal]: http://manage.windowsazure.com
  346. [WindowsAzure]: http://www.windowsazure.com
  347. [MongoC#LangCenter]: http://docs.mongodb.org/ecosystem/drivers/csharp/
  348. [MVCWebSite]: http://www.asp.net/mvc
  349. [ASP.NET]: http://www.asp.net/
  350. [MongoConnectionStrings]: http://www.mongodb.org/display/DOCS/Connections
  351. [MongoDB]: http://www.mongodb.org
  352. [InstallMongoOnCentOSLinuxVM]: /en-us/manage/linux/common-tasks/mongodb-on-a-linux-vm/
  353. [InstallMongoOnWindowsVM]: /en-us/manage/windows/common-tasks/install-mongodb/
  354. [VSEWeb]: http://www.microsoft.com/visualstudio/eng/2013-downloads#d-2013-express
  355. [VSUlt]: http://www.microsoft.com/visualstudio/eng/2013-downloads
  356. <!-- IMAGES -->
  357. [StartPageNewProject]: ./media/web-sites-dotnet-store-data-mongodb-vm/NewProject.png
  358. [NewProjectMyTaskListApp]: ./media/web-sites-dotnet-store-data-mongodb-vm/NewProjectMyTaskListApp.png
  359. [VS2013SelectMVCTemplate]: ./media/web-sites-dotnet-store-data-mongodb-vm/VS2013SelectMVCTemplate.png
  360. [VS2013DefaultMVCApplication]: ./media/web-sites-dotnet-store-data-mongodb-vm/VS2013DefaultMVCApplication.png
  361. [VS2013ManageNuGetPackages]: ./media/web-sites-dotnet-store-data-mongodb-vm/VS2013ManageNuGetPackages.png
  362. [SearchforMongoDBCSharpDriver]: ./media/web-sites-dotnet-store-data-mongodb-vm/SearchforMongoDBCSharpDriver.png
  363. [MongoDBCsharpDriverInstalled]: ./media/web-sites-dotnet-store-data-mongodb-vm/MongoDBCsharpDriverInstalled.png
  364. [MongoDBCSharpDriverReferences]: ./media/web-sites-dotnet-store-data-mongodb-vm/MongoDBCSharpDriverReferences.png
  365. [SolutionExplorerMyTaskListApp]: ./media/web-sites-dotnet-store-data-mongodb-vm/SolutionExplorerMyTaskListApp.png
  366. [TaskListAppBlank]: ./media/web-sites-dotnet-store-data-mongodb-vm/TaskListAppBlank.png
  367. [WAWSCreateWebSite]: ./media/web-sites-dotnet-store-data-mongodb-vm/WAWSCreateWebSite.png
  368. [WAWSDashboardMyTaskListApp]: ./media/web-sites-dotnet-store-data-mongodb-vm/WAWSDashboardMyTaskListApp.png
  369. [Image9]: ./media/web-sites-dotnet-store-data-mongodb-vm/RepoReady.png
  370. [Image10]: ./media/web-sites-dotnet-store-data-mongodb-vm/GitInstructions.png
  371. [Image11]: ./media/web-sites-dotnet-store-data-mongodb-vm/GitDeploymentComplete.png
  372. <!-- TOC BOOKMARKS -->
  373. [Create a virtual machine and install MongoDB]: #virtualmachine
  374. [Create and run the My Task List ASP.NET application on your development computer]: #createapp
  375. [Create an Azure web site]: #createwebsite
  376. [Deploy the ASP.NET application to the web site using Git]: #deployapp