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();
}
}
Silverlight调用WCF(1)的更多相关文章
- Silverlight调用一般性处理程序模拟Silverlight调用WCF效果(2)
[置顶] Silverlight调用一般性处理程序模拟Silverlight调用WCF效果(2) 分类: 技术2012-03-31 12:51 548人阅读 评论(0) 收藏 举报 silverlig ...
- 使用Task简化Silverlight调用Wcf
原文http://www.cnblogs.com/lemontea/archive/2012/12/09/2810549.html 从.Net4.0开始,.Net提供了一个Task类来封装一个异步操作 ...
- Silverlight客户端调用WCF服务难题解疑
一:解决办法 Silverlight客户端调用WCF服务在实际使用中经常会出现的问题就是无法直接应用类文件和配置文件.微软针对这一情况已经给出了解决办法.WCF开发框架可以帮助我们实现可靠性较高的跨平 ...
- WCF基础教程之开篇:创建、测试和调用WCF
一转眼,又半个月没有更新博客了.说实话,最近确实是有点忙.不过即使再忙忙,也要抽空来学习一些东西.最近用WCF比较多,就来跟大家分享一下关于WCF的知识吧!为了让大家都能看懂,照顾一些没有学过WCF的 ...
- silverlight与wcf双向通讯 例子
本文将建立一个silverlight与wcf双向通讯的简单实例,以下是详细步骤: 新建Silverlight应用程序,名称WCFtest.解决方案中添加WCF服务应用程序,名称WcfServiceTe ...
- 系列文章--Silverlight与WCF通信
Silverlight与WCF通信(一) :Silverlight通过httpBinding访问IIS宿主WCF 摘要: 首语本人在学习Silverlight 和 WCF的时候,各种问题层出不穷,在园 ...
- 【Win 10应用开发】手动调用WCF服务
调用服务最简单的方法就是,直接在VS里面添加服务引用,输入服务的地址即可,无论是普通Web服务,还是WCF服务均可.VS会根据获取到的元数据,自动生成客户端代码. 如果服务的调用量很大,应用广泛,可以 ...
- 【原创经验分享】JQuery(Ajax)调用WCF服务
最近在学习这个WCF,由于刚开始学 不久,发现网上的一些WCF教程都比较简单,感觉功能跟WebService没什么特别大的区别,但是看网上的介绍,就说WCF比WebService牛逼多少多少,反正我刚 ...
- c# 动态调用WCF方法笔记!
//动态调用wcf方法 string url = "http://localhost:54379/ServiceWCF.svc"; IDoubleService proxy = W ...
随机推荐
- linux下nginx、php和mysql安装配置
一.安装nginx 安装nginx yum install -y epel-release yum install nginx -y 查看nginx软件包包括了哪些文件 rpm -ql nginx 启 ...
- Python中接收用户的输入
一.如何去接收用户的输入?使用函数 input() 函数 input() 让程序暂停运行,等待用户输入一些文本,获取用户的输入后,Python将其存储到一个变量中,以方便后期使用. name = in ...
- matplotlib.pyplot.pcolormesh
matplotlib.pyplot.pcolormesh(*args, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, shading ...
- Python的DEBUG LOG
一直在嵌入式行业,熟悉嵌入式的朋友都很了解嵌入式设备上DEBUG的麻烦,特别是一些缺乏断电工具和没有UI界面的设备.久而久之,开发一个新东西,首先就是要先搞定DEBUG手段.最近写了几个测试的pyth ...
- 【02】HTML5与CSS3基础教程(第8版)(全)
[02]HTML5与CSS3基础教程(第8版)(全) 共392页. (魔芋:大体上扫了一遍.没有什么新东西,都是入门的一些基础知识.) 已看完. [美]elizabeth cast ...
- BNUOJ 6023 畅通工程续
畅通工程续 Time Limit: 1000ms Memory Limit: 32768KB This problem will be judged on HDU. Original ID: 1874 ...
- BNUOJ 26283 The Ghost Blows Light
The Ghost Blows Light Time Limit: 1000ms Memory Limit: 32768KB This problem will be judged on HDU. O ...
- JavaEE JDBC ResultSet内外移动
ResultSet内外移动 @author ixenos 内外移动指位置光标的移动 内移动就是一个ResultSet得到后的那个光标! 外移动就是多个ResultSet的迭代 内移动 一般的数据库都不 ...
- JSP内置对象和EL内置对象
JSP共有九大内置对象: (1) HttpSession类的session对象作用:主要用于来分别保存每个用户信息,与请求关联的会话: 会话状态维持是Web应用开发者必须面对的问题. ...
- MongoDB小结12 - update【多文档更新】
当一次更新一个文档无法满足我们的脚步时,我们可以选择一次更新多个文档,及在update的第四个参数的位置添上true,及做多文档更新,建议就算不做多文档更新也显式的在第四个参数上置false,这样明确 ...