Updated my WCF Data Contract but client doesn’t receive the property values….

I spent about ten minutes wondering why I wasn’t getting the data I expected from my WCF service. I had just changed my data contract to have one more property/field and the data wasn’t being received by my client application. The client is in javascript, so it’s happy with whatever it receives. So no errors there, just an undefined property.

I looked at fiddler and noticed it didn’t come through there either. Now I chalked it up to a stale build and rebuilt again. Hmm…. Still undefined…wtf?

Well, simple issue with a simple fix. It turns out I , DUH, forget to tag the property as a DataMember. So the serializer ignored it thinking it was just an internal variable. No need to serialize or expose. Geez.

My fault but it was pretty funny when I started going back through my entities and contracts and started comparing them.

So, in short, if your client for your WCF service is not receiving the property you expect on the data contract, make sure you marked them properly. Easy to overlook when you are updating the DAL DTO’s, Business Entities, and then your Contract Entity.

Example:

/// <summary>
/// Gets or sets the reference.
/// </summary>
/// <value>
/// The reference.
/// </value>
[DataMember(Name= “Reference”)]
public string Reference { get; set; }

Happy coding!

CommunicationException with Silverlight and a cross domain call

You are calling your services from Silverlight but the services are accessed via a different URI than the Silverlight application is being hosted. Errors galore, right? 

Silverlight honors the protection that helps mitigate a sites scripts from being called if someone simply copied your app to their server. 

The error you get is this: 

An error occurred while trying to make a request to URI ‘http://localhost.:2935/Services/UserService.svc’. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details. 

This error is very easily fixed. 

Create a file in you web root. Must be the root called clientaccesspolicy.xml . It must be named exactly and must live in the root. 

File: clientaccesspolicy.xml

Now, copy this into the file: 

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="SOAPAction">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

Save it, rebuild and run. Voila, you should now be up and running. If you need more info, check this helpful link. 

Happy Coding!

Fiddler and Silverlight with the localhost, how to debug WCF failures!

If you use Silverlight and you are trying to look at why service calls are failing, you will want to use Fiddler to see what is actually going on. Is the request going through, is the server returning an error. Since Silverlight always gives the same crappy error, Endpoint not found or something similair, then looking at the actual raw request responses is pretty helpful.

So you turn on Fiddler, but no requests appear? Well, some strange issues, with a long explanation, about using localhost don’t get logged into Fiddler. The trick is to rename your service references to localhost. Yes, simply add the .

Just make sure you type that URL the same way into your browser, otherwise you get a cross domain call issue. That is the subject for the next quick post.

Happy coding!

Config file issue to make you rip hair out

I spent about 2 hours staring at this lovely cryptic error:
Extension element ‘silverlightFaults’ cannot be added to this element.  Verify that the extension is registered in the extension collection at system.serviceModel/extensions/behaviorExtensions

I had it setup correctly, but why would the system not compile it?

This was the registration:

<add name="silverlightFaults"
type="Seekford.SilverlightFaultBehavior.SilverlightFaultBehavior,Seekford.SilverlightFaultBehavior, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7073c134a4dabf61" />

So? What is wrong with this picture? Nothing unless you are an unforgiving parse engine that exists to make life difficult.

I had to add a space. Yes, a space between the class and assembly name and BAM!, it worked.

<add name="silverlightFaults"
type="Seekford.SilverlightFaultBehavior.SilverlightFaultBehavior, Seekford.SilverlightFaultBehavior, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7073c134a4dabf61" />

What a pile of #$%!!

Anyway, remember your spacing.

Happy Coding!

Dynamic service endpoint binding for Silverlight using WCF

As part of my continuing effort in create a high quality line of business application in Silverlight, I am laying out a nice foundation for the repository layer. The services interaction is being shielded from the higher layers.

The main hurdle that was annoying me was having to change the endpoint the Silverlight application was pointing by editing a configuration file that was embedded in the application. Mainly, the fact that this required a recompile when going from local build to server. What a pain!!! Bad Microsoft…Bad..

I decided to just write a simple addition to my factory to generate the endpoints on the fly, no more recompile per site required. This also lets the application easily be moved server to server without any pains. Relative WCF URLS should have been a mandatory addition, but alas their not. If Microsoft had thought of everything, I wouldn’t have a job I guess.

