C# 如何让 Silverlight 从 MySQL 获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/100104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 11:42:55  来源:igfitidea点击:

How to have silverlight get its data from MySQL

提问by Isak Savo

I've written a small hello world test app in Silverlight which i want to host on a Linux/Apache2 server. I want the data to come from MySQL (or some other linux compatible db) so that I can databind to things in the db.

我在 Silverlight 中编写了一个小型的 hello world 测试应用程序,我想将其托管在 Linux/Apache2 服务器上。我希望数据来自 MySQL(或其他一些与 linux 兼容的数据库),以便我可以将数据绑定到数据库中的内容。

I've managed to get it working by using the MySQL Connector/.NET:

我设法通过使用MySQL Connector/.NET让它工作:

MySqlConnection conn = new MySqlConnection("Server=the.server.com;Database=theDb;User=myUser;Password=myPassword;");
conn.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM test;", conn);
using (MySqlDataReader reader = command.ExecuteReader())
{
     StringBuilder sb = new StringBuilder();
     while (reader.Read())
     {
         sb.AppendLine(reader.GetString("myColumn"));
     }
     this.txtResults.Text = sb.ToString();
}

This works fine if I give the published ClickOnce app full trust (or at least SocketPermission) and run it locally.

如果我完全信任已发布的 ClickOnce 应用程序(或至少是 SocketPermission)并在本地运行它,这会很好地工作

I want this to run on the server and I can't get it to work, always ending up with permission exception (SocketPermission is not allowed).

我希望它在服务器上运行,但我无法让它工作,总是以权限异常结束(不允许 SocketPermission)。

The database is hosted on the same server as the silverlight app if that makes any difference.

如果这有什么不同,该数据库与 Silverlight 应用程序托管在同一台服务器上。

EDITOk, I now understand why it's a bad idea to have db credentials in the client app (obviously). How do people do this then? How do you secure the proxy web service so that it relays data to and from the client/db in a secure way? Are there any examples out there on the web?

编辑好的,我现在明白为什么在客户端应用程序中拥有数据库凭据是个坏主意(显然)。那么人们如何做到这一点呢?您如何保护代理 Web 服务,以便它以安全的方式将数据中继到客户端/数据库或从客户端/数据库中继数据?网上有没有例子?

Surely, I cannot be the first person who'd like to use a database to power a silverlight application?

当然,我不会是第一个想要使用数据库来支持 Silverlight 应用程序的人吗?

采纳答案by Rob

The easiest way to do what you want (having read through your edits now :)) will be to expose services that can be consumed. The pattern that Microsoft is REALLY pushing right now is to expose WCF services, but the truth is that your Silverlight client can use WCF to consume a lot of different types of services.

做您想做的事情的最简单方法(现在已经阅读了您的编辑:))将公开可以使用的服务。Microsoft 现在真正推动的模式是公开 WCF 服务,但事实是您的 Silverlight 客户端可以使用 WCF 来使用许多不同类型的服务。

What may be easiest for you to do right now would be to use a .NET service on a web server or maybe a PHP REST service, and then point your Silverlight app at that service. By doing so, you're protecting your database not only from people snooping through it, but more importantly, you're restricting what people can do to your database. If your data is supposed to be read-only, and your service's contract only allows reading operations, you're set. Alternatively, your service may negotiate sessions with credentials, again, set up through WCF.

您现在最容易做的可能是在 Web 服务器上使用 .NET 服务或 PHP REST 服务,然后将您的 Silverlight 应用程序指向该服务。通过这样做,您不仅可以保护您的数据库免遭他人窥探,更重要的是,您可以限制人们对您的数据库的操作。如果您的数据应该是只读的,并且您的服务合同只允许读取操作,那么您就设置好了。或者,您的服务可能会与凭据协商会话,再次通过 WCF 设置。

WCF can be a client-only, server-only, or client-server connector platform. What you choose will affect the code you write, but it's all going to be independent of your database. Your code can be structured such that it's a one-to-one mapping to your database table, or it can be far more abstract (you can set up classes that represent full logical views if you choose).

