Monday, April 21, 2014

MVA Course: Developing ASP.NET MVC 4 Web Applications Jump Start (Modules 1 & 2)

Basic overview and ASP.NET MVC, with an emphasis on quickly getting into the code. First couple modules were relatively short (30-45 minutes) and easy to follow.




Note dump:

*******************************************************************************************
MODULE 1
*******************************************************************************************

Lesson 1: Overview of ASP.NET 4.5
Web Pages Applications
Web Forms Applications
MVC Applications
One ASP.NET
Shared ASP.NET Features
SLIDE NOTE: All three programming models are described in this lesson. However, students
will not see Web Pages or Web Forms in any further detail later in the course.
// MVC is built on ASP.NET: can also use web pages and web forms. Overall though, it is
// all ASP.NET.


Web Pages Applications
Web Matrix or Visual Studio
Code in .CSHTML files
Precise Control of HTML

<h2>Special Offers</h2>
<p>Get the best possible value on Northwind specialty
   foods by taking advantage of these offers:</p>
@foreach (var item in offers) {
  <div class="offer-card">
    <div class="offer-picture">
      @if (!String.IsNullOrEmpty(item.PhotoUrl)){
        <img src="@Href(item.PhotoUrl) alt="@item.Title" />
      }
    </div>
  </div>
}

Web Pages is designed as a simple server-side programming model that is quick to learn.
Ensure that you have built a simple Web Pages application before you teach this topic so
that you can highlight the differences between the programming models.
// web pages ok for smaller sites

Web Forms Applications
Visual Studio only
Code in .aspx files and code-behind files
Create a UI by dragging controls onto a page
Controls provide rich properties and events
Bind controls to data
Some of your students may be familiar with ASP.NET Web Forms because they have been
present since ASP.NET was introduced. If many students are familiar with Web Forms, you
may like to structure this topic as a discussion of the key features of this programming
model. This will enable you to assess students’ knowledge.
// traditional ASP. All control and event based
// does a lot of things "automagically"
// good for rapid application development
// similar to building a desktop app, difficult to control your HTML
// long term it requires discipline

MVC Applications
- Models encapsulate objects and data
- Views generate the user interface
- Controllers interact with user actions
- Visual Studio only
- Code in .cshtml and .cs files
- Precise control of HTML and URLs
// doesn't FORCE seperation of concerns, just makes it easier.
// controllers and models are classes - good for test driven development
// a lot easier to do CSS and JavaScript in the views

One ASP.NET: A framework for us all
// ASP.NET underlys the various web development models (pages, web forms, MVC)
The MVC programming model should be new to the audience for this course.

Shared ASP.NET Features
- Configuration
- Authentication
- Membership and Roles
- State Management
- Caching

// you can create hybrid applications that use elements from web forms and MVC
// in an MVC application you can add a web forms page
What does MVC look like?
Request comes in (user requests a URL)
The controller accepts the request and does some stuff
   if need be, the controller may access a model
Controller passes data from the model to the view.
The view turns this data into HTML and passes this back to the user

Lesson 3: Introduction to ASP.NET MVC 4
Models, Views, and Controllers
Demonstration: How to Explore an MVC Application

New Features of ASP.NET MVC 4
ASP.NET Web API
Mobile Features
Display Modes
Asynchronous Controllers
OAuth and OpenID
Bundling and Minification

Demonstration: Hello, MVC
In this demonstration, you will see how to:
Create a new project
Discuss the basics of the moving parts
Introduce MVC conventions
“See the Actors”
// you can add a view to a controller by right clicking in the controller and creating a
// veiw
// strongly typed controllers and models can make code cleaner (get intellisense)
// the view exists to display information, should not include a lot of logic
// model should be mostly dealing with data, not so much logic


*******************************************************************************************
MODULE 2
*******************************************************************************************

Lesson 1: Creating MVC Models
Developing Models
Using Display and Edit Data Annotations on Properties
Validating User Input with Data Annotations
What Are Model Binders?
Model Extensibility
Demonstration: How to Add a Model

Developing Models
public class Photo
{
   public int PhotoID { get; set; }
   public string Title { get; set; }
   public byte[] PhotoFile { get; set; }
   public string Description { get; set; }
   public DateTime CreatedDate { get; set; }
   public string Owner { get; set; }
   public virtual List<Comment> Comments { get; set; }
}
The slide shows a simple LDM diagram with two model classes: Photo and Comment. Each
class has a simple set of properties and there is a one-to-many relationship between the
classes; that is each photo can have zero or more comments.
The UML diagram on the slide shows both the Photo and Comment model classes and the
relationship between them. The code on the slide shows only the Photo class. Point out to
the students that the Photo class includes a collection of Comment objects – this
implements the one-to-many relationship between Photos and Comments.
// A model is JUST A CLASS. It is very basic, like any other class.
// one model can link to another
// It can hold complex data, byte array, complex types, whatever


