自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

詳解Silverlight與Access互操作的具體實現

開發(fā) 后端
這里將解釋Silverlight與Access互操作的具體實現,Silverlight與SQL Server或SQL Server Express的互操作,已成為我們常見的開發(fā)Siverlight應用程序的一種模式。
Silverlight與Access互操作是一個很基礎的問題,主要涉及到數據庫的操作。Access屬于輕量級的數據庫,應用起來還是比較方便的。51CTO編輯推薦《走向銀光 —— 一步一步學Silverlight

在開發(fā)一些小型應用程序時,我們就需要使用一些小巧的輕量級的數據庫,比如Access數據庫。由于Visual Studio中并沒有直接提供Silverlight與Access互操作的系列方法。于是本文就將為大家介紹如何讓Silverlight使用Access作為后臺數據庫。

準備工作

1)建立起測試項目

細節(jié)詳情請見強大的DataGrid組件[2]_數據交互之ADO.NET Entity Framework——Silverlight學習筆記[10]。

2)創(chuàng)建測試用數據庫

如下圖所示,創(chuàng)建一個名為Employees.mdb的Access數據庫,建立數據表名稱為Employee。將該數據庫置于作為服務端的項目文件夾下的App_Data文件夾中,便于操作管理。

創(chuàng)建測試用數據庫
 

建立數據模型

