PageRenderTime 27ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/DevCenter/dotNET/Tutorials/DeployWAWebSiteThatConnectsToMongo.md

https://github.com/mattshel/azure-content
Markdown | 499 lines | 373 code | 126 blank | 0 comment | 0 complexity | e6f10586c60b9b9ee776a25961a79e10 MD5 | raw file
  1. <properties linkid="develop-dotnet-website-with-mongodb-vm" urlDisplayName="Web site with MongoDB VM" pageTitle=".NET web site with MongoDB on a virtual machine - Windows Azure" metaKeywords="Azure Git ASP.NET MongoDB, Git .NET, Git MongoDB, ASP.NET MongoDB, Azure MongoDB, Azure ASP.NET, Azure tutorial" metaDescription="A tutorial that teaches you how to use Git to deploy an ASP.NET app to a Windows Azure web site connected to MongoDB on a virtual machine." metaCanonical="" disqusComments="1" umbracoNaviHide="1" />
  2. <div chunk="../chunks/article-left-menu.md" />#Create a Windows Azure web site that connects to MongoDB running on a virtual machine in Windows Azure
  3. Using Git, you can deploy an ASP.NET application to a Windows 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 Windows 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 a Windows Azure web site using Git.
  4. The ASP.NET application you'll build will look like this:
  5. ![My Task List Application][Image0]
  6. <div chunk="../../Shared/Chunks/create-account-and-websites-and-vms-note.md" />
  7. <h2><span class="short-header">Overview</span>Overview</h2>
  8. In this tutorial you will:
  9. - [Create a virtual machine and install MongoDB][]
  10. - [Create and run the My Task List ASP.NET application on your development computer][]
  11. - [Create a Windows Azure web site][]
  12. - [Deploy the ASP.NET application to the web site using Git][]
  13. <h2><span class="short-header">Background knowledge</span>Background knowledge</h2>
  14. Knowledge of the following is useful for this tutorial, though not required:
  15. * The C# driver for MongoDB. For more information on developing C# applications against MongoDB, see [CSharp Language Center][MongoC#LangCenter].
  16. * The ASP .NET web application framework. You can learn all about it at the [ASP.net web site][ASP.NET].
  17. * The ASP .NET MVC 3.0 web application framework. You can learn all about it at the [ASP.NET MVC 3 web site][MVC3].
  18. * Windows Azure. You can get started reading at [Windows Azure][WindowsAzure].
  19. <h2><span class="short-header">Preparation</span>Preparation</h2>
  20. In this section you will learn how to create a virtual machine in Windows Azure and install MongoDB, and set up your development environment.
  21. ###<a id="virtualmachine"></a> Create a virtual machine and install MongoDB
  22. This tutorial assumes you have created a virtual machine in Windows 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 2008 R2 in Windows Azure][InstallMongoOnWindowsVM].
  24. * Alternatively, to create a Linux virtual machine and install MongoDB, see [Install MongoDB on a virtual machine running CentOS Linux in Windows Azure][InstallMongoOnCentOSLinuxVM].
  25. After you have created the virtual machine in Windows 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. ### Set up the development environment
  27. This tutorial uses Microsoft Visual Studio 2010. You can also use Microsoft Visual Web Developer 2010 Express Service Pack 1, which is a free version of Microsoft Visual Studio. Before you start, make sure you've installed the prerequisites listed below on your local development computer. You can install all of them by clicking the following link: [Web Platform Installer] [WebPlatformInstaller]. Alternatively, you can individually install the prerequisites using the following links:
  28. * [Visual Studio 2010 prerequisites] [VsPreReqs]
  29. * [ASP.NET MVC 3 Tools Update] [MVCPrereqs]
  30. If you're using Visual Web Developer 2010 instead of Visual Studio 2010, install the prerequisites by clicking the following link: [Visual Studio Web Developer Express SP1 prerequisites] [VsWebExpressPreReqs]
  31. <h2><a id="createapp"></a><span class="short-header">Create and run the application locally</span>Create and run the My Task List ASP.NET application on your development computer</h2>
  32. In this section you will create the My Task List ASP.NET application using Visual Studio. You will also run the application locally against the MongoDB instance you created in the virtual machine hosted on Windows Azure.
  33. ###Create the application
  34. Start by running Visual Studio and select **New Project** from the **Start** page.
  35. Select **Visual C#** and then **Web** on the left and then select **ASP.NET MVC 3 Web Application** from the list of templates. Name your project "MyTaskListApp" and then click **OK**.
  36. ![New Project Screen][Image00]
  37. In the **New ASP.NET MVC 3 Project** dialog box, select **Internet Application**. Check **Use HTML5 markup** and leave **Razor** as the default view engine.
  38. Click **OK**.
  39. ![New Internet Application][Image1]
  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**, right-click the **MyTaskListApplication** project references and select **Add Library Package Reference...**.
  44. ![Add Library Package Reference][Image2]
  45. 2. In the **Add Library Package Reference** window, click **Online** and then search for "mongocsharpdriver". Click **Install** to install the driver.
  46. ![Search for MongoDB C# Driver][Image2.1]
  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][Image2.2]
  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][Image2.3]
  52. ###Add a model
  53. In **Solution Explorer**, right-click the *Models* folder and **Add** a new **Class** *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 Task
  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 file named *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<Task> GetAllTasks()
  107. {
  108. try
  109. {
  110. MongoCollection<Task> collection = GetTasksCollection();
  111. return collection.FindAll().ToList<Task>();
  112. }
  113. catch (MongoConnectionException)
  114. {
  115. return new List<Task>();
  116. }
  117. }
  118. // Creates a Task and inserts it into the collection in MongoDB.
  119. public void CreateTask(Task task)
  120. {
  121. MongoCollection<Task> 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<Task> GetTasksCollection()
  132. {
  133. MongoServer server = MongoServer.Create(connectionString);
  134. MongoDatabase database = server[dbName];
  135. MongoCollection<Task> todoTaskCollection = database.GetCollection<Task>(collectionName);
  136. return todoTaskCollection;
  137. }
  138. private MongoCollection<Task> GetTasksCollectionForEdit()
  139. {
  140. MongoServer server = MongoServer.Create(connectionString);
  141. MongoDatabase database = server[dbName];
  142. MongoCollection<Task> todoTaskCollection = database.GetCollection<Task>(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: /Task/
  185. public ActionResult Index()
  186. {
  187. return View(dal.GetAllTasks());
  188. }
  189. //
  190. // GET: /Task/Create
  191. public ActionResult Create()
  192. {
  193. return View();
  194. }
  195. //
  196. // POST: /Task/Create
  197. [HttpPost]
  198. public ActionResult Create(Task 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 the existing **h1** heading text with the following:
  236. <h1>My Task List Application</h1>
  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.Task>
  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.Task())</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.Task
  266. <script src="@Url.Content("~/Scripts/jquery-1.5.1.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][Image3]
  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 Windows 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**. A development web server 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 Windows Azure.
  312. ![My Task List Application][Image4]
  313. <h2><span class="short-header">Deploy the application to a Windows Azure web site</span>Deploy the ASP.NET application to a Windows 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> Create a Windows Azure web site
  316. In this section you will create a Windows Azure web site.
  317. 1. Open a web browser and browse to the [Windows Azure (Preview) Management Portal][AzurePreviewPortal]. Sign in with your Windows Azure account.
  318. 2. At the bottom of the page, click **+New**, then **Web Site**, and finally **Quick Create**.
  319. 3. Enter a unique prefix for the application's URL.
  320. 4. Select a region.
  321. 5. Click **Create Web Site**.
  322. ![Create a new web site][Image7]
  323. 6. Your web site will be created quickly and will be listed in **Web sites**.
  324. ![Dashboard][Image8]
  325. ###<a id="deployapp"></a> Deploy the ASP.NET application to the web site using Git
  326. In this section you will deploy the My Task List application using Git.
  327. 1. Click your web site name in **Web sites**, then click **Dashboard**. Click **Set up Git publishing** at the bottom of the **Dashboard** page for the **mytasklistapp** site.
  328. 2. Enter a user name and password in the **New user name and password** page and click the checkmark. Make note of the instructions on the resulting page as they will be used in the next section.
  329. 3. The Git repository should be created quickly.
  330. ![Git Repository is Ready][Image9]
  331. 4. Select **Push my local files to Windows Azure** to display instructions on pushing your code to Windows Azure. The instructions will look similar to the following:
  332. ![Push local files to Windows Azure][Image10]
  333. 5. If you do not have Git installed, install it using the **Get it here** link in step 1.
  334. 6. Following these instructions in step 2, commit your local files.
  335. 7. Add the remote Windows Azure repository and push your files to the Windows Azure web site by following the instructions in step 3.
  336. 8. When the deployment has completed you will see the following confirmation:
  337. ![Deployment Complete][Image11]
  338. 9. Your Windows 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: <a href="http://mytasklistapp.azurewebsites.net">http://mytasklistapp.azurewebsites.net</a>.
  339. <h2><span class="short-header">Summary</span>Summary</h2>
  340. You have now successfully deployed your ASP.NET application to a Windows 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].
  341. [AzurePreviewPortal]: http://manage.windowsazure.com
  342. [WindowsAzure]: http://www.windowsazure.com
  343. [ASP.NET]: http://www.asp.net
  344. [MVC3]: http://www.asp.net/mvc
  345. [MVCPrereqs]: http://www.microsoft.com/web/gallery/install.aspx?appsxml=&appid=MVC3
  346. [VsPreReqs]: http://www.microsoft.com/web/gallery/install.aspx?appsxml=&appid=VS2010SP1Pack
  347. [VsWebExpressPreReqs]: http://www.microsoft.com/web/gallery/install.aspx?appid=VWD2010SP1Pack
  348. [MongoConnectionStrings]: http://www.mongodb.org/display/DOCS/Connections
  349. [WebPlatformInstaller]: http://www.microsoft.com/web/gallery/install.aspx?appid=VWD2010SP1Pack
  350. [MongoC#LangCenter]: http://www.mongodb.org/display/DOCS/CSharp+Language+Center
  351. [MongoDB]: http://www.mongodb.org
  352. [MongoCSharpDriverDownload]: http://github.com/mongodb/mongo-csharp-driver/downloads
  353. [InstallMongoWinVM]: ../../../Shared/Tutorials/InstallMongoDbOnWin2k8VM.md
  354. [InstallMongoOnCentOSLinuxVM]: /en-us/manage/linux/common-tasks/mongodb-on-a-linux-vm/
  355. [InstallMongoOnWindowsVM]: /en-us/manage/windows/common-tasks/install-mongodb/
  356. [Image0]: ../../../DevCenter/dotNET/Media/TaskListAppFull.png
  357. [Image00]: ../../../DevCenter/dotNET/Media/NewProject.png
  358. [Image1]: ../../../DevCenter/dotNET/Media/NewProject2.png
  359. [Image2]: ../../../DevCenter/dotNET/Media/AddReference.png
  360. [Image2.1]: ../../../DevCenter/dotNET/Media/AddReference2.png
  361. [Image2.2]: ../../../DevCenter/dotNET/Media/AddReference3.png
  362. [Image2.3]: ../../../DevCenter/dotNET/Media/AddReference4.png
  363. [Image3]: ../../../DevCenter/dotNET/Media/SolnExplorer.png
  364. [Image4]: ../../../DevCenter/dotNET/Media/TaskListAppBlank.png
  365. [Image7]: ../../../DevCenter/dotNET/Media/NewWebSite.png
  366. [Image8]: ../../../DevCenter/dotNET/Media/Dashboard.png
  367. [Image9]: ../../../DevCenter/dotNET/Media/RepoReady.png
  368. [Image10]: ../../../DevCenter/dotNET/Media/GitInstructions.png
  369. [Image11]: ../../../DevCenter/dotNET/Media/GitDeploymentComplete.png
  370. [Create a virtual machine and install MongoDB]: #virtualmachine
  371. [Create and run the My Task List ASP.NET application on your development computer]: #createapp
  372. [Create a Windows Azure web site]: #createwebsite
  373. [Deploy the ASP.NET application to the web site using Git]: #deployapp