ASP.NET MVC 4 Recipes

Total Page:16

File Type:pdf, Size:1020Kb

ASP.NET MVC 4 Recipes For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. Contents at a Glance About the Author ............................................................................................................. xxiii About the Technical Reviewer .......................................................................................... xxv Acknowledgments .......................................................................................................... xxvii Introduction ..................................................................................................................... xxix ■ Chapter 1: The Need for Modern Web Applications ...........................................................1 ■ Chapter 2: Understanding ASP.NET MVC ..........................................................................15 ■ Chapter 3: Setting Up Your Environment .........................................................................59 ■ Chapter 4: Visual Studio 2012 Overview .......................................................................105 ■ Chapter 5: Getting the Most from the Built-in Templates ..............................................139 ■ Chapter 6: Architecting Applications with ASP.NET MVC...............................................185 ■ Chapter 7: Solution Design ............................................................................................215 ■ Chapter 8: Asynchronous Programming with ASP.NET MVC .........................................281 ■ Chapter 9: Test-Driven Development with ASP.NET MVC 4 ............................................321 ■ Chapter 10: Moving From Web Forms to ASP.NET MVC .................................................375 ■ Chapter 11: Creating Modern User Experiences Using jQuery, Knockout.js, and Web API ....475 ■ Chapter 12: Mobile, Social, and Cloud Technologies .....................................................543 Index .................................................................................................................................589 v Introduction The first time I saw a computer that could connect to a network was back in the late ’80s when my friend Greg showed me how we could use his Apple IIe to download the Anarchy Cookbook from a bulletin board service. That first experience, which included a misguided crash course in chemistry, eventually led Greg to a career as a pharmacist and got me hooked on the potential of computers. Fast-forward to 2013 and the Internet is everywhere. It’s in your home, at your job, in your car, and in your pocket. You can access the Web from your PC, your phone, your music player, your tablet, and you can even stream movies to your TV. Terrestrial radio is gradually being replaced by Internet music services, cable TV by services from Netflix and Amazon, paper maps by GPS systems, magazines and newspapers by e-readers and tablets. You surf the Web using touch screens, your voice, and TV remotes. Web pages adapt to fit your iPad’s orientation, your screen dims automatically to account for room lighting, your game console and your phone can recognize your face, and your tablet can read your handwriting. As software developers, you need to be three steps ahead of this changing world. You are on the front lines. The world expects that not only will your software work but also that it will get smarter, faster, more reliable, and easier to use. These goals are only possible with improved techniques and better tools. Adopting new techniques and learning new tools can be challenging, especially when you are on a tight schedule. When learning new technologies, many developers can spend more time searching Google and reading blogs and forum posts than writing code. Many times, they end up using a code snippet from some random source without a full understanding of what it does. The code may seem to fit the need at that time but if it ever breaks, they do not know how to fix it because they don’t understand it. This book was written to help ASP.NET MVC developers like you to quickly find the code you need to move your project forward. More importantly, this book also will help you understand how each solution works. Each solution is broken down step by step and each code sample is explained in detail. In many cases, the explanation will go beyond the code and will discuss what is happening behind the scenes. xxix CHAPTER 1 The Need for Modern Web Applications All around the world, people are spending less and less time on their PCs, and more time on tablets and smartphones. This trend is dramatically changing how we all collect, share, and work with information. As a web developer working with Microsoft technologies, you need to understand exactly what this means for your applications. A modern web application is designed for the demands of the post-PC world. It can be deployed to a cloud infrastructure, is resilient to unreliable network conditions, is accessible from any device—anywhere—and provides a beautiful and responsive user experience. While the basic fundamentals of modern web applications remain unchanged, the ways in which the content is consumed and experienced by the end user have evolved considerably. Modern web applications still use HTTP and HTTPS to send requests and receive responses, and most web applications still use HTML for presentation. On the other hand, the explosion of mobile devices, tablets, and hybrid PCs such as the Microsoft Surface Pro are making touch screens almost as pervasive as the mouse and keyboard. The popularity of social media has spawned a massive expansion of user-generated content that is made relevant by cutting-edge statistical algorithms paired with virtually boundless computing power. HTML5 and modern web browsers such as Google Chrome and Internet Explorer 10 have allowed developers to create dynamic, immersive user interfaces that rival native applications in sophistication and responsiveness. The following is a list of increasingly common features and characteristics in modern web applications, along with references to recipes in this book that will help you understand how to implement these features. • Cross-browser compatibility: The application experience is constant across all modern web browsers, including Google Chrome, Mozilla Firefox, Internet Explorer 9 and 10, Safari, and Opera. All of the recipes in this book have been designed and tested to work cross-browser. • Adaptive design: The application automatically adapts to work on many screen resolutions, from huge 30-inch monitors to tiny 3.4-inch cell phones. This technique is covered in Recipe 11-1. • Natural user interfaces: The application accepts input from natural user interfaces (NUI) such as touch, voice, NFC, video cameras, GPS, and other sensors. Meeting this requirement means that you have not only the right software but the hardware to test how the application behaves on these devices, as discussed in Recipe 3-1. • Social network integration: The application seamlessly interacts with social networks. Recipes 12-1 and 12-2 demonstrate how easy Visual Studio makes it to integrate your web site with Facebook. • Cloud-ready: The application can use cloud-based infrastructure and scales on demand, adding new servers when needed and scaling down when traffic slows. Chapter 6 describes architectural techniques for designing applications that can take advantage of these capabilities. Chapter 12 describes how to use Visual Studio to create an application that can be deployed to Windows Azure. 1 CHAPTER 1 ■ THE NEED FOR MODERN WEB APPLICATIONS • Resiliency: The application can adapt to challenging network conditions and, in some cases, can work in a disconnected state. The application is designed to tolerate failures of one or more subsystems and still operate at limited but acceptable capacity. Chapter 6 talks about how to architect systems to meet this requirement. Recipe 12-5 demonstrates how to use some of the built-in features on the Windows Azure APIs to enable resilient file uploads in an ASP. NET MVC 4 application that uses Azure BLOB storage. • Extensible: The application is extensible by way of RESTful APIs and its functionality can be augmented by third-party developers. Chapter 11 shows how to use ASP.NET Web API to design RESTful services and how to consume them using jQuery and Knockout. • Reliable: The application is reliable and supports multiple levels of automated and manual testing before being deployed. Many recipes in this book describe not only how to develop solutions using MVC, but also how to test them. Chapter 9 is entirely dedicated to testing. • Maintainable: The application is easy to maintain and can be upgraded frequently and seamlessly with minimal disruption of the service. Several recipes in this book take this into account. Recipe 1-5 shows how Microsoft Web Deploy can simplify your deployment process. Recipes 7-9 and 10-9 explain how to use the Area feature of ASP.NET MVC to keep your project organized. • RESTful: The application is built on established standards and protocols, and takes advantage of network optimization appliances, load balancers, and monitoring packages. Chapter 11 demonstrates using ASP.NET Web API to create RESTful web services. • Secure: The application has been designed to protect itself from evolving security threats using a layered system of counter measures. If a breach occurs, only the compromised subsystems will be affected; confidential
Recommended publications
  • Modern Web Application Frameworks
    MASARYKOVA UNIVERZITA FAKULTA INFORMATIKY Û¡¢£¤¥¦§¨ª«¬­Æ°±²³´µ·¸¹º»¼½¾¿Ý Modern Web Application Frameworks MASTER’S THESIS Bc. Jan Pater Brno, autumn 2015 Declaration Hereby I declare, that this paper is my original authorial work, which I have worked out by my own. All sources, references and literature used or ex- cerpted during elaboration of this work are properly cited and listed in complete reference to the due source. Bc. Jan Pater Advisor: doc. RNDr. Petr Sojka, Ph.D. i Abstract The aim of this paper was the analysis of major web application frameworks and the design and implementation of applications for website content ma- nagement of Laboratory of Multimedia Electronic Applications and Film festival organized by Faculty of Informatics. The paper introduces readers into web application development problematic and focuses on characte- ristics and specifics of ten selected modern web application frameworks, which were described and compared on the basis of relevant criteria. Practi- cal part of the paper includes the selection of a suitable framework for im- plementation of both applications and describes their design, development process and deployment within the laboratory. ii Keywords Web application, Framework, PHP,Java, Ruby, Python, Laravel, Nette, Phal- con, Rails, Padrino, Django, Flask, Grails, Vaadin, Play, LEMMA, Film fes- tival iii Acknowledgement I would like to show my gratitude to my supervisor doc. RNDr. Petr So- jka, Ph.D. for his advice and comments on this thesis as well as to RNDr. Lukáš Hejtmánek, Ph.D. for his assistance with application deployment and server setup. Many thanks also go to OndˇrejTom for his valuable help and advice during application development.
    [Show full text]
  • Pro ASP.NET MVC 3 Framework Third Edition
    Pro ASP.NET MVC 3 Framework Third Edition ADAM FREEMAN STEVEN SANDERSON ApressB Contents J About the Authors xxiii About the Technical Reviewer xxiv Acknowledgments xxv Part 1: Introducing ASP.NET MVC 3 1 Chapter 1: What's the Big Idea? 3 A Brief History of Web Development 3 Traditional ASP.NET Web Forms 5 What's Wrong with ASP.NET Web Forms? 6 Web Development Today 7 Web Standards and REST 7 Agile and Test-Driven Development 7 Ruby on Rails 8 Sinatra 8 Node.js 9 Key Benefits of ASP.NET MVC 9 MVC Architecture 10 Extensibility 10 Tight Control over HTML and HTTP 11 Testability 11 Powerful Routing System 11 Built on the Best Parts of the ASP.NET Platform 12 Modern API 12 ASP.NET MVC Is Open Source 13 Who Should Use ASP.NET MVC? 13 Comparisons with ASP.NET Web Forms 13 Migrating from Web Forms to MVC 14 Comparisons with Ruby on Rails 14 Comparisons with MonoRail 14 What's New in ASP.NET MVC 3 15 Summary 15 Chapter 2: Getting Ready 17 Preparing the Workstation , 17 Installing Visual Studio 2010 17 Installing the Essential Software 19 Installing Optional Components 21 Preparing the Server 22 Enabling the Web Server Role 23 Installing Additional Components 25 Setting up Web Deployment , 26 Getting Further Information 30 Summary 30 Chapter 3: Your First MVC Application 31 Creating a New ASP.NET MVC Project .31 Adding the First Controller 33 Understanding Routes 36 Rendering Web Pages 37 Creating and Rendering a View 37 Adding Dynamic Output 41 Creating a Simple Data-Entry Application 42 Setting the Scene 42 Designing a Data Model 43 Linking
    [Show full text]
  • Sams Teach Yourself Javascript in 24 Hours
    Phil Ballard Michael Moncur SamsTeachYourself JavaScript™ Fifth Edition in Hours24 800 East 96th Street, Indianapolis, Indiana, 46240 USA Sams Teach Yourself JavaScript™ in 24 Hours, Fifth Edition Editor-in-Chief Mark Taub Copyright © 2013 by Pearson Education, Inc. All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, Acquisitions Editor or transmitted by any means, electronic, mechanical, photocopying, recording, or other- Mark Taber wise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has Managing Editor been taken in the preparation of this book, the publisher and author assume no responsi- Kristy Hart bility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. Project Editor ISBN-13: 978-0-672-33608-9 Anne Goebel ISBN-10: 0-672-33608-1 Copy Editor Library of Congress Cataloging-in-Publication Data is on file. Geneil Breeze Printed in the United States of America First Printing October 2012 Indexer Erika Millen Trademarks All terms mentioned in this book that are known to be trademarks or service marks have Proofreader been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this Chrissy White, information. Use of a term in this book should not be regarded as affecting the validity of Language Logistics any trademark or service mark. Publishing Coordinator Warning and Disclaimer Vanessa Evans Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied.
    [Show full text]
  • Switching from Rails to Sinatra
    Switching from Rails to Sinatra Rushi Shah 26 October 2015 So recently I created this little Ruby on Rails app that lets you embed your Github Contribution calendar into any HTML (or Markdown) as an image. I would show you a great example, but one of the downsides to PDFs generated with LaTeX is that you have to save the image locally (and in doing so, the magic of the app would be lost). However, if you want to see an awesome example, totally check out the github repo or just get your own on the site. It is simple, straightforward, but still pretty neat, if I do say so myself. But soon I decided to rewrite the application in Sinatra, and here's why. 1 Starting with Rails When I started this project, I dove in with rails because I had used it before on apps like a CNN article generator and a bookshelf. After I had my basic functionality down, the file structure looked like a typical rails app. For reference, here is the file structure at that point (created using tree). Gemfile Gemfile.lock README.rdoc Rakefile app assets images javascripts application.js chart.coffee stylesheets application.css chart.scss scaffolds.scss controllers application_controller.rb chart_controller.rb 1 concerns helpers application_helper.rb chart_helper.rb mailers models concerns views layouts application.html.erb bin bundle rails rake setup spring config application.rb boot.rb database.yml environment.rb environments development.rb production.rb test.rb initializers assets.rb backtrace_silencers.rb cookies_serializer.rb filter_parameter_logging.rb inflections.rb
    [Show full text]
  • Javascript & AJAX
    JavaScript & AJAX JavaScript had to “look like Java” only less so—be Java's dumb kid brother or boy-hostage sidekick. Plus, I had to be done in ten days or something worse than JavaScript would have happened. JavaScript: the Big Picture(ELLS §11.1) © 2012 Armando Fox & David Patterson Licensed under Creative Commons Attribution- Image: Wikimedia. Used under CC-SA license. NonCommercial-ShareAlike 3.0 Unported License The Moving Parts • 1995: Netscape includes LiveScript JavaScript as browser scripting language • Originally, for simple client-side code such as animations and form input validation • Document Object Model (DOM) lets JavaScript inspect & modify document elements • 1997: standardized as ECMAScript • 1998: Microsoft adds XmlHttpRequest to IE5 • 2005: Google Maps, AJAX takes off JavaScript’s privileged position • Because it’s embedded in browser, JavaScript code can: 1. be triggered by user-initiated events (mouse down, mouse hover, keypress, …) 2. make HTTP requests to server without triggering page reload 3. be triggered by network events (e.g. server responds to HTTP request) 4. examine & modify (causing redisplay) current document DOM & JavaScript: Document = tree of objects • DOM is a language-independent, hierarchical representation of HTML or XML document • Browser parses HTML or XML => DOM • JavaScript API (JSAPI) makes DOM data structures accessible from JS code • Inspect DOM element values/attributes • Change values/attributes → redisplay • Implemented incompatibly across browsers …but jQuery framework will help us
    [Show full text]
  • Interface Evolution Via Virtual Extension Methods Brian Goetz Fourth Draft, June 2011
    Interface evolution via virtual extension methods Brian Goetz Fourth draft, June 2011 1. Problem statement Once published, it is impossible to add methods to an interface without breaking existing implementations. (Specifically, adding a method to an interface is not a source- compatible change.) The longer the time since a library has been published, the more likely it is that this restriction will cause grief for its maintainers. The addition of closures to the Java language in JDK 7 place additional stress on the aging Collection interfaces; one of the most significant benefits of closures is that it enables the development of more powerful libraries. It would be disappointing to add a language feature that enables better libraries while at the same time not extending the core libraries to take advantage of that feature1. V1 of the Lambda Strawman proposed C#-style static extension methods as a means of creating the illusion of adding methods to existing classes and interfaces, but they have significant limitations – for example, they cannot be overridden by classes that implement the interface being extended, so implementations are stuck with the “one size fits all” implementation provided as an extension2, and they are not reflectively discoverable. 2. Virtual extension methods3 In this document, we outline a mechanism for adding new methods to existing interfaces, which we call virtual extension methods. Existing interfaces can be augmented without compromising backward compatibility4 by adding extension methods to the interface, whose declaration would contain instructions for finding the default implementation in the event that implementers do not provide a method body.
    [Show full text]
  • Identitymodel Documentation
    IdentityModel Documentation Dominick Baier and Brock Allen May 11, 2021 IdentityModel 1 IdentityModel 3 2 IdentityModel.AspNetCore 5 3 IdentityModel.AspNetCore.OAuth2Introspection7 4 IdentityModel.OidcClient 9 5 oidc-client.js 11 5.1 Overview................................................. 11 5.2 Discovery Endpoint........................................... 12 5.3 Token Endpoint.............................................. 14 5.4 Token Introspection Endpoint...................................... 17 5.5 Token Revocation Endpoint....................................... 17 5.6 UserInfo Endpoint............................................ 18 5.7 Dynamic Client Registration....................................... 18 5.8 Device Authorization Endpoint..................................... 19 5.9 Protocol and Claim Type Constants................................... 19 5.10 Creating Request URLs (e.g. for Authorize and EndSession endpoints)................ 20 5.11 Fluent API for the X.509 Certificate Store................................ 22 5.12 Base64 URL Encoding.......................................... 22 5.13 Epoch Time Conversion......................................... 22 5.14 Time-Constant String Comparison.................................... 22 5.15 Overview................................................. 23 5.16 Worker Applications........................................... 23 5.17 Web Applications............................................ 25 5.18 Extensibility............................................... 27 5.19 Overview................................................
    [Show full text]
  • Ch08-Dom.Pdf
    Web Programming Step by Step Chapter 8 The Document Object Model (DOM) Except where otherwise noted, the contents of this presentation are Copyright 2009 Marty Stepp and Jessica Miller. 8.1: Global DOM Objects 8.1: Global DOM Objects 8.2: DOM Element Objects 8.3: The DOM Tree The six global DOM objects Every Javascript program can refer to the following global objects: name description document current HTML page and its content history list of pages the user has visited location URL of the current HTML page navigator info about the web browser you are using screen info about the screen area occupied by the browser window the browser window The window object the entire browser window; the top-level object in DOM hierarchy technically, all global code and variables become part of the window object properties: document , history , location , name methods: alert , confirm , prompt (popup boxes) setInterval , setTimeout clearInterval , clearTimeout (timers) open , close (popping up new browser windows) blur , focus , moveBy , moveTo , print , resizeBy , resizeTo , scrollBy , scrollTo The document object the current web page and the elements inside it properties: anchors , body , cookie , domain , forms , images , links , referrer , title , URL methods: getElementById getElementsByName getElementsByTagName close , open , write , writeln complete list The location object the URL of the current web page properties: host , hostname , href , pathname , port , protocol , search methods: assign , reload , replace complete list The navigator object information about the web browser application properties: appName , appVersion , browserLanguage , cookieEnabled , platform , userAgent complete list Some web programmers examine the navigator object to see what browser is being used, and write browser-specific scripts and hacks: if (navigator.appName === "Microsoft Internet Explorer") { ..
    [Show full text]
  • Appendix a and Appendix B
    This PDF contains 2 Appendices: Appendix A and Appendix B. Appendix A Answers to the Test Your Knowledge Questions This appendix has the answers to the questions in the Test Your Knowledge section at the end of each chapter. Chapter 1 – Hello, C#! Welcome, .NET! 1. Why can a programmer use different languages, for example, C# and F#, to write applications that run on .NET? Answer: Multiple languages are supported on .NET because each one has a compiler that translates the source code into intermediate language (IL) code. This IL code is then compiled to native CPU instructions at runtime by the CLR. 2. What do you type at the prompt to create a console app? Answer: You enter dotnet new console. 3. What do you type at the prompt to build and execute C# source code? Answer: In a folder with a ProjectName.csproj file, you enter dotnet run. 4. What is the Visual Studio Code keyboard shortcut to view Terminal? Answer: Ctrl + ` (back tick). Answers to the Test Your Knowledge Questions 5. Is Visual Studio 2019 better than Visual Studio Code? Answer: No. Each is optimized for different tasks. Visual Studio 2019 is large, heavy- weight, and can create applications with graphical user interfaces, for example, Windows Forms, WPF, UWP, and Xamarin.Forms mobile apps, but it is only available on Windows. Visual Studio Code is smaller, lighter-weight, code-focused, supports many more languages, and is available cross-platform. In 2021, with the release of .NET 6 and .NET Multi-platform App User Interface (MAUI), Visual Studio Code will get an extension that enables building user interfaces for desktop and mobile apps.
    [Show full text]
  • Web Development India
    WEB DEVELOPMENT INDIA Similar sites like www.tutorialspoint.com www.w3schools.com www.java2s.com www.tizag.com www.mkyong.com www.codecademy.com www.roseindia.net docs.oracle.com/javase/tutorial/ www.stackoverflow.com tutorials.jenkov.com imp……………………………………………….. http://www.xislegraphix.com/website-types.html http://orthodoxdaily.com/types-of-websites/ http://webstyleguide.com/wsg3/1-process/6-types-of-sites.html http://www.virtualmv.com/wiki/index.php?title=Internet:Types_of_Website http://www.marketingcharts.com/wp/online/which-types-of-websites-do-most-americans-visit- frequently-37970/ http://www.2createawebsite.com/prebuild/website-needs.html http://www.tomakewebsite.com/types-of-websites.html http://one-blog-wonder.tumblr.com/post/29818346464/what-types-of-websites-are-there http://www.roseindia.net/services/webdesigning/corporatewebsitedesign/Different-Kinds-of- Website.shtml http://www.marketingprofs.com/charts/2013/12083/which-types-of-websites-are-visited-most- frequently http://webdesignpeeps.com/types-of-websites/ http://www.webdesignerdepot.com/2011/11/navigation-patterns-for-ten-common-types-of- websites/ http://www.teach-ict.com/gcse_new/software/web_design/miniweb/pg2.htm http://www.methodandclass.com/article/what-are-the-different-types-of-web-site http://www.webmasterview.com/2013/03/three-types-of-website/ http://www.chinkin.com/Web-Design/Types-of-Website http://www.designer-daily.com/8-types-of-sites-you-can-build-with-drupal-13924 http://www.mediatopia.co.uk/types-of-websites .................................................................................WEB
    [Show full text]
  • Unobtrusive Javascript
    Unobtrusive JavaScript Unobtrusive JavaScript (Sample Chapter) Written by Christian Heilmann Version 1.0, July 2005-07-05 This document is copyright by Christian Heilmann and may not be fully or partly reproduced without consent by the author. If you want to use this information in part for presentations or courses, please contact the author. This is a free sample chapter, the whole course book is around 60 pages and covers the topic of Unobtrusive JavaScript in-depth with over 50 examples and demonstration files. You can obtain the complete course by donating a 2 figure amount at http://onlinetools.org/articles/unobtrusivejavascript/ Page 1 of 7 Unobtrusive JavaScript Unobtrusive JavaScript (Sample Chapter).................................................................................................1 Separation of CSS and JavaScript ........................................................................................................3 Our mistake .......................................................................................................................................3 Multiple class syntax..........................................................................................................................3 Applying classes via JavaScript ........................................................................................................4 Page 2 of 7 Unobtrusive JavaScript Separation of CSS and JavaScript You might have noticed in the previous examples that we are not exactly practising what we preach. Our mistake
    [Show full text]
  • A Comparison of C++, C#, Java, and PHP in the Context of E-Learning
    A Comparison of C++, C#, Java, and PHP in the context of e-learning MIKAEL OLSSON KTH Information and Communication Technology Master of Science Thesis Stockholm, Sweden 2009 TRITA-ICT-EX-2009:8 A Comparison of C++, C#, Java, and PHP in the context of e‐learning Mikael Olsson April 30, 2009 Master’s Thesis in Computer Science Royal Institute of Technology Examiner: Prof. Gerald Q. Maguire Jr. ‐ i ‐ Abstract The first part of this master thesis presents an effective method for producing video tutorials. This method was used during this thesis project to create tutorials on the e- learning site PVT (http://www.programmingvideotutorials.com). Part one also discloses how the production method was developed and how tutorials produced using this method compare to professional video tutorials. Finally, it evaluates the result of this thesis work and the efficiency of the production method. The second part of this thesis compares the syntactical similarities and differences between four of the languages taught via video tutorials for PVT. These languages are: C++, C#, Java, and PHP. The purpose of this comparison is to provide a bridge for programmers knowing one of these languages to rapidly learn one or more of the other languages. The reason why this would be necessary is because there is no single language suited for every area of software development. Knowing a multitude of languages gives a programmer a wider range of job opportunities and more choices in how to solve their problems. Part two of the thesis also includes a comparison of Java and C# in the context of a video tutorial series that shows how to build a basic text editor.
    [Show full text]