PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

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

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