10. 在添加服务器端数据库访问代码前,需要修改Web.Config文件。和Asp.Net项目一样,在链接数据库前,我们首先需要在Web.Config中配置数据库连接字符串,请自行替换数据库登录ID和密码
2 <add key="DbServiceConnectionString" value="Data Source=(Local);Initial Catalog=SilverlightDemo;User Id=dev;Password=dev;"/>
3 </appSettings>
11. 前文已经说过,Silverlight仅支持使用BasicHttpBinding通过WCF service进行通讯,而VS2008自动生成的代码是customBinding,所以,我们也需要在Web.Config中进行修改.下面是VS2008自动生成的Web.Config部分代码,划线部分是下面要修改的部分。
2 <behaviors>
3 <serviceBehaviors>
4 <behavior name="SilverlightDBDemo.Web.DBServiceBehavior">
5 <serviceMetadata httpGetEnabled="true" />
6 <serviceDebug includeExceptionDetailInFaults="False" />
7 </behavior>
8 </serviceBehaviors>
9 </behaviors>
18 <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
19 <services>
20 <service behaviorConfiguration="SilverlightDBDemo.Web.DBServiceBehavior"
21 name="SilverlightDBDemo.Web.DBService">
24 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
25 </service>
26 </services>
27 </system.serviceModel>
这里我们需要修改以下几个地方:
首先删除customBinding,从上面代码,第10行,到17行,使用下面代码替换:
2 <basicHttpBinding>
3 <binding name="BasicHttpBinding_IDataService"
4 maxBufferPoolSize="2147483647"
5 maxReceivedMessageSize="2147483647"
6 maxBufferSize="2147483647">
7 <readerQuotas
8 maxArrayLength="2147483647"
9 maxBytesPerRead="2147483647"
10 maxDepth="2147483647"
11 maxNameTableCharCount="2147483647"
12 maxStringContentLength="2147483647" />
13 </binding>
14 </basicHttpBinding>
15 </bindings>
其中那些2147483647之类的属性可以删除,但是如果读取数据库中的大型表格,就需要设置缓冲池之类的尺寸了。这里,我们已经使用了basicHttpBinding. Binding name我使用了BasicHttpBinding_DBService,大家可以随意更换,下面将用到。
然后修改22行和23行的代码,将endpoint中的binding,内容修改为basicHttpBinding,bindingConfiguration的内容修改为BasicHttpBinding_DBService。
2 contract="SilverlightDBDemo.Web.DBService" />
12. 现在我们可以在DBService.svc.cs中添加存取数据库代码,对用户名和密码进行简单匹配,这里不再着重讲述如何条件匹配登录信息。这里演示了如何调用数据库存储过程。完成存取数据库代码后,成功编译Web项目。代码有点长,这里折叠起来。
代码
2
3 [OperationContract]
4 public bool GetUser(string cUserName, string cPassword)
5 {
6 SqlConnection conn = new SqlConnection(connectionString);
7 SqlCommand cmd = new SqlCommand("Login", conn);
8 cmd.CommandType = CommandType.StoredProcedure;
9 cmd.Parameters.AddWithValue("@UserName", cUserName);
10
11 try
12 {
13 conn.Open();
14 SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
15 if (reader.Read())
16 {
17 Users user = new Users((string)reader["cUserName"],
18 (string)reader["cPassword"]);
19 if (user.Password == cPassword)
20 {
21 return true;
22 }
23 else
24 {
25 return false;
26 }
27 }
28 else
29 {
30 return false;
31 }
32 }
33 finally
34 {
35 conn.Close();
36 }
37 }
13. 在SilverlightDBDemo客户端,点击右键添加服务引用

14. 在弹出窗口中,点击"Discover",查找本地WCF service。在地址栏会自动搜索到本地的Service引用,在Services树形框中我们可以看到,在服务器端建立的DBService.svc,双击打开,可以看到,我们建立的GetUser函数,以及默认的DoWork函数。修改下面的命名空间为"DBService",方便调用。

15. 点击"Advanced.."高级按钮,确认选中"Reuse types in referenced assembiles",如下图,

16. 然后,点击确定,会在客户端中生成DBService服务引用。
17. 在生成DBService服务引用后,VS2008会自动生成一个ServiceReferences.ClientConfig文件。
我们需要留意查看一下该文件内容。其中,bindings信息是basicHttpBinding,而endpoint内容和Web.Config中的内容相同。这里我们不需要修改任何代码。
2 <system.serviceModel>
3 <bindings>
4 <basicHttpBinding>
5 <binding name="BasicHttpBinding_DBService" maxBufferSize="2147483647"
6 maxReceivedMessageSize="2147483647">
7 <security mode="None">
8 <transport>
9 <extendedProtectionPolicy policyEnforcement="Never" />
10 </transport>
11 </security>
12 </binding>
13 </basicHttpBinding>
14 </bindings>
15 <client>
16 <endpoint address="http://localhost/SilverlightDBDemo.Web/DBService.svc"
17 binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_DBService"
18 contract="DBService.DBService" name="BasicHttpBinding_DBService" />
19 </client>
20 </system.serviceModel>
21 </configuration>
22
18. 下面我们将在客户端调用该服务引用,获取数据库的返回值,根据返回值,我们将简单判断登录是否成功。
进入MainPage.xaml.cs中,建立GetUser方法。该代码中EndpointAddress是最重要的,出现没有发现远程服务器错误,和这里设置也有关系。在client_GetUserCompleted中,e.Result代表了数据库返回值。可以接受任何值,大家可以根据需要进行值类型转换。每次,用户点击登陆按钮,Silverlight客户端都会向服务器端请求验证,返回结果会在提示信息栏显示。
2 {
3 EndpointAddress address = new EndpointAddress(new Uri(Application.Current.Host.Source, "/SilverlightDBDemo.Web/DBService.svc"));
4 DBServiceClient client = new DBServiceClient(new BasicHttpBinding(), address);
5 client.GetUserCompleted += client_GetUserCompleted;
6 client.GetUserAsync(txtUsername.Text, pbPassword.Password);
7 }
8
9 private void client_GetUserCompleted(object sender, GetUserCompletedEventArgs e)
10 {
11 try
12 {
13 if (e.Result)
14 {
15 tbMessage.Text = "登录成功!";
16 }
17 else
18 {
19 tbMessage.Text = "登录失败!";
20 }
21 }
22 catch (Exception error)
23 {
24 tbMessage.Text = error.ToString();
25 }
26 }
27
28 private void btLogin_Click(object sender, RoutedEventArgs e)
29 {
30 GetUser();
31 }
登录成功如下图:

到这里为止,我想你已经学会了如何使用WCF存取MSSQL数据库了。如果有问题,可以留言给我,或者到Silverlight开发QQ群100844510来讨论。
![]() |
代码下载 |


