SlideShare ist ein Scribd-Unternehmen logo
1 von 87
Windows 8 apps
        and the outside world
Gill Cleeren
Microsoft Regional Director & MVP
Telerik MVP
About myself...
• Gill Cleeren
• .NET Architect @Ordina (www.ordina.be)
• Microsoft Regional Director
• Silverlight MVP
• Speaker (TechDays, TechEd, DevReach, DevDays, NDC Norway, Telerik
  Usergroup tours...)
• Visug user group lead (www.visug.be)
• Author:
     • Silverlight 4 Data and services cookbook
     • Silverlight 5 Data and services cookbook
• Blog: www.snowball.be
• Email: gill@snowball.be
• Twitter: @gillcleeren
Silverlight 5 Data and Services
Cookbook available!

• Updated for Silverlight 5
• Over 115 recipes (that’s 30 extra!)
• Extended to about 700 pages
   • (That’s 250 extra!)
• Covering WP7, MVVM,
  RIA Services and much more!
• More info:


         http://bit.ly/SL5DataAndServices
Agenda

•   Accessing data behind a service
•   Working with WCF and ASMX services
•   Working with REST services
•   Accessing oData services
•   Syndication with RSS
•   Background transfers
•   Tiles interactions
      • Periodic tile updates
      • Push notifications
•   Authenticating with Twitter and Facebook using the WebAuthBroker
•   Using the Live SDK in your Windows 8 apps
•   Using roaming data in your applications
•   Working with sockets
      • TCP sockets
      • WebSockets
What we aren’t covering today

• ControlChannelTrigger
• Raw notifications
• Azure
Accessing data behind
a service
Working with services to access
data
• Service communication is always done asynchronous
   • In Silverlight, this was done using a callback
   • In C#5, we got the async/await keywords
       • Fully supported in Metro/WinRT development
       • await keyword makes things easier
       • Doesn’t block UI thread
           • Doesn’t require the ugly
             Dispatcher.BeginInvoke(() => …);

• Getting data in a Metro application is a 3-step process
   • Calling the service asynchronous
   • Receiving and parsing the data
   • Using the data, for example in a data-binding scenario
Working with services to access
data
• Working with services is preferred in most cases
   • Relational databases should be behind a service
   • Local app storage
      • App has its own storage directory
      • Can access local file system
      • Not the focus of this talk!
Working with services

• Windows 8 supports all kinds of services
   • ASMX
   • WCF
   • REST (JSON or XML)
   • RSS (later in this talk)
   • Sockets (much later in this talk)
   • oData services (you get the drill, it’s also further in this
     talk…)
   • No WCF RIA Services support out-of-the-box though (so
     yes, that is NOT in this talk )
   •…
WCF and ASMX
Services
ASMX services (aka good old
webservices)
• ASMX services can be accessed without any change
• Communication is done asynchronously
• SOAP messages can be sent and received over
  ASMX services
• From Visual Studio, use the default way of
  connecting with a service
  • Add service reference
  • Generates proxy
     • All Task-based!
  • Use proxy-class with the async/await keywords
Accessing an ASMX
service from Windows
8
DEMO
WCF Services

• What is supported?
   • Bindings:
       •   BasicHttpBinding
       •   NetTcpBinding
       •   NetHttpBinding
       •   CustomBinding
   • Binding elements:
       •   BinaryMessageEncodingBindingElement
       •   TextMessageEncodingBindingElement
       •   ConnectionOrientedTransportBindingElement
       •   SslStreamSecurityBindingElement
       •   WindowsStreamSecurityBindingElement
       •   TcpTransportBindingElement
       •   Http(s)TransportBindingElement
       •   TransportSecurityBindingElement
WCF Services

• What is supported
   • Encoding:
        • Text, Binary
   • Security modes:
        • None, Transport, TransportWithMessageCredential, TransportCredentialOnly
          (for BasicHttpBinding)
   • ClientCredentialType:
        • None, Basic, Digest, Negotiate, Ntlm, Windows
   • Transfer Mode:
        • Buffered, Streamed, StreamedRequest, and StreamedResponse
   • Serializers:
        • DataContractSerializer, DataContractJsonSerializer, XmlSerializer
   • Miscellaneous:
        • ChannelFactory
        • DuplexChannelFactory
        • CallbackBehavior
Things to note when working with
WCF (also goes for ASMX)
• No XML config file code
   • Code gets generated in the Reference.cs file
      • No config edit possible 
   • Use the partial ConfigureEndpoint method
• Only Task-based methods are available
   • Ensures there are no blocking calls
   • Is done by default
• Specify Internet capability
Accessing a WCF
service
from Windows 8
DEMO
What about security for service
communication?
• WinRT supports sending credentials
• When building service that expects
  credentials, generated code in Reference.cs will reflect
  this
result.Security.Mode =
         System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly;

result.Security.Transport.ClientCredentialType =
         System.ServiceModel.HttpClientCredentialType.Windows;




• https, custom validation are supported to enable
  TransportWithMessageCredential
   • Allows safe passing of username/password to service
     endpoint
Secure
communication from a
Windows 8 app
DEMO
Working with REST
services
REST services

• No more WebClient, replaced with HttpClient
   • Works with async
   • Located in System.Net
• HttpClient defines
   • Get(Async)
      • Returns an HttpResponseMessage
   • Put(Async)
   • Post(Async)
   • Delete(Async)
    RESTful!
Parsing the response

• XML
   • Linq-To-XML
   • XmlReader/XmlWriter
   • XmlSerializer
• JSON:
   • Use the JsonObject and feed it the returned string
        • We can use the Parse() method
            • Throws error if the returned string is faulty or invalid
        • Also defines GetNamedString(), GetNamedNumber()
        • Parsing via indexer
            • Not recommended
   • DataContractJsonSerializer is also available
Searching on Flickr
using the HttpClient
class
DEMO
Credential support with REST
services
• If REST service requires authentication , WinRT will
  support it
• Some samples:

    HttpClientHandler handler = new HttpClientHandler();
    handler.UseDefaultCredentials = true;
    HttpClient client = new HttpClient(handler);
        using (var handler = new HttpClientHandler
        {
               Credentials = ...
        })
        using (var client = new HttpClient(handler))
        {
            var result = await client.GetAsync(...);
        }
Secure REST
communication
DEMO
Working with oData
services
What is oData?

• Open Data Protocol
• Design goals ...
   • Invent as little as possible
   • Very low barrier of entry
• OData is a RESTful protocol
• Builds on HTTP and AtomPub
• Defines ...
   •   XML + JSON data representation
   •   Addressing scheme
   •   Query operators
   •   Metadata
Sample URIs

• http://odata.netflix.com/Catalog/
   • AtomPub service document, list of all collections
