ASP.NET MVC 4 Mobile App Development - Andy Meadows - E-Book

ASP.NET MVC 4 Mobile App Development E-Book

Andy Meadows

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

The ASP.NET MVC 4 framework is used to build scalable web applications with the help of design patterns and .NET Framework. The Model-View-Controller (MVC) is a design principle which separates the components of a web application. This separation helps you to modify, develop, and test different components of a web application.

ASP.NET MVC 4 Mobile App Development helps you to develop next generation applications, while guiding you to deal with the constraints the mobile web places on application development. By the end of the book, you will be well versed with all the aspects of mobile app development.

ASP.NET MVC 4 Mobile App Development introduces you to developing mobile web apps using the ASP.NET MVC 4 framework. Walking you through the process of creating a homebrew recipe sharing application, this book teaches you the fundamentals and concepts relevant to developing Internet-ready mobile-enabled web apps. Through the sample application, you will learn how to secure your apps against XSS and CSRF attacks, open up your application to users using third party logins such as Google or Facebook, and how to use Razor, HTML 5, and CSS 3 to create custom views and content targeting mobile devices. Using these custom views, you will then learn how to create web apps with a native mobile device feel using jQuery mobile. By the end of the book, you will be presented with a set of challenges to prove to yourself that you now have the skills to extend your existing web applications to the mobile web or create new mobile web apps.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 380

Veröffentlichungsjahr: 2013

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

