June 27, 2011

Create XML using Linq to XML

Xml stands for eXtensible Markup Language that is designed to store and transfer data. An example xml file is below.

Sample Xml file
  1. <?xml version="1.0" encoding="utf-8" standalone="no"?>
  2. <!--demo on how to create xml file-->
  3. <root>
  4.   <Country id="1" name="Australia" capital="Canberra">
  5.     <state>New South Wales</state>
  6.     <state>Victoria</state>
  7.   </Country>
  8.   <Country id="2" name="India" capital="New Delhi">
  9.     <state>Maharashtra</state>
  10.     <state>Rajasthan</state>
  11.   </Country>
  12.   <Country id="2" name="Bangladesh" capital="Dhaka"><![CDATA[Bangladesh doesn't have any states.]]></Country>
  13. </root>

Xml file starts the xml declaration as in the first line. It supports comments similar to html comments as shown in line 2. It can have elements, can have attributes and can contain CData that is data that can be considered as plain text. Line 4 shows an example of element and attributes – Country is an element and id, name and capital are attributes. The value 1, Australia, etc are the values of the attributes.

In .NET, Linq to Xml makes it easy to create and parse xml documents. It’s easy to create xml, add declarations, add elements, attributes and also add data appropriately. The necessary classes are within the System.Xml.Linq namespace. Linq to Xml has XDocument class with xml documents can be created and loaded. XComment class can be used to add comments. XElement can be used to create elements and XAttribute classes can be used to add attributes to elements. XCData class can be used to add data in cdata format. An example on how to create xml using Linq to Xml is below.

Create xml using Linq
  1. private void CreateXml()
  2. {
  3.     XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "no"));
  5.     XComment comment = new XComment("demo on how to create xml file");
  6.     doc.Add(comment);
  8.     XElement el = new XElement("root");
  9.     XElement p1 = new XElement("Country", new object[] { new XAttribute("id", "1"), new XAttribute("name", "Australia"), new XAttribute("capital", "Canberra") });
  11.     XElement p1city1 = new XElement("state", "New South Wales");
  12.     XElement p1city2 = new XElement("state", "Victoria");
  14.     p1.Add(p1city1);
  15.     p1.Add(p1city2);
  17.     XElement p2 = new XElement("Country", new object[] { new XAttribute("id", "2"), new XAttribute("name", "India"), new XAttribute("capital", "New Delhi") });
  19.     XElement p2city1 = new XElement("state", "Maharashtra");
  20.     XElement p2city2 = new XElement("state", "Rajasthan");
  22.     p2.Add(p2city1);
  23.     p2.Add(p2city2);
  25.     XElement p3 = new XElement("Country", new object[] { new XAttribute("id", "3"), new XAttribute("name", "Bangladesh"), new XAttribute("capital", "Dhaka") });
  27.     p3.Add(new XCData("Bangladesh doesn't have any states."));
  29.     el.Add(p1);
  30.     el.Add(p2);
  31.     el.Add(p3);
  32.     doc.Add(el);
  34.     doc.Save(Server.MapPath("country.xml"));            
  35. }

As can be seen, once the XElement, XComment, XAttribute objects are created, they got to be added to parent object. Once the necessary data has been added, the xml file can be saved using XDocument’s Save method as in line 34 above.

June 16, 2011

Query DataTable using Linq

In this example, I will show how to use Linq to query DataTable. A DataTable is a table of data stored in memory. Since Linq can query data of IEnumerable type, the data rows are declared as as IEnumerable so that Linq can query the data.

I have already setup the web application and have added a page. I will now define the schema of the DataTable and then create it. The code for creating the DataTable is below.

Create DataTable
  1. private DataTable GetDataTable()
  2. {
  3.     DataTable dt = new DataTable();
  5.     //add columns
  6.     dt.Columns.Add("ID", typeof (Int32));
  7.     dt.Columns.Add("Name", typeof(string));
  8.     dt.Columns.Add("DateOfBirth", typeof(DateTime));
  10.     //add rows of data
  11.     dt.Rows.Add(new object[] { 1, "Bugs Bunny", DateTime.Now});
  12.     dt.Rows.Add(new object[] { 2, "Daffy Duck", DateTime.Now });
  13.     dt.Rows.Add(new object[] { 3, "Scooby Doo", DateTime.Now });
  14.     return dt;        
  15. }

As can be seen, columns of type int, string and DateTime are added to the DataTable. Then, rows of data are added. This DataTable is later used for querying using Linq.

