redevil
redevil

Reputation: 82

Calling a wcf service method from Silverlight

I need to call a wcf service method in my project, if I have a method called getPrimaryList, how do I call it?

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

                }

            }
        }

Upvotes: 1

Views: 1547

Answers (2)

sajoshi
sajoshi

Reputation: 2763

Say you want to invoke the service on 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....
}

Upvotes: 0

Emond
Emond

Reputation: 50692

Open the project that needs to call the service. Add a Service Reference to the WCF Service. Make an instance of the generated proxy/client class and call the method.

(this answer is nearly as general as your question, if you need more details you have to ask for them specifically)

EDIT

Example (the use of the dispatcher is not really needed here):

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

Upvotes: 2

Related Questions