• http://odata.netflix.com/Catalog/Genres
   • all entries of a collection
• http://.../Catalog/Genres('Adventures')
   • one entry by PK
• http://.../Catalog/Genres('Adventures')/Name
   • one property as XML
• http://.../Catalog/Genres('Adventures')/Name/$value
   • only the value
Navigation

• http://.../Catalog/Genres('Adventures')/Titles
   • related entities
• http://.../Catalog/Genres('Adventures')/$links/Title
  s
   • only the links
• http://.../Catalog/Genres('Adventures')/Titles/$cou
  nt
   • count
Queries

• ... /Titles?$filter=AverageRating gt 4
   • filters
• ... /Titles?$orderby=AverageRating desc,
  ReleaseYear asc
   • sorting
• .../Titles?$select=ShortName, ReleaseYear
   • projection
• Paging support: $top, $skip, $skiptoken,
  $inlinecount
oData and WinRT

• There’s an OData client library available
• Requires servers that comply with oData v1-v3
• Support for Add Reference since RC
   • Previously we had to use the DataSvcUtil tool to
     generate the proxy
   • Still works if you want complete control over the proxy
     generation
Working with oData
services
DEMO
Syndication
Syndication in general

• Real Simple Syndication
• RSS feeds expose information from sites mostly through
  XML
• Feed is a list of syndication entries
   •   Post
   •   Author
   •   Data
   •   Links
   •    Fixed set of elements
• Parsing it is possible
   • Manually (if you like to hurt yourself…)
   • Through a third-party library
Syndication in WinRT

   • WinRT has the Windows.Web.Syndication namespace
       •   Contains SyndicationFeed and SyndicationClient classes
       •   Allows downloading feed asynchronously
       •   Can be provided with credentials if source requires them
       •   Supports
            • Atom 0.3 and 1.0
            • RSS 0.91, 0.92, 1.0 and 2.0)
       • Returns items in an object model
var    • Async (Task-based)
   client = new SyndicationClient();
SyndicationFeed feed = await client.RetrieveFeedAsync(“<My RSS Feed>”);
Syndication
DEMO
Background transfers
Background transfers

• Just like Windows Phone 7, only 1 app can be the
  main app
• Can be annoying if your app downloads files
   • User can’t switch away or the download is interrupted
• Windows.Networking.BackgroundTransfer has a
  BackgroundDownloader
   • Creates DownloadOperation instances
      • Can be paused, resumed...
Background transfers

• Support for
   • Credentials
   • Custom headers via SetRequestHeader
      • Use for authentication methods such as cookies, forms-based
        authentication...
   • Progress reporting
• Managed through separate process:
  BackgroundTransferHost.exe
   • Keeps running in the background
Background transfers
DEMO
Tiles interactions
Types of notifications

• Local (from the app code)
   • Can only be used when the app is running
   • Useful for tile updates (not that useful for toasts)
• Scheduled
   • Update at specific time
   • Useful for tiles and toasts


• Periodic updates

• Push notifications
Periodic tile updates
Periodic tile updates

• Poor man’s live tiles
• Require nothing more than a service that returns
  XML of a tile/badge update
• Great for distributing updates with wide audience
Periodic tile updates

• Setting it up:
   • Build a service that returns an XML string
   • Build a Metro app that calls the service and sets up periodic
     tile/badge updates
       • TileUpdater.StartPeriodicUpdate should be called with every start
         of the application
       • Service should update after about the same amount of time
         polling happens
       • If service is not available, Windows will retry only at the next
         interval
       • Service can be http or https
       • App must declare internet capability
• No support for tile update queueing
• Don’t use it for breaking news!
Periodic Tiles
DEMO
Push Notifications
Types of notifications

• Local (from the app code)
   • Can only be used when the app is running
   • Useful for tile updates (not that useful for toasts)
• Scheduled
   • Update at specific time
   • Useful for tiles and toasts
• Periodic
   • Update at specific interval
   • Poll a cloud service for content
   ...?

• Push notifications are the missing link
Push notifications over WNS

• WNS = Windows Notification Service
• Allows delivery of tile and toast XML messages over the
  wire
   • Can arrive when the app isn’t running
   • Create background processing without processing
       • Happens on the server
• Transparent process for the developer
• Free services
   • Cloud-based so no worries on scalability
   • Easily updates millions of devices
   • Register your app for now via
     https://manage.dev.live.com/build
WNS architecture

                   1. Request Channel URI
                   2. Register with your Cloud Service
                   3. Authenticate & Push Notification
Push notifications using Azure

• What we need
   • Secure, web based API for channel URI registration
   • Persistent storage of channel URI
   • Storage for tile and toast images
• What Azure offers us
   • Windows Azure Compute
      • Web Role
      • Full IIS support
      • WCF REST and ASP.NET MVC
   • Windows Azure Storage
      • Table Storage
      • Blob Storage
Push notifications
DEMO
Authenticating using
the WebAuthBroker
The WebAuthBroker class

• The web authentication broker provides a set of
  APIs and the infrastructure for apps to use Internet
  authentication and authorization protocols such as
  Oauth
   • When an app calls the web authentication broker, the
     user gets a dialog box in which the necessary webpages
     are rendered to sign in
   • After the user completes those steps, the dialog box
     goes away and the user continues with the app
The WebAuthBroker class
Benefits of the WebAuthBroker

• An easy-to-use programming interface that frees
  the app developer from hosting a browser control
  within their own app
• User credentials that are isolated from the app
• Native support for single sign-on with online
  providers
   •   Twitter
   •   Facebook
   •   Flickr
   •   …
How the WebAuthBroker
 works
• The web authentication broker is the facilitator between
  your app and authentication
• It consists of a set of APIs, a broker, and a web host.
   • Your app uses the APIs to communicate with the broker.
   • The broker creates a new web host process in a separate app
     container
   • The broker communicates with the app, assembles the UI and
     controls the lifecycle of the web authentication host
   • The web authentication host renders the pages from the online
     provider's website
Authenticating using
the WebAuthBroker
DEMO
Using the Live SDK in
your Windows 8 apps
Live SDK Integration

• Using the Live SDK, we can, from WinRT apps:
   • Leverage SSO functionality
   • Access data in SkyDrive
   • Integrate with Hotmail/Outlook and Messenger
• Requires the Live SDK 5.0 to be installed on your system
• Application needs to be registered with Windows Live
   • http://manage.dev.live.com/build
   • Only need the package name
• Requires that you are signed in with a Live ID/Microsoft
  account
   • We can log in using a live account or a local account
   • It’s possible to switch between the two
Live SDK Integration

• The device has to be trusted
   • In the screenshot below, this hasn’t been done yet 