As mentioned earlier, to query DataTable using Linq, it has to be of type System.Collections.Generic.IEnumerable . To do this, DataTable’s AsEnumerable method can be used. This method converts the standard DataTable to a DataTable of IEnumerable type. The method for converting and querying the DataTable is below.

Query DataTable
  1. private void QueryDataTable(DataTable dt)
  2. {
  3.     var q = from DataRow row in dt.AsEnumerable()
  4.             select row;
  6.     int col = dt.Columns.Count;//no of columns
  8.     foreach (DataRow row in q)
  9.     {
  10.         for (int i = 0; i < col; i++)
  11.         {
  12.             L1.Text += row[i].ToString() + "&nbsp;";
  13.         }
  14.         L1.Text += "<br/>";
  15.     }
  16. }

At first, I have converted the DataTable to of type IEnumerable and have selected all the rows. Then, I have queried each of the DataRow and retrieved the values for each of the columns. L1 is a Literal control that has been declared on the aspx page.

Please note that, I have simply added the values returned in string variables, ideally, a System.Text.StringBuilder object should be used to achieve this.

The above methods can then be called from Page_Load or other methods as shown below.

Page_Load event
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     QueryDataTable(GetDataTable());
  4. }

June 5, 2011

Access anchor link from code-behind

Html anchor links are a way to navigate within a page. The anchor can be considered as a bookmark within a page, which when clicked takes the user to that section of a page. An anchor to a certain section of a page can be set in the following way.

  1. <a name=”anchor”></a><div>content</div>

The name attribute of the “a” element determines the anchor / bookmark to the page. The anchor can be accessed by setting the link like below.

  1. <a href=”#anchor”>Anchor</a>

However, the anchor link is a client side thing and cannot be accessed from server-side. In this post, I am going to show how the anchor link can be accessed from server-side using hidden field and javascript. The following is the code for the aspx page.

aspx page
  1. <body>
  2.     <form id="form1" runat="server">
  3.     <div>
  4.     <a name="anchor"></a>
  5.     <div>Some content <a href="#anchor" onclick="SetUrl('anchor')">click here</a></div>
  6.     <asp:HiddenField ID="HF1" runat="server" />
  7.     <asp:Button ID="B1" runat="server" Text="Check Anchor" OnClick="GetAnchor" />
  8.     <asp:Literal ID="L1" runat="server"></asp:Literal>
  9.     </div>
  10.     <script type="text/javascript">
  11.         SetUrl("");
  12.     </script>
  13.     </form>
  14. </body>

The page is simple, contains a HiddenField, Button and Literal control to display the anchor, if any. At the bottom of the page, before the closing form tag is a javascript method, SetUrl(“”) that sets the anchor in the hidden field. The code for javascript method is below.

JavaScript code
  1. <script type="text/javascript">
  2.     function SetUrl(val) {
  3.         if (val == "" && location.href.indexOf("#") > -1) {
  4.             document.getElementById('<%= HF1.ClientID %>').value = location.href; //set value of HiddenField
  5.         }
  6.         else if (val == "" && location.href.indexOf("#") == -1) {
  7.             document.getElementById('<%= HF1.ClientID %>').value = "";
  8.         }
  9.         else {
  10.             document.getElementById('<%= HF1.ClientID %>').value = val;
  11.         }
  12.         alert(val);
  13.     }    
  14. </script>

The javascript method, checks if there is a value for the anchor when the link is clicked. If not and if it does not contain the “#” character in the url, it does not set the value of the anchor in the HiddenField. Otherwise, it either sets the value when clicked or sets the url if it contains “#” character.

Once the HiddenField value is set, the value can be accessed from the server side. In this example, when the button is clicked, the value is obtained and set as the Text property of the Literal control. Here is the code for Button click event.

Button click event
  1.     protected void GetAnchor(object sender, EventArgs e)
  2.     {
  3.         string anchor = HF1.Value;//get url from hidden field
  4.         if (anchor.Contains("#"))//check if it an anchor
  5.         {
  6.             string[] list = anchor.Split(new char[] { '#' });
  7.             L1.Text = "anchor name is :" + list[1];
  8.         }
  9.         else if (anchor != "")
  10.             L1.Text = anchor;
  11.         else
  12.             L1.Text = string.Empty;
  13.     }
  14. }

The code finds the value of the HiddenField and displays it in the Literal control.

Reference: Shahed Kazi at AspNetify.com