Applicazioni Web con ASP.NET MVC 2

advertisement
Cloud e Web con Windows AZURE e
ASP.NET MVC 3
Speakers: Antimo Musone e Daniele
Midi
antimo.musone@studentpartner.com
daniele.midi@studentpartner.com
About We
Antimo Musone
Cloud Development Tour Owner
Daniele Midi
Web Development Tour Owner
Web Team
Agenda
Cloud Platform
Why Cloud ?
Windows Azure
Hosting
App Models
Management
Demo
Hello World
Windows Azure
Storage
Interoperability
MVC 3 Web App
MVC 3 in
Azure
Demo MVC3
START WITH :
Cloud
Antimo Musone
Cloud Development Tour Owner
What is the cloud?
An approach to computing that’s about internet scale
and connecting to a variety of devices and endpoints
Why Cloud?
Customer Requirements :
• Efficency, Reliability
• Scalability , Agility
• Reduce IT Costs
IT Consultants
• Don’t must be IT warriors
• Can delegate IT Problems
Compute
Compute
Cloud Computing Patterns
Inactivity
Period
Average Usage
Usage
Average
Time
Time
Successful services needs to grow/scale
Compute
Compute
On & off workloads (e.g. batch job)
Average Usage
Average Usage
Time
Unexpected/unplanned peak in demand
Time
Services with micro seasonality trends
Cloud Services
“IaaS”
Infrastructure-as-a-Service
host
“PaaS”
Platform-as-a-Service
build
“SaaS”
Software-as-a-Service
consume
Caso Cloud: Il Censimento
• 500 000 connessione in un
solo giorno
• Carico di workload
inaspettato
• In tilt dopo poche ore
dal lancio
• Raddoppiata l’infrastruttura IT
in una sola Notte
• Infrastuttura Cloud : Telecom
Italia
Windows Azure Platform
Windows Azure Platform : Layers
Middleware
Services
Data
Services
“Red Dog” Front End (RDFE)
Compute
Services
Windows Azure
Networking
Windows Azure Platform Data Centers
North America
Region
Europe
Region
Asia Pacific
Region
Windows Azure
Compute
Windows Azure Platform
Components Horizontal View
Windows Azure
Windows Azure is a foundation of Microsoft’s Cloud Platform for
Developers
Operating System for the Cloud
•
•
•
•
Runs applications in the cloud
Provides Storage
Application Management
Developer SDK
Windows Azure ideal for applications needing
• Scalability
• Availability
• Fault Tolerance
IaaS
Developer
1) Choose image,
then create VM
for DBMS and
configure DBMS
3) Choose
image,
then create
and
configure
VM(s) for
application
Library
4) Install
application
5) Configure
load
balancer
6) Manage VMs
and DBMS (e.g.,
deploying new OS
images in VMs)
VM Images
Application
Web
Server
DBMS
Operating
System
VM
Operating
System
VM
Load
Balancer
PaaS
Developer
1) Provision database,
then create tables and
add data
Application
2) Deploy
application
3) Manage
Applications
Load
Balancer
PaaS - Azure
Azure Developer
1) Provision database,
then create tables and 2) Deploy
application
add data
3) Install Other application
DBMS
Operating
System
VM
Role
Application
Application
Other
Application
Operating
System
VM
Load
Balancer
Windows Azure in 1 Slide
Developer Portal
RDP
User Code
WA SDK
Desktop
…
Compute Cluster
VS Tools
Runtime API
…
…
Storage Cluster
Service Management Service
VM Setup
Cloud VM
API REST
MSFT Datacenters
Azure Role :
Scale Application
Archetype
Azure Scale Applications: Layers
Intelligent Network : Load Balancer
Stateless Web Application : Web Role
Stateless ‘Worker’ Machines : Worker Role
Async Work
Data
/State
Tier
Queues
Key/Value
Datastores
Partitioned
RDBMS
Shared
Filesystem
Azure Scale Applications: Roles
The Internet via HTTP/TCP
L
B
L
B
L
B
Queues
Worker
Worker
Worker
Role
Service
Service
WebSite
Site
Web
(ASPX, ASMX,
Web
(ASPX,Role
ASMX,
WCF)
WCF)
IIS as
Host
Managed
Interface Call
Tables
Storage
Blobs
Windows Azure Data Center
Azure Role: Application Box
Role Interface
Role is an application container, that run inside Azure VM, through it we
can provide Web / Service / Standalone Applications and also offers an
interface to manage it
Services,Roles and Instances
A Service is a packaged application for Azure, composed by one or more role
Roles are defined in a Service Model
• May define one or more Roles per Service
• A role definition specifies
 VM size
 Communication Endpoints
 Local storage resources
 Etc…
At runtime each Role will execute on one or more instances (up to 20 per
subscription)
• A role instance is a set of code, configuration, and local data, deployed in a
dedicated VM
Worker Role Patterns
Queue Polling Worker
• Poll and Pop Messages within while(true) loop
• E.g. Map/Reduce pattern, background image processing
Listening Worker Role
• Create TcpListener or WCF Service Host
• E.g. Run a .NET SMTP server or WCF Service
External Process Worker Role
• OnStart or Run method executes Process.Start()
• Startup Task installs or executes background/foreground process
• E.g. Run a database server, web server, distributed cache
Web Role
All features of a worker role + IIS 7 or 7.5
MVC 3 , ASP.NET 3.5 SP1 or 4.0 – 64bit
Hosts
• Webforms or MVC
• FastCGI applications (e.g. PHP)
• Multiple Websites
Http(s)
Web/Worker Hybrid
• Can optionally implement RoleEntryPoint
Service Definition
Describes the shape of your Windows Azure Service
• Defines Roles
• Ports, Certificates
• Configuration
• Startup Tasks
• IIS Configuration
Service Configuration
Supplies Runtime Values, can be updated any time through Portal or API
• Scale
• Config Settings
• Certificates to use,
•
VHD
•
etc.
VM Size in Windows Azure
Windows Azure
•
•
•
•
•
Supports Various VM Sizes
Size set on Role in Service Definition
Service can have multiple roles
Balance of Performance per node vs. High Availability from multiple nodes
Set in Service Model definition All instances of role will be of equal size
Size
CPU Cores
RAM
Local Storage
Cost ( $/Hour)
Extra Small
Shared
768M
20GB
.05
Small
1
1.7GB
250GB
.12
Medium
2
3.5GB
500GB
.24
Large
4
7GB
1000GB
.48
Extra large
8
15GB
2000GB
.96
Windows Azure Platform Portal
• Web Access to :
https://windows.azure.com
• Supports multiple service
administrators (co-admins)
• Enable and connect to
Windows Azure instances using
Remote Desktop
• Built on the Windows Azure
Service Management APIs
Demo
Hello World by
Windows Azure
Windows Azure
Storage
Windows Azure Storage
Storage in the Cloud
• Scalable, durable, and available
• Anywhere at anytime access
• Only pay for what the service uses
Exposed via RESTful Web Services
• Use from anywhere on the internet
 User specified globally unique account name
 Can call these from any HTTP client (Flash, Silverlight )