ASP.NET MVC 4 Mobile App Development
Credits
About the Author
Acknowledgment
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Instant Updates on New Packt Books
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Developing for the Mobile Web
History of the mobile web
The Nokia 9000
Market fragmentation
WAP 1.0 and WML
WAP 2.0 and XHTML MP
Continued development constraints
Processing constraints
Network constraints
Content compression
Server to client compression
Minification
Image optimizations
Lower color depth
CSS image sprites
Data URIs
Content Delivery Networks
Cached data
Less traffic
Presentation constraints
Single window
Lower resolution
Content spacing
Viewing the mobile web
Market percentage
Browser variants and compatibility
WebKit
Trident
Gecko
Presto
Emulating the mobile web
Mobile device and browser emulators
Opera
Android
iOS
Windows Mobile
The user agent
Emulating Internet Explorer Mobile
Emulating Mobile Safari
Emulating Chrome for Mobile
Emulation in this book
Support for the mobile web in ASP.NET MVC 4
Summary
2. Homebrew and You
Understanding the homebrew domain
Knowing your ingredients
Malt
Yeast
Ale versus lager
Hops
Brewing
Mashing
Sparging
The boil
Fermentation
Bottling and kegging
About our mobile app
App requirements
Adding, editing, and deleting recipes
Adding recipes to a library
Rating recipes
Commenting on recipes
Anonymous browsing, authenticated contributing
The BrewHow solution
Creating the project
Choosing our template
The Empty template
The Basic template
The Internet Application template
The Intranet Application template
The Mobile Application template
The Web API template
Project changes in MVC 4
NuGet
Global.asax
Launching the BrewHow app
Responsive design
Configuring and launching an emulator
Summary
3. Introducing ASP.NET MVC 4
The Model-View-Controller pattern
The controller
The view
The model
The MVC pattern and ASP.NET MVC 4
Controllers in ASP.NET MVC
Creating the Recipe controller
Introduction to routing
Action methods
ActionResults
Invoking the Recipe controller
Views in ASP.NET MVC
Razor
The @ character
Code blocks
Expressions
Inline code
Comments
Shared views
Layouts
The _ViewStart file
Partial views
HTML helpers
Html.RenderPartial and Html.Partial
Html.RenderAction and Html.Action
Display templates
Html.Display
Html.DisplayFor
Html.DisplayForModel
Editor templates
Creating our Recipe view
Making Recipe default
Returning a model to the view
Using ViewData
Using ViewBag
Using TempData
Strongly typed models
Returning a Recipe list
Creating the model
Returning the model
Displaying the model
Summary
4. Modeling BrewHow in EF5
What's new in Entity Framework 5.0?
Performance enhancements
LocalDB support
Enumeration support
The BrewHow model
Modeling data
Recipe
Review
Style
Category
The BrewHow context
Generating our database
Altering the model
Adding relationships
Overriding conventions
Enabling migrations
The InitialCreate migration
The Configuration class
Adding seed data
Adding a migration
Applying migrations
Consuming the model
Pagination
Summary
5. The BrewHow Domain and Domain-driven Design
Tenets of DDD
Domain model
Entities
Value objects
Aggregates
Factories
Repositories
Services
BrewHow design
BrewHow entities
BrewHow repositories
Consuming the domain
Recipe view model
Data annotations
Recipe controller
GET versus POST
Model binding
Recipe views
Summary
6. Writing Maintainable Code
The SOLID principles
Single Responsibility Principle
Open Closed Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle
SOLIDifying BrewHow
Adding interfaces
Infrastructure
Dependency Injection
Service locator
Managed Extensibility Framework
Convention-based configuration
MEF Service Locator
Using the MEF Service Locator
Dependency Resolver
The MefDependencyResolver class
Completing the conversion
IBrewHowContext
Repositories
Registering dependencies
Summary
7. Separating Functionality Using Routes and Areas
Routes
Locating by style
Routing constraints
Style interaction
Recipe list modification
Style Controller and view
Slugging BrewHow
Model slugs
Stage the database
Modifying entities
Retrieval by slug
Areas
Creating the review area
Registering the Review area
The Recipe review controller
Recipe review view models
Recipe review action methods
Creating the views
Area route values
Routing namespaces
Summary
8. Validating User Input
Data validation
Data annotations
MetadataType attribute
Updating the database
Validating the validations
Server validation
Cross-Site Request Forgery (CSRF)
ValidateAntiForgeryToken
Cross-Site Scripting (XSS)
ValidateInput attribute
AllowHtml
Html.Raw
Summary
9. Identifying and Authorizing Users
User authentication
Windows authentication
Forms authentication
Authenticating BrewHow users
SimpleMembership
Customizing authentication
SimpleMembership initialization
Unifying contexts
The UserProfile repository
AccountController contexts
Registering and logging in
External authentication
Registering with an external account
Associating an external account
Authorization
Restricting access
The Authorize attribute
Authorizing user contributions
Cleaning the UI
Content ownership
Enabling ownership
UserProfile schema mapping
Seeding users
Applying the ownership migration
Assigning ownership
Enforcing ownership
Adjusting the view model
Ensuring ownership
Validating ownership
A recipe library
The library data model
The library repository
The library controller
The library view
Summary
10. Asynchronous Programming and Bundles
Asynchronous programming
Task Parallel Library
Task
Creating a Task
Awaiting completion
Completion callbacks
Async
Await
Asynchronous controller action methods
Creating asynchronous actions
An asynchronous recipe controller
Bundles
Creating bundles
Bundle types
Wildcard support
Consuming bundles
Summary
11. Coding for the Real-time Web
Simulating a connected state
Long polling
Forever Frame
Server-Sent Events
WebSockets
SignalR
Persistent connections
Hubs
Real-time recipe updates
Installing and configuring SignalR
Creating the recipe hub
Modifying the recipe list view
Publishing event notifications
Summary
12. Designing Your App for Mobile Devices
HTML5
Markup changes
The DOCTYPE tag
The character set
Type attributes
Visual Studio 2012 support
Semantic tags
The article tag
The header tag
The section tag
The nav tag
The footer tag
Modifying recipe details
Custom data attributes
Form controls
Local storage
Geolocation
CSS3
Media types
CSS selectors
Type selectors
ID selectors
Attribute selectors
Class selectors
Universal selectors
Pseudo-class selectors
CSS media queries
Media features
The viewport meta tag
A responsive design
A responsive list
Summary
13. Extending Support for the Mobile Web
Mobile views
A .Mobile layout
Mobilizing BrewHow
Removing content
Prioritizing content
How it works
Display modes
Supporting Asus Nexus 7
Creating the display mode
Registering the display mode
Testing with Nexus 7
Summary
14. Improving the User Experience with jQuery Mobile
Installing jQuery Mobile
Enabling the jQuery Mobile bundle
Viewing the results
jQuery Mobile's layout
Data-roles and data attributes
Form elements
Themes
$.mobile
View switcher
Mobilizing BrewHow
Adjusting the header
The home button
Logging in users
Site navigation
Creating a footer
Desktop footer
Configuring content
Recipe list
The jQuery Mobile listview
Expanded listview content
Listview filters
Buttons
Navigation hints
Recipe details
Back button
Action buttons
Recipe edits
Fieldcontain
Reviews
IsMobileDevice
Mobile views
Summary
15. Reader Challenges
Full-text search
Embedded search
Search boxes
APIs
Lucene.NET
SQL Server Full-text Search
Socialization
Social media support
Recipe additions
Recipe sharing
Offline support
Push notifications
Going native
ASP.NET Web API
Developing native apps
PhoneGap and Appcelerator
Xamarin
Summary
Index

