sticky
Accessing the Web Services with Silverlight FAQ

    Question

  • Accessing the Web Services with Silverlight FAQ

    Contents

    1.      How can I access the ASP.NET session in Silverlight?

    2.      How can I consume DataSet in Silverlight?

    3.      How can I handle WCF FaultException in Silverlight?

    4.      How can I change the client channel configuration without recompiling it?

    5.      How Can I consume RSS in Silverlight?

    6.      How can I push data from a server to Silverlight?

    7.      How can I solve the WCF deployment issue?

     

    1.   How can I access the ASP.NET session in Silverlight?

     

    One approach is to create a WCF with ASP.NET session enabled and then let Silverlight consume it.

    Please try the following steps to enable ASP.NET session on WCF:

    1.       Create a service contract, exposing a session query method. (To simplify, we just query string type session)

        [ServiceContract]

        public interface ISessionService

        {

            [OperationContract]

            string GetSessionString(string key)

        }

    2.       Create the WCF service class to implement our service contract, and then apply AspNetCompatibilityRequirementsAttribute on service class.

        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

        public class sessionwcf: ISessionService

        {

            public string GetSessionString(string key)

            {

                return HttpContext.Current.Session[key] as string;

            }

        }

     

    3.       In web.config, add the following line to enable aspNetCompatibility function.

       <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

    2.   How can I consume DataSet in Silverlight?

     

    Silverlight doesn’t support dataset, to consume dataset, please transform serialized DataSet XML to a certain collection type. Sladapter provides a good solution; please obtain more information from this thread.

    http://forums.silverlight.net/forums/t/16733.aspx

     

    3.   How can I handle WCF FaultException in Silverlight?

    Silverlight 3 supports WCF Soap fault programming model. However, by default, the WCF service returns fault message with HTTP 500 response code, which would not be accessible within Silverlight. One approach to solve this issue is to define the WCF endpoint behavior and insert MessageInspector to change the 500 message code to 200.

    Behavior code sample:

        public class SilverlightFaultBehavior : BehaviorExtensionElement, IEndpointBehavior

        {       

            public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)

            {

                SilverlightFaultMessageInspector inspector = new SilverlightFaultMessageInspector();

                endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);

            }

     

            public class SilverlightFaultMessageInspector : IDispatchMessageInspector

            {

                public void BeforeSendReply(ref Message reply, object correlationState)

                {

                    if (reply.IsFault)

                    {

                        HttpResponseMessageProperty property = new HttpResponseMessageProperty();

     

                        // Here the response code is changed to 200.

                        property.StatusCode = System.Net.HttpStatusCode.OK;

     

                        reply.Properties[HttpResponseMessageProperty.Name] = property;

                    }

                }

               

                public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)

                {

                    // Do nothing to the incoming message.

                    return null;

                }

            }

     

            // The following methods are stubs and not relevant.

            public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)

            {

            }

     

            public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)

            {

            }

     

            public void Validate(ServiceEndpoint endpoint)

            {

            }

     

            public override System.Type BehaviorType

            {

                get { return typeof(SilverlightFaultBehavior); }

            }

     

            protected override object CreateBehavior()

            {

                return new SilverlightFaultBehavior();

            }

     

        }

    To add this behavior in the WCF service config, please refer to this sample.

    <system.serviceModel>

        <extensions>

         <behaviorExtensions>

            <add name=”silverlightFaults”

                 type=”Microsoft.Silverlight.Samples.SilverlightFaultBehavior,

                 SilverlightFaultBehavior,

                 Version=1.0.0.0,

                 Culture=neutral,

                 PublicKeyToken=null”/>

          </behaviorExtensions>

        </extensions>

        <behaviors>

            <endpointBehaviors>

              <behavior name=”SilverlightFaultBehavior”>

                <silverlightFaults/>

              </behavior>

            </endpointBehaviors>

        </behaviors>

        <services>

            <service name=”Calculator.Web.Service”>

                <endpoint address=””

                          binding=”basicHttpBinding”

                          contract=”Calculator.Web.Service”

                          behaviorConfiguration=”SilverlightFaultBehavior” />

    </service>

      </services>

    </system.serviceModel>

     

    For more details about how to handle WCF faults in Silverlight, please read this article

    http://msdn.microsoft.com/en-us/library/dd470096(VS.95).aspx

     

    4.   How can I change the client channel configuration without recompiling it?

     

    Some users encountered an issue that when deploying the Silverlight applications they need to update the Silverlight service endpoint address and recompile Silverlight project.

    If we create service client by using configuration in “ServiceReferences.ClientConfig” file, then we could change the configuration without recompiling project.  Silverlight application file “xap” is of zip format, thus we can use the zip tool to unzip the xap file, find “ServiceReferences.ClientConfig” file, and then open and update endpoint configuration.

    If the Silverlight application and the service which Silverlight consumed are in same site, we could write code to refer to service address in Silverlight. For example:

                var client2 = new Service1Client(

                    new BasicHttpBinding(),

                    new EndpointAddress(

                        // endpoint address http://[site]/[subfolders]/Service1.svc

                        new Uri(

                            Application.Current.Host.Source,

                            "/[subfolders]/Service1.svc")));

     

    By doing this, we do not need to update the client endpoint address while deploying the website.

     

    5.   How Can I consume RSS in Silverlight?

     

    Here are the steps to consume RSS in Silverlight:

    1.       Download RSS resources by WebClient

    2.       Use SyndicationFeed to parse the downloaded RSS stream.

    Here is a thread discussing how to use Youtube API (RSS format) in Silverlight

    http://forums.silverlight.net/forums/p/110790/254912.aspx

     

    6.   How can I push data from a server to Silverlight?

     

    Sometimes, we need push data from a server to the Silverlight client. In this case, duplex service is useful. The traditional duplex solution is not suitable for Silverlight. To implement duplex communication, please use “PollingDuplexHttpBinding” type binding. See a complete sample at

    http://msdn.microsoft.com/en-us/library/dd470105(VS.95).aspx

     

    7.   How can I solve the WCF deployment issue?

     

    Some users encountered the WCF access issue after they deployed the Silverlight site on IIS.

    There are some tips that may help locate and fix the issue:

    ·         To get client side exception details, we could configure the serviceDebug behavior

    <serviceDebug includeExceptionDetailInFaults="true" />

    For security reasons, after debugging, please disable this behavior.

    ·         Use fiddler tool to capture the network traffic to check if it is the client or server who caused the issue, this would be useful to locate the root cause.

    ·         After deploying the Silverlight hosted site, the WCF service address may have changed. We need to change the client endpoint configuration to refer to new WCF address. If we encounter the cross-domain issue, then we need to deploy cross domain policy file at site root folder. For more information about cross-domain issues, please refer to this article.

    http://msdn.microsoft.com/en-us/library/cc645032(VS.95).aspx

    ·         After we have deployed WCF service on IIS, the account under which the service is running would change. If our application required permissions for specific resource such as read/write local file, database etc., then please grant the corresponding permission to the service running account.

    ·         You may find more advices for debugging at:

    http://forums.silverlight.net/forums/t/146423.aspx

    Wednesday, March 10, 2010 10:04 PM