More about Silverlight RawFaults

by mgordon 31. July 2009 15:32

While writing the Silverlight applications at FunkyTools.com, I quickly found that not being able return exceptions from my WCF calls was a huge problem for me.  I located a solution that had been released by the Silverlight WCF team and, at the time, learned just enough about the code to get it integrated into my solution.  I documented how to use the code in a previous blog post. Recently, however, I’ve taken the time to dig into the code and learn more about how it works.

 

Why Faults Don’t Get Returned To Silverlight In The First Place

When Silverlight makes a WCF call, the communication with the server does not happen from the Silverlight application.  Rather, Silverlight uses the browser API to originate the call and the response comes back to the browser, first, and it passes it back to our application.  When an exception occurs in the WCF service, the return HTTP Response Code is changed from 200 to some other value to indicate the call was problematic.  If a response code other than 200 is returned to the browser, Silverlight gets handed back a “Not Found”" Exception from the browser and the actual exception information is lost.

 

The Sample Solution

The sample solution contains 4 projects.

  • SilverlightFaultBehavior – Defines a behavior that is added to a customer binding we can use to enable to have out exceptions returned.
  • SilverlightMessageInspector – Defines a new Channel and Binding for use in the solution.  This Project wires up the Channel, Binding,  and behavior.  These first two projects define all that’s needed to set up the server side of the functionality we desire.
  • SilverlightRawFaults – Defines a single class that is of interest which is a message inspector – more on this in a second.
  • SilverlightRawFaults.Web – A test web site to host the sample service.

 

SilverlightFaultBehavior Project

This project defines a single class, SilverlightFaultBehavior, which extends BehaviorExtensionElement and IEndPointBehavior.  Basically, it adds an additional behavior that we can tie to our bindings.  In this class, there is a method IDispatchMessageInspector.BeforeSendReply that contains the following code:

 

if (reply.IsFault)
{
   HttpResponseMessageProperty property = new HttpResponseMessageProperty();
   property.StatusCode = System.Net.HttpStatusCode.OK; // 200

   reply.Properties[HttpResponseMessageProperty.Name] = property;
}

 

So, basically, just before the response is returned to the browser, this behavior sets the return code to 200 if it’s any other value.

 

SilverlightMessageInspector Project

This project is basically a plumbing project.  It composes the behavior, channel and the message inspector into a binding, which when used, is pre-configured to return the exceptions we desire.

 

SilverlightRawFaults Project

This project contains file SilverlightFaultRawMessageInspector.cs and defines the two classes needed on the client side.  The file contains two classes; RawFaultException, a custom CommunicationException and SilverlightFaultMessageInspector which implements IClientMessageInspector.  In the latter of these classes a method, AfterReceiveReply, contains this code:

 

if (reply != null && reply.Version == MessageVersion.Soap11)
{
    if (reply.IsFault)
    {
        throw new RawFaultException(reply.GetReaderAtBodyContents());
    }
}

 

So, when the reply is received by Silverlight, but before it is returned to our application, this method checks to see if the reposonse contains a Soap 1.1 Fault and if it does, and instance of the custom CommunicationException is created that contains the fault details (error code, message and stack trace) and that exception instance is thrown into our application.

 

So, our response is inspected on the server and its response code is set back to 200 so the browser will interrupt the flow of our fault.  Once Silverlight gets the response, our client side message inspector checks to see if a fault is contained in the response and if so, the fault is converted into an exception and thrown back to the method in our application that originated the call.  

Tags: ,

.Net | Silverlight

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

Setting Up a Build Server - Part 1 (Subversion)

by mgordon 11. March 2008 07:54

For the past several months, we've been using a build server on our project for continuous integration.  I've been involved with teams, in the past, that used build servers, but this particular setup has proved to to be a real asset and the experience of using it day-to-day has been a pleasure. 

I'd like to share how we built the server.  I'll make several posts over the next few days to address the various parts that work together.  Along the way, I'll discuss version control (subversion in our case), Cruise Control .Net, NAnt and StatSvn.

What We're Trying to Accomplish

Why would you want a build server, anyway?  The primary benefits of a build server are continuous integration and automation.  Let's say you have a team of five and all are working on the same project.  Each has a piece of the application that they're working on.  As they develop, they test the code they're responsible for.  Who, though, is responsible for making sure that all the pieces work together?  The reality is that at any given time each developer's machine has a unique version of the application that's different everyone else's.  The purpose of the build server is to periodically take the code that exists in the source repository and process is to verify the code all works together.  In other words, the health of the code (how well all the parts integrate) is always known.