To integrate…

     • We can use some of the built-in controls in the SDK
<live:SignInButton Name="MySignInButton" Scopes="wl.signin wl.basic wl.contacts_create"/>

     • Scope
          • A scope grants a permission level
          • Can be:
              • wl.signin
                   • Single sign-in behavior
              • wl.basic
                   • Read access to a user's basic profile info. Also enables read access to a user's
                     list of contacts
              • wl.contacts_create
                   • Creation of new contacts in the user's address book
              • wl.calendars_update
                   • Read access to a user's personal, preferred, and business email addresses
              • …
              • Complete list at http://msdn.microsoft.com/en-
                us/library/live/hh243646.aspx
Accessing SkyDrive from your
apps
• Windows 8 integrates with SkyDrive (cloud)
• Metro Apps can use SkyDrive through the Live SDK
   • Enables single sign-on using your Microsoft account
      • Don’t bother the user asking to login with every app
      • App automatically knows who you are
      • Called the easy sign-in
• Users can use the machine with their Microsoft
  account
   • Apps can benefit from this as well using Live SDK
   • User needs to grant permission though (once)
Using the Live SDK in
your Windows 8 apps
DEMO
Using roaming data in
your applications
Roaming data

• Users can personalize their devices and settings
• Windows and the built-in apps create a “connected”
  experience
   • Configure once, use everywhere
• Roaming application data makes creating this for us very
  easy
   • App data can be local, roaming or temporary
   • Roaming will make sure that the data is synced to the cloud and
     other devices where the Microsoft account uses the particular
     app
Roaming data

• What to place in roaming data?
   • Data that is relevant to the app that created it
       •   Settings
       •   Temporary document
       •   Level in a game
       •   App state
       •   Context
• Data that should not be placed in roaming data
   • Data that can be read/shared with other apps
   • Documents, pictures, exported data
   • Data that should be exported to SkyDrive
• Limit is currently 100k
   • Preserve battery and performance
   • Can be checked using the RoamingStorageQuota class
   • If limit is surpassed, no data will be synced at all
       • It’s vital to only sync URIs instead of full pages
Example of roaming data

     • RSS reader app where the user can save how many
       items he wants to see on his screen
Windows.Storage.ApplicationData.Current.RoamingSettings.Values[“ItemsPerPage”] = 10;

     • If you want to save the last article ID and want to
       create a continuous experience, name the setting
       HighPriority


Windows.Storage.ApplicationData.Current.RoamingSettings.Values[“HighPriority”] =
currentFeedId;
Example of roaming data

      • If more than one setting need to be synced
        together, we can use a CompositeSettingValue
Windows.Storage.ApplicationDataCompositeValue currentFeed =
new Windows.Storage.ApplicationDataCompositeValue();
currentFeed.Insert(“CurrentFeedId”, currentFeedId);
currentFeed.Insert(“CurrentFeedPage”, currentFeedPage);
Windows.Storage.ApplicationData.Current.RoamingSettings.Values[“HighPriority”] =
currentFeed;



      • With the app running, the app can register for the
        DataChanged event on the ApplicationData class
          • Will fire when the application data has changed
Some best practices around
roaming data
• Only works with a Microsoft account
• The device has to be trusted before roaming data
  will work
• Don’t use it for simultaneous use of applications on
  more than one device at a time
   • Last save wins
• Write often-changing only every now and then
   • Don’t use it to constantly write the location within a
     song
   • Writing too often can result in the device being locked-
     out for a certain amount of time
Using roaming data in
your applications
DEMO
Working with sockets
Types of socket communication in
WinRT
• StreamSocket - Used to support network communication
  using a TCP stream socket
• StreamSocketListener - Used to support listening for an
  incoming network connection using a TCP stream socket
• DatagramSocket - Used to support network communication
  using a UDP datagram socket
• MessageWebSocket - Used to support network
  communication that allows reading and writing whole
  messages using a WebSocket
• StreamWebSocket - Used to support network
  communication that allows reading and writing streams
  using a WebSocket

• All live in the Windows.Networking.Sockets namespace
When and when not to use
sockets
Requirement                                       Solution

Connects to a network service that uses an        TCP or UDP sockets
existing protocol (SMTP, POP, IMAP, or MAPI
for mail, for example) that is not directly
supported by other networking features

Connects to another machine on the same           TCP or UDP sockets
local network



Requires a simple requestresponse protocol       Representational State Transfer (REST) APIs
that can communicate through HTTP proxies         that are available using C#, VB.NET, and C++



Requires socket-like semantics (asynchronous,     WebSockets
bi-directional transfers) to connect across the
Web, including through HTTP proxies.
TCP Sockets
TCP Sockets

• TCP and UDP can be used to send and receive data in
  WinRT apps
• Based on classes from the
  Windows.Networking.Sockets namespace
   • StreamSocket
   • StreamSocketListener
   • DatagramSocket
• Support for
   • Making client connections
   • Listening for connections
   • Operating as a server, or for both client and server operations
TCP Sockets

• Steps to get TCP sockets working in your Metro app
   • Use the StreamSocket class to create a TCP socket
   • ConnectAsync on the StreamSocket class allows making a
     network connection to a TCP network server
   • Streams.DataWriter allows sending data to the server
       • Basically allows writing common types on a stream
   • Streams.DataReader allows reading data from a server
       • Basically allows reading common types from a stream
• StreamSocket object can be configured to use SSL/TLS
  for communications between the client and the server.
   • This support for SSL/TLS is limited to using the StreamSocket
     object as the client in the SSL/TLS negotiation
Using the StreamSocket

• This class enables network communication using a TCP
  stream socket
• What you can do with the StreamSocket
   • After instantiation of the StreamSocket, get a StreamSocketControl
     object using the Control property
         • Allows setting any properties on the StreamSocketControl object before
           calling one of the ConnectAsync methods
   • Use one of the ConnectAsync methods to establish a connection
     with the remote endpoint
         • Can be configured for use with SSL
   •   Get the OutputStream property to write data to the remote host
   •   Get the InputStream property to read data from the remote host
   •   Read and write data as needed
   •   Call the Close method to abort any pending operations
         • Releases all unmanaged resources associated with the StreamSocket
           object
Using the
StreamSocketListener
• This class enables listening for an incoming network
  connection using a TCP stream socket and accepting the
  connection
• What you can do with the StreamSocketListener
   • After instantiation of the StreamSocketListener, use the Control
     property to retrieve a StreamSocketListenerControl object
       • Can be used to set the socket quality of service
   • Assign the ConnectionReceived event to an event handler
   • Call the BindServiceNameAsync or BindEndpointAsync method to
     bind to a local TCP port or service name
   • After an incoming connection is received, use the
     StreamSocketListenerConnectionReceivedEventArgs object to
     retrieve the Socket property with the StreamSocket object created
   • Use the StreamSocket object to send and receive data
   • Call the Close method to stop listening for and accepting incoming
     network connections
       • Releases all unmanaged resources associated with the
         StreamSocketListener object.