EmployeeModel.cs文件(放置在服務端項目文件夾下)

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. namespace datagridnaccessdb  
  5. {  
  6.     public class EmployeeModel  
  7.     {  
  8.         public int EmployeeID { get; set; }  
  9.         public string EmployeeName { get; set; }  
  10.         public int EmployeeAge { get; set; }  
  11.     }  

建立服務端Web Service★

右擊服務端項目文件夾,選擇Add->New Item....,按下圖所示建立一個名為EmployeesInfoWebService.asmx的Web Service,作為Silverlight與Access數據庫互操作的橋梁。

建立服務端Web Service

創(chuàng)建完畢后,雙擊EmployeesInfoWebService.asmx打開該文件。將里面的內容修改如下:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Services;  
  6. using System.Data.OleDb;//引入該命名空間為了操作Access數據庫  
  7. using System.Data;  
  8. namespace datagridnaccessdb  
  9. {  
  10.     /// <summary> 
  11.     /// Summary description for EmployeesInfoWebService  
  12.     /// </summary> 
  13.     [WebService(Namespace = "http://tempuri.org/")]  
  14.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  15.     [System.ComponentModel.ToolboxItem(false)]  
  16.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  17.     // [System.Web.Script.Services.ScriptService]  
  18.     public class EmployeesInfoWebService : System.Web.Services.WebService  
  19.     {  
  20.         [WebMethod]//獲取雇員信息  
  21.         public List<EmployeeModel> GetEmployeesInfo()  
  22.         {  
  23.             List<EmployeeModel> returnedValue = new List<EmployeeModel>();  
  24.             OleDbCommand Cmd = new OleDbCommand();  
  25.             SQLExcute("SELECT * FROM Employee", Cmd);  
  26.             OleDbDataAdapter EmployeeAdapter = new OleDbDataAdapter();  
  27.             EmployeeAdapter.SelectCommand = Cmd;  
  28.             DataSet EmployeeDataSet = new DataSet();  
  29.             EmployeeAdapter.Fill(EmployeeDataSet);  
  30.             foreach (DataRow dr in EmployeeDataSet.Tables[0].Rows)  
  31.             {  
  32.                 EmployeeModel tmp = new EmployeeModel();  
  33.                 tmp.EmployeeID = Convert.ToInt32(dr[0]);  
  34.                 tmp.EmployeeName = Convert.ToString(dr[1]);  
  35.                 tmp.EmployeeAge = Convert.ToInt32(dr[2]);  
  36.                 returnedValue.Add(tmp);  
  37.             }  
  38.             return returnedValue;  
  39.         }  
  40.        [WebMethod] //添加雇員信息  
  41.         public void Insert(List<EmployeeModel> employee)  
  42.         {  
  43.             employee.ForEach( x =>   
  44.            {  
  45.                 string CmdText = "INSERT INTO Employee(EmployeeName,EmployeeAge) VALUES('"+x.EmployeeName+"',"+x.EmployeeAge.ToString()+")";  
  46.                 SQLExcute(CmdText);  
  47.             });  
  48.         }  
  49.         [WebMethod] //更新雇員信息  
  50.        public void Update(List<EmployeeModel> employee)  
  51.         {  
  52.            employee.ForEach(x => 
  53.             {  
  54.                 string CmdText = "UPDATE Employee SET EmployeeName='"+x.EmployeeName+"',EmployeeAge="+x.EmployeeAge.ToString();  
  55.                 CmdText += " WHERE EmployeeID="+x.EmployeeID.ToString();  
  56.                 SQLExcute(CmdText);  
  57.             });  
  58.         }  
  59.         [WebMethod] //刪除雇員信息  
  60.        public void Delete(List<EmployeeModel> employee)  
  61.         {  
  62.             employee.ForEach(x => 
  63.             {  
  64.                 string CmdText = "DELETE FROM Employee WHERE EmployeeID="+x.EmployeeID.ToString();  
  65.                 SQLExcute(CmdText);  
  66.             });  
  67.         }  
  68.        //執(zhí)行SQL命令文本,重載1  
  69.         private void SQLExcute(string SQLCmd)  
  70.         {  
  71.             string ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath(@"App_Data\Employees.mdb;");  
  72.             OleDbConnection Conn = new OleDbConnection(ConnectionString);  
  73.             Conn.Open();  
  74.             OleDbCommand Cmd = new OleDbCommand();  
  75.             Cmd.Connection = Conn;  
  76.             Cmd.CommandTimeout = 15;  
  77.             Cmd.CommandType = CommandType.Text;  
  78.             Cmd.CommandText = SQLCmd;  
  79.             Cmd.ExecuteNonQuery();  
  80.             Conn.Close();  
  81.         }  
  82.         //執(zhí)行SQL命令文本,重載2  
  83.         private void SQLExcute(string SQLCmd,OleDbCommand Cmd)  
  84.         {  
  85.             string ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath(@"App_Data\Employees.mdb;");  
  86.             OleDbConnection Conn = new OleDbConnection(ConnectionString);  
  87.             Conn.Open();  
  88.             Cmd.Connection = Conn;  
  89.             Cmd.CommandTimeout = 15;  
  90.             Cmd.CommandType = CommandType.Text;  
  91.             Cmd.CommandText = SQLCmd;  
  92.             Cmd.ExecuteNonQuery();  
  93.         }  
  94.     }  

之后,在Silverlight客戶端應用程序文件夾下,右擊References文件夾,選擇菜單選項Add Service Reference...。如下圖所示,引入剛才我們創(chuàng)建的Web Service(別忘了按Discover按鈕進行查找)。

選擇菜單選項Add Service Reference

創(chuàng)建Silverlight客戶端應用程序
  1. MainPage.xaml文件  
  2. <UserControl 
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
  4.    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  5. xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     mc:Ignorable="d" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" xmlns:dataFormToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit" x:Class="SilverlightClient.MainPage" 
  6.  
  7.     d:DesignWidth="320" d:DesignHeight="240"> 
  8. <Grid x:Name="LayoutRoot" Width="320" Height="240" Background="White"> 
  9.  <dataFormToolkit:DataForm x:Name="dfEmployee" Margin="8,8,8,42"/> 
  10. <Button x:Name="btnGetData" Height="30" Margin="143,0,100,8" VerticalAlignment="Bottom" Content="Get Data" Width="77"/> 
  11. <Button x:Name="btnSaveAll" Height="30" Margin="0,0,8,8" VerticalAlignment="Bottom" Content="Save All" HorizontalAlignment="Right" Width="77"/> 
  12. <TextBlock x:Name="tbResult" Height="30" HorizontalAlignment="Left" Margin="8,0,0,8" VerticalAlignment="Bottom" Width="122" TextWrapping="Wrap" FontSize="16"/> 
  13. </Grid> 
  14. </UserControl> 
  15. MainPage.xaml.cs文件  
  16. using System;  
  17. using System.Collections.Generic;  
  18. using System.Collections.ObjectModel;  
  19. using System.Linq;  
  20. using System.Net;  
  21. using System.Windows;  
  22. using System.Windows.Controls;  
  23. using System.Windows.Documents;  
  24. using System.Windows.Input;  
  25. using System.Windows.Media;  
  26. using System.Windows.Media.Animation;  
  27. using System.Windows.Shapes;  
  28. using System.Xml;  
  29. using System.Xml.Linq;  
  30. using System.Windows.Browser;  
  31. using SilverlightClient.EmployeesInfoServiceReference;  
  32. namespace SilverlightClient  
  33. {  
  34.     public partial class MainPage : UserControl  
  35.     {  
  36.         int originalNum;//記錄初始時的Employee表中的數據總數  
  37.         ObservableCollection<EmployeeModel> deletedID = new ObservableCollection<EmployeeModel>();//標記被刪除的對象  
  38.        public MainPage()  
  39.         {  
  40.             InitializeComponent();  
  41.             this.Loaded += new RoutedEventHandler(MainPage_Loaded);  
  42.             this.btnGetData.Click += new RoutedEventHandler(btnGetData_Click);  
  43.             this.btnSaveAll.Click += new RoutedEventHandler(btnSaveAll_Click);   
  44.             this.dfEmployee.DeletingItem += new EventHandler<System.ComponentModel.CancelEventArgs>(dfEmployee_DeletingItem);  
  45.         }  
  46.         void dfEmployee_DeletingItem(object sender, System.ComponentModel.CancelEventArgs e)  
  47.         {  
  48.             deletedID.Add(dfEmployee.CurrentItem as EmployeeModel);//正在刪除時,將被刪除對象進行標記,以便傳給服務端真正刪除。  
  49.         }  
  50.         void btnSaveAll_Click(object sender, RoutedEventArgs e)  
  51.         {  
  52.             List<EmployeeModel> updateValues = dfEmployee.ItemsSource.Cast<EmployeeModel>().ToList();  
  53.             ObservableCollection<EmployeeModel> returnValues = new ObservableCollection<EmployeeModel>();  
  54.             if (updateValues.Count > originalNum)  
  55.             {  
  56.                 //添加數據  
  57.                 for (int i = originalNum; i <= updateValues.Count - 1; i++)  
  58.                 {  
  59.                     returnValues.Add(updateValues.ToArray()[i]);  
  60.                 }  
  61.                 EmployeesInfoWebServiceSoapClient webClient = new EmployeesInfoWebServiceSoapClient();  
  62.                 webClient.InsertCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(webClient_InsertCompleted);  
  63.                 webClient.InsertAsync(returnValues);  
  64.                 //必須考慮數據集中既有添加又有更新的情況  
  65.                 returnValues.Clear();  
  66.                 updateValues.ForEach(x => returnValues.Add(x));  
  67.                 webClient.UpdateCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(webClient_UpdateCompleted);  
  68.                 webClient.UpdateAsync(returnValues);  
  69.             }  
  70.             else if (updateValues.Count < originalNum)  
  71.             {  
  72.                 //刪除數據  
  73.                 EmployeesInfoWebServiceSoapClient webClient = new EmployeesInfoWebServiceSoapClient();  
  74.                 webClient.DeleteCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(webClient_DeleteCompleted);  
  75.                 webClient.DeleteAsync(deletedID);  
  76.             }  
  77.             else  
  78.             {  
  79.                //更新數據  
  80.                 updateValues.ForEach(x => returnValues.Add(x));  
  81.                 EmployeesInfoWebServiceSoapClient webClient = new EmployeesInfoWebServiceSoapClient();  
  82.                 webClient.UpdateCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(webClient_UpdateCompleted);  
  83.                 webClient.UpdateAsync(returnValues);  
  84.            }  
  85.         }  
  86.         void webClient_UpdateCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)  
  87.         {  
  88.             tbResult.Text = "更新成功!";  
  89.         }  
  90.         void webClient_DeleteCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)  
  91.         {  
  92.             tbResult.Text = "刪除成功!";  
  93.         }  
  94.         void webClient_InsertCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)  
  95.         {  
  96.             tbResult.Text = "添加成功!";  
  97.         }  
  98.         void btnGetData_Click(object sender, RoutedEventArgs e)  
  99.         {  
  100.             GetEmployees();  
  101.         }  
  102.         void MainPage_Loaded(object sender, RoutedEventArgs e)  
  103.         {  
  104.             GetEmployees();  
  105.         }  
  106.         void GetEmployees()  
  107.         {  
  108.             EmployeesInfoWebServiceSoapClient webClient = new EmployeesInfoWebServiceSoapClient();  
  109.             webClient.GetEmployeesInfoCompleted +=  
  110.             new EventHandler<GetEmployeesInfoCompletedEventArgs>(webClient_GetEmployeesInfoCompleted);  
  111.             webClient.GetEmployeesInfoAsync();  
  112.         }  
  113.         void webClient_GetEmployeesInfoCompleted(object sender, GetEmployeesInfoCompletedEventArgs e)  
  114.         {  
  115.             originalNum = e.Result.Count;//記錄原始數據個數  
  116.             dfEmployee.ItemsSource = e.Result;  
  117.         }  
  118.     }  