Various storage abstractions
• Tables, Blobs, Queues, Drives
100TB per account, have two independent 512 bit shared secret keys
Blob Storage
Blob Storage Concepts
http://<account>.blob.core.windows.net/<container>/<blobname>
Account
Container
Blob
Pages/
Blocks
PIC01.JPG
Block/Page
images
PIC02.JPG
contoso
Block/Page
videos
VID1.AVI
Blob Details
Main Web Service Operations
• PutBlob,GetBlob
• DeleteBlob,CopyBlob
• SnapshotBlob ,LeaseBlob
Associate Metadata with Blob
• Standard HTTP metadata/headers
(Cache-Control, Content-Encoding, Content-Type, etc)
• Metadata is <name, value> pairs, up to 8KB per blob
• Either as part of PutBlob or independently
Blob always accessed by name
• Can include ‘/‘ or other delimeter in name
e.g. /<container>/myblobs/blob.jpg
Blob Containers
Multiple Containers per Account
• Special $root container
Blob Container
•
•
•
•
A container holds a set of blobs
Set access policies at the container level
Associate Metadata with Container
List the blobs in a container
• Including Blob Metadata and MD5
• NO search/query. i.e. no WHERE MetadataValue = ?
Blobs Throughput
• Effectively in Partition of 1
• Target of 60MB/s per Blob
Table Storage
Table Storage Concepts
http://<account>.table.core.windows.net/<tablename>
Account
Table
Entity
Name =…
Email = …
customers
Name =…
EMailAdd= …
contoso
Photo ID =…
Date =…
photos
Photo ID =…
Date =…
Table Details
It’s not an RDBMS system but it’ s a container where we can serialize a
collection of objects
Table Operations :
• Create, Query, Delete
• Tables can have metadata
Entities Operations :
• Insert,Delete
• Update
• Merge – Partial update
• Replace – Update entire entity
• Query
• Entity Group Transactions
• Multiple CUD Operations in a single atomic transaction
Entity Properties
Entity can have up to 255 properties ( members of class )
• Up to 1MB per entity
Mandatory Properties for every entity
•
•
•
•
•
PartitionKey & RowKey (only indexed properties)
Uniquely identifies an entity
Defines the sort order
Timestamp
Optimistic Concurrency. Exposed as an HTTP ETag
No fixed schema for other properties
• No schema stored for a table
• Properties can be the standard types:
 String, binary, bool, DateTime, GUID, int, int64, and double
Querying
http://<account>.table.core.windows.net/<tablename>
http://antimo.table.core.windows.net/Accounts
?$filter=Last eq ‘Akers’
First
Last
Birthdate
Kim
Akers
2/2/1981
Nancy
Anderson
3/15/1965
Mark
Hassall
May 1, 1976
Queue Storage
Queue Storage Concepts
http://<account>.queue.core.windows.net/<queuename>
Account
adventureworks
Queue
order
processing
Message
customer ID
order ID
http://…
customer ID
order ID
http://…
Loosely Coupled Workflow with Queue
Enables workflow between roles
• Load work in a queue
 Producer can forget about message once it is in queue
