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