Here is the simple code to do a dynamic endpoint in Silverlight. Enjoy!

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Windows;

namespace Seekford.Repository.MyServices
{
    internal class MyServiceFactory
    {
        private const string myServiceLocation = "../Services/MyCService.svc";

        /// <summary>
        /// Creates the binding.
        /// </summary>
        /// <returns></returns>
        private static CustomBinding CreateBinding()
        {
            CustomBinding binding = new CustomBinding();
            binding.Name = "SilverlightBindingGoodTimes";
           binding.Elements.Add(new BinaryMessageEncodingBindingElement());
            binding.Elements.Add(new HttpTransportBindingElement()
                {
                    MaxBufferSize = int.MaxValue,
                    MaxReceivedMessageSize = int.MaxValue
                }
            );

            binding.OpenTimeout = new TimeSpan(0, 5, 0);
            binding.CloseTimeout = new TimeSpan(0, 5, 0);
            binding.ReceiveTimeout = new TimeSpan(0, 5, 0);
            binding.SendTimeout = new TimeSpan(0, 5, 0);         

            return binding;
        }

        /// <summary>
        /// Creates the aand C service client.
        /// </summary>
        /// <returns></returns>
        public static MyServiceClient CreateMyServiceClient()
        {
            var binding = CreateBinding();
            return new MyServiceClient (binding, new EndpointAddress(
                new Uri(Application.Current.Host.Source, myServiceLocation )));
        }       

    }
}

You will obviously need to tailor to your needs, but the idea is pretty straight forward.

Happy coding!

FedEx Integration Address Service: Unable to generate a temporary class…ParsedElement[]

Are you using the new WCF service reference against the FedEx Address service WSDL? I’ll bet your scratching your head on why you get this craptastic error.

 InnerException: {"Unable to generate a temporary class (result=1).rnerror CS0030: Cannot convert type 'YOURNAMESPACE.FedExAddressService.ParsedElement[]' to 'YOURNAMESPACE.FedExAddressService.ParsedElement'rnerror CS0029: Cannot implicitly convert type 'YOURNAMESPACE.FedExAddressService.ParsedElement' to 'YOURNAMESPACE.FedExAddressService.ParsedElement[]'rn"}
    Message: "There was an error in serializing body of message addressValidationRequest1: 'Unable to generate a temporary class (result=1).rnerror CS0030: Cannot convert type 'YOURNAMESPACE.FedExAddressService.ParsedElement[]' to 'YOURNAMESPACE.FedExAddressService.ParsedElement'rnerror CS0029: Cannot implicitly convert type 'YOURNAMESPACE.FedExAddressService.ParsedElement' to 'YOURNAMESPACE.FedExAddressService.ParsedElement[]'rn'.  Please see InnerException for more details."
    Source: "mscorlib"

The answer is annoying. You would think running on the .NET 4.0 Framework they would have figured out their bugs with consuming WSDL’s.

So, open your references.cs file for the service. (It’s hidden, you either go to disk or hit the little icon that says show all files, hit the arrow on the service reference, then you see the magic file)

Hit Ctrl+H and type in [][] for the find and replace with [].

Basically, it made this nice two dimensional array that the server is less than pleased to receive.

If you refresh from the WSDL, guess what? You get to do this all over again, so quit hitting the refresh button.

Happy coding!

WCF Timeouts: To send or to receive, that is the question!

You decide to write a nice WCF service and you know the operation could take up to 5 minutes to complete. Well, what to do? What to do?

It is possible you say, well I well manually set the operation timeouts in code. That works but is annoying. How about setting the binding timeouts? There you go, nice and easy right?

Let’s take a look at the following binding:

<binding name="MyBinding" closeTimeout="00:00:30" openTimeout="00:00:30" receiveTimeout="00:05:00" sendTimeout="00:0:30">

It looks pretty accurate right? The operation takes 5 minutes or less, so it should work fine with the receiveTimeout being set to 5 minutes. No worries.

Well, YOUR WRONG!. Surprise!

