Silverlight 使用 RIA Services Silverlight Client 与 WCF 通信

本文关键字:Silverlight WCF 通信 Services 使用 RIA Client | 更新日期: 2023-09-27 17:57:15

我的 silverlight 项目引用了 RIA Services Silverlight 客户端,我的 .web 应用程序可以访问 RIAServices.Server。

我似乎找不到一个好的教程来学习如何连接这些。一旦我了解如何从我的数字生成器方法获取数据。我可以从那里捡起来。我有三个问题需要帮助。

首先,我是否正确设置了此项目?我以前从未与RIA做过项目。

其次,我需要什么参考才能使用ServiceContract(),FaultContract和OperationContract?大多数示例显示它们位于 System.ServiceModel 库中。在这种情况下,使用外部库 RIA Services Silverlight 客户端的情况并非如此。它抛出一个错误,说我缺少引用。还有哪些图书馆会包含这三个库?

我的最后一个问题是你在SystemDomainContext中使用什么URI?我在哪里找到代码使用了这个MyFirstRIAApplication-Web-EmployeeDomainService.svc,但就我而言,我没有任何具有.svc扩展名的东西。我会使用 .xap 还是.aspx?

这是我的银光代码

这是我的 NumberGenerator Silverlight 用户控件页面代码

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;
    }
} 

这是我的系统客户端服务类

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);
}

这是我在 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;
        }
    }
 }

这是 silverlight 本地项目上的系统域 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);
        }
    }
}

这是我在 Silverlight.web 上的系统域服务类。

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

这是 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;
    }
}

Silverlight 使用 RIA Services Silverlight Client 与 WCF 通信

问题二的答案 你可能必须转到顶部的工具、NuGet 包管理器、包管理控制台,然后键入以下命令来安装这三个函数的包。PM> install-Package RIAServices.Silverlight.DomainDataSource