Spiga

Silverlight 2 (beta1)数据操作(4)——调用WCF进行数据CRUD操作

2008-04-17 16:37 by 李永京, 6412 visits, 收藏, 编辑

Silverlight 2 (beta1)数据操作(4)——调用WCF进行数据CRUD操作

目录

  • 导言
  • 软件需求
  • 在SQL 2005中创建数据库
  • 在Visual Studio 2008创建Silverlight工程和WCF Service
  • 编写WCF Service
  • 在Silverlight 2 (beta1)工程中引用WCF
  • 在Silverlight中调用WCF进行CRUD操作
  • 结语

导言

Silverlight 2支持JSON、Web Service、WCF以及Sockets等新特性对数据CRUD操作,这个系列用实例结合数据库一步一步的图文描述来学习一下Silverlight 2 beta 1中进行数据库的CRUD操作方面的实战能力。

这篇文章介绍如何在Silverlight 2 beta 1中调用WCF进行数据CRUD操作。

软件需求

  • Silverlight 2 (beta1)
  • Visual Studio 2008
  • SQL 2005 Express with Management Studio

在SQL 2005中创建数据库

创建一个名为User的表,如下图所示。我在第一篇文章中详细介绍了,这一篇我们还需要这张表。

User表

在Visual Studio 2008创建Silverlight工程和WCF Service

第一步:在VS2008中创建一个新的Silverlight工程,命名为:YJingLee.WCF。并选择ASP.NET Web Site用来托管Silverlight应用程序。

创建Silverlight工程

第二步:在Web项目中添加一个WCF Service文件,我命名为UserService.svc

添加WCF Service文件

编写WCF Service

第一步:定义服务契约。我们为WCF Service提供的增删查改方法定义服务契约。

[ServiceContract]
public interface IUserService
{
    [OperationContract]
    string RetrieveUser();
    [OperationContract]
    bool CreateUser(string userName);
    [OperationContract]
    bool UpdateUser(int userID, string userName);
    [OperationContract]
    bool DeleteUser(int userID);
}

第二步:在UserService中实现服务:为增删查改四个方法具体实现。这里使用SQL语句了,同第一篇类似。

public class UserService : IUserService
{
    //查询用户
    public string RetrieveUser()
    {
        try
        {
            SqlConnection _sqlConnection = 
               new SqlConnection( ConfigurationManager.
                ConnectionStrings["sqlConnectionString"].
                ConnectionString);
            _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(ConfigurationManager.
                ConnectionStrings["sqlConnectionString"]
                .ConnectionString);
            _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(ConfigurationManager.
                ConnectionStrings["sqlConnectionString"]
                .ConnectionString);
            _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(ConfigurationManager.
                ConnectionStrings["sqlConnectionString"]
                .ConnectionString);
            _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;
        }
    }
}

第三步:修改Web.config中的服务配置。

这里使用basicHttpBinding绑定,并且开启httpGetEnabled,以便后面我们可以在浏览器中查看服务。

<system.serviceModel>
    <behaviors>
        <serviceBehaviors>
            <behavior name="UserServiceBehavior">
                <serviceMetadata httpGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <services>
        <service behaviorConfiguration="UserServiceBehavior"
                 name="UserService">
            <endpoint address="" binding="basicHttpBinding" 
                      contract="IUserService">
            </endpoint>
        </service>
    </services>
</system.serviceModel>

第四步:设置Web应用程序的端口号。

把器端口号设置为固定端口52600,在浏览器中查看服务是否正常:

在浏览器中查看服务

好了,现在服务端我们就实现完成了。

在Silverlight 2 (beta1)工程中引用WCF Service

第一步:在Silverlight工程的引用节点上右击选择“Add Service Reference...”。

选择Add Service Reference...

第二步:在下面的对话框中点击“Discover”按钮

点击“Discover”按钮

第三步:在点击Discover按钮之后,地址栏里显示了UserService.svc。在Service面板出现一个WCF Service,双击这个服务。修改Namespace为UserService,单击OK。

修改服务属性

第四步:添加完成后,在Silverlight工程的ServiceReferences.ClientConfig文件中,我们查看一下,他自动生成了WCF客户端的配置。

