The server side of the application consists of Web services that load the data from the database and returns it to the server, or receive a list of changes from the client and applies it to the database.
We could implement the server side as a generic handler class (ashx), as a Web Service (asmx), or as a Silverlight-enabled WCF service (SVC). For this sample, any of the choices would do. We chose a classic Web Service.
Follow these steps to create the service:
After you click the Add button, Visual Studio opens the newly created DataService.asmx.cs (or DataService.asmx.vb) file. The file contains a single HelloWorld method.
Edit the file as follows:
C# |
Copy Code
|
---|---|
using System.IO; using System.Data; |
C# |
Copy Code
|
---|---|
[System.Web.Script.Services.ScriptService] |
C# |
Copy Code
|
---|---|
[WebMethod] public byte[] GetData(string tables) { // Create DataSet with connection string var ds = GetDataSet(); // Load data into DataSet ds.Fill(tables.Split(',')); // Persist to stream var ms = new System.IO.MemoryStream(); ds.WriteXml(ms, XmlWriteMode.WriteSchema); // Return stream data return ms.ToArray(); } |
C# |
Copy Code
|
---|---|
[WebMethod] public string UpdateData(byte[] dtAdded, byte[] dtModified, byte[] dtDeleted) { try { UpdateData(dtAdded, DataRowState.Added); UpdateData(dtModified, DataRowState.Modified); UpdateData(dtDeleted, DataRowState.Deleted); return null; } catch (Exception x) { return x.Message; } } |
C# |
Copy Code
|
---|---|
void UpdateData(byte[] data, DataRowState state) { // No changes, no work if (data == null) return; // Load data into dataset var ds = GetDataSet(); var ms = new MemoryStream(data); ds.ReadXml(ms); ds.AcceptChanges(); // Update row states with changes foreach (DataTable dt in ds.Tables) { foreach (DataRow dr in dt.Rows) { switch (state) { case DataRowState.Added: dr.SetAdded(); break; case DataRowState.Modified: dr.SetModified(); break; case DataRowState.Deleted: dr.Delete(); break; } } } // Update the database ds.Update(); } |
C# |
Copy Code
|
---|---|
SmartDataSet GetDataSet() { // Get physical location of the mdb file string mdb = Path.Combine( Context.Request.PhysicalApplicationPath, @"App_Data\nwind.mdb"); // Check that the file exists if (!File.Exists(mdb)) { string msg = string.Format("Cannot find database file {0}.", mdb); throw new FileNotFoundException(msg); } // Make sure file is not read-only (source control often does this...) FileAttributes att = File.GetAttributes(mdb); if ((att & FileAttributes.ReadOnly) != 0) { att &= ~FileAttributes.ReadOnly; File.SetAttributes(mdb, att); } // Create and initialize the SmartDataSet var dataSet = new SmartDataSet(); dataSet.ConnectionString = "provider=microsoft.jet.oledb.4.0;data source=" + mdb; return dataSet; } |