MCSD Web Applications Certification Windows Azure Web Services
MCSD Web Applications Certification Windows Azure Web Services
MCSD Web Applications Certification Windows Azure Web Services
1. 1
Module 1
Overview of Service and
Cloud Technologies
Developing Windows Azure
and Web Services
1. 2
Deploying Web
Applications
and Services
19%
Creating and
Consuming
Web API-based
services
18%
Designing and
Implementing
WCF Services
19%
Accessing Data
24%
Querying and
Manipulating
Data by Using
the Entity
Framework
20%
Warnings!
Some of the code in questions
miss spaces, commas, or semicolons. Try not to let that put
you off:
var doc = newXDocument();
1. 3
Qs
6: Hosting Services
8: Deploying Services
D: LINQ
42
1. 4
Overview
DataAdapter
Oracle
Etc.
1. 5
Overview
Object-Relational Mapping
What are ORMs?
Objects are more natural to work with for programmers...
...but relational data is better for storage
Mapping converts CRUD on objects to CRUD on relational data
Philosophy of ORM
If you do most work through stored procedures (SELECT, etc.)
you will gain very little from using an ORM so use Classic
ADO.NET instead
1. 6
Overview
LINQ
to XML
LINQ to
Objects
DataAdapter
Entity SQL
LINQ
to SQL
LINQ to Entities
EntityClient
SQL Server
Oracle
Etc.
SQL Server
Oracle
Etc.
1. 7
Overview
1. 8
Overview
LINQ
to XML
LINQ to
Objects
LINQ
to SQL
Entity SQL
LINQ to Entities
ObjectContext1
DbContext2 .
EntityClient
DataAdapter
SQL Server
Oracle
Etc.
SQL Server
Oracle
Etc.
Overview
1. 9
Overview
1. 10
Overview
1. 11
Third-Party Providers
http://msdn.microsoft.com/en-us/data/dd363565.aspx
Further Study
1. 12
Further Study
1. 13
Further Study
1. 14
Further Study
1. 15
Windows Azure
Windows Azure is changing so fast that printed books
are not the best choice
Use the official online documentation and blogs
You can also download the 211 page PDF about
Building Real-World Cloud Apps with Windows Azure
using the link below
Windows Azure
http://msdn.microsoft.com/en-us/library/windowsazure/dd163896.aspx
2. 1
Module 2
Querying and Manipulating
Data Using Entity Framework
Developing Windows Azure
and Web Services
2. 2
Entity Framework
Contents
Topic
Slide
ADO.NET Classic
Connection Strings
11
17
22
Inheritance Hierarchies
30
Designer Tools
33
Loading Patterns
38
Entity SQL
39
EntityClient
46
Querying Summary
48
Performance
49
Transactions
50
ADO.NET Classic
2. 3
using System.Data;
using System.Data.SqlClient;
var con = new SqlConnection(conStr);
var cmd = new SqlCommand(sql, con);
con.Open(); // open connection before executing commands
Common CommandBehaviors
CloseConnection, SequentialAccess, SingleResult, SingleRow
var reader = cmd.ExecuteReader(CommandBehavior.SingleResult);
while (reader.Read()) // returns true if another row exists
{
// process row
}
// reader.NextResult(); // returns true if another result exists
reader.Close(); // close reader before reading parameters
int outputParam = (int)cmd.Parameters[2].Value;
con.Close(); // or use CommandBehavior.CloseConnection
ADO.NET Classic
2. 4
ADO.NET Classic
2. 5
ADO.NET 4.5
Task<int> t = cmd.ExecuteNonQueryAsync();
// do other work
int i = await t;
Connection Strings
2. 6
Entity Framework
http://msdn.microsoft.com/en-us/data/aa937723
Connection Strings
2. 7
Connection Strings
2. 8
Option
Description
assemblyFullName
resourceName
2. 9
Connection Strings
EntityConnectionStringBuilder
Should be used in conjunction with a
SqlConnectionStringBuilder (or underlying provider)
The connection string for the underlying data source is supplied
by the ProviderConnectionString property which is not checked
for valid keyword/value pairs
var sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = serverName;
// set other provider-specific properties
var efBuilder = new EntityConnectionStringBuilder();
efBuilder.Provider = providerName;
efBuilder.ProviderConnectionString = sqlBuilder.ToString();
efBuilder.Metadata = @"res://*/AdventureWorksModel.csdl|...";
string s = efBuilder.ConnectionString;
2. 10
Connection Strings
database=Northwind;
2. 11
Defining an Entity
CSDL (Conceptual Schema Definition Language)
<EntityType Name="Accessory">
Class/Entity
<Key>
<PropertyRef Name="ProductID" /> Property
</Key>
<Property Name="ProductID" Type="Int32"
Nullable="false" />
<Property Name="SystemName" Type="String"
Nullable="false"
.NET Type
MaxLength="100" ...="" />
<NavigationProperty Name="Product"
Relationship="..."
FromRole="Accessory" ToRole="Product" />
</EntityType>
2. 12
Defining a Table
SSDL (Store Schema Definition Language)
Table
<EntityType Name="Accessory">
Primary Key
<Key>
<PropertyRef Name="ProductID" />
Column
</Key>
<Property Name="ProductID" Type="int" Nullable="false" />
<Property Name="SystemName" Type="nvarchar"
Nullable="false" MaxLength="100" /> Database Type
<Property Name="rowguid" Nullable="false"
Type="uniqueidentifier"
Generated when
StoreGeneratedPattern="Identity" />
entity is inserted
<Property Name="ModifiedDate" Type="timestamp"
StoreGeneratedPattern="Computed" />
Generated when
entity is updated
</EntityType>
2. 13
Entity to Table
MSL (Mapping Specification Language)
<EntitySetMapping Name="AccessoryMapping"
StoreEntitySet="Accessory"
TypeName="Accessory">
Table
Class/Entity
Property
<ScalarProperty Name="ProductID"
ColumnName="ProductID" />
Column
<ScalarProperty Name="SystemName"
ColumnName="SystemName" />
</EntitySetMapping>
2. 14
2. 15
2. 16
2. 17
CSDL
<FunctionImport Name="GetBill">
<Parameter Name="StartProductID"
Mode="In" Type="Int32" />
MSL
<FunctionImportMapping FunctionImportName="GetBill"
FunctionName="AWModel.Store.uspGetBillOfMaterials" />
SSDL
<Function Name="uspGetBillOfMaterials" ... Schema="dbo">
<Parameter Name="StartProductID" Type="int" Mode="In" />
VS2010 adding a stored procedure adds <Function> to the SSDL, but you must also
import the function to the CSDL which then adds the mapping and method
VS2012 adding a stored procedure does all four parts
2. 18
SSDL
<Function Name="uspUpdateProduct" ... Schema="dbo">
<Parameter Name="ProductID" Type="int" Mode="In" />
2. 19
2. 20
<Function> Attributes
Attribute Name
Description
Name (required)
StoreFunctionName
Schema
Aggregate
BuiltIn
NiladicFunction
IsComposable
10
2. 21
Summary
public ObjectResult<Department> GetDeptsByGroup(string group) {
return base.ExecuteFunction<Department>("GetDeptsByGroup", ...
<FunctionImport Name="GetDeptsByGroup" ... >
<Parameter ...
<Function Name="GetDeptsByGroup" ... >
<DefiningExpression> /* E-SQL */
CSDL
MSL
<FunctionImportMapping FunctionImportName="GetDeptsByGroup"
FunctionName="AWModel.Store.uspSelectDepartments" />
<DeleteFunction FunctionName="AWModel.Store.uspDeleteProduct">
<ScalarProperty Name="Name" ParameterName="Name" Version="Current" />
<Function Name="uspSelectDepartments" ... >
<CommandText> /* T-SQL */ </CommandText>
<Parameter ...
<Function Name="uspSelectDepartments" ... >
<Parameter ...
Code First
SSDL
2. 22
11
Code First
2. 23
Code First
2. 24
12
Code First
2. 25
Code First
2. 26
Modifying Data
Use the DbContext
using (var db = new NorthwindContext())
{
var food = new Category { CategoryName = "Foods" };
db.Categories.Add(food);
int recordsAffected = db.SaveChanges();
}
13
Code First
2. 27
Annotations
You can apply annotations to your model
using System.ComponentModel.DataAnnotations;
public class Category
{
[Key]
public int CategoryID { get; set; }
[MaxLength(20, ErrorMessage="20 chars max!")]
public string CategoryName { get; set; }
Annotations include
Key, StringLength, MaxLength, ConcurrencyCheck, Required,
Timestamp, ComplexType, Column, Table, InverseProperty,
ForeignKey, DatabaseGenerated, NotMapped
System.ComponentModel.DataAnnotations Namespace
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations(v=vs.110).aspx
Code First
2. 28
Fluent API
Considered a more advanced feature and we would
recommend using Data Annotations unless your
requirements require you to use the fluent API
public class NorthwindContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Supplier>().Property(s => s.Name).IsRequired();
14
Code First
2. 29
Conventions
Primary key convention
Code First infers that a property is a primary key if a property
on a class is named ID (not case sensitive), or the class name
followed by ID
If the type of the primary key property is numeric or GUID it will
be configured as an identity column
Code First
2. 30
Custom Conventions
Custom primary key convention
Now any property in our model named Key will be configured as
the primary key of whatever entity its part of
public class ProductContext : DbContext
{
static ProductContext()
{
Database.SetInitializer(
new DropCreateDatabaseIfModelChanges<ProductContext>());
}
public DbSet<Product> Products { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties()
.Where(p => p.Name == "Key")
.Configure(p => p.IsKey());
15
Code First
2. 31
Migration Support
For example, if you wanted to add a new column to a
Blogs table called Url
public partial class AddBlogUrl : DbMigration
{
public override void Up()
{
AddColumn("Blogs", "Url", c => c.String());
}
public override void Down()
{
DropColumn("Blogs", "Url");
}
}
EF 4.3 Released
http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-released.aspx
Inheritance Hierarchies
2. 32
16
2. 33
Inheritance Hierarchies
Table-per-hierarchy (TPH)
Characteristics
One table with discriminator column
GadgetId
Discriminator
Vendor
FormFactor
DisplayResolution
Nokia
Monoblock
NULL
Sony
NULL
1024*768
Advantages
High performance of CRUD operations
Minimum number of tables in the database
Disadvantages
Data redundancy which leads to the data integrity violation if
data was changed manually
Complexity of adding and deleting new entities because it is
necessary to add or delete columns to/from the result table
2. 34
Inheritance Hierarchies
Table-per-type (TPT)
Characteristics
One table for each entity
GadgetId
Vendor
Nokia
Sony
MobilePhoneId
FormFactor
NetbookId
Resolution
Monoblock
1280*768
Advantages
Data integrity is preserved with no data redundancy
Flexibility in object model modification
Disadvantages
The speed of the CRUD operation decreases when the number of
classes in the hierarchy grows
A large number of tables in the database
Entity Framework Mapping Scenarios
http://msdn.microsoft.com/en-us/library/cc716779.aspx
17
Designer Tools
2. 35
Designer Tools
2. 36
18
2. 37
Designer Tools
ObjectContext
.AddObject("entityset", entity)
.DeleteObject("entityset", entity)
ObjectQuery.ToTraceString()
.ExecuteStoreCommand("T-SQL")
.ExecuteStoreQuery("T-SQL")
.LoadProperty(customer, "Orders")
.ContextOptions.LazyLoadingEnabled
.ContextOptions.ProxyCreationEnabled
DbContext
.DbSet.Add(entity)
.DbSet.Remove(entity)
DbQuery.ToString()
.Database.ExecuteSqlCommand("T-SQL")
.Database.SqlQuery("T-SQL")
.Entry(customer).Collection(
"Orders").Load()
.Configuration.LazyLoadingEnabled
.Configuration.ProxyCreationEnabled
DbContext Class
http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.103).aspx
Designer Tools
2. 38
DbQuery<TResult> Class
http://msdn.microsoft.com/en-us/library/gg696530(v=vs.103).aspx
19
Designer Tools
2. 39
Navigation properties
Navigation properties in designer-generated code
public partial class Customer
{
public virtual ICollection<Order> Orders { get; set; }
public partial class Order
{
public virtual Customer Customer { get; set; }
2. 40
Loading Patterns
Pattern
Description
All in query
Compose a LINQ to Entities or Entity SQL query that uses navigation properties
Explicit
loading
Lazy
loading
Related entities are automatically loaded when you access a navigation property
(requires MARS and multiple round-trips to the database) Note: if you create an
.edmx it sets LazyLoadingEnabled = true
Eager
loading
Use Include() to define a query path that controls which related entities to
return so only a single request to the database is required
var contacts = from contact in db.Contacts
.Include("SalesOrderHeaders.SalesOrderDetails")
.Include(c => c.Address);
// to use lambda in Include
using System.Data.Entity;
20
Entity SQL
2. 41
Entity SQL
2. 42
VALUE Keyword
If your query returns a subset of columns then the
DbDataRecord type must be used (VALUE not allowed)
Returns IEnumerable<DbDataRecord>
SELECT p.ProductID, p.ProductName, p.UnitPrice
FROM NorthwindEntities.Products AS p
Returns IEnumerable<Product>
SELECT VALUE p FROM NorthwindEntities.Products AS p
SELECT
http://msdn.microsoft.com/en-us/library/bb399554.aspx
21
Entity SQL
2. 43
Returns IEnumerable<string>
SELECT VALUE p.ProductName FROM NorthwindEntities.Products AS p
Entity SQL
2. 44
it
In a query builder method you refer to the current
ObjectQuery command by using an alias
By default, the string it is the alias that represents
the current command
var db = new NorthwindEntities(); // a DbContext
var oc = (db as IObjectContextAdapter).ObjectContext;
ObjectQuery<Product> productQuery =
oc.Products.Where("it.StandardCost > @cost",
new ObjectParameter("cost", 23));
22
Entity SQL
2. 45
An Entity SQL query is invalid if both the TOP modifier and the
SKIP sub-clause are present in the same expression
Entity SQL
2. 46
INTERSECT
Distinct values from both left and right sides
IN
Determines whether a value matches any value in a collection
EXISTS
Determines if a collection is empty
Comparison Semantics
http://msdn.microsoft.com/en-us/library/bb896323
23
Entity SQL
2. 47
Why?
A REF is a lightweight entity in which we dont need to spend
resources in creating and maintaining the full entity
state/values until it is really necessary
EntityClient
2. 48
24
EntityClient
2. 49
Querying Summary
2. 50
When To Use
LINQ to Entities
Use this most of the time
Materializes data into entities tracked by DbContext
25
Performance
2. 51
Transactions
2. 52
ACID
Atomic aka all or nothing
Groups multiple actions into a single, indivisible transaction
Consistent
Leave the system in a consistent state after the transaction, for
example, if we credit $100, we must also debit $100
26
Transactions
2. 53
Transactions
2. 54
Isolation Levels
ReadUncommitted (weakest isolation)
Allows dirty reads, non-repeatable reads, and phantom data
ReadCommitted
Allows non-repeatable reads and phantom data
RepeatableRead
Allows phantom data
Defaults
SQL Server & ADO.NET Classic default to ReadCommitted
TransactionScope defaults to Serializable
27
Transactions
2. 55
Snapshot Isolation
SQL Server 2005 introduced a new isolation level
Once snapshot isolation is enabled, updated row versions for
each transaction are maintained in tempdb
ALTER DATABASE MyDatabase
SET ALLOW_SNAPSHOT_ISOLATION ON
The term snapshot reflects the fact that all queries in the
transaction see the same version, or snapshot, of the database,
based on the state of the database at the moment in time when
the transaction begins
No locks are acquired on the underlying data rows or data pages
in a snapshot transaction, which permits other transactions to
execute without being blocked by a prior transaction
var options = new TransactionOptions {
IsolationLevel = System.Transactions.IsolationLevel.Snapshot };
Transactions
2. 56
TransactionScope
var options = new TransactionOptions {
IsolationLevel = IsolationLevel.ReadCommitted,
Timeout = TimeSpan.FromMinutes(2)
}; // auto-rollback if it doesnt complete in two minutes
using (var tsOuter = new TransactionScope(
TransactionScopeOption.Required, options)) {
// perform action A
OutputTransInfo(); // => {guid}:1
DoWork();
// perform action B
tsOuter.Complete();
}
private void DoWork() {
using(var tsInner = new TransactionScope(
TransactionScopeOption.RequiresNew)) {
OutputTransInfo(); // => {guid}:2
// perform action C
private void OutputTransInfo() {
// perform action D
Console.WriteLine(Transaction
tsInner.Complete();
.Current.TransactionInformation
}
.LocalIdentifier);
}
}
28
Transactions
2. 57
TransactionScopeOption
Required (default)
Uses the ambient transaction if one already exists, otherwise, it
creates a new transaction before entering the scope
Use Transaction.Current to get the ambient transaction
RequiresNew
A new transaction is always created for the scope
Suppress
The ambient transaction context is suppressed when creating
the scope and all operations within the scope are done without
an ambient transaction context
using (var tsPreventRollback = new TransactionScope(
TransactionScopeOption.Suppress)) {
// call method that could throw an exception
}
Transactions
2. 58
DependentTransaction class
A DependentTransaction is a clone of a Transaction
object created using the DependentClone method
Its sole purpose is to allow the application to come to rest and
guarantee that the transaction cannot commit while work is still
being performed on the transaction (for example, on a worker
thread)
29
Transactions
2. 59
SqlTransaction.Save Method
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqltransaction.save.aspx
30
3. 1
Module 3
Creating and Consuming
ASP.NET Web API Services
Developing Windows Azure
and Web Services
3. 2
Contents
Exam Topics: Design a Web API
Define HTTP resources with HTTP actions
Plan appropriate URI space, map URI space using routing
Choose appropriate HTTP method (get, put, post, delete) to meet requirements
Choose appropriate format (Web API formats) for responses to meet requirements
Plan when to make HTTP actions asynchronous
Exam Topics: Implement a Web API
Accept data in JSON format (in JavaScript, in an AJAX callback)
Use content negotiation to deliver different data formats to clients
Define actions and parameters to handle data binding
Use HttpMessageHandler to process client requests and server responses
Implement dependency injection, along with the dependency resolver, to create more
flexible applications
Implement action filters and exception filters to manage controller execution
Implement asynchronous and synchronous actions
Implement streaming actions
Exam Topics: Consume Web API web services
Consume Web API services by using HttpClient synchronously and asynchronously
Send and receive requests in different formats (JSON/HTML/etc.)
3. 3
3. 4
He named this style REST and suggested its use to build services
3. 5
GET
The cacheability of the GET verb contributes to the scalability
of the web
GETs are also considered safe in the sense that they should
not cause side effects i.e. they dont change resources
3. 6
SOAP
SOAP doesnt follow the architecture of the web at all
Rather than URIs, SOAP uses actions, which are a thin veneer
over method calls
SOAP services usually have only one URI and many different
actions
SOAP is really an interoperable cross-platform remote
procedure call (RPC) system
When using HTTP, SOAP only uses one HTTP verb, POST
POSTs cannot be cached, so its not as scalable as GET
But SOAP wasnt designed for the web and goes out of
its way to be protocol independent
3. 7
{
"ProductID" : "123",
...
3. 8
3. 9
HTTP Method
Relative URI
GET
/api/orders
GET
/api/orders/id
Retrieve by custom
GET
/api/orders?category=category
POST
/api/orders
Update entity
PUT
/api/orders/id
Remove entity
DELETE
/api/orders/id
3. 10
Uniform Interface
With REST there is no need to design the semantics of
the actions you want to perform because HTTP already
defines them for you
GET (or HEAD): retrieves a resource (or without the body)
POST: Microsoft recommends this means create a new resource
PUT: Microsoft recommends this means replace an existing
resource with a new version (idempotent1)
PATCH: update a resource with a subset of new values
DELETE: remove a resource (idempotent1)
CONNECT, TRANSFER, OPTIONS, TRACE
Idempotent means that the effect of calling it many times is the same as calling it once
3. 11
Resource Formats
REST has no restrictions on resource formats
A REST services resource types are known as media types
3. 12
3. 13
Or received
config.MaxReceivedMessageSize = 1024 * 1024 * 3; // 3 MB
3. 14
using System.Threading.Tasks;
using System.Net.Http;
3. 15
3. 16
To preserve references
[JsonObject(IsReference = true)]
public class Category
[DataContract(IsReference = true)]
public class Product
Loop Reference handling in Web API
http://code.msdn.microsoft.com/Loop-Reference-handling-in-caaffaf7
3. 17
3. 18
4. 1
Module 4
Extending and Securing
ASP.NET Web API Services
Developing Windows Azure
and Web Services
4. 2
Contents
Topic
Slide
OData
10
HTTP Methods
13
16
19
OData
4. 3
OData
4. 4
Overview
OData is a standard for building
HTTP services that follow standards
for querying the data model
It defines a query syntax using URIs
similar to SQL
4. 5
OData
http://.../Northwind.svc/Employees?
$select=FirstName,LastName,Age&
$filter=State eq 'CA' and Price gt 500&
$orderby=LastName,Age&$skip=40&$top=10
OData Core
http://www.odata.org/documentation/odata-v3-documentation/odata-core/
OData
4. 6
$format
Allows query to specify return data format
$format=json
$format=atom
$format=xml
$format=service-specific-format
4. 7
OData
$expand
The syntax of a $expand query option is a commaseparated list of Navigation Properties
Each Navigation Property can be followed by a forward slash
and another Navigation Property to enable identifying a multilevel relationship
/Categories?$expand=Products
/Categories?$expand=Products/Suppliers
/Products?$expand=Category,Suppliers
Expand System Query Option ($expand)
http://www.odata.org/documentation/uri-conventions#ExpandSystemQueryOption
OData
4. 8
$metadata
Returns an EDMX document that contains a complete
description of the feeds, types, properties,
relationships exposed by the service in EDM
It isnt queryable so if you want to find Types that have an
Address property you have to retrieve the whole EDMX and
search the xml yourself
http://services.odata.org/Northwind/Northwind.svc/$metadata
4. 9
OData
Returns
/Customers('ALFKI')/
ContactName
/Customers('ALFKI')/
ContactName/$value
/Customers('ALFKI')/Orders
/Orders(10643)/Customer
/Orders?$filter=not
endswith(ShipPostalCode,'100')
/Categories(1)/$links/Products
/Categories?$select=Name,
Products&$expand=Products
4. 10
How to Create
Project Add New Item WCF Data Service
Create a context class that represents your data
ADO.NET Entity Data Model is easiest
Or any class that has properties of type IQueryable<T> where
T is an entity (and optionally implements IUpdatable)
Use context class in DataService<TContext>
4. 11
json Support
Differences in OData V2 and V3
In V2 you could ask for application/json in Accept
In V3 you must ask for application/json;odata=verbose
WCF Data Services 5.0 will return a 415 in response to a request
for application/json if the service configuration allows a v3
response and if the client does not specify a
MaxDataServiceVersion header or specifies a
MaxDataServiceVersion header of 3.0
HTTP/1.1
Accept: application/json
MaxDataServiceVersion: 2.0
What happened to application/json in WCF DS 5.0?
http://blogs.msdn.com/b/odatateam/archive/2012/04/11/what-happened-to-application-json-in-wcf-ds-5-0.aspx
4. 12
4. 13
4. 14
HTTP Methods
4. 15
Warning!
By default the WCF Data Services client library passes all
properties using a MERGE, not just the ones that have changed
Use SaveChangesOptions.ReplaceOnUpdate to change to using a
PUT (which requires all properties to be sent)
WCF Data Services: Optimizing bandwidth usage and performance with updates
http://blogs.infosupport.com/wcf-data-services-optimizing-updates-in-the-client-library/
HTTP Methods
4. 16
HTTP Methods
4. 17
X-HTTP-Method
Some network intermediaries block HTTP verbs like
DELETE or PUT or MERGE
Verb tunnelling or POST tunnelling gets around this
4. 18
4. 19
Troubleshooting
To find out how a LINQ to OData query will translate
into an OData URL use RequestUri
var query = from p in DataServiceContext.Products
where p.Color == "Red"
select p;
string uri = ((DataServiceQuery)query).RequestUri.ToString();
http://localhost:1034/AW.svc/Products()?$filter=Color eq 'Red'
4. 20
How to: Set Headers in the Client Request (WCF Data Services)
http://msdn.microsoft.com/en-us/library/gg258441.aspx
10
4. 21
Overview
For the most common scenarioJavaScript in a Web
page accessing a Web API service on the same site
discussing security for ASP.NET Web API is redundant
Provided that you authenticate your users and authorize access
to the Web Forms/Views holding the JavaScript that consumes
your services, youve probably provided all the security your
services need
4. 22
Further Study
Using this book, you can gain a
solid understanding of the
security techniques relevant to
ASP.NET Web API
All the underlying concepts are
introduced from basic principles
and developed to the point where
you can use them confidently,
knowing what you are doing
11
5. 1
Module 5
Creating WCF Services
Developing Windows Azure
and Web Services
5. 2
Contents
Topic
Slide
Data Contracts
Service Contracts
17
Bindings
21
Clients
25
Faults
30
RESTful Services
34
Endpoints
39
Behaviors
43
Sessions
51
Summaries
5. 3
Data Contracts
Serializing Enumerations
[DataContract]
// optional: rename the type in WSDL
public class Car
[DataContract(Name = "CarCondition")]
{
public enum CarConditionEnum {
[DataMember]
[EnumMember]
public string Model;
New,
[DataMember]
// optional: rename the value
public CarConditionEnum Condition;
[EnumMember(Value = "Used")]
PreviouslyOwned,
[EnumMember]
Rental,
Broken,
If you use an enum value that is not marked as an EnumMember
Stolen
and it is serialized then WCF will throw an exception
}
var car = new Car {
Model = "Volvo",
Condition = CarConditionEnum.PreviouslyOwned
<Model>Volvo</Model>
<Condition>Used</Condition>
EnumMemberAttribute Class
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.enummemberattribute.aspx
Data Contracts
5. 4
ExceptionDetail Properties
HelpLink
InnerException (of type ExceptionDetail)
Message
StackTrace
Type
ExceptionDetail Class
http://msdn.microsoft.com/en-us/library/system.servicemodel.exceptiondetail(v=vs.110).aspx
5. 5
Data Contracts
[DataContract(IsReference=true)]
public class Address
5. 6
Data Contracts
[DataMember(EmitDefaultValue=false)]
public int Height = 0;
[DataMember(EmitDefaultValue=false)]
public int Weight = 10;
<Height>0</Height>
<Weight>10</Weight>
<Weight>10</Weight>
DataMemberAttribute.EmitDefaultValue
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.emitdefaultvalue.aspx
5. 7
Data Contracts
<Age> ...
<FirstName> ...
<LastName> ...
<FirstName> ...
<LastName> ...
<Age> ...
<Age> ...
<FirstName> ...
<LastName> ...
Data Contracts
5. 8
XML Namespaces
It is best practice to provide a namespace for your data
contracts rather than use the default (tempuri.org)
[DataContract(Namespace="http://www.firebrand.com/hr/2012/11")]
public class Employee
Data Contracts
5. 9
Versioning
Strict schema validity
This means in both directions (new-to-old and old-to-new) so
data and service contracts must be considered immutable
If a new version is required then a new data contract must be
created with a different name or namespace and the service
contract should add a new operation
DataMemberAttribute.IsRequired Property
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.isrequired.aspx
Data Contracts
5. 10
Round-Tripping (1/2)
If strict schema validity is NOT required, and you need
to be able to round-trip an instance of a data contract
with older clients, use IExtensibleDataObject
IExtensibleDataObject provides a data structure to store extra
data encountered during deserialization
In a roundtrip operation where data is received, processed, and
sent back, any extra data is returned to the sender intact
If you do not implement the interface, any extra data is ignored
and lost during a roundtrip operation
Useful to store data received from future versions of the
contract
Note: svcutil and VS-generated code implement this but you
need to implement it yourself if reusing data contracts
IExtensibleDataObject Interface
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iextensibledataobject.aspx
5. 11
Data Contracts
Round-Tripping (2/2)
Must mark versions e.g. Person and PersonV2 with same
Name and Namespace
Best practice to apply an order to new members
[DataContract(Name="Person", Namespace="http://.../")]
public class Person : IExtensibleDataObject
{
public ExtensionDataObject ExtensionData { get; set; }
[DataContract(Name="Person", Namespace="http://.../")]
public class PersonV2 : IExtensibleDataObject
{
public ExtensionDataObject ExtensionData { get; set; }
[DataMember(Order=2)]
public int Age { get; set; } // new member
5. 12
Data Contracts
ChannelFactories
The client should have
a reference to the
contracts so will know
exactly what
collection type to use
5. 13
Data Contracts
Warning!
If you use MessageContract then you can only have a single
input parameter on the operation of type Message or a class
like the one above that has MessageContract applied
5. 14
Data Contracts
<Keys>
<Key>123</Key>
<Key>456</Key>
<Key>789</Key>
</Keys>
<Keys>123</Keys>
<Keys>456</Keys>
<Keys>789</Keys>
5. 15
Data Contracts
using System.Net.Security;
http://msdn.microsoft.com/en-us/library/aa347791.aspx
5. 16
Data Contracts
Switching Serializers
WCF can use two different serialization technologies
DataContractSerializer (default) or XmlSerializer
Service Contracts
5. 17
Best Practice
Best practice is to separate contract from
implementation
Use an interface for the contract
[ServiceContract]
public interface ISampleService
Service Contracts
5. 18
Other parameters
Service: CallbackContract, Namespace, ConfigurationName
Operation: Action, IsOneWay, ReplyAction
OperationContractAttribute Class
http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontractattribute.aspx
ServiceContractAttribute Class
http://msdn.microsoft.com/en-us/library/system.servicemodel.servicecontractattribute.aspx
5. 19
Service Contracts
using System.ServiceModel.Channels;
[OperationContract]
void ProcessData(Person p);
[OperationContract]
void ProcessData(Message m);
To read a Message
m.GetReaderAtBodyContents() returns XmlDictionaryReader
m.GetBody() returns the message body as a typed object
if(!m.IsEmpty) { // check for null message in service or client;
// on client-side should also check IsFault
Person p = m.GetBody<Person>();
Using the Message Class
http://msdn.microsoft.com/en-us/library/ms734675(v=vs.110).aspx
Message Class
http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.message.aspx
Service Contracts
5. 20
IncomingWebRequestContext.Accept
http://msdn.microsoft.com/en-us/library/system.servicemodel.web.incomingwebrequestcontext.accept.aspx
10
5. 21
Bindings
Message Encodings
Text: ASCII, UTF16, UTF8 (default)
Binary: uses a WCF proprietary algorithm
Message Transmission Optimization Mechanism (MTOM)
MTOM is a mechanism for transmitting large binary attachments
with SOAP messages as raw bytes, allowing for smaller messages
while still interoperating with non-.NET systems
5. 22
Bindings
Duplex
Streaming
XxxBinding
Interop
Security (default)
Encoding
Sessions
Transactions
WS-*
Choosing a Binding
BasicHttp
Basic
Text, Mtom
WebHttp
REST 2
None, Transport
Text
WS
Text, Mtom
WSHttp
WS2007Http
WS
Text, Mtom
WSDualHttp
WS
None, Message
Text, Mtom
WSFederationHttp
WS-Fed
Text, Mtom
NetTcp
.NET
Binary
NetNamedPipes
.NET
None, Transport
Binary
NetMsmq
.NET
Binary
Others
System-Provided Bindings
http://msdn.microsoft.com/en-us/library/ms730879.aspx
11
5. 23
Bindings
Custom Bindings
Order must be
Protocol(s)
MessageEncoding
Transport
EXCEPT
<customBinding>
<binding name="MyBinding" ... >
<protocol1 ... />
<protocol2 ... />
<somethingMessageEncoding ... />
<somethingTransport ... />
</binding>
</customBinding>
System-Provided Bindings
http://msdn.microsoft.com/en-us/library/ms730879.aspx
Bindings
5. 24
msmqIntegrationTransport
Suitable for cross-machine communication between a WCF
application and existing Message Queuing applications
Queuing in WCF
http://msdn.microsoft.com/en-us/library/ms789048.aspx
12
Clients
5. 25
Clients
5. 26
13
Clients
5. 27
Clients
5. 28
14
Clients
5. 29
Supported
Service Invocation: Request/Response and One-way message
Bindings: all bindings supported by Svcutil.exe
Controlling Session
NOT supported
Duplex, transactions, Security: Certificate & Username/Pwd
Bindings: WSFederation, Https, WebHttpBinding
WCF Test Client (WcfTestClient.exe)
http://msdn.microsoft.com/en-us/library/bb552364.aspx
Faults
5. 30
15
5. 31
Faults
5. 32
Faults
False
FaultException<T>
16
Faults
5. 33
Fault Contracts
To exclude any stack trace information when an
exception occurs, throw a new instance of a custom
fault exception
[ServiceContract]
public interface IPersonService
{
[OperationContract]
[FaultContract(typeof(PersonFault))]
void AddPerson(Person p);
public class PersonService : IPersonService
{
public void AddPerson(Person p)
{
...
catch(IOException ex)
{
throw new FaultException<PersonFault>(personFault,
new FaultReason("I/O exception"));
RESTful Services
5. 34
Enabling REST
To create a REST-compliant endpoint
Use webHttpBinding and apply webHttp as an endpoint behavior
<endpoint address="kermit"
binding="webHttpBinding"
behaviorConfiguration="RESTful"
contract="Firebrand.ISampleService"
webHttp changes messages
<endpointBehaviors>
from SOAP to XML/JSON
<behavior name="RESTful">
<webHttp helpEnabled="true"
automaticFormatSelectionEnabled="true" />
17
5. 35
RESTful Services
Invoking REST
SOAP only uses POST; REST uses POST (by default)
Or you can apply [WebInvoke] to map an operation to another
HTTP verb such as PUT
WebInvoke/WebGet require
System.ServiceModel.Web
assembly and namespace
[OperationContract]
[WebInvoke(Method = "PUT")]
public string AddName(string newName);
PUT http://localhost:801/Sample/kermit/AddName
...
<newName>Alice</newName>
5. 36
RESTful Services
[OperationContract]
public int AddNumbers(Numbers n);
18
RESTful Services
5. 37
RESTful Services
5. 38
URI Templates
To customize the URL path use a UriTemplate
Path variables must use string
[OperationContract]
[WebGet(UriTemplate = "weather/{state}/{city}")]
string GetWeather(string state, string city);
[OperationContract]
[WebInvoke(UriTemplate = "order/{id}", Method = "DELETE")]
void DeleteOrder(string id);
19
Endpoints
5. 39
Requirement
Expose the service over TCP
Solution
Leave the existing endpoint as-is and define a new endpoint for
TCP
<service name="Firebrand.SampleService">
<endpoint address="net.tcp://.../"
binding="netTcpBinding"
contract="Firebrand.ISampleService" />
<endpoint address="http://.../"
binding="wsHttpBinding"
contract="Firebrand.ISampleService" />
Endpoints
5. 40
ClientVia
A service can use a logical address while using a
different address and binding for the transport
<client>
<endpoint address="http://www.aw.com/Calc"
binding="netTcpBinding"
behaviorConfiguration="viaBehavior"
contract="ServiceReference.ICalc" />
<endpointBehaviours>
<behaviour name="viaBehavior">
<clientVia viaUri="net.tcp://www.aw.com/ICalc" />
// or use code
client.Endpoint.Behaviors.Add(new ClientViaBehavior(
new Uri("net.tcp://www.aw.com/ICalc"));
ClientViaBehavior Class
http://msdn.microsoft.com/en-us/library/system.servicemodel.description.clientviabehavior.aspx
20
Endpoints
5. 41
Endpoints
5. 42
Standard Endpoints
Standard endpoints enable a developer to define an
endpoint that has default values or where one or more
endpoints properties does not change
For example, to enable cross-domain script access for all
instances of a web script endpoint
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="true" />
Standard Endpoints
http://msdn.microsoft.com/en-us/library/ee358762(v=vs.110).aspx
21
5. 43
Behaviors
<behavior name="Default">
<service behaviorConfiguration="Default">
<behavior> of <serviceBehaviors>
http://msdn.microsoft.com/en-us/library/aa967282.aspx
Behaviors
5. 44
22
Behaviors
5. 45
Multiple
Service instance is multi-threaded
Reentrant
Service instance is single-threaded and accepts reentrant calls
when you call another service
It is your responsibility to leave your object state consistent
before callouts and you must confirm that operation-local data
is valid after callouts
Behaviors
5. 46
PerCall
A new InstanceContext object is created prior to and recycled
subsequent to each call
Single
Only one InstanceContext object is used for all incoming calls
and is not recycled subsequent to the calls
If a service object is not passed to the ServiceHost constructor,
one (and only one) is created automatically on first call
Your service can only process one message at a time unless you
also set the ConcurrencyMode value to Multiple
InstanceContextMode Enumeration
http://msdn.microsoft.com/en-us/library/system.servicemodel.instancecontextmode.aspx
23
5. 47
Behaviors
Concurrency
Instancing
Single
PerSession
PerCall
Notes
Single
n/a
Reentrant
n/a
Multiple
n/a
If Instancing is PerCall, Concurrency is ignored because only one thread will ever be created.
Scenario
Solution
ConcurrencyMode.Reentrant on
ServiceBehavior
(not CallbackBehavior)
Behaviors
5. 48
24
5. 49
Behaviors
Publishing Metadata
HTTP(S) GET metadata endpoints are easily enabled
and use the base address
<serviceBehaviors>
<behavior> <!-- and httpsGetEnabled -->
<serviceMetadata httpGetEnabled="true" />
<endpoint address="mex"
binding="mexTcpBinding"
contract="IMetadataExchange" />
mexHttpsBinding,
mexNamedPipeBinding,
mexTcpBinding
Publishing Metadata
http://msdn.microsoft.com/en-us/library/aa751951.aspx
Behaviors
5. 50
25
Sessions
5. 51
What Is a Session?
Correlates a group of messages into a conversation
Do NOT confuse with Session state in ASP.NET
Sessions
5. 52
26
5. 53
Summaries
Data Contracts
Member Opt-In
[DataContract(...)]
public class Person
{
[DataMember(...)]
public int PersonID { get; set; }
// Salary not serialized
public decimal Salary { get; set; }
5. 54
Summaries
On Class (Implementation)
[ServiceBehavior(...)]
public class ClassName : IInterfaceName
{
[OperationBehavior(...)]
public void Method(...)
{
...
}
See the next slide for the details of the
attributes for services and operations
On Interface/Class (Contract)
[FaultContract(Type, ...)]
Action, Name, Namespace, ProtectionLevel
[TransactionFlow(TransactionFlowOption)]
Allowed, Mandatory, NotAllowed
[WebGet(UriTemplate = "", ...)]
RequestFormat, ResponseFormat: Json, Xml
27
5. 55
Summaries
On Class (Implementation)
[ServiceContract(
CallbackContract (null)
ConfigurationName
("qualified.classname")
HasProtectionLevel,
ProtectionLevel (None,
Sign, EncryptAndSign)
Name, Namespace
SessionMode (Allowed,
Required, NotAllowed)
[OperationContract(
Action, ReplyAction
AsyncPattern (false)
ProtectionLevel (None)
IsInitiating (true)
IsTerminating (false)
IsOneWay (false)
Name
[OperationBehavior(
AutoDisposeParameters (true)
Impersonation (NotAllowed, Allowed, Required)
ReleaseInstanceMode (None*, BeforeCall, AfterCall,
BeforeAndAfterCall)
TransactionAutoComplete (true)
TransactionScopeRequired (false)
* Uses InstanceContextMode setting
Summaries
5. 56
System.Runtime.Serialization Assembly
Namespace: System.Runtime.Serialization
[DataContract]
[DataMember]
[IgnoreDataMember]
[EnumMember]
[KnownType]
ExtensionDataObject
IExtensibleDataObject
DataContractSerializer
Namespace: System.Runtime.Serialization.Json
DataContractJsonSerializer
28
Summaries
5. 57
Summaries
5. 58
29
Summaries
5. 59
30
6. 1
Module 6
Hosting Services
Developing Windows Azure
and Web Services
6. 2
Hosting Services
Contents
Topic
Slide
WCF Hosting
WCF Hosting in
Windows Apps
ASP.NET
Compatibility
Mode
Syndication (RSS)
11
15
6. 3
WCF Hosting
Choosing a Host
Host/Transport
HTTP
Others
IIS 6
IIS 7+ only
Windows Process Activation Service (WAS) only
WCF Hosting
6. 4
6. 5
WCF Hosting
6. 6
using System.ServiceModel;
using System.ServiceModel.Activation;
6. 7
<serviceActivations>
http://msdn.microsoft.com/en-us/library/ee816902.aspx
6. 8
UI Thread Problems
When using a Windows application to host a service you
must ensure that the UI thread does not block the
service
[ServiceBehavior(UseSynchronizationContext = false)]
6. 9
What Is It?
In compatibility mode, WCF services use the HTTP
pipeline through an IHttpHandler implementation so
WCF behaves identically to ASMX with respect to the
following ASP.NET features (therefore must use HTTP)
HttpContext: can access Current and its associated state
File-based authorization: can be secure by attaching file system
access control lists (ACLs) to the services .svc file
Configurable URL authorization: ASP.NETs URL authorization
rules are enforced for WCF requests
HttpModuleCollection extensibility: any HTTP module
configured in the HTTP pipeline is able to operate on WCF
requests both before and after service invocation
ASP.NET Impersonation: WCF services run using the current
identity of the ASP.NET impersonated thread
6. 10
How to Use It
Enable compatibility mode in .config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
Syndication Support
6. 11
System.ServiceModel.Syndication namespace
Publish and consume RSS and Atom syndication feeds
Reference System.ServiceModel.Web.dll for .NET 3.5
Classes
Atom10FeedFormatter: (De)serializes a feed in Atom 1.0 format
Rss20FeedFormatter: (De)serializes a feed in RSS 2.0 format
SyndicationFeed: a top-level feed object
Syndication Support
6. 12
Feed contract
public interface INewsFeed {
[OperationContract]
[WebGet(UriTemplate = "GetNews?format={format}")]
SyndicationFeedFormatter GetNews(string format);
http://localhost:8000/NewsFeedService/GetNews?format=rss
Feed implementation
public SyndicationFeedFormatter GetNews(string format)
{
var feed = new SyndicationFeed(...);
feed.Authors.Add(new SyndicationPerson("[email protected]"));
feed.Categories.Add(new SyndicationCategory("Tech News"));
Syndication Support
6. 13
Syndication Support
6. 14
Consume Example
Load the feed
var atomReader = XmlReader.Create(
"http://.../NewsFeedService/GetNews?format=atom");
var feed = SyndicationFeed.Load(atomReader);
6. 15
6. 16
7. 1
Module 7
Windows Azure Service Bus
Developing Windows Azure
and Web Services
7. 2
Contents
Exam Topics: Create and configure a WCF service on Windows Azure
Create and configure bindings for WCF services (Azure SDK extensions to WCF)
Relay bindings to Azure using service bus endpoints
Integrate with the Azure service bus relay
Exam Topics: Implement messaging patterns
Implement Windows Azure Service Bus and Windows Azure Queues
7. 3
8. 1
Module 8
Deploying Services
Developing Windows Azure
and Web Services
8. 2
Deploying Services
Contents (1 of 2)
Topic
Slide
Deployment Tools
Windows Azure
NuGet
Deploying Services
8. 3
Contents (2 of 2)
Exam Topics: Manage packages by using NuGet
Create and configure a NuGet package
Install and update an existing NuGet package
Connect to a local repository cache for NuGet, set up your own package repository
Exam Topics: Create, configure, and publish a web package
Create an IIS InstallPackage
Configure the build process to output a web package
Apply pre- and post- condition actions to ensure that transformations are correctly applied
Include appropriate assets (web content, certificates)
Exam Topics: Share assemblies between multiple applications and servers
Prepare the environment for use of assemblies across multiple servers (interning)
Sign assemblies by using a strong name
Deploy assemblies to the global assembly cache
Implement assembly versioning
Create an assembly manifest
Configure assembly binding redirects (for example, from MVC2 to MVC3)
8. 4
Assembly Libraries
If you want to use an assembly in multiple web
applications and services, deploy to the GAC
If you deploy a private assembly and then release a
new version, you might need to force a bindingRedirect
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="myAssembly"
publicKeyToken="32ab4ba45e0a69a1"
culture="neutral" />
<bindingRedirect oldVersion="1.0.0.0"
newVersion="2.0.0.0"/>
Deployment Tools
8. 5
Web Deploy
For any question about deployment tools, the answer is
almost always use Web Deploy because
It works securely
It is powerful and flexible by changing the web publish pipeline
You can install SSL certificates using a custom target
Windows Azure
8. 6
Windows Azure
8. 7
NuGet
8. 8
What Is It?
NuGet is a Visual Studio extension that makes it easy to
install and update third-party libraries and tools
Choose Library Package Manager from the Tools menu
NuGet
8. 9
A local feed
NuGet
8. 10
Just add packages into the Packages folder and theyll show up
9. 1
Module 9
Windows Azure Storage
Developing Windows Azure
and Web Services
9. 2
Contents
Exam Topic: Implement data storage in Windows Azure
Access data storage in Windows Azure
Choose data storage mechanism in Windows Azure (blobs, tables, queues, SQL Database)
Distribute data by using the Content delivery network (CDN)
Handle exceptions by using retries (SQL Database)
Manage Windows Azure Caching
9. 3
Your Choices
Windows Azure storage (100TB per account)
Table: each structured entry (up to 1MB), table (unlimited)
Blob: block (up to 200GB) or page (up to 1TB) e.g. videos
Queue: message exchange (up to 64KB)
Drive: permanent files in separate VM defined by a VHD
Local: temporary files in a role VM (could be lost at any time)
9. 4
RowKey
The second part of the primary key is the row key
A unique identifier for an entity within a given partition
Together the PartitionKey and RowKey uniquely identify every
entity within a table
The row key is a string value that may be up to 1 KB in size
Designing a Scalable Partitioning Strategy for Windows Azure Table Storage
http://msdn.microsoft.com/en-us/library/windowsazure/hh508997.aspx
9. 5
10. 1
Module 10
Monitoring and Diagnostics
Developing Windows Azure
and Web Services
10. 2
Contents
Topic
Slide
Troubleshooting
Tracing
Performance Counters
Stopwatch
12
Debugging
13
Error Handlers
14
Throttling
15
10. 3
Tracing
WCF Milestones
System.ServiceModel trace source
General WCF trace source records processing milestones across
the WCF communication stack, from entering/leaving transport
to entering/leaving user code
<system.diagnostics>
<sources>
<source name="System.ServiceModel">
<listeners>
<add name="traces"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="c:\logs\traces.svclog" />
To correlate
traces across
tiers
<source name="System.ServiceModel"
propagateActivity="true"
switchValue="Warning, ActivityTracing">
Configuring Tracing
http://msdn.microsoft.com/en-us/library/ms733025.aspx
Tracing
10. 4
Logging Messages
To configure a service to log messages from a client
<system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add name="messages"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="c:\logs\messages.svclog" />
<system.serviceModel>
<diagnostics>
<messageLogging logEntireMessage="true"
logMessagesAtServiceLevel="true"
logMessagesAtTransportLevel="false"
Tracing
10. 5
<messageLogging>
http://msdn.microsoft.com/en-us/library/ms731308.aspx
Tracing
10. 6
App.config or Web.config
<system.serviceModel>
<diagnostics>
<messageLogging logKnownPii="true" ...
Performance Counters
10. 7
Options
All: ServiceModelService, ServiceModelEndpoint and
ServiceModelOperation
ServiceOnly: ServiceModelService
None
Performance Counters
10. 8
10. 9
Performance Counters
10. 10
Stopwatch
s.Stop();
TimeSpan ts = s.Elapsed;
long ms = s.ElapsedMilliseconds;
Stop method
Stop and retain cumulative elapsed time
Reset method
Stop and reset the elapsed time to zero
Error Handlers
10. 11
Processing Messages
The body of a Message instance can only be accessed or
written once
If you have an operation that accepts the Message type
and you need to process it multiple times you must
Call the CreateBufferedCopy method to load into memory
Call the CreateMessage method of the MessageBuffer
MessageBuffer Class
http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.messagebuffer.aspx
Throttling
10. 12
MaxReceivedMessageSize
Gets and sets the maximum allowable message size,
measured in bytes, that can be received
Default is 65536 bytes (64 KB)
For example, you might want to increase the maximum size of a
message that a service can receive to 256 KB
<wsHttpBinding>
<binding maxReceivedMessageSize="262144"
var binding = new WSHttpBinding();
binding.MaxReceivedMessageSize = 256 * 1024;
TransportBindingElement.MaxReceivedMessageSize - http://msdn.microsoft.com/en-us/library/
system.servicemodel.channels.transportbindingelement.maxreceivedmessagesize.aspx
12. 1
Module 12
Scaling Services
Developing Windows Azure
and Web Services
12. 2
Scaling Services
Contents
Topic
Slide
System.Runtime.Caching
Real-Time Synchronization
System.Runtime.Caching
12. 3
CacheItemPolicy
Represents a set of eviction and expiration details
Some methods in the MemoryCache (inherits from ObjectCache)
classes accept a CacheItemPolicy instance
ObjectCache cache = MemoryCache.Default;
string fileContents = cache["filecontents"].ToString();
string root = HttpContext.Current.Server.MapPath("~");
if (fileContents == null)
{
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(60.0);
policy.ChangeMonitors.Add(new HostFileChangeMonitor(
new List<string> { root + "\\cache.txt" }));
fileContents = File.ReadAllText(root + "\\cache.txt");
cache.Set("filecontents", fileContents, policy);
}
CacheItemPolicy Class
http://msdn.microsoft.com/en-us/library/system.runtime.caching.cacheitempolicy.aspx
Real-Time Synchronization
12. 4
Query Notifications
Built upon the Service Broker infrastructure
SQL Server 2005 or later
System.Data.SqlClient.SqlDependency
High-level implementation; least developer effort
Designed for small number of middle-tier objects; you should
limit the number of listeners
System.Data.Sql.SqlNotificationRequest
Low-level implementation; requires you to implement the entire
listening infrastructure yourself
Can receive messages even if not running at time of notification
12. 5
Real-Time Synchronization
Start listening
using System.Data.SqlClient;
SqlDependency.Start(connectionString);
Real-Time Synchronization
12. 6
12. 7
What Is It?
When youre designing a real world cloud app, one of
the things you have to think about is how to handle
temporary service interruptions
You can frequently get little glitches that are typically selfhealing, and if you arent prepared to handle them intelligently,
theyll result in a bad experience for your customers
12. 8
Entity Framework 6 builds this kind of retry logic right into the
framework
public class EFConfiguration : DbConfiguration {
public EFConfiguration() {
AddExecutionStrategy(() => new SqlAzureExecutionStrategy());
}
Transient Fault Handling Application Block
http://msdn.microsoft.com/en-us/library/dn440719(v=pandp.60).aspx
A. 1
Appendix A
Designing and Extending WCF
Services
Developing Windows Azure
and Web Services
A. 2
Contents
Topic
Slide
MEP Contracts
Asynchronous Operations
Extending WCF
Transactions
Discovery
13
Routing
17
MEP Contracts
A. 3
One-Way Considerations
With a one-way operation the receiver does not send a
reply message there is no response message to carry
fault information back to the client
You may be able to detect error conditions by using features of
the underlying binding, such as reliable sessions
Asynchronous Operations
A. 4
Asynchronous Operations
A. 5
Asynchronous Operations
A. 6
A. 7
Extending WCF
Dispatch = server-side
Client = client-side
DispatchOperation
ParameterInspectors,
Formatter
DispatchRuntime
MessageInspectors
ClientOperation
ParameterInspectors,
Formatter
ClientRuntime
MessageInspectors
Transactions
A. 8
Enabling Transactions
For an operation to automatically participate in an
existing transaction or to create a new transaction if
one does not exist (default is false)
[OperationBehavior(TransactionScopeRequired=true)]
public bool ValidateCredit(string cardNumber)
Transactions
A. 9
Transactions
A. 10
Transactions
A. 11
Transactions
A. 12
TransactionProtocol Class
http://msdn.microsoft.com/en-us/library/system.servicemodel.transactionprotocol.aspx
Discovery
A. 13
Announcements
AnnouncementService
Used by clients to listen for and act on incoming messages on a
standard announcement endpoint (AnnouncementEndpoint)
Provides event notification when Hello or Bye announcement
messages arrive
AnnouncementClient
Used by services to send discovery announcement messages
An announcement message contains information about the
service such as its fully-qualified contract name, any scopes
that the service is operating in as well as any custom metadata
the service wants to send
You do not need an AnnouncementClient if you want to service
to make announcements automatically when the host opens and
closes
Discovery
A. 14
or with configuration
<services>
<service name="MyService">
<endpoint kind="udpDiscoveryEndpoint" />
<behaviors>
<serviceBehaviors>
<behavior>
<serviceDiscovery>
<announcementEndpoints>
<endpoint kind="udpAnnouncementEndpoint" />
Discovery
A. 15
Discovery
A. 16
FindResponse
FindResponse
Represents the response from a find request
FindResponse.Endpoints Property
Gets a collection of EndpointDiscoveryMetadata for the
discoverable services that matched the find request
EndpointDiscoveryMetadata
Address: Gets or sets the endpoint address
ContractTypeNames: Gets a collection of contract type names
implemented by the service
ListenUris: Gets the listen URIs for the service
Extensions, Scopes, and Version: other properties
EndpointDiscoveryMetadata Class
http://msdn.microsoft.com/en-us/library/system.servicemodel.discovery.endpointdiscoverymetadata
A. 17
Routing
Interface
Request-Response
IRequestReplyRouter
One-Way
ISimplexDatagramRouter
ISimplexSessionRouter
Duplex
IDuplexSessionRouter
Routing
A. 18
http://seroter.wordpress.com/2011/01/13/wcf-routing-service-deep-dive-part-iiusing-filters/
Message Filters
http://msdn.microsoft.com/en-us/library/ee517424.aspx
B. 1
Appendix B
Implementing Security in
WCF Services
Developing Windows Azure
and Web Services
B. 2
WCF Security
Contents
Topic
Slide
Certificates
Comparison
Authentication
Authorization
11
Impersonation
14
Auditing
16
Protection
17
20
Certificates
B. 3
What is X.509?
In cryptography, X.509 is a standard for a public key
infrastructure (PKI)
X.509 specifies, amongst other things:
Formats for public key certificates
Certificate revocation lists
Certification path validation algorithm
Certificates
B. 4
Certificates
B. 5
Sample
Certificate:
Data:
Version: 1 (0x0)
Serial Number: 7829 (0x1e95)
Signature Algorithm: md5WithRSAEncryption
Issuer: C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc,
OU=Certification Services Division,
CN=Thawte Server CA/[email protected]
Validity
Not Before: Jul 9 16:04:02 1998 GMT
Not After : Jul 9 16:04:02 1999 GMT
Subject: C=US, ST=Maryland, L=Pasadena, O=Brent Baccala,
OU=FreeSoft, CN=www.freesoft.org/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public Key: (1024 bit)
Modulus (1024 bit):
00:b4:31:98:0a:c4:bc:62:c1:88:aa:dc:b0:c8:bb:
33:35:19:d5:0c:64:b9:3d:41:b2:96:fc:f3:31:e1:
...
e8:35:1c:9e:27:52:7e:41:8f
Exponent: 65537 (0x10001)
Signature Algorithm: md5WithRSAEncryption
93:5f:8f:5f:c5:af:bf:0a:ab:a5:6d:fb:24:5f:b6:59:5d:9d:
...
Certificates
B. 6
X509CertificateRecipientServiceCredential Methods
http://msdn.microsoft.com/en-us/library/ms577349.aspx
B. 7
Comparison
Security Modes
Security Mode
Encryption
Authentication
None
None
None
Transport
SSL
(point-to-point)
TransportWith
MessageCredential
SSL
(point-to-point)
Message
Only if ProtectionLevel is
set in service, operation,
fault, or message
contracts (end-to-end)
Transport
CredentialOnly
None
<basicHttpBinding>
<binding name="kermit">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
*Kerberos
B. 8
Comparison
Security Types
Transport (e.g. HTTPS) Message (SOAP)
Speed
Slower
Extensible
No
Yes
Authentication
Choices
Windows, UserName,
Certificate, IssuedToken, Custom
Encryption
Point-to-point
End-to-end
Warning!
You cannot use Message security
with a REST endpoint because there
wont be a SOAP message to use
Authentication
B. 9
Identity types
Domain Name System (DNS), Certificate or Certificate
Reference, RSA, User principal name, Service principal name
A DNS check enables you to use certificates reissued with a new
RSA key but the same DNS or subject name, so the identity
check is still valid
Service Identity and Authentication
http://msdn.microsoft.com/en-us/library/ms733130.aspx
Authentication
B. 10
http://stackoverflow.com/questions/1683724/what-are-the-impacts-of-setting-establishsecuritycontextfalse-if-i-use-https
Authorization
B. 11
SecurityAction
Demand: throw exception if security context does NOT match
Deny: throw exception if security context DOES match
PrincipalPermissionAttribute Class
http://msdn.microsoft.com/en-us/library/system.security.permissions.principalpermissionattribute.aspx
Authorization
B. 12
Service Authorization
principalPermissionMode
None, UseWindowsGroups, UseAspNetRoles, Custom
Authorization
B. 13
Impersonation
B. 14
Impersonation
B. 15
Level
To access out-of-process resources on behalf of a caller
using System.Security.Principal;
ServiceSecurityContext.Current.WindowsIdentity
.ImpersonationLevel = TokenImpersonationLevel.Delegation;
TokenImpersonationLevel
None, Anonymous: no impersonation
Identification: identify but not impersonate
Impersonation: impersonates the clients security context on its
local system, but not on remote systems
Delegation: impersonates the clients security context on
remote systems
TokenImpersonationLevel Enumeration
http://msdn.microsoft.com/en-us/library/system.security.principal.tokenimpersonationlevel.aspx
Auditing
B. 16
Audit levels
None (default), Success, Failure, SuccessAndFailure
Protection
B. 17
Securing Streams
Scenario
Need to stream sensitive BLOBs over a public network
Protection
B. 18
Other options
Basic256 (default), Basic128, Basic128Rsa15, Basic128Sha256,
TripleDesSha256Rsa15, and so on
SecurityAlgorithmSuite Class
http://msdn.microsoft.com/en-us/library/system.servicemodel.security.securityalgorithmsuite(v=vs.110).aspx
B. 19
Protection
B. 20
10
C. 1
Appendix C
Classic XML and ADO.NET
Developing Windows Azure
and Web Services
C. 2
Contents
Topic
Slide
System.Xml
11
XPath
15
Connections
17
Protecting Data
28
Factories
34
Commands
36
DataReaders
40
DataAdapters
44
DataSets
48
SQL Server
57
C. 3
C. 4
System.Xml
Methods
<book>
<title>C# Rocks!</title>
</book>
<book>
<title>C# Rocks!</title>
</book>
System.Xml
C. 5
System.Xml
C. 6
XML Namespaces
Whats the difference between Name and LocalName?
XML can have namespaces with prefixes to differentiate
elements and attributes defined by different schemas
Elements without prefixes belong to the default namespace
<item xmlns:media="http://schemas.microsoft.com/video/2006/04">
<title>Article 1</title>
<description><![CDATA[How to use StackOverflow.com]]></description>
<link>http://youtube.com/?v=y6_-cLWwEU0</link>
<media:player url="http://youtube.com/?v=y6_-cLWwEU0"
/>
<media:thumbnail url="http://img.youtube.com/vi/y6_-cLWwEU0/default.jpg"
width="120" height="90" />
XmlNode.LocalName Property
http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.localname(v=vs.110).aspx
System.Xml
C. 7
System.Xml
C. 8
Writing Elements
Write methods efficiently generate well-formed XML
WriteStartDocument, WriteEndDocument
WriteElementString, WriteStartElement, WriteEndElement,
WriteFullEndElement
WriteAttributeString, WriteComment, and so on
myWriter.WriteStartElement("FirstNames");
myWriter.WriteAttributeString("color", "Red");
myWriter.WriteElementString("Name", "Libby");
myWriter.WriteEndElement();
myWriter.WriteStartElement("LastNames");
myWriter.WriteEndElement();
<FirstNames color="Red">
<Name>Libby</Name>
</FirstNames>
<LastNames />
System.Xml
C. 9
XmlDocument
<?xml version="1.0"?>
<books>
<book>
<author>Carson</author>
<price format="dollar">31.95</price>
<pubdate>05/01/2001</pubdate>
</book>
<pubinfo>
<publisher>MSPress</publisher>
<state>WA</state>
</pubinfo>
</books>
System.Xml
C. 10
XSLT Transformations
The Transform method accepts three input types for
the source document: an object that implements the
IXPathNavigable interface, an XmlReader object that
reads the source document, or a string URI
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
var doc = new XPathDocument("books.xml");
var writer = XmlWriter.Create("books.html");
var transform = new XslCompiledTransform();
var settings = new XsltSettings();
settings.EnableScript = true; // if you use scripting in the XSLT
transform.Load("transform.xsl", settings, null);
transform.Transform(doc, writer);
XSLT Transformations
http://msdn.microsoft.com/en-us/library/14689742.aspx
C. 11
DataSet.WriteXml
WriteXml method can be used to write the data to an
XML file or a stream
aDataSet.WriteXml(HttpContext.Current.Server.MapPath(
@"App_Data\employee.xml"));
<?xml version="1.0" standalone="yes" ?>
<NewDataSet>
<Employee>
<Eid>123456789A</Eid>
<FirstName>Nancy</FirstName>
...
</Employee>
<Employee>
...
C. 12
XmlWriteMode enumeration
IgnoreSchema (default): outputs data only
WriteSchema: outputs an inline schema as well as data
C. 13
Using Diffgrams
Diffgrams maintain row state and versions
<diffgr:diffgram
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<AWDataSet> ... </AWDataSet>
<diffgr:before> ... </diffgr:before>
<diffgr:errors> ... </diffgr:errors>
</diffgr:diffgram>
C. 14
XmlReadMode enumeration
Auto (default)
DiffGram: if XML is in DiffGram format
Fragment: allows multiple root elements
ReadSchema: if XML contains schema, it is processed
IgnoreSchema: if XML contains schema, it is ignored
InferSchema: if XML contains schema, it is ignored; schema
inferred from data; all column data types are strings
InferTypedSchema: column data types are inferred
C. 15
XPath
Overview
Use / to define a path to
elements and attributes
Name of all author elements
bookstore/author/name
Use * as a wildcard
Name of all authors and books
bookstore/*/name
<bookstore>
<author>
<name>Victor Hugo</name>
<nationality>French</nationality>
</author>
<author period="classical">
<name>Sophocles</name>
<nationality>Greek</nationality>
</author>
<author>
<name>Leo Tolstoy</name>
<nationality>Russian</nationality>
</author>
<author>
<name>Alexander Pushkin</name>
<nationality>Russian</nationality>
</author>
<book period="classical">
<name>Plato's Works</name>
<price>24.95</price>
</book>
</bookstore>
bookstore/author/*
XPath
C. 16
Connections
C. 17
RAISERROR
RAISERROR 'Error message', 11, 1234567
RAISERROR
http://msdn.microsoft.com/en-us/library/ms178592.aspx
Connections
C. 18
C. 19
Connections
C. 20
Connections
Security
Windows Authentication
Secure as no password is transmitted across the network
Not easy to configure across domains or firewalls
Use of service accounts is highly recommended to aid pooling
"...;Integrated Security=SSPI;"
"...;Trusted_Connection=true;"
10
Connections
C. 21
Connections
C. 22
11
C. 23
Connections
Connection pools
Reusing existing connections to reduce overhead and increase
performance
Pooled connections must have identical connection string
C. 24
Connections
Default Description
Connection 0
Lifetime or
Load
Balance
Timeout
Connection True
Reset
Enlist
True
Max/Min
Pool Size
100/0
Pooling
True
12
C. 25
Connections
C. 26
Connections
using System.Configuration;
Two providers
RsaProtectedConfigurationProvider
DataProtectionConfigurationProvider
Warning!
To use the same encrypted configuration file on multiple
servers, such as a Web farm, only the
RsaProtectedConfigurationProvider enables you to export the
keys and import them on another server
13
Connections
C. 27
ConnectionStringBuilder
To dynamically but safely build a connection string
var sb = new SqlConnectionStringBuilder();
sb["Data Source"] = @".\SQLEXPRESS"; // or sb.DataSource
sb["database"] = "AdventureWorks";
// or sb["Initial Catalog"]
sb["Integrated Security"] = true;
// this connection string will use the modern keywords
string connectionString = sb.ConnectionString;
Protecting Data
C. 28
Three Techniques
Encrypt
Two-way operation (i.e. can be decrypted)
Best choice for data such as credit card numbers
14
Protecting Data
C. 29
Asymmetric Keys
Public-private key pair
Mathematically linked but cannot derive one from the other
Protecting Data
C. 30
Symmetric Encryption
Good
Fast, large amounts of data
Bad
Need a way to share the key
15
Protecting Data
C. 31
Asymmetric Encryption
Good
More secure than symmetric encryption
Bad
Slow, small amounts of data
Algorithm
RSACryptoServiceProvider: encrypt (and also sign!)
Name comes from initials of three men who invented it
How it works
Sender uses receiver's public key to encrypt data
Receiver uses their private key to decrypt
Often combined with symmetric for best of both worlds, for
example, HTTPS/SSL
Protecting Data
C. 32
16
C. 33
Protecting Data
Example
To store user passwords in the database in a way that they
cannot be extracted, the passwords need to be hashed using a
one-way hashing algorithm such as SHA1
To do so, use the RNGCryptoServiceProvider to create a random
salt, append the salt to the password, hash it using SHA1
CryptoServiceProvider class, and store the resulting string in the
database along with the salt
The benefit provided by using a salted password is making a
lookup table assisted dictionary attack against the stored values
impractical, provided the salt is large enough
C. 34
Factories
DbProviderFactories
using System.Data.Common;
GetFactoryClasses method
Returns a DataTable loaded from Machine.config
0:Name, 1:Description, 2:InvariantName, 3:AssemblyQualifiedName
17
Commands
C. 35
DbCommand Members
Methods
ExecuteNonQuery: returns Int32
ExecuteReader: returns DbDataReader-derived object
ExecuteScalar: returns Object
Prepare, Cancel
Properties
CommandType: TableDirect, StoredProcedure, Text (default)
CommandText: name of table, stored procedure, or SQL
CommandTimeout: default 30 seconds
Connection, Transaction: objects associated with this command
Parameters: collection of DbParameters
Commands
C. 36
SqlCommand.ExecuteXmlReader
SQL Server 2000 and later supports FOR XML
AUTO means use attributes for column names and values
cmd.CommandText = "SELECT CustomerID, CompanyName, " +
"Country FROM Customers FOR XML AUTO";
<Customers CustomerID="ALFKI"
CompanyName="Alfreds Futterkiste" Country="Germany" />
XmlReader xr = cmd.ExecuteXmlReader();
while (xr.Read())
{
Console.WriteLine(xr.GetAttribute("CompanyName"));
}
18
C. 37
Commands
DbParameter
Properties
ParameterName: string
Value: object
DbType: DbType enumeration
Binary, Byte, Boolean, Currency, and so on
Size: in bytes
C. 38
Commands
19
DataReaders
C. 39
ExecuteReader
CommandBehavior values
CloseConnection: close related connection when close reader
Default: equivalent to no parameter
SchemaOnly: returns column information (call GetSchemaTable
method of reader to return a DataTable); SqlCommand prefixes
call with SET FMTONLY ON
KeyInfo: returns column and key information
SequentialAccess: instead of loading entire row into a buffer,
loads each column sequentially as a stream; good for BLOBs
SingleResult: optimizes for a single result set
SingleRow: optimizes for a single row; good for commands that
pass a value for the primary key
DataReaders
C. 40
IDataRecord interface
Pass ordinal position, i, of column
GetName(i): returns name of column
GetBoolean(i), GetInt32(i), GetString(i), and so on: returns
column as strongly-typed values
GetValue(i): returns column value as Object
GetData(i): returns a IDataReader for column value
IsDBNull(i): returns True if value is null
Others
FieldCount property
Item(), [int], [string]: indexers return column value as Object
GetOrdinal("column"): returns ordinal position of column
GetValues(object[]): returns number of items
GetDataTypeName: returns string, GetFieldType: returns Type
20
DataReaders
C. 41
DbDataReader members
HasRows
GetSchemaTable(): returns DataTable with schema info
DataReaders
C. 42
21
DataAdapters
C. 43
DataAdapters
C. 44
SqlCommandBuilder
Used to generate INSERT, UPDATE, and DELETE
statements based on a SELECT command
Must be associated with a data adapter
var cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Products";
var da = new SqlDataAdapter(cmd);
var bldr = new SqlCommandBuilder(da);
bldr.ConflictOption = ConflictOption.OverwriteChanges;
da.InsertCommand = bldr.GetInsertCommand();
da.UpdateCommand = bldr.GetUpdateCommand();
da.DeleteCommand = bldr.GetDeleteCommand();
22
DataAdapters
C. 45
DataAdapters
C. 46
TableAdapterManager
Enables hierarchical updates (ADO.NET 3.5+)
Created at design-time with a typed DataSet so not in BCL
Uses the foreign-key constraints in data tables to determine the
correct order to send the Inserts, Updates, and Deletes from a
dataset to the database
Members
BackupDataSetBeforeUpdate: use for AutoIncrements that must
not miss values
UpdateOrder: InsertUpdateDelete (default)
UpdateAll(): implicit transaction
23
DataSets
C. 47
RemotingFormat
Xml (default) or Binary (usually smaller, but 20kb overhead)
SchemaSerializationMode
IncludeSchema (default) or ExcludeSchema
DataSets
C. 48
DataColumn.Expression
When you create an expression, use the ColumnName
property to refer to columns
col.Expression = "UnitPrice * Quantity";
24
DataSets
C. 49
DataRow.DataRowState
Detached
Newly created row not yet added to Rows collection
Added
Newly created row now member of Rows collection
Unchanged
Row that has not been modified; only has current version
Modified
Row that has been modified; has current and original versions
Deleted
Row that has been marked for deletion; only has original version
DataSets
C. 50
DataRowVersion
DataRows can have up to four versions
Current
Original
Proposed: only exists until EndEdit is called on an edited row
Default: only one copy of this version exists for each table
25
DataSets
C. 51
Modify a row
SelectedRow.BeginEdit(); // optional
SelectedRow["CompanyName"] = "Contoso";
SelectedRow.EndEdit(); // Proposed becomes Current
DataSets
C. 52
RejectChanges
Can be issued on the DataRow, DataTable and, DataSet objects
Data changes are rejected
DataRow is rolled back to the point in time when the last
AcceptChanges method was called
26
DataSets
C. 53
DataSets
C. 54
27
DataSets
C. 55
Data Integrity
Add a ForeignKeyConstraint to Constraints collection of
the foreign table
Properties of ForeignKeyConstraint
Table: Orders, Columns: CustomerID
RelatedTable: Customer, RelatedColumns: ID
DeleteRule, UpdateRule
Cascade (default): child rows deleted or updated (if necessary)
None (throw exception), SetDefault, SetNull
AcceptRejectRule
None (default)
Cascade: AcceptChanges or RejectChanges on related child rows
C. 56
Exploits of a Mom
http://xkcd.com/327/
28
SQL Server
C. 57
SQL Server
C. 58
Stored Procedures
Stored procedures should use parameters as their input
CREATE PROCEDURE HumanResources.uspGetEmployees
@LastName nvarchar(50) = NULL, --default value
@FirstName nvarchar(50),
@HowMany int OUTPUT /* or OUT */
AS
SET NOCOUNT ON;
SET @HowMany = SELECT COUNT(*) FROM ...;
SELECT FirstName, LastName, Department
FROM HumanResources.vEmployeeDepartmentHistory
WHERE FirstName = @FirstName AND LastName = @LastName;
29
C. 59
SQL Server
Partitioning
Partitioning a database improves performance and
simplifies maintenance
Hardware partitioning
RAID
Horizontal partitioning (SQL Server 7.0 and later)
Each table has same columns, but subset of rows
C. 60
SQL Server
money
Decimal
bit
Boolean
binary / image
Byte[]
numeric
Decimal
float
Double
uniqueidentifier
Guid
String, Char[]
datetime
DateTime
date
DateTime
time
TimeSpan
timestamp
Byte[]
bigint
Int64
smallint
Int16
tinyint
Byte
30
SQL Server
C. 61
SQL Server
C. 62
Spatial Datatypes
SQL Server 2008 and later
geometry: planar (Euclidean) data
SqlDbType.Udt
UdtTypeName: "GEOMETRY"
geography: ellipsoidal data such as GPS coordinates
SqlDbType.Udt
UdtTypeName: "GEOGRAPHY"
31
C. 63
SQL Server
C. 64
SQL Server
NULL, ...
32
SQL Server
C. 65
SQL Server
C. 66
33
SQL Server
C. 67
34
D. 1
Appendix D
LINQ
Developing Windows Azure
and Web Services
D. 2
LINQ
Contents
Topic
Slide
var
Generics
Initializers
Delegates
Lambda Expressions
11
LINQ
15
Extension Methods
22
Projection
33
39
LINQ to XML
43
48
D. 3
var
The compiler must be able to infer the type so you must assign
an initial value, which can be returned from a method call
D. 4
Generics
D. 5
Generics
Constraints
When you define a generic class or method, you can
apply restrictions to the kinds of types that can be used
Constraint
Description
where T : struct
where T : class
where T : new()
where T : U
Generics
D. 6
Generic Methods
Any type (including non-generic types) can have
generic methods
The generic applies to the type in the method signature
public class NonGen
{
public void M1<T>(T Value)
{
// use Value
}
}
Initializers
D. 7
Object Initializers
Given this type
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
Initializers
D. 8
D. 9
Delegates
What Is A Delegate?
A delegate is a type-safe function pointer
Like a reference it contains the memory address of something,
but it points to a method rather than a data structure
method directly
M1("Hello");
method indirectly
new Del(M1);
d("Goodbye");
Delegates
D. 10
Anonymous delegates
Simplify code by removing need for defining a private method
Button1.Click += delegate { Debug.Write("Clicked"); };
D. 11
Lambda Expressions
Generic delegate
Lambda expression
D. 12
Lambda Expressions
Syntax
A lambda expression syntax
(parameters) => expression
Lambda Expressions
D. 13
Func(T, TResult)
For lambda expressions with one input parameter
Func<int, bool> myFunc = x => x == 5;
bool result1 = myFunc(4); // returns false
bool result2 = myFunc(5); // returns true
Lambda Expressions
D. 14
D. 15
LINQ
What Is It?
Most databases understand SQL...
...but to C# 2.0 and VB 8.0, an SQL statement is just a string
LINQ integrates query syntax to a .NET language
LINQ
D. 16
Provider Limitations
Theoretically, once you learn LINQ, you can query any
LINQ provider...
...but some LINQ providers have limitations
D. 17
LINQ
LINQ
D. 18
D. 19
LINQ
LINQ
D. 20
10
D. 21
LINQ
D. 22
Where
Where takes a Func<TInput,TReturn> generic delegate
as input (so we can use a lambda expression instead)
Expression must have a single input parameter (of whatever
type T in IEnumerable(T) is) and must return a boolean
n would be a string
string[] names = ...;
... names.Where(n => n.StartsWith("A"));
p would be a Person
Person[] people = ...;
... people.Where(p => p.Age > 18);
11
D. 23
D. 24
OrderBy
OrderBy takes a Func<TInput,TKeySelector> generic
delegate as input
Lambda expression must have a single input parameter (of
whatever type T in IEnumerable(T) is) and can return any type
For names string array, we might want to order by the number
of characters in each string entry
12
D. 25
E
Emily
F
Fred
G
Gary
George
E
Emily
F
Fred
G
George
Gary
D. 26
13
D. 27
Range
IEnumerable<int> numbers = Enumerable.Range(4, 3);
/* 4
5
6 */
Repeat
IEnumerable<string> madness = Enumerable.Repeat(
"All work and no play makes Jack a dull boy.", 99);
/* All work and no play makes Jack a dull boy.
All work and no play makes Jack a dull boy.
All work and no play makes Jack a dull boy.
D. 28
All(), Any()
Returns true if all or any elements satisfy the lambda expression
if(names.Any(name => name.StartsWith("A")))
SequenceEqual()
Returns true if the two sequences contain the same elements in
the same order
14
D. 29
Single, SingleOrDefault
Returns a specific member of a sequence, or default value, or
throws exception if more than one item in sequence
Person q1 = people.Where(p => p.ID == 123).Single();
Person q2 = people.Single(p => p.ID == 123);
D. 30
Skip, SkipWhile
Skips n members, or while lambda expression returns true
Take, TakeWhile
Takes n members, or while lambda expression returns true
15
D. 31
AsSomething Conversions
AsEnumerable<T>()
Convert IEnumerable to IEnumerable<T>
Execute a query without creating a local collection
D. 32
ToSomething Conversions
ToList and ToArray: return flat collection of results
ToDictionary
ToLookup
One-to-many mapping of keys to collections
Requires a lambda to define property to use for the key
ILookup<string, Product> products =
db.Products.ToLookup(p => p.Category.CategoryName);
IEnumerable<Product> bikes = products["Bike"];
// we could use var but it is better to document the actual type
16
D. 33
Projection
Primitive Results
p is a Product
// syntactic sugar
var query = from p in db.Products
select p;
p.ProductName is a string
// syntactic sugar
var query = from p in db.Products
select p.ProductName;
D. 34
Projection
Materialize results
List<ProductSubset> results = query.ToList();
17
D. 35
Projection
Projection
D. 36
SelectMany Example 1
SelectMany projects each element of a sequence to an
IEnumerable<T> and flattens the resulting sequences
into one sequence
var nameList = new List<string> {
"Matt", "Adam", "John", "Peter",
"Owen", "Steve", "Richard", "Chris" };
18
D. 37
Projection
SelectMany Example 2
We want to create a single sequence of words from a
sequence of sentences
var sentences = new List<string> {
"Bob is quite excited.",
"Jim is very upset."
};
Using SelectMany
// extensions and lambdas
var words = sentences
.SelectMany(s => s.TrimEnd('.').Split(' '));
D. 38
Projection
SelectMany Example 3
We want to get a flat list of products from categories
var db = new NorthwindEntities();
Using SelectMany
var query = db.Categories.SelectMany(c => c.Products);
// syntactic sugar
var query = from c in db.Categories
from p in c.Products
select p;
... = from c in db.Categories
select c.Products;
19
D. 39
D. 40
20
D. 41
D. 42
21
LINQ to XML
D. 43
LINQ to XML
D. 44
22
D. 45
LINQ to XML
LINQ to XML
D. 46
23
D. 47
LINQPad
http://www.linqpad.net
24
E. 1
Appendix E
Entity Framework 4
Developing Windows Azure
and Web Services
E. 2
Entity Framework 4
Contents
Topic
Slide
POCO
Retrieving Data
12
Modifying Data
16
Performance
22
You are unlikely to get questions about features of EF4 and ObjectContext
in the exam although Visual Studio can generate the old ObjectContext
and EntityObject classes or the inner ObjectContext can be accessed by
casting a DbContext as an IObjectContextAdapter like this:
using System.Data.Entity.Infrastructure;
var db = new NorthwindEntities(); // DbContext
var oc = ((IObjectContextAdapter)db).ObjectContext;
E. 3
Vocabulary Overview
AWModel.edmx
AWModel.edmx.cs
Database
<EntityContainer
Name="AdventureWorksEntities"
class AdventureWorksEntities :
ObjectContext (or DbContext)
Table
<EntitySet Name="Contacts"
ObjectSet<Contact> Contacts
(or DbSet<Contact> Contacts)
Row
<EntityType Name="Contact"
Column
<Property Name="ContactID"
[EdmScalarProperty()]
Int32 ContactID
Relationship
<NavigationProperty
Name="Orders"
<NavigationProperty
Name="Contact"
<Association Name=
"FK_Orders_Contact_ContactID"
[EdmRelationshipNavigationPro
perty()]
EntityCollection<Order> Orders
[EdmRelationshipNavigationPro
perty()]
Contact Contact
E. 4
Entity Properties
<EntityType Name="Category">
...
<Property Name="CategoryName" ...
<NavigationProperty
Name="Products" ...
E. 5
E. 6
A corresponding
AssociationSetMapping
element is not
necessary to map this
association to the
data source
<Association Name="CustomerOrders">
<End Type="ExampleModel.Customer"
Role="Customer" Multiplicity="1" >
<OnDelete Action="Cascade" />
</End>
<End Type="ExampleModel.Order"
Role="Order" Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="Customer">
<PropertyRef Name="Id" />
</Principal>
<Dependent Role="Order">
<PropertyRef Name="CustomerId" />
</Dependent>
</ReferentialConstraint>
</Association>
E. 7
http://msdn.microsoft.com/en-us/library/bb345303.aspx
http://msdn.microsoft.com/en-gb/magazine/gg490349.aspx
E. 8
EntityCollection(T), EntityReference(T)
Navigation properties in designer-generated code
public class Customer : EntityObject { ...
public EntityCollection<Order> Orders { ...
public class Order : EntityObject { ...
public EntityReference<Customer> CustomerReference { ...
Useful members
IsLoaded: returns true if collection or reference is loaded
Load(MergeOption): Loads related object(s)
CreateSourceQuery(): Returns an object query that returns the
same object(s) that exist in the current collection or reference
EntityCollection(T).Count: the number of entities in collection
EntityReference(T).Value: the actual entity
EntityCollection(TEntity) Class
http://msdn.microsoft.com/en-us/library/bb354106.aspx
E. 9
POCO
Requirements
To use POCO
with EF
To create
either type of
proxy
To create a
lazy-loading
proxy
1. Navigation properties must have a public, virtual, and nonsealed get accessor
To create a
changetracking proxy
POCO
E. 10
POCO
E. 11
Change Tracking
POCO supports two methods of change tracking
Proxy creation (aka instant) change tracking
Snapshot change tracking
Retrieving Data
E. 12
ObjectContext.TryGetObjectByKey Method
http://msdn.microsoft.com/en-us/library/bb738728.aspx
Retrieving Data
E. 13
Entity Keys
You can create an instance of EntityKey by using the
class constructor
var key = new EntityKey(
"AWEntities.Contacts", "ContactID", 3);
Retrieving Data
E. 14
ExecuteStoreCommand
Executes an arbitrary command directly against the data source
using the existing connection
ExecuteStoreQuery
Executes a query directly against the data source that returns a
sequence of typed results
Translate
Translates a DbDataReader that contains rows of entity data to
objects of the requested entity type
ObjectContext Class
http://msdn.microsoft.com/en-us/library/bb156104
Retrieving Data
E. 15
CreateQuery<T>() method
Creates an ObjectQuery<T> by using the specified
query string
var query = oc.CreateQuery<Contact>(
"SELECT VALUE c FROM AWEntities.Contacts
AS c WHERE c.FirstName = @fn",
new ObjectParameter("fn", "John"));
Modifying Data
E. 16
Modifying Data
E. 17
OverwriteChanges
Objects that do not exist in the object context are attached
Existing objects are overwritten
PreserveChanges
Objects that do not exist in the object context are attached
Existing objects that are Unchanged are overwritten
Existing objects that are Modified are preserved
Modifying Data
E. 18
ObjectContext methods
AddObject(string entitySet, object)
Adds an object to the object context (marked as Added)
Modifying Data
E. 19
ObjectStateEntry
Maintains state and key information for objects and
relationships and change tracking for object properties
ObjectStateEntry stateEntry = context.ObjectStateManager
.GetObjectStateEntry(((IEntityWithKey)order).EntityKey);
CurrentValueRecord rec1 = stateEntry.CurrentValues;
string oldPO = (string)rec1.GetValue(
rec1.GetOrdinal("PurchaseOrderNumber"));
order.PurchaseOrderNumber = "12345";
string newPO = (string)rec1.GetValue(
rec1.GetOrdinal("PurchaseOrderNumber"));
IEnumerable<string> modifiedFields =
stateEntry.GetModifiedProperties();
foreach (string s in modifiedFields)
Console.WriteLine("Modified field name: {0}\n" +
"Old Value: {1}\n New Value: {2}", s, oldPO, newPO);
Modifying Data
E. 20
ObjectContext.SaveChanges
SaveChanges()
Persists all updates to the data source and resets change
tracking in the object context (i.e. it calls AcceptAllChanges()
automatically)
Returns number of objects in an Added, Modified, or Deleted
state when SaveChanges was called
SaveChanges(SaveOption)
None, AcceptAllChangesAfterSave (default),
DetectChangesBeforeSave
Use to control the automatic call to AcceptAllChanges() or
enable an automatic call to DetectChanges()
Flag so can be combined
SaveChanges(bool) is obsolete
10
E. 21
Modifying Data
OptimisticConcurrencyException
When invoking SaveChanges, catch this exception
Invoke Refresh on context to resolve conflict
RefreshMode: StoreWins, ClientWins
Pass entity or IEnumerable
E. 22
Performance
Considerations
Operation
Frequency
Comments
Loading metadata
Opening connection
As needed
Generating views
Can pre-generate
Can pre-compile
Loading and
validating types
Tracking
Materializing
11
Performance
E. 23
EF 4.1
E. 24
12
F. 1
Appendix F
Firebrand Sample Services
Developing Windows Azure
and Web Services
F. 2
Contents
Topic
Slide
Overview
The Service
The Clients
12
Exposing Data
21
24
Faults
27
Duplex
30
REST
34
Discovery
35
Router
40
Sessions
46
F. 3
Overview
ClientUsingChannelFactory / ManualContract
Dynamic Proxy
ClientUsingDiscovery
Announcement
Service
ClientUsingDuplex
CalculatorClient
RoutingService
Callback
Hello
Bye
SampleService
IISHost on port 802
SampleService
Calculator (Duplex)
Overview
F. 4
The Service
F. 5
The Service
F. 6
F. 7
The Service
F. 8
The Hosts
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Description;
The Hosts
F. 9
The Hosts
F. 10
F. 11
The Hosts
File-Add Service...
Enter URL: http://localhost:801/Sample
Double-click Config File and review it (or right-click to edit it)
Double-click AddNumbers, fill parameters, click Invoke
F. 12
The Hosts
<customBinding>
<binding name="FBBinaryOverHttp">
<binaryMessageEncoding/>
<httpTransport/>
<services>
<service name="Firebrand.SampleService">
<endpoint address=""
binding="customBinding"
bindingConfiguration="FBBinaryOverHttp"
contract="Firebrand.ISampleService" />
<endpoint address="ws"
binding="wsHttpBinding"
bindingConfiguration="FBWSNoSecurity"
contract="Firebrand.ISampleService" />
The Clients
F. 13
The Clients
F. 14
The Clients
F. 15
The Clients
F. 16
The Clients
F. 17
The Clients
F. 18
F. 19
The Clients
using System.ServiceModel;
using Firebrand;
The Clients
F. 20
10
Exposing Data
F. 21
Exposing Data
F. 22
S3.Implementation, SampleService.cs
public Product[] GetProducts() {
using (var db = new NorthwindEntities()) {
db.Configuration.LazyLoadingEnabled = false;
using System.Linq;
return db.Products.ToArray();
}
}
public Product GetProduct(int ProductID) {
using (var db = new NorthwindEntities()) {
db.Configuration.LazyLoadingEnabled = false;
return db.Products.Single(p => p.ProductID == ProductID);
}
}
11
Exposing Data
F. 23
S3.Implementation
Add NuGet package for EntityFramework (best to use the same
version that your S1.DataContracts project uses)
Exposing Data
F. 24
12
Exposing Data
F. 25
F. 26
13
F. 27
Warning! When testing a Web Project solution in Visual Studio 2010 you are using the ASP.NET
Development Server (aka Cassini) which only supports HTTP. To test other bindings you must either
deploy to IIS 7.x with WAS or create a non-Web host like the ConsoleHost project.
F. 28
14
Faults
F. 29
S2.ServiceContracts
[ServiceContract]
public interface ISampleService {
[OperationContract]
[FaultContract(typeof(ExtraError))]
int AddNumbers(int a, int b);
Faults
F. 30
Note: when using SOAP 1.1 only the first translation will be sent
Use WSHttpBinding or later to use SOAP 1.2 which does support
multiple translations
15
Faults
F. 31
Duplex
F. 32
Service Contract
S2.ServiceContract, add two new interfaces
Interface for service-side to implement
[ServiceContract(CallbackContract = typeof(ICalcAnswer))]
public interface ICalcOneWay {
[OperationContract(IsOneWay = true)]
void Multiply(int a, int b);
}
16
Duplex
F. 33
H1.ConsoleHost, App.config
Endpoint will use the base address specified on the next slide
<service name="Firebrand.Calculator">
<endpoint address=""
binding="wsDualHttpBinding"
contract="Firebrand.ICalcOneWay" />
Duplex
F. 34
17
F. 35
Duplex
Add a Button
F. 36
REST
Change Console
app to use full .NET
Framework 4
http://localhost:801/Sample/REST/AddNumbers?a=2&b=3
<int xmlns="http://...">5</int>
18
Discovery
F. 37
Discovery
F. 38
19
F. 39
Discovery
System.ServiceModel;
System.ServiceModel.Discovery;
Firebrand;
System.Collections.ObjectModel;
Discovery
F. 40
20
Discovery
F. 41
Router
F. 42
Web.config
<serviceBehaviors>
<behavior name="FirebrandRouting">
<routing filterTableName="FirebrandTable"/>
21
Router
F. 43
Router
F. 44
22
Router
F. 45
The console host will act as the primary service on port 801, but
can now fail over automatically to use the secondary service on
port 802 hosted by IIS
Router
F. 46
App.config
Edit the client endpoint to use Router.svc for address instead of
talking directly to Sample.svc
Edit the name of the endpoint because the code uses named
<client>
endpoints
creating the proxy (i.e. on slide 12)
<endpointwhen
address="http://localhost:803/Router.svc"
binding= ...
23
Router
F. 47
Start C1.ClientUsingWSDL
Click Modify Widget: name will be suffixed with SuffixB
Stop the H1.ConsoleHost
Click Modify Widget: name
will be suffixed with Suffix
Sessions
F. 48
S3.Implementation
private int Counter;
private static int StaticCounter;
24
Sessions
F. 49
Sessions
F. 50
25
G. 1
Appendix G
Whats New in Visual Studio 2013
and Updated Exam
Developing Windows Azure
and Web Services
G. 2
G. 3
G. 4
Slide
5
16
21
G. 5
Miscellaneous Improvements
Improved Intellisense Support
Support for UDP Endpoint (udpBinding)
Typically TCP is used in non-time critical (may be non-realtime) applications but UDP is very useful for real-time
applications
TCP performs data-packets checking for the order of the
message to be send, it is slower than UDP
In UDP, packet delivery is not guaranteed and loss or out-ofarrival of packets is acceptable
G. 6
In WCF 4.5
If IIS is enabled for SSL and if the service does not have any
explicit endpoint defined for the specific binding, then WCF can
be hosted on IIS with HTTPS enabled i.e. basicHttpsBinding
To experience the automatic Https protocol mapping on IIS, you
need to create an Application Pool with Identity as LocalSystem
G. 7
G. 8
Authentication
WCF 4.5 enabled you to inherit the authentication
types from IIS, so you only need to declare them once
Set the clientCredentialType attribute to InheritedFromHost
<services>
<service name="MyService">
<endpoint address="" binding="basicHttpBinding"
contract="Mycontract" bindingConfiguration="secured"/>
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="secured">
<security mode="Transport">
<transport clientCredentialType="InheritedFromHost" />
Whats new in WCF 4.5? Multiple authentication support on a single endpoint in IIS
http://blogs.microsoft.co.il/idof/2011/09/25/whats-new-in-wcf-45-multiple-authentication-support-on-a-single-endpoint-in-iis/
G. 9
What Is It?
Attribute routing gives you more control over the URIs
in your web API
The earlier style of routing, called convention-based routing, is
still fully supported
You can combine both techniques in the same project
G. 10
Why Is It Useful?
Resources often contain child resources: Customers
have orders, books have authors, and so forth
Its natural to create URIs that reflect these relations
/customers/1/orders
G. 11
G. 12
Route Prefixes
You can set a common prefix for an entire controller
[RoutePrefix("api/books")]
public class BooksController : ApiController
{
// GET api/books
[Route("")]
public IEnumerable<Book> Get() { ... }
// GET api/books/5
[Route("{id:int}")]
public Book Get(int id) { ... }
// POST api/books
[Route("")]
public HttpResponseMessage Post(Book book) { ... }
// GET /api/authors/1/books
[Route("~/api/authors/{authorId:int}/books")]
public IEnumerable<Book> GetByAuthor(int authorId) { ... }
}
G. 13
Route Constraints
The general syntax is "{parameter:constraint}
Here, the first route will only be selected if the "id" segment of
the URI is an integer
Otherwise, the second route will be chosen
[Route("users/{id:int}"]
public User GetUserById(int id)
[Route("users/{name}"]
public User GetUserByName(string name)
Route Constraints
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#constraints
G. 14
using System.Web.Http.Routing;
G. 15
G. 16
Request Batching
using System.Web.Http.Batch;
On the client side you can use the existing Web API
client library to submit a batch request
G. 17
G. 18
G. 19
G. 20
using Microsoft.Owin.Hosting;
using System;
using System.Net.Http;
10
G. 21
App Suspend
Radically changes the economic model for hosting large
numbers of ASP.NET sites on a server
Built on top of a new feature in Windows Server
2012 R2 called IIS Idle Worker Process Page-out
Its the cloud version of the app suspend (AKA tombstoning) that
you see in Windows Phone and Windows Store apps
G. 22
App Suspend
App Suspend is a
new setting in IIS
configuration,
available on each
application pool
You can validate
that an app was
suspended in the
event viewer, in the
Application event
log
Search for event 2310
Enable and monitor ASP.NET App Suspend on Windows Server 2012 R2
http://blogs.msdn.com/b/webdev/archive/2013/10/09/enable-and-monitor-asp-net-app-suspend-on-windows-server-2012-r2.aspx
11