TCP Sockets
DEMO
WebSockets
What’s a WebSocket?

• The WebSocket Protocol defines a mechanism for
  two-way communication between a client and a
  server.
  • To establish a WebSocket connection, a specific, HTTP-
    based handshake is exchanged between the client and
    the server.
  • If successful, the application-layer protocol is
    "upgraded" from HTTP to WebSockets, using the
    previously established TCP connection. Once this
    occurs, HTTP is completely out of the picture
     • Data can be sent or received using the WebSocket protocol by
       either endpoint at any time, until the WebSocket connection is
       closed
  • Only works when the server has a WebSocket
Two types of WebSockets
   exist
MessageWebSocket                       StreamWebSocket
                                       Suitable for scenarios in which large
Suitable for typical scenarios where
                                       files (such as photos or movies) are
messages are not extremely large
                                       being transferred

Enables notification that an entire Allows sections of a message to be
WebSocket message has been received read with each read operation.

Supports both UTF-8 and binary
                                       Supports only binary messages
messages
Using WebSockets
from a Metro style
application
DEMO
Summary

• Windows 8 supports many types of services
• Most common including WCF, ASMX, oData work
  similarly to Silverlight
• Async/await pattern makes development easier
• More complex types including oAuth and sockets
  are pretty easy using WinRT API
• Support for security
Q&A
Thanks!
Windows 8,
     Metro apps
and the outside world
              Gill Cleeren
   Microsoft Regional Director & MVP
              Telerik MVP

Weitere ähnliche Inhalte

Was ist angesagt?

Xplore Group - Flashtalk (Fabric8, Neo4j, GraphQL, OpenID Connect)
Xplore Group - Flashtalk (Fabric8, Neo4j, GraphQL, OpenID Connect)Xplore Group - Flashtalk (Fabric8, Neo4j, GraphQL, OpenID Connect)
Xplore Group - Flashtalk (Fabric8, Neo4j, GraphQL, OpenID Connect)Dries Elliott
 
High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016Vlad Mihalcea
 
Infinum Android Talks #09 - DBFlow ORM
Infinum Android Talks #09 - DBFlow ORMInfinum Android Talks #09 - DBFlow ORM
Infinum Android Talks #09 - DBFlow ORMInfinum
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overviewukdpe
 
Advance java session 20
Advance java session 20Advance java session 20
Advance java session 20Smita B Kumar
 
WebObjects Optimization
WebObjects OptimizationWebObjects Optimization
WebObjects OptimizationWO Community
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel.NET Conf UY
 
Securing Your MongoDB Deployment
Securing Your MongoDB DeploymentSecuring Your MongoDB Deployment
Securing Your MongoDB DeploymentMongoDB
 
Test driving Azure Search and DocumentDB
Test driving Azure Search and DocumentDBTest driving Azure Search and DocumentDB
Test driving Azure Search and DocumentDBAndrew Siemer
 
Scaling a MeteorJS SaaS app on AWS
Scaling a MeteorJS SaaS app on AWSScaling a MeteorJS SaaS app on AWS
Scaling a MeteorJS SaaS app on AWSBrett McLain
 
MongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless WorldMongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless WorldMongoDB
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkStefano Paluello
 
Steve Jones - Encrypting Data
Steve Jones - Encrypting DataSteve Jones - Encrypting Data
Steve Jones - Encrypting DataRed Gate Software
 
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.Oleg Shanyuk
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajaxNir Elbaz
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-CJuio Barros
 

Was ist angesagt? (20)

Xplore Group - Flashtalk (Fabric8, Neo4j, GraphQL, OpenID Connect)
Xplore Group - Flashtalk (Fabric8, Neo4j, GraphQL, OpenID Connect)Xplore Group - Flashtalk (Fabric8, Neo4j, GraphQL, OpenID Connect)
Xplore Group - Flashtalk (Fabric8, Neo4j, GraphQL, OpenID Connect)
 
High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016
 
Infinum Android Talks #09 - DBFlow ORM
Infinum Android Talks #09 - DBFlow ORMInfinum Android Talks #09 - DBFlow ORM
Infinum Android Talks #09 - DBFlow ORM
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 
Advance java session 20
Advance java session 20Advance java session 20
Advance java session 20
 
WebObjects Optimization
WebObjects OptimizationWebObjects Optimization
WebObjects Optimization
 
Ajax and PHP
Ajax and PHPAjax and PHP
Ajax and PHP
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
Securing Your MongoDB Deployment
Securing Your MongoDB DeploymentSecuring Your MongoDB Deployment
Securing Your MongoDB Deployment
 
Test driving Azure Search and DocumentDB
Test driving Azure Search and DocumentDBTest driving Azure Search and DocumentDB
Test driving Azure Search and DocumentDB
 
Scaling a MeteorJS SaaS app on AWS
Scaling a MeteorJS SaaS app on AWSScaling a MeteorJS SaaS app on AWS
Scaling a MeteorJS SaaS app on AWS
 
How fast is it?
How fast is it?How fast is it?
How fast is it?
 
MongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless WorldMongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless World
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net Framework
 
Steve Jones - Encrypting Data
Steve Jones - Encrypting DataSteve Jones - Encrypting Data
Steve Jones - Encrypting Data
 
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and Typescript
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-C
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 

Ähnlich wie Windows 8 Apps and the Outside World

Collector Web Services
Collector Web ServicesCollector Web Services
Collector Web Servicespublisyst
 
ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2Jaliya Udagedara
 
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
The server side story:  Parallel and Asynchronous programming in .NET - ITPro...The server side story:  Parallel and Asynchronous programming in .NET - ITPro...
The server side story: Parallel and Asynchronous programming in .NET - ITPro...Panagiotis Kanavos
 
Utilizing the open ntf domino api
Utilizing the open ntf domino apiUtilizing the open ntf domino api
Utilizing the open ntf domino apiOliver Busse
 
Utilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino APIUtilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino APIOliver Busse
 
An Azure of Things, a developer’s perspective
An Azure of Things, a developer’s perspectiveAn Azure of Things, a developer’s perspective
An Azure of Things, a developer’s perspectiveBizTalk360
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.Andrey Oleynik
 
What's New in .Net 4.5
What's New in .Net 4.5What's New in .Net 4.5
What's New in .Net 4.5Malam Team
 
Service stack all the things
Service stack all the thingsService stack all the things
Service stack all the thingscyberzeddk
 
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPRafal Gancarz
 
Exploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices💡 Tomasz Kogut
 
Architecting for Microservices Part 2
Architecting for Microservices Part 2Architecting for Microservices Part 2
Architecting for Microservices Part 2Elana Krasner
 
Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)Igalia
 
透過Amazon CloudFront 和AWS WAF來執行安全的內容傳輸
透過Amazon CloudFront 和AWS WAF來執行安全的內容傳輸透過Amazon CloudFront 和AWS WAF來執行安全的內容傳輸
透過Amazon CloudFront 和AWS WAF來執行安全的內容傳輸Amazon Web Services
 
From the Trenches: Effectively Scaling Your Cloud Infrastructure and Optimizi...
From the Trenches: Effectively Scaling Your Cloud Infrastructure and Optimizi...From the Trenches: Effectively Scaling Your Cloud Infrastructure and Optimizi...
From the Trenches: Effectively Scaling Your Cloud Infrastructure and Optimizi...Allan Mangune
 
Utilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino APIUtilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino APIOliver Busse
 
Web Technologies in Java EE 7
Web Technologies in Java EE 7Web Technologies in Java EE 7
Web Technologies in Java EE 7Lukáš Fryč
 

Ähnlich wie Windows 8 Apps and the Outside World (20)

Windows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside worldWindows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside world
 
Collector Web Services
Collector Web ServicesCollector Web Services
Collector Web Services
 
ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2
 
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
The server side story:  Parallel and Asynchronous programming in .NET - ITPro...The server side story:  Parallel and Asynchronous programming in .NET - ITPro...
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
 
Utilizing the open ntf domino api
Utilizing the open ntf domino apiUtilizing the open ntf domino api
Utilizing the open ntf domino api
 
Utilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino APIUtilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino API
 
An Azure of Things, a developer’s perspective
An Azure of Things, a developer’s perspectiveAn Azure of Things, a developer’s perspective
An Azure of Things, a developer’s perspective
 
API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.
 
What's New in .Net 4.5
What's New in .Net 4.5What's New in .Net 4.5
What's New in .Net 4.5
 
Service stack all the things
Service stack all the thingsService stack all the things
Service stack all the things
 
Securing Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTPSecuring Microservices using Play and Akka HTTP
Securing Microservices using Play and Akka HTTP
 
App fabric introduction
App fabric introductionApp fabric introduction
App fabric introduction
 
Exploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices
 
Architecting for Microservices Part 2
Architecting for Microservices Part 2Architecting for Microservices Part 2
Architecting for Microservices Part 2
 
Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)Streams API (Web Engines Hackfest 2015)
Streams API (Web Engines Hackfest 2015)
 
透過Amazon CloudFront 和AWS WAF來執行安全的內容傳輸
透過Amazon CloudFront 和AWS WAF來執行安全的內容傳輸透過Amazon CloudFront 和AWS WAF來執行安全的內容傳輸
透過Amazon CloudFront 和AWS WAF來執行安全的內容傳輸
 
From the Trenches: Effectively Scaling Your Cloud Infrastructure and Optimizi...
From the Trenches: Effectively Scaling Your Cloud Infrastructure and Optimizi...From the Trenches: Effectively Scaling Your Cloud Infrastructure and Optimizi...
From the Trenches: Effectively Scaling Your Cloud Infrastructure and Optimizi...
 
[Struyf] Automate Your Tasks With Azure Functions
[Struyf] Automate Your Tasks With Azure Functions[Struyf] Automate Your Tasks With Azure Functions
[Struyf] Automate Your Tasks With Azure Functions
 
Utilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino APIUtilizing the OpenNTF Domino API
Utilizing the OpenNTF Domino API
 
Web Technologies in Java EE 7
Web Technologies in Java EE 7Web Technologies in Java EE 7
Web Technologies in Java EE 7
 

Mehr von Microsoft Developer Network (MSDN) - Belgium and Luxembourg

Mehr von Microsoft Developer Network (MSDN) - Belgium and Luxembourg (20)

Code in the Cloud - Ghent - 20 February 2015
Code in the Cloud - Ghent - 20 February 2015Code in the Cloud - Ghent - 20 February 2015
Code in the Cloud - Ghent - 20 February 2015
 
Executive Summit for ISV & Application builders - January 2015
Executive Summit for ISV & Application builders - January 2015Executive Summit for ISV & Application builders - January 2015
Executive Summit for ISV & Application builders - January 2015
 
Executive Summit for ISV & Application builders - Internet of Things
Executive Summit for ISV & Application builders - Internet of ThingsExecutive Summit for ISV & Application builders - Internet of Things
Executive Summit for ISV & Application builders - Internet of Things
 
Executive Summit for ISV & Application builders - January 2015
Executive Summit for ISV & Application builders - January 2015Executive Summit for ISV & Application builders - January 2015
Executive Summit for ISV & Application builders - January 2015
 
Code in the Cloud - December 8th 2014
Code in the Cloud - December 8th 2014Code in the Cloud - December 8th 2014
Code in the Cloud - December 8th 2014
 
Adam azure presentation
Adam   azure presentationAdam   azure presentation
Adam azure presentation
 
release management
release managementrelease management
release management
 
cloud value for application development
cloud value for application developmentcloud value for application development
cloud value for application development
 
Modern lifecycle management practices
Modern lifecycle management practicesModern lifecycle management practices
Modern lifecycle management practices
 
Belgian visual studio launch 2013
Belgian visual studio launch 2013Belgian visual studio launch 2013
Belgian visual studio launch 2013
 
Windows Azure Virtually Speaking
Windows Azure Virtually SpeakingWindows Azure Virtually Speaking
Windows Azure Virtually Speaking
 
Inside the Microsoft TechDays Belgium Apps
Inside the Microsoft TechDays Belgium AppsInside the Microsoft TechDays Belgium Apps
Inside the Microsoft TechDays Belgium Apps
 
TechDays 2013 Developer Keynote
TechDays 2013 Developer KeynoteTechDays 2013 Developer Keynote
TechDays 2013 Developer Keynote
 
Windows Phone 8 Security Deep Dive
Windows Phone 8 Security Deep DiveWindows Phone 8 Security Deep Dive
Windows Phone 8 Security Deep Dive
 
Deep Dive into Entity Framework 6.0
Deep Dive into Entity Framework 6.0Deep Dive into Entity Framework 6.0
Deep Dive into Entity Framework 6.0
 
Applied MVVM in Windows 8 apps: not your typical MVVM session!
Applied MVVM in Windows 8 apps: not your typical MVVM session!Applied MVVM in Windows 8 apps: not your typical MVVM session!
Applied MVVM in Windows 8 apps: not your typical MVVM session!
 
