WCF RIA Services and POCO - Is there any Value?

A few weeks back I wrote about getting RIA services to work with POCO.  It was a long post, so long that it was 5 posts.  In the weeks since, I spent some time trying to use POCO/RIA in some work that I was doing for a client, and I started to develop some strong feelings about why bother with all of this extra work to just get things to work with RIA instead of just using WCF/Data Contracts/DTOs.  I'm still trying to be able to articulate these feelings, but figure I'll give it a shot right now.

First, it was a lot of work to get the POCO to work with RIA, at least compared to just creating a class that is annotated with DataContact/DataMember attributes.  The former took me 5 posts just to describe how it works.  The latter takes maybe a minute to build an end to end solution.

But that's not all.

Second, a lot of what RIA (excuse me WCF RIA) does is autogenerate code to do different things, such as generating client side objects that know how to track changes and do automatic validation.  I'm left to wonder about the former, but do by that the automatic validation code is useful, but I'm not sure its worth the effort getting POCO to work over using validation libraries such as EL. 

The issue with tracking changes I think is the sticking point, as I don't see what value there is in POCO, as it is inherently tied to using entities on the server side (read Entity Framework).  Without the mapping back to entities in the client side, is it adding any value?  I don't see that it is.

This also leads to the generation of service methods for which I can see as nothing but CRUD operations.  Again in a POCO world, is CRUD really necessary?  If I'm not using a database, and not modelling my objects off of entities generated from the database, do I really need CRUD methods auto generated by convention? And to be honest, it was really hard to just get a single POCO object returned with RIA.

So what I think this boils down to is without a database, and then additionally without EF, I don't see the advantage.