WCF 可以是仅客户端、仅服务器或客户端-服务器连接器平台。您选择的内容会影响您编写的代码,但这一切都将独立于您的数据库。您的代码可以结构化为一对一映射到您的数据库表,或者它可以更加抽象(如果您愿意,您可以设置表示完整逻辑视图的类)。

回答by cruizer

Silverlight does not have any capability to directly access database servers. What you can do is to expose your database operations through web services (ASMX or WCF, even non-.NET!) and use Silverlight to access those services.

Silverlight 没有任何直接访问数据库服务器的能力。您可以做的是通过 Web 服务(ASMX 或 WCF,甚至非 .NET!)公开您的数据库操作,并使用 Silverlight 访问这些服务。

回答by Kristian J.

Having DB connections directly to the server from the client side is usually a bad idea. I don't know how easy it is to decompile a Silverlight app, but I would guess it's possible in some way. Then you're basically giving away your DB credentials to your users.

从客户端直接连接到服务器通常是一个坏主意。我不知道反编译 Silverlight 应用程序有多么容易,但我猜想这在某种程度上是可能的。然后您基本上将您的数据库凭据提供给您的用户。

回答by MatthiasS

While the "official" answer is to use WCF to push a service to Silverlight, I kind of figure that anyone using MySQL would probably not be using a complete ASP.NET solution. My solution was to build a PHP webservice (like Rob suggested) to interact with the MySQL database and have the Silverlight access it in a RESTful manner.

虽然“官方”的答案是使用 WCF 将服务推送到 Silverlight,但我认为使用 MySQL 的任何人都可能不会使用完整的 ASP.NET 解决方案。我的解决方案是构建一个 PHP 网络服务(如 Rob 建议的那样)来与 MySQL 数据库交互并让 Silverlight 以 RESTful 方式访问它。

Here is beginning of a three part tutorial for using Silverlight to access a MySQL database through a PHP web service:

下面是使用 Silverlight 通过 PHP Web 服务访问 MySQL 数据库的三部分教程的开始:

PHP, MySQL and Silverlight: The Complete Tutorial

PHP、MySQL 和 Silverlight:完整教程

回答by angularsen

I just got this working; ASP.NET4 site with Silverlight4 content on Linux Ubuntu 10 / Apache2 server. Content is developed using Visual Studio 2010. VS2008 should work fine too.

我刚刚开始工作;在 Linux Ubuntu 10 / Apache2 服务器上具有 Silverlight4 内容的 ASP.NET4 站点。内容是使用 Visual Studio 2010 开发的。VS2008 也应该可以正常工作。

Server:

服务器:

  • Setup a Linux server with Apache2 and MySQL, there are tons of guides on this.
    • Make sure MySQL is accessible from the development PC and optionally from the Internet. See here for details: Causes of Access-Denied Errors.
    • Setup the database table structures and add some content for testing later. In our example we assume you have the table 'persons' with the column 'name'.
  • Since Silverlight is a client-side technology you are pretty much good-to-go and can host the application with a simple HTML page.
  • A web service is required between Silverlight and MySQL. Microsoft's WCF RIA is one flavor, but requires .NET. On the plus-side, you get to host ASP.NET4 pages as well. Here is a thorough guide to setting it up: Setting up Mono 2.8 with Asp.Net 4.0 and MVC2 on Ubuntu with MySql Membership
  • 使用 Apache2 和 MySQL 设置 Linux 服务器,有很多关于此的指南。
    • 确保 MySQL 可以从开发 PC 访问,也可以从 Internet 访问。有关详细信息,请参见此处:拒绝访问错误的原因
    • 设置数据库表结构并添加一些内容以供稍后测试。在我们的示例中,我们假设您有包含“name”列的“persons”表。
  • 由于 Silverlight 是一种客户端技术,因此您非常容易上手,并且可以使用简单的 HTML 页面托管应用程序。
  • Silverlight 和 MySQL 之间需要一个 Web 服务。Microsoft 的 WCF RIA 是一种风格,但需要 .NET。从好的方面来说,您还可以托管 ASP.NET4 页面。这是设置它的详尽指南:Setup up Mono 2.8 with Asp.Net 4.0 and MVC2 on Ubuntu with MySql Membership

Visual Studio:

