Developing ASP.NET MVC Web Applications Developing ASP.NET MVC Web Applications © 2014 Aptech Limited All rights reserved No part of this book may be reproduced or copied in any form or by any means – graphic, electronic or mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent or transferred without the prior written permission of copyright owner Aptech Limited All trademarks acknowledged APTECH LIMITED Contact E-mail: ov-support@onlinevarsity.com Edition - 2014 Dear Learner, We congratulate you on your decision to pursue an Aptech Worldwide course Aptech Ltd designs its courses using a sound instructional design model – from conceptualization to execution, incorporating the following key aspects: ¾¾ Scanning the user system and needs assessment Needs assessment is carried out to find the educational and training needs of the learner Technology trends are regularly scanned and tracked by core teams at Aptech Ltd TAG* analyzes these on a monthly basis to understand the emerging technology training needs for the Industry An annual Industry Recruitment Profile Survey is conducted during August - October to understand the technologies that Industries would be adapting in the next to years An analysis of these trends & recruitment needs is then carried out to understand the skill requirements for different roles & career opportunities The skill requirements are then mapped with the learner profile (user system) to derive the Learning objectives for the different roles ¾¾ Needs analysis and design of curriculum The Learning objectives are then analyzed and translated into learning tasks Each learning task or activity is analyzed in terms of knowledge, skills and attitudes that are required to perform that task Teachers and domain experts this jointly These are then grouped in clusters to form the subjects to be covered by the curriculum In addition, the society, the teachers, and the industry expect certain knowledge and skills that are related to abilities such as learning-to-learn, thinking, adaptability, problem solving, positive attitude etc These competencies would cover both cognitive and affective domains A precedence diagram for the subjects is drawn where the prerequisites for each subject are graphically illustrated The number of levels in this diagram is determined by the duration of the course in terms of number of semesters etc Using the precedence diagram and the time duration for each subject, the curriculum is organized ¾¾ Design & development of instructional materials The content outlines are developed by including additional topics that are required for the completion of the domain and for the logical development of the competencies identified Evaluation strategy and scheme is developed for the subject The topics are arranged/organized in a meaningful sequence The detailed instructional material – Training aids, Learner material, reference material, project guidelines, etc.- are then developed Rigorous quality checks are conducted at every stage ¾¾ Strategies for delivery of instruction Careful consideration is given for the integral development of abilities like thinking, problem solving, learning-to-learn etc by selecting appropriate instructional strategies (training methodology), instructional activities and instructional materials The area of IT is fast changing and nebulous Hence considerable flexibility is provided in the instructional process by specially including creative activities with group interaction between the students and the trainer The positive aspects of Web based learning –acquiring information, organizing information and acting on the basis of insufficient information are some of the aspects, which are incorporated, in the instructional process ¾¾ Assessment of learning The learning is assessed through different modes – tests, assignments & projects The assessment system is designed to evaluate the level of knowledge & skills as defined by the learning objectives ¾¾ Evaluation of instructional process and instructional materials The instructional process is backed by an elaborate monitoring system to evaluate - on-time delivery, understanding of a subject module, ability of the instructor to impart learning As an integral part of this process, we request you to kindly send us your feedback in the reply prepaid form appended at the end of each module *TAG – Technology & Academics Group comprises of members from Aptech Ltd., professors from reputed Academic Institutions, Senior Managers from Industry, Technical gurus from Software Majors & representatives from regulatory organizations/forums Technology heads of Aptech Ltd meet on a monthly basis to share and evaluate the technology trends The group interfaces with the representatives of the TAG thrice a year to review and validate the technology and academic directions and endeavors of Aptech Ltd Aptech New Products Design Model Key Aspects Scanning the user system and needs assessment Evaluation of Instructional Processes and Material Need Analysis and design of curriculum Design and development of instructional material Assessment of learning Strategies for delivery of instructions Preface ASP.Net is a platform for developing Web applications that provide a comprehensive software infrastructure, a programming model, and a number of services required to develop robust Web application for PC, as well as mobile devices This book will teach to develop advanced ASP.NET MVC applications using NET Framework 4.5 and design the architecture of Web application and create MVC Models This book is the result of a concentrated effort of the Design Team, which is continuously striving to bring you the best and the latest in Information Technology The process of design has been a part of the ISO 9001 certification for Aptech-IT Division, Education Support Services As part of Aptech’s quality drive, this team does intensive research and curriculum enrichment to keep it in line with industry trends We will be glad to receive your suggestions Design Team Table of Contents Sessions Introduction to ASP.NET MVC Controllers in ASP.NET MVC Views in ASP.NET MVC Models in ASP.NET MVC Data Validation and Annotation Data Access Consistent Styles and Layouts Responsive Pages State Management and Optimization 10 Authentication and Authorization 11 Security 12 Globalization 13 Debugging and Monitoring 14 Advanced Concepts of ASP.NET MVC 15 Testing and Deploying 15 Session Testing and Deploying ViewResult result = controller.About() as ViewResult; // Assert Assert.AreEqual(“Your application description page.”, result.ViewBag.Message); } [TestMethod] public void Contact() { // Arrange HomeController controller = new HomeController(); // Act ViewResult result = controller.Contact() as ViewResult; // Assert Assert.IsNotNull(result); } } } Concepts This code uses the [TestClass] attribute in the class declaration and the [TestMethod] attributes for each action method that needs to be tested V 1.0 © Aptech Limited 15 Session Testing and Deploying 15.1.3 Performing Unit Tests To unit test the Home controller class using the HomeControllerTest unit test, you need to perform the following step: Select TestRunAll Tests in Visual Studio 2013 The Test Explorer window displays the test results Figure 15.4 shows the Test Explorer window Figure 15.4: Test Explorer Window 15.2 Preparing the Application for Deployment While developing and executing an ASP.NET MVC application using Visual Studio 2013, the application automatically deployed on Internet Information Server (IIS) Express IIS Express makes deployment simple, because it runs with your identity, and allows you to start and stop the Web server whenever required To make your application accessible over the Internet, you need to host it on an IIS or any other Web server Before deploying the application on a Web server, you first need to prepare the application for deployment This process of preparing an application contains activities, such as identifying the files and folders to be copied on the Web server, configuring Web.config file, and precompiling the application V 1.0 © Aptech Limited Concepts You have learned that after creating an ASP.NET MVC application, you should make it available to the users The Internet is the best and the most used medium for getting information on any topic To enable users to access the information contained in your application, you need to install the application on a Web server The process of installing a Web application on a Web server is known as deployment 15 Session Testing and Deploying 15.2.1 Identifying the Files and Folders When you create an application using Visual Studio 2013, the application is saved on the path of the local computer that you can explicitly specify Once you have created the application then, you need to deploy it on a Web server, such as IIS To deploy the application on IIS, first you need to identify the files and folders that are created in the specified path and need to be copied to the destination server While using Visual Studio 2013, by default, it deploys only those files and folders that are required to run the application However, sometimes there might be a requirement where you need to copy several other files and folders to copy on the destination server For example, consider a scenario where you only need some database files available in the App_Data folder while developing an application In such scenario, you need to identify those files and exclude them while deploying the application For this, you need to configure the deployment settings 15.2.2 Configuring the Web.config File Once you have deployed an ASP.NET MVC application on a Web server, some of the settings of the Web.config file vary in the deployed application Consider a scenario, where you need to disable the debug options and change connection strings so that they point to different databases You need to configure these types of settings in the Web.config transformation file, which is an XML file that allows you to specify how the Web.config file should be changed when it is deployed You can specify such transformation actions in the Web.config file by using XML attributes A transform file is associated with a build configuration When you compile and execute an application in Visual Studio 2013, by default, it creates the Debug and Release build configurations files named Web Debug.config and Web.Release.config respectively When you compile the application in Release mode, the Web.release.config file contains the changes that Visual Studio 2013 made in the Web config file On the other hand, when you compile the application in the Debug mode, the Web.debug.config file contains the changes that Visual Studio 2013 made in the Web.config file To publish the application using release configuration, you need to remove the debug attribute from the element in the Web.config file Code Snippet shows how to remove the debug attribute Code Snippet 2: Concepts In this code, the xdt:Transform attribute is used to remove the debug attribute from the Web.config file V 1.0 © Aptech Limited 15 Session Testing and Deploying 15.2.3 Precompilation To deploy an application, you need to copy the files and folders of the application to the hard drive of a Web server In this process, most of the files are deployed to the Web server without compilation Deploying an application in this way typically contains the following issues: ÎÎ The application might get deployed with compilation errors ÎÎ The source code of the application is exposed ÎÎ The application loads slowly because files are required to be compiled when it is accessed for the first time Precompiling a Web application is a process that involves compilation of the source code into DLL assemblies before deployment The process of precompiling provides the following advantages: ÎÎ It provides faster response because the files of the application not need to be compiled at the first time as it is accessed ÎÎ It helps in identifying the errors that can occur when a page is requested, because errors are rectified at the time of compiling the application ÎÎ It secures the source code of the application from malicious users 15.3 Deploying on IIS Consider the scenario where you have created an ASP.NET MVC application and it is ready to be made available to the user To allow users to access the application, it has to be deployed on a Web server, such as IIS IIS is a Web server that allows you to develop, host, and manage your application Before deploying an application on IIS, you first need to install it on your computer To deploy an ASP.NET MVC application, you need to perform the following tasks: Install IIS Create an application in IIS Create a publish profile for the application Publish the project Concepts V 1.0 © Aptech Limited 15 Session Testing and Deploying 15.3.1 Installing IIS The first step to deploy an application is to install IIS To install IIS, you need to perform the following tasks: Open Control Panel Click Uninstall a program under the Programs icon The Program and Features window displays the Uninstall or change a program screen Click the Turn Windows features on or off link in the left pane The Windows Features window is displayed Ensure that all the check boxes are selected under the Internet Information Services node Figure 15.5 shows the Windows Features window Concepts Figure 15.5: Windows Features Click OK The Windows Features message box is displayed Wait until the changes are applied to the system Click the Close button Close the Programs and Features window V 1.0 © Aptech Limited 15 Session Testing and Deploying 15.3.2 Creating an Application on IIS Create a folder with the name of your project, for example, MVCDemo in the C:\inetpub\wwwroot folder Press the Windows+R keys The Run dialog box is displayed Type inetmgr in the Run dialog box Click OK The Internet Information Services (IIS) Manager window is displayed Figure 15.6 shows the Internet Information Services (IIS) Manager window Figure 15.6: Internet Information Services (IIS) Manager Window Expand the node under the Connections pane Expand the Sites node Right-click the Default Web Site node under the Sites node, and then, select Add Application The Add Application dialog box is displayed V 1.0 © Aptech Limited Concepts Once you have installed IIS, the next step that you need to perform is creating a publish profile To create an application on IIS, you need to perform the following steps: 15 Session Testing and Deploying In the Add Application dialog box, type MVCDemo in the Alias text field and type C:\inetpub\ wwwroot\MVCDemo in the Physical path text field Figure 15.7 shows the Add Application dialog box Figure 15.7: Add Application Dialog Box Click the OK button in the Add Application dialog box The MVCDemo node is displayed under the Connections node of the Internet Information Services (IIS) Manager window Figure 15.8 shows the MVCDemo node under the Connections node Concepts Figure 15.8: MVCDemo Node under the Connections 10 Close the Internet Information Services (IIS) Manager window V 1.0 © Aptech Limited 15 Session Testing and Deploying 15.3.3 Creating a Publish Profile After creating the application on IIS, you need to create a publish profile A publish profile represents various deployment options, such as the target server to be used for deployment, the credentials needed to log on to the server to deploy To create a publish profile in Visual Studio 2013, you need to perform the following tasks: Start Visual Studio 2013 with Administrator privilege Open the MVCDemo project to publish Right-click the project in the Solution Explorer window and select Publish The Publish Web dialog box is displayed From the Select or import a publish profile drop-down list, select the option The New Profile dialog box is displayed Type MVCDemoPublishProfile in the Profile Name text field Figure 15.9 shows the New Profile dialog box Figure 15.9: New Profile Dialog Box Click OK The Publish Web dialog box is displayed with the specified profile name Ensure that Web Deploy is selected in the Publish method drop-down list In the Service URL text field, type localhost and in the Site/application text field, type Default Web Site/MVCDemo Concepts V 1.0 © Aptech Limited 15 Session Testing and Deploying Figure 15.10 shows the specifying the Service URL and Site/application text fields Figure 15.10: Publish Web Dialog Box Concepts 10 Click Validate Connection When the connection is valid that is correct mark is displayed by the side of the Validate Connection button V 1.0 © Aptech Limited 15 Session Testing and Deploying Figure 15.11 shows that the specified connection is valid Figure 15.11: Displaying a Valid Connection 11 Click Next The Publish Web dialog box is displayed Concepts 12 Click Publish The Output window of Visual Studio 2013 displays a message to indicate that the project has been successfully published Figure 15.12 shows the Output window Figure 15.12: Output Window V 1.0 © Aptech Limited 15 Session Testing and Deploying To test the published application, type the following URL in the address bar of the browser: http://localhost/MVCDemo The Home page of the application published on IIS is displayed on the browser Figure 15.13 shows the Home page of the published application on the browser Concepts Figure 15.13: Home Page of the Deployed Application V 1.0 © Aptech Limited 15 Session Testing and Deploying 15.4 Check Your Progress Which of the following files you need to configure before deploying an application on a Web server? (A) Web.Debug.config (B) Global.asax (C) Web.config (D) Web.Release.config (E) Startup.cs (A) A (C) D (B) C (D) B Which of the following files contain the changes that Visual Studio 2013 made when you compile an application in the Debug mode? (A) Web.Release.config (B) Web.config (C) Startup.cs (D) Global.asax (E) Web.debug.config (A) A (C) D (B) C (D) E Which of the following directory structure on IIS you need to create for an application to deploy? (A) C:\inetpub\wwwroot (B) C:\inetpub\applicationname (C) C:\wwwroot\inetpub (D) C:\inetpub\wwwroot\deploy (E) C:\inetpub\deploy\wwwroot (A) B (C) A (B) C (D) E V 1.0 © Aptech Limited Concepts 15 Session Which of the following URL will you use to access an application that has been deployed on IIS server? Assuming that the name of your application is TestMVCApp (A) http://inetpub/TestMVCApp (B) www.localhost/TestMVCApp (C) www.localhost/TestMVCApp/Home (D) https://localhost/TestMVCApp (E) http://localhost/TestMVCApp (A) B (C) D (B) E (D) A Which of the following options represents various deployment options, such as the target server to be used and the credentials needed to log on to the server to deploy? (A) Publish profile (B) IIS profile (C) Unit testing (D) IIS manager (E) Web profile (A) B (C) A (B) C (D) E Concepts Testing and Deploying V 1.0 © Aptech Limited 15 Session Testing and Deploying (1) B (2) D (3) C (4) B (5) C Concepts 15.4.1 Answers V 1.0 © Aptech Limited 15 Session Testing and Deploying Summary Unit testing is a technique that allows you to create classes and methods in your application and test their intended functionality ÎÎ While developing and executing an ASP.NET MVC application using Visual Studio 2013, the application automatically deployed on Internet Information Server (IIS) Express ÎÎ To deploy the application on IIS, first you need to identify the files and folders that are required to be copied on the destination server ÎÎ While using Visual Studio 2013, by default, it deploys only those files and folders that are required to run the application ÎÎ Precompiling a Web application is a process that involves compilation of the source code into DLL assemblies before deployment ÎÎ To deploy an ASP.NET MVC application, you need to install IIS, create an application in IIS, create a publish profile for the application, and finally, publish the project ÎÎ A publish profile represents various deployment options, such as the target server to be used for deployment, the credentials needed to log on to the server to deploy Concepts ÎÎ V 1.0 © Aptech Limited