And now one more kicker.  The system I was building wanted to try and use RIA, but we were not connecting to a database, so hence the POCO route.  Instead of a database, we are connecting with a backend system via EMS messages bridged over JMS into services in Oracle.  This throws this whole thing into the world of asyncronous messaging.  WCF RIA services are inherently tied to syncronous operations, since they pretty much are generated to do syncronous communications to the database and return the result.  The EMS method we looked at had to be asyncronous (it's the nature of the environment I'm working in, not that EMS can't be syncronous - the back end Oracle app could not do this syncronously). 

So, the method to get objects would need to either block waiting to a response message on EMS, or return directly without any data.  In the latter case, there is really no use for RIA; why do all this magic if I can't get the data to be managed during the RIA services call?  Well, none that I can see.  In the case of blocking waiting for a response, sure I can program that, but it is going to inherently reduce scalability of the solution.  And it kind of defeats one of the things I really like about Silverlight - the asyncronous nature of calls to the client.  The Silverlight client will still do the call asyncronously which is great, but with my having to program syncronous blocks on the server it just seems to defeat the purpose.  I would rather go totally asyncronous and gain all the scalability possible, even at the expense of having to use callbacks from the server to the silverlight client for when response messages arrive back on EMS.

So, I guess this would lead to some rules about when to use / not use WCF RIA.  I'll take a try at them...

When not to use:

  • You are not using a database.
  • You need asyncronous communications with a third tier
  • You are using something other than Silvelright for a client

When to use:

  • You don't have a database, or are doing async communications with a third tier, but feel the automatic generation and use of validation rules is worth the effort
  • You are building forms-like CRUD apps against your database model

I also have concerns about how portable this is to non-Silverlight clients.  For example, I can't use the RIA objects in WPF, and I wonder how this would integrate to web or AJAX clients; sure the classes can't be used, but can you use the web services that are exposed?  My guess (as I haven't tried it yet) is that you can't, at least easily.

I'd really like to hear your comments on this.  Every time I look at RIA services I really want to like it, and I'd like to be able to feel like it has broader value, so please let me know your experiences.

 

Using Silverlight 4 and Net.TCP Duplex Callbacks

Over the last several weeks I've been investigating for a client a means of providing callbacks to Silverlight clients to push trade updates to all the users.  This has typcially been done using a PollingDuplexHttpBinding in Silverlight 3 and 2, but this is problematic as it is first a polling model (yuk!), and second the only data format is XML it could be slower then using a binary format.

The experience has been quite an adventure, as usual with beta Microsoft stuff.  There's not much documentation available, and everything that can be found is kind of all over the place in quality.  The best two sources I have found are the following two great blog posts by Tomasz Janczuk and Radenco Zec:

While these were valuable posts, I did still find the effort to have a lot of troubles, so I thought I'd also throw out my $0.02 on the process.

To get this Net.TCP to Silverlight 4 to work, you are going to need to do a bunch of things even to get up and running:

  • You need to run the web solution under IIS as the VS.NET web server does not support NET.TCP
  • You must configure Non-HTTP activation for IIS so it can respond to Net.TCP request
  • You must configure both the web site and web application to respond to Net.TCP
  • You must provide a policy server to verify the client as being able to communicate to the server with TCP

I had some problems with each of these, and I'll walk through configuration of these items.

Once you have that complete, there is also a bunch of configuration and programming that you need to get right in order for everything to work:

  • Your server web.config needs to be configured properly to support Net.TCP
  • Your client must also bind properly to the service

Yes, all WCF things need this, but I found documentation to be vexing, so I'll show exactly how I did it.

To get IIS configured to use Net.TCP, you need to go to control panel / install windows components, and make sure the following is selected:

This allows .NET to integrate with the Windows Process Activation Service to kick-start IIS on receipt of Net.TCP requests.  After installing this you will notice in the service management console the following service:

Make sure this service is running or you will get the an error when attempting to contact the service (I'll show the error later, once I get to some code).

Ok, A little of the prerequisites are out of the way so lets do a little coding!  Create a new visual studio solution which consists of a Silverlight 4 application and web site to serve the application.   My example looks like this:

At this point, because we cant use the VS.NET web server, we need to modify the web site configuration to run under IIS.  To do this, right click the web solution and bring up properties / web, and select "Use Local IIS Web server".  It will auto fill a project url, and then press 'Create Virtual Directory' to set up the application in IIS:

You should get a dialog stating that the virtual directory was created successfully.  Now add a WCF service to the web project that we will use to send messages back to the client.  I've called mine "PushDataService", and it creates an interface file (IPushDataService.cs) and PushDataService.svc file in the web project.  It is also needed to create an interface that represents the API that the server uses to talk back the the client, so I add an interface to the web solution named IPushDataCallback.

Now that we have the service and interfaces created, we need to add some method definitions to them and annotate them with attributes properly.  My IPushDataService interface is as follows:

namespace DuplexSilverlightExamples.Web
{
    [ServiceContract(CallbackContract = typeof(IPushDataCallback))]
    public interface IPushDataService
    {
        [OperationContract(IsOneWay = true)]
        void RegisterForUpdates();
        [OperationContract(IsOneWay = true)]
        void UnregisterForUpdates();
    }
}

The interface contains two methods, one that the client will call to notify the server that it wants to receive push updates, and another to tell the server would like to stop receiving updates.  Both of these methods are annotated with [OperationContract(IsOneWay = true)] which tells WCF that the client can call these methods and that there is no return value and it doesn't need to worry about a back channel.

The [ServiceContract(CallbackContract = typeof(IPushDataCallback))] on the interface tells WCF that the service implementing this interface is a WCF service and that it will support a communications channel back to the client and that it will follow the interface specified by IPushDataCallback.  And speaking of IPushDataCallback, here it is:

namespace DuplexSilverlightExamples.Web
{
    public interface IPushDataCallback
    {
        [OperationContract(IsOneWay = true)]
        void Update(string theUpdateMessage);
    }
}

This tells WCF that the communication channel back to the client will support a one way communications channel for passing a string message back to the client through the Update message.

Now we need to implement the service.  My service is implemented as such:

namespace DuplexSilverlightExamples.Web
{
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class PushDataService : IPushDataService
    {
        public static Dictionary<IPushDataCallback, IPushDataCallback> _clients =
            new Dictionary<IPushDataCallback, IPushDataCallback>();

        public PushDataService()
        {
            new Thread(new ThreadStart(pumpUpdates))
            {
                IsBackground = true
            }
            .Start();

        }

        public void RegisterForUpdates()
        {
            IPushDataCallback c = OperationContext.Current.GetCallbackChannel<IPushDataCallback>();
            if (!_clients.ContainsKey(c))
            {
                lock (_clients)
                {
                    _clients.Add(c, c);
                }
            }
        }

        public void UnregisterForUpdates()
        {
            IPushDataCallback c = OperationContext.Current.GetCallbackChannel<IPushDataCallback>();
            if (_clients.ContainsKey(c))
            {
                lock (_clients)
                {
                    _clients.Remove(c);
                }
            }
        }

        public void pumpUpdates()
        {
            Random w = new Random();

            List<IPushDataCallback> bad = new List<IPushDataCallback>();
            int count = 0;

            while (true)
            {
                Thread.Sleep(w.Next(10000));

                lock (_clients)
                {
                    if (_clients.Count > 0)
                    {
                        bad.Clear();
                        foreach (IPushDataCallback client in _clients.Keys)
                        {
                            try
                            {
                                client.Update(string.Format("{0}", count++));
                            }
                            catch (Exception)
                            {
                                bad.Add(client);
                            }
                        }

                        bad.ForEach(bc => _clients.Remove(bc));
                    }
                }
            }
        }
    }
}

The attributes on the class setup some Asp.NET compatibility, and also specify that I want a single instance of the service and that multiple clients can access it simultaneously.  The constructor starts a thread that runs the pumpUpdates method, and this will always run for the lifetime of the service, and since it is a singleton there will only be one of this tread running.  I also declare a dictionary object that will keep references to all connected clients that will be used to send the updates to the client.

The RegisterForUpdate method used the following statement:

IPushDataCallback c = OperationContext.Current.GetCallbackChannel<IPushDataCallback>();

What this does is it looks at the "context" of the current call - which contains information about various things, including any callback channels.  The GetCallbackChannel will look to see if there is an implementation of IPushDataCallback (which is specified on the IPushDataService definition, so it better be there).  If this client is not already in the dictionary, then the reference will be stored there for use by the pumpUpdates method.  The UnregisterForUpdates method basically does the opposite.

The pumpUpdates method will loop endlessly, sleeping for a random period up to 10 seconds, and then will send a message to all clients that are subscribed (the message is the count value).  Also on each pass through I keep track if there is an exception calling a specific client in the 'bad' list variable.  If an exception is caught, I'll remember that client and assume that it has "died" and that we don't want to call back to it anymore, and after all clients are updated I'll remove those "bad" clients from the update dictionary.

Ok, we've got the code in place.  Now we need to configure WCF (via the web.config) to support Net.TCP communication.  The configuration file as currently put together by vs.net is the following:


<?xml version="1.0"?>
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.webServer>
      <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>

    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>

We need to extend this to the following:


<?xml version="1.0"?>
<configuration>

    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
 
    <system.webServer>
      <modules runAllManagedModulesForAllRequests="true"/>
    </system.webServer>

    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
             
              <behavior name="PushDataServiceBehavior">
                <serviceMetadata httpGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="true" />
                <serviceThrottling maxConcurrentCalls="2147483647" />
              </behavior>
             
            </serviceBehaviors>
        </behaviors>

      <bindings>
        <netTcpBinding>
          <binding name="InsecureTcp">
            <security mode="None"/>
          </binding>
        </netTcpBinding>
      </bindings>
     
      <services>
        <service behaviorConfiguration="PushDataServiceBehavior"
                 name="DuplexSilverlightExamples.Web.PushDataService">
          <endpoint address="" binding="netTcpBinding" bindingConfiguration="InsecureTcp"
                    contract="DuplexSilverlightExamples.Web.IPmtPocPushService"/>
          <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
          <host>
            <baseAddresses>
              <add baseAddress="net.tcp://localhost:4502/DuplexSilverlightExamples.Web/PushDataService.svc" />
            </baseAddresses>
          </host>
        </service>
      </services>
     
    </system.serviceModel>
</configuration>

What I've done here is added three sections:

  1. A service definition
  2. A netTcpBinding declaration
  3. and a new behavior section

The service definition:


<service behaviorConfiguration="PushDataServiceBehavior"
         name="DuplexSilverlightExamples.Web.PushDataService">
  <endpoint address="" binding="netTcpBinding" bindingConfiguration="InsecureTcp"
            contract="DuplexSilverlightExamples.Web.IPmtPocPushService"/>
  <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
  <host>
    <baseAddresses>
      <add baseAddress="net.tcp://localhost:4502/DuplexSilverlightExamples.Web/PushDataService.svc" />
    </baseAddresses>
  </host>
</service>

What this is specifying is that we want WCF to create a service implementing the IPushDataService interface, that we want to use the behavior we added in another section, the binding in the binding section, and that we want to expose two endpoints, one for metadata (using the mexTcpBinding), and one using NetTcpBinding (what this is all about) with the new behavior as well as the specified binding we are adding. 

Note that it is needed to add a base address entry to the service specifying the full address of the service.  Net.TCP doesn't seem to like that and you'll get and error if you dont use it.  Note also that I specify that the port used is 4502.  Silverlight is limited to ports 4502 - 4534, so you better specify one in that range.

The netTcpBinding is needed as we need to specify that there is no security to be used on the channel.  Net.TCP does not currently support a secure channel (they say this will likely be added in a future version) and we are forced to explicitly specify the insecurity.  The behavior section is also useful, mostly to specify that we want to have the maximum amount of simultaneous clients accessing the service.

Ok, we now have the server side complete, and we need to modify the client to use the service.  Add a service reference to the client application.  Or, well, try to, because you will likely get the following error:

Contract Requires Duplex, ...  WTF?  Well, this is a problem that I always get and expect you will too, and needs to be addressed.  Unfortunately, I spent a lot of time googling this to no avail.  How did I solve it?  I rebooted the computer and that problem went away.  Go figure!

However, like many things like this, that one problem begat another:

But this one is well known, and mentioned earlier.  We need to configure both the web site and the web application to accept net tcp connections.  First, configure the binding on the web site by right clicking the site and selecting edit bindings:

So, add the binding for net.tcp on port 4502:*  Then, it is also necessary to add net.tcp to the application, so right click on the application, select manage application -> advanced settings, and make sure that net.tcp is also specified instead of just http:

You should now be able to add the service reference to the client application.

The client application I put together shows the messages in a listbox; I won't go into that code.  But to utilize the service, I modify the MainPage.xaml.cs file as such:

public partial class MainPage : UserControl
{
    private ObservableCollection<string> _updates = new ObservableCollection<string>();

    public MainPage()
    {
        InitializeComponent();

        messagesListbox.ItemsSource = _updates;

        pds.PushDataServiceClient c =
            new pds.PushDataServiceClient("NetTcpBinding_IPushDataService");
        c.UpdateReceived += c_UpdateReceived;
        c.RegisterForUpdatesAsync();
    }

    void c_UpdateReceived(object sender, pds.UpdateReceivedEventArgs e)
    {
        if (e.Error == null)
        {
            _updates.Add(e.theUpdateMessage);
        }
    }
}

This is pretty straight forward code.  I keep an overvable collection of strings that hold the update messages and it is bound to the items source of the listbox.  I create an instane of PushDataServiceClient and pass the name of the binding in the ServiceReferences.ClientConfig file for the service (automatically created by the add service reference process).  The UpdateReceived event is bound to a method which will be called when the Update method on the client is called by the server (which triggers the UpdateReceived event - the name is the method name + "Received").  The event handler check to see if there was no error, and if so adds the parameter to the callback to the list, which then triggers an update of the UI.

But wait.  There is still a problem.  If you run this as is, it just looks like nothing is happening.  So, run the application in the debugger and you get the following error:

This is caused by us not having a socket policy server running.  When Silverlight attempts socket communications, it will contact the origin server on port 943 and ask for a policy file to see if the client is allowed to do communications.  This was actually a big issue for me at first as I thought I could just post the policy file in IIS and map port 943 to serve it with TCP.  That did not work.  You need to write your own server to do this, but thankfully there is one available as an online template project that you can add to your solution.  So, add a new project to the solution, but select "Online Templetes" for "silverlight tcp":

Once you have that project added, you can start it manually (it's a console app), or do like I do and setup multiple project starts with it going first.  Once you have it running you should see something like this in the application:

That is the listbox showing the messages sent from the server.  The console window just behind is the socket policy server.

But wait - there is perhaps one more problem!  If for some reason the Net.Tcp Listener service is not running, you would get an error similar to the following.  If that is the case, make sure the service is running.

Phew!  That's about it!  Must be a record for me for a blog post, but I hope it saves you a lot of hassle!

BTW, I will have a follow up post where I extend this service to have a binding for Http Duplex Polling in addition to the Net.TCP binding.  This will allow Silverlight 3 clients to still use the service, albeit a bit less efficiently, but it does keep them from being excluded from all the fun.  I'll write about how to do that soon.

Using WCF RIA Services with your POCO, Part 5: Returning a POCO in another Assembly from the Domain Service

In part 4 of this series I showed how to declare a POCO for use in RIA services, and how to use the object on the client.  In this post, I'll show how to use a class in another project/assembly.  Honestly, it's not very difficult at all.

As part of the SocialBus solution, I already has a User class defined in another project (SocialBus.Model).  This is a pretty straightforward class as-is:



A user in SocialBus is just a SocialBus specific user id, and a ServiceInfo object.  The ServiceInfo object is what is of real interest in SocialBus, as it will contains users and messages from various social networks (Twitter, Yammer, ...) that are mapped to this SocialBus user with the specified ID.  But for purposes of this example, it is only needed to be concerned with this User class.

To RIA enable this class, all I need to do as before is annotate the class, and all that is needed for now is to add a Key attribute:



This class is now ready to be used in the RIA services library.  All that is needed to be done is to add a reference to SocialBus.Model to SocialBus.RIA.Web, and to change the domain service to return an instance of this User class:



Now this service is very contrived and not of much use, but this is just for showing this example.  In another series of posts I will discuss connecting the domain service to LINQ to SQL, Twitter and Yammer; returning collections of objects; but like I said that's for another time.

The differences in this service model are really just in the using for the SocialBus.Model namespace, and in returning and instance of that object.  The client only changes slightly (besides there are no e-mail and username properties) is that I needed to add a 'using SocialBus.Model;' line.

That's it for this series.  There's a lot more that can be covered, but like I said those will be for another series of posts (that I'll do soon).



Using WCF RIA Services with your POCO, Part 4: Returning a Simple POCO from RIA

In part 3 I showed how to access a simple RIA service from Silverlight, but it wasn't too interesting as it didn't even return an object of a class (just a double).  In this post I'll show how to extend the service to return an instance of a user class.  For simplicity I'll still implement this in the RIA web project and in later posts we'll use another library.

Creating a class for use in RIA services is as easy as creating a new class and adding a few data annotations.  In the case of SocialBus, the primary data type is a 'User', so I'll add a simple user class to the project and add a couple of useful properties:



This class itself isn't very useful for RIA services.  As a matter of fact if we tried to use it in a service API the system would throw an exception complaining that there is not a key defined for the class.  This is imporant in RIA services, even with POCO, as the class needs to have this attribute assigned using data annotations.  So, I'll add this by including the System.ComponentModel.DataAnnotations namespace, and the [Key] attribute on the ID property:



What is interesting is that if you compile the solution, there is still no additional code generated.  The code generator is smart enough to know that even though I annotated this class, that no domain service uses the class and therefore code is not needed.



Now I need to modify the domain service to return  User object.  This is a typical use case in SocialBus, that given an ID the client would like to get User object for that ID.  For right now to keep it simple I will just add a single GetUser method that takes no parameters and returns a canned instance (this will get much more complicated later):



I won't show the generated code for the service, but the generator has added a User class to the generated code:



Notice all the niceties here.  DataContract, DataMember and Key attributes; fully formed properties that handle all of the entity types of operations (on this, on that, ...); all automatic.

To use the object on the client, the Silverlight code changes to be as follows:



Notice that there are some subtle differences here than in the last example.  First, notice that the GetUser method in out domain service generates a method named 'GetUserQuery'.  This is because since it the method is returning and entity, it appends Query to the client side method name.  This is to clue you into the second difference, in that this method returns an EntityQuery<User> object instead of an InvokeOperation instance, because this is actually constructing an entity query object that is both lazy loaded and can be used in a LINQ clause.

The third difference is that to get the object it is needed to pass the query to the Load method of the domain context object.  This will actually invoke the service call asynchronously, and it is then possible to set the Completed event handler to a method that is executed when the call completed.

The final difference(s) are that the first parameter to the callback is of type LoadOperation<T>, and that to get the result values it is needed to access the 'Entities' property of this object, and in this case I get the first object and assign it to the data context of the user control.

For reference, here is the XAML for this control to show how the data binding is specified:



That's it for this post.  The next post will show how to use a POCO in another library other than the .web project created by the RIA wizard.

Using WCF RIA Services with your POCO, Part 3: Calling the Domain Service form a Silverlight Client

In part 2 I showed how to create a domain service and get the code generated for that service (heck that was automatic).  In this post I'll show how to call that service from Silverlight.

In the the first post I added a reference to the Silverlight project to the Silverlight.RIA project, which will allow the Silverlight application to use those classes.  I modify the MainPage.XAML to have a TextBox named 'result' and modify the MainPage.XAML.cs file to be as follows to call the service and display the result:



What's going on here?  We'll, there is a whole new syntax to these calls, which I will explain briefly. 

On lines 14 and 15 I add two namespaces as they are needed for the InvokeOperation (System.Windows.Ria), and the SocialBus.RIA.Web is the namespace in our RIA web project that contains the domain service.

The domain service we created is implemented by the SocialBusDomainContext class.  It has a bunch of methods for managing entities, as well as the method I added to the class, 'Add'.  To call the service, I create a new instance of this class, and call the 'Add' method.  As is the case in Silverlight, all calls are asynchronous, so to capture the result a delegate is assigned to the method calls return value's (which is an InvokeOperation object) Completed event handler.  I choose to use the lamba syntax for this, and the method is actually passed the InvokeOperation object and an EventArgs object.  I cast the 's' parameter to InvokeOperation<double> (the generic is important), get the return Value, convert it to a string and assign it to the text box on the UI.

Sure, there is a lot more detail that can be covered here, such as error/exception handling and such, but this show the basics of calling the service and using the result.  In the next post, I'll show how to create a POCO and pass it to the client.

Using WCF RIA Services with your POCO, Part 2: Creating a Simple Domain Service

In part 1 of this series of posts I covered adding a new WCF RIA Services Class Library to your solution.  In this post, I'm going to cover creating a domain service and getting the code generated for the domain service.  Note that in this post I'm not even going to create a new POCO - I'll keep it even simpler.  In follow up posts I'll show how to use POCO and an POCO in an existing library.

To add a domain service for that will eventualy serve POCO objects, and hence create a web service to implement it, I add a new items called 'Domain Service Class' to the SocialBus.RIA.Web project:



When you press add on this dialog, you will then be presented with the 'Add New Domain Service Class' dialog.  The purpose of this dialog is to allow you to select a data context (or object context) from you solution for the derive the domain service.  Normally this adds a lot of smarts to the domain service for managing entities exposed by providers like the Entity Framework.  Since we are using POCO, we can just select 'OK':



This adds a file named 'SocialBusDomainService.cs' to the project, and it looks like the following:



There's not a whole lot to this class, but I'll shortly be adding methods to provide functionality to clients.

One thing that I'm going to do right now is add a quick Silverlight application to the solution for showing how to use these classes; right now we have no place to use these so we need to do that now.  So, in the RIA folder I add a new Silverlight application (named SocialBus.RIA.TestClient) and I already had a web project in the solution (named SocialBus.Web) so I serve up the Silverlight app from that project. 

I also make sure to 'Enable .NET RIA Services' on the dialog that pops up:



Two things now need to be done.  I need to add references for the RIA projects to both the new Silverlight client, and to SocialBus.web web site.  So, in the new Silverlight project I a reference to SocialBus.RIA, and to the SocialBus.Web I add a reference to SocialBus.RIA.Web.  What this does is allow the Silverlight app to use the code generated by VS.NET / RIA, and the reference to SocialBus.Web extends that solution to know how to serve up the domain services declared sin SovialBus.RIA.Web.

Before proceeding, a useful thing to do is to select 'Project -> Show All Files' from the main menu when the SocialBus.RIA project is selected.  RIA auto-generates code into a hidden folder anmed in that solution, and this lets you see that folder and the code files:



Right now there is not folder or files files as no code has been generated, even if you compile the solution.  This is because the domain service is empty at this point, and the code generation extensions see this and don't generate anything.  As a matter of fact, there is also a warning to this fact emitted by the compiler:



To get some code generated, I'll add a real simple method to the domain service.  I don't think this scenario is written anywhere, as every example seems based upon entities, and CRUD operations.  What I'm going to do is just add a method that adds two doubles and returns the result:



I'll be honest, I'm not sure this is even supposed to work as I can't find any info that supports it.  But it does.  Compile the solution and you now see code generated:



Cool!

Double click the generated file to examine the generated code.  The at this point contains one class, SocialBusDomainContext, which is the class we will use in the Silveright project to call the domain service (partially shown here):



Note the 'Add' method which is generated to match the add method of the domain service we created.  There are actually two versions with different signatures that are created (to give different ways of calling the service):



One thing I want to point out at this point.  How is this code generation triggered, and how does it know what code to look at?  Open the properties for the SocialBus.RIA project, and it shows the following:



The .NET RIA Services link specifies a project, that when this project is compiled, that will be examined for domain services and entities, and for those identified code will be generated.

One more thing.  Because I'm using a Silverlight RIA Class Library and my own web site (not one auto generated by the wizard), the web.config on my site must be modified to know how to serve the RIA service from the domain service class.  Getting this to work requires adding three entries to web.config:



There's is still some magic in all of this on how the service is exposed, but that's a story for another post.

Okay, I think that's enough for this post.  In the next post I'll show how to call this service from Silverlight.

 

Using WCF RIA Services with your POCO, Part 1: Creating a WCF RIA Service Library

Now that it's post PDC09 I've decided to take some time to migrate some of the code that I have in my SocialBus project from standard WCF and DTO's over to RIA services.  The SocialBus project is something I've been working on as an evolution of back end of the TweetZenn client I was building before.  What it will provide is a unified interface to various social networks; right now that being just Twitter and Yammer.

Up to now I've built it with standard WCF services.  This always had a problem that bugs me to now end.  In the solution I have "Model" classes for the domain, and the service calls return those model objects to the client.  The problem is that to use the service in Silverlight, the proxy generator builds new classes based off of the WSDL from the service.  These classes look the same from the perspective of properties, but they are:

  1. In a different namespace
  2. Lose any methods to perform manipulations of the data in the objects

What this is in all actuality is an implementation of the Data Transfer Object pattern implemented by visual studio.  It's problematic for the reasons mentioned above, as well as if you build any libraries that use the model objects, the objects you have in the client are actually not the objects in the library, and it won't work.

A typical scenario to solve this is the following:

  1. Cross-compile the model code in Silverlight, and
  2. Project the DTO objects into the silveright versions of the model objects

Well, this works fine, but it's a real pain in the butt.  Every model object's .cs flle has to be added as a link into a Silverlght project.  First, this is real fun with the Silverlight and non-silverlight libraries get out of sync because you forgot to add a link to a new class.  Second, you are doing all these projects.  Sure, LINQ makes it real easy, but why can't I just use my object as I defined it the first time!?!?

Well, WCF RIA services is supposed to solve all of this.  I've played with it a bit in the last week and decided to really start using it.  Note, I tried the CTP and had too much trouble with it, but those issues seem to be solved.  So, I'm going to stick it in a real project now and give you some tips on how to use it. 

Now, this may not be the most elegant way of doing it.  It's what I'm doing to learn more.  Also, I am using POCO, which is for the most part very sparsely documented and not in a manner of how I want to use it.  Finally, yes, I use LINQ to SQL on the backend, and I could just move to LINK to EF and use RIA to move the entities to the client.  However, this has issues to me that are not obvious yet in this solution; so yes, I could do it and things would be easier for purposes of this demonstration, but it is not in the long run so I'm just going to use LINQ to SQL for that database access and project them into the domain model POCO objects for passing back by RIA (also note that client side I am not planning to need any entity tracking, so that lack of functionality also makes EF an amount of overkill).

To start out, the solution looks like this:



What we need to do is add a WCF RIA Services Class Libary to the solution (I'm putting it in a solution folder named 'RIA' - which is already shown):



This creates two projects in the solution:



The Class1.cs files are not needed so I will delete them as I'm going to use an existing C# library instead of adding new classes to these projects.  This is one area in existing documentation that is not clear as it always mentions to add new classes to these projects.  What if I have existing classes in another assembly and I don't want to duplicate effort (Dont Repeat Yourself - DRY)?  Well it's okay as it works fine and I'll show an example of it.

Anyway, what are the purposes of these two projects?

The project that ends in '.Web' is where we will place our RIA domain service(s), which will eventually be exposed as WCF services (I'd say web services, which used to be true, but there are other potentials now too).  This project can be linked into your web project for you Silverlight app and the service(s) defined by the domain service classes will be exposed from that web site.  Also, in most examples on the web, you also put your domain objects in this solution.  Since I've got them declared already, we'll only be putting domain services in here.

The other project is where the RIA services extensions in Visual Studio will auto generate code for Silverlight based applications, which includes both service proxies, as well as Silverlight based versions of your domain objects.  This code generation is done by the extensions by examining the attributes on classes in this solution (and it turns out any referenced assemblies) post compile.

This is really convenient for the following reasons:

  1. You don't have to manually create the proxies through add service reference,
  2. You never have to regenerate proxies when changing the service interface (the code is always regenerated),
  3. The domain objects are in the same namespace as you gave them in wither the .web file, or in our case the assembly that we already have written, and
  4. The signature of the Silverlight objects will be the same, and given the correct use of RIA attributes, will also have any methods that you define for client side business logic.

Well, I'm thinking I'll break this into a number of parts as it appears this will be involved.  In the next post, I'll write about how to create and consume a really basic domain service thereby showing how RIA makes this all work.

 

403.3 Problem with WCF and Azure WebRole in local development fabric

During the building of the WCF service mentioned in my previous post, I came across an error when trying to access the WCF service when running it within the local development fabric.  It worked fine when just running the web role, and when deployed into Azure.  So, this led me to investigating if the IIS as used by the local development fabric to see if it was not configured to serve .SVC files.

One of the first things that I did to investigate was to just navigate to the service in the browser with a brand new service project that I put together.  When doing this, I received the following:



There should be a page showing the information about the service, instead a 403.3 error.  Likewise, when stepping through the debugger, similar errors could be seen when checkin the exceptions.

After a bit of googling, the solution to this turns out to be the following.  Apparently, WCF is not configured properly with IIS.  This feels very similar to the problem when ASP.NET sometimes is not configured properly, in that the solution is very similar.

To solve the problem, navigate to the windows communication foundation folder as shown here, and run the "ServiceModelReg.exe -i" command.



After running that program, you will see output similar to the following and the problem will then be solved.



About the author

I'm a .NET, XAML, and iOS polyglot that loves playing with new things and making cool and innovative stuff.  I am also a Mac junkie.

I am Principal Technologist for SunGard Global Services in NYC, in their Advanced Technologies practice, and I work extensively with SunGard's energy and financial customers.

Note the the posting on this blog are my own and do not represent the position, strategies or opinions of SGS.

Widget TwitterFeed not found.

The file '/widgets/TwitterFeed/widget.ascx' does not exist.X

Recent Comments

None

Month List