简体   繁体   English

Silverlight使用RIA Services Silverlight Client与WCF交谈

[英]Silverlight talking to a WCF using RIA Services Silverlight Client

My silverlight project has references to the RIA Services Silverlight Client and my .web application has access to RIAServices.Server. 我的silverlight项目引用了RIA Services Silverlight客户端,而我的.web应用程序可以访问RIAServices.Server。

I can't seem to find a good tutorial to learn how to connect these. 我似乎找不到很好的教程来学习如何将它们连接起来。 Once I understand how to get the data from my NumberGenerator method. 一旦我了解了如何从NumberGenerator方法获取数据。 I can pick it up from there. 我可以从那里拿起。 I have three questions that I need some help with. 我有三个问题需要帮助。

First, am I setting up this project correctly? 首先,我是否正确设置了这个项目? I never done a project with RIA before. 我以前从未与RIA合作完成过一个项目。

Secondly what reference do I need to use ServiceContract(), FaultContract, and OperationContract? 其次,使用ServiceContract(),FaultContract和OperationContract需要什么参考? Most examples show that they are in the System.ServiceModel library. 大多数示例表明它们位于System.ServiceModel库中。 In this case with using the external library RIA Services Silverlight Client that is not the case. 在这种情况下,使用外部库RIA Services Silverlight Client并非如此。 It throws a error saying I am missing a reference. 引发错误,提示我缺少参考。 What other libraries would have those three in it? 还有哪些其他图书馆有这三个图书馆?

My last question is what URI do you use in the SystemDomainContext? 我的最后一个问题是您在SystemDomainContext中使用什么URI? Where I found the code at used this MyFirstRIAApplication-Web-EmployeeDomainService.svc but in my case I don't have anything that has a .svc extension. 在哪里找到使用此MyFirstRIAApplication-Web-EmployeeDomainService.svc的代码,但就我而言,我没有任何扩展名为.svc的东西。 Would I use the .xap or .aspx? 我会使用.xap还是.aspx?

Here is my Silverlight code 这是我的Silverlight代码

Here is my NumberGenerator Silverlight UserControl Page Code 这是我的NumberGenerator Silverlight UserControl页面代码

public partial class NumberGenerator : UserControl
{
    public NumberGenerator()
    {
       InitializeComponent();
       GenerateNumber();
     }

    private void GenerateButton_Click(object sender, RoutedEventArgs e)
    {
        GenerateNumber();
    }

    private void GenerateNumber()
    {
       int result = 0 
       SystemClientServices systemclientservices = SystemClientServices.Instance;
       result = systemclientservices.GenerateNumber();
       NumberLabel.Content = result;
    }
} 

Here is my System Client Services class 这是我的系统客户端服务类

private readonly static SystemClientServices _instance = new SystemClientServices();

private SystemDomainContext _domainContext = new SystemDomainContext();

private SystemClientServices() { }

public static SystemClientServices Instance
{
    get
    {
        return _instance;
    }
}

public int GenerateNumber()
{
    //Code goes here to get the information from the Domainservices
    LoadOperation load = this._domainContext.Load(this._domainContext.GetNumberGeneratorQuery(), LoadBehavior.KeepCurrent, false);
    return Convert.ToInt32(load.Entities);
}

Here is my NumberGenerator class on the silverlight local project 这是我在silverlight本地项目上的NumberGenerator类

 public sealed partial class NumberGenerator : Entity
 {
    private static readonly NumberGenerator _instance = new NumberGenerator();
    public int NumberGenerated { get; set; }

    public NumberGenerator()
    {
        NumberGenerated = 0;
    }

    public static NumberGenerator Instance
    {
        get
        {
            return _instance;
        }
    }
 }