ASP.NET MVC 4 Mobile App Development

ASP.NET MVC 4 Mobile App Development

Copyright © 2013 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: July 2013

Production Reference: 1160713

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-84968-736-2

www.packtpub.com

Cover Image by Abhishek Pandey (<[email protected]>)

Credits

Author

Andy Meadows

Reviewers

Shailendra Chauhan

Shiju Varghese

Acquisition Editor

Mary Jasmine Nadar

Commissioning Editor

Llewellyn F. Rozario

Lead Technical Editor

Neeshma Ramakrishnan

Technical Editors

Mausam Kothari

Rikita Poojari

Amit Ramadas

Project Coordinator

Arshad Sopariwala

Proofreader

Christopher Smith

Indexer

Hemangini Bari

Graphics

Abhinash Sahu

Production Coordinators

Manu Joseph

Nitesh Thakur

Cover Work

Nitesh Thakur

About the Author

Andy Meadows has been in a love affair with technology since his third-grade teacher introduced him to her TRS-80 Model III in 1981. After several months of typing "Go North" on the keyboard, he began his foray into BASIC programming. The TRS-80 Model III begat a Commodore 64 and an introduction to Pascal. By 1988, he was spending his summers earning money by writing software in C for local small businesses.

While attending college at the University of Georgia, Andy developed his passion for web development and, of course, beer. His first web application was a series of CGI scripts that output content for NCSA Mosaic and by 1994, he was designing web interfaces for global information systems.

After college, Andy wandered listlessly through the IT world spending time in several verticals using several different languages, but he always returned home to web development. In 2002, he began his foray into mobile development beginning with native Java development, and quickly moving into the mobile web space where he began marrying his two passions: mobile web development and .NET.

Since then, Andy has worked on several projects involving mobile development, web development, or both. He is extremely excited about the future of the mobile web made possible by the newest generation of mobile devices. He is currently working at a startup in Atlanta, where he lives with his wife and two children.

Acknowledgment

Writing this book was one of the biggest challenges I have ever undertaken. When originally approached with the idea for this book, I was hesitant. I'd heard horror stories about the sheer level of effort and commitment it takes to complete this task, but after consulting with the family I decided to try. Let me tell you, those stories are wrong. It was much, much more difficult than I had heard, but more fulfilling than I could have imagined.

The biggest commitment I had to make when writing this book was time. Lots and lots of time. Fortunately, I was blessed with a wonderful supporting cast.

I would first like to thank the people at Packt Publishing for their gentle encouragement and guidance through this process. They were truly a pleasure to work with, and their level of commitment to their authors and a quality product is evident in every action they take.

To my reviewers, thanks for the candid feedback—both critical and complimentary. This book is better because of you.

To my wife, Amy, and my two children, Noah and Nate, who permitted me to undertake this venture, thank you for your patience and support. And thanks for letting me take over practically every room in the house at one point in time as I attempted to find my muse. I sure must have done something right at one point to deserve the unconditional love you have shown through the long days at work, followed by the long nights in front of the computer. I love you all.

About the Reviewers

Shailendra Chauhan is an N-Tier Application Developer & .NET Consultant in Noida, Delhi, Gurgaon NCR region, India. He has 4.5 years of experience in building web applications using Microsoft Technologies including ASP.NET, MVC, C#, jQuery, SQL Server, WCF, Web API, Entity Framework, and many more web things. He loves to work with Internet applications using Microsoft technology and other related technologies.

He likes to share his experience and knowledge through his blogs www.dotnet-tricks.com and www.windowsappstutorial.com, which he started in Jan 2012. He strives to be the best he can be. He always tries to gain more knowledge and skills in Microsoft Technologies. He always keeps up with new technologies and learning new skills that allow him to provide better solutions to problems.

Shiju Varghese is a Microsoft MVP and a Technical Architect, specializing in Cloud, Mobility, and Web technologies. His current technology focus is on Windows Azure, ASP.NET MVC, Node.js, HTML 5, and CQRS. Shiju is passionate about building Cloud apps on the Windows Azure Platform. His areas of interest include Cloud Computing, Enterprise Mobility, Agile software development, Domain-Driven Design (DDD), Test-Driven Development (TDD), and Web application scalability. Shiju has been working with .NET technologies since its inception.

