The Best Service Reference Strategy for Silverlight

by mgordon 12. June 2009 06:08

When first learning Silverlight, having often utilized the “Add Web Reference” functionality in Visual Studio in days gone by, I reached for the alluring “Add Service Reference” functionality when adding references to WCF services to my Silverlight projects. I encountered a few problems using this approach and began to search for a better way to reference WCF services.

Project Bloat

The first problem I noticed was the sheer number of files generated by Visual Studio when you add a service reference.  If you’re using source control (and you should be), any modification made to a service reference is going to delete several files and replace them with new ones.  When checking these changes into source control, it can sometimes be confusing trying to figure out how to get your source checked in in a valid state.

Reusing Referenced Assemblies

Second problem I found I was having was that I was often getting errors and warnings when adding or modifying a service reference.  These came in different flavors, but most all complained about the format of the WSDL being received from the service.  With some trial and error, I figured out that the problems were being caused by the default behavior of Visual Studio when adding a reference in respect to reusing types in referenced assemblies. When adding a service reference, the below dialog appears.

AddRef

If you click on the Advanced button, this dialog appears.

Advanced

By default, the “Reuse types in referenced assemblies” checkbox is checked and the “Reuse types in all referenced assemblies” radio button is selected.  If you’re having problems getting client proxies to generate for your services, try clearing the checkbox as this seemed to be the solution for me.

Location, Location, Location

The third problem I’ve had with adding references this way is probably the most important.  With the Add Web Reference I knew and loved, it was a fairly simple matter to modify the generated Reference.cs file to pull the URL for the web service endpoint from a configuration file.  But, when adding a service reference with visual studio, whatever endpoint you specify when adding the reference gets scattered through various of the generated files which makes manual modification extremely difficult.

When I’m working with a Silverlight project, I typically like to have all the services running locally while I’m developing to facilitate debugging and modification of the services which means that my service references need to be pointing to localhost.  Before I deploy, I have to go to each reference and reconfigure it to point to the production server which means that any modified version of my services have to already exist on the server and all this makes deployment a huge headache.  If my shop employed a full set of environments - dev, QA, staging, prod – I’m sure I’d go postal.

The Search for a Better Way

In thinking about the problem, I realized that what I needed was a simple way to generate a client proxy.  I could then build my address, binding and channel in code, pulling any of the necessary pieces of configuration from a config file.  My first thought was to create the proxy class using SvcUtil.exe.  I soon found, though, that the proxies generated by this tool are incompatible with Silverlight.  I then found out about a tool called SlSvcUtil.exe that generates proxies specifically for Silverlight.  Unfortunately, this tool is supposed to ship with Silverlight 3 and I’m still working in version 2.

For now, I’ve found two alternatives.  First is a bit of a hack, but still a fairly easy way to generate proxies that I found here.  Basically, this blog post suggests using the “Add Service Reference” functionality in Visual Studio to generate a reference.cs, saving that class and then deleting the service reference.  I also found an article by David Betz, here, that takes you through an excellent explanation of the details of the inner workings of WCF with Silverlight and suggests writing proxies by hand.

It’s good to have choices and I’m sure I can find circumstances where each approach will be beneficial.

Tags:

.Net | ASP.Net | Silverlight | WCF

Windows 7, Silverlight and the Unrecognized Element Exception

by mgordon 12. June 2009 04:22

I recently rebuilt my development laptop with Windows 7 and have been developing on it.  I have an existing Silverlight application that I have been deploying to a Windows Server 2003 machine and encountered some odd behavior after making modifications to in on the Windows 7 box and deploying it to the server.  The application ran fine on the development box, but after deploying to Windows 2003, any time the application made a call to a WCF service, an exception was raised declaring that an unrecognized element had been encountered.  After looking through several of the XML files in the solution, I happened upon the problem.

When looking at the ServiceReferences.ClientConfig file, I found the bindings defined there looked like this:

<binding name="BasicHttpBinding_Processing" maxBufferSize="2147483647"
    maxReceivedMessageSize="2147483647">
    <security>
        <transport>
            <extendedProtectionPolicy policyEnforcement="Never" />
        </transport>
    </security>