<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IUserService"
                    maxBufferSize="65536"
                    maxReceivedMessageSize="65536">
                    <security mode="None" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint 
                address="http://localhost:52600/YJingLee.WCF_Web/
                                            UserService.svc"
                binding="basicHttpBinding" 
                bindingConfiguration="BasicHttpBinding_IUserService"
                contract="YJingLee.WCF.UserService.IUserService" 
                name="BasicHttpBinding_IUserService" />
        </client>
    </system.serviceModel>
</configuration>

现在,我们可以在Silverlight工程中调用WCF Service了。

在Silverlight中调用WCF进行CRUD操作

由于在WCF服务的配置中我们采取了BasicHttpBinding,客户端也要采用BasicHttpBinding。所以我们先定义一个全局变量:

UserService.UserServiceClient userSvcClient;

然后在Page()方法中,我们调用这个服务,免得每次在各个方法中调用。

userSvcClient = new YJingLee.WCF.UserService.UserServiceClient();

这里,我直接这样写了,没有添加任何参数,原因很简单,在ServiceReferences.ClientConfig文件中,VS自动生成了WCF客户端的配置。当然你也可以这样写,两者选其一:

BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress endPoint = new EndpointAddress(
    "http://localhost:52600/YJingLee.WCF_Web/UserService.svc");
userClient = 
  new YJingLee.WCF.UserService.UserServiceClient(binding, endPoint);

1.创建数据

编写调用服务并创建数据,这里采用异步模式,我们需要注册CreateUserCompleted事件处理方法,以便完成后回调,同时调用CreateUserAsync()方法创建用户。

void createButton_Click(object sender, RoutedEventArgs e)
{
    //模拟一个用户
    string userName = "YJingLee";
    //注册CreateUserCompleted事件
    userSvcClient.CreateUserCompleted +=
        new EventHandler<YJingLee.WCF.UserService.
        CreateUserCompletedEventArgs>
        (userSvcClient_CreateUserCompleted);
    //调用CreateUserAsync()方法创建用户
    userSvcClient.CreateUserAsync(userName);
}
void userSvcClient_CreateUserCompleted(object sender, 
    YJingLee.WCF.UserService.CreateUserCompletedEventArgs e)
{
    //完成CreateUserAsync()方法后回调,这里象征性的提示是否完成
    if (e.Error == null)
    {
        errMessage.Text = "创建用户成功!";
        errMessage.Visibility = Visibility.Visible;
    }
    else
    {
        errMessage.Text = e.Error.ToString();
        errMessage.Visibility = Visibility.Visible;
    }
}

2.读取数据

同创建数据类似,调用服务并读取数据。

void retrieveButton_Click(object sender, RoutedEventArgs e)
{
    //注册RetrieveUserCompleted事件
    userSvcClient.RetrieveUserCompleted += 
        new EventHandler<YJingLee.WCF.UserService.
        RetrieveUserCompletedEventArgs>
        (userSvcClient_RetrieveUserCompleted);
    //调用RetrieveUserAsync()方法查询用户
    userSvcClient.RetrieveUserAsync();
}
void userSvcClient_RetrieveUserCompleted(object sender, 
    YJingLee.WCF.UserService.RetrieveUserCompletedEventArgs e)
{
    //调用成功,显示数据
    if (e.Error == null)
        displayData(e.Result);
}

显示数据方法:

private void displayData(string xmlContent)
{
    try
    {
        if (xmlContent != string.Empty)
        {
            XDocument xmlUsers = XDocument.Parse(xmlContent);
            var users = from user in xmlUsers.Descendants("User")
                        select new
                        {
                          UserID = Convert.ToInt32(
                              user.Element("UserID").Value),
                          UserName = 
                          (string)user.Element("UserName").Value
                        };
            List<User> usersList = new List<User>();
            foreach (var u in users)
            {
                User use = new User 
                   { UserID = u.UserID, UserName = u.UserName };
                usersList.Add(use);
            }
            UserList.ItemsSource = usersList;
        }
        else
        {
            UserList.ItemsSource = null;
        }
    }
    catch (Exception ex)
    {

        Console.Write(ex.Message);
    }
}

3.更新数据

这里,我们模拟更新UserID为7的用户,修改这个用户的UserName为YJingLee。

