Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

ASP.NET MVC 4 Mobile App Development
ASP.NET MVC 4 Mobile App Development
ASP.NET MVC 4 Mobile App Development
Ebook764 pages4 hours

ASP.NET MVC 4 Mobile App Development

Rating: 0 out of 5 stars

()

Read preview

About this ebook

A step-by-step tutorial to get acquainted with the ASP.NET MVC4 Framework and its features in order to discover how to develop web applications using them.This book is targeted at people who are familiar with C# development on the .NET platform and are interested in web development with the ASP.NET development framework. No prior web or mobile development experience is required
LanguageEnglish
Release dateJul 23, 2013
ISBN9781849687379
ASP.NET MVC 4 Mobile App Development

Related to ASP.NET MVC 4 Mobile App Development

Related ebooks

Programming For You

View More

Related articles

Reviews for ASP.NET MVC 4 Mobile App Development

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    ASP.NET MVC 4 Mobile App Development - Andy Meadows

    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 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 Packt

    Copy and paste, print and bookmark content

    On 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 Recipes { get; set; }

      IDbSet Reviews { get; set; }

      IDbSet Styles { get; set; }

     

    IDbSet UserProfiles { get; set; }

     

     

      int SaveChanges();

    }

     

    public class BrewHowContext : DbContext, IBrewHowContext

     

    {

      public IDbSet Recipes { get; set; }

      public IDbSet Reviews { get; set; }

      public IDbSet Styles { get; set; }

      public IDbSet 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

    Enjoying the preview?
    Page 1 of 1