Here is System Domain Conext class on the silverlight local project 这是Silverlight本地项目上的System Domain Conext类

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.ComponentModel.DataAnnotations;
 using System.Linq;
 using System.Runtime.Serialization;
 using System.ServiceModel.DomainServices;
 using System.ServiceModel.DomainServices.Client;
 using System.ServiceModel.DomainServices.Client.ApplicationServices;
 using System.ServiceModel.Web;
 using System.ServiceModel;
 public sealed partial class SystemDomainConext : DomainContext
 {
    #region Extensibility Method Definitions

    /// <summary>
    /// This method is invoked from the constructor once initialization is complete and
    /// can be used for further object setup.
    /// </summary>
    partial void OnCreated();

    #endregion


    /// <summary>
    /// Initializes a new instance of the <see cref="EmployeeDomainContext"/> class.
    /// </summary>
    public SystemDomainConext() : this(new WebDomainClient<ISystemDomainServiceContract>(new Uri("MyFirstRIAApplication-Web-EmployeeDomainService.svc", UriKind.Relative)))
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="EmployeeDomainContext"/> class with the specified service URI.
    /// </summary>
    /// <param name="serviceUri">The EmployeeDomainService service URI.</param>
    public SystemDomainConext(Uri serviceUri) : this(new WebDomainClient<ISystemDomainServiceContract>(serviceUri))
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="EmployeeDomainContext"/> class with the specified <paramref name="domainClient"/>.
    /// </summary>
    /// <param name="domainClient">The DomainClient instance to use for this DomainContext.</param>
    public SystemDomainConext(DomainClient domainClient) : base(domainClient)
    {
        this.OnCreated();
    }

    /// <summary>
    /// Gets the set of <see cref="Employee"/> entity instances that have been loaded into this <see cref="EmployeeDomainContext"/> instance.
    /// </summary>
    public EntitySet<NumberGenerator> GeneratedNumber
    {
        get
        {
            return base.EntityContainer.GetEntitySet<NumberGenerator>();
        }
    }

    /// <summary>
    /// Gets an EntityQuery instance that can be used to load <see cref="Employee"/> entity instances using the 'GetEmployee' query.
    /// </summary>
    /// <returns>An EntityQuery that can be loaded to retrieve <see cref="Employee"/> entity instances.</returns>
    public EntityQuery<NumberGenerator> GetNumberGeneratorQuery()
    {
        this.ValidateMethod("GetGeneratedNumber", null);
        return base.CreateQuery<NumberGenerator>("GetNumberGenerator", null, false, true);
    }

    /// <summary>
    /// Creates a new EntityContainer for this DomainContext's EntitySets.
    /// </summary>
    /// <returns>A new container instance.</returns>
    protected override EntityContainer CreateEntityContainer()
    {
        return new NumberGeneratorDomainContextEntityContainer();
    }

    /// <summary>
    /// Service contract for the 'EmployeeDomainService' DomainService.
    /// </summary>
    [ServiceContract()]
    public interface ISystemDomainServiceContract
    {
        /// <summary>
        /// Asynchronously invokes the 'GetEmployee' operation.
        /// </summary>
        /// <param name="callback">Callback to invoke on completion.</param>
        /// <param name="asyncState">Optional state object.</param>
        /// <returns>An IAsyncResult that can be used to monitor the request.</returns>
        [FaultContract(typeof(DomainServiceFault), Action="http://tempuri.org/EmployeeDomainService/GetEmployeeDomainServiceFault", Name="DomainServiceFault", Namespace="DomainServices")]
        [OperationContract(AsyncPattern=true, Action="http://tempuri.org/EmployeeDomainService/GetEmployee", ReplyAction="http://tempuri.org/EmployeeDomainService/GetEmployeeResponse")]
        [WebGet()]
        IAsyncResult GetGeneratedNumber(AsyncCallback callback, object asyncState);

        /// <summary>
        /// Completes the asynchronous operation begun by 'BeginGetEmployee'.
        /// </summary>
        /// <param name="result">The IAsyncResult returned from 'BeginGetEmployee'.</param>
        /// <returns>The 'QueryResult' returned from the 'GetEmployee' operation.</returns>
        QueryResult<NumberGenerator> EndGetGeneratedNumber(IAsyncResult result);

        /// <summary>
        /// Asynchronously invokes the 'SubmitChanges' operation.
        /// </summary>
        /// <param name="changeSet">The change-set to submit.</param>
        /// <param name="callback">Callback to invoke on completion.</param>
        /// <param name="asyncState">Optional state object.</param>
        /// <returns>An IAsyncResult that can be used to monitor the request.</returns>
        [FaultContract(typeof(DomainServiceFault), Action="http://tempuri.org/EmployeeDomainService/SubmitChangesDomainServiceFault", Name="DomainServiceFault", Namespace="DomainServices")]
        [OperationContract(AsyncPattern=true, Action="http://tempuri.org/EmployeeDomainService/SubmitChanges", ReplyAction="http://tempuri.org/EmployeeDomainService/SubmitChangesResponse")]
        IAsyncResult BeginSubmitChanges(IEnumerable<ChangeSetEntry> changeSet, AsyncCallback callback, object asyncState);

        /// <summary>
        /// Completes the asynchronous operation begun by 'BeginSubmitChanges'.
        /// </summary>
        /// <param name="result">The IAsyncResult returned from 'BeginSubmitChanges'.</param>
        /// <returns>The collection of change-set entry elements returned from 'SubmitChanges'.</returns>
        IEnumerable<ChangeSetEntry> EndSubmitChanges(IAsyncResult result);
    }

    internal sealed class NumberGeneratorDomainContextEntityContainer : EntityContainer
    {

        public NumberGeneratorDomainContextEntityContainer()
        {
            this.CreateEntitySet<NumberGenerator>(EntitySetOperations.Edit);
        }
    }
}