void updateButton_Click(object sender, RoutedEventArgs e)
{
    //模拟更新userID为7的用户
    int userID = 7;
    string userName = "YJingLee";
    userSvcClient.UpdateUserCompleted +=
       new EventHandler<YJingLee.WCF.UserService.
       UpdateUserCompletedEventArgs>
       (userSvcClient_UpdateUserCompleted);
    userSvcClient.UpdateUserAsync(userID, userName);
}
void userSvcClient_UpdateUserCompleted(object sender,
    YJingLee.WCF.UserService.UpdateUserCompletedEventArgs e)
{
    if (e.Error == null)
    {
        errMessage.Text = "更新用户成功!";
        errMessage.Visibility = Visibility.Visible;
    }
    else
    {
        errMessage.Text = e.Error.ToString();
        errMessage.Visibility = Visibility.Visible;
    }
}

4.删除数据

我在这里指定UserID为7的用户。

void deleteButton_Click(object sender, RoutedEventArgs e)
{
    //模拟删除userID为7的用户
    int userID = 7;
    userSvcClient.DeleteUserCompleted +=
       new EventHandler<YJingLee.WCF.UserService.
       DeleteUserCompletedEventArgs>
       (userSvcClient_DeleteUserCompleted);
    userSvcClient.DeleteUserAsync(userID);
}
void userSvcClient_DeleteUserCompleted(object sender,
    YJingLee.WCF.UserService.DeleteUserCompletedEventArgs e)
{
    if (e.Error == null)
    {
        errMessage.Text = "删除用户成功!";
        errMessage.Visibility = Visibility.Visible;
    }
    else
    {
        errMessage.Text = e.Error.ToString();
        errMessage.Visibility = Visibility.Visible;
    }
}

结语

Silverlight应用程序的后端数据库操作有很多技术可以实现,像LINQ to SQL、Entity Framework、ADO.NET Data Services(Astoria )、ASP.NET Web Service(ASMX)。 这一篇使用基本的SQL语句,然后在服务层调用WCF技术实现,本来打算不写的,但是在InfoQ看到Silverlight 2中文学习资源集萃的推荐,我发现在数据库这块就手把这些知识掌握一下。

这篇就介绍到这里。从这篇我们知道了如何在Silverlight 2 beta 1中调用WCF进行数据CRUD操作。

Add your comment

