You are on page 1of 117

06/10/2013

Dezvoltarea aplicaiilor de tip Cloud


INTRODUCERE
s.l. dr. ing. Daniel Iercan

Organizare
2 ore curs 2 ore laborator (B624) nota activitate = media notelor 3 lucrari || teme curs nota examen = examen grila || aplicatie

06/10/2013

Cuprins
evoluia puterii de calcul tipuri de cloud principalele platforme cloud tipuri de probleme care sunt rezolvate de tehnologiile de tip cloud impedimente n adoptarea tehnologiilor de tip cloud

beneficiile folosirii puterii de calcul din cloud

Evoluia puterii de calcul


mainframe i terminale

06/10/2013

Evoluia puterii de calcul


PCs

Evoluia puterii de calcul


reele de calculatoare

06/10/2013

Evoluia puterii de calcul


WWW era (servere simple)

Evoluia puterii de calcul


WWW era (clustere de servere)

06/10/2013

Evoluia puterii de calcul


WWW era (centre de date)

Microsoft Data Center in Dublin, 27,000 m2, 22 MW, US$ 500 M

Centre de date
consum mare de energie (1.5% din toat energia electric consumat in SUA, EPA 2007) durat lung de dezvoltare capitalul investit este dificil de recuperat/refolosit

este nevoie de specialiti n diverse domenii (securitate, fiabilitate, load balancing etc.)
se pierde din concentrarea de pe domeniul principal de activitate accesibil doar pentru companiile foarte mari din cauza dificultilor de ntreinere

06/10/2013

Soluia: externalizarea centrului de date


dezvoltatorii de aplicaii web se concentreaz pe competenele de baz timp scurt de lansare capitalul investit iniial este redus puterea de calcul devine o utilitate, la fel cum s-a ntmplat cu energia electric la nceputul secolului XX

Evoluia produciei de energie electric

See The Big Switch: Rewiring the World, from Edison to Google , by Nicholas Carr, Norton, 2008

06/10/2013

Tipuri de cloud
Private (On-Premise)
aplicaie runtime securitate i integrare baze de date servere virtualizare servere hardware spaiu de stocare reea

Infrastructure (as a Service)


aplicaie runtime securitate i integrare baze de date servere virtualizare servere hardware spaiu de stocare reea

Platform (as a service)


aplicaie runtime securitate i integrare baze de date servere virtualizare servere hardware spaiu de stocare reea

Software (as a service)


aplicaie runtime securitate i integrare baze de date servere virtualizare servere hardware spaiu de stocare reea

gestionat de dezvoltator

gestionat de provider

Principalele platforme cloud

06/10/2013

Amazon Web Services


http://aws.amazon.com/

Amazon Web Services


lansat n 2002 dezvoltat de amazon.com deschis pentru o gam larg de limbaje de programare: Java, Python, Ruby, .Net

a evoluat de la putere de calcul simpl la servicii specializate pentru comer

06/10/2013

AWS Products

Google App Engine


https://cloud.google.com/

06/10/2013

Google App Engine


lansat n 2008 principalele limbaje de programare sunt Python i Java

Google App Engine Products and Services

10

06/10/2013

Microsoft Windows Azure


http://www.windowsazure.com/en-us/

Microsoft Windows Azure


lansat n 2009 programare folosind limbajele din platform .Net, dar i Java, JavaScript i PHP putere de calcul i spaiu de stocare

acces la infrastructur

11

06/10/2013

Microsoft Windows Azure Products and Services

Tipuri de probleme rezolvate de tehnologiile de tip cloud

12

06/10/2013

On / Off
Inactivity Period

ex: rularea unor experimente

Cretere rapit

ex: un joc care are mare succes

13

06/10/2013

Vrfuri predictibile

puterea de procesare nefolosit nsemn resurse irosite incapacitatea de a satisface cererile de vrf pot distruge afacerea

Vrfuri nepredictibile

incapacitatea de a gestiona un altfel de vrf poate avea efecte negative asupra afacerii

14

