且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Silverlight应用程序创建和使用WCF Sevice

更新时间:2022-04-19 03:16:29

听起来像您需要WCF RIA服务.这简化了在Rich Internet Applications(例如Silverlight)中使用WCF服务的过程:

http://msdn.microsoft.com/en-us/library/ee707344 (v = vs.91).aspx [ http://www.silverlight.net/学习/高级技术/wcf-ria-services/get-started-with-wcf-ria-services [
Sounds like you need WCF RIA Services. This simplifies the process of using WCF services in Rich Internet Applications (like Silverlight):

http://msdn.microsoft.com/en-us/library/ee707344(v=vs.91).aspx[^]

or

http://www.silverlight.net/learn/advanced-techniques/wcf-ria-services/get-started-with-wcf-ria-services[^]

Lots of examples and walk-throughs in these links.


查看以下链接

带有WCF的Silverlight [ ^ ]

希望这对您有帮助...

-Sagar Solanki
Check out following link

Silverlight with WCF[^]

hope this may help you...

-Sagar Solanki




使用WCF服务的Silverlight 4中的DataGrid绑定和CRUD操作
在本文中,我们将使用Silverlight 4创建电话簿应用程序.我们将创建WCF服务以使用数据并绑定DataGrid.然后,我们将在其中实现CRUD操作.
首先,我们将创建一个Silverlight应用程序
打开VS2010->文件->新项目-> Silverlight应用程序

输入项目名称->单击确定
将出现新的Silverlight应用程序"窗口

单击确定
设计电话簿的页面,如下所示.

设计结束后,添加启用了Silverlight的WCF服务"
解决方案资源管理器->右键单击MSCoderSilverlightGridSampleWithWCF.Web->添加->新项目->选择启用了Silverlight的WCF服务

点击添加
然后右键单击MSCoderService.svc->选择代码
我们将编写以下3种方法
使用系统;
使用System.Collections.Generic;
使用System.Data.SqlClient;
使用System.ServiceModel;
使用System.ServiceModel.Activation;
使用System.Configuration;