Shiju works as a Technical Architect in Marlabs Inc where he is focusing on Cloud apps with Windows Azure.

Thanks to my lovely wife, Rosmi, for her support and motivation. I would also like to thank my daughter, Irene Rose.

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. 

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Instant Updates on New Packt Books

Get notified! Find out when new books are published by following @PacktEnterprise on Twitter, or the Packt Enterprise Facebook page.

Preface

Today's web developers are faced with a multitude of challenges in delivering their product to market. Once upon a time, applications only needed to look and function properly within Internet Explorer. Today's applications must not only function within multiple browsers, but on multiple operating systems running on multiple devices.

ASP.NET MVC 4 Mobile App Development is meant to serve as a guide to successfully building web applications that target current desktop browsers and browsers meant to consume the mobile web.

ASP.NET MVC 4 Mobile App Development walks you through the process of creating a web application from concept to delivery.

What this book covers

In the first section of this book, we build a fully functional sample application to manage and share recipes for homebrewed beers. Chapter 1, Developing for the Mobile Web, begins with a discussion on the importance of understanding how to develop for the mobile web. You are then given a brief history of how we arrived to at the mobile web of today. The chapter ends by discussing all of the constraints we, as developers, must acknowledge if we are to successfully develop applications for the mobile web.

Chapter 2, Homebrew and You, introduces you to the domain of homebrewing and BrewHow—our homebrew recipe sharing application. From our understanding of this domain we build the requirements for our application and then examine how ASP.NET MVC 4 and its new features will help us develop it. We conclude the chapter by setting up our environment to launch our mobile emulator to design and test our application.

Chapter 3, Introducing ASP.NET MVC 4, introduces the MVC pattern. We then discuss how it is implemented within ASP.NET MVC 4 as we begin to build our application. By the end of this chapter the initial shell of our application will be complete and running inside our desktop and mobile browsers.

Chapter 4, Modeling BrewHow in EF5, walks us through creating a data model for BrewHow. We begin by discussing the new features and improvements of Entity framework and create a data model and database for our domain using the code-first model in EF. The model and database are continually refined through the use of migrations until the needs of our application are met and our application is consuming data from LocalDB.

Chapter 5, The BrewHow Domain and Domain-driven Design, introduces us to the tenets of DDD. We apply these tenets to BrewHow by creating repositories, view models, and domain entities to enforce the boundaries between persistence, logic, and display.

Chapter 6, Writing Maintainable Code, begins with a discussion on the SOLID principles of object-oriented design; principles that serve to facilitate the writing of maintainable code. We then review the topics of Dependency Injection and Inversion of Control as tools to help us SOLIDify the BrewHow codebase. This chapter ends by applying these principles and tools to the codebase leveraging the extension points provided to us by ASP.NET MVC 4.

Chapter 7, Separating Functionality Using Routes and Areas, provides a detailed discussion on this key piece of technology in ASP.NET MVC 4. We examine how, by leveraging routing and areas, we can create meaningful SEO-friendly URLs and separate the functionality of BrewHow into discrete units of work for the content contained within BrewHow. We then exercise our knowledge by adding support for user reviews.

Chapter 8, Validating User Input, looks at the server-side support for data validation contained within the .NET Framework's System.ComponentModel.DataAnnotations namespace. The data model and view models are modified to support the use of these attributes so we can validate input on the client side and again once the data has made it to the server. We also explore how these technologies help protect BrewHow from common web attacks such as CSRF and XSS.

Chapter 9, Identifying and Authorizing Users, introduces the new membership functionality available in ASP.NET MVC 4. BrewHow is modified to support user authentication using the new membership functionality and we then modify the application to allow authentication using a Google login. We end the chapter by tying together the BrewHow data model with the membership data model so we can associate recipes and reviews with the users that created them.

Our application is now functionally complete and has met all of the requirements set forth in Chapter 2, Homebrew and You. In the second section of the book we take a look at a few advanced features provided by ASP.NET MVC 4. Chapter 10, Asynchronous Programming and Bundles, explores how we can design the server-side portion of our application to get information to our users more efficiently and with less wait time—something critical for mobile applications. To accomplish this, we begin by examining and then implementing support for asynchronous actions. We then examine the support of minification provided to us in the form of bundles.

Chapter 11, Coding for the Real-Time Web, investigates how we can use always-on connectivity to provide the illusion of a desktop application within BrewHow. We then leverage SignalR to simulate push notifications from the server to BrewHow.