06/10/2013

Ce se ntmpl dac platforma cloud moare


platformele cloud au o fiabilitate mult mai redicat dect ce ar putea realiza o companie pe cont propriu dac fiabilitatea este foarte important se recomand pstrarea unui numr minim de server n interiorul companiei care s asigure minimul necesar funcionrii afacerii ex.: spitalele au propriile generatoare de energie electric

Impedimente n adoptarea tehnologiilor de tip cloud


date ultra-sensibile legal

disponibilitatea resurselor cloud

15

06/10/2013

Beneficiile folosirii puterii de calcul din cloud


cost redus spaiu de stocare crescut nivel ridicat de automatizare flexibilitate mobilitate crescut

accentul se pune pe inovare i nu pe ntreinerea infrastructurii

Arhitecturi bazate pe servicii


unitate logic ce se autogestioneaz partajeaz doar protocoale apelate de aplicaii software reprezentnd un sistem software complex

serviciu web metod de comunicare ntre componente aflate pe WWW

Tipuri de servicii dup protocol:


SOAP bazat pe XML RESTful bazat pe protocolul HTTP

16

06/10/2013

SOAP
Envelope Header

Body

RESTful
operaiile sunt mapate peste verbele HTTP:
GET obine o resurs POST creaz o resurs PUT actualizeaz o resurs DELETE - terge o resurs)

format mesaj
XML: <Persoana> <Nume>Jon</Nume><Prenume>Smith</Prenume></Persoana> JSON: {nume: Jon, prenume:Smith}

17

06/10/2013

DEMO RESTful

DEMO
publicare aplicatie ca si web site creare baza de date conectare aplicaie la baza de date cost

18

08/10/2013

Dezvoltarea aplicaiilor de tip Cloud


COMPUTE
s.l. dr. ing. Daniel Iercan

Ce este Windows Azure Compute?

08/10/2013

Cloud Services
General purpose host for executing code or an executable Implement code in a Run method

WORKER ROLE

Similar to a Windows Service Host your own web server, encoder, etc. Typically used for background processing

Designed for web sites/services accessible using HTTP

WEB ROLE

Provides all features of a worker role and IIS 7 or 7.5 Execute ASP.NET, WCF, PHP, etc. Can include multiple web sites in the same role Optionally implement RoleEntryPoint

Ce se poate rula?

08/10/2013

Rol vs. Instanta

08/10/2013

08/10/2013

Roles and Instances

Fault Domain vs. Upgrade Domain


Fault Domain #1 Fault Domain #2 Fault Domain #3 Upgrade Domain #1 Instance #1 Upgrade Domain #2 Instance #2

Upgrade Domain #3

Instance #3

Fault Domain #2 Fault Domain #1

Upgrade Domain #1 Upgrade Domain #2 Upgrade Domain #3

Instance #1 Instance #2 Instance #3

08/10/2013

Role Environment API


RoleEnvironment: - var settingValue = RoleEnvironment.GetConfigurationSettingValue("MySetting"); - LocalResource localResource = RoleEnvironment.GetLocalResource("localStoreTwo"); - RoleEnvironment.CurrentRoleInstance - RoleEnvironment.Changed += RoleEnvironmentChanged private void RoleEnvironmentChanged(object sender, RoleEnvironmentChangedEventArgs e) {}

The High Scale Application Archetype

08/10/2013

08/10/2013

Local Storage

08/10/2013

DEMO - website
create a new web site deploy an ASP.NET MVC application explore various configurations retrieve application settings enable diagnostic

simulate error
download diagnostics using azure command

DEMO
create a cloud service only web role with two instances
show fault domain and upgrade domain Production vs. staging local storage share session using Cache remote desktop

create a cloud service with web and worker role, worker role will host a WCF

08/10/2013

Dezvoltarea aplicaiilor de tip Cloud


STORAGE
s.l. dr. ing. Daniel Iercan

Windows Azure Storage

08/10/2013

Windows Azure Storage Account

Windows Azure Storage Account

08/10/2013

