Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

2008/08/25

A simple Asp.Net Counter [2/25/2011 updated]

2/25/2011 Updated:
Added the Thread-Safe lock.

I create a very simple page counter for some purposes:
  1. It will store the counter data (visit times, last visit date) in a file for easy manipulation.
  2. If the file doesn't exist, then program should create it automatically.
  3. One file can store as many counters info as I want. It I have 5+ pages (or even the whole website) need to be counted, this file can store than all.
  4. Data should be read/wrote easily.
  5. The file should be read by other programs/software easily.
  6. The counter can be reset by program without editing the file manually.
I chose XML as my file format. Here is the code:
static object LockMe = new object();
public static string CounterInfo(string tag, bool resetCounter)
{
  lock (LockMe)
  {
    string counterValue = "1";

    try
    {
      bool tagNotFound = true;
      XmlDocument xDoc = new XmlDocument();
      string filename = @"~/CounterData.xml"; //file to store the counter value
      FileInfo oFile = new FileInfo(HttpContext.Current.Server.MapPath(
      filename));

      //create one if the file doesn't exist
      if (!file.Exists)
        xDoc.LoadXml("");
      else
      {
        //load file which contains counter info
        xDoc.Load(HttpContext.Current.Server.MapPath(filename));

        foreach (XmlNode node in xDoc.GetElementsByTagName(tag))
        {
          if (!resetCounter)
          {
            //show counter value
            counterValue = (Convert.ToInt16(node.InnerText) + 1).ToString();

            //update counter value
            node.InnerText = counterValue;
          }
          else
          {
            //set the value to zero
            node.InnerText = "0";
          }

          //update modified date
          node.Attributes["modifieddate"].Value = DateTime.Now.ToShortDateString();
          tagNotFound = false;
          break;
        }
      }

      //if we can't find the tag, then create one
      if (tagNotFound)
      {
        XmlElement elem = xdoc.CreateElement(tag);
        elem.SetAttribute("modifieddate", DateTime.Now.ToShortDateString());
        elem.InnerText = "1";
        xDoc.DocumentElement.AppendChild(elem);
        elem = null;
      }

      //save back to the xml file
      xDoc.Save(HttpContext.Current.Server.MapPath(filename));
      xDoc = null;
      oFile = null;
    }
    catch (Exception e)
    {
      //log your error message here
    }

    return counterValue;
  }
}

2008/05/16

Use XmlDocument to generate XML

This way is much simpler than XmlTextWriter:
public static String createItem(DataTable dt)
{
  XmlDocument XmlDoc = new XmlDocument();
  XmlDoc.LoadXml("");
  XmlElement XmlElem;

  foreach (DataRow dr in dt.Rows)
  {
    XmlElem = XmlDoc.CreateElement("customer");
    XmlElem.SetAttribute("Name", dr["custName"].ToString());
    XmlElem.SetAttribute("ID", dr["custID"].ToString());
    XmlElem.SetAttribute("Address", dr["address"].ToString());
    XmlElem.SetAttribute("ZipCode", dr["zip"].ToString());
    XmlElem.SetAttribute("Phone", dr["phone"].ToString());
    XmlElem.InnerText = "Kenny";

    XmlDoc.DocumentElement.AppendChild(XmlElem);
  }

  return XmlDoc.FirstChild.InnerXml;
}

Use XmlTextWriter to generate XML

using (MemoryStream ms = new MemoryStream())
{
  XmlTextWriter Xwriter = new XmlTextWriter(ms, Encoding.UTF8);

  Xwriter.WriteStartDocument();  //Put the XML declaration
  Xwriter.Formatting = Formatting.Indented;  //Format the XML document

  Xwriter.WriteComment("XML sample file for ch2.2"); //Put a comment
  Xwriter.WriteStartElement("po");  //This is the root element
  Xwriter.WriteAttributeString("id", "PO1456");

  Xwriter.WriteStartElement("address");
  Xwriter.WriteAttributeString("type", "shipping");
  Xwriter.WriteElementString("name", "Frits Mendels");
  Xwriter.WriteElementString("street", "152 Cherry St");
  Xwriter.WriteElementString("city", "San Francisco");
  Xwriter.WriteElementString("state", "CA");
  Xwriter.WriteElementString("zip", "94045");
  Xwriter.WriteEndElement();

  Xwriter.WriteStartElement("items");
  Xwriter.WriteStartElement("item");
  Xwriter.WriteAttributeString("quantity", "1");
  Xwriter.WriteAttributeString("productCode", "R-273");
  Xwriter.WriteAttributeString("description", "14.4 Volt Cordless Drill");
  Xwriter.WriteAttributeString("unitCost", "189.95");
  Xwriter.WriteEndElement();

  Xwriter.WriteStartElement("item");
  Xwriter.WriteAttributeString("quantity", "1");
  Xwriter.WriteAttributeString("productCode", "1632S");
  Xwriter.WriteAttributeString("description", "12 Piece Drill Bit Set");
  Xwriter.WriteAttributeString("unitCost", "14.95");
  Xwriter.WriteEndElement();
  Xwriter.WriteEndElement();

  Xwriter.WriteEndElement();
  Xwriter.WriteEndDocument();
  Xwriter.Flush();  //flush everything from the buffer
  ms.Position = 0;
  StreamReader sr = new StreamReader(ms);
  return sr.ReadToEnd();
}

The output will be



Frits Mendels 152 Cherry St San Francisco CA 94045

We can also use StreamWriter class instead of MemoryStream, just replace this line of code
XmlTextWriter Xwriter = new XmlTextWriter(ms, Encoding.UTF8);
with
StreamWriter sw = new StreamWriter();
XmlTextWriter Xwriter = new XmlTextWriter(sw);
and remove the using of MemoryStream. Also replace this part
Xwriter.Flush();
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
return sr.ReadToEnd();
with
Xwriter.Flush();
Xwriter.Close();
return sw;

Here is an example from Microsoft Technet.

2007/12/10

Convert xml to table in SQL 2005

This is how I convert XML string into a Table in SQL 2005:
DECLARE @tempTable TABLE (
userId INT,
userName NVARCHAR(50),
password NVARCHAR(50)
)
DECLARE @xml XML
SET @xml='
<row userId="67" userName="Kenny1" password="1234" />
<row userId="80" userName="Kenny2" password="5678" />'

INSERT INTO @tempTable
SELECT Tbl.Col.value('@userId', 'INT'),
       Tbl.Col.value('@userName', 'NVARCHAR(50)'),
       Tbl.Col.value('@password', 'NVARCHAR(50)')
FROM   @xml.nodes('//row') Tbl(Col)

--See the table
SELECT * FROM @tempTable