Aracılığıyla paylaş


Networking in Silverlight for Windows Phone

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Silverlight for Windows Phone and Silverlight for the desktop have some networking differences. This topic describes the networking features in Silverlight for Windows Phone and some of the differences from Silverlight for the desktop.

This topic contains the following sections.

  • Supported Networking Features
  • Unsupported Networking Features
  • Header Support
  • Sockets
  • WCF in Silverlight for Windows Phone
  • Other Implementation Differences
  • Related Topics

Supported Networking Features

The following networking features are supported on Silverlight for Windows Phone.

Supported Networking Feature

Notes

Windows Communication Foundation (WCF)

For more information, see the WCF in Silverlight for Windows Phone section later in this topic.

HttpWebRequest

Six active Web service connections are allowed simultaneously. Additional requests are paused until a connection is available.

HttpWebRequest returns on the originating thread and the calls should be wrapped with a call to BeginInvoke when updating the UI.

WebClient

Six active Web service connections are allowed simultaneously. Additional requests are paused until a connection is available.

WebClient returns on the originating thread and the calls should be wrapped with a call to BeginInvoke when updating the UI thread.

Basic authentication

Basic authentication is supported for HttpWebRequest, WebClient, and in WCF service proxies.

System.Net.Sockets classes

TCP, UDP unicast, and UDP multicast are supported. For more information, see the Sockets section later in this topic.

Full header access on requests.

You can set several request headers in Silverlight for Windows Phone including the User-agent string. For more information, see the Header Support section later in this topic.

Unsupported Networking Features

The following networking features are not supported on Silverlight for Windows Phone.

Unsupported Networking Feature

Notes

Silverlight SDK networking features, including the following:

  • Duplex communication over HTTP

  • JSON serialization

  • RSS and Atom feeds (syndication)

Partial support for JSON serialization is provided by the DataContractJsonSerializer class.

Silverlight Toolkit networking features

Custom bindings

NoteNote:

For detailed information about unsupported types and members, and for information about using the class library reference documentation, see Class Library Support for Windows Phone.

Header Support

You can set the headers for requests to Web services similar to Silverlight for desktop applications. However, the list of headers you can set is slightly different on Silverlight for Windows Phone. The following is the list of headers that you can set in the HttpWebRequest.Headers or the WebClient.Headers collection when making a call to a Web service from a Silverlight for Windows Phone client.

  • AcceptCharset

  • AcceptEncoding

  • AcceptLanguage

  • Allow

  • Connection

  • ContentLength

  • ContentLocation

  • ContentRange

  • ContentType

  • Cookie

  • Date

  • Expect

  • Host

  • IfModifiedSince

  • KeepAlive

  • LastModified

  • MaxForwards

  • Referer

  • Te

  • Trailer

  • TransferEncoding

  • Upgrade

  • UserAgent

  • Via

  • Warning

The following example shows how to set the User-agent header using the Headers property.

request.Headers["UserAgent"]= "appname";

Header Properties in Silverlight for Windows Phone

In Silverlight for Windows Phone, you can set the Accept, ContentLength, ContentType, or UserAgent headers of an HttpWebRequest using the dedicated property for that header.

Important noteImportant Note:

You must set the Accept, header using the dedicated property. Attempting to set this header using the Headers collection will cause an ArgumentException to occur.

The following example shows how to set the User-agent header using the UserAgent property.

request.UserAgent = "appname";

In Windows Phone OS 7.1, if you compare the value of the ContentLength property to -1 to determine if the ContentLength header is set on an HttpWebResponse, you should compare the value as 64-bit and also 32-bit integers. To do this, you compare ContentLength with -1 as a 64-bit integer and then cast the value to a 32-bit integer and compare with -1. The following code example shows how to do this.

if (response.ContentLength == -1L || (Int32)response.ContentLength == -1)
{
   // The ContentLength header is not set. Handle this appropriately.
}

Sockets

TCP, UDP unicast, and UDP multicast are supported similar to the support in Silverlight 4. The following is the only known difference.

  • Setting SendBufferSize=0 on a socket message is not enabled in Windows Phone applications and throws a SocketException with the following message: An invalid argument was supplied.

For more information about how to use sockets with Windows Phone applications, see Sockets Overview for Windows Phone.

WCF in Silverlight for Windows Phone

The networking features in Silverlight for Windows Phone and Silverlight for the desktop are slightly different. Therefore, when you use WCF in Silverlight for Windows Phone, make sure that the service you are connecting to does not require that the client application use features that are not supported on Windows Phone. For more information, see Silverlight and WCF Feature Comparison and Silverlight Feature Introduction History Listed by Version.

Generating a Proxy Class

When you create a proxy class for a WCF service, you must do so at compile time. You cannot create a dynamic proxy. This is because the CreateChannel overloads are present, but not supported in Silverlight for Windows Phone. You can generate a compile-time proxy using slsvcutil.exe or the Add Service Reference feature in Visual Studio.

