How to set up an Authenticated Web Service for Windows Phone

image

Setting up an authenticated web service is recommended, as communication occurs over an HTTPS interface for better security. Authenticated web services do not have a daily limit on the number of push notifications they can send. Unauthenticated web services, on the other hand, are throttled at a rate of 500 push notifications per subscription per day. Additionally, authenticated web services are able to register a callback request, as described in How to: Set up a Callback Registration Request for Windows Phone. more here.

 

Learn more about Push Notification:


Handling and Troubleshooting WCF Faults in Silverlight

image

Shows you how to identfy the problems with your WCF services and how to fix them. He covers several topics including these:

  • Handling Faults: How to get exceptions propogated from the sderver to Silverlight e.g. using FaultBehavior (more detail about FaultBehavior go here @msdn)
  • How to use Fiddler to use with WCF  – replace localhost with ipv4.fiddler in SerivceReference.ClientConfig and Browser’s address bar
  • Using the new relative address feature in Silverlight 4’s ServiceReference.Clientconfig e.g. ..\xyz.svc

Via http://channel9.msdn.com/Shows/SilverlightTV/Silverlight-TV-46-Whats-Wrong-with-my-WCF-Service

Passing WCF Exception to Silverlight

Since it is not possible to catch regular exception from a WCF service in a silverlight application, there is another way to do it by using BehaviorExtensionElement.

1. On Server-side First create a behavior like this:

public class MyFaultBehavior : 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(MyFaultBehavior); }
        }
        protected override object CreateBehavior()
        {
            return new MyFaultBehavior();
        }
    }

2. On Server-side Modify you web.config:

	<system.serviceModel>
		<!--Add a behavior extension within the service model-->
		<extensions>
			<behaviorExtensions>
				<add name="myFault" type="SilverlightWCF.Web.MyFaultBehavior, SilverlightWCF.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
			</behaviorExtensions>
		</extensions>
		<behaviors>
			<!--Add a endpointBehavior below the behaviors-->
			<endpointBehaviors>
				<behavior name="myFaultBehavior">
					<myFault/>
				</behavior>
			</endpointBehaviors>
			<serviceBehaviors>
				<behavior name="SilverlightWCF.Web.MyCoolServiceBehavior">
					<serviceMetadata httpGetEnabled="true"/>
					<!--For debugging, it might be cool to have some more error information.
       to get this, set includeExceptionDetailInFaults to true-->
					<serviceDebug includeExceptionDetailInFaults="true"/>
				</behavior>
			</serviceBehaviors>
		</behaviors>
...
		<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
		<services>
			<service behaviorConfiguration="SilverlightWCF.Web.MyCoolServiceBehavior" name="SilverlightWCF.Web.MyCoolService">
				<!--Set the behaviorConfiguration of the endpoint-->
				<endpoint address="" binding="customBinding" bindingConfiguration="customBinding0" contract="SilverlightWCF.Web.MyCoolService" behaviorConfiguration="myFaultBehavior"/>
				<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
			</service>
		</services>
	</system.serviceModel>

3. On Server-side Throw you FaultException

        [OperationContract]
        public void Foo()
        {
            throw new FaultException("this is my Exception");
        }

4. On Client-side Catch the Exception like this:

        void serviceClient_FooCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                // In case of success
            }
            else if (e.Error is FaultException)
            {
                FaultException fault = e.Error as FaultException;
                string text =  e.Error.Message;
            }
        }

via http://www.codeproject.com/KB/silverlight/SilverlightWCFService.aspx

Configuring WCF Web Service Usage in Silverlight Clients

Absolute service addresses in .clientConfig

By default when you invoke Add Service Reference in Visual Studio, it will generate a .clientConfig file which contains the binding and address for the service you are trying to access. The problem is that the service address generated is always a absolute address, such as http://localhost:1234/Service1.svc. If you then take the web application containing the Silverlight .xap package out of Visual Studio and try to deploy it to a production machine, the absolute service address will no longer be correct, so the WCF calls will fail. The fix is simple, but annoying: when you deploy, you  have to unzip the .xap package, manually edit the .clientConfig to correct the address, then zip the .xap file back up.

Part of the solution was already shipped in Silverlight 4, and is described in this documentation topic (check the section “Configuring the Service Address”). This feature gives you the ability to specify relative service addresses such as address="../Service1.svc". However the problem is that Add Service Reference by default will still generate absolute addresses by default. So the proposed feature here is to make Add Service Reference generate relative addresses by default. This way the address will always be correct, as long as the .xap and the .svc file are moved together.

WCF RIA Services Essentials at codeplex

The RIA Services Essentials project contains sample applications/extensions demonstrating using and extending WCF RIA Services v1.

  • Book Club – It was written to demonstrate some aspects of writing a semi-real-worldish application (note that it is still very much a demo app), but more importantly, demonstrating how you can use RIA Services effectively by going beyond the basics.
  • Here is a list of what the application demonstrates:

  • Entity framework data model with one-to-many and many-to-many relationships as well as use of stored procedures
  • Local data model augmented/mixed with a web service-based data model (in this case Amazon).
  • CRUD and more (queries, insert, update, delete, as well as named update methods, and invoke methods)
  • Use of convention and configuration for identifying CRUD operations
  • Validation (field level, entity level, operation level, change-set scoped, server-only validation, async validation)
  • Custom authentication (i.e. using your DAL/user table, rather than asp.net membership)
  • Authorization (including custom authorization rules)
  • Using authentication service and your User object in server code
  • Usage of DomainServiceFactory
  • Exposing reference data
  • Presentation model for defining custom (non-DAL) types for use between client and server
  • Shared code between client and server for validation rules
  • Query limits, and caching
  • Using RIA Services with MVVM on the client
  • Adding computed properties on Entities on the client along with propagation of change notifications
  • "More" style paging (as seen for example on twitter.com)
  • Display of pending changes, validation errors
  • Reference data used to fill lookup dropdown lists.
  • Building RESTful application using SQL Azure, WCF, ADO.NET Data Service & Telerik OpenAccess WCF Wizard