.Net RIA Service – Hello World

Trusted By

Welcome Back! I hope you enjoy the content on this site. If you have not done so already, you may want to subscribe to my RSS feed or become a fan of this blog on Facebook. Thanks for visiting!

This is the second part of the a multi post series on .Net RIA Services. The first part – Getting Started with .Net RIA Services - was about how to get started, what you need to install and an overview of the platform. If you are new to the platform I recommend reading the overview first.

On this article I will focus on building a simple Hello World application to explain the use of the domain service and the code generation on the client side.

So let’s get to it, we will start by creating our solution and adding our projects. We will first create an ASP.Net Web Application:

image 

We will call our web application Demo.HelloWorld and create the solution at the same time.

The next step is to add a new project to our solution to create the Silverlight client application:

image

Leave everything in the next dialog as it is. It should look like this:

image

One thing that is important is the “link to ASP.NET server project” check box. This tells visual studio and the generator that we want to generate proxy classes for our client.

You can also set this option from the properties page of the Sliverlight client application.

image

Now your  solution should have this structure:

image

Now that we are all setup we can get to the interesting stuff.

The component that allows all the magic  to happen and is the critical step that demonstrates the new features of the .Net RIA Services Framework is the DomainService Class; so let’s take a deeper look at this class.

A DomainService is a class that exposes entities and operations for a specific data domain. It is also where you can add the application logic. You can think of it as the business layer in an n-tier application.

The .NET RIA Services framework contains the plumbing code to make the entities and operations declared in a DomainService class available to other tiers.

We will create our sample DomainService by selecting the server project and choosing Add New Item. Under the Web category is the new Domain Service Class template. We choose to call this new DomainService class HelloWorldService:

image

Next we are presented with another dialog dialog where we can Enable/Disable Client Access. Enabling client access results in having the class tagged with the attribute EnableClientAccess this attribute will tell Visual Studio to generate the proxy class to any linked client.

We can also specify the DataContext or ObjectContext that the domain service will utilize. Since we haven’t defined any we will leave this part to its default value.

image

Our HelloWorldService class should look like this:

namespace Demo.HelloWorld
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web.Ria;
    using System.Web.Ria.Data;
    using System.Web.DomainServices;

    // TODO: Create methods containing your application logic.
    [EnableClientAccess()]
    public class HelloWorldService : DomainService
    {
    }
}

 

If we compile our solution we will get the following warning:

image

So let’s make the compiler happy and add a method to our service. Our method will be a simple with no arguments and returns a string.

        [ServiceOperation]
        public string SayHello()
        {
            return "Hello RIA World!";
        }

 

Notice the ServiceOperation attribute, methods marked with the [ServiceOperation] attribute will:

  • Generate an event in the DomainContext that will fire when that operation completes

  • Generate a method with the same signature in the DomainContext that will cause the server method to be called immediately but asynchronously

I guess it’s time we talk about the DomainContext. The domain context class is a class that the proxy generated on the client application inherits from and contains the implementation of the plumbing required to invoke the methods on the server.

After building the solution we can take a look at the generated code to call our method in the Silverlight client application.

image

As described above the generated class inherits from DomainContext

public sealed partial class HelloWorldContext : DomainContext
    

 

And here is the implementation of the call to our method. The call is asynchronous and thanks to the .Net RIA Services we don’t need to write any additional code to consume the server side methods from the client app.

public void SayHello()
{
   base.InvokeServiceOperation("SayHello", typeof(string), null, 
                   this.OnSayHelloCompleted, null);
}

 

Now we can try to call our method. Let’s add a TextBlock and a Button to the Silverlight client; to do that open MainPage.xaml and copy/paste the code below.