41 条回复

  1. #1楼 jillzhang      2008-04-17 16:44
    诚邀您加入WCF技术研究团队
    WCF是"Windows Communication Foundation "的缩写,原来的代号为"Indigo",它是MS为SOA(Service Oriented Architecture)而设计的一套完整的技术框架。利用它能够轻松的开发出分布式(Distributed)应用程序。该技术是MS以往的分布式开发技术的集大成者,优点多多,同时也是.net 3.0中最重要的一个组成部分,目前很多人在学习这门技术,本团队就是想更方便的方便大家学习交流WCF技术。

    团队概况

    团队地址:http://wcfs.cnblogs.com/

    团队名称:WCF技术研究团队

    成立日期:2008年4月17日星期四

    加入机制:自由申请制

    团队宗旨: 学习,交流,创新,探索

     回复 引用 查看   
  2. #2楼[楼主] 李永京      2008-04-17 16:55
    @jillzhang
    好的,已经加入了!多多交流!
     回复 引用 查看   
  3. #3楼 李战      2008-04-18 08:32
    路过,学习。
     回复 引用 查看   
  4. #4楼[楼主] 李永京      2008-04-18 08:34
    @李战
    o(∩_∩)o...
     回复 引用 查看   
  5. #5楼 霍泰稳[未注册用户]2008-04-20 17:02
    感谢楼主对InfoQ中文站文章的推荐,也欢迎其他朋友访问InfoQ中文站浏览更多和.NET、Silverlight相关的新闻、文章和视频等:)

    http://www.infoq.com/cn
     回复 引用   
  6. #6楼[楼主] 李永京      2008-04-20 18:54
    @霍泰稳
    不客气。这个网站挺好的,很多好的文章。不过这篇“Silverlight 2.0中文学习资源集萃”这个题目我认为有点非议,微软发布的是Silverlight 2 beta1 并不是Silverlight 2.0,也不是Silverlight 2.0的Beta 1,现在好多人刚刚学习,很多人还不熟悉,不要误导初学者,这样让别人误解。
     回复 引用 查看   
  7. #7楼 fanpan[未注册用户]2008-04-30 11:29
    在编写WCF Service第四步时,查看服务是否正常,出现下面的错误提示:


    “/a.wcf_Web”应用程序中的服务器错误。
    无法找到资源。
    说明: HTTP 404。您正在查找的资源(或者它的一个依赖项)可能已被移除,或其名称已更改,或暂时不可用。


    请问这是什么原因造成的!
     回复 引用   
  8. #8楼[楼主] 李永京      2008-04-30 11:59
    @fanpan
    不知道你的具体情况,命名规则方面有什么出入???
     回复 引用 查看   
  9. #9楼 欧阳继[未注册用户]2008-05-16 10:31
    @楼主
    我照楼主的方法去做,总是发生以下错误:
    "“System.ServiceModel.ProtocolException”类型的异常在 System.ServiceModel.dll 中发生,但未在用户代码中进行处理

    其他信息: [UnexpectedHttpResponseCode]
    Arguments:Not Found
    Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=2.0.30226.2&File=System.ServiceModel.dll&Key=UnexpectedHttpResponseCode"

    就是在 这个方法上执行时 bool _result = ((bool)(base.EndInvoke("CreateUser", _args, result)));
    请问是什么问题造成的?
     回复 引用   
  10. #10楼[楼主] 李永京      2008-05-16 12:52
    @欧阳继
    我这里没有你这个原因的,建议看看端口设置,web.config设置,代码都可以直接调用的,这里找了这方面的解决方法:
    http://timheuer.com/blog/archive/2008/04/09/silverlight-cannot-access-web-service.aspx
    http://blogs.msdn.com/carlosfigueira/archive/2008/03/07/enabling-cross-domain-calls-for-silverlight-apps-on-self-hosted-web-services.aspx
     回复 引用 查看   
  11. #11楼 欧阳继[未注册用户]2008-05-16 13:06
    谢谢楼主了,在你给出的链接中找到解决办法了,哈哈
     回复 引用   
  12. #12楼 yiyisawa      2008-05-20 12:48
    弄不明白,请教楼主:
    为什么我的web.config中自动生成以下两个behavior 和service,我把其中的SilverlightApplication14_Web.UserServiceBehavior和SilverlightApplication14_Web.UserService删除后,UserService(http://localhost:52660/UserService.svc)就不能正常显示,且我明明只有一个service,为什么在配置里出现两个service呢:
    <system.serviceModel>
    <behaviors>
    <serviceBehaviors>
    <behavior name="UserServiceBehavior">
    <serviceMetadata httpGetEnabled="true" />
    <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
    <behavior name="SilverlightApplication14_Web.UserServiceBehavior">
    <serviceMetadata httpGetEnabled="true" />
    <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
    </serviceBehaviors>
    </behaviors>
    <services>
    <service behaviorConfiguration="UserServiceBehavior" name="UserService">
    <endpoint address="" binding="basicHttpBinding" contract="IUserService" />
    </service>
    <service behaviorConfiguration="SilverlightApplication14_Web.UserServiceBehavior"
    name="SilverlightApplication14_Web.UserService">
    <endpoint address="" binding="basicHttpBinding" contract="SilverlightApplication14_Web.IUserService">
    <identity>
    <dns value="localhost" />
    </identity>
    </endpoint>

    </service>
    </services>

    </system.serviceModel>

    如果不删除其中的话,运行整个程序最后会出现:
    An exception of type 'System.Windows.Markup.XamlParseException' occurred in System.Windows.dll but was not handled in user code

    Additional information: System.ArgumentNullException: Value cannot be null.
    Parameter name: binding
    at System.ServiceModel.ClientBase`1..ctor(Binding binding, EndpointAddress remoteAddress)
    at SilverlightApplication14.UserService.UserServiceClient..ctor(Binding binding, EndpointAddress remoteAddress)
    at SilverlightApplication14.UserService.UserServiceClient..ctor()
    at SilverlightApplication14.EntryControl..ctor() [Line: 6488169 Position: 4391013]



    我的客户端:
    <configuration>
    <system.serviceModel>
    <bindings>
    <basicHttpBinding>
    <binding name="BasicHttpBinding_IUserService"
    maxBufferSize="65536"
    maxReceivedMessageSize="65536">
    <security mode="None" />
    </binding>
    </basicHttpBinding>
    </bindings>
    <client>
    <endpoint
    address="http://localhost:52600/UserService.svc"
    binding="basicHttpBinding"
    bindingConfiguration="BasicHttpBinding_IUserService"
    contract="UserService.IUserService"
    name="BasicHttpBinding_IUserService" />
    </client>
    </system.serviceModel>
    </configuration>
     回复 引用 查看   
  13. #13楼[楼主] 李永京      2008-05-20 13:00
    @yiyisawa
    你好像是多次添加wcf文件造成每次添加的时候web.config文件自动添加一些配置的,其实web.config文件中只要一配置就行了。最简单的方法就是把web.config文件和wcf文件删除。然后按下面的步骤:新建web.config文件,在新建wcf服务,这时web.config文件就是一个了~~
     回复 引用 查看   
  14. #14楼 fanpan[未注册用户]2008-05-22 08:54
    请问楼主,在显示数据方法那步,
    List<User> usersList = new List<User>();
    里面的User表示什么呢?错误提示:找不到类型或命名空间名称“User”!
     回复 引用   
  15. #15楼 whywhy[未注册用户]2008-05-24 12:21
    为什么运行到:XDocument xmlUsers = XDocument.Parse(xmlContent);
    就会发生异常呢?

    “System.Xml.XmlException”类型的异常在 System.Xml.dll 中发生,但未在用户代码中进行处理

    其他信息: [Xml_TagMismatch]
    Arguments:RoomId,1,User
    Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=2.0.30226.2&File=System.Xml.dll&Key=Xml_TagMismatch [Xml_ErrorPosition]
    Arguments:1,193
    Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=2.0.30226.2&File=System.Xml.dll&Key=Xml_ErrorPosition
     回复 引用   
  16. #16楼[楼主] 李永京      2008-05-24 12:41
    @fanpan
    C#3.0基础东西,建议先学习基础的,这些新技术在基础知识之上
     回复 引用 查看   
  17. #17楼[楼主] 李永京      2008-05-24 12:43
    @whywhy
    还是基础!!还有程序集加了没,引用了没??取到数据没?建议先学习基础东西...
     回复 引用 查看   
  18. #18楼 whywhy[未注册用户]2008-05-25 17:35
    @李永京
    程序集加了,引用了,取到数据了,可是就是异常,很无奈!
     回复 引用   
  19. #19楼[楼主] 李永京      2008-05-25 18:21
    @whywhy
    这里找了这方面的解决方法:
    http://timheuer.com/blog/archive/2008/04/09/silverlight-cannot-access-web-service.aspx
    http://blogs.msdn.com/carlosfigueira/archive/2008/03/07/enabling-cross-domain-calls-for-silverlight-apps-on-self-hosted-web-services.aspx
     回复 引用 查看   
  20. #20楼 yiyisawa.liu[未注册用户]2008-05-26 09:15
    楼主:您好.我在12楼提出的问题已在您的帮助下解决了,非常感谢.
    另楼上fanpan,whywhy 两位提出的问题,您把解决方案发到我的邮箱里来了,(是否应发往他们各自的邮箱?),最后还是感谢楼主及时.热情地回复问题!!!:)
     回复 引用   
  21. #21楼[楼主] 李永京      2008-05-26 09:28
    @yiyisawa.liu
    你是否勾选了有回复时邮件通知我,去掉吧,不然下面有人提问还是发你邮箱,我没有发你邮箱的,就在这里回复他们的问题的。
     回复 引用 查看   
  22. #22楼 yiyisawa.Liu[未注册用户]2008-05-27 09:05
    呵呵,不好意思,我已经去掉了"有回复通知我",:)
     回复 引用   
  23. #23楼 whywhy[未注册用户]2008-05-27 15:51
    @李永京
    问题解决了,原来是字符串有点问题,谢谢楼主了!
     回复 引用   
  24. #24楼 Alex Wang      2008-06-01 17:36
    请教楼主两个问题:
    1、我用Silverlight 2做了一个附件上传的功能,但是只能上传几kb。我把wcf的maxBufferSize扩大了10000倍还是不好使,不知道是linq的问题,还是web.config的问题
    2、我做的例子linq的添加好使,修改却不好用,提示好像是说权限有问题,但不知道该如何解决,望指教,谢谢!!!!
     回复 引用 查看   
  25. #25楼[楼主] 李永京      2008-06-01 18:56
    @Alex Wang
    1.现在SL bate1还不支持读取配置文件,需要在后台写代码
    你设置MaxReceivedMessageSize属性:
    UserService.UserServiceClient userSvcClient;
    userSvcClient = new YJingLee.WCF.UserService.UserServiceClient();
    userSvcClient.MaxReceivedMessageSize = int.MaxValue;
    数据超过默认大小就会抛出下面一个异常:
    An exception of type 'System.ServiceModel.CommunicationException' occurred in System.ServiceModel.dll but was not handled in user code
    Additional information: [MaxReceivedMessageSizeExceeded]

    2.先测试wcf服务,看看其方法是否可以运行。一步一步进行。关于linq看看http://www.cnblogs.com/lyj/archive/2008/04/21/1164713.html
     回复 引用 查看   
  26. #26楼 问题总是很多[未注册用户]2008-07-01 23:04
    为何我在调试程序的时候,是不是会出现
    The remote server returned an unexpected response: (404) Not Found
    这样的异常呢?
    如果再调试一次,又没这提示了,奇怪哦。
     回复 引用   
  27. #27楼[楼主] 李永京      2008-07-01 23:13
    @问题总是很多
    应该是哪里需要更新一下,版本问题,你查下SDK。
     回复 引用 查看   
  28. #28楼 问题总是很多[未注册用户]2008-07-02 06:52
    @李永京
    楼主的回复总是很快啊!
     回复 引用   
  29. #29楼 问题总是很多[未注册用户]2008-07-02 21:43
    楼主,能问你些其他问题么。忙活了一天了,到处发帖子也没找到个答案,只能麻烦你一下了!。。。
    TextBlock怎么才能解析带html标记的字符串呢?现在赋值给他都是原样显示出来了。需要做啥设置呢?
    还有就是动态添加的控件怎么布局呢?grid里面添加进去都是默认的第一行或者第一列,怎么才可以添加到选定列呢?Canvas也是这样的问题,添加了几个控件在canvas里面,怎么可以让他们布局呢..
     回复 引用   
  30. #30楼 问题总是很多[未注册用户]2008-07-02 22:02
    html标记在这找到答案了,不好意思占用你的空间了!
    http://blogs.msdn.com/delay/archive/2007/09/10/bringing-a-bit-of-html-to-silverlight-htmltextblock-makes-rich-text-display-easy.aspx
     回复 引用   
  31. #31楼[楼主] 李永京      2008-07-11 20:55
    @问题总是很多
    不好意思,一直没有时间上网,没得及时回复。
     回复 引用 查看   
  32. #32楼 杨鑫奇      2009-04-14 20:37
    楼主,这个Page()方法具体在哪个地方?
    为什么WCF服务中定义了 返回为String 而本地服务里面加了Asy( 后就变成void的了?
     回复 引用 查看   
  33. #33楼 shuniu[未注册用户]2009-07-07 16:31
    艾,不得不说的是 ,数据删除后,如何更新datagird列表呢?
    如果有空的话,希望能在写写~
    lilop@126.com
     回复 引用   
  34. #34楼 virus      2010-01-28 11:26
    有一个小问题,我按照你说的添加了两个类库,一个是普通的类库,放服务端的实体类,一个sl的类库,放sl的实体类,两个的命名空间一样

    sl引用sl类库,wcf应用普通类库

    sl的代码是

    protected void GetCustomerById(int customerId)
    {
    try
    {

    client.GetCustomerCompleted += new EventHandler<GetCustomerCompletedEventArgs>(client_GetCustomerCompleted);
    client.GetCustomerAsync(customerId );
    }
    catch (Exception ex)
    {
    MessageBox.Show(ex.Message + ex.InnerException.Message);
    }
    }

    wcf返回用户信息是

    public Customer GetCustomer( int customerId)
    {

    Customer objCustomer = new Customer();

    objCustomer = _customerDao.GetCustomerById(customerId);

    return objCustomer;
    }

    设置断点之后,在wcf中看到的return objCustomer;还是有值且正确的,可是return objCustomer;运行之后就报错


    错误System.Reflection.TargetInvocationException

    ,之后应该是返回到客户端的client.GetCustomerCompleted 事件,可是还没有运行到就报错了,我想是在服务端的实体类和客户端的实体类不一样导致反射失败,不知道你是怎么解决的呢??
     回复 引用 查看   
  35. #35楼 virus      2010-01-28 11:26
    客户端实体类

    using System;
    using System.Net;
    using System.ComponentModel;
    namespace Domain.Entity
    {

    public class Customer : INotifyPropertyChanged
    {
    private int _intCustomerId;
    private string _strCustomerName;
    private string _strCustomerCode;
    private CustomerType _CustomerType;
    private int _intCustomerTypeId;

    public virtual int CustomerTypeId
    {
    get { return _intCustomerTypeId; }
    set { _intCustomerTypeId = value; }
    }
    public virtual CustomerType CustomerType
    {
    get { return this._CustomerType; }
    set
    {

    this._CustomerType = value;
    OnPropertyChanged("CustomerType");
    }
    }

    public virtual int CustomerId
    {
    get { return this._intCustomerId; }
    set
    {
    this._intCustomerId = value;
    OnPropertyChanged("CustomerId");
    }
    }

    public virtual string CustomerName
    {
    get { return this._strCustomerName; }
    set
    {
    this._strCustomerName = value; OnPropertyChanged("CustomerName");
    }
    }

    public virtual string CustomerCode
    {
    get { return _strCustomerCode; }
    set
    {
    this._strCustomerCode = value;
    OnPropertyChanged("CustomerCode");
    }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
    private void OnPropertyChanged(string propertyName)
    {
    if (PropertyChanged != null)
    {
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    }
    }
    }
     回复 引用 查看   
  36. #36楼 virus      2010-01-28 11:27
    服务端实体类
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using System.ComponentModel;
    using System.Runtime.Serialization;

    namespace Domain.Entity
    {
    [DataContract]
    public class Customer : INotifyPropertyChanged
    {
    private int _intCustomerId;
    private string _strCustomerName;
    private string _strCustomerCode;
    private CustomerType _CustomerType;
    private int _intCustomerTypeId;

    [DataMember ]
    public virtual int CustomerTypeId
    {
    get { return _intCustomerTypeId; }
    set { _intCustomerTypeId = value; }
    }

    [DataMember ]
    public virtual CustomerType CustomerType
    {
    get { return this._CustomerType; }
    set
    {

    this._CustomerType = value;
    OnPropertyChanged("CustomerType");
    }
    }

    [DataMember]
    public virtual int CustomerId
    {
    get { return this._intCustomerId; }
    set
    {
    this._intCustomerId = value;
    OnPropertyChanged("CustomerId");
    }
    }
    [DataMember]
    public virtual string CustomerName
    {
    get { return this._strCustomerName; }
    set
    {
    this._strCustomerName = value; OnPropertyChanged("CustomerName");
    }
    }
    [DataMember]
    public virtual string CustomerCode
    {
    get { return _strCustomerCode; }
    set
    {
    this._strCustomerCode = value;
    OnPropertyChanged("CustomerCode");
    }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
    private void OnPropertyChanged(string propertyName)
    {
    if (PropertyChanged != null)
    {
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    }
    }
    }
     回复 引用 查看   
  37. #37楼 virus      2010-01-28 11:27
    我现在有点明白了,是不是你那个例子的实体类只有一份,在server是对client的一个引用,所以两个是一个东西,可是我的是两个文件,尽管命名空间一样,其实是两个类,所以反射的时候就出错了。是不是呢
     回复 引用 查看   
  38. #38楼 virus      2010-01-28 11:27
    可是我的需要和wcf交互,需要 [DataContract],而且是配合NHibernate,需要using Iesi.Collections.Generic;
    可是这两个在sl的类库中都不能应用
     回复 引用 查看   
  39. #39楼 virus      2010-01-28 11:27
    silverlight system.servicemodel.communicationexception
     回复 引用 查看   
  40. #40楼 virus      2010-01-28 11:31
    是不是和我的实体类的定义有关系呢?

    后来我去掉了
    using System.Linq;
    using System.Text;
    using System.ServiceModel;

    这三个,以为看到有ServiceModel的提示信息,但是错误依旧
     回复 引用 查看   
发表评论

昵称: [登录] [注册]

主页:

邮箱:(仅博主可见)

评论内容:

  登录  注册

[使用Ctrl+Enter键快速提交评论]

0 1158346 djIr6wVJgo0=