从Silverlight调用wcf服务方法

时间:2011-05-12 07:06:46

标签: c# silverlight wcf methods service

我需要在我的项目中调用一个wcf服务方法,如果我有一个名为getPrimaryList的方法,我该怎么称呼它?

[OperationContract]
        public List<PrimaryClass> getPrimaryList()
        {
            string priConn = System.Configuration.ConfigurationManager.ConnectionStrings["SchoolConnectionString"].ConnectionString;
            var priList = new List<PrimaryClass>();
            using (SqlConnection conn = new SqlConnection(priConn))
            {
                const string sql = @"SELECT PrimarySchool,TopHonour,Cca,TopStudent,TopAggregate,TopImage FROM [Primary]";
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    SqlDataReader dr = cmd.ExecuteReader(
                        CommandBehavior.CloseConnection);
                    if (dr != null)
                        while (dr.Read())
                        {
                            var pri = new PrimaryClass
                            {
                                PrimarySchool = dr.GetString(0),
                                TopHonour = dr.GetString(1),
                                Cca = dr.GetString(2),
                                TopStudent = dr.GetString(3),
                                TopAggregate = dr.GetString(4),
                                TopImage = dr.GetString(5)
                            };
                            priList.Add(pri);
                        }
                    return priList;

                }

            }
        }

2 个答案:

答案 0 :(得分:2)

打开需要调用该服务的项目。 将服务引用添加到WCF服务。 创建生成的代理/客户端类的实例并调用该方法。

(这个答案几乎和你的问题一样通用,如果你需要更多细节,你必须特别要求他们)

修改

示例(此处不需要使用调度程序):

private void Button_Click(object sender, RoutedEventArgs e)
{
    var proxy = new ServiceReference1.HelloWorldServiceClient();
    proxy.SayHelloCompleted += proxy_SayHelloCompleted;
    proxy.SayHelloAsync(_nameInput.Text);
}

void proxy_SayHelloCompleted(object sender, ServiceReference1.SayHelloCompletedEventArgs e)
{
    if (e.Error == null)
    {
        this.Dispatcher.BeginInvoke(
            () => _outputLabel.Text = e.Result
        );
    }
    else
    {
        this.Dispatcher.BeginInvoke(
            () => _outputLabel.Text = e.Error.Message
        );
    }
}

答案 1 :(得分:0)

假设你想在button_click上调用服务..

private void Button_Click(object sender, RoutedEventArgs e) 
{     
   var client = new ServiceReference1.MyWCFServiceClient(); 
   var result = client.getPrimaryList();
   //do something here with the result now....
}