introducing asp.net mvc 4 and entity framework

of 61 /61
An Intertech Course Introducing ASP.NET MVC 4 and Entity Framework Intertech’s Oxygen Blast – November 26, 2013 Davin Mickelson, [email protected]

Author: others

Post on 12-Feb-2022

5 views

Category:

Documents


0 download

Embed Size (px)

TRANSCRIPT

Introducing MVCIntertech’s Oxygen Blast – November 26, 2013
Davin Mickelson, [email protected]
FrontPage and Visual InterDev, FPSEs, ASP, COM.
Perl, ColdFusion <cftag>, ASP.NET: C#, VB.NET, F#.
Intertech Consultant/Instructor since 2005.
Programming in HTML5 with JavaScript and CSS3 (5 days).
Developing ASP.NET MVC 4 Web Applications (5 days).
Programming in C# (5 days)
Developing Applications Using Entity Framework 4.1 (2 days).
I teach .NET, SQL Server BI, TFS, jQuery, MVC, HTML5, etc.
Intertech blog: http://www.intertech.com/blog
New fishing hat
doesn’t work!
ASP.NET MVC 4 Agenda, 1 of 3
Purpose/History of MVC 4
Versions/Features of MVC/Visual Studio
Routing
Entity Framework Agenda, 2 of 3
Purpose/History of EF
MVC & EF Futures, 3 of 3
ASP.NET MVC 5
Three ASP.NET Web App Architectures
ASP.NET Forms
Visual Studio 2002+
ASP.NET Web Pages
Visual Studio 2008+ Web Site or WebMatrix (free!)
ASP.NET MVC
Today, we will look this architecture!
<DEMO>
Intertech
What is MVC? Model – View – Controller (MVC)
Originally developed in 1978 with Smalltalk at Xerox PARC
In recent years, MVC has been used as a Web framework
MVC is used with Java and Ruby
Jakarta Struts, Ruby on Rails, JSF, Spring, and more
“Separation of Concerns”
The model, the view, and the controller are broken into
separate domains
These domains may or may not be defined in separate
methods, classes, or assemblies
There is no hard set of rules but rather conventions
Intertech
Copyright © Intertech, Inc. 2013 • www.Intertech.com • 800-866-9884 • Slide 8
Introducing ASP.NET MVC Popular new way to develop ASP.NET Web applications.
MVC applied to the ASP.NET framework.
Already been done before with ALT.NET! Example:
Castle MonoRail http://www.castleproject.org/projects/monorail/
Based on file and folder naming conventions.
High quality coding promoted by unit testing.
Test Driven Development (TDD) is supported.
Support for DI / IoC frameworks.
Ninject, StructureMap, MEF, Castle Windsor, Spring.NET,
Autofac, Unity, etc.
Simplifies testing parts of an app by using mock objects.
Copyright © Intertech, Inc. 2013 • www.Intertech.com • 800-866-9884 • Slide 9
Why Use ASP.NET MVC? Hate the resource wastefulness of standard ASP.NET forms.
Need unit testing.
Prefer greater control over the HTML, CSS, and JavaScript sent to
the Web browser.
(SEO).
Have previous experience with the MVC model in another language.
Tired of standard Web forms and want to try something new and
cool!
Intertech
Copyright © Intertech, Inc. 2013 • www.Intertech.com • 800-866-9884 • Slide 10
Why NOT Use ASP.NET MVC? Already supporting a large ASP.NET Web forms project that doesn’t
need this architecture.
Prefer ASP.NET Rapid Application Development (RAD) environment
(drag and drop).
Not a professional web developer. Prefer the simplicity of Web pages
in WebMatrix.
Prefer controls having automatic state management (ViewState).
Don’t need this level of control over the final HTML, CSS, and JS.
Haven’t had time to sharpen your C#/VB programming skills with:
HTML/CSS/JS, Lambda operator, LINQ, Extension methods,
Entity Framework, etc.
ASP.NET MVC vs. ASP.NET Forms ASP.NET Web Forms ASP.NET MVC
We know this stuff already! Entirely new model we must learn
Supports ASP.NET Server Controls Primarily supports raw HTML/JS
Automatic state management of controls Manual state management
Drag and drop controls “Scaffolded” (wizard) views and manual
Web page coding
Been around since 2002 1.0 released on April 9th, 2009
Weak or custom unit testing required Encourages and includes unit testing
support!
Both ASP.NET frameworks are supported in VS 2008/2010/2012/2013+
Both have access to the five intrinsic objects (Session, Application, etc.)
Both support the use of the ASP.NET Provider models
(Membership, Profile, Sitemap, and more)
Both support EF and the popular JavaScript libraries: Modernizr, jQuery, etc.
Intertech
ASP.NET MVC - Five Versions
ASP.NET MVC is a revolutionary step for Microsoft
This is the first time Microsoft has ever embraced the open
source model at this level
The complete ASP.NET MVC source code can be downloaded
from CodePlex, modified, and then recompiled for your needs!
http://aspnetwebstack.codeplex.com/
Modernizr, and Knockout
Visual Studio 2010 v2/v3/v4 (v2 native), v3 and v4 added
Visual Studio 2012 v3/v4/v5 (3.0 native), v4 and v5 added
Visual Studio 2013 v4/v5 (both native)
Copyright © Intertech, Inc. 2013 • www.Intertech.com • 800-866-9884 • Slide 13
Create an ASP.NET MVC Project Pick a language (C# or VB) for your WAP
Click File | New | Project | ASP.NET MVC 4 Web Application
Intertech
Copyright © Intertech, Inc. 2013 • www.Intertech.com • 800-866-9884 • Slide 14
Create an ASP.NET MVC Project Choose a template, decide on a view engine, and select
whether to create a unit test project
Visual Studio supports alternative (installed) testing frameworks:
NUnit, MBUnit, and more
Project Created!
assemblies!
Some are referenced .NET Framework
assemblies – System.<anything>
selected project template
They are also copied to the WAP’s \bin\ folder
Curious what they do?
Copyright © Intertech, Inc. 2013 • www.Intertech.com • 800-866-9884 • Slide 16
Models, Views, and Controllers These three folders suggest where to define
the three domains
Conventions: Each controller class must be in the Controllers folder
Each controller class contain one or more action
methods
Each view file is placed in subfolder named after a
controller class.
Each view file maps to an action method of a
controller class
Models folder is fine or in a separate .dll.
The Shared folder contains shared resources such as:
Web pages, layouts, error view, and partial views.
Intertech
Controllers - Purpose
A Controller is responsible for handling incoming
requests and sending back the proper response.
It is the first of the three MVC members to interact with the
request.
A Controller class contains “action methods” that usually map to
views with the same name.
Most typically, they interact with a Model to generate or
retrieve data and/or use business rules.
They take the retrieved data and pass it off to a View for
generating a Web response to the user.
Intertech
Controllers - Defining A Controller must implement IController interface and
must end in the name Controller.
Usually, it will inherit from the Controller base class.
Intertech
Controllers - Defining
interface
This is a really simple controller that just returns a simple
message.
Intertech
Controllers - Actions
browser
controller class can be called from the Web browser
Intertech
Controllers - ActionResult Most controller methods return a type of ActionResult
ActionResult
Types
PartialViewResult Displays a Partial View return PartialView();
RedirectToRouteResult Redirects to a route return RedirectToRoute(“NamedRoute”);
RedirectResult Simple URL redirection return Redirect(“http://bing.com”);
ContentResult Returns raw text to the browser return Content(rssString,
“application/rss+xml”);
“application/vnd.ms-word”);
JavaScriptResult Returns JavaScript intended to run
on the browser. Used with Ajax.
return JavaScript(“$(#elementName).hide();”);
Intertech
Copyright © Intertech, Inc. 2013 • www.Intertech.com • 800-866-9884 • Slide 22
Controllers – Passing Data Data is passed to a View using the ViewData or the
TempData dictionary collections.
ViewBag, introduced with MVC 3, is usually preferred and
uses ViewData object.
Stores data as “dynamic”,not Object - no casting required in View!
TempData is a TempDataDictionary object.
Used to preserve data between a RedirectResult or
RedirectToRouteResult.
Uses Session object behind the scenes.
Intertech
Controllers – Passing Data
Controllers – Passing Data
The View and the final response displayed in IE 10.
Intertech
Copyright © Intertech, Inc. 2013 • www.Intertech.com • 800-866-9884 • Slide 25
Controllers - Adding New Controllers can be easily added to the project.
There are many (hidden?) context menus available for launching
powerful MVC wizards.
Controllers - Adding Incredible scaffolding support is included!
Intertech
Controllers - Ajax
These are also public methods exposed from the controller class.
The example below uses the ASPX Forms view engine.
Intertech
Models – Purpose
Business Logic (BL), Data Access Logic (DAL) – it’s all
defined here!
Where you actually write the code is up to you.
With the Model, you have the most flexibility as to where you’d
like to place the code
The Model code can be located:
Right inside the Controller class (not recommended)
In classes defined in the Models folder
In classes defined elsewhere in the WAP
In a Class Library assembly for greater reuse
Intertech
Models - Purpose
A Model is code that enforces business logic.
It can also store and return data in a fashion that can ultimately
be bound to and displayed by a View
There are many different types of models!
Specifically, a model can be used for:
Retrieving/Storing Data in an .xml file
Retrieving/Storing Data in a database
Pure business logic
Intertech
Models - Types
defined in CRUD methods of a DAL
Often times referred to as POCOs (Plain Old CLR Objects)
Models can also be based on Object-Relational Mapper
(ORM) software.
Examples include:
Entity Framework (More coming up!)
NHibernate (a .NET version of Java’s Hibernate)
Intertech
Views - Description
They are never directly requested by the Web browser
They are often used with .master pages/_layouts
ASPX Views make use code nugget <%: %> syntax
This is the same as typing out Response.Write() but shorter
Razor uses a simplified code nugget @ syntax based on
Web Pages
Consider initially learning MVC with ASPX View Engine
Intertech
Copyright © Intertech, Inc. 2013 • www.Intertech.com • 800-866-9884 • Slide 32
Views - Adding Views give us full control to the HTML and JavaScript
mark up
Views can be easily added to the project in the Solution Explorer
IMPORTANT: Make sure you are adding it to subfolder!
Best way to add view?
Right-click the code in an action method and click Add New…
Intertech
Copyright © Intertech, Inc. 2013 • www.Intertech.com • 800-866-9884 • Slide 33
Views – HTML Helper Methods Views also make use of the HTML Helper methods
For example: @Html.TextBox("txtName", ViewData["Name"])
HTML Helper Example Use
CheckBox Html.CheckBox(“chkChoose”, true)
Password Textbox Html.Password(“pPassword”, “val”)
Text Area Html.TextArea(“taTextArea”, “val”, 4, 10, null)
TextBox Html.TextBox(“txtName”, “Davin”)
ListBox Html.ListBox(“lbColors”, new MultiSelectList(
new [] {“Red”, “Green”, “Blue”}))
Views – HTML Helper Methods
Classic un-typed Helper methods (v1/v2 – no editor help)
Strongly-typed Helper methods (IntelliSense!)
Rich Helper methods (Chart, WebGrid)
Your custom Helpers via Extension Methods <DEMO>
Many 3rd Party Helper methods (Fill in the gaps!)
Telerik, ComponentSource, CodePlex, GitHub, etc.
Intertech
System.Web.Routing.dll
Installed with VS 2008 SP1 (.NET 3.5 SP1) and newer
Used by Dynamic Data Web applications for routing web
requests
Also used with ASP.NET MVC for routing requests to the
proper controllers
A static method called RegisterRoutes() registers URL
requests to controller action methods.
Intertech
RouteConfig.cs – Default Route
Default Route “Default” is the optional name of the route
{controller} is the name of the controller class
{action} is the name of the public action method in the
controller class
{id} is an optional value passed to the action method as a
parameter
If any or all are not specified, the default URL values are
used (http://server:<port #>/Home/Index)
Routes can be confusing!
They should be added from most specific to most generic
The first route that matches a request wins
Not necessarily the best match!
Important points:
The static RegisterRoute() method can be unit tested
Routing is a silent but powerful fourth player in ASP.NET MVC
You can also define “catchall” wildcard routes for handling all
kinds of data tacked onto the end of the query string
Consider developing or downloading a route debugger
There are free ones available
Intertech
Sample Routes (Ignore port 6831)
http://localhost:6831/
http://localhost:6831/product
http://localhost:6831/6
http://localhost:6831/product/junk
http://localhost:6831/product/Index
Intertech
Route Debuggers
visualizers/debuggers
available.
Intertech
Unit Testing ASP.NET MVC
matter the visibility declarations
public members
Framework, NUnit, xUnit.net, and more. http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#.NET_programming_languages
Unit Testing ASP.NET MVC
changed them
Testing the controllers can simulate user requests
Web users will try to pass you anything; be ready for that!
Testing the Models guarantee correct results
Especially important if the models are in separate Class Library
assembly for reuse across projects!
Testing ORM classes probably unnecessary (opinion!)
Testing Views? Maybe
Unfortunately, if you change the HTML/JS out just slightly, your
View tests will fail
Some developer prefer not to tests their Views, or only certain
Views
Intertech
Test-Driven Development (TDD)
implemented
tests
Intertech
New ASP.NET MVC 4 Features
New project template wizard.
via CSS media queries.
services with OData queries.
3rd party sites such as Facebook and Yahoo.
Single Page App project template.
Mobile project template that include jQuery Mobile.
Intertech
Introducing Entity Framework (EF)
The ADO.NET Entity Framework (or simply EF) was
introduced with Visual Studio 2008 Service Pack 1.
.NET 4.0 / Visual Studio 2010 support new EF designers, and a
better programming experience.
EF 1 left a lot of “opportunities for improvement”.
So much so that the next version was EF 4 with .NET 4.0.
The version EF 5 switched to Open Source!
You can download it as NuGet package.
EF 6 was released with VS 2013.
Learn more here:
Introducing Entity Framework (EF)
EF is a programming model which attempts to lessen the
gap between database constructs and object oriented
programming constructs.
Using EF, you can interact with a relational database without ever
seeing a line of SQL code (if you so choose).
Rather, when you apply LINQ queries to your strongly typed
classes, the EF runtime will generate proper SQL statements on
your behalf.
By way of another example, rather than updating database data
by finding a row, updating the row, and sending the row back for
processing using a batch of SQL queries, you can simply change
properties on an object and save its state.
The EF runtime will update the database automatically.
Intertech
Introducing Entity Framework (EF)
Framework is a new member of the data access family -
not meant to replace the connected or disconnected
layers.
However, EF works really nicely with MVC.
It saves you an incredible amount of typing over the more
primitive world of SQL queries and row/column collections.
.NET 4.0+ ships with EF providers for Microsoft SQL
Server databases.
aware data providers.
The strongly typed classes used within EF are termed
entities.
Entities are a conceptual model of a physical database which
maps to your business domain.
Formally speaking, this model is termed Entity Data Model
(EDM).
While the EDM is a client side set of classes which map to a
physical database, understand that the entities need not map
directly to the database schema in so far as naming conventions
go.
Your entity classes can be restructured to fit your needs, and the
EF runtime will map your unique names to the correct database
schema.
database table in a SQL Server database:
If you were to generate an EDM for the Inventory table of
the AutoLot database, the entity will be called (by default)
Inventory. However, you could rename this class to Car and rename the properties which
map to the columns of the Inventory table.
Because of this loose coupling, the entities can be shaped to closely model your
business domain.
EF Example
Copyright © Intertech, Inc. 2013 • www.Intertech.com • 800-866-9884 • Slide 50
If you were to generate an EDM for the Inventory table of
the AutoLot database, the entity will be called (by default)
Inventory.
However, you could rename this class to Car and rename the
properties which map to the columns of the Inventory table.
Because of this loose coupling, the entities can be shaped to
closely model your business domain.
EF Example
Consider the following Program class, which will add a
new row to the Inventory table of AutoLot, using the Car
entity class, and a related class named AutoLotEntities.
This class is called an object context, whose job it is to
communicate with the physical database on your behalf.
EF Example
class Program
using (AutoLotEntities context = new AutoLotEntities())
{
// Add a new record to Inventory table, using our entity.
context.Cars.AddObject(new Car() {
}
}
}
Copyright © Intertech, Inc. 2013 • www.Intertech.com • 800-866-9884 • Slide 52
ObjectContext Members Member of ObjectContext Meaning in Life
AcceptAllChanges() Accepts all changes made to entity objects within the object context.
AddObject() Adds an object to the object context.
DeleteObject() Marks an object for deletion. Must still SaveChanges().
ExecuteFunction() Executes a stored procedure in the database.
ExecuteStoreCommand() Allows you to directly send a SQL command to the data store.
GetObjectByKey() Locates an object within the object context by its key.
SaveChanges() Saves all updates to the data store.
CommandTimeout This property gets or sets the timeout value, in seconds, for all object context
operations.
Connection This property returns the connection string used by the current object context.
SavingChanges This event fires when the object context is saving changes to the data store.
Intertech
Three Ways to Use EF
Database First
A model and ObjectContext class is automatically built based on
an existing database.
Model First
A model is built first, then EF automatically creates the database
and the ObjectContext class
DBContext.
of SQL Express.
No .edmx model is created – the classes are the model!
Intertech
Three Layers (Database/Model First)
All three layers of the Entity Data Model (EDM) are
defined in the *.edmx file.
Conceptual Layer
This represents the entities and their relationships in the model
Physical Layer
Mappings
Most settings (not all!) can be made using the designer.
Each new version of EF released adds more functionality to the
designer.
Intertech
Database First
EF 4.1
Oldest way of using EF
Greatest support in Visual Studio
Model validation more difficult
data annotations/validation rules
are not lost.
Model First
Allows you to design the model using prototypes in the
Toolbox.
string in Web.config
Code First Most flexible to create and easiest for programmers.
No visible .edmx designer file created
Database created in /App_Data/ using EF base classes
DBContext represents the model
DBSet represents an entity
Database can be recreated:
When the model changes
Global.asax
Most commonly, you will use LINQ Query Expressions to retrieve
data from EF.
Entity SQL
Similar to the standard SQL language, this alternate SQL language
can be used to query EF.
SELECT VALUE c FROM AWLTEntities.Customers AS c WHERE
c.FirstName = ‘Jim’
EntityClient API
Programming can also be done directly against the EntityClient API.
Similar to classic ADO.NET but objects are Entity versions.
EntityConnection, EntityCommand, EntityDataReader, etc.
Microsoft Tool Futures
ASP.NET MVC 5
Is included with VS 2013 next month, Available for VS 2012 now!
Includes ASP.NET Identity,Twitter Bootstrap in the MVC
template, Authentication Filters, Filter overrides, more…
EF 6
Included with VS 2013
Visual Studio 2013, looks a little different but easier to
use than VS 2012
Support added for Windows 8.1, EF6, and MVC 5
Intertech
Microsoft Tool Futures
Not that many new features – .NET 4.5 just came out!
Suggested moving to NuGet package release
Obvious support added for Windows 8.1 Store front apps
Windows 8.1
Three apps simultaneously can run on Tile view
Store front apps are fun to build with C#, VB, or JavaScript.
All your JavaScript skills transfer over check it out!
NOTE: Must develop on Windows 8/8.1 (not Windows 7 or Server
2012)
Intertech
Thank you!