<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Three2Tango &#187; C# Codes</title>
	<atom:link href="http://www.three2tango.com/category/techcorner/csharpcodes/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.three2tango.com</link>
	<description>Points To Ponder : The Latest news from the TechWorld,Automobiles,CellPhones and lots of useful Code Snippets</description>
	<lastBuildDate>Fri, 27 Jan 2012 09:03:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Populating ASP.NET TreeView Control from DataBase</title>
		<link>http://www.three2tango.com/techcorner/populating-asp-net-treeview-control-from-database.html/</link>
		<comments>http://www.three2tango.com/techcorner/populating-asp-net-treeview-control-from-database.html/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 09:46:45 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C# Codes]]></category>
		<category><![CDATA[Tech Corner]]></category>
		<category><![CDATA[C# Code Snippets]]></category>
		<category><![CDATA[TreeView]]></category>

		<guid isPermaLink="false">http://www.three2tango.com/?p=2636</guid>
		<description><![CDATA[Here i will explain the binding of a treeview from the Database.This can be a tricky task since we may have to build a parent-child relationship here.So first thing you would need is a table in the database where we actually have the parent-child relationship.
An Example
Table Name: Category
CategoryId  INT
CategoryName  Varchar(50)
ParentCategoryId INT
NodeLevel  INT
Suppose we have Data in the Table named Category as follows



1
Root
NULL
0


2
Child
1
1


3
Child2
1
1


4
grandChild
2
2


5
grandChild2
2
2


6
grandChild3
3
2



// 

Now to bind this to the tree,we will use a recursive function.Also for better performance,we will bind the database results into a global DataTable first and then apply filtering.
Here is the Code ...]]></description>
			<content:encoded><![CDATA[<p>Here i will explain the binding of a treeview from the Database.This can be a tricky task since we may have to build a parent-child relationship here.So first thing you would need is a table in the database where we actually have the parent-child relationship.<br />
An Example<br />
Table Name: Category<br />
CategoryId  INT<br />
CategoryName  Varchar(50)<br />
ParentCategoryId INT<br />
NodeLevel  INT</p>
<p>Suppose we have Data in the Table named Category as follows</p>
<table border="1">
<tbody>
<tr>
<td>1</td>
<td>Root</td>
<td>NULL</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>Child</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>Child2</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>grandChild</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>grandChild2</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>6</td>
<td>grandChild3</td>
<td>3</td>
<td>2</td>
</tr>
</tbody>
</table>
<p><script type="text/javascript">// <![CDATA[
           google_ad_client = "pub-6525089797582043"; /* 468x15, created 7/8/09 */ google_ad_slot = "8684679217"; google_ad_width = 468; google_ad_height = 15;
// ]]&gt;</script><br />
<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script><br />
Now to bind this to the tree,we will use a recursive function.Also for better performance,we will bind the database results into a global DataTable first and then apply filtering.</p>
<p>Here is the Code to bind to the DataTable.</p>
<pre name="code" language="c-sharp"> private void bindDataTable()
    {
       
        string strConn = ConfigurationManager.ConnectionStrings["yourConnectionName"].ConnectionString;
        SqlConnection conn = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand("Select * from Category", conn);
        cmd.CommandType = CommandType.Text;
       
        SqlDataAdapter sqlDa = new SqlDataAdapter();
        sqlDa.SelectCommand = cmd;
        sqlDa.Fill(dt);
        conn.Close();

    }</pre>
<p>Now we will add a recursive method that will make use of this DataTable to build the TreeView.</p>
<pre name="code" language="c-sharp">private void buildNodes(TreeNode n, int? categoryId)
    {
        DataRow[] drCategories;
        if (categoryId == null)
            drCategories = dt.Select("NodeLevel=0"); // This will get the Root Node
        else
            drCategories = dt.Select("ParentIdFK='" + categoryId + "'");

        foreach (DataRow dr in drCategories)
        {
            TreeNode t = new TreeNode();
            t.Text = dr["CategoryName"].ToString();
            t.Value = dr["CategoryId"].ToString();    
           
            buildNodes(t, Convert.ToInt32(dr["CategoryId"].ToString()));// Calling the function resursively
            if (n == null)// If it is Root Node
                TreeView1.Nodes.Add(t);
            else
                n.ChildNodes.Add(t);

        }</pre>
<p>Above we are using int? so that int type can accept null values.</p>
<p>So now all we have to do is call these methods.</p>
<pre name="code" language="c-sharp">  protected void Page_Load(object sender, EventArgs e)
     {
         if (!IsPostBack)
         {
              bindDataTable();
              buildNodes(null, null);//CategoryId=null is passed which is the ParentId of the Root Node
         }
     }</pre>
<p>Now you can add some formatting and Css as you may please to get a better looking Treeview.Happy Coding Folks!!!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.three2tango.com/techcorner/populating-asp-net-treeview-control-from-database.html/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Convert a String in CSV format to INT Array in .NET</title>
		<link>http://www.three2tango.com/techcorner/convert-a-string-in-csv-format-to-int-array-in-net.html/</link>
		<comments>http://www.three2tango.com/techcorner/convert-a-string-in-csv-format-to-int-array-in-net.html/#comments</comments>
		<pubDate>Tue, 06 Oct 2009 17:27:12 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C# Codes]]></category>
		<category><![CDATA[Tech Corner]]></category>
		<category><![CDATA[C# Code Snippets]]></category>
		<category><![CDATA[Convert a String in CSV format to INT Array in .NET]]></category>

		<guid isPermaLink="false">http://www.three2tango.com/?p=2540</guid>
		<description><![CDATA[There may be many instances in which we may have to supply a string in CSV format to be converted into an integer array.For example,if we have to invoke a web method in a web service in which the parameters to be passed is an integer array.There is no way that we can pass an Integer array to the web method,else you would have to have a client application to test the method.Well,this was the instance in which i had the need to pass these integers in CSV format as ...]]></description>
			<content:encoded><![CDATA[<p>There may be many instances in which we may have to supply a string in CSV format to be converted into an integer array.For example,if we have to invoke a web method in a web service in which the parameters to be passed is an integer array.There is no way that we can pass an Integer array to the web method,else you would have to have a client application to test the method.Well,this was the instance in which i had the need to pass these integers in CSV format as a string and get the result.</p>
<p>Here is the code to  convert a string in CSV format ot an integer array.</p>
<pre name="code" class="c-sharp">
 
public int[] StringToArray(string input)
        {
            string[] stringList = input.Split(",".ToCharArray(),
                                              StringSplitOptions.RemoveEmptyEntries);
           
            int[] ids = new int[stringList.Length];

            for (int i = 0; i &lt; stringList.Length; i++)
            {
                ids[i] = (int)Convert.ChangeType(stringList[i], typeof(int));
            }

            return ids;  
        }
</pre>
<p> <br />
Here instead of the &#8220;,&#8221; delimiter you can make use of the delimiter used in your format</p>
]]></content:encoded>
			<wfw:commentRss>http://www.three2tango.com/techcorner/convert-a-string-in-csv-format-to-int-array-in-net.html/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XML serialization of Objects in .NET</title>
		<link>http://www.three2tango.com/techcorner/xml-serialization-of-objects-in-net.html/</link>
		<comments>http://www.three2tango.com/techcorner/xml-serialization-of-objects-in-net.html/#comments</comments>
		<pubDate>Mon, 05 Oct 2009 17:12:52 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C# Codes]]></category>
		<category><![CDATA[Tech Corner]]></category>
		<category><![CDATA[C# Code Snippets]]></category>
		<category><![CDATA[XML serialization of Objects in .NET]]></category>

		<guid isPermaLink="false">http://www.three2tango.com/?p=2538</guid>
		<description><![CDATA[Serialization is a process by which information in an object is converted into a persistable and transportable form.Here i will explain the easiest way to do XML Serialization,which converts (serializes) the public fields and properties  of an object, or the parameters and return values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document.
To explain the basics of serialization,lets create a class Product containing information about a Product
Public Class Product()
{
public product(){ }
public string productName;
public float productPrice;
}
Now to create an XML representation of the object ...]]></description>
			<content:encoded><![CDATA[<p>Serialization is a process by which information in an object is converted into a persistable and transportable form.Here i will explain the easiest way to do XML Serialization,which converts (serializes) the public fields and properties  of an object, or the parameters and return values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document.<br />
To explain the basics of serialization,lets create a class Product containing information about a Product</p>
<pre name="code" language="c-sharp">Public Class Product()
{
public product(){ }
public string productName;
public float productPrice;
}</pre>
<p>Now to create an XML representation of the object of class Product,we can make use of the XmlSerializer class in .Net.Here is the C# code for implementing serialization.</p>
<pre name="code" language="c-sharp">Product p=new Product();
p.productName="product1";
p.productPrice=12.00;
XmlSerializer serializer=new XmlSerializer(typeOf(Product));
StringWriter sw=new StringWriter();
serializer.Serialize(sw,p);
sw.Close(); </pre>
<p> <br />
Here is another example.In the below code,i have an object of class Product,which contains Product Information.when i run the webservice,i have to pass the ProductId(second line) to get the information and the webservice will automatically generate an XML file containing the details.Now what do we do if we have to save this information to another XML file so that we have the information even after the web service is stopped or in more technical terms we want the data to be persistent.</p>
<p>Namespace used: <em>System.Xml.Serialization</em>;      </p>
<pre name="code" class="c-sharp">Product productXml = new Product();
productXml = application.getProducts().getProductInfo(id);//build the product object
XmlSerializer serialize = new XmlSerializer(typeof(Product));
TextWriter tw = new StreamWriter(Server.MapPath("Products.xml"));
serialize.Serialize(tw, productXml);
tw.Close();</pre>
<p>Dont forget to include System.IO,else you wont be able to use TextWriter and StreamWriter.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.three2tango.com/techcorner/xml-serialization-of-objects-in-net.html/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>DataBase Access in dot net</title>
		<link>http://www.three2tango.com/techcorner/database-access-in-dot-net.html/</link>
		<comments>http://www.three2tango.com/techcorner/database-access-in-dot-net.html/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 08:18:34 +0000</pubDate>
		<dc:creator>LG</dc:creator>
				<category><![CDATA[C# Codes]]></category>
		<category><![CDATA[Tech Corner]]></category>
		<category><![CDATA[c sharp]]></category>
		<category><![CDATA[database access]]></category>

		<guid isPermaLink="false">http://www.three2tango.com/?p=1230</guid>
		<description><![CDATA[&#8220;DBAccess&#8221; class(Download code)
                For making the sqlserver connection easier a user defined class “DBAccess.cs” is used in which all the database activities are done.The “GetTable( )” will help you execute a select query.This method returns a DataTable  “dt” .Now there is another method called &#8220;ExecuteQuery( )&#8220;, which also takes as input a string,this method is used to execute insert and update queries.Eventhough both methods can be used interchangably i prefer this way,because the &#8220;ExecuteQuery( )&#8221; returns an integer value which will give us ...]]></description>
			<content:encoded><![CDATA[<p><strong>&#8220;DBAccess&#8221;</strong> class(<a href="http://www.three2tango.com/ourfiles/dbaccess.zip">Download code</a>)<br />
                For making the sqlserver connection easier a user defined class <a href="http://www.three2tango.com/ourfiles/dbaccess.zip">“DBAccess.cs”</a> is used in which all the database activities are done.The “<strong>GetTable( )</strong>” will help you execute a select query.This method returns a DataTable  “<strong>dt</strong>” .Now there is another method called &#8220;<strong>ExecuteQuery( )</strong>&#8220;, which also takes as input a string,this method is used to execute insert and update queries.Eventhough both methods can be used interchangably i prefer this way,because the &#8220;ExecuteQuery( )&#8221; returns an integer value which will give us the idea of the number of rows affected.<br />
                 Now there is one private method &#8220;<strong>GetConnection( )</strong>&#8221; inside the class,this is used to check  the state of a connection,that is whether the created connection is open or close.This method returns the SqlConnection Object &#8220;<strong>Sqlcon</strong>&#8220;.Now inside the constructor of the class the connetcio nstring is created and this is how a connection between visual studio and Sql server is established.Server = dot implies the same machine acts as the server.Uid,pwd indicates the user id and password of the sqlserver simultaneously.And database gives the name of the database where our tables are created.In our example &#8220;test&#8221; is the database name.Now the namespaces imported varies according to situation.&#8221;<strong>System</strong>&#8221; is the root namespace.Namespace &#8220;<strong>Data</strong>&#8221; is used for getting structure of Datatable,dataset etc.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.three2tango.com/techcorner/database-access-in-dot-net.html/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting IP Address</title>
		<link>http://www.three2tango.com/techcorner/getting-ip-address.html/</link>
		<comments>http://www.three2tango.com/techcorner/getting-ip-address.html/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 10:34:33 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[C# Codes]]></category>
		<category><![CDATA[Tech Corner]]></category>
		<category><![CDATA[Find IP Address]]></category>

		<guid isPermaLink="false">http://www.three2tango.com/?p=63</guid>
		<description><![CDATA[Getting the Ip address of the local machine
using system.net;

string strHostName = string.Empty;

cmbIPAddress.Items.Clear();//combo box to hold the ip address

strHostName = Dns.GetHostName();//get name of the local machine

IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress[] iparrAddr = ipEntry.AddressList
if (iparrAddr.Length &#62; 0)
{
for (int intLoop = 0; intLoop &#60; iparrAddr.Length; intLoop++)
cmbIPAddress.Items.Add(iparrAddr[intLoop].ToString());
}
Getting the ip addresses of machines connected through LAN


First Get the names of the machines
using System.Net;
using System.Diagnostics;
using System.IO;

Process netUtility = new Process();

netUtility.StartInfo.FileName = "net.exe";
netUtility.StartInfo.CreateNoWindow = true;
netUtility.StartInfo.Arguments = "view";
netUtility.StartInfo.RedirectStandardOutput = true;
netUtility.StartInfo.UseShellExecute = false;
netUtility.StartInfo.RedirectStandardError = true;
netUtility.Start();

StreamReader streamReader = new StreamReader(netUtility.StandardOutput.BaseStream, netUtility.StandardOutput.CurrentEncoding);

string line = "";
while ((line = streamReader.ReadLine()) != null)
{
if (line.StartsWith("\\"))
{
cmbnetworkcomputers.Items.Add(line.Substring(2).Substring(0, line.Substring(2).IndexOf(" ...]]></description>
			<content:encoded><![CDATA[<p><strong><em>Getting the Ip address of the local machine</em></strong></p>
<pre name="code" class="c-sharp">using system.net;

string strHostName = string.Empty;

cmbIPAddress.Items.Clear();//<em>combo box to hold the ip address</em>

strHostName = Dns.GetHostName();<em>//get name of the local machine</em>

IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress[] iparrAddr = ipEntry.AddressList
if (iparrAddr.Length &gt; 0)
{
for (int intLoop = 0; intLoop &lt; iparrAddr.Length; intLoop++)
cmbIPAddress.Items.Add(iparrAddr[intLoop].ToString());
}</pre>
<p><em><strong>Getting the ip addresses of machines connected through LAN</strong><br />
</em><br />
<em><br />
First Get the names of the machines</em></p>
<pre name="code" class="c-sharp">using System.Net;
using System.Diagnostics;
using System.IO;

Process netUtility = new Process();

netUtility.StartInfo.FileName = "net.exe";
netUtility.StartInfo.CreateNoWindow = true;
netUtility.StartInfo.Arguments = "view";
netUtility.StartInfo.RedirectStandardOutput = true;
netUtility.StartInfo.UseShellExecute = false;
netUtility.StartInfo.RedirectStandardError = true;
netUtility.Start();

StreamReader streamReader = new StreamReader(netUtility.StandardOutput.BaseStream, netUtility.StandardOutput.CurrentEncoding);

string line = "";
while ((line = streamReader.ReadLine()) != null)
{
if (line.StartsWith("\\"))
{
cmbnetworkcomputers.Items.Add(line.Substring(2).Substring(0, line.Substring(2).IndexOf(" ")).ToUpper());//cmbnetworkcomputers is a combobox

}

}
streamReader.Close();
netUtility.WaitForExit(1000);
</pre>
<p><em>Now to get the ip addrresses,use these names</em></p>
<pre name="code" class="c-sharp">for (int i = 0; i &lt; cmbnetworkcomputers.Items.Count; i++)
{
string st;
st = cmbnetworkcomputers.Items[i].ToString();
IPHostEntry ipEntry = Dns.GetHostByName(st);
IPAddress[] iparrAddr = ipEntry.AddressList;
if (iparrAddr.Length &gt; 0)
{
for (int intLoop = 0; intLoop &lt; iparrAddr.Length; intLoop++)
cmbIPAddress.Items.Add(iparrAddr[intLoop].ToString());//combobox to hold Ip Address
}
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.three2tango.com/techcorner/getting-ip-address.html/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Interact with system processes</title>
		<link>http://www.three2tango.com/techcorner/csharpcodes/interact-with-system-processes.html/</link>
		<comments>http://www.three2tango.com/techcorner/csharpcodes/interact-with-system-processes.html/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 07:05:04 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[C# Codes]]></category>
		<category><![CDATA[Start & Kill Process]]></category>
		<category><![CDATA[System.Diagnostics]]></category>

		<guid isPermaLink="false">http://www.three2tango.com/?p=57</guid>
		<description><![CDATA[For Interacting with system Processes,like start or kill process,.Net provides us with the namespace System.Diagnostics.
System.Diagnostics namespace contains a class Process which provides the functionality to monitor processes connected across a network as well as the local machine
Running another exe file

System.Diagnostics.Process.Start("pathofexefile");
System.Diagnostics.Process.Start("notepad.exe");

Killing a currently running process

Process[] processes = Process.GetProcessesByName("googletalk");
foreach (Process p in processes)
{
Process.GetProcessById(p.Id).Kill();
}

]]></description>
			<content:encoded><![CDATA[<p>For Interacting with system Processes,like start or kill process,.Net provides us with the namespace System.Diagnostics.</p>
<p>System.Diagnostics namespace contains a class Process which provides the functionality to monitor processes connected across a network as well as the local machine</p>
<p><em>Running another exe file</em></p>
<pre name="code" class="c-sharp">
System.Diagnostics.Process.Start("pathofexefile");
System.Diagnostics.Process.Start("notepad.exe");
</pre>
<p><em>Killing a currently running process</em></p>
<pre name="code" class="c-sharp">
Process[] processes = Process.GetProcessesByName("googletalk");
foreach (Process p in processes)
{
Process.GetProcessById(p.Id).Kill();
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.three2tango.com/techcorner/csharpcodes/interact-with-system-processes.html/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