To generate a proxy using slsvcutil.exe:

  1. Ensure that you use the slsvcutil.exe included with Visual Studio 2010 Express for Windows Phone.

  2. Follow the steps described in Using SLsvcUtil.exe to Access a Service.

    TipTip:

    When you use slsvcutil.exe to generate proxies and reference an assembly with the /reference option, the Web service you are generating a proxy for should be compiled using the .NET Framework or Silverlight compiler. If you compile the Web service with the Windows Phone SDK and try to create a proxy with slsvcutil.exe, an exception will occur. In this case, use Add Service Reference in Visual Studio to generate the proxy.

    Caution noteCaution:

    If you encounter errors and you are not able to resolve them, make sure that you can access the Web service from a Silverlight browser-based application. If the issue is specific to Windows Phone, you may be able to find more specific help in the Windows Phone forums.

To generate a proxy using Add Service Reference:

  1. Use Add Service Reference in a Windows Phone project that was created by using the Windows Phone SDK.

    TipTip:

    The Add Service Reference function is provided by Microsoft.Silverlight.Phone.ServiceReference assembly that is available with the Windows Phone SDK. The Microsoft.Silverlight.ServiceReference assembly from the Silverlight SDK is not supported for use with Windows Phone applications.

    TipTip:

    You should not run Visual Studio as an administrator. If you run Visual Studio as an administrator and you create a proxy using Add Service Reference, errors will occur.

  2. Follow the steps described in How to: Access a Service from Silverlight.

    If you encounter errors and you are not able to resolve them, take the following steps:

    1. Stop and restart Visual Studio, and retry the scenario.

    2. Make sure that you can access the Web service from a Silverlight browser-based application. If the issue is specific to Windows Phone, you may be able to find more specific help in the Windows Phone forums.

    TipTip:

    If you are generating a proxy to an authentication Web service and a WCF service, always generate the proxy to the WCF service first, and then the authentication service second. If you generate the proxy to the authentication service first, the proxy for the WCF service may not generate correctly.

Implementation Differences for Calling WCF Services from Windows Phone Clients

There are a few implementation differences that you should be aware of when you call WCF services.

All BasicHttpSecurityMode values are supported. However, when you use the TransportWithMessageCredential value, you have to manually set the Basic authentication values for the Credentials property since UseDefaultCredentials specifies NTLM or digest authentication.

When you use OperationContext.Current.OutgoingMessageHeaders.Add to add headers to an outgoing Web service call, the headers will be overwritten when the call returns. This means that if you want to send the same headers for each Web service call, you need to add the headers each time you make a call.

Setting the MessageContractAttribute.IsWrapped property to false is not supported and will cause a service call to return null.

Calling a WCF Service using Basic Authentication

When you call a WCF service using basic authentication you need to set headers that contain the appropriate authentication information. The following code example shows an example of how to do this.

using (OperationContextScope contextScope = new OperationContextScope(svc.InnerChannel))
{
    byte[] bc = System.Text.Encoding.UTF8.GetBytes(@"username" + ":" + "password"); // the string passed after basic:
    HttpRequestMessageProperty httpProps = new HttpRequestMessageProperty();
    httpProps.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(bc);
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpProps;
    // call the service.
}
Using contextScope As New OperationContextScope(svc.InnerChannel)
    Dim bc As Byte() = 
        System.Text.Encoding.UTF8.GetBytes("username" & ":" & "password")
    'The string passed after basic:
    Dim httpProps As New HttpRequestMessageProperty()
    httpProps.Headers(HttpRequestHeader.Authorization) = "Basic " & 
        Convert.ToBase64String(bc)
    OperationContext.Current.OutgoingMessageProperties(
        HttpRequestMessageProperty.Name) = httpProps
    ' Call the service.
End Using

WCF Members that are Not Supported

Considerations for Using Windows Phone Emulator or a Device with WCF Services

There are some special considerations for the emulator or a device when you are testing applications that interact with WCF services.

  • When you use HTTPS to access a WCF service for a Windows Phone application, you should make sure the current date and time of the emulator or device is in sync with the date and time on the computer hosting the Web service. Typically this is the case, but when the emulator starts there is a delay before the date and time is set on it. You should wait 1-2 minutes after you start the emulator to make sure that the date and time is set correctly before you try to call a Web service.

  • If certificate installation is required by a Web service client, you will need to install the certificate on the device or emulator for the call to the service to return successfully. If a required certificate is not installed, the Web service may return a EndpointNotFoundException or ArgumentNullException.

  • When you are testing applications that call Web services through a proxy with the emulator, you do not have access to fully-qualified domain names.

Other Implementation Differences

The implementation of some networking features in Silverlight for Windows Phone differs from the implementation on other operating systems.

For more information related to supported features that might affect networking applications, see the following sections in Implementation Differences Between Silverlight and Silverlight for Windows Phone.

  • Streams

  • URIs

  • Paths

  • XML

System.Net.HttpWebRequest and System.Net.HttpWebResponse are abstract classes in Silverlight, but are not abstract in Silverlight for Windows Phone.

Some exceptions thrown by applications that use networking features are different in Silverlight for Windows Phone:

  • If you attempt to access a file from an FTP site, the application throws NullReferenceException instead of NotSupportedException.

  • MessageHeaders.CopyHeaderFrom displays the message Specified argument was out of the range of valid values instead of The value of this argument must fall in the range [lower bound] to [upper bound].

  • DataContractJsonSerializer.ReadObject throws SecurityException when MethodAccessException is thrown on other operating systems.