With our application fully optimized to deliver content to mobile devices, we can now begin the third part of the book. Chapter 12, Designing Your App for Mobile Devices, discusses how we can use the next-generation of web standards, HTML5 and CSS3, to create responsive markup to present our content to users in a manner best fitting the device on which they are viewing it.

Chapter 13, Extending Support for the Mobile Web, extends the concept of mobile design to our servers as we explore the mobile view support built into ASP.NET MVC 4. We then extend this concept to target specific mobile devices using the new support for display modes.

Chapter 14, Improving the User Experience with jQuery Mobile, shows how BrewHow can be converted to a mobile web application that looks and feels as if it were native to the device. We look at some of the controls provided by jQuery Mobile and apply them within the context of everything we have learned to build a fully polished and functional mobile application.

Chapter 15, Reader Challenges, presents how BrewHow could be extended to be an even richer experience for the user. We discuss how full-text search technology could be integrated into BrewHow, how we might provide support for social networking, and how we might even extend BrewHow into a truly native mobile application. The readers are then encouraged to undertake these tasks themselves.

What you need for this book

To build the sample application within this book you will need a copy of Microsoft Visual Studio Express for Web 2012. To view the sample application you will need a web browser capable of supporting HTML5 and CSS3. The sample application in this book was tested using the current version of Google Chrome and Opera Mobile Emulator running on Windows 8.

Who this book is for

This book is for any individual wishing to learn ASP.NET MVC 4 and its role in developing applications that target the mobile web. The material in this book assumes the reader has familiarity with the .NET framework and exposure to C#. If you are new to ASP.NET MVC and want a good solid introduction, if you want to learn what's new in ASP.NET MVC 4, or if you want to learn how you can modify your web applications to support multiple devices this book is for you.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: " In prior versions of MVC, all of the application bootstrap code was located in the Global.asax code-behind".

A block of code is set as follows:

.white-go { width:31px; background:url('img-sprite.png') 0 0; } .orange-go { width: 31px; background:url('img-sprite.png') -32px 0; }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

public interface IBrewHowContext { IDbSet<Models.Recipe> Recipes { get; set; } IDbSet<Models.Review> Reviews { get; set; } IDbSet<Models.Style> Styles { get; set; } IDbSet<Models.UserProfile> UserProfiles { get; set; } int SaveChanges(); } public class BrewHowContext : DbContext, IBrewHowContext { public IDbSet<Models.Recipe> Recipes { get; set; } public IDbSet<Models.Review> Reviews { get; set; } public IDbSet<Models.Style> Styles { get; set; } public IDbSet<Models.UserProfile> UserProfiles { get; set; } public BrewHowContext() : base("DefaultConnection") { } /* ... */ }

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Select the ASP.NET MVC 4 Web Application icon and provide a name and location for the new project in the Name and Location text boxes respectively".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Developing for the Mobile Web

If you are at all interested in developing web apps in the future, it is important you understand the increasing role played by mobile devices, and how to develop apps fitting their capabilities. I'm saying this not to scare you into buying my book (though I hope that you are currently reading your purchased copy), but to underscore the fact that mobile computing will play an increased role in the lives of every connected person.

To appreciate the growth in mobile usage, one should consider the iPhone. The iPhone, typically heralded as the smartphone that began the current mobile computing revolution, wasn't introduced until 2007. At the end of 2008, more than a year after its release, mobile traffic accounted for less than 1 percent of the global Internet traffic, which was not much of a revolution.

However, by the end of 2010, mobile traffic accounted for nearly 5 percent of all the Internet traffic, and at the end of 2012 it was nearly 13 percent. Halfway through 2013, mobile traffic has passed 15 percent of all the Internet traffic. This trend is roughly a multiplier of 1.5, year-over-year, and is likely to accelerate.

In the 4th quarter of 2012, iPad sales reached approximately 140,000,000 total units shipped, approximately 3 times the total number of iPhones shipped. The iPad was introduced 3 years after the iPhone, and just 3 years after the tablet revolution was launched by the iPad, total tablet shipments in the 4th quarter of 2012 surpassed both desktop and notebook shipments.

As developers, it is important we understand and embrace this mobile revolution or else we will be run over by it.

Throughout this book, we will be building a fully functional web app using ASP.NET MVC 4, HTML5, and CSS3 to support both desktop and mobile computing platforms. We will begin with building the desktop version of the web app but will be keeping mobile considerations in mind.

Once our desktop app is complete, we will modify it to support the mobile web using concepts such as responsive design and media queries. During this modification, we will examine the new features of ASP.NET MVC 4 we can use to better target mobile web devices.