视觉工作室:

  • Install latest MySQL Connector/Netand restart VS
  • Add your MySQL database as data source
    • Open Server Explorer -> Add data connection -> Select 'MySQL Database'
    • Fill in credentials and test connection
  • 安装最新的MySQL Connector/Net并重新启动 VS
  • 将您的 MySQL 数据库添加为数据源
    • 打开服务器资源管理器 -> 添加数据连接 -> 选择“MySQL 数据库”
    • 填写凭据并测试连接

Setting up the site with MySQL access:

使用 MySQL 访问设置站点:

Here is a guide I found helpful: Step By Step Guide to WCF RIA enabled SL4 application with Entity Framework

这是我发现有用的指南:使用实体框架的 WCF RIA 启用 SL4 应用程序的分步指南

  • Create or open a Silverlight project.
    • The server-side project is typically named 'ProjectName.Web'
    • The client-side project is typically named 'ProjectName'
  • Add 'ADO.NET Entity Data Model' to the server project. This will be a model of your database structure.
    • Select 'Generate from database'
    • Choose the MySQL database connection you created
    • Select the tables you want to access
  • Build your solution now before proceeding.
  • Add 'Domain Service Class' to the server project, f.ex. 'FooDomain'. This will make the database entities available to the client-side Silverlight code.
    • In 'Available DataContext/ObjectContext classes:' select the Entity Framework model you created in the previous step.
    • Check the entities you want to access and check 'Enable editing' where appropriate
    • Check 'Generate associated classes for metadata'
  • Build your solution again to generate 'FooDomainContext', based on 'FooDomain' in server project.
  • 创建或打开 Silverlight 项目。
    • 服务器端项目通常命名为“ProjectName.Web”
    • 客户端项目通常命名为“ProjectName”
  • 将“ADO.NET 实体数据模型”添加到服务器项目。这将是您的数据库结构的模型。
    • 选择“从数据库生成”
    • 选择您创建的 MySQL 数据库连接
    • 选择要访问的表
  • 在继续之前立即构建您的解决方案。
  • 将“域服务类”添加到服务器项目,例如。'FooDomain'。这将使数据库实体可用于客户端 Silverlight 代码。
    • 在“Available DataContext/ObjectContext classes:”中选择您在上一步中创建的实体框架模型。
    • 选中您要访问的实体,并在适当的地方选中“启用编辑”
    • 选中“为元数据生成关联类”
  • 再次构建您的解决方案以基于服务器项目中的“FooDomain”生成“FooDomainContext”。

Testing:

测试:

Let's get data from MySQL into Silverlight. Assuming there is a table named 'persons' with column name 'name', we can bind a list box to show the names of the persons.

让我们从 MySQL 获取数据到 Silverlight。假设有一个名为“persons”的表,列名为“name”,我们可以绑定一个列表框来显示人员的姓名。

First add a Silverlight page, let's say 'Home'. In Home.xaml add:

首先添加一个 Silverlight 页面,让我们说“主页”。在 Home.xaml 中添加:

<ListBox x:Name="TestList" Width="100" />

In Home.xaml.cs file add:

在 Home.xaml.cs 文件中添加:

public partial class Home : Page
{
    public Home()
    {
        InitializeComponent();

        Loaded += Home_Loaded;
    }

    void Home_Loaded(object sender, RoutedEventArgs e)
    {
        var context = new FooDomainContext();
        var query = context.Load(context.GetPersonsQuery());
        TestList.ItemsSource = query.Entities;
        TestList.DisplayMemberPath = "name";
    }
}

Here we assume you named your domain service 'FooDomain', and this would generate the 'FooDomainContext' class used.

在这里,我们假设您将域服务命名为“FooDomain”,这将生成使用的“FooDomainContext”类。

Hopefully, if all is set up properly, you will now see a list of person names when running your Silverlight project.

希望如果一切设置正确,您现在将在运行 Silverlight 项目时看到人员姓名列表。

Edit:ASP.NET is not optional, but required for the WCF RIA web service used in my example.

编辑:ASP.NET 不是可选的,而是我的示例中使用的 WCF RIA Web 服务所必需的。

回答by mjb

You can get data from MySQL by using Web Services.

您可以使用 Web 服务从 MySQL 获取数据。

Walkthrough:

演练:

Step 1: Create Web Services

步骤 1:创建 Web 服务

Step 2: Add Service Reference to Silverlight

步骤 2:将服务引用添加到 Silverlight



Step 1: Create Web Services步骤 1:创建 Web 服务

Add a new Silverlight project.

添加一个新的 Silverlight 项目。

Add a new Silverlight project

添加新的 Silverlight 项目

Create a new Web Service. Right click on the web project > Add > New Item

创建一个新的 Web 服务。右键单击 web 项目 > 添加 > 新建项目

Create a new Web Service

创建一个新的 Web 服务

Select "Web Service".

选择“网络服务”。

enter image description here

在此处输入图片说明

Initial code of a new Web Service.

新 Web 服务的初始代码。

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;

namespace SilverlightApplication1.Web
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

In order for the Web Service able to connect to MySQL, we need to add a reference of MySql.Data.DLL into the web project and add the Using statement at top of the Web Service class:

为了Web Service能够连接到MySQL,我们需要在Web工程中添加一个MySql.Data.DLL的引用,并在Web Service类的顶部添加Using语句:

using MySql.Data.MySqlClient; 

HelloWorld()is an initial sample method created by Visual Studio. You may want to delete it as it is not needed. I'm going to create 2 simple method to demonstrate how Web Services are used to communicate between SilverLight and MySQL.

HelloWorld()是 Visual Studio 创建的初始示例方法。您可能想要删除它,因为它不需要。我将创建 2 个简单的方法来演示如何使用 Web 服务在 SilverLight 和 MySQL 之间进行通信。

First method: ExecuteScalar()

第一种方法:ExecuteScalar()

This method is simple. Get a single object from MySQL.

这个方法很简单。从 MySQL 获取单个对象。