命名空间MSCoderSilverlightGridSampleWithWCF.Web
{
[ServiceContract(Namespace =")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
公共类MSCoderService
{
字符串myConnectionString =数据源=.\\ SQLEXPRESS; AttachDbFilename = | DataDirectory | \\ Database.mdf;集成安全性= True;用户实例= True";

[OperationContract]
公共列表< person> GetAllPersons()
{
列出< person>人员=新列表<人员>();
使用(SqlConnection con = new SqlConnection(myConnectionString))
{
使用(SqlCommand cmd =新的SqlCommand())
{
cmd.CommandText ="GetAllPersons";
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Person person = new Person();
person.ID = int.Parse(阅读器["ID"].ToString());
person.Name = Convert.ToString(reader ["NAME"]);
person.City = Convert.ToString(reader ["CITY"]);
person.PhoneNo = Convert.ToString(reader ["PHONENO"]);

person.Add(人员);
}
}
}

归国人员;
}

[OperationContract]
public int SavePerson(人员)
{
使用(SqlConnection con = new SqlConnection(myConnectionString))
{
使用(SqlCommand cmd =新的SqlCommand())
{
cmd.CommandText ="SavePerson";
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;

cmd.Parameters.Add("@ ID",System.Data.SqlDbType.Int).Value = person.ID;
cmd.Parameters.Add("@ NAME",System.Data.SqlDbType.VarChar).Value = person.Name;
cmd.Parameters.Add("@ CITY",System.Data.SqlDbType.VarChar).Value = person.City;
cmd.Parameters.Add("@ PHONENO",System.Data.SqlDbType.VarChar).Value = person.PhoneNo;

con.Open();

返回Convert.ToInt32(cmd.ExecuteScalar());
}
}

}

[OperationContract]
公共布尔DeletePerson(int id)
{
使用(SqlConnection con = new SqlConnection(myConnectionString))
{
使用(SqlCommand cmd =新的SqlCommand())
{
cmd.CommandText ="DeletePerson";
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;

cmd.Parameters.Add("@ ID",System.Data.SqlDbType.Int).Value = id;

con.Open();

返回Convert.ToBoolean(cmd.ExecuteNonQuery()> 0);
}
}
}
}
}
现在,将服务参考添加到"MSCoderSilverlightGridSampleWithWCF"项目中
解决方案资源管理器->右键单击"MSCoderSilverlightGridSampleWithWCF"项目->选择添加服务参考…将出现添加服务参考对话框..
单击发现

输入名称空间作为"PersonService"->单击确定
现在打开MainPage.xaml.cs
在构造函数中,我们将向DataGrid添加所需的列

公共MainPage()
{
InitializeComponent();

grdPerson.Columns.Add(新的DataGridTextColumn
{
标头="ID",
绑定=新的Binding("ID")
});

grdPerson.Columns.Add(新的DataGridTextColumn
{
标头=名称",
绑定=新Binding("Name"),
宽度=新的DataGridLength(100)

});

grdPerson.Columns.Add(新的DataGridTextColumn
{
标头=城市",
绑定=新的Binding("City")
});

grdPerson.Columns.Add(新的DataGridTextColumn
{
标头=电话号码",
绑定=新Binding("PhoneNo")
});

LoadGrid();
}

然后我们将调用LoadGrid()方法
私有void LoadGrid()
{
MSCoderServiceClient客户端=新的MSCoderServiceClient();
client.GetAllPersonsCompleted + =新的EventHandler< getallpersonscompletedeventargs>(client_GetAllPersonsCompleted);
client.GetAllPersonsAsync();
}

在LoadGrid()方法中,我们将创建MSCoderServiceClient的实例以从Service获取数据.
然后,我们将为GetAllPersonCompleted附加一个事件处理程序.
void client_GetAllPersonsCompleted(对象发送者,GetAllPersonsCompletedEventArgs e)
{
grdPerson.ItemsSource = e.Result;
}

在此事件处理程序中,我们将在绑定网格之后调用函数
client.GetAllPersonsAsync()以异步获取数据.
就像这样,我们还将附加用于保存和删除记录的事件处理程序.
私有无效btnNew_Click(对象发送者,RoutedEventArgs e)
{
ClearFields();
}
私有void ClearFields()
{
lblID.Content ="-1";
txtName.Text = string.Empty;
txtCity.Text = string.Empty;
txtPhoneNo.Text = string.Empty;
txtName.Focus();
}

私有void btnSave_Click(对象发送者,RoutedEventArgs e)
{
如果(Validate())
{
MSCoderServiceClient客户端=新的MSCoderServiceClient();
client.SavePersonCompleted + =新的EventHandler< savepersoncompletedeventargs>(client_SavePersonCompleted);

Person person = new Person();
person.ID = int.Parse(lblID.Content.ToString());
person.Name = txtName.Text;
person.City = txtCity.Text;
person.PhoneNo = txtPhoneNo.Text;

client.SavePersonAsync(person);
}
}

void client_SavePersonCompleted(对象发送者,SavePersonCompletedEventArgs e)
{
如果(e.Result> -1)
{
MessageBox.Show(记录已成功更新",保存",MessageBoxButton.OK);
ClearFields();
LoadGrid();
}
}

私人布尔Validate()
{
如果(txtName.Text.Trim().Length == 0)
{
MessageBox.Show(名称不能为空",错误",MessageBoxButton.OK);
txtName.Focus();
返回false;
}
否则,如果(txtPhoneNo.Text.Trim().Length == 0)
{
MessageBox.Show(电话号码不能为空",错误",MessageBoxButton.OK);
txtPhoneNo.Focus();
返回false;
}
其他
{
返回true;
}
}

私有void btnDelete_Click(对象发送者,RoutedEventArgs e)
{
如果(lblID.Content.ToString()=="-1")
{
MessageBox.Show(选择要删除的记录",删除",MessageBoxButton.OK);
}
其他
{
如果(MessageBox.Show(确定要删除吗?",删除",MessageBoxButton.OKCancel)== MessageBoxResult.OK)
{

MSCoderServiceClient客户端=新的MSCoderServiceClient();
client.DeletePersonCompleted + =新的EventHandler< deletepersoncompletedeventargs>(client_DeletePersonCompleted);
client.DeletePersonAsync(int.Parse(lblID.Content.ToString()));
}
}
}

void client_DeletePersonCompleted(对象发送者,DeletePersonCompletedEventArgs e)
{
如果(e.Result)
{
MessageBox.Show(记录已删除",删除",MessageBoxButton.OK);
ClearFields();
LoadGrid();
}
其他
{
MessageBox.Show(删除失败",删除",MessageBoxButton.OK);
}
}
现在,我们将处理网格的Click事件假设如果单击网格的特定行,则记录应显示在控件中.
为此,我使用了Grid的LoadingRow事件,并为此附加了一个事件处理程序.
私有void grdPerson_LoadingRow(对象发送方,DataGridRowEventArgs e)
{
e.Row.MouseLeftButtonUp + =新的MouseButtonEventHandler(Row_MouseLeftButtonUp);
}

void Row_MouseLeftButtonUp(对象发送者,MouseButtonEventArgs e)
{
人员人员= grdPerson.SelectedItem作为人员;

lblID.Content = person.ID;
txtName.Text = person.Name;
txtCity.Text = person.City;
txtPhoneNo.Text = person.PhoneNo;
}


DataGrid Binding and CRUD Operations in Silverlight 4 using WCF Service
In this article we will create a Phone Book Application using Silverlight 4. We will create a WCF Service to consume data and to bind the DataGrid. We will then implement CRUD operations in it.
First we will create a Silverlight Application
Open VS2010 -> File -> New Project -> Silverlight Application

Enter Project Name -> Click OK
New Silverlight Application window will appear

Click Ok
Design the page for Phone Book as shown below.

Once design is over Add the "Silverlight-enabled WCF Service"
Solution Explorer -> Right Click on the MSCoderSilverlightGridSampleWithWCF.Web -> Add -> New Item -> Select Silverlight-enabled WCF Service

Click Add
Then right click on the MSCoderService.svc -> Select Code
We will write 3 methods as below
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Configuration;

namespace MSCoderSilverlightGridSampleWithWCF.Web
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MSCoderService
{
string myConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True";

[OperationContract]
public List<person> GetAllPersons()
{
List<person> persons = new List<person>();
using (SqlConnection con = new SqlConnection(myConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "GetAllPersons";
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Person person = new Person();
person.ID = int.Parse(reader["ID"].ToString());
person.Name = Convert.ToString(reader["NAME"]);
person.City = Convert.ToString(reader["CITY"]);
person.PhoneNo = Convert.ToString(reader["PHONENO"]);

persons.Add(person);
}
}
}

return persons;
}

[OperationContract]
public int SavePerson(Person person)
{
using (SqlConnection con = new SqlConnection(myConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SavePerson";
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;

cmd.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = person.ID;
cmd.Parameters.Add("@NAME", System.Data.SqlDbType.VarChar).Value = person.Name;
cmd.Parameters.Add("@CITY", System.Data.SqlDbType.VarChar).Value = person.City;
cmd.Parameters.Add("@PHONENO", System.Data.SqlDbType.VarChar).Value = person.PhoneNo;

con.Open();

return Convert.ToInt32(cmd.ExecuteScalar());
}
}

}

[OperationContract]
public bool DeletePerson(int id)
{
using (SqlConnection con = new SqlConnection(myConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "DeletePerson";
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;

cmd.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = id;

con.Open();

return Convert.ToBoolean(cmd.ExecuteNonQuery() > 0);
}
}
}
}
}
Now add Service Reference to "MSCoderSilverlightGridSampleWithWCF" Project
Solution Explorer -> Right Click "MSCoderSilverlightGridSampleWithWCF" Project -> Select Add Service Reference…Add Service Reference Dialog will be appearing..
Click Discover