</binding>

The security element and everything within it was added when I modified one of the service references in my Silverlight project.  Removing all occurrences of these tags solves the problem.  These tags are not added under the same circumstances when developing on Vista or XP.

I’m still not sure why these tags were added.  I’m running .Net 3.5 SP1 on both my development machine and the server.

Tags:

.Net | ASP.Net | Silverlight | WCF

Accessing the Membership Provider from Silverlight

by mgordon 13. May 2009 04:50

In a particular Silverlight application, I felt it would be common for a user to have the application open for long periods, but not necessarily be interacting with it all the time.  This meant that there was always a chance the user’s session would time out.  Since the application uses the Membership and Role providers, nasty errors were being raised from web service calls depending on data from these providers if the session was not available.

To handle this situation, I tested for a valid session in my services and raised a custom exception if it wasn’t available.  Then, using the ideas in my last post I trapped that exception in my Silverlight application and showed a login box to the user so they could log back into the application and re-establish a valid session.

The next piece of this puzzle to solve was how to gain access to the Membership Provider from the Silverlight application to log the user back in.  Turns out there are two ways to go and both are equally valid for an Ajax application as well as Silverlight, though one is clearly more suitable for Ajax than Silverlight.

ASP.Net Ajax

The first solution is to use functionality built into the ASP.Net Ajax framework.  There is a javascript object in the framework, Sys.Services.AuthenticationService, that provides the needed functionality.  So, if you have all the necessary parts of the Ajax framework set up, in JavaScript you can say

var ssa = Sys.Services.AuthenticationService;

ssa.login(username,
              password,
              isPersistent,
              customInfo,
              redirectUrl,
              onLoginComplete,
              onError);

Of course you pass the username and password.  IsPersistent is a bool value indicating whether or not the user wants to be “remembered” by the application.  CustomInfo can be null as can the redirectUrl.  Of course, if you would like the user to be redirected to a certain Url after a successful log in, you’d specify that Url. The last two values are pointers to the methods to call when the login has completed or has errored out.  If you’re calling this from a web page it’s straight forward and from Silverlight, you’d need to wrap this code in a JavaScript function, and then call it from Silverlight like this.

Exposing Authentication as Web Service

Brad Abrams has an excellent tutorial on how to expose the needed functionality as a web service, here.  This was the approach I ended up using in my Silverlight application because it fit well with how the rest of the application was designed.   Once the functionality has been exposed as a web service, you could call this web service the same way you’d call any other from an Ajax application.

Tags:

.Net | Silverlight | WCF | ASP.Net

WCF Exceptions in Silverlight

by mgordon 6. May 2009 08:49

I’ve been working on a fairly substantial Silverlight 2 application and finally took on an aspect of it that I had been dreading and putting off for some time – exception handling – specifically handling exceptions being thrown from my WCF services.  I just knew this was going to be a bear.  Turns out, it wasn’t quite as bad as I had feared, but it was enough trouble that I thought a blog post sharing the experience would be a good thing.

The Problem

Silverlight doesn’t communicate directly with your web services, but rather it uses the browser API for this communication.  When calling a web service, if any exception occurs, the browser converts this into a generic 400 (Page not found) error and hands it back to Silverlight.  The result is that inside your Silverlight application, you know that an exception has occurred during your call, but have no way of knowing what it was.  This problem is supposed to be fixed in version 3.

The Research

This was certainly something I didn’t want to rush into solving so I did a bit of research on the Internet before jumping in.  Some we solving this by using out parameters on their services that contained the exception information which required checking the value of this parameter after each call.  I found a solution that was quite nice on CodeProject that used attributes on the service methods and contracts and a base class for the proxy on the client.  Since I’m still using Visual Studio generated proxies in my project, this one aspect of the solution made it unusable for my purposes.  In a discussion, here, I discovered that Microsoft’s Silverlight web service team had published a solution to the problem.  I checked it out and decided on this solution for my application.  A blog post about the solution can be found here and the code can be downloaded from code.msdn.microsoft.com.

The Code and Configuration

I found a few blog posts from folks who had implemented this solution, but none that were comprehensive and none that addressed its use with Visual Studio generated proxies.  Below, then, are the steps I took to get it all working in my application.

