cloud e web con windows azure e asp.net mvc 3 speakers: antimo musone e daniele midi...
TRANSCRIPT
Microsoft Academic Tour 2011
Cloud e Web con Windows AZURE e ASP.NET MVC 3
Speakers: Antimo Musone e Daniele [email protected]@studentpartner.com
Facoltà di Ingegneria,Tor Vergata,12 Dicembre 2011
About We
Antimo MusoneCloud Development Tour Owner
Daniele MidiWeb Development Tour Owner
Web Team
AgendaCloud Platform
Why Cloud ?Windows Azure
HostingApp ModelsManagement
Demo
Hello WorldWindows Azure
StorageInteroperability
MVC 3 Web App
MVC 3 in AzureDemo MVC3
START WITH : Cloud
Antimo MusoneCloud 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
Cloud Computing Patterns
Usage
Com
pu
te
Time
Average
Inactivity
Period
“On and Off “
On & off workloads (e.g. batch job)
Com
pu
te
Time
“Unpredictable Bursting“
Average Usage
Unexpected/unplanned peak in demand
Average Usage
Com
pu
te
Time
“Growing Fast“
Successful services needs to grow/scale
Com
pu
te
Time
Average Usage
“Predictable Bursting“
Services with micro seasonality trends
Cloud Services
Software-as-a-Service
consume
“SaaS”Platform-as-a-Service
build
“PaaS”Infrastructure-as-a-Service
host
“IaaS”
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 PlatformScalable compute and storageAutomated service managementFamiliar tools, technologies, languages
Relational storage for the cloudConsistent development modelAutomated database management
Connect existing apps to the cloudConnect through network boundariesEasily control authorization to apps
Windows Azure Platform : Layers
Fabric ControllerWindows Azure
Networking
AppFabric Caching
AppFabric Access Control
SQL Azure
AppFabric Service Bus
“Red Dog” Front End (RDFE)Compute Services
Middleware Services
Windows Azure Storage
Windows Azure CDN
Data Services
Windows Azure Platform Data Centers
North America Region
Europe Region
Asia Pacific Region
6 datacenters across 3 continentsSimply select your data center of choice when deploying an application
S. Central – U.S.
W. Europe
N. Central – U.S.
N. Europe
S.E. Asia
E. Asia
Windows AzureCompute
Windows Azure PlatformComponents Horizontal View
Virtual NetworkCompute Storage
Windows AzureWindows 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
Operating System
Operating System
VM
WebServer
Operating System
VM
DBMS
3) Choose image, then
create and
configure VM(s) for applicati
on
1) Choose image, then
create VM for DBMS and configure
DBMS
IaaS
Library
VM Images
Developer
Application Load Balancer
5) Configure
loadbalancer
6) Manage VMs and DBMS (e.g., deploying new OS images in
VMs)
2) Provision
database, then
create tables
and add data
4) Install applicatio
n
Operating System
Operating System
VM
Operating System
VM
DBMS
PaaSDeveloper
Application
2) Deploy application
WebServer
1) Provision database, then
create tables and add data
Load Balancer
3) Manage Applications
Operating System
Operating System
VM
RoleApplicatio
n
Operating System
VM
DBMS
PaaS - AzureAzure Developer
Application
Load Balancer
3) Install Other application
2) Deploy application
1) Provision database, then
create tables and add data
4) Manage VM & Applications
Other Application
Windows Azure in 1 Slide
Desktop
VS Tools
WA SDK Sto
rage
Clu
ster
MSFT Datacenters
Developer Portal
Com
pute
Clu
ster
……
Service Management Service
API REST
…
Cloud VM
Runtime API
VM Setup
User Code
RDP
Azure Role :
Scale Application
Archetype
Azure Scale Applications: LayersIntelligent Network : Load
Balancer
Stateless ‘Worker’ Machines : Worker Role
Stateless Web Application : Web Role
Async Work
Shared Filesyste
m
Partitioned RDBMS
Key/Value
Datastores
Data /State Tier
Queues
Azure Scale Applications: Roles
StorageTables
LB
Blobs
Worker ServiceWorker Service
Worker Role
Managed Interface Call
Web Site(ASPX, ASMX,
WCF)
Web Site(ASPX, ASMX,
WCF)
Web RoleIIS as Host
Queues
Windows Azure Data Center
LB
LB
The Internet via HTTP/TCP
Role
In
terf
ace
OnStart
Methods
Fabric C
alls
Run
OnStop
Events
Busy
Status
StatusCheck
Stopping
Ready
Busy
StatusCheck
StatusCheck
Role
Lifetim
e
Requests R
oute
dAzure Role: Application BoxRole 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 InstancesA 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 sizeCommunication EndpointsLocal storage resourcesEtc…
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 PatternsQueue 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 RoleAll 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 DefinitionDescribes the shape of your Windows Azure Service
• Defines Roles
• Ports, Certificates
• Configuration
• Startup Tasks
• IIS Configuration
Service ConfigurationSupplies Runtime Values, can be updated any time through Portal or API
• Scale
• Config Settings
• Certificates to use,
• VHD
• etc.
VM Size in Windows AzureWindows 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
Hello World by Windows Azure
Demo
Windows Azure
Storage
Windows Azure StorageStorage 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 nameCan 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
BlobContainer
Account
contoso
images
PIC01.JPG
videos VID1.AVI
http://<account>.blob.core.windows.net/<container>/<blobname>
Pages/Blocks
Block/Page
Block/Page
PIC02.JPG
Blob DetailsMain 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 ContainersMultiple 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
EntityTableAccount
contoso
customers
Name =…Email = …
Name =…EMailAdd= …
photos
Photo ID =…Date =…
Photo ID =…Date =…
http://<account>.table.core.windows.net/<tablename>
Table DetailsIt’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 PropertiesEntity 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
First Last Birthdate
Kim Akers 2/2/1981
Nancy Anderson 3/15/1965
Mark Hassall May 1, 1976
Querying
?$filter=Last eq ‘Akers’
http://antimo.table.core.windows.net/Accounts
http://<account>.table.core.windows.net/<tablename>
Queue Storage
Queue Storage Concepts
MessageQueueAccount
order processing
customer ID order ID http://…
customer ID order ID http://…
adventureworks
http://<account>.queue.core.windows.net/<queuename>
Loosely Coupled Workflow with QueueEnables workflow between roles
• Load work in a queueProducer 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
Queue
Input Queue (Work Items)
Web Role
Web Role
Web Role
Worker Role
Worker Role
Worker Role
Worker Role
Queue DetailsSimple 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 AzureExtending SQL Server to the Cloud
Data Sync
Database
Reporting
SQL Azure DatabaseFamiliar 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 AzureSQL Azure Use & Deployment :
Web Portal(API)
SQL AzureTDS
DB Script
SQL Server Managment
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 & InteroperabilityMicrosoft & 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 / 2Phone• Connection• Smart• Marketplace
Azure• Services• Scalability
Azure Key Word : Interoperability
Azure + Phone 2 / 2
Azure Apps
Development Tools & Interoperability with all mobile platforms
Azure Datacenters
SWITCH TO : Web
Daniele MidiWeb 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
E’ un pattern architetturale che risolve il problema di disaccopiare la logica di interfaccia da quella di dominio.
Model
View Controller
Observer
Model
View Controller
Model
View Controller
MVC adattato al Web (Model 2)
”Skinny
Controller, Fat Model and
Dumb View
“(RubyOnRails devs)
MVC secondo MicrosoftB
RO
WSER
RO
UTIN
G E
NG
INE
Controller
Model
View
1 2
3
4
5
6
ATTORI:CONTROLLER, ACTION, ROUTING, VIEWMODEL, VIEW, MODELBINDER.
ControllerE’ 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
ActionE’ 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 ActionRes
ult
RICHIESTA
HomeController
Index ()
About ()
AnnunciController
Index ()
Details (int id)
Create ()
?
Routing engine
ROUTING ENGINE
routes.MapRoute( "Default", "{controller}/{action}/{id}", new {
controller = "Home", action = "Index", id = UrlParameter.Optional });
www.ilmiosito.com/Annunci/Details/12
www.ilmiosito.com/Annunci/Details/12Annunci Details 12
CONTROLLER IDACTION
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 AnnotationsDato 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-TypedASP.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-TypedInizia 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
MODEL BINDE
R
QUERYSTRINGwww.contoso.com/Libri/Details/?
id=12
URL PARAMETERwww.contoso.com/Libri/Details/12
HTML FORMSACTION del CONTROLLER “Libri”
public ActionResult Details(int id)
HTML FORM<form action=“/Persone/Edit”>
<input type=“text” name=“persona.Nome” />
<input type=“text” name=“persona.Cognome” />
<input type=“text” name=“persona.Eta” />
</form>
HTML FORM<form action=“/Persone/Edit”>
@Html.TextBoxFor(model => model.Nome)
@Html.TextBoxFor(model => model.Cognome)
@Html.TextBoxFor(model => model.Eta)
</form>
Model Binder: oggettiCLASSE “PERSONA”public string Nome { get; set; }
public string Cognome { get; set; }
public int Eta { get; set; }
MODEL BINDER
ACTION del CONTROLLER “Persone”public ActionResult Edit(Persona persona)
DEMO:ViewModel, Data Annotation e Strongly-Typed Views
ASP.NET MVC PER WINDOWS AZURE:BEH, CHE PROBLEMA C’È?
StatelessnessLoad 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 AzureClient 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 StateWindows Azure Load Balancer uses round-robin allocation. Session state must persist to client or storage on every request
SQL Azure Windows Azure Storage
LB
session[“foo”] = 1; session[“foo”] = 2;
What is the value of session[“foo”]?
Solving Session StatePersist 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 StateSession state stored using Windows Azure AppFabric Caching and an out-of-the-box session state provider
LB
session[“foo”] = 1; session[“foo”] = 2;
AppFabric Caching
What is the value of session[“foo”]?
SQL Server Session StateUse 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 StateSession state stored using SQL Server Session State Provider and session state partitioning
SQL Azure 3 x 1GB Databases
LB
session[“foo”] = 1;
resolve partition
session[“foo”] = 2;
What is the value of session[“foo”]?
Windows Azure Storage Providers
Sample ASP.NET Providers (Session, Membership, Role etc…)
Sample Codehttp://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.
CookiesSerialize 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
DNSAll 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 UploadASP.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 SolutionsUpload 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
TakeawaysASP.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
Creazione di un’applicazione Web con ASP.NET MVC + Azure
Demo
Creazione di un’applicazione Web con ASP.NET MVC
Demo
http://www.microsoft.com/windowsazure/free-trial
Questions
MicrosoftLogo here
Microsoft Logo Tagline here
IMAGINE CUP 2012
MicrosoftLogo here
Microsoft Logo Tagline here
IMAGINE A WORLD...
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.
OVERVIEW
The Game Design: Phone competition is an excellent opportunity to learn the art of mobile video game design!
The IT Challenge is an individual challenge for students around the world who have the nterest, and technical knowledge to design infrastructures.
The structure of the game is entirely up to you! The goal :Creatively using technology.
The Software Design Competition is all about creating real-world applications that can help make the world a better place.
MicrosoftLogo here
Microsoft Logo Tagline here
INSPIRATION
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
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!!
MicrosoftLogo here
STAY TUNED ON
SITE: WWW.MICROSOFT.IT/STUDENTIWWW.IMAGINECUP.COM
SOCIAL: FB FANPAGE INIZIATIVE STUDENTI
MAIL TO: [email protected]
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