In the last chapters of this book, we will modify the app to support a truly mobile experience using jQuery Mobile. It is my goal that, by the end of the last chapter in this book, you will have a complete understanding of what it takes to develop for the mobile web, and the tools to take your mobile web apps to the next level.

In this chapter, we will begin by examining a history of the mobile web. This understanding is essential in appreciating the unprecedented growth in the past few years. This chapter will also highlight some of the constraints that existed, and still exist, when trying to target the mobile devices of yesterday, today, and tomorrow. We will end with a preview of the new platform support in Microsoft ASP.NET MVC 4.

Our journey into the mobile web begins now.

History of the mobile web

Without knowing how the mobile web started, it's impossible to appreciate the ease with which we can develop for mobile devices. If the mobile web works at all, it is a feat in itself, and it took the convergence of several technologies to make it all possible.

The Nokia 9000

The Nokia 9000 is, arguably, the first mobile web device. Developed by Nokia in 1996, this phone weighed in at a whopping 14 ounces (397 g), and was powered by an Intel i386. It was equipped with a 640 x 200 pixel gray-scale LCD. This phone allowed owners to send faxes, send and receive email, and surf the web. It also came equipped with terminal and Telnet applications for accessing mainframe systems.

Market fragmentation

During this time, Nokia was in competition with Ericsson and others for control of the mobile data space. The Nokia 9000 was designed to use Narrow Band Sockets, a communication protocol developed and championed by Nokia. Information that was to be displayed on the Nokia 9000 was returned to the phone using Tagged Text Markup Language (TTML), a markup language that content providers could use to optimize web pages for mobile devices by removing extraneous information from the display and transmission.

At about the same time, Ericsson had developed Intelligent Terminal Transfer Protocol (ITTP). ITTP was Ericsson's proprietary markup for the mobile web.

It became evident to the major phone manufacturers that market fragmentation was going to be inevitable unless they could develop a common standard to enable the mobile web on their devices.

WAP 1.0 and WML

On June 26, 1997, Nokia, Ericsson, Motorola, and Unwired Planet publicly announced that they would be cooperating on a Wireless Application Protocol (WAP). WAP 1.0 was to be an open protocol that any vendor could implement, and this new protocol would enable mobile device manufacturers to connect to the IP-based world of the Internet from mobile devices that had an inherently high rate of data loss during communication.

Wireless Markup Language (WML) became the standard for designing applications that ran on WAP 1.0, and was a second-generation derivative of HTML and XML.

However, WAP and WML had some shortcomings. The protocol and companion markup languages were designed for very slow data networks and very limited display capabilities. If your device had limited data input capabilities and a low-resolution display, then WML served you well, but with the advent of smart phones and mobile web browsers, derivatives of their desktop counterparts, WAP 1.0 and WML became less relevant.

WAP 2.0 and XHTML MP

As the convergence of mobile phones and PDAs gained momentum, new standards were needed to support the growing use of web-enabled mobile devices. To support the new browsers that began to ship with mobile devices, a new markup language was required.

In 2001, eXtensible HyperText Markup Language Mobile Profile (XHTML MP) was adapted from XHTML Basic by the WAP Forum (now part of the Open Mobile Alliance) to replace WML as the default protocol for WAP.

Note

While WAP became the standard in the United States, United Kingdom, and Europe, the standard in Japan, i-mode, was developed by NTT DoCoMo.

The new standards were short-lived. Today, most mobile devices ship with browsers supporting the latest HTML standards including HTML5 and CSS3, but it is still a good practice to deliver content to target the broadest market possible.

Continued development constraints

Having modern browsers on our phones, tablets, and other mobile devices doesn't mean we should make no accommodation for users of the mobile web. There are still many real-time constraints placed upon mobile devices which we, as developers, should take into consideration when writing mobile web apps. We can't simply shrink down the desktop version of our web app and provide a satisfying experience to the user. One must keep in mind when developing mobile apps that the mobile devices on which our app is being executed have different processing, network, and presentation constraints than their desktop counterparts.

Processing constraints

Today's mobile devices have several times the processing power of the Apollo Guidance Computer that put humans on the moon. They do not, however, have infinite processing power and have much less processing power than the common PC has at its disposal.

To accommodate the lack of processing power, mobile web apps should refrain from running highly intensive JavaScript functions, image manipulation, or any other processor-intensive operations in your app unless it is absolutely necessary to the functionality of the app.