<UserControl x:Class="Demo.HelloWorld.Client.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel Orientation="Vertical">
            <TextBlock Name="HelloTextBlock" Width="150" Height="50" FontSize="15"
                       Margin="5" Foreground="Navy"></TextBlock>
            <Button Name="HelloInvokeButton" Click="HelloInvokeButton_Click" 
                    Width="100" Height="20" Content="Invoke Method"></Button>
         </StackPanel>
    </Grid>
</UserControl>

Add the code bellow to MainPage.xaml.cs

private void HelloInvokeButton_Click(object sender, RoutedEventArgs e)
{
    Demo.HelloWorld.HelloWorldContext context = new HelloWorldContext();

    context.SayHelloCompleted += new EventHandler
                <System.Windows.Ria.Data.InvokeEventArgs>(context_SayHelloCompleted);

    context.SayHello();

}

void context_SayHelloCompleted(object sender, 
                       System.Windows.Ria.Data.InvokeEventArgs e)
{
    HelloTextBlock.Text = (string)e.ReturnValue;
}

 

We added the event handler for the button click and handler for the asynchronous call to our SayHello method.

Now let’s build and test the application:

image

Click on the button to test!

image 

Really cool isn’t it?

Check back soon for the next parts of this series.

Update: Check out the next part about using Metadata Programming in .Net RIA Services

Hope this was helpful.

Hatim

13 Comments

.Net RIA Service – Hello World | Hatim’s Development Blog…

Thank you for submitting this cool story - Trackback from DotNetShoutout…

[...] Started with .Net RIA Services and .Net RIA Service – Hello World and .Net RIA Services Metadata Programming [...]

So, what if you wanted to have a number of RIA Services defined and you wanted them to be on seperate web servers … how can the silverlight client link to more than one?

Ed,

I think what you are trying to say is your have one Silverlight client application that consumes services from multiple domains.

It’s pretty easy to achieve in the generated code for your DomainContext you have this constructor which takes as a parameter the URI for the domain you want to consume:
HelloWorldContext(Uri serviceUri)

It should do the trick.

[...] is a question that came up in the comments of my Hello World .Net RIA Services [...]

Excellent, and well explained and it works well.

In VB.Net, (RIA Services - July 2009 Preview) the HelloWorldContext class does NOT seem to generate events.

So for this service method:

Public Function SayHello() As String
Return “Hello World”
End Function

Here’s the generated code:

Public Overloads Function SayHello() As InvokeOperation(Of String)
Return MyBase.InvokeServiceOperation(Of String)(”SayHello”, Nothing, Nothing, Nothing)
End Function

Does anyone have any idea why it isn’t generating the event code?

I have two issue:
1. I don’t see SayHelloCompleted in my generated code.
2. I don’t see InvokeEventArgs in System.Windows.Ria.Data

Hi there,

My apologies if this has been answered elsewhere. I have looked around but can’t find it.

My issue appears similar to the 2 earlier posts.

1. I don’t see SayHelloCompleted in my generated code.
2. I don’t see InvokeEventArgs in System.Windows.Ria.Data

I suspect I have missed something really obvious (and embarressing!).

Thanks again for the article, if I can get it to run in VB it will be fantastic.

Thanks, GB

I’m using the newest version of RIA services, and I’ve been trying to figure this out for a while, how to do primitive types, since everything I try tries to give me an IEnumerable instead, but I can’t seem to find the ServiceOperationAttribute class in the dll’s I have. What namespace is it supposed to be in, and what version of the dll?

For the current release, replace [ServiceOperation] with [Invoke] and use :

private void HelloInvokeButton_Click(object sender, RoutedEventArgs e)
{
Demo.HelloWorld.HelloWorldContext context = new HelloWorldContext();
InvokeOperation invokeOp = context.SayHello();
invokeOp.Completed +=new EventHandler(context_SayHelloCompleted);
}

void context_SayHelloCompleted(object sender, EventArgs e)
{
InvokeOperation op = (InvokeOperation)sender;
HelloTextBlock.Text = op.Value.ToString();
}

for the methods in the client.

Leave a Comment