Enter Namespace as "PersonService" -> Click OK
Now Open MainPage.xaml.cs
In Constructor We will add required columns to the DataGrid

public MainPage()
{
InitializeComponent();

grdPerson.Columns.Add(new DataGridTextColumn
{
Header = "ID",
Binding = new Binding("ID")
});

grdPerson.Columns.Add(new DataGridTextColumn
{
Header = "Name",
Binding = new Binding("Name"),
Width = new DataGridLength(100)

});

grdPerson.Columns.Add(new DataGridTextColumn
{
Header = "City",
Binding = new Binding("City")
});

grdPerson.Columns.Add(new DataGridTextColumn
{
Header = "Phone No",
Binding = new Binding("PhoneNo")
});

LoadGrid();
}

And then we will call LoadGrid() method
private void LoadGrid()
{
MSCoderServiceClient client = new MSCoderServiceClient();
client.GetAllPersonsCompleted += new EventHandler<getallpersonscompletedeventargs>(client_GetAllPersonsCompleted);
client.GetAllPersonsAsync();
}

In LoadGrid() method we will create a instance of MSCoderServiceClient to get the data from Service.
Then we will attach an event handler for GetAllPersonCompleted.
void client_GetAllPersonsCompleted(object sender, GetAllPersonsCompletedEventArgs e)
{
grdPerson.ItemsSource = e.Result;
}

