ASP.NET MVC 4 Recipes: A Problem-Solution Approach ppt

619 1.8K 1
ASP.NET MVC 4 Recipes: A Problem-Solution Approach ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

www.it-ebooks.info 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. www.it-ebooks.info v 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 www.it-ebooks.info xxix Introduction e rst 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. at rst 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 Netix 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 t 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. e world expects that not only will your software work but also that it will get smarter, faster, more reliable, and easier to use. ese 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. e code may seem to t the need at that time but if it ever breaks, they do not know how to x it because they don’t understand it. is book was written to help ASP.NET MVC developers like you to quickly nd 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. www.it-ebooks.info 1 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. www.it-ebooks.info CHAPTER 1 ■ THE NEED FOR MODERN WEB APPLICATIONS 2 • 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 and personally identifiable information will not be exposed. Several recipes discuss security best practices, including Recipe 3-11, which shows you how to use the IIS Application Identity feature, and Recipes 10-2 and 10-3, which demonstrate how to protect against cross-site scripting attacks when creating custom HTML helpers. • Scalable: The application should be able to support thousands of concurrent users. Recipe 6-7 explains how to architect an ASP.NET MVC 4 application for Internet scale. Chapter 8 has several examples that demonstrate how to use .NET Task-based asynchronous programming to create a highly scalable application. Although not all applications will implement all the features listed here, as frameworks evolve and these features become easier to create, consumers will begin to expect them in the same way that car buyers expect a satellite navigation system to be an option in most new cars. 1-1. Developing Modern Web Applications on the Microsoft Platform Microsoft ASP.NET MVC Framework 4 is a solid web application framework with a growing developer community. Both the framework and its accompanying tools are actively developed and improved upon. If you have read the notoriously anti-Microsoft article, “Microsoft’s Lost Decade,” in Vanity Fair’s August 2012 issue, or other similar articles, you may have the impression that Microsoft is in big trouble. Although this article is not untrue, it does not tell the whole story. Contrary to what some media commentators have been suggesting, Microsoft is actually in a pretty good place. Products such as Kinect, Windows Phone 8, Windows 8, Skype, Direct X 11, and Windows Azure are not only keeping pace but are breaking new ground. Microsoft is perhaps the only vendor with enough technical depth for an ecosystem that starts in the consumer space—with technologies such as Xbox—and extends all the way into corporate applications and servers. www.it-ebooks.info CHAPTER 1 ■ THE NEED FOR MODERN WEB APPLICATIONS 3 Windows 7 was the fastest-selling desktop operating system in history and Windows 8 sold over 60 million copies in its first few months. Kinect for Xbox holds a world record as the fastest-selling consumer product, and one year later had a one million–unit sales lead over the brand-new console from Nintendo. With the Microsoft Surface and other Windows 8 tablets, Microsoft has a created a true challenger to the iPad and Android-based tablets. On the mobile front, even though Windows Phone 7 sales were poor, Windows Phone 8 has experienced better than expected results, with Nokia selling more than 4.4 million Lumia smartphones over the 2012 holiday season. The Windows desktop operating system still enjoys more than a 90 percent market share, even with an onslaught of new competitors. Microsoft Office is still the standard productivity suite for the vast majority of businesses around the world. Microsoft’s ASP.NET is the most popular commercial web application framework and, after PHP, the second-most popular web application framework overall. According to BuiltWith (http://trends.builtwith.com/framework/ASP.NET), ASP.NET is used on more than 20 million public web sites. Unfortunately, it’s not all good news. Over the past few years, the number of web sites that use ASP.NET and IIS has been slowly drifting south. Frameworks such as Django CSRF, a Python-based web framework, and Ruby on Rails have been slowly eating into Microsoft’s market share. Is ASP.NET a Dying Technology? ASP.NET is not a dying technology but rather a technology going through a transformation. ASP.NET Web Forms, which was all there was to ASP.NET before the MVC Framework came into existence, is in an undeniable decline. While Microsoft is continuing to support and improve Web Forms, the momentum is clearly moving toward the ASP. NET MVC Framework. In the same period that the overall ASP.NET platform saw a general decline, the ASP.NET MVC Framework has grown in usage by over 110 percent. The fastest growth in this trend is in the top 10,000 most popular web sites. Figure 1-1 shows a chart by BuiltWith, which depicts the number of web sites that are using ASP.NET MVC over a one-year period. It is based on statistics taken from over 90 million web sites. The chart has three line graphs, each representing a set of web sites grouped by popularity ranking. The bottom line shows growth as a percentage of sites ranked in the top one million web sites. The next two lines show the top 100,000 sites and the top 10,000 sites, respectively. www.it-ebooks.info CHAPTER 1 ■ THE NEED FOR MODERN WEB APPLICATIONS 4 With ASP.NET 4.5 and the MVC Framework 4, Microsoft has merged its innovations in web server technologies and development tools, and has incorporated lessons learned from many competing web development technologies. From Ruby on Rails, they have taken page routing, scaffolding, and the “convention over configuration” philosophy. Microsoft answered Sinatra, which provides a simple framework for creating RESTful web services, by introducing Web API. Node.js is a relatively new web development framework based on Google’s open-source V8 JavaScript runtime engine, which is the same engine built into the Google Chrome browser. It has been making major inroads on web sites because its event-driven, nonblocking I/O model makes it easier to design highly scalable applications. Microsoft’s response to Node.js is a new set of enhancements in the core .NET Framework and the new C# language features that make asynchronous programming with C# almost as simple as synchronous programming. When you combine the advances Microsoft has made in ASP.NET and the .NET Framework with its new set of front-end development tools, including its embrace of HTML5 and inclusion of third-party open-source JavaScript frameworks (Kinect API, WinRT, XNA Studio, and Expression Blend), you begin to see a picture of a modern development stack that is extremely competitive. Two common criticisms of Microsoft’s web technologies are that everything is a closed black-box system and that Visual Studio is too expensive. This is in major contrast to the platforms that it competes against, in which most of the tools and frameworks are open source and the development tools are free. Microsoft’s response to these criticisms was to open the MVC Framework source code to the community on CodePlex and to expand the capabilities of the free version of Visual Studio. Microsoft also created several programs for students, startups, and small businesses that grant free licenses for the commercial versions of Visual Studio, Windows Server, and SQL Server, and that offers free hosting in some cases. When you put it all together, the Microsoft platform and the ASP.NET MVC Framework provide a great foundation for developing modern web applications. Figure 1-1. ASP.NET MVC Usage Statistics (Source: BuiltWith.com) www.it-ebooks.info CHAPTER 1 ■ THE NEED FOR MODERN WEB APPLICATIONS 5 1-2. Learning Through Recipes Unlike most programming books that are designed to be read cover to cover in a sequential order, a recipe book like this one lets you read whatever you need in any order you wish. Each recipe is completely self-contained and, in most cases, does not assume that you have read other material in the book. Occasionally, recipes reference one another to minimize unnecessary replication of content, but most often the referenced content is not essential to complete the task described. Each recipe is broken into three sections. The first section is the Problem; it is the challenge that you face, such as how to create an MVC model using the Entity Framework Code First approach (Recipe 7-6). The second section, the Solution, provides a brief overview of the solution at a conceptual level; it is usually limited to one or two paragraphs. The bulk of the discussion, including the source code, follows in the How It Works section. 1-3. An Outline of This Book In the first few chapters, many of the recipes focus on the fundamentals of development with ASP.NET, the ASP.NET MVC architecture, and how to get the most out of Visual Studio. The remainder of the book deals with requirements solved by writing code. Chapter 2: Understanding ASP.NET MVC In Chapter 2, you will find recipes that help you understand the fundamentals of the Microsoft development ecosystem and the underlying concepts behind the MVC Framework. Recipes discuss the MVC Pattern (Recipe 2-3); the differences between MVC, MVVM, and MVP (Recipe 2-4); and the architecture of the MVC Framework (Recipe 2-6). Each of the main components of the MVC Framework, including the Model (Recipe 2-7), controllers and actions (Recipe 2-8), page routing (Recipe 2-9), and view engines (Recipe 2-10) is described in detail. Recipe 2-12 is a must-read for developers new to the Razor engine. It demonstrates each of the Razor syntax elements through examples. It can be used as a handy cheat sheet as you begin your development. The last recipe in this chapter demonstrates how to install an alternative third-party view engine called Spark. Chapter 3: Setting Up Your Environment Chapter 3 is a collection of recipes that tackle setting up your development environment, including choosing which version of the Windows OS to install (Recipe 3-2), setting up a virtual machine for development (Recipe 3-5), and installing Visual Studio 2012 (Recipe 3-7). Chapter 4: Visual Studio 2012 Overview The recipes in Chapter 4 cover the Visual Studio IDE in detail. Each recipe looks at a different feature, such as the Page Inspector (Recipe 4-8), the debugger (Recipes 4-9 and 4-10), and the Extension Manager (Recipe 4-13). Recipe 4-14 contains a comprehensive list of Visual Studio’s keyboard shortcuts. Chapter 5: Getting the Most from the Built-in Templates The ASP.NET MVC Framework 4 comes with many rich templates—each containing many files and referenced assemblies. The recipes in Chapter 5 dissect each template by looking at each assembly and NuGet package included, and by describing what the templates do and how you can use them to help implement your solution. www.it-ebooks.info CHAPTER 1 ■ THE NEED FOR MODERN WEB APPLICATIONS 6 Chapter 6: Architecting Applications with ASP.NET MVC In Chapter 6, the recipes take a step back from the code and look at how to apply the MVC Framework from the perspective of a solutions architect. Recipe 6-1 describes the role of the architect and why it is important for large projects. Recipe 6-2 looks at the decision on whether you should build a new solution or buy a packaged product. Recipe 6-3 discusses the decision of deploying to a private data center or a public cloud. Other recipes in the chapter look at different scenarios and describe reference architectures for each. Chapter 7: Solution Design This chapter looks at configuring the ASP.NET membership providers for real-world deployment (Recipe 7-10) and designing a model with the Entity Framework, as well as improving application startup performance (Recipe 7-7), and organizing your project into Areas (Recipe (7-9). Recipe 7-4 looks at what is needed to build a project that uses the Entity Framework for Oracle Data Provider and demonstrates how to set up your development environment to connect to an Oracle database. Recipe 7-6 shows how you can generate a database from your C# classes using Entity Framework Code First. Recipe 7-3 shows how to create an entity model from an SQL Server database. Recipe 7-5 shows the model-first approach. Chapter 8: Asynchronous Programming with ASP.NET MVC Chapter 8 takes a deep look at asynchronous programming with ASP.NET MVC and how multithreading is handled in Microsoft Internet Information Server (IIS) 7 and 8. With .NET 4.5, Microsoft has greatly simplified asynchronous programming. Unfortunately, without a firm understanding of how this technology works, using it can lead to problems that are difficult to diagnose and fix. The recipes in this chapter give you everything you need to start programming right away and they also teach the architecture, tradeoffs, and benefits of the technology so that you can better apply it. Recipe 8-1 shows how to create an asynchronous action using the Task-based asynchronous style with the async and await keywords. Recipe 8-3 demonstrates how to asynchronously consume a WCF service from an MVC controller action. Recipe 8-5 looks under the covers to help you understand the code generated by the C# compiler when using the async and await keywords. The last recipe in this chapter looks at how to troubleshoot performance problems using the built-in reporting features in IIS. It also looks at the differences between synchronous and asynchronous action under load by comparing the results of multiple performance tests. Chapter 9: Test-Driven Development with ASP.NET MVC 4 Chapter 9 is a collection of eight recipes dedicated to unit testing. Recipe 9-1 outlines how to create a testing strategy and how it can improve the quality of your application. Recipe 9-2 looks at creating unit tests for a controller action using MS Test. Recipe 9-3 demonstrates how to build an ASP.NET MVC application using a test-first approach and shows how to modify your application for testability using the tools built into Visual Studio. Recipes 9-6 and 9-7 discuss the NUnit unit-testing framework and demonstrate how to integrate it into Visual Studio to test an ASP.NET MVC application. Recipe 9-8 demonstrates creating a mock repository using the Moq library. Chapter 10: Moving from Web Forms to ASP.NET MVC In Chapter 10, the recipes address everyday tasks such as creating data grids that allow sorting , filtering, and paging, and demonstrate how the technique is done using ASP.NET Web Forms and how to convert the Web Forms code to www.it-ebooks.info [...]... on ASP.NET Web forms In March 2010, version 2 was released and included more than 15 new features, such as API improvements and support for ASP.NET 4 MVC 3 was released in January 2011 MVC 3 introduced the Razor view engine and many other features that simplified the creation of views and made it easier to maintain a separation of concerns In August 2012, MVC 4 was released, along with a massive wave... ASP.NET MVC 4 Internet Template • 11-1 Creating an Adaptive Multicolumn Layout Using CSS Media Queries • 11-2 Creating a Data Grid That Can Page and Sort Without Full-Page Postbacks • 11-3 Implementing Two-Way Data Binding Using Web API and Knockout • 11 -4 Creating a Custom Route for an API Controller • 11-5 Using Fiddler to Debug a Web API • 12-5 Enabling Large File Uploads in an ASP.NET MVC Application... project About the Sample Database To complement the code samples used in this book, I have included a fairly complex database that is made up of over 30 tables and contains thousands of records The data is based on publicly available data from a real music collaboration web site that is used by thousands of people around the world The sample database is used in many of the examples in this book, starting... Sorting, and Filtering Support • 10 -4 Creating a Data Grid That Allows Inline Editing 8 www.it-ebooks.info Chapter 1 ■ The Need for Modern Web Applications • 10-5 Creating a Master/Details View in ASP.NET MVC • 10-6 Custom Validators in ASP.NET MVC • 10-7 Moving from Master Pages in ASP.NET Web Forms to Layout Pages in Razor • 10-8 Creating a Multipage Wizard Using ASP.NET MVC • 10-9 Adding MVC to a Web... extensible and there are many places for developers to add customized functionality Some corporations have adopted SharePoint as an application platform where many teams can deploy their custom solutions onto a shared SharePoint infrastructure In many cases, the value-added functionality of SharePoint can dramatically reduce the amount of code that is required to create the solution There are several drawbacks... create a simple application For example, let’s say that you need to create a web site for your softball team and would like to expose a database of batting averages The simplicity of WebMatrix allows you to do this faster than if you did the same application using MVC in Visual Studio ASP.NET Web Pages is less ideal for a team of developers working on a large project For enterprise developers, ASP.NET. .. Understanding the MVC Pattern • 2 -4 Understanding the Differences Between MVC, MVVM, and MVP • 2-6 Understanding the ASP.NET MVC Framework Architecture • 3-11 Configure an Application Pool to Use an Application Identity • 6-7 Architecting an ASP.NET MVC Application for the Internet • 6-8 Architecting a Large-Scale Internet Application • 6-9 Architecting a Line-of-Business Application with ASP.NET MVC • 7-1... Framework model-first technique to map the sample database to an Entity Data Model For the sake of convenience, I have packaged this library into an external DLL that is also available in the Shared folder in the book’s code samples In addition to the code shown in Chapter 7, the library has some other useful utilities that are designed to make the sample applications more visually palatable For example,... MVC 4 It is available as a downloadable add-in for Visual Studio 2010, and is included by default with Visual Studio 2012 This is the first time that a new version of the MVC Framework has been released as part of a major version of Visual Studio This is a clear indication from Microsoft that the MVC Framework is now considered both mature and mainstream The growth in interest and activity in the MVC. .. WarningIconImageUrl="Images/alert-large.gif" Width="300px"> . 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. model-first approach. Chapter 8: Asynchronous Programming with ASP. NET MVC Chapter 8 takes a deep look at asynchronous programming with ASP. NET MVC and how multithreading is handled in Microsoft Internet. Registration Page on an Internet Site Created with the ASP. NET MVC 4 • Internet Template 11-1. Creating an Adaptive Multicolumn Layout Using CSS Media Queries• 11-2. Creating a Data Grid That Can

Ngày đăng: 31/03/2014, 15:20

Từ khóa liên quan

Mục lục

  • ASP.NET MVC 4 Recipes

    • Contents at a Glance

    • Contents

    • About the Author

    • About the Technical Reviewer

    • Acknowledgments

    • Introduction

    • Chapter 1: The Need for Modern Web Applications

      • 1-1. Developing Modern Web Applications on the Microsoft Platform

        • Is ASP.NET a Dying Technology?

        • 1-2. Learning Through Recipes

        • 1-3. An Outline of This Book

          • Chapter 2: Understanding ASP.NET MVC

          • Chapter 3: Setting Up Your Environment

          • Chapter 4: Visual Studio 2012 Overview

          • Chapter 5: Getting the Most from the Built-in Templates

          • Chapter 6: Architecting Applications with ASP.NET MVC

          • Chapter 7: Solution Design

          • Chapter 8: Asynchronous Programming with ASP.NET MVC

          • Chapter 9: Test-Driven Development with ASP.NET MVC 4

          • Chapter 10: Moving from Web Forms to ASP.NET MVC

          • Chapter 11: Creating Modern User Experiences Using jQuery, Knockout, and Web API

          • Chapter 12: Mobile, Social, and Cloud Technologies

          • 1-4. Finding the Recipes That You Need

            • Recommended Recipes for People New to Web Development

Tài liệu cùng người dùng

Tài liệu liên quan