The retarded illogical answer to the above quandary is that WCF uses the sendTimeout to figure out how long to wait to RECEIVE data. I know, painful. You will get timeout errors out the wazoo with the simple mixup of this little fact.

So, next time you setup your bindings, make sure to know the client really cares about the sendTimeout. It doesn’t seem to really concern itself with the receiveTimeout so much.

Here is the right binding:

<binding name="MyBinding" closeTimeout="00:00:30" openTimeout="00:00:30" receiveTimeout="00:05:00" sendTimeout="00:05:00" maxBufferSize="500000000" maxReceivedMessageSize="500000000">
 </binding>

Enjoy this little trickery and hopefully you save some time.

Happy coding!

How to connect to a WCF service that has a mismatched Identity in code…

I had an issue where my client was connecting to a WCF service that was using certificate authentication, but the certificate was for a different dns name.

i.e. server was foobar.comp and the certificate was for foo.foobar.comp.

This presented an issue. Of course, you can change the Identity tag in the configuration file, but I wanted my program to be a little smarter. I grab the error from the WCF service and switch the Identity on the fly. Mainly I did this for a test application in a load balancing scenario due to the load balancer having a different DNS name than the servers. (Obviously!)

Hopefully you have written your own proxy class with a constructor that takes in the configuration name and an EndPointAddress.

You can then use the following style code to create your proxy with the Identity mismatch taken care of.


 protected override MyProxyClient CreateConnection(string Server, string altIdentity)
        {
            if (string.IsNullOrEmpty(altIdentity))
                altIdentity = Server;

            return new MyProxyClient ("MyServiceBindingConfiguration",
                new EndpointAddress(
                    new Uri(
                        string.Format("net.tcp://{0}:8090/seekford/2.0/SeekfordService",
                    Server)
                    ),
                    EndpointIdentity.CreateDnsIdentity(altIdentity))
                );
        }

We only are using the configuration for the primary settings, such as binding info. The actual server endpoint is being set on the fly with the altIdentity param being used to allow the server to masquerade with a different certificate.

Happy Coding!

How to use SSL transport security using a certificate in your WCF hosted service…

So you want to use some channel security in your WCF service. Maybe you even want to guarantee the server your are talking to is who they say they are.

Well, transport security is what you are looking for. It is really quite easy to implement.
Things you will need:
1) A certificate from a trusted signing authority (thawte,godaddy, verisign,etc)
2) A WCF service (duh)

You will need to make changes to the server app.config and the client app.config.

On the Server:

You will need to add this tag to the binding:
<security mode=”Transport”>
<transport clientCredentialType=”None”/>
</security>

We are basically saying here, use transport security but don’t look for a client certificate.

You will also need to create a service behavior.
<behaviors>
<serviceBehaviors>
<behavior name=”MyServiceBehavior”>
<serviceCredentials>
<serviceCertificate findValue=”CN=server.contoso.com” storeLocation=”LocalMachine” storeName=”My” x509FindType=”FindBySubjectDistinguishedName” />
<clientCertificate>
<authentication certificateValidationMode=”None” />
</clientCertificate>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>

Notice the serviceCertificate tag. This is the important one. the CN=XXXXX is the portion you need to change to your servers certificate subject.

Now the service is setup. You will need to modify the Client app.config as follows:

You need to change the bindings on the client the same way as the server. Example.
<bindings>
<netTcpBinding>
<binding  name=”TCP_Binding” …..>
<security mode=”Transport”>
<transport clientCredentialType=”None” />
</security>
</binding>
</netTcpBinding>
</bindings>

Now you have your service protected with SSL and validation.

Happy coding!

How to make your own SSL test certificate for IIS or WCF

I had to create a test ssl certificate to use with my WCF service.

Here is the simple way to do it in 2 Easy Steps!

1) Open the Visual Studio 2008 Command Prompt

2) Fire off this command. change bseekford00111 to your computer name or whatever name you want the certificate to be.

makecert -r -pe -n "CN=bseekford00111" -b 01/01/2000 -e 01/01/2050 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr CurrentUser -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12

That is all there is to it.
It will drop it in the current user MY store. If you want it under local machine store, change CurrentUser to LocalMachine