Storage in the Development Fabric

The Storage Client API

08/10/2013

Storage Libraries in Many Languages

Storage Security

08/10/2013

Windows Azure Storage Abstractions

Blob Storage

08/10/2013

Blob Storage Concepts

Blob Details

08/10/2013

Blob Details

Blob Details

08/10/2013

Blob Containers

Enumerating Blobs

08/10/2013

Pagination

APIs
REST API: http://msdn.microsoft.com/enus/library/windowsazure/dd135733.aspx

.NET Library
http://www.nuget.org/packages/WindowsAzure.Storage

08/10/2013

Demo
desktop application to publish to storage
publish course material use a third party tool to see published files make files public use RESTful API to download files

Drives

10

08/10/2013

Windows Azure Drives

Windows Azure Drive Capabilities

11

08/10/2013

Windows Azure Drive Capabilities

Drive Details

12

08/10/2013

How Windows Azure Drives Works

Cloud Drive Client Library Sample


CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("CloudStorageAccount"); //Initialize the local cache for drives mounted by this role instance CloudDrive.InitializeCache(localCacheDir, cacheSizeInMB); //Create a cloud drive (PageBlob) CloudDrive drive = account.CreateCloudDrive(pageBlobUri); drive.Create(1000 /* sizeInMB */); //Mount the network attached drive on the local file system string pathOnLocalFS = drive.Mount(cacheSizeInMB, DriveMountOptions.None); //Use NTFS APIs to Read/Write files to drive //Snapshot drive while mounted to create backups Uri snapshotUri = drive.Snapshot(); //Unmount the drive drive.Unmount();

13

08/10/2013

Failover with Drives

Demo???

14

08/10/2013

Queues

Queue Storage Concepts

15

08/10/2013

Loosely Coupled Workflow with Queues

Queue Details

16

08/10/2013

Queue Details

Queues Reliable Delivery

17

08/10/2013

APIs

Demo
upload photo and create thumb nails using worker role

18

08/10/2013

Tema
50% examen HTML + JavaScript (JQuery) 25% examen (Windows Forms || WPF cu HttpClient) - inscriere laborator - publicare material curs/laborator

- descarcare material curs/laborator


- publicare rezolvari

Termen 21 Oct. 2013

Web resources
http://blogs.msdn.com/b/windowsazurestorage/archive/2010/12/30/ windows-azure-storage-architecture-overview.aspx http://blogs.msdn.com/b/windowsazurestorage/archive/2010/05/10/ windows-azure-storage-abstractions-and-their-scalability-targets.aspx

http://www.windowsazure.com/en-us/develop/net/how-toguides/blob-storage/
http://blogs.msdn.com/b/windowsazurestorage/archive/2010/04/17/ windows-azure-storage-explorers.aspx

19

20/11/2013

Dezvoltarea aplicaiilor de tip Cloud


NO-SQL VS. SQL
s.l. dr. ing. Daniel Iercan

NO-SQL

20/11/2013

Key-value type of storage


good for storing simple data

Name: Jon

Dob: 01-01-1990

City: New York

Street: One street

ZipCode: 12345

Variable schema
a single table can contain rows with different columns

Name: Smith Name: Holmes

Dob: 01-01-1990 Dob: 01-01-1991

City: New York Village: New York

Street: One street Street: One street

ZipCode: 12345 PostalCode: 12345

20/11/2013

No-relational
there is no implicit relation between rows in database relations can be defined in code

Distributed architecture
- highly scalable database (web scale) - redundant storage - geographic distribution

20/11/2013

CAP Theorem
Availability

Relational

Consistency

Partition Tolerance

Querying
some use SQL more likely imperative programming (map-reduce)

20/11/2013

Types of NO-SQL
key-value stores
Schema-free

document stores
schema-free

wide column store


semi-schematic

graph databases
Social networks

NO-SQL in Azure
TABLE STORAGE

20/11/2013

Table Storage Concepts

Entity Properties

20/11/2013

No Fixed Schema

Querying

20/11/2013