One way to reduce the load on the client is to make certain determinations on the server before returning content back to the mobile device. This practice, referred to as server-side browser sniffing, allows the application to return web pages and content targeted for a specific device, and limits the need to do browser capability checks on the client. It is during this time that you can also preprocess data that would be returned to the client for processing otherwise. This is a shift from current web development trends where data is typically submitted to the client for processing.

By reducing the amount of content that is returned to the client by the server, you also mitigate some of the network constraints inherent to mobile devices.

Network constraints

While today's mobile networks rival, and in some cases surpass, speeds available to home-based broadband networks, your users may be constrained by data limits, speed governance, corporate policy, or some other constraint on the limit or speed at which they can retrieve data on their mobile device.

Mobile networks also inherently lose more network data in transmission than land-based communication. This data loss has two effects on the application and the user experience. Firstly, packet loss requires the TCP/IP stack implementation to request resends for lost packets and increases the amount of data that must be sent across the network. Secondly, your app needs to be written such that it can survive failed requests because it's guaranteed to happen.

How do we, as developers, ensure that our mobile web apps provide a great user experience on such a network?

Content compression

We can start reducing the amount of data representing content we're sending to the client by compressing it on the server side.

Server to client compression

Content compression can occur as part of the communication between client apps and web servers that support it. Content compression works by serving static, and occasionally dynamic content, and compressing it using gzip or deflate before returning it to the requesting app.

For a client to indicate that it can accept and process content, it must send an Accept-Encoding HTTP header with the request with the types of encoding it will accept.

Accept-Encoding: gzip, deflate

Enabling compression on the server is vendor and version-specific. It should be noted that while enabling compression on the server for communication does reduce the amount of data the server must send, it increases server processor utilization.

In addition to compression, we can also reduce the amount of data that needs to be sent to the client through a process called minification.

Minification

Minification is the act of removing extraneous white space from our HTML, CSS, and JavaScript files. Minification is not compression in the typical sense. The benefit of minification is that while you have reduced the amount of data you are sending to the client, it is immediately usable because nothing functional from that data has been removed.

Some minification techniques can also serve as a way to obfuscate JavaScript making it harder for people with ill intent to decipher what your code is doing. This is accomplished by parsing the content that is being minified and renaming long variables to between 1 and 3 characters.

Tip

Think Security

Never perform any action on the client that requires you to expose keys, usernames, passwords, or other sensitive information. Transmitting this information to the client is inviting mischief.

Image optimizations

Images make up a large percentage of the content your app will be serving to the client. Outside of minification, image optimizations may be one of the fastest ways to reduce the size of your app.

Lower color depth

Perhaps the easiest way to optimize images on your site is to reduce their color depth. Most images on the web are icons that can easily be represented with images of 8-bit or 16-bit color depth. With that said, it is an art more than a science. As today's mobile device displays increase their pixel depth, images of poor quality can detract from the functionality of your site and may discourage some users from using it.

CSS image sprites

An image sprite is a single image (that contains multiple images) that might be used on a site. The image sprite is then referenced by the stylesheet with different image offsets to only show a portion of that image. The following image from the Packt Publishing website (www.packtpub.com) is an example of an image sprite:

This image is actually a single image that contains two images for the site to use. Both images are 31 x 31 pixels. From this image we can create the following two styles:

.white-go { width:31px; background:url('img-sprite.png') 0 0; } .orange-go { width: 31px; background:url('img-sprite.png') -32px 0; }

Firstly, note that the styles both have a width that is limited to the width of the actual image we want to display, that is, 31 pixels.

The white-go class sets the background image of the element which is applied to the sprite and sets the offset of the image to be the top-left corner, that is, 0,0. Since the image is restricted to 31 pixels wide, the viewer of the image will only be presented with the portion of the image containing the white go button.

The orange-go class has a negative offset to the image display telling the browser to show 31 pixels of the image starting at pixel 32. This displays only the orange image.

Both images may be reused by the app by applying the defined styles to the elements within the HTML markup, but the true benefit is that the app only made one request to the server to retrieve both images.

Data URIs

Data URIs (Universal Resource Identifiers) allow you to put content data directly into a URI link. The URI is formatted using the data:[<mediatype>][;base64],<data> format. From RFC 2397, the data URI scheme is defined as follows:

The <mediatype> is an Internet media type specification (with optional parameters). The appearance of ";base64" means that the data is encoded as base64. Without ";base64", the data (as a sequence of octets) is represented using ASCII encoding for octets inside the range of safe URL characters and using the standard %xx hex encoding of URLs for octets outside that range. If <mediatype> is omitted, it defaults to text/plain;charset=US-ASCII.

