首页 技术 正文
技术 2022年11月22日
0 收藏 896 点赞 4,357 浏览 5842 个字

[置顶] Silverlight调用WCF(1)

分类: 技术2012-03-31 12:29 940人阅读 评论(0) 收藏 举报wcfsilverlightexceptionusersecuritystring

代码下载

程序结构

移动手机开发企业应用,常常会访问远程数据库(云端数据库),往往通过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();

}
        }

@原文引入:http://blog.csdn.net/zhaoyu_1979/article/details/7415151

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,556
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898