Silverlight调用WCF(1)

代码下载

程序结构

移动手机开发企业应用,常常会访问远程数据库(云端数据库),往往通过WCF对外提供接口访问。程序结构一般是:Silverlight+WCF+Sql Server数据库

下面就是以操作用户User为例,移动终端通过调用WCF实现对数据库的基本操作(增删改查)。
1.数据库
1)创建数据库表
CREATE TABLE [dbo].[User](
[UserID] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nchar](100) NOT NULL,
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[UserID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
2.WCF
1)定义接口
[ServiceContract]
public interface IService1
{
[OperationContract]
string RetrieveUser();
[OperationContract]
bool CreateUser(string userName);
[OperationContract]
bool UpdateUser(int userID, string userName);
[OperationContract]
bool DeleteUser(int userID);
}
2)实现接口
public class Service1 : IService1
{
//查询用户
public string RetrieveUser()
{
try
{
SqlConnection _sqlConnection =
new SqlConnection("Database=test1;Server=lochost;Integrated Security=false;password=1;user id=sa;");
_sqlConnection.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("SELECT * FROM [User]",
_sqlConnection);
DataSet ds = new DataSet();
da.Fill(ds);
StringBuilder sb = new StringBuilder();
sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
sb.Append("<Users>");
foreach (DataRow dr in ds.Tables[0].Rows)
{
sb.Append("<User>");
sb.Append("<UserID>");
sb.Append(dr[0].ToString());
sb.Append("</UserID>");
sb.Append("<UserName>");
sb.Append(dr[1].ToString());
sb.Append("</UserName>");
sb.Append("</User>");
}
sb.Append("</Users>");
_sqlConnection.Close();
return sb.ToString();
}
catch (Exception ex)
{
return string.Empty;
}
}
//创建用户
public bool CreateUser(string userName)
{
try
{
SqlConnection _sqlConnection =
new SqlConnection("Database=test1;Server=lochost;Integrated Security=false;password=1;user id=sa;");
_sqlConnection.Open();
SqlCommand command = new SqlCommand();
command.Connection = _sqlConnection;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO [User] ([UserName]) VALUES ('" +
userName.ToString().Replace("'", "''") + "')";
command.ExecuteNonQuery();
_sqlConnection.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
//更新用户
public bool UpdateUser(int userID, string userName)
{
try
{
SqlConnection _sqlConnection =
new SqlConnection("Database=test1;Server=lochost;Integrated Security=false;password=1;user id=sa;");
_sqlConnection.Open();
SqlCommand command = new SqlCommand();
command.Connection = _sqlConnection;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE [User] " +
"SET [UserName] = '" +
userName.ToString().Replace("'", "''") + "'" +
"WHERE [UserID] = " + userID.ToString();
command.ExecuteNonQuery();
_sqlConnection.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
//删除用户
public bool DeleteUser(int userID)
{
try
{
SqlConnection _sqlConnection =
new SqlConnection("Database=test1;Server=lochost;Integrated Security=false;password=1;user id=sa;");
_sqlConnection.Open();
SqlCommand command = new SqlCommand();
command.Connection = _sqlConnection;
command.CommandType = CommandType.Text;
command.CommandText = "DELETE [User] WHERE [UserID] = "
+ userID.ToString();
command.ExecuteNonQuery();
_sqlConnection.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
3)允许跨域访问
建立clientaccesspolicy.xml文件,放于WCF项目根目录
<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
3.Silverlight
1)添加Web引用
2)异步调用WCF中对象方法

private ServiceReference1.Service1Client userSvcClient;
private void button1_Click(object sender, RoutedEventArgs e)
{
userSvcClient = new ServiceReference1.Service1Client();
//模拟一个用户
string userName = "zhaoyu";
//注册CreateUserCompleted事件
userSvcClient.CreateUserCompleted += new EventHandler<ServiceReference1.CreateUserCompletedEventArgs>(userSvcClient_CreateUserCompleted);
//调用CreateUserAsync()方法创建用户
userSvcClient.CreateUserAsync(userName);
}

void userSvcClient_CreateUserCompleted(object sender, ServiceReference1.CreateUserCompletedEventArgs e)
{
//完成CreateUserAsync()方法后回调.
if (e.Error == null)
{
errMessage.Content = "创建用户成功!";

}
else
{
errMessage.Content = e.Error.ToString();

}
}

代码下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值