Building SPA’s (Single Page App) with Backbone.js
Building SPA’s (Single Page App) with Backbone.jsBuilding SPA’s (Single Page App) with Backbone.js
Building SPA’s (Single Page App) with Backbone.js
 
Deep Dive and Best Practices for Windows Azure Storage Services
Deep Dive and Best Practices for Windows Azure Storage ServicesDeep Dive and Best Practices for Windows Azure Storage Services
Deep Dive and Best Practices for Windows Azure Storage Services
 
Building data centric applications for web, desktop and mobile with Entity Fr...
Building data centric applications for web, desktop and mobile with Entity Fr...Building data centric applications for web, desktop and mobile with Entity Fr...
Building data centric applications for web, desktop and mobile with Entity Fr...
 
Bart De Smet Unplugged
Bart De Smet UnpluggedBart De Smet Unplugged
Bart De Smet Unplugged
 

Windows 8 Apps and the Outside World

  • 1. Windows 8 apps and the outside world Gill Cleeren Microsoft Regional Director & MVP Telerik MVP
  • 2. About myself... • Gill Cleeren • .NET Architect @Ordina (www.ordina.be) • Microsoft Regional Director • Silverlight MVP • Speaker (TechDays, TechEd, DevReach, DevDays, NDC Norway, Telerik Usergroup tours...) • Visug user group lead (www.visug.be) • Author: • Silverlight 4 Data and services cookbook • Silverlight 5 Data and services cookbook • Blog: www.snowball.be • Email: gill@snowball.be • Twitter: @gillcleeren
  • 3. Silverlight 5 Data and Services Cookbook available! • Updated for Silverlight 5 • Over 115 recipes (that’s 30 extra!) • Extended to about 700 pages • (That’s 250 extra!) • Covering WP7, MVVM, RIA Services and much more! • More info: http://bit.ly/SL5DataAndServices
  • 4. Agenda • Accessing data behind a service • Working with WCF and ASMX services • Working with REST services • Accessing oData services • Syndication with RSS • Background transfers • Tiles interactions • Periodic tile updates • Push notifications • Authenticating with Twitter and Facebook using the WebAuthBroker • Using the Live SDK in your Windows 8 apps • Using roaming data in your applications • Working with sockets • TCP sockets • WebSockets
  • 5. What we aren’t covering today • ControlChannelTrigger • Raw notifications • Azure
  • 7. Working with services to access data • Service communication is always done asynchronous • In Silverlight, this was done using a callback • In C#5, we got the async/await keywords • Fully supported in Metro/WinRT development • await keyword makes things easier • Doesn’t block UI thread • Doesn’t require the ugly Dispatcher.BeginInvoke(() => …); • Getting data in a Metro application is a 3-step process • Calling the service asynchronous • Receiving and parsing the data • Using the data, for example in a data-binding scenario
  • 8. Working with services to access data • Working with services is preferred in most cases • Relational databases should be behind a service • Local app storage • App has its own storage directory • Can access local file system • Not the focus of this talk!
  • 9. Working with services • Windows 8 supports all kinds of services • ASMX • WCF • REST (JSON or XML) • RSS (later in this talk) • Sockets (much later in this talk) • oData services (you get the drill, it’s also further in this talk…) • No WCF RIA Services support out-of-the-box though (so yes, that is NOT in this talk ) •…
  • 11. ASMX services (aka good old webservices) • ASMX services can be accessed without any change • Communication is done asynchronously • SOAP messages can be sent and received over ASMX services • From Visual Studio, use the default way of connecting with a service • Add service reference • Generates proxy • All Task-based! • Use proxy-class with the async/await keywords
  • 12. Accessing an ASMX service from Windows 8 DEMO
  • 13. WCF Services • What is supported? • Bindings: • BasicHttpBinding • NetTcpBinding • NetHttpBinding • CustomBinding • Binding elements: • BinaryMessageEncodingBindingElement • TextMessageEncodingBindingElement • ConnectionOrientedTransportBindingElement • SslStreamSecurityBindingElement • WindowsStreamSecurityBindingElement • TcpTransportBindingElement • Http(s)TransportBindingElement • TransportSecurityBindingElement
  • 14. WCF Services • What is supported • Encoding: • Text, Binary • Security modes: • None, Transport, TransportWithMessageCredential, TransportCredentialOnly (for BasicHttpBinding) • ClientCredentialType: • None, Basic, Digest, Negotiate, Ntlm, Windows • Transfer Mode: • Buffered, Streamed, StreamedRequest, and StreamedResponse • Serializers: • DataContractSerializer, DataContractJsonSerializer, XmlSerializer • Miscellaneous: • ChannelFactory • DuplexChannelFactory • CallbackBehavior
  • 15. Things to note when working with WCF (also goes for ASMX) • No XML config file code • Code gets generated in the Reference.cs file • No config edit possible  • Use the partial ConfigureEndpoint method • Only Task-based methods are available • Ensures there are no blocking calls • Is done by default • Specify Internet capability
  • 17. What about security for service communication? • WinRT supports sending credentials • When building service that expects credentials, generated code in Reference.cs will reflect this result.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly; result.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows; • https, custom validation are supported to enable TransportWithMessageCredential • Allows safe passing of username/password to service endpoint
  • 20. REST services • No more WebClient, replaced with HttpClient • Works with async • Located in System.Net • HttpClient defines • Get(Async) • Returns an HttpResponseMessage • Put(Async) • Post(Async) • Delete(Async)  RESTful!
  • 21. Parsing the response • XML • Linq-To-XML • XmlReader/XmlWriter • XmlSerializer • JSON: • Use the JsonObject and feed it the returned string • We can use the Parse() method • Throws error if the returned string is faulty or invalid • Also defines GetNamedString(), GetNamedNumber() • Parsing via indexer • Not recommended • DataContractJsonSerializer is also available
  • 22. Searching on Flickr using the HttpClient class DEMO
  • 23. Credential support with REST services • If REST service requires authentication , WinRT will support it • Some samples: HttpClientHandler handler = new HttpClientHandler(); handler.UseDefaultCredentials = true; HttpClient client = new HttpClient(handler); using (var handler = new HttpClientHandler { Credentials = ... }) using (var client = new HttpClient(handler)) { var result = await client.GetAsync(...); }
  • 26. What is oData? • Open Data Protocol • Design goals ... • Invent as little as possible • Very low barrier of entry • OData is a RESTful protocol • Builds on HTTP and AtomPub • Defines ... • XML + JSON data representation • Addressing scheme • Query operators • Metadata
  • 27. Sample URIs • http://odata.netflix.com/Catalog/ • AtomPub service document, list of all collections • http://odata.netflix.com/Catalog/Genres • all entries of a collection • http://.../Catalog/Genres('Adventures') • one entry by PK • http://.../Catalog/Genres('Adventures')/Name • one property as XML • http://.../Catalog/Genres('Adventures')/Name/$value • only the value
  • 28. Navigation • http://.../Catalog/Genres('Adventures')/Titles • related entities • http://.../Catalog/Genres('Adventures')/$links/Title s • only the links • http://.../Catalog/Genres('Adventures')/Titles/$cou nt • count
  • 29. Queries • ... /Titles?$filter=AverageRating gt 4 • filters • ... /Titles?$orderby=AverageRating desc, ReleaseYear asc • sorting • .../Titles?$select=ShortName, ReleaseYear • projection • Paging support: $top, $skip, $skiptoken, $inlinecount
  • 30. oData and WinRT • There’s an OData client library available • Requires servers that comply with oData v1-v3 • Support for Add Reference since RC • Previously we had to use the DataSvcUtil tool to generate the proxy • Still works if you want complete control over the proxy generation
  • 33. Syndication in general • Real Simple Syndication • RSS feeds expose information from sites mostly through XML • Feed is a list of syndication entries • Post • Author • Data • Links •  Fixed set of elements • Parsing it is possible • Manually (if you like to hurt yourself…) • Through a third-party library
  • 34. Syndication in WinRT • WinRT has the Windows.Web.Syndication namespace • Contains SyndicationFeed and SyndicationClient classes • Allows downloading feed asynchronously • Can be provided with credentials if source requires them • Supports • Atom 0.3 and 1.0 • RSS 0.91, 0.92, 1.0 and 2.0) • Returns items in an object model var • Async (Task-based) client = new SyndicationClient(); SyndicationFeed feed = await client.RetrieveFeedAsync(“<My RSS Feed>”);
  • 37. Background transfers • Just like Windows Phone 7, only 1 app can be the main app • Can be annoying if your app downloads files • User can’t switch away or the download is interrupted • Windows.Networking.BackgroundTransfer has a BackgroundDownloader • Creates DownloadOperation instances • Can be paused, resumed...
  • 38. Background transfers • Support for • Credentials • Custom headers via SetRequestHeader • Use for authentication methods such as cookies, forms-based authentication... • Progress reporting • Managed through separate process: BackgroundTransferHost.exe • Keeps running in the background
  • 41. Types of notifications • Local (from the app code) • Can only be used when the app is running • Useful for tile updates (not that useful for toasts) • Scheduled • Update at specific time • Useful for tiles and toasts • Periodic updates • Push notifications
  • 43. Periodic tile updates • Poor man’s live tiles • Require nothing more than a service that returns XML of a tile/badge update • Great for distributing updates with wide audience
  • 44. Periodic tile updates • Setting it up: • Build a service that returns an XML string • Build a Metro app that calls the service and sets up periodic tile/badge updates • TileUpdater.StartPeriodicUpdate should be called with every start of the application • Service should update after about the same amount of time polling happens • If service is not available, Windows will retry only at the next interval • Service can be http or https • App must declare internet capability • No support for tile update queueing • Don’t use it for breaking news!
  • 47. Types of notifications • Local (from the app code) • Can only be used when the app is running • Useful for tile updates (not that useful for toasts) • Scheduled • Update at specific time • Useful for tiles and toasts • Periodic • Update at specific interval • Poll a cloud service for content ...? • Push notifications are the missing link
  • 48. Push notifications over WNS • WNS = Windows Notification Service • Allows delivery of tile and toast XML messages over the wire • Can arrive when the app isn’t running • Create background processing without processing • Happens on the server • Transparent process for the developer • Free services • Cloud-based so no worries on scalability • Easily updates millions of devices • Register your app for now via https://manage.dev.live.com/build
  • 49. WNS architecture 1. Request Channel URI 2. Register with your Cloud Service 3. Authenticate & Push Notification
  • 50. Push notifications using Azure • What we need • Secure, web based API for channel URI registration • Persistent storage of channel URI • Storage for tile and toast images • What Azure offers us • Windows Azure Compute • Web Role • Full IIS support • WCF REST and ASP.NET MVC • Windows Azure Storage • Table Storage • Blob Storage
  • 53. The WebAuthBroker class • The web authentication broker provides a set of APIs and the infrastructure for apps to use Internet authentication and authorization protocols such as Oauth • When an app calls the web authentication broker, the user gets a dialog box in which the necessary webpages are rendered to sign in • After the user completes those steps, the dialog box goes away and the user continues with the app
  • 55. Benefits of the WebAuthBroker • An easy-to-use programming interface that frees the app developer from hosting a browser control within their own app • User credentials that are isolated from the app • Native support for single sign-on with online providers • Twitter • Facebook • Flickr • …
  • 56. How the WebAuthBroker works • The web authentication broker is the facilitator between your app and authentication • It consists of a set of APIs, a broker, and a web host. • Your app uses the APIs to communicate with the broker. • The broker creates a new web host process in a separate app container • The broker communicates with the app, assembles the UI and controls the lifecycle of the web authentication host • The web authentication host renders the pages from the online provider's website
  • 58. Using the Live SDK in your Windows 8 apps
  • 59. Live SDK Integration • Using the Live SDK, we can, from WinRT apps: • Leverage SSO functionality • Access data in SkyDrive • Integrate with Hotmail/Outlook and Messenger • Requires the Live SDK 5.0 to be installed on your system • Application needs to be registered with Windows Live • http://manage.dev.live.com/build • Only need the package name • Requires that you are signed in with a Live ID/Microsoft account • We can log in using a live account or a local account • It’s possible to switch between the two
  • 60. Live SDK Integration • The device has to be trusted • In the screenshot below, this hasn’t been done yet 
  • 61. To integrate… • We can use some of the built-in controls in the SDK <live:SignInButton Name="MySignInButton" Scopes="wl.signin wl.basic wl.contacts_create"/> • Scope • A scope grants a permission level • Can be: • wl.signin • Single sign-in behavior • wl.basic • Read access to a user's basic profile info. Also enables read access to a user's list of contacts • wl.contacts_create • Creation of new contacts in the user's address book • wl.calendars_update • Read access to a user's personal, preferred, and business email addresses • … • Complete list at http://msdn.microsoft.com/en- us/library/live/hh243646.aspx
  • 62. Accessing SkyDrive from your apps • Windows 8 integrates with SkyDrive (cloud) • Metro Apps can use SkyDrive through the Live SDK • Enables single sign-on using your Microsoft account • Don’t bother the user asking to login with every app • App automatically knows who you are • Called the easy sign-in • Users can use the machine with their Microsoft account • Apps can benefit from this as well using Live SDK • User needs to grant permission though (once)
  • 63. Using the Live SDK in your Windows 8 apps DEMO
  • 64. Using roaming data in your applications
  • 65. Roaming data • Users can personalize their devices and settings • Windows and the built-in apps create a “connected” experience • Configure once, use everywhere • Roaming application data makes creating this for us very easy • App data can be local, roaming or temporary • Roaming will make sure that the data is synced to the cloud and other devices where the Microsoft account uses the particular app
  • 66. Roaming data • What to place in roaming data? • Data that is relevant to the app that created it • Settings • Temporary document • Level in a game • App state • Context • Data that should not be placed in roaming data • Data that can be read/shared with other apps • Documents, pictures, exported data • Data that should be exported to SkyDrive • Limit is currently 100k • Preserve battery and performance • Can be checked using the RoamingStorageQuota class • If limit is surpassed, no data will be synced at all • It’s vital to only sync URIs instead of full pages
  • 67. Example of roaming data • RSS reader app where the user can save how many items he wants to see on his screen Windows.Storage.ApplicationData.Current.RoamingSettings.Values[“ItemsPerPage”] = 10; • If you want to save the last article ID and want to create a continuous experience, name the setting HighPriority Windows.Storage.ApplicationData.Current.RoamingSettings.Values[“HighPriority”] = currentFeedId;
  • 68. Example of roaming data • If more than one setting need to be synced together, we can use a CompositeSettingValue Windows.Storage.ApplicationDataCompositeValue currentFeed = new Windows.Storage.ApplicationDataCompositeValue(); currentFeed.Insert(“CurrentFeedId”, currentFeedId); currentFeed.Insert(“CurrentFeedPage”, currentFeedPage); Windows.Storage.ApplicationData.Current.RoamingSettings.Values[“HighPriority”] = currentFeed; • With the app running, the app can register for the DataChanged event on the ApplicationData class • Will fire when the application data has changed
  • 69. Some best practices around roaming data • Only works with a Microsoft account • The device has to be trusted before roaming data will work • Don’t use it for simultaneous use of applications on more than one device at a time • Last save wins • Write often-changing only every now and then • Don’t use it to constantly write the location within a song • Writing too often can result in the device being locked- out for a certain amount of time
  • 70. Using roaming data in your applications DEMO
  • 72. Types of socket communication in WinRT • StreamSocket - Used to support network communication using a TCP stream socket • StreamSocketListener - Used to support listening for an incoming network connection using a TCP stream socket • DatagramSocket - Used to support network communication using a UDP datagram socket • MessageWebSocket - Used to support network communication that allows reading and writing whole messages using a WebSocket • StreamWebSocket - Used to support network communication that allows reading and writing streams using a WebSocket • All live in the Windows.Networking.Sockets namespace
  • 73. When and when not to use sockets Requirement Solution Connects to a network service that uses an TCP or UDP sockets existing protocol (SMTP, POP, IMAP, or MAPI for mail, for example) that is not directly supported by other networking features Connects to another machine on the same TCP or UDP sockets local network Requires a simple requestresponse protocol Representational State Transfer (REST) APIs that can communicate through HTTP proxies that are available using C#, VB.NET, and C++ Requires socket-like semantics (asynchronous, WebSockets bi-directional transfers) to connect across the Web, including through HTTP proxies.
  • 75. TCP Sockets • TCP and UDP can be used to send and receive data in WinRT apps • Based on classes from the Windows.Networking.Sockets namespace • StreamSocket • StreamSocketListener • DatagramSocket • Support for • Making client connections • Listening for connections • Operating as a server, or for both client and server operations
  • 76. TCP Sockets • Steps to get TCP sockets working in your Metro app • Use the StreamSocket class to create a TCP socket • ConnectAsync on the StreamSocket class allows making a network connection to a TCP network server • Streams.DataWriter allows sending data to the server • Basically allows writing common types on a stream • Streams.DataReader allows reading data from a server • Basically allows reading common types from a stream • StreamSocket object can be configured to use SSL/TLS for communications between the client and the server. • This support for SSL/TLS is limited to using the StreamSocket object as the client in the SSL/TLS negotiation
  • 77. Using the StreamSocket • This class enables network communication using a TCP stream socket • What you can do with the StreamSocket • After instantiation of the StreamSocket, get a StreamSocketControl object using the Control property • Allows setting any properties on the StreamSocketControl object before calling one of the ConnectAsync methods • Use one of the ConnectAsync methods to establish a connection with the remote endpoint • Can be configured for use with SSL • Get the OutputStream property to write data to the remote host • Get the InputStream property to read data from the remote host • Read and write data as needed • Call the Close method to abort any pending operations • Releases all unmanaged resources associated with the StreamSocket object
  • 78. Using the StreamSocketListener • This class enables listening for an incoming network connection using a TCP stream socket and accepting the connection • What you can do with the StreamSocketListener • After instantiation of the StreamSocketListener, use the Control property to retrieve a StreamSocketListenerControl object • Can be used to set the socket quality of service • Assign the ConnectionReceived event to an event handler • Call the BindServiceNameAsync or BindEndpointAsync method to bind to a local TCP port or service name • After an incoming connection is received, use the StreamSocketListenerConnectionReceivedEventArgs object to retrieve the Socket property with the StreamSocket object created • Use the StreamSocket object to send and receive data • Call the Close method to stop listening for and accepting incoming network connections • Releases all unmanaged resources associated with the StreamSocketListener object.
  • 81. What’s a WebSocket? • The WebSocket Protocol defines a mechanism for two-way communication between a client and a server. • To establish a WebSocket connection, a specific, HTTP- based handshake is exchanged between the client and the server. • If successful, the application-layer protocol is "upgraded" from HTTP to WebSockets, using the previously established TCP connection. Once this occurs, HTTP is completely out of the picture • Data can be sent or received using the WebSocket protocol by either endpoint at any time, until the WebSocket connection is closed • Only works when the server has a WebSocket
  • 82. Two types of WebSockets exist MessageWebSocket StreamWebSocket Suitable for scenarios in which large Suitable for typical scenarios where files (such as photos or movies) are messages are not extremely large being transferred Enables notification that an entire Allows sections of a message to be WebSocket message has been received read with each read operation. Supports both UTF-8 and binary Supports only binary messages messages
  • 83. Using WebSockets from a Metro style application DEMO
  • 84. Summary • Windows 8 supports many types of services • Most common including WCF, ASMX, oData work similarly to Silverlight • Async/await pattern makes development easier • More complex types including oAuth and sockets are pretty easy using WinRT API • Support for security
  • 85. Q&A
  • 87. Windows 8, Metro apps and the outside world Gill Cleeren Microsoft Regional Director & MVP Telerik MVP