Here is my System Domain Services class that is on the Silverlight.web 这是我在Silverlight.web上的“系统域服务”类

[EnableClientAccess()]
public class SystemDomainServices : DomainService
{
  private NumberGenerator numberGenerator = NumberGenerator.Instance;
  public int NumberGenerate()
  {
      return numberGenerator.NumberGenerated;
  }
}   

Here is the NumberGenerator class on the silverlight.web 这是silverlight.web上的NumberGenerator类

private static readonly NumberGenerator _instance = new NumberGenerator();
[Key]
public int NumberGenerated { get; set; }

public NumberGenerator()
{
    NumberGenerated = GenerateNumber();
}

public static NumberGenerator Instance
{
    get
    {
        return _instance;
    }
}

public int GenerateNumber()
{
    string db_date = "";
    int db_num = 0;
    string todaysdate = "";
    int temp_num = db_num;
    int result = 0;
    using (SqlConnection connection = new SqlConnection(DBConnectionString))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand("SELECT * FROM table", connection))
        {
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    db_date = reader.GetString(0);
                    db_num = (int)(reader.GetSqlInt32(1));
                    todaysdate = DateTime.Now.ToString("yMMdd");
                    temp_num = db_num;
                }
                reader.Close();
            }
            if (todaysdate != db_date)
            {
                using (SqlCommand dateUpate = new SqlCommand("UPDATE table SET tsDate='" + todaysdate + "' WHERE tsDate='" + db_date + "'", connection))
                {
                    dateUpate.ExecuteNonQuery();
                }
                db_num = 0;
                db_date = todaysdate;
            }
            db_num++;
            using (SqlCommand numUpate = new SqlCommand("UPDATE table SET tsNum='" + db_num + "' WHERE tsNum='" + temp_num + "'", connection))
            {
                numUpate.ExecuteNonQuery();
            }
            result = Convert.ToInt32(db_date + db_num.ToString().PadLeft(3, '0'));
            connection.Close();
            connection.Dispose();
        }
        return result;
    }
}

The answer to question two you might be have to go to Tools at the top, NuGet Package Manager, Package Management Console, and then type the following command to install the package for those three functions. 问题2的答案可能必须转到顶部的工具,NuGet程序包管理器,程序包管理控制台,然后键入以下命令来为这三个功能安装程序包。 PM> Install-Package RIAServices.Silverlight.DomainDataSource PM>安装包RIAServices.Silverlight.DomainDataSource

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM