Friday, May 23, 2008

How To Read Embedded Resource File

state.cs
using System;
using System.Collections.Generic;

using System.Text;

namespace EmbeddedResource.Library
{
   public class State
   {
       private string _name;
       private string abbreviation;

       public string Abbreviation
       {
           get { return abbreviation; }
           set { abbreviation = value; }
       }
 

       public string Name
       {
           get { return _name; }
           set { _name = value; }
       }
 
     
   }
}

StatesCollection.cs

using System;
using System.Collections.Generic;

using System.Text;
using System.Xml;
using System.Reflection;
using System.Collections;

namespace EmbeddedResource.Library
{
   public class StatesCollection : System.Collections.Generic.List<State>
   {
       private StatesCollection()
       {

       }

       private static StatesCollection _southernStates = null;
       public static StatesCollection SouthernStates
       {
           get
           {
               if (_southernStates == null)
               {
                   StatesCollection states = new StatesCollection();
                   try
                   {
                       System.Reflection.Assembly asm =
Assembly.GetExecutingAssembly();
                       System.IO.Stream xmlStream =
 asm.GetManifestResourceStream("EmbeededResource.Data.SouthernStates.xml");
                       XmlDocument xmlDoc = new XmlDocument();
                       xmlDoc.Load(xmlStream);
                       XmlNodeList nodes = xmlDoc.SelectNodes("/States/State");
                       StatesCollection coll = new StatesCollection();
                       foreach (XmlNode node in nodes)
                       {
                           State state = new State();
                           state.Abbreviation = node["Abbreviation"].InnerText;
                           state.Name = node["Name"].InnerText;
                           coll.Add(state);
                       }
                       return coll;
                   }
                   catch (Exception ex)
                   {
                       throw new Exception(ex.Message);
                   }
               }
               else
               {
                   return _southernStates;
               }
           }
       }
   }
}


How To Read

using System;
using System.Collections.Generic;
using System.Text;
using EmbeddedResource;
using EmbeddedResource.Library;

namespace ReadXml
{
   class Program
   {
       static void Main(string[] args)
       {
           foreach (State state in StatesCollection.SouthernStates)
           {
               Console.WriteLine("Name: " + state.Name + " | Abbr: " + state.Abbreviation);
           }
           Console.ReadLine();
       }
   }
}
Place this XML(
SouthernStates.xml)
file in Data folder
<?xml version="1.0" encoding="utf-8" ?>
- <States>
- <State>
  <Name>Mississippi</Name>
  <Abbreviation>MS</Abbreviation>
  </State>
- <State>
  <Name>Tennesse</Name>
  <Abbreviation>TN</Abbreviation>
  </State>
- <State>
  <Name>Arkansas</Name>
  <Abbreviation>AR</Abbreviation>
  </State>
- <State>
  <Name>Louisiana</Name>
  <Abbreviation>LA</Abbreviation>
  </State>
- <State>
  <Name>Georiga</Name>
  <Abbreviation>GA</Abbreviation>
  </State>
- <State>
  <Name>Florida</Name>
  <Abbreviation>FL</Abbreviation>
  </State>
  </States>

Thursday, May 15, 2008

Parsing Comma-Separated Values or CSV files into a DataTable using Regular Expressions

Sometimes, you find the need to parse CSV files dynamically into a DataTable. CSV files can be simple or complex. The simple CSV file would just have the fields separated by commas. Complexity comes in when the data itself has embedded commas, quotes or line breaks. This solution, written in C#, and using the .NET Framework's Regular Expression object can handle such complex data. This has been tested to work with CSV formatted files saved from Microsoft Excel.

To begin with, make sure that you have the following namespaces:


using System.Data;
using System.IO;
using System.Text.RegularExpressions;

Next, we build a function that parses any CSV input string into a DataTable:


public static DataTable ParseCSV(string inputString)
{

    DataTable dt = new DataTable();

    // declare the Regular Expression that will match versus the input string
    Regex re = new
Regex("((?<field>[^\",\\r\\n]+)|\"(?<field>([^\"]|\"\")+)\")(,|(?<rowbreak>\\r\\n|\\n|$))");

    ArrayList colArray = new ArrayList();
    ArrayList rowArray = new ArrayList();

    int colCount = 0;
    int maxColCount = 0;
    string rowbreak = "";
    string field = "";

    MatchCollection mc = re.Matches(inputString);

    foreach (Match m in mc)
    {

        // retrieve the field and replace two double-quotes with a single double-quote
        field = m.Result("${field}").Replace("\"\"", "\"");

        rowbreak = m.Result("${rowbreak}");

        if (field.Length > 0)
        {
            colArray.Add(field);
            colCount++;
        }

        if (rowbreak.Length > 0)
        {

            // add the column array to the row Array List
            rowArray.Add(colArray.ToArray());

            // create a new Array List to hold the field values
            colArray = new ArrayList();

            if (colCount > maxColCount)
                maxColCount = colCount;

            colCount = 0;
        }
    }

    if (rowbreak.Length == 0)
    {
        // this is executed when the last line doesn't
        // end with a line break
        rowArray.Add(colArray.ToArray());
        if (colCount > maxColCount)
            maxColCount = colCount;
    }

    // create the columns for the table
    for (int i = 0; i < maxColCount; i++)
        dt.Columns.Add(String.Format("col{0:000}", i));

    // convert the row Array List into an Array object for easier access
    Array ra = rowArray.ToArray();
    for (int i = 0; i < ra.Length; i++)
    {

        // create a new DataRow
        DataRow dr = dt.NewRow();

        // convert the column Array List into an Array object for easier access
        Array ca = (Array)(ra.GetValue(i));

        // add each field into the new DataRow
        for (int j = 0; j < ca.Length; j++)
            dr[j] = ca.GetValue(j);

        // add the new DataRow to the DataTable
        dt.Rows.Add(dr);
    }

    // in case no data was parsed, create a single column
    if (dt.Columns.Count == 0)
        dt.Columns.Add("NoData");

    return dt;
}

Now that we have a parser for converting a string into a DataTable, all we need now is a function that will read the content from a CSV file and pass it to our ParseCSV function:


public DataTable ParseCSVFile(string path)
 {

     string inputString = "";

     // check that the file exists before opening it
     if (File.Exists(path))
     {

         StreamReader sr = new StreamReader(path);
         inputString = sr.ReadToEnd();
         sr.Close();

     }

     return ParseCSV(inputString);
 }

And now you can easily fill a DataGrid with data coming off the CSV file:


protected System.Web.UI.WebControls.DataGrid DataGrid1;

private void Page_Load(object sender, System.EventArgs e) {

// call the parser
DataTable dt=ParseCSVFile(Server.MapPath("./demo.csv"));

// bind the resulting DataTable to a DataGrid Web Control
DataGrid1.DataSource=dt;
DataGrid1.DataBind();
}

Friday, May 2, 2008

GridView UpdatePanel and Javascript

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewScript.aspx.cs"
Inherits="GridViewScript" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
   <title>Untitled Page</title>

   <script type="text/javascript">
   function checkCheckBoxes()
   {
     alert('There are ' + checkBoxes.length + 'checkboxes');
  
       for(i=0;i<checkBoxes.length;i++)
       {
           var cb=document.getElementById(checkBoxes[i]);
           if(cb.checked)
           {
               alert('CheckBox on row ' + (i + 1) + ' is checked!' );
           }
        
       }
   }
   </script>

</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:ScriptManager ID="ScriptManager1" runat="server">
           </asp:ScriptManager>
           <asp:UpdatePanel ID="UpdatePanel1" runat="server">
               <ContentTemplate>
                   <asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="false" OnPreRender="GridView1_PreRender">
                       <Columns>
                           <asp:TemplateField>
                               <ItemTemplate>
                                   <asp:CheckBox ID="CheckBox1" runat="server" Text='<%#Container.DataItem %>' />
                               </ItemTemplate>
                           </asp:TemplateField>
                           <asp:TemplateField>
                               <ItemTemplate>
                                   <asp:Button ID="Button1" runat="server" Text="Cause async postback for demonstration" />
                               </ItemTemplate>
                           </asp:TemplateField>
                       </Columns>
                   </asp:GridView>
                   <input type="button" value="Show thew checked states in javascript" onclick="checkCheckBoxes()" />
                   <asp:TextBox ID="txtRowCount" runat="server">3</asp:TextBox>
                   <asp:Button ID="btnBind" runat="server" OnClick="btnBind_Click" Text="Bind x rows to grid" />
               </ContentTemplate>
           </asp:UpdatePanel>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;

public partial class GridViewScript : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Binding the grid for demonstration
        if (!Page.IsPostBack)
        {
            BindXDummyRowToGrid(3);
        }
    }

    private void BindXDummyRowToGrid(int rowCount)
    {
        List<int> ints = new List<int>();
        for (int i = 1; i < rowCount + 1; i++)
        {
            ints.Add(i);
        }
        GridView1.DataSource = ints;
        GridView1.DataBind();
    }


    protected void btnBind_Click(object sender, EventArgs e)
    {

        int rowCount = Int32.Parse(txtRowCount.Text);
        BindXDummyRowToGrid(rowCount);
    }

    protected void GridView1_PreRender(object sender, EventArgs e)
    {
        StringBuilder sbScript = new StringBuilder();
        //I'm doing this in PreRender because RowDataBound happens only when databinding occurs -
        //not necessarily on every request
        //and RowCreated is too early to get the correct client-side ID
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox CheckBox1 = (CheckBox)row.FindControl("CheckBox1");
            sbScript.Append("'");
            sbScript.Append(CheckBox1.ClientID);
            sbScript.Append("'");
            if (row.RowIndex != (GridView1.Rows.Count - 1))
                sbScript.Append(",");

        }

        ScriptManager.RegisterArrayDeclaration(this, "checkBoxes", sbScript.ToString());
    }



}

Thursday, May 1, 2008

Create Dynamic Control using Repeater and List




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicTextBox.aspx.cs"
Inherits="DynamicTextBox" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtNumber" runat="server" BackColor="#FF8000"
ForeColor="#FF8000"></asp:TextBox>
<asp:Button ID="btnCreate" runat="server" Text="Create" OnClick="btnCreate_Click" />
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:TextBox ID="txt" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table></FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

public partial class DynamicTextBox : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{



}
protected void btnCreate_Click(object sender, EventArgs e)
{
int numberOfTextboxes = int.Parse(txtNumber.Text);
List<int> dataSource = new List<int>();
for (int i = 0; i < numberOfTextboxes; i++)
{
dataSource.Add(i);
}

this.rpt.DataSource = dataSource;
this.rpt.DataBind();


}
}

How To Read XML Using Javascript




<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
void Page_Load()
{
if (Request.QueryString["sendData"] != null &&
Request.QueryString["sendData"] == "ok")
{
string xml = "<book title=\"ASP.NET Code Book\" author=\"Blog\">" +
"<chapters><chapter number=\"1\" title=\"Introduction\" />" +
"<chapter number=\"2\" title=\"JavaScript\" /><chapter number=\"3\" title=\"Ajax\" />" +
"<chapter number=\"4\" title=\"WPF\" /></chapters></book>";
Response.ContentType = "text/xml";
Response.Write(xml);
Response.End();
}
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Ajax with ASP.NET</title>

<script language="Javascript" type="text/javascript">
function getXMLHTTP( )
{
var XMLHTTP = null;
if (window.ActiveXObject)
{
try {
XMLHTTP = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try {
XMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
}
}
}
else if (window.XMLHttpRequest)
{
try {
XMLHTTP = new XMLHttpRequest( );
}
catch (e)
{
}
}
return XMLHTTP;
}
var XMLHTTP;
window.onload = function( )
{
XMLHTTP = getXMLHTTP( );
if (XMLHTTP != null)
{
XMLHTTP.open("GET", "xmldocument.aspx?sendData=ok");
XMLHTTP.onreadystatechange = stateChanged;
XMLHTTP.send(null);
}
}
function stateChanged( ) {
if (XMLHTTP.readyState == 4 && XMLHTTP.status == 200)
{
var xml = XMLHTTP.responseXML;
var root = xml.documentElement;
document.getElementById("output").innerHTML =
root.getAttribute("title") +" by " + root.getAttribute("author");
var list = document.getElementById("list");
var chapters = xml.getElementsByTagName("chapter");
for (var i=0; i<chapters.length; i++)
{
var listItem = document.createElement("li");
var listItemText = document.createTextNode(
chapters[i].getAttribute("number") +
": " +
chapters[i].getAttribute("title"));
listItem.appendChild(listItemText);
list.appendChild(listItem);
}
}
}
</script>

</head>
<body>
<p id="output">
Wait and see ...</p>
<ul id="list">
</ul>
</body>
</html>

How To Join Two TextBox Values Using Javascript

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AutoName.aspx.cs"
Inherits="AutoName" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
      <div>
          <asp:TextBox ID="firstName" runat="server" onkeyup="autoname( );" Text="First" />
          <asp:TextBox ID="lastName" runat="server" onkeyup="autoname( );" Text="Last" />
          <asp:TextBox ID="fullName" runat="server" Text="" />
      </div>
  </form>

  <script type="text/javascript">

  function autoname( )
  {
      var temp = document.getElementById( "firstName" ).value.toLowerCase( );
      temp += " "+ document.getElementById( "lastName" ).value.toLowerCase( );

      document.getElementById( "fullName" ).value = temp;
  }

  autoname( );

  </script>

</body>
</html>