Display and Edit Data Annotations
public class Photo
{
   // other properties excluded
   [DisplayName("Picture")]
   public byte[] PhotoFile { get; set; }

   [DataType(DataType.MultilineText)]
   public string Description { get; set; }

   [DataType(DataType.DateTime)]
   [DisplayName("Created Date")]
   [DisplayFormat(DataFormatString = "{0:dd/MM/yy}"]
   public DateTime CreatedDate { get; set; }
}
// centralizing code makes maintenance easier
// add metadata to the class
// these annotation allow you to describe a class
// not unique to MVC

Validating User Input with Data Annotations
public class Person
{
   public int PersonID { get; set; }

   [Required(ErrorMessage="Please enter a name.")]
   public string Name { get; set; }

   [Range(0, 400)]
   public int Height { get; set; }

   [Required]
   [DataType(DataType.EmailAddress)]
   public string EmailAddress { get; set; }
}
// we can use annotation to define how to validate a value and an error message to
// display when validation fails.
// MVC will generate HTML for you. If you say the input is email, MVC will use
// an HTML5 email input type.

What Are Model Binders?
- The Default Controller Action Invoker uses model binders to determine how parameters are
  passed to actions
- The Default Model Binder passes parameters by using the following logic:
- The binder examines the definition of the action that it must pass parameters to
- The binder searches for values in the request that can be passed as parameters
// user data could be in different places - query string, route data, form data...
// reading all the fields and recreating an object is a waste of time
// old way required using a.property = textbox.value ad nauseum.
// model binders will automagically link a form to a object, and we can just use our
// object in our code
// default model binder will work most of the time.
// NOTE: The "What is ASP.NET MVC?" video uses model binding


DEMO - Add a model
// CTRL+. is a useful keyboard shortcut in VS
// Why use a "Display" annotation versus just putting it in the view?
// We get validation and flexibility by using annotation

Lesson 2: Working with Data
The Entity Framework
Using an Entity Framework Context
Data Access in Models and Repositories

The Entity Framework
Types of Entity Framework Workflows
Database First
Model First
Code First
Question: You have a Visio diagram, which a business analyst created that shows all the model classes for your web application and their relationships. You want to recreate this diagram in Visual Studio. Which Entity Framework workflow would you use?
Answer: The model-first workflow is most appropriate because the designer in Visual Studio enables developers to create the model by drawing it.
Note: The Photo Sharing application that you create in the labs uses Entity Framework with the code-first workflow.

DEMO - Use entity framework
// based on convention, if we have a class named "speaker" and a public
// property called "speakerID", then code-first entity framework will pick it up as
// the primary key. You can also use just "ID" for the property. You can also
// customize these conventions.
// Linq is Language INtegraged Query. We need something between our app and the
// backend, which is what a context does... inherit from DbContext
// DbSet<> is a data-aware collection set
// virtual is like a foreign key - "Session" has "Speaker", allows lazy loading between
// them.
// We also want a context initiallizer
// this will inherit from DropCreateDatabaseAlways - use this for test, never for
// production.
// code first migrations can control how the app interacts with the database over time
// With entity framework, multiple ways to go - data first we already have a database, map
// it to our app. This demo uses code first, where entity framework takes our code and
// creates an app when we run the app.
// EF is smart enough to create database objects in the right order so we don't get
// FK constraint errors.

Data Access in Models and Repositories
This topic introduces the concept of separating repositories and models. Many MVC
projects do not separate these concerns Students may not use it in their own projects.
The model students develop in the lab does not use separate repositories. However,
repositories are an important concept and should be used when separation of concerns is
essential.
The code samples introduce the use of interfaces to describe implementation classes. This
is the first step toward loosely-coupled components, which will be described in Module 6
along with dependency injection. Loose coupling is essential for unit testing but is a
complex concept. By introducing interfaces and separation of concerns here, this topic
helps to prepare students for Module 6.
You will see how to create a loosely coupled architecture in Module 6.

// going through a repository or service will simplify things.
// queries and everything else should be done in the model.
// we can use repository as a go between, let it do all the work.
// if you have a lot of services, make a services folder and make a class
// very easy to mock repository for testing.

1 comment:

  1. The information you have given here are most worthy for me. I have implemented in my training program as well, thanks for sharing.


    Mobile Application Development Course

    ReplyDelete