First, download the code the Silverlight web service team makes available and compile all the solutions.  You’ll need to set references to a few of the generated assemblies.

References

In the web project containing your WCF web services, set a reference to the assembly “SilverlightFaultBehavior.dll”.  Now, in your Silverlight project set references to the assemblies “SilverlightRawFaults.dll” and “SilverlightMessageInspector.dll”.

Code

If the web project containing your WCF web services doesn’t have a Global.asax file, add it and add the following code to it.  This code will cause any service requests that fail to return a 200 status code instead of 400.

 

protected void Application_EndRequest(object sender, EventArgs e)
{
    if (HttpContext.Current.Request.PhysicalPath.EndsWith(".svc", StringComparison.OrdinalIgnoreCase) &&
        HttpContext.Current.Response.StatusCode == 500 &&
        !HttpContext.Current.Request.Browser.Crawler &&
        HttpContext.Current.Request.Browser.EcmaScriptVersion.Major > 0)
    {
        // Set 200 if its a faulted service request
        HttpContext.Current.Response.StatusCode = 200;
    }
}
 

In any Silverlight class that makes a call to a WCF service, add the following (C#).

using Microsoft.Silverlight.Samples;
using SilverlightRawFaults;

At the point where you’re making the WCF call, you’ll be creating an instance of the proxy for that service.  Before making the call on that proxy, replace its binding by adding a line similar to this.

proxy.Endpoint.Binding = new BasicHttpMessageInspectorBinding(new SilverlightFaultMessageInspector());

This binding will ensure that the message inspector has a chance to look at the message returned from your call.

Finally, in the completed event for your service call, you’ll need to evaluate the Error property on the passed in event argument. 

if (e.Error != null && e.Error is RawFaultException)
{
    RawFaultException exception = (RawFaultException)e.Error;
    MessageBox.Show("Service says: " + exception.FaultMessage + Environment.NewLine +
        "Exception type: " + exception.FaultType + Environment.NewLine +
        "Stack trace: " + exception.StackTrace);
}
The Bug

After making the above modifications to my code, the value of the FaultMessage was not what I was expecting.  No matter what the exception was, this property always had the same generic value.  I found that there was a bug in the code provided by the Silverlight web service team and once it was corrected, all worked as expected.

Correcting the Bug

To correct the bug, open the downloaded solution called “SilverlightRawFaults”.  In the SilverlightRawFaults project, you’ll find a class called “BasicHttpMessageInspectorBinding”.  There is a property on this class called “FaultMessage” (oddly enough, the value that was incorrect).  Change this

public string FaultMessage 
{
    get { return Message; } 
}

to this

public string FaultMessage 
{
    get { return message; } 
}

Note that all I changed was the case of the “M” in “message”.  In this class, message is a member variable where Message is a property of the base class which is never set.  In the method RawFaultException sets message to the string containing the exception’s message, which is the value that should be returned.

Tags:

.Net | Silverlight | WCF

Silverlight, WCF and Domain Names

by mgordon 14. January 2009 11:33

As I learn more about WCF, especially as it’s consumed by Silverlight, the better equipped I am to identify and solve problems.  This is what I keep telling myself as a justification for the time I spend and angst I feel sometimes as I feel my way through my first significant Silverlight application.

I am far enough along that I wanted to add a deployment step to by build process which would copy all the requisite application files to a web server I have running at home.  My main goal was to iteratively deploy the application, as it progressed, so some folks whose opinions matter to me could look at and play with the application and give me feedback.

When I created the Visual Studio solution for my application, I elected to have VS create a web application for me and my .xap file and WCF services are both hosted in that application.  So, as I develop, I’m typically working in a mode where I’m running the web application in the development web server so I can make service changes on the fly.  This all worked fine in regard to being able to communicate with my services from the Silverlight application.

I realized, after deploying, that my Silverlight application would need to talk to services running on my server instead of locahost, so before checking in the code each time, I changed my service references to point to services located there.  More specifically, to point to a domain I have set up for that server.  I checked in, the build deployed the application, I tested and found no joy at all.  As I investigated, I discovered that when I set my service references to point to my domain (http://www.domain.com/MyService.svc) what was actually being recorded in web.config and the artifacts that were created by adding the reference was http://machineName/MyService.svc.  After a good bit of research and thinking about the problem, I found the solution.

The root of the problem has nothing to do with Silverlight or WCF.  It’s actually a web site configuration issue that can be corrected by going to the Internet Information Services MMC Snap-In, and drilling down to your web site.  Note that if IIS is listening on only one port, this will be the “Default Web Site”.  In IIS 6 and before, you’ll want to go to the “Web Site” tab and click the “Advanced” button.  You should see a window like the one below.

WebSiteConfig 

Notice that this site is listening on port 80 and has no Host Header Name and so the default value is used which is the name of the machine IIS is running on.  To correct the problem, select the one row and click the edit button.  Then, fill in the Host Header Name such that it matches your domain like www.domain.com and click OK.

For IIS 7, select the web site in the tree view, select the “IPv4 Address and Domain” icon and then click the “Bindings” link on the right hand side.  Select the record for port 80 and click the Edit button.

websettings

Enter your host name, as above, and click the OK button and then the Close button.

After making this change, your service references should be scoped to your domain instead of to the machine name.

Tags:

.Net | Silverlight | WCF

Silverlight and WCF Serialization Woes

by mgordon 29. December 2008 04:58

So, it's been a good while since my last post.  It's been a crazy several months and time has been scarce to devote to blogging, but my situation has changed and I'm back in the saddle.

After spending the past couple of years working on .Net 2.0 project, I've spent the last few months playing catchup on some of the latest fodder to roll out of Microsoft...Linq, Silverlight and WCF.  I have a long way to go on each, but with time and a bit of effort I should be caught up in good time.  As is my usual style, I'll be posting about the stumbling blocks I encounter and how I managed to either solve or mitigate them.  This first post concerns a problem I faced working with WCF services from a Silverlight project.  Here are the details.

Being a newbie to Silverlight, I cruised over to Microsoft's Silverlight web site, watched the videos and read the tutorials before getting started.  I felt I had a pretty good grasp on things and started work on an idea I had.  I created a Silverlight project and allowed Visual Studio to create a web project for me, as well.  I, then, added a third project to host my service layer which would be made up of Linq to Sql calls, so I also created the dbml file, there, that represented my database.  The idea was that the Silverlight project would call WCF services hosted in the web project which would in turn call methods in the Service layer to query and effect changes in the database.

I started work and created several methods on my WCF service.  Each time I added functionality to the service, I would right-click the service reference and select "Update Service Reference" to allow the new methods to be generated in my proxy (I'm aware that using Visual Studio to generate WCF client code is emerging as an anti-pattern.  I will, at some point, replace the generated code with code of my own creation...stay tuned for more on this).  After several days with no problems, I repeated this process again and had several warnings raised saying that no proxy could be generated and that my service was not Silverlight compatible.  Hmmmm.

I rechecked all the classes I was sending over the wire to make sure the right serialization attributes were present.  I ran svcutil.exe against my service and it generated a proxy, just fine.  As a last ditch effort, I recreated the web project tried again only to have the problem reoccur.  I was truly stumped.  So, I reverted my service reference code to a good state and continued to look around and found nothing until I had a revelation.  When you right click the service reference, there is an option to "Configure Service Reference".  This opens a dialog that allows you to tweak the settings for the service that control what generic classes among other things.

servicerefconfig

In the lower part of the box, you are allowed to chose which types to reuse.  Best I can tell, this reuse involves serialization since the types would be "reused" on both sides of the service binding.  Upon inspection, I found that some Telerik assemblies were included in the list.  If I chose the lower radio button and unselected the Telerik assemblies, my service reference was generated properly.  Apparently, some of the types in one or more of these assemblies could not be serialized.

This is an example of the kind of thing that can happen and the frustration it can cause when you know just enough about a technology to be dangerous.  I'll be working hard to remedy this in the coming days.

Tags: , , ,

.Net | Linq | Silverlight | WCF

Powered by BlogEngine.NET 1.5.0.7
Theme by Extensive SEO