public string ExecuteScalar(string sql)
{
    try
    {
        string result = "";
        using (MySqlConnection conn = new MySqlConnection(constr))
        {
            using (MySqlCommand cmd = new MySqlCommand())
            {
                conn.Open();
                cmd.Connection = conn;
                cmd.CommandText = sql;
                result = cmd.ExecuteScalar() + "";
                conn.Close();
            }
        }
        return result;
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
} 

Second method: ExecuteNonQuery()

第二种方法:ExecuteNonQuery()

For single SQL execution. Example of SQL type: INSERT, UPDATE, DELETE.

用于单个 SQL 执行。SQL 类型示例:INSERT、UPDATE、DELETE。

public string ExecuteNonQuery(string sql)
{
    try
    {
        long i = 0;
        using (MySqlConnection conn = new MySqlConnection(constr))
        {
            using (MySqlCommand cmd = new MySqlCommand())
            {
                conn.Open();
                cmd.Connection = conn;
                cmd.CommandText = sql;
                i = cmd.ExecuteNonQuery();
                conn.Close();
            }
        }
        return i + " row(s) affected by the last command, no resultset returned.";
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}  

This is how the Web Service looks like after adding the two methods above:

添加上述两个方法后,Web Service 的样子是这样的:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using MySql.Data.MySqlClient;

namespace SilverlightApplication1.Web
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class WebService1 : System.Web.Services.WebService
    {
        string constr = "server=localhost;user=root;pwd=1234;database=test;";

        [WebMethod]
        public string ExecuteScalar(string sql)
        {
            try
            {
                string result = "";
                using (MySqlConnection conn = new MySqlConnection(constr))
                {
                    using (MySqlCommand cmd = new MySqlCommand())
                    {
                        conn.Open();
                        cmd.Connection = conn;
                        cmd.CommandText = sql;
                        result = cmd.ExecuteScalar() + "";
                        conn.Close();
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        [WebMethod]
        public string ExecuteNonQuery(string sql)
        {
            try
            {
                long i = 0;
                using (MySqlConnection conn = new MySqlConnection(constr))
                {
                    using (MySqlCommand cmd = new MySqlCommand())
                    {
                        conn.Open();
                        cmd.Connection = conn;
                        cmd.CommandText = sql;
                        i = cmd.ExecuteNonQuery();
                        conn.Close();
                    }
                }
                return i + " row(s) affected by the last command, no resultset returned.";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }  
    }
} 

You will notice that an attribute of [WebMethod]is added to the methods.

您会注意到[WebMethod]的属性被添加到方法中。

Rebuild the project and let the Web Service be ready for next step.

重建项目并让 Web 服务为下一步做好准备。

Rebuild the project

重建项目

Web Service Access Permission

网络服务访问权限

Please note that, by default, Web Service only allow those Silverlight that is hosted at the same domain with the Web Service to access. If the Silverlight application is hosted on another website/domain, Web Service will deny the communication. Therefore we have to configure the permission for the Web Service to be accessed by Silverlight which is hosted at different domain.

请注意,默认情况下,Web Service 仅允许与 Web Service 位于同一域中的那些 Silverlight 访问。如果 Silverlight 应用程序托管在另一个网站/域上,Web 服务将拒绝通信。因此,我们必须配置托管在不同域的 Silverlight 访问 Web 服务的权限。

You have to create two additional files: clientaccesspolicy.xmland crossdomain.xml.

您必须创建两个附加文件:clientaccesspolicy.xmlcrossdomain.xml

These files has to be put at the root of the domain where the Web Services are hosted.

这些文件必须放在托管 Web 服务的域的根目录中。

Example: http://www.mywebsite.com/clientaccesspolicy.xmland http://www.mywebsite.com/crossdomain.xml

例子:http://www.mywebsite.com/clientaccesspolicy.xmlhttp://www.mywebsite.com/crossdomain.xml

clientaccesspolicy.xml

客户端访问策略.xml

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="SOAPAction">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

If you only want to allow the Web Service to be accessed by specific domain (example: www.myanotherwebsite.com), you can add it within . Example:

如果您只想允许特定域(例如:www.myanotherwebsite.com)访问 Web 服务,您可以将其添加到 . 例子:

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="SOAPAction">
        <domain uri="http://www.myanotherwebsite.com"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

crossdomain.xml

跨域.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE cross-domain-policy SYSTEM 
"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-http-request-headers-from domain="*" headers="SOAPAction,Content-Type"/>
</cross-domain-policy>

To understand more about this, please read: Making a Service Available Across Domain Boundaries (MSDN)

要了解更多相关信息,请阅读:使服务跨域边界可用 (MSDN)



Step 2: Add Service Reference to Silverlight

步骤 2:将服务引用添加到 Silverlight

Add a Service Reference to Silverlight.

添加对 Silverlight 的服务引用。

Add a Service Reference to Silverlight

添加对 Silverlight 的服务引用

Type the address of the Web Service and press [Go].

输入 Web 服务的地址,然后按 [Go]。

Example of address: http://www.mywebsite.com/MyCoolWebService.asmx

地址示例:http: //www.mywebsite.com/MyCoolWebService.asmx

Change the Namespace to your favor, and press [OK].

将命名空间更改为您喜欢的,然后按 [OK]。

Web Service Browser

网络服务浏览器

Visual Studio will analyze the Web Service, do the data binding and create a class.

Visual Studio 将分析 Web 服务,进行数据绑定并创建一个类。

Before continue coding, let's us see what methods that we can use in the new created class. Right click the new class and select [View in Object Browser].

在继续编码之前,让我们看看我们可以在新创建的类中使用哪些方法。右键单击新类并选择[在对象浏览器中查看]。

View in Object Browser

在对象浏览器中查看

The class that we are going to use is WebService1SoapClient (in this example). The naming is based on the Service name. If we name our service class as MyCoolWebService, then MyCoolWebServiceSoapClient will be chosen as the name of the class in Silverlight. At the right panel, two methods and two events are highlighted. Those are the methods used to call the Web Services.

我们将要使用的类是 WebService1SoapClient(在本例中)。命名基于服务名称。如果我们将服务类命名为 MyCoolWebService,则在 Silverlight 中将选择 MyCoolWebServiceSoapClient 作为类的名称。在右侧面板中,突出显示了两个方法和两个事件。这些是用于调用 Web 服务的方法。

Object of WebService1SoapClient

WebService1SoapClient 的对象

Lets create a simple Silverlight application by adding a Textbox and two Buttons.

让我们通过添加一个文本框和两个按钮来创建一个简单的 Silverlight 应用程序。

In this example, user will key in SQL query directly into the Textbox.

在本例中,用户将直接在文本框中键入 SQL 查询。

Button of [ExecuteScalar] will send the SQL to the Web Service and retrieve data back. (SELECT, SHOW, etc.)

[ExecuteScalar] 按钮会将 SQL 发送到 Web 服务并取回数据。(选择、显示等)

Button of [ExecuteNonQuery] will send the SQL to the Web Service for execution only. (INSERT, UPDATE, DELETE, etc.)

[ExecuteNonQuery] 按钮会将 SQL 发送到 Web Service 仅执行。(插入、更新、删除等)

Design a simple SilverLight App

设计一个简单的 SilverLight 应用程序

This is the initial code behind of MainPage.xaml:

这是 MainPage.xaml 背后的初始代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void btExecuteScalar_Click(object sender, RoutedEventArgs e)
        {
        }

        private void btExecuteNonQuery_Click(object sender, RoutedEventArgs e)
        {
        }
    }
}

Now, these are what we are going to do here:

现在,这些是我们要做的:

  • Declare the service as static object at class level: ServiceReference1.WebService1SoapClient
  • Create the service completed event of the two methods.
  • Call the service in the event of button click.
  • Display the service result: MessageBox.Show()
  • 在类级别将服务声明为静态对象:ServiceReference1.WebService1SoapClient
  • 创建两个方法的服务完成事件。
  • 单击按钮时调用该服务。
  • 显示服务结果:MessageBox.Show()



public partial class MainPage : UserControl
{
    ServiceReference1.WebService1SoapClient myService;

    public MainPage()
    {
        InitializeComponent();
        myService = new ServiceReference1.WebService1SoapClient();
        myService.ExecuteScalarCompleted += myService_ExecuteScalarCompleted;
        myService.ExecuteNonQueryCompleted += myService_ExecuteNonQueryCompleted;
    }

    void myService_ExecuteNonQueryCompleted(object sender, 
                   ServiceReference1.ExecuteNonQueryCompletedEventArgs e)
    {
        MessageBox.Show(e.Result);
    }

    void myService_ExecuteScalarCompleted(object sender, 
         ServiceReference1.ExecuteScalarCompletedEventArgs e)
    {
        MessageBox.Show(e.Result);
    }

    private void btExecuteScalar_Click(object sender, RoutedEventArgs e)
    {
        myService.ExecuteScalarAsync(textBox1.Text);
    }

    private void btExecuteNonQuery_Click(object sender, RoutedEventArgs e)
    {
        myService.ExecuteNonQueryAsync(textBox1.Text);
    }
}

Press [F5], run and test the Silverlight application.

按 [F5],运行并测试 Silverlight 应用程序。

Testing

测试

Testing

测试

Testing

测试

Together with your creativity, I believe you can do something more than this for now Smile | :)

加上你的创造力,我相信你现在可以做更多的事情 Smile | :)

If you have done any changes to the Web Service, maybe you added new Service (new web methods), you have to update the Service Reference at Silverlight to re-bind the Services. You might want to update the Web Service address, if you uploaded the files to a different web hosting.

如果您对 Web 服务进行了任何更改,也许您添加了新的服务(新的 Web 方法),您必须更新 Silverlight 中的服务参考以重新绑定服务。如果您将文件上传到不同的 Web 主机,您可能需要更新 Web 服务地址。

update the Service Reference

更新服务参考

Happy coding.

快乐编码。

Read More:

阅读更多:

  1. Original Post - Connecting MySQL From SilverLight With Web Services - CodeProject.com (written by me)
  2. Access a Web Service from a Silverlight Application
  3. HOW TO: Write a Simple Web Service by Using Visual C# .NET
  4. How to: Build a Service for Silverlight Clients
  1. 原帖 - 从 SilverLight 连接 MySQL 与 Web 服务 - CodeProject.com(由我编写)
  2. 从 Silverlight 应用程序访问 Web 服务
  3. 如何:使用 Visual C# .NET 编写简单的 Web 服务
  4. 如何:为 Silverlight 客户端构建服务