#devsum15
Learning How to Shape and Configure an OData Feed for High
Performing Web Sites and Applications
Chris Woodruff
@cwoodruff [email protected]
Hi, I’m Woody!
Chris Woodruff
• http://chriswoodruff.com
• http://deepfriedbytes.com
• twitter @cwoodruff
VALIDATION CLIENT SIDEBEST PRACTICES
AGENDA
What are the 2 Sides of OData?SERVER-SIDE (PRODUCER) CLIENT-SIDE (CONSUMER)
Server Side for OData
UNDERSTAND RESTThe Top Reasons You Need to Learn about Data in Your Windows Phone App
WHAT IS REST?
RESOURCES
VERBS
URL
WHAT SHOULD YOU KNOW ABOUT REST?
Resources REST uses addressable resources to define the
structure of the API. These are the URLs you use to
get to pages on the web
Request HeadersThese are additional instructions that are sent with the
request. These might define what type of response is
required or authorization details.
Request VerbsThese describe what you want to do with the resource.
A browser typically issues a GET verb to instruct the
endpoint it wants to get data, however there are many
other verbs available including things like POST, PUT
and DELETE.
Request BodyData that is sent with the request. For example a
POST (creation of a new item) will required some data
which is typically sent as the request body in the format
of JSON or XML.
Response BodyThis is the main body of the response. If the request
was to a web server, this might be a full HTML page, if
it was to an API, this might be a JSON or XML
document.
Response Status codesThese codes are issues with the response and give
the client details on the status of the request.
REST & HTTP VERBS
GETRequests a representation of the specified
Requests using GET should only retrieve have no other effect.
POSTRequests that the server accept the entity enclosed in the request as a new subordinate of the web resource identified by the URI.
PUTRequests that the enclosed entity be stored
under the supplied URI.
DELETEDeletes the specified resource.
EXAMPLES OF REST AND ODATA
/Products
RESOURCE EXPECTED OUTCOMEVERB RESPONSE CODE
/Products?$filter=Color eq ‘Red'
/Products
/Products(81)
/Products(881)
/Products(81)
/Products(81)
GET
GET
POST
GET
GET
PUT
DELETE
A list of all products in the system
A list of all products in the system
where the color is red
Creation of a new product
Product with an ID of 81
Some error message
Update of the product with ID of 81
Deletion of the product with ID of
81
200/OK
200/OK
201/Created
200/OK
404/Not Found
204/No Content
204/No Content
BEST PRACTICES
Get to know the OData Protocol!!!
Examples (http://chinookdata.azurewebsites.net)GET serviceRoot/Artists?$filter=Name eq 'Foo Fighters'
GET serviceRoot/Artists?$filter=contains(Name, 'Foo')
GET serviceRoot/Artists(1)?$expand=Albums
GET serviceRoot/Artists(58)/Albums?$orderby=Title desc
GET serviceRoot/Artists?$skip=20&$top=10
GET serviceRoot/Artists?$search=AC ***
GET serviceRoot/Customer?$filter=Email/any(s:endswith(s, 'contoso.com')) ***
GET serviceRoot/$metadata
Query Projection
Examples (http://chinookdata.azurewebsites.net)
PROPERTIES OF THE CUSTOMER ENTITY
• CustomerId
• FirstName
• LastName
• Company
• Address
• City
• State
QUERY PROJECTIONS FOR PERFORMANCE
GET serviceRoot/Customers?$select= FirstName, LastName, Company
GET serviceRoot/Customers?$select= LastName, Address, City, State, Country, PostalCode
GET serviceRoot/Customers?$select= FirstName, LastName, Phone, Email
• Country
• PostalCode
• Phone
• Fax
• SupportRepId
Server Side Paging
Examples[EnableQuery(PageSize=20)]
Configuration Settings
Examplesinvoice.Ignore(t => t.InvoiceDate);
Data Caching with Web API OData v4
ExampleAdd the CacheCow Server NuGet package to your server project.
ExampleAdd the following to your WebApiConfig.cs file:
var cacheCowCacheHandler = new CachingHandler(config);
config.MessageHandlers.Add(cacheCowCacheHandler);
When you get a resource you will get an Etag
ETag: W/”002a41972c3d43f0bb14d033907b3f41″
When you make a second request to the same resource, you should send this ETag. The server uses this identifier to check if the resource you requested has changed (remember, the server is the authoritative source). If the resource has indeed changed, it sends you the latest copy. Otherwise, it sends a 304 Not Modified.
VALIDATION AND FILTERING
QUERYABLE ODATA ATTRIBUTES
AllowedFunctionsConsider disabling the any() and all() functions, as these can be
05
IgnoreDataMember (not with Queryable)Represents an Attribute that can be placed on a property to specify that the property cannot be navigated in OData query.
06
PageSizeEnable server-driven paging, to avoid returning a large data set in one query. For more information
01
AllowedQueryOptionsDo you need $filter and $orderby? Some applications might allow client paging, using $top and $skip, but disable the other query options.
02
AllowedOrderByPropertiesConsider restricting $orderby to properties in a clustered index. Sorting large data without a clustered index is slow.
03
AllowedLogicalOperatorsConsider any logical operators that you do not want to allow
04
Examples[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.Filter)]
[EnableQuery(AllowedLogicalOperators = AllowedLogicalOperators.Equal)]
[EnableQuery(AllowedFunctions = AllowedFunctions.AllStringFunctions)]
[EnableQuery(AllowedOrderByProperties = "ID")]
ODATA ATTRIBUTES (CONT)
NotExpandableRepresents an Attribute that can be placed on a property to specify be used in the $expand OData query option.
05
NotNavigableRepresents an Attribute that can be placed on a property to specify that the property cannot be navigated in OData query.
06
NotSortableRepresents an attribute that can be placed on a property to specify that the property cannot be used in the $orderby OData query option.
07
NonFilterableRepresents an Attribute that can be placed on a property to specify that the property cannot be used in the $filter OData query option.
01
UnSortableRepresents an Attribute that can be placed on a property to specify that the property cannot be used in the $orderby OData query option.
02
NotExpandableRepresents an Attribute that can be placed on a property to specify that the property cannot be used in the $expand OData query option.
03
NotCountableRepresents an Attribute that can be placed on a property to specify that the $count cannot be applied on the property.
04
[NonFilterable]
[Unsortable]
public string Name { get; set; }
QUERY SECURITY
Consider disabling the any() and all() functions, as these can be slow.
06
If any string properties contain large strings—for example, a product description or a blog entry—consider disabling the string functions.
07
Consider disallowing filtering on navigation properties. Filtering on navigation properties can result in a join, which might be slow, depending on your database schema.
08
Test your service with various queries and profile the DB.
01
Enable server-driven paging, to avoid returning a large data set in one query.
02
Do you need $filter and $orderby? Some applications might allow client paging, using $top and $skip, but disable the other query options.
03
Consider restricting $orderby to properties in a clustered index. Sorting large data without a clustered index is slow.
04
Consider restricting $filter queries by writing a validator that is customized for your database.
09
Maximum node count: The MaxNodeCount property on [Queryable] sets the maximum number nodes allowed in the $filter syntax tree. The default value is 100, but you may want to set a lower value, because a large number of nodes can be slow to compile.
05
VALIDATION PATHS
Filter QueryRepresents a validator used to validate a
FilterQueryOption based on the
ODataValidationSettings.
Order By QueryRepresents a validator used to validate an
OrderByQueryOption based on the
ODataValidationSettings.
OData QueryRepresents a validator used to validate OData queries
based on the ODataValidationSettings.
Select Expand QueryRepresents a validator used to validate a
SelectExpandQueryOption based on the
ODataValidationSettings.
Skip QueryRepresents a validator used to validate a
SkipQueryOption based on the
ODataValidationSettings.
Top QueryRepresents a validator used to validate a
TopQueryOption based on the
ODataValidationSettings.
QUERY SECURITY
// Validator to prevent filtering on navigation properties.public class MyFilterQueryValidator : FilterQueryValidator{
public override void ValidateNavigationPropertyNode(Microsoft.Data.OData.Query.SemanticAst.QueryNode sourceNode, Microsoft.Data.Edm.IEdmNavigationProperty navigationProperty, ODataValidationSettings settings)
{throw new ODataException("No navigation properties");
}}
// Validator to restrict which properties can be used in $filter expressions.public class MyFilterQueryValidator : FilterQueryValidator{
static readonly string[] allowedProperties = { "ReleaseYear", "Title" };
public override void ValidateSingleValuePropertyAccessNode(SingleValuePropertyAccessNode propertyAccessNode,ODataValidationSettings settings)
{string propertyName = null;if (propertyAccessNode != null){
propertyName = propertyAccessNode.Property.Name;}
if (propertyName != null && !allowedProperties.Contains(propertyName)){
throw new ODataException(String.Format("Filter on {0} not allowed", propertyName));
}base.ValidateSingleValuePropertyAccessNode(propertyAccessNode,
settings);}
}
Demo
www.chriswoodruff.com Page Number 31
Client Side for OData
DEBUGGING/TESTING
XODATAWeb-based OData Visualizer
FIDDLERFree web debugging tool which logs all HTTP(S) traffic between
your computer and the Internet.
LINQPAD (v3)Interactively query SQL
databases (among other data sources such as OData or WCF Data Services) using LINQ, as
well as interactively writing C# code without the need for an
IDE.
ODATA VALIDATOR
Enable OData service authors to validate their
implementation against the OData specification to ensure the service interoperates well
with any OData client.
TESTING/DEBUGGING ODATA
www.websitename.com
CONSUMING ODATA
DemoShow How to Consume an OData Feed in an Universal App
GITHUB
http://github.com/cwoodruff
Project:
ChinookWebAPIOData
ChinookOData
Where can you find the source for this talk?
ODATA WORKSHOP
0102
0304
TESTING/DEBUGGING ODATA
DEVELPING CLIENT SIDE SOLUTIONS• Web Apps using Javascript to consume Odata• iOS Swift development for native iPhone and iPad
apps• Windows 8.1 and Windows Phone apps C# and WinJS• Android development using Java• Using Xamarin for consuming OData
LEARNING THE PROTOCOL• The Metadata and Service Model of OData
• URI Conventions of OData• Format Conventions of OData
• OData HTTP Conventions and Operations
DEVELPING SERVER SIDE SOLUTIONS• ASP.NET Web API
• Advanced Performance Tips and Best Practices
Go to http://ChrisWoodruff.com for more details and pricing
THANK YOU
Find me around the conference and would enjoy chatting
Email: [email protected]
Twitter: @cwoodruff