Assume we want to embed the following simple image in a page using a data URI:

If you were to embed the image above as a base-64 encoded PNG data URI into a page on your site, you would construct a data URI in your HTML source.

This provides the browser the benefit of not having to make a separate request to retrieve the image. With some clever JavaScript and CSS you could reuse the content of the URI without submitting another request to retrieve the image or embedding the image twice into the page.

As part of the page content, there is a second added benefit: the image data is compressed when sent from the server to the client as part of the web server's gzip compression.

Note

Data URIs are not supported in all browsers. If you elect to use data URIs in your site, make sure that your target market's primary browser supports them.

Content Delivery Networks

AContent Delivery Network (CDN) is a distributed network of servers that exist solely for returning static content. CDNs can reduce network load by hosting static content that is commonly cached and reducing the amount of data an application sends and receives for any given request.

Cached data

If you are using common third-party libraries such as jQuery, the mobile device executing your app may have already loaded that library from a third-party CDN. If the device has already retrieved the data you want to load, there is no need for the client to retrieve it again from the server. It can simply load it from the cache. There are several free CDN networks available for common content. As of this writing, Microsoft hosts a large amount of common third-party content on its CDN, of which a listing may be found at http://www.asp.net/ajaxlibrary/cdn.ashx.

As a routine point of maintenance, you will want to make sure the CDN you are using for shared content continues to provide the content. If they remove the content, your app will eventually degrade or fail.

Less traffic

A CDN is also useful for your proprietary static content. If you are using cookies within your site, every HTTP request to the domain specified in the cookie will retransmit the cookie data. Static content has no need for this data and it is consuming bandwidth that could be used elsewhere. If you move the static content of your site onto a different domain than the domain(s) on which your cookies reside, you reduce the amount of data sent to and from your app.

Tip

Don't make them wait

While it is critical to limit the amount of time any user has to wait to load your app's content, this is especially true of mobile web apps.

Presentation constraints

Processing constraints and network constraints help define how you implement your background services, but it is what the user sees that typically defines their experience. When presenting the content of your app to the user you need to keep in mind there are very real constraints placed on how information is presented to the user.

Single window

For starters, you only have a single window in which you can work. This means you should not be creating content that requires pop-up windows. Pop-up windows will open up in new tabs on most mobile browsers and those browsers may have limits as to the number of tabs open at any given time.

It is far better to stick with a simple navigation paradigm, and reduce the amount of data you present to the user at any given time. The user may have a few more screen touches to navigate through your application, but if you make the behavior consistent then it is unlikely your users will notice.

Lower resolution

With the exception of the newest mobile devices on the market, most devices do not have the resolution of their desktop counterparts.

Comparing standard phone form factors, the iPhone 5 has a screen resolution of 1136 x 640 pixels and the Samsung Galaxy S3 has a resolution of 1280 x 720. Of the popular 7-inch tablets, both the Kindle Fire HD and Google Nexus 7 have a screen resolution of 1280 x 800. Only the largest tablets such as the 10-inch third generation iPad (2048 x 1536) and the 8.9-inch Kindle Fire HD (1920 x 1200) come close to matching a desktop's display capability.

By way of comparison, the iPhone 4 and iPhone 4S have a resolution of 960 x 640.

While these resolutions seem respectable for mobile devices you must keep in mind that these resolutions are presented on screens that are substantially smaller than a desktop monitor, meaning not only is the number of available pixels for your app reduced on these smaller displays, but your app needs to present content, text, and buttons larger than it would to a desktop browser. This is partly because of the increased pixel density of the mobile devices, and partly because the input mechanism to these devices is your user's finger.

Content spacing

Designing a system to support touch instead of traditional input methods of mouse and keyboard mean that your buttons need to be larger, and a larger area of padding must surround any area of the screen that is designed for interaction with the user. This means your user interface and user experience must account for a large percentage of spacing.

Viewing the mobile web

While most of us own one, two, or perhaps three or more mobile devices with which we can browse the web, we need to develop our mobile web applications to support the broadest number of devices possible.

Market percentage

It is important for us to look at what technology is being used to browse the mobile web, so that we can target our mobile app appropriately. Currently, Android and iOS dominate the mobile OS market, but the newest version of Windows Mobile is gaining market share. Supporting the common browsers on these operating systems should be sufficient for most application needs.

Browser variants and compatibility

How does