Source Code

for file /AJAXEngine/S06_AJAXForms/TableData.asmx

<%@ WebService Language="C#" Class="TableData" %>

// TableData.asmx
// Data provider to a list of demo data for ther Table Data Sample.
// Copyright (c) by Matthias Hertel, http://www.mathertel.de
// This work is licensed under a BSD style license. See http://www.mathertel.de/License.aspx
// ----- 
// 01.06.2005 created by Matthias Hertel
// 29.09.2005 namespaces rearranged.
// 09.07.2007 update implemented. changed values are not persisted to the data file.

using System;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.XPath;

using AJAXControls;

/// <summary>
/// This is a simple WebService implementing the ITableDataService interface for the TableData Ajax Control
/// by reading from an XML file.
/// </summary>
[WebService(Namespace = "http://www.mathertel.de/AJAXForms/TableData")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TableData : System.Web.Services.WebService, ITableDataService {

  private static XmlDocument _data = null;


  public TableData() {

  }


  // see http://samples.gotdotnet.com/quickstart/howto/doc/Xml/XPathExpression.aspx
  [WebMethod(Description = "Return the ids of all found rows in a sorted order.")]
  public string Select(string filter, string order) {
    Load();
    StringBuilder ret = new StringBuilder();

    XPathNavigator myXPathNavigator = _data.CreateNavigator();
    myXPathNavigator.MoveToRoot();

    XPathExpression myXPathExpr = myXPathNavigator.Compile("/customers/customer");

    myXPathExpr.AddSort(order, XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Text);

    XPathNodeIterator nav = myXPathNavigator.Select(myXPathExpr);

    while (nav.MoveNext()) {
      if (ret.Length > 0) ret.Append(';');
      nav.Current.MoveToChild("id", "");
      ret.Append(nav.Current.Value);
    } // while

    return (ret.ToString());
  } // Select

  //  <customer>
  //  <id>ANATR</id>
  //  <company>Ana Trujillo Emparedados y helados</company>
  //  <name>Ana Trujillo</name>
  //  <city>M�xico D.F.</city>
  //  <country>Mexico</country>
  //</customer>


  [WebMethod(Description = "Return the ids of all found rows in a sorted order.")]
  public string Search(XmlDocument doc, string order) {
    string ret = String.Empty;
    string xPathSearch = String.Empty;

    // the doc parameter contains the values of the form elements
    // that are used to search for records.
    foreach (XmlNode xNode in doc.DocumentElement.ChildNodes) {
      if ((xNode.InnerText != null) && (xNode.InnerText.Length > 0)) {
        string val = xNode.InnerText.Replace("\'", "\\\'");
        if (xPathSearch.Length > 0)
          xPathSearch += " and ";
        if (val.EndsWith("%")) {
          xPathSearch += string.Format("starts-with({0}, '{1}')", xNode.Name, val.Substring(0, val.Length - 1));
        } else {
          xPathSearch += string.Format("{0}='{1}'", xNode.Name, val);
        } // if
      } // if  
    } // foreach

    XmlDocument data = Load();
    //XPathNavigator xpn = data.CreateNavigator();
    if (xPathSearch.Length > 0) {
      xPathSearch = "//customer[" + xPathSearch + "]";
    } else {
      xPathSearch = "//customer";
    } // if


    XPathNavigator myXPathNavigator = _data.CreateNavigator();
    myXPathNavigator.MoveToRoot();

    XPathExpression myXPathExpr = myXPathNavigator.Compile(xPathSearch);
    if ((order != null) && (order.Length > 0))
      myXPathExpr.AddSort(order, XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Text);
    
    XPathNodeIterator nav = myXPathNavigator.Select(myXPathExpr);
    while (nav.MoveNext()) {
      if (ret.Length > 0) ret += (';');
      nav.Current.MoveToChild("id", String.Empty);
      ret += nav.Current.Value;
    } // while

    return (ret);
  } // Select


  [WebMethod(Description = "Return a single row, identified by the id.")]
  public XmlNode Fetch(string id) {
    Load();

    string[] idList = id.Split(';');
    
    XmlDocument ret2 = new XmlDocument(_data.NameTable);
    XmlNode ret3 = ret2.AppendChild(ret2.CreateElement("records"));

    XPathNavigator myXPathNavigator = _data.CreateNavigator();

    foreach (string i in idList) {
      myXPathNavigator.MoveToRoot();
      XPathNavigator n = myXPathNavigator.SelectSingleNode("/customers/customer[id='" + i.Replace("'", "") + "']");
      if (n != null)
        ret3.AppendChild(ret2.ImportNode(((IHasXmlNode)n).GetNode(), true));
    } // foreach
      
    return (ret3);
  } // Fetch


  [WebMethod(Description = "Insert a record.")]
  public XmlNode Insert(XmlDocument doc) {
    Load();

    XmlDocument retDoc = new XmlDocument(_data.NameTable);
    XmlNode retNode = retDoc.AppendChild(retDoc.CreateElement("records"));

    XPathNavigator myXPathNavigator = _data.CreateNavigator();
    
    XmlNode col = _data.SelectSingleNode("/customers");
    XmlNode rec = _data.CreateElement("customer");
    col.AppendChild(rec);

    foreach (XmlNode a in doc.DocumentElement.ChildNodes) {
      if (a.Name != "id") {
        XmlElement e = _data.CreateElement(a.Name);
        rec.AppendChild(e);
        e.InnerText = a.InnerText;
      } // if
    } // foreach

    XmlElement id = _data.CreateElement("id");
    rec.AppendChild(id);
    id.InnerText = Guid.NewGuid().ToString();
    
    
    return (retNode.AppendChild(retDoc.ImportNode(rec, true)));
  } // Insert


  [WebMethod(Description = "Update a record.")]
  public XmlNode Update(string id, XmlDocument doc) {
    Load();

    XmlDocument retDoc = new XmlDocument(_data.NameTable);
    XmlNode retNode = retDoc.AppendChild(retDoc.CreateElement("records"));

    XPathNavigator myXPathNavigator = _data.CreateNavigator();

    // find the record specified by id
    myXPathNavigator.MoveToRoot();
    XPathNavigator n = myXPathNavigator.SelectSingleNode("/customers/customer[id='" + id.Replace("'", "") + "']");
    XmlNode current = ((IHasXmlNode)n).GetNode();

    // update all fields
    foreach (XmlNode xNode in doc.DocumentElement.ChildNodes) {
      XmlNode currentField = current.SelectSingleNode(xNode.Name);
      string val = currentField.InnerText;
      string newval = xNode.InnerText;

      if (val != newval) {
        currentField.InnerText = newval;
      } // if  
    } // foreach
    
    
    // return updated node
    if (n != null)
      retNode.AppendChild(retDoc.ImportNode(((IHasXmlNode)n).GetNode(), true));

    return (retNode);
  } // Update


  [WebMethod(Description = "Delete a record.")]
  public void Delete(string id) {
    Load();

    XmlDocument retDoc = new XmlDocument(_data.NameTable);
    XmlNode retNode = retDoc.AppendChild(retDoc.CreateElement("records"));

    XPathNavigator myXPathNavigator = _data.CreateNavigator();

    // find the record specified by id
    myXPathNavigator.MoveToRoot();
    XPathNavigator n = myXPathNavigator.SelectSingleNode("/customers/customer[id='" + id.Replace("'", "") + "']");
    if (n != null) {
      XmlNode current = ((IHasXmlNode)n).GetNode();
      current.ParentNode.RemoveChild(current);
    }

  } // Delete

  
  // load a recordset to the _data member.
  // load from a file if not in memory yet.
  private XmlDocument Load() {
    if (_data == null) {
      _data = new XmlDocument();
      _data.Load(Server.MapPath("TableData.xml"));
    } // if
    return (_data);
  } // Load

}



This page is part of the http://www.mathertel.de/ web site.

For updates and discussions see http://ajaxaspects.blogspot.com/.