Getting Started with WCF RIA Services

I know many posts have been written on this subject by many people, but I am writing this one mostly for myself.  I find it very useful to type my thoughts on any subject and create a sample project to help me commit more information to memory.  So, here it goes.

What you need to get started.

  1. Visual Studio 2008 SP 1 (You can use 2010 as well)
  2. WCF RIA Services Beta for Visual Studio 2008 SP1 (http://www.microsoft.com/downloads/details.aspx?FamilyID=76bb3a07-3846-4564-b0c3-27972bcaabce&displaylang=en)

Here is what needs to be done next.

Create new Silverlight project.  To do so just create new project and select Silverlight.  Make sure to create a host web site as well.

image

On the next wizard screen select an option to create new host web site and enable .NET RIA Services.

image

 

Now, add new project to the solution, selecting WCF RIA Services Library under Silverlight projects.

image

Here is what your solution will look like:

image

Go ahead and delete Class1.cs from both RIAServicesLibrary projects.  What you see here are two new project.  RIAServicesClassLibrary1.Web will be server side project, the other RIA project is client side.  Now you need to establish references.  Add a project reference to SilverlightApplication1 and point it to RIASerivcesLibrary1 project.  Add a project reference to SilverlightApplication1.Web and point it to RIAServicesLirbary1.Web.

 

Now you need to create Entity Framework item inside the RIAServicesLibrary1.Web project.

image

Follow all the step of that wizard, generating a model from the database and pointing to a new or existing server connection.  You can select all or some tables from a database.

Go ahead and build your solution now.

Now add another new item to RIAServicesLirbary1.Web project and select Domain Service Class

image

Select the Entity Framework model you just created in that wizard and select tables you would like to use on the client.

image

Rebuild the solution once more to generate Silverlight side hidden classes that support RIA Services.  You can see that code if you click on Show All Files button in Solution Explorer:

image

Now, I am going to test the setup by adding the following code to MainPage.xaml.cs.  I am going to simulate the login process by getting a specific user from my Users table and checking the password:

using System.Windows.Ria;

using System.Linq;

public partial class MainPage : UserControl

    {

        DomainService1 _context = new DomainService1();

        public MainPage()

        {

            InitializeComponent();

            Login();

        }

 

        private void Login()

        {

            var query = _context.GetUsersQuery().Where(one => one.UserName == "admin");

 

            _context.Load<Users>(query, LoadBehavior.RefreshCurrent, (o) =>

            {

                if (o.Error != null)

                    MessageBox.Show(o.Error.ToString());

                else

                {

                    if ((o.AllEntities.Count() == 1) &&

                        (o.AllEntities.First() as Users).Password == "admin")

                    {

                        MessageBox.Show("Login successfull.");

                    }

 

                    else

                    {

                        MessageBox.Show("Login failed.");

                    }

                }

            }, null); ;

        }

    }

Next we need to update web.config in SilverlightApplication1.Web project using app.config from RIAServicesLirbary1.Web project as an example.  Make sure to paste all appropriate data into correct places:

<?xml version="1.0" encoding="utf-8"?>

<configuration>

    <connectionStrings>

        <add name="RolodexEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.sql2008;Initial Catalog=Rolodex;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

    </connectionStrings>

    <system.serviceModel>

        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

    </system.serviceModel>

    <system.web>

        <httpModules>

            <add name="DomainServiceModule" type="System.Web.Ria.Services.DomainServiceHttpModule, System.Web.Ria, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

        </httpModules>

    </system.web>

</configuration>

Run the application now to confirm that everything is working properly.  In the next post I will explore the subject of updating the data on the server.

6 Comments

  1. Hi !
    I’m develop similar app.
    I have 10 entyti’s and 10 diferent connection strings.
    In my app.setings, i create ONE connString metadata=res://*;provider=System.Data.SqlClient;provider connection string=”Data Source=localhost;Initial Catalog=XXX;Connect Timeout=20;User ID=XXX;Password=XXX”
    In my service class I create new instance of model1, my select function work fine,
    but when i try to submitchange()
    I get error

    at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
    at System.Web.DomainServices.Providers.LinqToEntitiesDomainService`1.GetEntitySetName(Type entityType)
    at System.Web.DomainServices.Providers.LinqToEntitiesDomainService`1.SetEntityKey(EntityObject entity)
    at System.Web.DomainServices.Providers.LinqToEntitiesDomainService`1.ExecuteChangeSet(ChangeSet changeSet)
    at System.Web.DomainServices.DomainService.Submit(ChangeSet changeSet)
    at System.Web.Ria.Services.ChangeSetProcessor.Process(DomainService domainService, IEnumerable`1 changeSetEntries)
    at System.Web.Ria.Services.SubmitOperationBehavior.SubmitOperationInvoker.InvokeCore(Object instance, Object[] inputs, Object[]& outputs)

  2. I have found a solution for my problem.
    In my service class:
    public override void Initialize(DomainServiceContext context)
    {
    this.ObejctContext.Connection.ConnectionString =
    GetConnString(“model name”);
    base.Initialize(context);
    }

    public static string GetConnString(string entity_name)
    {
    EntityConnectionStringBuilder conStrIntegratedSecurity = new
    EntityConnectionStringBuilder()
    {
    Metadata = “res://*/FOLDER.” + entity_name + “.csdl|res://*/FOLDER.”
    + entity_name + “.ssdl|res://*/FOLDER.”+entity_name+”.msl”,
    Provider = “System.Data.SqlClient”,
    ProviderConnectionString = Properties.Settings.Default.myConn
    };
    return conStrIntegratedSecurity.ToString();
    }
    and in designe settings.settings:
    Properties.Settings.Default.myConn = Data Source=localhost;Initial Catalog=XXX;Connect Timeout=20;User ID=XXX;Password=XXX”

    This work fine.

  3. How to reload(refresh) frame element?

    I navigate
    Frame.Navigate(new Uri(“/Templates/FormPage.xaml”, UriKind.Relative));
    and on some button_click call again
    Frame.Navigate(new Uri(“/Templates/FormPage.xaml”, UriKind.Relative));
    but nothing occur.

    tnx

Leave a Reply

Your email address will not be published. Required fields are marked *