There are many functions the build server can perform.  It can do a compile, execute test suites, generate an installer or even a CD image.  Crucial to the whole process is source control, so let's look at getting started with Subversion.

Subversion

All source code repositories have their own take on how best to solve the problem of keeping up with all the changes made to to the code base.  Some require the developer to lock a file while it's being worked on, while others allow changes to be made by anyone at any time.  Subversion falls into the latter category.  Basically, a developer grabs a snapshot of the current version in the repository, makes his changes and then pushes them back up.  Committing of changes happens in a transaction so the commits are always stable.  Subversion takes the version being committed and merges it into the current version in the repository.  This means that manual merging is greatly reduced.  On the occasions when Subversion can't figure out how to merge the changes, the developer is notified and is give an opportunity to manually do the merge. 

Installation

You can obtain the subversion installer here.  I downloaded the installer, svn-1.4.6-setup.exe, and executed it taking all the defaults.  At this point, all the binaries are installed on your system, but Subversion hasn't been configured to run as a Windows Service.  To set it up to run this way, execute the following from a command line.

C:\>sc create svn binPath= "\"c:\program files\subversion\bin\svnserve.exe\" --service -r c:\repos" DisplayName= "Subversion Server" depend= Tcpip

This command will create a Windows service named "Subversion Server" that runs svnserve.exe when it's started. 

Subversion Client

Regarding a client that you'll use for interacting with your Subversion server, you'll need to decide whether you prefer to have the client integrated into Visual Studio or not.  If having everything available within the IDE is you bent, then you'll likely prefer something like AnkhSVN.  Personally, I'd rather do my source repository work outside the IDE and prefer to use TortoiseSVN which installs as a shell extension.  Either way, you'll need to create a repository and then connect to it with your client.

Creating and Configuring a Repository

On the machine on which the Subversion service is running, create a folder in which you'll be storing your code repository.  Then, go to a command line and execute the following.

svnadmin create c:\path-to-repos

This will create a repository for you in the directory you created.  Now, we need to configure access to the repository.  Go to the folder you created, before, and you'll find that three files have been created there.  First, open the svnserve file.  All the lines in the file are currently commented out.  You'll need to modify at lease three of these lines.  Find the line that contains "anon-access".  This line controls what access users connecting to the repository anonymously have.  Your options are "read", "write" and "none".  In my case, I set this value to "none".  Next, find the line that contains "auth-access" and set its value to either "read", "write" or "none".  this line controls what access authenticated users will have.  For the last change, find the line that contains "password-db" and remove the "#" character and the space that follows it to un-comment the line.  This tell  Subversion to look in the passwd file to find a list if valid users of the repository.  Save your changes to this file.

Now, open the passwd file.  All lines in this file are commented out, as well.  Beneath the line "[users]", you will need to create a list of valid users for the repository in the form "username = password".  Save your changes.

Accessing the Repository From a Client

Whichever client you choose, you'll need to specify a URL and your credentials.  URL's for subversion are of the form svn://server-name.  For credentials, you'll need to use one of the user-name / password combinations you created in the passwd file, earlier.  At this point, you should be able to check out (get a copy of the current version) and commit (check in) to and from your repository.  If, however, you're having problems reaching the server you'll want to check that the Subversion service is running and you also may need to configure svnserve.exe as an exception in windows firewall.

That's it for Subversion.  Next time, we'll set up CruiseControl.Net.

Tags: ,

.Net | Productivity

Workflow Services and the DTC

by mgordon 7. February 2008 04:56

As noted in a former post, I implemented a change order system using Windows Workflow.  Recently, the system was deployed for User Acceptance Testing and odd things began to happen.  The system is using both tracking and persistence services and what we observed in the Sql Profiler was that the Sql to insert the persistence record was never making it to the database, but the tracking was working fine.

I implemented a handler for the ServicesExceptionNotHandled event on the WorkflowRuntime object, but nothing was being raised.  After a couple of hours poking and prodding, I finally linked the problem to the windows firewall.  If the firewall was turned off, everything worked as expected.  I spent some time researching the problem and found a couple of posts on the Microsoft Forums here and here that discuss the SharedConnectionWorkflowTransactionService.  Apparently, when the persistence and tracking data are in two different databases, the DTC gets involved any updates to the data and the firewall was blocking the DTC traffic. 