最終效果圖

最終效果圖

 

原文標題:Silverlight與Access數據庫的互操作(CURD完全解析)

鏈接:http://www.cnblogs.com/Kinglee/archive/2009/09/05/1561021.html

【編輯推薦】

  1. Office 2010將使用Silverlight改善用戶體驗
  2. 微軟.NET平臺主管談Silverlight企業(yè)級開發(fā)
  3. Flash與Silverlight多領域實測對比
  4. 微軟宣稱Silverlight裝機量超過三億
  5. 圖解Silverlight 3的7個新功能
責任編輯:彭凡 來源: 博客園
相關推薦

2009-09-07 15:25:24

MySQL數據庫互操作Silverlight

2009-12-30 14:36:29

Silverlight

2009-12-31 17:31:23

Silverlight

2009-12-09 10:51:18

ibmdwJava

2009-12-29 18:02:26

SilverLight

2009-12-30 15:47:40

Silverlight

2009-08-12 10:47:38

Silverlight

2009-12-31 15:36:13

SilverLight

2009-12-29 18:34:21

Silverlight

2009-12-30 17:19:09

Silverlight

2009-12-31 15:36:13

SilverLight

2010-04-30 13:26:50

Oracle數據庫

2009-12-30 16:48:52

Silverlight

2010-01-04 16:06:34

Silverlight

2010-01-04 13:09:51

Silverlight

2011-06-15 10:09:31

云計算互操作混合云

2009-10-27 10:28:33

Silverlight

2009-02-20 08:54:20

DownloaderSilverlight對象

2012-09-25 14:17:39

互操作

2009-11-18 11:33:23

Silverlight
點贊
收藏

51CTO技術棧公眾號