• Many workers consume the queue
• For extreme throughput use multiple queues or multiple work items per message
Input Queue (Work Items)
Queue
Queue Details
Simple asynchronous dispatch queue
• No limit to queue length subject to storage limit
• 8kb per message
• ListQueues - List queues in account
Queue operations
• CreateQueue ,DeleteQueue
• Get/Set Metadata
• Clear Messages
Message operations
•
•
•
•
PutMessage– Reads message and hides for time period
GetMessages – Reads one or more messages and hides them
PeekMessages – Reads one or more messages w/o hiding them
DeleteMessage – Permanently deletes messages from queue
SQL AZURE
Database
SQL Azure
Extending SQL Server to the Cloud
SQL Azure Database
Familiar SQL Server relational database model delivered as a service
• Support for existing APIs & tools
• Built for the cloud with high availability & fault tolerance
• Easily provision and manage databases across multiple datacenters
SQL Azure provides logical server
• Gateway server that understands TDS protocol
• Looks like SQL Server to TDS Client
• Actual data stored on multiple backend data nodes
Logical optimizations supported
• Indexes, Query plans etc..
Physical optimizations not supported
• File Groups, Partitions etc…
Transparently manages physical storage
SQL Azure
SQL Azure Use & Deployment :
Web Portal
(API)
DB
Script
SQL Server
Managment
SQL Azure
TDS
Custom Tool
SQL Azure Data Sync
Geo-replication of SQL Azure data and spanning on-premises with
cloud
• geo-replication
• sync between SQL Server and
SQL Azure
Builds on Sync Framework
• Sync data between SQL Azure,
SQL Compact and SQL Server
On-Premises
Cloud
Offline
Clients
AZURE
Interoperability
Development & Interoperability
Microsoft & Partners provide development tools & sdk to design/develop
Web Apps & Services on Azure Platform
Windows Azure SDK & Training Kit : A step by step helper , provide a full developer
local environment to develop and test Azure Apps
• Development Fabric: simulate in local Windows Azure SO
• Development Storage: : simulate in local Windows Azure Storage
Not only tools for Microsoft Platform but also Windows Azure Team provide tools for
Eclipse , Java and many other open source technology
C/C++
Win32
VHD
Azure + Phone 1 / 2
Phone
•
•
•
Connection
Smart
Marketplace
Azure Key Word : Interoperability
Azure
•
•
Services
Scalability
Azure + Phone 2 / 2
Development Tools & Interoperability with all mobile platforms
Azure Apps
Azure Datacenters
SWITCH TO :
Web
Daniele Midi
Web Development Tour Owner
Coffee break
(5 min)
PATTERNS:
MVC ORIGINALE,
MVC MODEL2,
ASP.NET MVC.
Parleremo di...
Pattern MVC
MVC secondo Microsoft
Gestione dei dati
Web Apps per il Cloud
PATTERNS:
MVC ORIGINALE,
MVC MODEL2,
ASP.NET MVC.
MVC: formulazione originale
Model
E’ un pattern
architetturale che risolve
il problema di
disaccopiare la logica di
interfaccia da quella di
dominio.
Observer
View
Controller
MVC adattato al Web (Model 2)
“
Skinny Controller,
Model
Fat Model and Dumb
View
”
(RubyOnRails devs)
View
Controller
MVC secondo Microsoft
1
ROUTING ENGINE
BROWSER
Model
Controller
2
6
View
ATTORI:
CONTROLLER, ACTION,
ROUTING, VIEWMODEL,
VIEW, MODELBINDER.
Controller
E’ una classe.
Convention-over-configuration: per convenzione, la classe del Controller deve
chiamarsi “NomeControllerController”
– es.: “AnnunciController”
Contiene la logica di interazione per un certo numero di “pagine” logicamente
collegate
– es.: AnnunciController potrebbe:
• visualizzare l’elenco degli annunci
• vedere i dettagli di un annuncio
• aggiungere un nuovo annuncio
Action
E’ un metodo di un Controller.
Quando l’utente richiede l’esecuzione di una certa “azione” (visualizzare i
dettagli di un annuncio, crearne uno nuovo, …) viene invocata la relativa Action.
La Action esegue della logica applicativa e poi restituisce un oggetto
ActionResult, che sarà utilizzato per mostrare i risultati all’utente in una “pagina”
(la View).
ActionFilter
Action
ActionResult
HomeController
Index ()
RICHIESTA
?
About ()
AnnunciController
Index ()
Details (int id)
Create ()
Routing engine
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {
controller = "Home", action = "Index", id = UrlParameter.Optional
}
);
www.ilmiosito.com/Annunci/Details/12
ROUTING ENGINE
www.ilmiosito.com/Annunci/Details/12
Annunci Details 12
CONTROLLER
ACTION
ID
AnnunciController.Details(12)
DEMO:
Creazione di un’applicazione Web
con ASP.NET MVC
Model (anzi, ViewModel)
Il Model in ASP.NET MVC fa da intermediario fra Controller e View
– permette di tipizzare i dati scambiati fra Controller e View
Si parla allora di ViewModel:
– Classi create ad uso e consumo delle View
– Classi completamente anemiche (solo attributi)
Validazione: Data Annotations
Dato che i ViewModel nascono prettamente per tipizzare i dati scambiati con la
view, possono essere usate anche per definire le regole di validazione e
rendering della view che le consuma.
In .NET possiamo indicare tali informazioni con dei semplici attributi chiamati
Data Annotations:
View Loosely-Typed
ASP.NET MVC < 3: ViewData
– ACTION
ViewData[“Messaggio”] = “Benvenuto!”;
ViewData[“Cliente”] = new Customer();
– VIEW
<%: ViewData[“Messaggio”] %>
<%: (ViewData[“Cliente”] as Cliente).Nome %>
ASP.NET MVC 3: dynamic ViewBag + Razor
– ACTION
ViewBag.Messaggio = “Benvenuto!”;
ViewBag.Cliente = new Customer();
– VIEW
@ViewBag.Messaggio
@ViewBag.Cliente.Nome
View Strongly-Typed
Inizia con una dichiarazione @model T
– es.: una View che mostri i dettagli di una Sessione può iniziare con la
dichiarazione @model Sessione
È una normale pagina Web
T è il ViewModel
– un “modello” della View: raggruppa in una classe i dati che la View deve
mostrare e gestire
Vantaggi:
– Intellisense
– Controlli alla compilazione
Model Binder: tipi primitivi
URL PARAMETER
www.contoso.com/Libri/Details/12
ACTION del CONTROLLER “Libri”
QUERYSTRING
public ActionResult Details(intHTML
id) FORMS
www.contoso.com/Libri/Details/?id=12
MODEL
BINDER
Model Binder: oggetti
CLASSE “PERSONA”ACTION del CONTROLLERHTML
“Persone”
FORM
public string Nome
{ get; set; }
public string Cognome
{ get; set; }
public int Eta
{ get; set; }
<form action=“/Persone/Edit”>
public ActionResult
Edit(Persona persona)
<input type=“text” name=“persona.Nome”
@Html.TextBoxFor(model
=> model.Nome) />
<input type=“text” name=“persona.Cognome”
@Html.TextBoxFor(model
=> model.Cognome) />
<input type=“text” name=“persona.Eta”
@Html.TextBoxFor(model
=> model.Eta) />
</form>
MODEL BINDER
DEMO:
ViewModel, Data Annotation e
Strongly-Typed Views
ASP.NET MVC PER
WINDOWS AZURE:
BEH, CHE
PROBLEMA C’È?
Statelessness
Load balancer round-robins requests in multi instance roles
Follow web farm best practices
– Do not store state on individual instances
– Do not assume subsequent requests will hit the same instance
• Don’t forget things like dynamically generated images loaded by a
page
All instances require the same MachineKey for hashing
– Fabric uses same machine key for all instances in a role
AJAX and Windows Azure
Client side calls may not return to the same instance the original page came
from
AJAX calls must be stateless
– Don’t generate a page and leave state on the server to call via AJAX later
Windows Azure Session State
Windows Azure Load Balancer uses round-robin allocation. Session state must
persist to client or storage on every request
Solving Session State
Persist to Storage via Session State Provider
–
–
–
–
–
Windows Azure AppFabric Caching
3rd party distributed cache (e.g. MemCached)
SQL Azure
Windows Azure Storage
Custom
Persist to Client
– Use cookies  performance issues
Windows Azure AppFabric Caching
Using Windows Azure AppFabric Caching as the session store
In-memory, distributed cache
Based on Windows Server AppFabric Caching
Used the Microsoft.Web.DistributedCache assembly found in the SDK
Enable ASP.NET 4 Session Compression
Currently available in AppFabric LABS Portal as CTP
AppFabric Caching Session State
SQL Server Session State
Use SQL Azure as backing store
Round trip to database twice per request
– Read at request start
– Write at request end
Enable ASP.NET 4 Session Compression
Scale out across multiple DBs
– Use session state partitioning
– http://tinyurl.com/scale-session
SQL Azure is competitive on cost basis
SQL Azure Session State
Session state stored using SQL Server Session State Provider and
session state partitioning
resolve partition
Windows Azure Storage Providers
Sample ASP.NET Providers (Session, Membership, Role etc…)
Sample Code
http://code.msdn.microsoft.com/windowsazuresamples
Uses Blob + Table Storage
Several storage transactions per request
Enable ASP.NET 4 Session Compression
Sample Provider should be treated as a starting point only.
Cookies
Serialize and Encrypt state into cookie
Possible to implement as Session State Provider
Cookies add significant performance overhead
Cookies sent with every request to domain
– Use alternative host header to serve images, …
• http://www.myweb.com
• http://images.myweb.com
– Use Windows Azure Storage for static content
DNS
All services get a *.cloudapp.net address
– myservicename.cloudapp.net
– TTL is 10 seconds
Standard approach is to CNAME to *.cloudapp.net
– Requires two DNS lookups
– Limited caching due to low TTL
Officially, Windows Azure do not support the use of A records
IP Address for deployment is fixed for lifetime of that slot
ASP.NET ON AZURE:
COMMON CHALLENGES
File Upload
ASP.NET File Upload Control uses ASP.NET temporary directory to buffer files
– Temp path cannot be changed to Local Resource or Windows Azure Drive
Windows Azure Compute roles have 100MB of root disk space
Problems arise
– Uploading large files (~100MB)
– Multiple users uploading concurrently (10 users uploading 10MB files)
File Upload Solutions
Upload direct to Blob storage using Silverlight
– Provide a Shared Access Signature to Silverlight control
– Upload blocks direct to storage [http://tinyurl.com/sl-blob]
Use 3rd Party Control
Implement a custom IHttpHandler to receive file and buffer to disk
Takeaways
ASP.NET In Windows Azure
– Broad support for ASP.NET Features
– Must understand and architect for scale out
Advanced Techniques
– SaaS Applications using Virtual Path Providers and Host header checking
Challenges
Demo
Creazione
di un’applicazione
Web con ASP.NET
MVC + Azure
Demo
Creazione di
un’applicazione
Web con ASP.NET MVC
http://www.microsoft.com/windowsazure/free-trial
Questions
Microsoft
Logo here
IMAGINE CUP 2012
Microsoft Logo Tagline here
IMAGINE A WORLD...
Microsoft
Logo here
The most important student technology competition!Let’s join to
thousands of students from around the world who are stepping up to the
challenge of global change. Choose from three team competitions—
Software Design, Game Design: Xbox/Windows, and Game Design:
Phone or take on the IT Challenge.
Microsoft Logo Tagline here
OVERVIEW
The Software Design Competition is all about creating real-world
applications that can help make the world a better place.
The Game Design: Phone competition is an excellent opportunity
to learn the art of mobile video game design!
The structure of the game is entirely up to you!
The goal :Creatively using technology.
The IT Challenge is an individual challenge for students
around the world who have the nterest, and technical
knowledge to design infrastructures.
INSPIRATION
Microsoft
Logo here
Need a Litte Inspiration? Get motivated by one of the eight United Nations
Millennium Development Goals: the Imagine Cup offers these ambitious
challenges as a guide to promote change all around the world. Game “Malaria
Wars” based on Windows for Xbox that improves knowledge about Malaria,
Software Design project “Brain” which allow children, who had their elementary
education interrupted, to continue learning and “G7oups” a Windows Phone 7
based application with a clear goal to improve in a creative way the education of
guys
More at Imagine cup.com/Student stories
Microsoft Logo Tagline here
STEP UP THE CHALLENGE
• Check out
www.imaginecup.com
• Form your Team
• Make new Friends,
compete & change the
World!
Next year you could be on
stage @Sidney Finals!!
Microsoft
Logo here
STAY TUNED ON
SITE:
WWW.MICROSOFT.IT/STUDENTI
WWW.IMAGINECUP.COM
SOCIAL: FB FANPAGE INIZIATIVE
STUDENTI
MAIL TO:
ITAUNI@MICROSOFT.COM
Vinci con Windows Phone
Premi per oltre 20.000 euro complessivi in buoni acquisto
spendibili online presso Media World. tra estrazioni bisettimanali e
premi finali
http://www.microsoft.it/msdn/concorso
Download