As mentioned in one of these posts, I combined the persistence and tracking databases into one, and added the SharedConnectionWorkflowTransactionService to runtime when I started up.  The combination of these actions removed the dependency on the DTC and all is working fine, now. 

Tags: , ,

.Net | Sql Server 2005 | Workflow

Convert Linq Result Set to DataTable

by mgordon 16. January 2008 07:43

I'm in the process of evaluating Linq by converting an existing data layer from using Subsonic to to using Linq queries.  One challenge with this, of course, is trying not to change method signatures in the process.  I have some methods that return DataSets and was stressing over having to modify all the logic that called the methods to consume a return type of var, or a collection of entity classes instead.  Thankfully, while looking for possible solutions to the problem, I stumbled over this article from CoDe Magazine that contains code for an extension method that converts a Linq result into a DataTable.

Tags: ,

.Net | Linq

Evolution of the Delegate

by mgordon 15. January 2008 16:04

When .Net was introduced, one of the most powerful language features has been delegates which provide a way to pass around, not only data values, but also chunks of implementation and logic.  Consider how often you need to add a button to a web form or windows form and have some code execute when the button is clicked.  In Visual Studio, you can simply double-click on the button in the designer and the IDE will generate a new method for you, and wire that method to the event.  The generated code contsructs a delegate and passes it to the button so it can be called by the button at the proper time.  In effect, it tells the button, "When you're clicked on, execute this chunk of code".

Delegates have come a long way since the 1.0 days.  Consider the following code for a Windows Form class.  In this example, we'll look at the evolution of the delegate.

  public partial class Form1 : Form    
  {        
public Form1()        
{            
InitializeComponent();             

         //DotNet 1.0 and 1.1 - had to specify the implementation in a separate method            
this.button1.Click += new System.EventHandler(this.button1_Click);                        
        //DotNet 2.0 - Anonymous Methods.  Can declare implementation inline.            
this.button2.Click += delegate            
{
                MessageBox.Show("Clicked Button 2");
        };             
        //DotNet 3.5 - Declaring implementation inline using Lambda Expressions
        this.button3.Click += (sender, e) => MessageBox.Show("Clicked Button 3");
    }
    private void button1_Click(object sender, EventArgs e)
    {
            MessageBox.Show("Clicked Button 1");
    }
} 
  I've created a form in Visual Studio 9 (Orcas), dropped three buttons on it and implemented event handlers using three different syntaxes.  If you were to double-click on Button1, you'd get the implemenntation demonstrated for that button, above.  A separate method is created and your event handling code is written in that method.  This is a bit verbose and anyone reading the code may have to scroll around to follow the picture since the delegate and the method it calls are in two separate places.

For Button2, I've created the delegate using the anonymous method syntax introduced in .Net 2.0.  With it, you don't need to declare a separate method containing the implementation.  Instead, where the delegate is declared, you can also specify the implementation.  This makes the code both more brief and also keeps the delegate declaration and its implementation located together, making the code more readable.

In the latest .Net release, Lambda Expressions were introduced.  While the name may sound scary and complicated, they're really nothing more than a third syntax for specifying delegate implementations.  As you can see in the implementation for Button3, I've specified the familiar parameter list of (sender, e).  Also, I didn't need to specify the types of the parameters though you could if you wanted to.  The compiler will figure out the types for us based on the context of the expression. As Scott Guthrie explains in this post, the parameters' types are also known by the intellisense engine so we can get intellisense on the parameters. The parameter list is then followed by a "=>" symbol and finally the implementation itself.  Once again, more concise and far more readable than the previously introduced syntax.

I can barely imagine what LINQ queries would look like had the latter two syntaxes not been introduced for delegates (especially the Lambda Expression syntax), but this doesn't mean the improvements are only useable in Linq queries.  As I've demonstrated, they are useful and even preferable any time a delegate is required. 

Tags: ,

.Net | Productivity

SmartPhone Development in VS2008

by mgordon 12. December 2007 15:21