Purpose of the PartitionKey

Partitions and Partition Ranges

20/11/2013

Demo
C# library to access Azure tables Extend photo album to store list of files in a table And list of comments in a second table

SQL

20/11/2013

SQL Azure Database is

Get started quickly

Ready to get started?

Provision Your Server


Server defined
Service head that contains databases Connect via automatically generated FQDN (xxx.database.windows.net) Initially contains only a master database

Provision servers interactively


Log on to Windows Azure Management Portal Create a SQL Azure server Specify admin login credentials Add firewall rules and enable service access

Automate server provisioning


Use Windows Azure Platform PowerShell cmdlets (or use REST API directly) wappowershell.codeplex.com

10

20/11/2013

Build Your Database


Use familiar technologies
Supports Transact-SQL Supports popular languages
.NET Framework (C#, Visual Basic, F#) via ADO.NET C / C++ via ODBC Java via Microsoft JDBC provider PHP via Microsoft PHP provider

Differences in comparison to SQL Server

Supports popular frameworks


OData (REST data access) Entity Framework WCF Data Services NHibernate

Focus on logical vs. physical administration Database and log files automatically placed Three high-availability replicas maintained for every database Databases are fully contained Tables require a clustered index Maximum database size is 50 Gb

Supports popular tools


SQL Server Management Studio (2008 R2 and later) SQL Server command-line utilities (SQLCMD, BCP) CA Erwin Data Modeler Embarcadero Technologies DBArtisan

Unsupported SQL Server features

BACKUP / RESTORE USE command, linked servers, distributed transactions, distributed views, distributed queries, four-part names Service Broker Common Language Runtime (CLR) SQL Agent

Database
Thin client database development

Rich client database development

11

20/11/2013

Database
Data-tier Application Framework (DAC Fx)

How to get the latest DAC Fx

Database
Interactive approach for dacpac v1 and v2

Interactive approach for bacpac v2

Upgrading a dacpac or bacpac

12

20/11/2013

Secure Your Database


Server identity and access control
SQL authentication supported Integrated authentication not supported Connect to master to administer logins and create / drop databases The admin login (configured during service provisioning) is like sa The admin login has full rights on the server (and all databases) and should only be used for administration Manage logins with CREATE / ALTER / DROP LOGIN commands Membership in the loginmanager server role grants CREATE / ALTER / DROP LOGIN priveleges Membership in the dbmanager server role grants CREATE / DROP DATABASE privileges

Database identity and access control

Logins must have an associated user account to connect to a database The admin login is automatically associated with a special user known as dbo (database owner) The dbo has full rights in the database and should only be used for administration Manage users with CREATE / ALTER / DROP USER commands Add users to system or user-defined database roles to grant privileges via sp_add_rolemember Organize database objects into schema containers based upon common access control requirements Grant privileges to schema containers instead of individual objects for better productivity

Connect Your Application


Connecting to SQL Azure
TDS (Tabular Data Stream) protocol over TCP/IP supported SSL required Use firewall rules to connect from outside Microsoft data center ASP .NET example:

Special considerations
Legacy tools and providers may require special format for login: [login]@[server] Idle connections terminated after 30 minutes Long running transactions terminated after 24 hours

DoS guard terminates suspect connections with no error message


Failover events terminate connections Throttling may cause errors Use connection pooling and implement retry logic to handle transient failures Latency introduced for updates due to HA replicas No cross-database dependencies, result sets from different databases must be combined in application tier

<connectionStrings> <addname="AdventureWorks"connectionString= "Data Source=[server].database.windows.net; Integrated Security=False; Initial Catalog=ProductsDb; User Id=[login]; Password=[password]; Encrypt=true;" providerName="System.Data.SqlClient"/> </connectionStrings>

13

20/11/2013

Demo
Create new DB Create a Data project Deploy to Azure Connect from an application
ADO.NET EF

No-Sql vs. Sql

14

20/11/2013

Performance
certain types of queries can be slow for business application SQL most likely are better for fetching few bits of information but high traffic an concurrency NOSQL is better

Business Intelligence
best works with SQL NO-SQL (wide-columns) works good with BIG DATA

15

20/11/2013

Dezvoltarea aplicaiilor de tip Cloud


VIRTUAL MACHINES
s.l. dr. ing. Daniel Iercan

What is Infrastructure as a Service (IaaS)


hardware as a programmable resource
server network storgae

20/11/2013

Why use IaaS


hard to predict costs dynamically allocate hardware resources agility (develop based on business needs) fault tolerance

IaaS use scenario


extend storage use VMs deploy apps move existing apps disaster recovery

20/11/2013

IaaS on Windows Azure


Virtual Machines Blobs Virtual Networks

Demo create a VM from UI

20/11/2013

Disks and Images


VHD (Virtual Hard Disk) Image read-only template, generic vhd

Discs vhd that can be mounted


os disk 127GB max data disk max 1TB local cache (enabled for OS disabled for data disk)

VM Costs
compute cost (includes OS license) storage costs (space + # of operations) 1cent / 100000 operations boot Windows Server 2008 = 20000 operations

20/11/2013

Demo create an Image

Demo persisted vs. transient storage

20/11/2013

Availability set and load balance set


machine in the same cloud service can be deployed in separate availability sets public endpoints are load balanced (round robin) VIP and load balancer port mapping

Import/Export configuration data to XML


recreate the machine in a different data centre

20/11/2013

Virtual network
connect VMs separate VMs - create subnets DNS resolve

Extend private network (enterprise network) - Hybrid networks

Demo virtual network

20/11/2013

Azure PowerShell
scripting language that can be used to manage IaaS on Azure CmdLets Pipe Operator .Include Variables

Scope

http://msdn.microsoft.com/en-us/library/jj156055.aspx

Azure IaaS object model


CloudService Deployment Role NetworkConfigurationSet InputEndPoin OSVirtualHardDisk DataVirtualHardDisks WindowsProvisioningConfiguratioSet LinuxProvisioningConfigurationSet

20/11/2013

Deploy a VM using PowerShell


http://msdn.microsoft.com/enus/library/windowsazure/jj835085.aspx#bk_Custom

20/11/2013

Dezvoltarea aplicaiilor de tip Cloud


IDENTITY
s.l. dr. ing. Daniel Iercan

Classic approach
manage user by the application
e.g.: ASP.NET membership database 1 unauthenticated request 2 redirect to login client (browser) web application

3 username and password 2 redirect to requested resource or fail

20/11/2013

Identity provider
manage user by the application
e.g.: ASP.NET membership database 3 login procedure

1 unauthenticated request 2 request to login


client (browser) 5 authenticated request 8 resource needed web application

6 request user info 7 user info identity provider

4 security token is sent

Protocols
WS-Security (WS-Federation, WS-Trust) SAML 2.0

20/11/2013

Security token
unique ID of the user other claims
name e-mail address

Windows Azure Identity


Can be used to run Windows Active Directory (on a VM) which allows control of access to VM in Azure Implement single sign-on to the Software as a Service applications (Windows Azure Active Directory)

Allows using external identity providers, e.g., Google, Facebook, Live (Windows Azure Active Directory Access Control)

20/11/2013

Running AD in VMs

http://www.windowsazure.com/en-us/develop/net/fundamentals/identity/

Windows Azure Active Directory

http://www.windowsazure.com/en-us/develop/net/fundamentals/identity/

20/11/2013

Graph API
RESTful API supports extensions defined by Odata can be used to get extra information about a user from Azure Active Directory based on the security token (e.g., social graph)

http://msdn.microsoft.com/enus/library/windowsazure/hh974476.aspx

Windows Azure Active Directory Access Control

http://www.windowsazure.com/en-us/develop/net/fundamentals/identity/

20/11/2013

Windows Azure Active Directory


Provides:
Identity Access management

Active Directory is managed by the Azure platform to ensure high availability, disaster recovery, high scalability

Can be integrated with on-premises Active Directory


Integrates with applications to provide single sign-on functionality Intermediates with other IdPs

Windows Identity Fundation


http://msdn.microsoft.com/en-us/library/hh377151.aspx

20/11/2013

Demo
ASP.NET MVC application that logins through google using Windows Azure Active Directory Access Control

20/11/2013

Dezvoltarea aplicaiilor de tip Cloud


MOBILE SERVICIES
s.l. dr. ing. Daniel Iercan

Overview of Azure Mobile Services


data allows using SQL identity authorize users using various Identity Providers API build RESTful API scheduler perform period tasks push send push notifications

20/11/2013

http://msdn.microsoft.com/en-us/library/hh221549.aspx

Demo default TODO item app


download todo item app for windows store add support for authentication add support for notifications create RESTfull API for the to item APP

20/11/2013

Add support for authentication


register with an Identity Provider http://www.windowsazure.com/en-us/develop/mobile/how-toguides/register-for-google-authentication/ modify windows store APP to authenticate users
async void MainPage_Loaded(object sender, RoutedEventArgs e) { _user = await App.MobileService.LoginAsync( MobileServiceAuthenticationProvider.Google); }

Add support for authentication


Update INSERT and READ operations to use information about user
function insert(item, user, request) { item.userId = user.userId; request.execute(); }

function read(query, user, request) { query.where({ userId: user.userId }); request.execute(); }

20/11/2013

Notify clients for incomplete tasks


In windows store app create a notification channel
Windows.Networking.PushNotifications.PushNotificationChannelManager. CreatePushNotificationChannelForApplicationAsync()

Save notification URI with the todo item

add a schedule to send notifications

Send notification from scheduler


function SendTodoNpotificaiton() { tables.getTable("TodoItem").where({complete:false}).read({success: sendNotifications}); } function sendNotifications(results){ for(var i=0; i<results.length; i++){ if(results[i].channel!== null){ push.wns.sendToast(results[i].channel, {text1: "Reminder", text2: results[i].text}); } } }

20/11/2013

Dezvoltarea aplicaiilor de tip Cloud


MEDIA SERVICIES
s.l. dr. ing. Daniel Iercan

Overview of Azure Media Services


upload video in the cloud convert video to different formats

RESTful (OData) and .Net API

20/11/2013

Operations
Ingest bring assets into the system Process encoding, converting and generating media assets

Manage working with assets in Media Services

Deliver retrieve media out of the Media services (streaming content live or on-demand to clients)

Programming entities
Assets virtual entity that contains metadata about media; can contain one or many files Files an actual video or audio blob, always associated with a file Jobs entity that contains metadata about tasks; a job is associated with one or more tasks Tasks individual operation of work AccessPolicies define permissions to a file or asset Locator URI that provides time-based access to a specific asset

20/11/2013

Programming entities
JobTemplates provides reusable settings for jobs ContentKeys store key data, which is used to encrypt an asset TaskTemplate provides reusable settings for tasks

http://msdn.microsoft.com/enus/library/windowsazure/hh973632.aspx

http://msdn.microsoft.com/enus/library/windowsazure/jj129584.aspx

http://msdn.microsoft.com/enus/library/windowsazure/jj129575.aspx

20/11/2013

Dezvoltarea aplicaiilor de tip Cloud


INTEGRATION
s.l. dr. ing. Daniel Iercan

Service Bus
service relay
WCF model

messaging
queues publish-subscribe

notification hubs
Windows phone Windows store iOS Android

20/11/2013

Why Service Bus?

Cloud/On-Premise Integration

20/11/2013

Cloud/On-Premise Integration

Cross-Site Federation (SaaS)

20/11/2013

Tightly Coupled
Drivers

Tracking

Store Front End

Shipping Service

Tightly Coupled
Drivers

Tracking

Store Front End

Shipping Service

20/11/2013

Loosely Coupled
Drivers

Tracking

Store Front End

Order Queue

Shipping Service

Loosely Coupled
Drivers

Tracking

Store Front End

Order Queue

Shipping Service

20/11/2013

Loosely Coupled
Drivers

Tracking

Store Front End

Order Queue

Shipping Service

Loosely Coupled

Tracking

Tracking

Store Front End

Order Queue

Shipping Service

20/11/2013

Service Bus Relay

Expose Web Services from anywhere to anywhere


Key Capabilities
Relayed One-Way Unicast and Multicast Relayed WCF NET.TCP with Direct Connect Option Relayed WCF HTTP with support for REST and SOAP 1.1/1.2 Endpoint protection with Access Control

Outbound TCP (Ports 9350-9353)


9350 Unsecured TCP One-way (client) 9351 Secured TCP One-way (all listeners, secured clients) 9352 Secured TCP Rendezvous (all listeners except one-way) 9353 Direct Connect Probing Protocol (TCP listeners with direct connect)

Connectivity Options

Outbound HTTP (Port 80, Listeners)


TCP equivalent tunnel with overlaid TLS/SSL formed over pair of HTTP requests Alternate connectivity path if outbound TCP is blocked

Outbound HTTPS (Port 443, Senders)

20/11/2013

Relay Programming Model

Oneway

20/11/2013

20/11/2013

Windows Azure

10

20/11/2013

Windows Azure

Existing Datacenter

On Premises

Windows Azure

On Premises

11

20/11/2013

Service Bus Messaging

Relay vs. Message Broker

12

20/11/2013

Push vs. Pull

Ways to Pull

13

20/11/2013

Messages

Queues

14

20/11/2013

Queues

Topics

15

20/11/2013

Subscription Filters

Runtime API Choices

16

20/11/2013

Messaging API Hello World!


var tkp = TokenProvider.CreateSharedSecretTokenProvider var svcUri = ServiceBusEnvironment.CreateServiceUri( var nsm = new NamespaceManager(svcUri, tkp); nsm.CreateQueue(queueName); var mf = MessagingFactory.Create(svcUri, tkp); var qc = mf.CreateQueueClient(queueName); qc.Send(new BrokeredMessage { Properties = {{ var m = qc.Receive(); Console.WriteLine(m.Properties[ ]); , }}}); , , ""); , "");

17

04/12/2013

Dezvoltarea aplicaiilor de tip Cloud


ODATA
s.l. dr. ing. Daniel Iercan

Context
service design
SOAP (Simple Object Access Protocol), well defined message formats (there is a lot of protocol information)

POX (Plain Old XML) builds on top of HTTP and uses XML to exchange data, there are no constrains
REST (REpresentational State Tranfser), builds on top of POX but adds some constrains

04/12/2013

Context
web data formats
XML
common data format open format

JavaScript Object Notation (JSON)


AJAX optimized Compact

Atom
based on XML, supports embedded data
used for feeds (e.g., RSS feeds)

Atom Publishing Protocol (AtomPub)


extends Atom to allow editing documents (e.g., blogs)

What is OData
a data access protocol provide CRUD access to a data source via a REST service open
based on web standards HTTP, JSON, AtomPub

data
designed to query and update data flexible enough to be used with relational databases, files, etc.

protocol
convention for representing data entities query string convention (addressing and filtering data) constrained HTTP operations for submitting requests

04/12/2013

What is OData
metadata support well defined parameters for query http://www.odata.org/

OData Service with WCF


WCF data services
entity data model LINQ to SQL .Net object custom provider

DataService base class for the service configure access to entities add custom operations define filters and interceptors

04/12/2013

Filters and interceptors


query interceptors apply to GET operations
can be used to apply business rules, validations and security, when data is queried

change interceptors apply to POST, PUT, DELETE


can be used to apply business rules, validations and security, when data is updated

use attributes to hook the process (e.g., QueryInterceptor, ChangeInterceptor) apply to a particular entity in the model

Demo
OData service using WCF
discuss how data is represented and how entities are linked filtering Metadata

add custom operation to retrieve list of enrolled courses

04/12/2013

OData Client in .Net


any client library that support HTTP (e.g., HttpClient) use jQuery LINQ to REST

System query options


$filter $orderby $top $skip $select $inlecount $value $expand

04/12/2013

Odata Client in .Net


Add service reference
LINQ support Data binding support Batch operations support

.Net built in classes


DataServiceContext Querying
DataServiceQuery QueryOperationResponse

Updates
DataServiceRequest DataServiceResponse

continuation token can be used to get paged results

04/12/2013

Demo
DataServiceContext
query data find extra information about query

Batch update Paging and continuation

OData Client in JS
jQuery Datajs (http://datajs.codeplex.com/wikipage?title=OData%20Code%20Snipp ets&referringTitle=Documentation)

04/12/2013

JASONP(JASON with padding)


only works for GET for other verbs a proxy is needed both service and client need special setup to support this

Demo
JS OData client fro students enrol Invoke GetInscrieri using JSONP

04/12/2013

Dezvoltarea aplicaiilor de tip Cloud


ODATA & OAUTH
s.l. dr. ing. Daniel Iercan

Odata Services security


can use HTTP built in security (e.g., client credential, client certificates, forms authentication) or layered security (e.g., Oauth, Access Control)

04/12/2013

What is OAuth
delegating authorization authorize service to service communication without using username and password ability to revoke authorization authorization throw OAuth consists of to steps:
request access token from authorization service use token to access resources on a different server

Main scenario
resource owner client resource

user

user user applications

cloud resource

04/12/2013

OAuth parties
resource owner resource server authorization server client (trusted / untrusted)

Oauth parties
03 is registered with client 04 authorizes 05 accesses 02 uses trusts authorization server

user

01 own resource

resource server

04/12/2013

Difference between OAuth and Open ID Connect


Open ID Connect allow identification of the user (authentication) OAuth authorize access to resources

Security Token
protected data structures
contains information about issuer and subject signed expiration date

requested by client issued by an issuer Resource consumes the token

04/12/2013

Tokens historic
SAML (WS-*)
XML based support complex cryptography

Simple Web Tokens (SWT)


Only symmetric cryptography

JSON Web Token (JWT)


JSON encoded symmetric and asymmetric signatures/encription

JSON Web Token (JWT)


Header
Metadata algorithms and keys used

Claims
issuer audience issued at expiration subject application defined claims

04/12/2013

Demo
JWT encoded eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJpc3MiOiJDbG91ZExhYiIsI mF1ZCI6Imh0dHA6Ly9odHRwOi8vY2xvdWRsYWIuYXp1cmV3ZWJzaX Rlcy5uZXQvIiwibmJmIjoxMzg1NTg1NjkyLCJleHAiOjEzODU1ODYyOTIsI mh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaW RlbnRpdHkvY2xhaW1zL3NpZCI6IjEiLCJEaXNjaXBsaW5hIjoiREFUQyIsIl VVSUQiOiJqS0pBaFZPcE0zTUp6cmdmbUVVY25pZVRaKzhneHZjTUorS UZ4U3ZmYjhZPSJ9.

Demo - JWT decoded


Header { "alg": "none", "typ": "JWT" } Claims { "Disciplina": "DATC", "aud": "http://http://cloudlab.azurewebsites.net/", "iss": "CloudLab", "exp": 1385586292, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid": "1", "nbf": 1385585692, "UUID": "jKJAhVOpM3MJzrgfmEUcnieTZ+8gxvcMJ+IFxSvfb8Y=" } Signature (encoded)

04/12/2013

.Net Library
System.IdentityModel.Tokens.JWT (NuGet)

Demo
Generating JWT in .net (TokenGenerator) Consuming JWT in .net (enrol service)

04/12/2013

OAuth flows (with user interaction)


authorization code flow
web application clients
request authorization request token access resource

implicit flow
native / local clients
request authorization & token access ressource

OAuth flows (with no user interaction)


resource owner password credential flow
trusted clients
request token with resource owner credential access resource

client credential flow


client to service communication
request token with client credential access resource

You might also like