In this event handler we will be binding the grid after that we will call function
client.GetAllPersonsAsync() to get the data asynchronously.
Just like this we will be attaching the event handlers for Saving and Deleting Records also.
private void btnNew_Click(object sender, RoutedEventArgs e)
{
ClearFields();
}
private void ClearFields()
{
lblID.Content = "-1";
txtName.Text = string.Empty;
txtCity.Text = string.Empty;
txtPhoneNo.Text = string.Empty;
txtName.Focus();
}

private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (Validate())
{
MSCoderServiceClient client = new MSCoderServiceClient();
client.SavePersonCompleted += new EventHandler<savepersoncompletedeventargs>(client_SavePersonCompleted);

Person person = new Person();
person.ID = int.Parse(lblID.Content.ToString());
person.Name = txtName.Text;
person.City = txtCity.Text;
person.PhoneNo = txtPhoneNo.Text;

client.SavePersonAsync(person);
}
}

void client_SavePersonCompleted(object sender, SavePersonCompletedEventArgs e)
{
if (e.Result > -1)
{
MessageBox.Show("Record Updated Successfully", "Save", MessageBoxButton.OK);
ClearFields();
LoadGrid();
}
}

private bool Validate()
{
if (txtName.Text.Trim().Length == 0)
{
MessageBox.Show("Name cannot be blank", "Error", MessageBoxButton.OK);
txtName.Focus();
return false;
}
else if (txtPhoneNo.Text.Trim().Length == 0)
{
MessageBox.Show("Phone No cannot be blank", "Error", MessageBoxButton.OK);
txtPhoneNo.Focus();
return false;
}
else
{
return true;
}
}

private void btnDelete_Click(object sender, RoutedEventArgs e)
{
if (lblID.Content.ToString() == "-1")
{
MessageBox.Show("Select a record to delete", "Delete", MessageBoxButton.OK);
}
else
{
if (MessageBox.Show("Are you sure you want to delete ? ", "Delete", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
{

MSCoderServiceClient client = new MSCoderServiceClient();
client.DeletePersonCompleted += new EventHandler<deletepersoncompletedeventargs>(client_DeletePersonCompleted);
client.DeletePersonAsync(int.Parse(lblID.Content.ToString()));
}
}
}

void client_DeletePersonCompleted(object sender, DeletePersonCompletedEventArgs e)
{
if (e.Result)
{
MessageBox.Show("Record Deleted", "Delete", MessageBoxButton.OK);
ClearFields();
LoadGrid();
}
else
{
MessageBox.Show("Deletion failed", "Delete", MessageBoxButton.OK);
}
}
Now We will handle the Click event of the Grid Suppose If we click on a particular row of the grid that record should get displayed in the controls
For this I am using LoadingRow event of the Grid and in this I am attaching an eventhandler.
private void grdPerson_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.MouseLeftButtonUp += new MouseButtonEventHandler(Row_MouseLeftButtonUp);
}

void Row_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Person person = grdPerson.SelectedItem as Person;

lblID.Content = person.ID;
txtName.Text = person.Name;
txtCity.Text = person.City;
txtPhoneNo.Text = person.PhoneNo;
}