I've been working on some infrastructure for my contracting business.  There are a lot of things that need to be tracked when you run your own business and for me it seemed that whenever I remembered something needed to be recorded I wasn't near a computer.  However, I always have my mobile phone (Samsung Blackjack) near by and it made sense to me to write an application that allowed me to log things like time, mileage and the like from my phone.

Architecture
I could have gone the route of creating a web site for this purpose, but instead I decided to create a SmartPhone application that called web services on my server, at home.  This way, if I ever decide to write a Windows Form or Web application front end, I can use the same web services and not have to recreate the logic they provide.  The web service methods give me all the CRUD functionality I need to manipulate the data I'm storing, so all the UI code on the phone needed to do was collect data and call the web service for storage.

Writing the mobile application was very straight forward.  I set a web reference to the web services I'd written and coded against the generated proxy.  Getting used to the mobile controls and the bits of functionality not provided in the compact framework were the biggest challenges, but nothing major at all.

Lessons Learned
Getting an internet connection in the emulator
After I had written a bit of code, I was eager to see it run.  I clicked the Start Debugging button on the Visual Studio toolbar and after prompting me for a target to deploy to (choose the emulator), an instance of the emulator was created and my code was deployed to it.  When I tried exercising some code that made a web service call, a transport error was raised.  I then tried to open pocket IE on the emulator and browse to an internet address, but got a message saying that I needed to configure my network settings on the phone.  After some searching, I figured out how to set it all up.  First, make sure you have ActiveSync installed and running.  Then, right-click its tray icon and choose "Connection Settings" from the context menu.  Make sure the check box for "Allow connections to one of the following:" is checked and select "DMA" in the combo box. 

In Visual Studio, go to the Tools menu and select "Device Emulator Manager...".  When the dialog opens, right-click the entry for "USA Windows Mobile 5.0 Smartphone R2 QVGA Emulator" and select "Connect".  This will open an instance of the emulator.  Next, right-click the same entry again and select "Cradle".  At this point, ActiveSync should detect the emulator and treat it as it would a physical phone plugged into the USB port of the PC.  Once you go through the connection wizard, you should have access to your PC's internet connection from the emulator through ActiveSync.

Deploying to the SmartPhone
Once my mobile application was unit tested, I was ready to deploy it to my phone.  I connected the phone to the PC, right-clicked my mobile project in Visual Studio and selected "Deploy".  The phone popped up up several dialogs asking me to approve the installation of several files on my phone.  I approved all of these, but the deployment still failed.  The reason stated indicated that there were some certs needed on my phone to deploy for development.  To get past this error, copy the file ...\Program Files\Microsoft Visual Studio 9.0\SmartDevices\SDK\SDKTools\VSDCerts.cab to your phone.  Then, on the phone, open the cab file to install the required certificates.  The deployment should succeed after this is done.  Of course, if you're developing an application for distribution, you'll want to properly sign your application instead of taking this short cut.

 

Tags: , ,

.Net | Contracting | SmartPhone

Automatic Properties

by mgordon 14. November 2007 08:20

I've been exploring some of the new language features that will be available in the coming version of .Net.  I continue to see things that look like they have been borrowed from dynamic languages.  Another to add to the list is automatic properties.  In C#, you'll be able to define properties like this.

public string FirstName { get; set;}

This is functionally equivalent to the following:

private string _FirstName;
public string FirstName
{
    get
    {
        return _FirstName;
    }
    set
    {
        _FirstName = value;
    }
}

This will be a real timesaver for those not using a tool such as CodeRush where creating he above block of code is reduced to three keystrokes (ps<space>) and then typing in the name of the property. 

Now, look at how the equivalent is accomplished in Ruby.

attr_accessor: FirstName

Instead of specifying get; and set;, you specify attr_writer for a write-only property and attr_reader for read-only.

Tags: , , ,

General | .Net | Productivity | Ruby

Extension Methods

by mgordon 9. November 2007 04:33

With the release of the next version of Visual Studio and the .Net languages, a new feature called Extension Methods will be available.  In a general sense, these allow you to add functionality to classes without having to modify their source including any class in the .Net Framework.  This is a very similar idea to what is offered in a dynamic language such as Ruby, but in the strongly typed .Net languages.

 For example, Ruby has a string type.  If, for some reason, we wanted to add a method to the string class that would return the string wrapped in html that would render the string in a particular color, we could do something like this.

