Handwritten Text Recognition for manuscripts and early printed texts
Â
Windows 8 Metro apps and the outside world
1. Windows 8,
Metro apps
and the outside world
SILVERLIGHTSHOW.NET WEBINARS SERIES
GILL CLEEREN, 15th August 2012
www.snowball.be - gill.cleeren@ordina.be - @gillcleeren
2. Agenda
⢠Accessing data behind a service
⢠Working with WCF and ASMX services
⢠Working with REST services
⢠Accessing oData services
⢠Syndication with RSS
⢠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
⢠Setting the correct capabilities for network communication
4. 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
5. 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!
6. 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 ď)
ââŚ
8. 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. 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
13. 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
14. 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!
15. 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
16. 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(...);
}
18. 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
19. 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
22. oData and WinRT
⢠Currently, 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
24. 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
25. 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
â Async (Task-based)
var client = new SyndicationClient();
SyndicationFeed feed = await client.RetrieveFeedAsync(â<My RSS Feed>â);
27. 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
29. 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
â âŚ
30. 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
32. 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
33. Live SDK Integration
⢠The device has to be trusted
â In the screenshot below, this hasnât been done yet
ď
34. 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
35. 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)
37. 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
38. 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
39. 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;
40. 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
41. 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
43. 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
44. 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.
46. 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
47. 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
48. 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
49. 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.
51. 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
52. 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
54. Setting the correct capabilities for
network communication
⢠When building apps that need accessing services, we
need to set the correct capabilities
⢠Checklist
â Determine the direction of network access needed by the
app
⢠Outbound client-initiated requests
⢠Inbound unsolicited requests
⢠A combination of the two
â Determine the type of network resources that that app will
communicate with
⢠Trusted resources on a Home or Work network
⢠An app might need to communicate with resources on the Internet
⢠An app might need access to both types of network resources
â Configure the minimum-required networking isolation
capabilities in the app manifest
55. Network capabilities
⢠Not all apps require access to the network!
â Only enable the network capabilities for the apps that do!
â Windows 8 exposes several types of network access
⢠Network access requests are divided into two categories:
â Outbound client-initiated requests
⢠The app acts as the client and initiates network access
⢠The client app sends one or more requests to the server and the
server sends back a response
â Inbound unsolicited requests
⢠The app acts as a network server and listens for inbound network
requests from a remote computer
⢠The remote computer initiates network access by sending an initial
request to the app, which acts as server
⢠The remote computer sends one or more requests to the
app, which sends back one or more responses to the remote
computer
⢠An app that functions as a media server
56. Networking isolation capabilities
Capability Description
Provides outbound access to the Internet and
Internet (Client) networks in public places, like airports and
(internetClient in manifest) coffee shop. Most apps that require Internet
access should use this capability.
Gives the app inbound access from the Internet
and networks in public places like airports and
Internet (Client & Server) coffee shops. Inbound access to critical ports
(internetClientServer in manifest) are always blocked.
The internetClient capability will still need be
declared if outbound connectivity is required.
Gives the app inbound and outbound network
Private Networks (Client & Server) access at the user's trusted places, like home
(privateNetworkClientServer in manifest) and work. Inbound access to critical ports are
always blocked.
57. Some typical use cases of capabilities
Application Description
A Web client that only consumes content. This would
include apps that loads HTML from a website and apps internetClient
that uses RSS syndication or the AtomPub protocol.
A social network app. This includes an app that
consumes and produces content on a social network internetClient
site.
A peer to peer (p2p) app. This includes an app that
provide access to instant messenger or chat.
internetClientServer
An app for sharing in a home or work network. This
includes an app that accesses media or network privateNetworkClientServer
attached storage (NAS) content.
A line of business app at home or work. This includes an
app that acts as an HTTP client or uses sockets or privateNetworkClientServer
WebSockets.
A productivity app with networking features at home or
work. This includes a productivity app that accesses privateNetworkClientServer
network features.
58. Some typical use cases of capabilities (2)
Application Description
A game app that requires network access. internetClient
A multiplayer internet game app that does
matchmaking.
internetClient
A multiplayer game app that discovers players with
multicast discovery or using multicast.
internetClientServer
A multiplayer game app that uses the home or work
network. This includes an app that discovers players with privateNetworkClientServer
multicast discovery or is discovered using multicast.
A broadcasting app. This includes an app that receives
radio broadcasts over the Internet.
internetClient
59. 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
61. Windows 8,
Metro apps
and the outside world
SILVERLIGHTSHOW.NET WEBINARS SERIES
GILL CLEEREN, 15th August 2012
www.snowball.be - gill.cleeren@ordina.be - @gillcleeren