class String
  def to_htmlColor (color)
    "<font color='" + color + "'>" + self + "</font>"
  end
end

puts "fido".to_htmlColor("#AAAAAA")

This would return the string <font color='#AAAAAA>fido</font>

In C#, we can accomplish a similar thing this way.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace testExtensionMethods
{

    class Program
   
{
       
static void Main(string[] args)
        {
           
Console.WriteLine("423".to_i());
           
Console.WriteLine("xxx".to_i());
        }
    }

    public static class Extensions
   
{
       
public static int to_i(this string s)
        {
           
int i;

           
if (!int.TryParse(s, out i))
            {
               
throw new InvalidCastException("String cannot be converted to an integer");
            }
           
return i;
        }
    }
}

Here, I've added a to_i() method to the .Net string class that converts the string value to an integer if it can and throws an exception if it can't.  What triggers the desired behavior is the inclusion of the this keyword in the method signature.  This syntax tells the compiler that the method is to be added to the string type since it follows the this keyword.  The new method can be used on the string class anytime my extension class is in scope.  For example, I could have added my Extensions class in a different namespace and anytime that namespace was included with a using or imports statment, my extension method is available.

Certainly, this is a more brief syntax than int.Parse("423") and feels more natural.  I can recall several situations where I've had to string together commands from various classes in a single statement.  Extension methods could help out with creating convenience methods to replace complicated syntax in these situations.

Scott Gutherie discusses how extension methods were used to add functionality to classes for use with Linq, here.  When the Linq namespaces are included, standard classes are augmented with new functionality that make them easier to use in conjunction with Linq.  In thinking about how I might use these, one idea that came to mind was in a situation where I had a data transport class.  It needs only to be able to contain the data when it's moving between layers, but when it arrives in the business layer from the data layer, it would be nice to be able to add functionality to the class.  This would keep the class nice and tight as it is passed around, but when you need to perform some action on the data contained within, extension methods could be used to add that functionality.  In a way, this technology allows you to have a class function differently based on the "mode" or context it happens to be in at any given time.  Very snazzy!

Tags: , ,

.Net | Productivity | Ruby

Sql CLR Pattern

by mgordon 5. September 2007 04:30

I recently had the chance to immerse myself in doing CLR development on Sql Server 2005.  The project I'm working on requires some complex pricing algorithms for varying combinations of products and doing the calculations in a "set-based" way just didn't feel right.

I needed to write several closely related stored procedures and did so in a single project.  When you create each procedure, Visual Studio creates a separate file for each procedure, but the files declare the class using the partial keyword which means that each procedure is actually just a static (shared) method on a single class.  As work progressed, I saw a number of opportunities to reuse some of the methods I had written across procedures.  This was easy enough since all the procs were actually in the same class...even private members we accessible from all the procedures. 

At some point, however, I realized that I needed to call one procedure from another.  This presented a problem, though.  I typically started all my procedure like this...

Partial Public Class StoredProcedures
    <Microsoft.SqlServer.Server.SqlProcedure()> _
   
Public Shared Sub up_MyProc(ByVal parm1 As Integer, ByVal parm2 As Integer)

   
Dim conn As New SqlConnection("Context Connection=true")
    conn.Open()

    . . . .

So, at the entry point of the first procedure, I opened a Context Connection and as soon as I called into the second proc, it tried to create another connection.  Since only one context connection is allowed per call, the attempt to open the second one failed.  I could, of course, call into the second procedure by creating a SqlCommand and executing it, but that feels dirty considering that both procs are actually in the same class.

So, after some thought, I determined a pattern that I intend to use from now on in such situations.  For all my CLR procs, the method that is the entry point for the procedure will be structured like this...

<Microsoft.SqlServer.Server.SqlProcedure()> _
Public Shared Sub up_DoWork(ByVal parm1 As Integer, ByVal parm2 As Integer)

    Dim conn As New SqlConnection("Context Connection=true")
    conn.Open()

    DoWork(parm1, parm2, conn)

    conn.Close()

End Sub

Now, I can call the code as a stored procedure (through up_DoWork), which is its primary purpose, and also call into the whole of the proc's functionality (DoWork) while passing in a context connection created in another proc.

Tags: ,

.Net | Sql Server 2005

Powered by BlogEngine.NET 1.5.0.7
Theme by Extensive SEO