<?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>TechTips &#187; Technical</title>
	<atom:link href="http://kshitijsharma.net/category/netaspnetvbnetcsql-server-mysql/feed/" rel="self" type="application/rss+xml" />
	<link>http://kshitijsharma.net</link>
	<description>.NET/ CSLA.NET / ASP.NET / VB.NET / C# / SQL Server / MySql ..</description>
	<lastBuildDate>Tue, 24 Aug 2010 15:37:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Showing Multiline string in a DataGridView Cell</title>
		<link>http://kshitijsharma.net/2010/08/23/showing-multiline-string-in-a-datagridview-cell/</link>
		<comments>http://kshitijsharma.net/2010/08/23/showing-multiline-string-in-a-datagridview-cell/#comments</comments>
		<pubDate>Mon, 23 Aug 2010 13:53:07 +0000</pubDate>
		<dc:creator>Kshitij Sharma</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://kshitijsharma.net/?p=158</guid>
		<description><![CDATA[Hi,

Recently I need to show multi-line string in a datagridview cell. To achieve that we need to write code in CellFormatting event of DataGridview. Following is the code]]></description>
			<content:encoded><![CDATA[<p>Hi,</p>
<p>Recently I need to show multi-line string in a datagridview cell. To achieve that we need to write code in CellFormatting event of DataGridview. Following is the code</p>
<pre class="brush: csharp;">
        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.Value.Equals(&quot;Error&quot;))
            {
                e.CellStyle.BackColor = Color.Red;
                e.CellStyle.ForeColor = Color.White;

            }
            else
            {
                if ((!e.Value.Equals(&quot;OK&quot;)) &amp;&amp; e.ColumnIndex==2)
                {
                    e.CellStyle.BackColor = Color.Green;
                    e.CellStyle.ForeColor = Color.White;
                    e.CellStyle.WrapMode = DataGridViewTriState.True;
                    dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                    dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

                }

            }
        }
</pre>
<p>I hope this help!</p>
<p>Kshitij</p>
<div class='wp_likes' id='wp_likes_post-158'><a class='like' href="javascript:wp_likes.like(158);" title='' ><img src="http://kshitijsharma.net/wp-content/plugins/wp-likes/images/like.png" alt='' border='0'/>Like</a><span class='text'></span>
<div class='unlike'><a href="javascript:wp_likes.unlike(158);">Unlike</a></div>
</div>
<div id="st0000000001" class="st-taf"><script src="http://taf.socialtwist.com:80/taf/js/shoppr.core.js?id=0000000001"></script><img style="border:0;margin:0;padding:0;" src="http://tellafriend.socialtwist.com:80/wizard/images/tafbutton_blue16.png" onmouseout="hideHoverMap(this)" onmouseover="showHoverMap(this, '0000000001', 'http%3A%2F%2Fkshitijsharma.net%2F2010%2F08%2F23%2Fshowing-multiline-string-in-a-datagridview-cell%2F', 'Showing+Multiline+string+in+a+DataGridView+Cell')" onclick="cw(this, {id:'0000000001',link: 'http%3A%2F%2Fkshitijsharma.net%2F2010%2F08%2F23%2Fshowing-multiline-string-in-a-datagridview-cell%2F', title: '+Showing+Multiline+string+in+a+DataGridView+Cell+' })"/></div>]]></content:encoded>
			<wfw:commentRss>http://kshitijsharma.net/2010/08/23/showing-multiline-string-in-a-datagridview-cell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Add text to the beginning of a file using C#</title>
		<link>http://kshitijsharma.net/2009/12/08/add-text-to-the-beginning-of-a-file-using-c/</link>
		<comments>http://kshitijsharma.net/2009/12/08/add-text-to-the-beginning-of-a-file-using-c/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 11:18:53 +0000</pubDate>
		<dc:creator>Kshitij Sharma</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://kshitijsharma.net/?p=136</guid>
		<description><![CDATA[Hi,

Few days back i needed a code snippet to write a text in starting of all files in a directory. Searched net but could not find any working code. Then i decide to write my own code and come up with following code. I hope ]]></description>
			<content:encoded><![CDATA[<p><!-- You will NOT be able to see the ad on your site! This unit is hidden on your page, and will only display to your search engine traffic (from US and CA). To preview, paste the code up on your site, then add #chitikatest=mortgage to the end of your URL in your browser's address bar.  Example:  www.yourwebsite.com#chitikatest=mortgage. This will show you what the ad would look like to a user who is interested in "mortgages." -->
<script type="text/javascript"><!--
ch_client = "kshitijsharma";
ch_type = "mpu";
ch_width = 500;
ch_height = 250;
ch_noborders=0;
ch_non_contextual = 4;
ch_vertical ="premium";
ch_sid = "Chitika Premium";
var ch_queries = new Array( );
var ch_selected=Math.floor((Math.random()*ch_queries.length));
if ( ch_selected < ch_queries.length ) {
ch_query = ch_queries[ch_selected];
}
//--></script>
<script  src="http://scripts.chitika.net/eminimalls/amm.js" type="text/javascript">
</script></p>
<p>Hi,</p>
<p>Few days back i needed a code snippet to write a text in starting of all files in a directory. Searched net but could not find any working code. Then i decide to write my own code and come up with following code.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-5111267738769255";
/* 468x15_LinkAd_Horizontal, created 6/17/09 */
google_ad_slot = "4303000503";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
I hope this will help guys who are looking to do same.</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace AddTextToFiles
{
    class Program
    {
        private static DirectoryInfo ds;
        static void Main(string[] args)
        {
            Console.WriteLine(&quot;*********************Written By Kshitij Sharma ***********************&quot;);
            Console.WriteLine(&quot;Please Enter the path and Press enter &quot;);
            string sPath = Console.ReadLine();
            Console.WriteLine(&quot;Please Enter &lt;B style=&quot;BACKGROUND-COLOR: #a0ffff; COLOR: black&quot;&gt;Text&lt;/B&gt; &quot;);
            string sText = Console.ReadLine();
            addText(sPath,sText);
            Console.WriteLine(&quot;*****************Reach Me @ k.sharma78@gmail.com****************&quot;);
            Console.Read();
        }

        private static void addText(string pth,string txt)
        {
            try
            {

                if (!string.IsNullOrEmpty(pth))
                {
                    ds = new DirectoryInfo(pth);
                }
                else
                {
                    ds = new DirectoryInfo(&quot;c:\\testfiles&quot;);
                }
                if (string.IsNullOrEmpty(txt))
                {
                    txt = &quot;&lt;!--#Include File=\&quot;CheckSQL.inc\&quot;--&gt;&quot;;
                }
                foreach (FileInfo f in ds.GetFiles(&quot;*.asp&quot;))
                {
                    Console.WriteLine(&quot;Writing to file--&gt;&quot; + f.Name);
                    string strPath = ds.Root + ds.Name + &quot;\\&quot; + f.Name;
                    StreamReader sr = new StreamReader(strPath);
                    string fileContent = sr.ReadToEnd();
                    sr.Close();
                    StreamWriter sw = new StreamWriter(strPath, false);
                    StringReader gr = new StringReader(fileContent);
                    sw.WriteLine(txt);
                    sw.WriteLine(gr.ReadToEnd());
                    sw.Close();
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Read();
            }
        }
    }
}
</pre>
</p>
<div class='wp_likes' id='wp_likes_post-136'><a class='like' href="javascript:wp_likes.like(136);" title='' ><img src="http://kshitijsharma.net/wp-content/plugins/wp-likes/images/like.png" alt='' border='0'/>Like</a><span class='text'></span>
<div class='unlike'><a href="javascript:wp_likes.unlike(136);">Unlike</a></div>
</div>
<div id="st0000000001" class="st-taf"><script src="http://taf.socialtwist.com:80/taf/js/shoppr.core.js?id=0000000001"></script><img style="border:0;margin:0;padding:0;" src="http://tellafriend.socialtwist.com:80/wizard/images/tafbutton_blue16.png" onmouseout="hideHoverMap(this)" onmouseover="showHoverMap(this, '0000000001', 'http%3A%2F%2Fkshitijsharma.net%2F2009%2F12%2F08%2Fadd-text-to-the-beginning-of-a-file-using-c%2F', 'Add+text+to+the+beginning+of+a+file+using+C%23')" onclick="cw(this, {id:'0000000001',link: 'http%3A%2F%2Fkshitijsharma.net%2F2009%2F12%2F08%2Fadd-text-to-the-beginning-of-a-file-using-c%2F', title: '+Add+text+to+the+beginning+of+a+file+using+C%23+' })"/></div>]]></content:encoded>
			<wfw:commentRss>http://kshitijsharma.net/2009/12/08/add-text-to-the-beginning-of-a-file-using-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Reflection</title>
		<link>http://kshitijsharma.net/2009/06/16/using-reflection/</link>
		<comments>http://kshitijsharma.net/2009/06/16/using-reflection/#comments</comments>
		<pubDate>Tue, 16 Jun 2009 07:44:09 +0000</pubDate>
		<dc:creator>Kshitij Sharma</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[VB.NET]]></category>

		<guid isPermaLink="false">http://kshitijsharma.net/?p=98</guid>
		<description><![CDATA[<strong>So what basically is reflection:</strong>

Using a class library methods at runtime without adding its reference in your project is done through Reflection.  In this article I will show you how to use reflection using a simple example.

Letâ€™s first create a Class Library.

<a href="http://kshitijsharma.net/wp-content/uploads/2009/06/ScreenHunter_01Jun.1312.06.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_01 Jun. 13 12.06" src="http://kshitijsharma.net/wp-content/uploads/2009/06/ScreenHunter_01Jun.1312.06_thumb.gif" border="0" alt="ScreenHunter_01 Jun. 13 12.06" width="400" height="325" /></a>
]]></description>
			<content:encoded><![CDATA[<p><!-- You will NOT be able to see the ad on your site! This unit is hidden on your page, and will only display to your search engine traffic (from US and CA). To preview, paste the code up on your site, then add #chitikatest=mortgage to the end of your URL in your browser's address bar.  Example:  www.yourwebsite.com#chitikatest=mortgage. This will show you what the ad would look like to a user who is interested in "mortgages." -->
<script type="text/javascript"><!--
ch_client = "kshitijsharma";
ch_type = "mpu";
ch_width = 500;
ch_height = 250;
ch_noborders=0;
ch_non_contextual = 4;
ch_vertical ="premium";
ch_sid = "Chitika Premium";
var ch_queries = new Array( );
var ch_selected=Math.floor((Math.random()*ch_queries.length));
if ( ch_selected < ch_queries.length ) {
ch_query = ch_queries[ch_selected];
}
//--></script>
<script  src="http://scripts.chitika.net/eminimalls/amm.js" type="text/javascript">
</script><br />
<strong>So what basically is reflection:</strong></p>
<p><div style="display:block; float:right; margin: 0 15px 0 0;"><script type="text/javascript"><!--
google_ad_client = "pub-5111267738769255";
/* 300x250_Medium_Rectangle, created 6/22/09 */
google_ad_slot = "9407728766";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><br />
Using a class library methods at runtime without adding its reference in your project is done through Reflection.Â  In this article I will show you how to use reflection using a simple example.<br />
Letâ€™s first create a Class Library.</p>
<p><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/ScreenHunter_01Jun.1312.06.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_01 Jun. 13 12.06" src="http://kshitijsharma.net/wp-content/uploads/2009/06/ScreenHunter_01Jun.1312.06_thumb.gif" border="0" alt="ScreenHunter_01 Jun. 13 12.06" width="400" height="325" /></a></p>
<p>letâ€™s code our ReflectionTest Class</p>
<pre class="brush: vb;">

Namespace reflectionclass
Public Class ClsReflection

#Region &quot;Methods&quot;
Public Function add(ByVal x As Integer, ByVal y As Integer) As Integer
Return x + y
End Function

Public Function [sub](ByVal x As Integer, ByVal y As Integer) As Integer
Return x - y
End Function
#End Region

End Class
End Namespace
</pre>
<p>letâ€™s make a test project now. Add a windows form application to the solution.</p>
<p><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/ScreenHunter_02Jun.1312.20.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_02 Jun. 13 12.20" src="http://kshitijsharma.net/wp-content/uploads/2009/06/ScreenHunter_02Jun.1312.20_thumb.gif" border="0" alt="ScreenHunter_02 Jun. 13 12.20" width="515" height="330" /></a><br />
<script type="text/javascript"><!--
google_ad_client = "pub-5111267738769255";
/* 468x60_Banner, created 6/9/09 */
google_ad_slot = "7151717024";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<br />
Now letâ€™s design our Form.</p>
<p><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/ScreenHunter_02Jun.1612.48.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_02 Jun. 16 12.48" src="http://kshitijsharma.net/wp-content/uploads/2009/06/ScreenHunter_02Jun.1612.48_thumb.gif" border="0" alt="ScreenHunter_02 Jun. 16 12.48" width="466" height="478" /></a><br />
<script type="text/javascript"><!--
google_ad_client = "pub-5111267738769255";
/* 468x15_LinkAd_Horizontal, created 6/17/09 */
google_ad_slot = "4303000503";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
so after putting two command buttons two listview controls and four textbox controls our form should look like this.</p>
<p>Letâ€™s code our form now</p>
<pre class="brush: vb;">
Imports System.Reflection

Public Class Form1
Dim objAssembly As Assembly
'Declare an array of Types to Hold All Classes of Assembly
Dim arrTypes As Type()
Dim objType As Type
'Delcare an array to hold all methods of Assembly
Dim arrMethods As MethodInfo()
Dim objMethod As MethodInfo

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
OpenFileDialog1.ShowDialog()
txtAssembly.Text = OpenFileDialog1.FileName
objAssembly = System.Reflection.Assembly.LoadFrom(txtAssembly.Text)
For Each cls In objAssembly.GetTypes
'
If cls.FullName.IndexOf(&quot;ClsReflection&quot;) &gt; 0 Then
lstClasses.Items.Add(cls.FullName)
End If
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub lstClasses_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstClasses.SelectedIndexChanged
Try
lstMethods.Items.Clear()
objType = objAssembly.GetType(Me.lstClasses.SelectedItem.ToString)
arrMethods = objType.GetMethods
For Each method In objType.GetMethods
lstMethods.Items.Add(method.Name)
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Private Sub cmdCallMethod_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCallMethod.Click
Try
objMethod = objType.GetMethod(lstMethods.SelectedItem.ToString())
Dim obj As Object
obj = Activator.CreateInstance(objType)
'Let's Create Array of Parameter
Dim objParameters As Object() = {Int32.Parse(txtNum1.Text), Int32.Parse(txtNum2.Text)}
'If there is no parameter in method then on the place of oo pass the null
txtResult.Text = objMethod.Invoke(obj, objParameters).ToString()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
</pre>
<p><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/ScreenHunter_03Jun.1613.09.gif"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="ScreenHunter_03 Jun. 16 13.09" src="http://kshitijsharma.net/wp-content/uploads/2009/06/ScreenHunter_03Jun.1613.09_thumb.gif" border="0" alt="ScreenHunter_03 Jun. 16 13.09" width="381" height="326" /></a></p>
<p>Select Add and put any two numbers in the first and second number textbox and click on execute method and you should get the result.</p>
<p><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/ScreenHunter_04Jun.1613.12.gif"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="ScreenHunter_04 Jun. 16 13.12" src="http://kshitijsharma.net/wp-content/uploads/2009/06/ScreenHunter_04Jun.1613.12_thumb.gif" border="0" alt="ScreenHunter_04 Jun. 16 13.12" width="437" height="367" /></a><br />
<script type="text/javascript"><!--
google_ad_client = "pub-5111267738769255";
/* 468x15_LinkAd_Horizontal, created 6/17/09 */
google_ad_slot = "4303000503";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
Now select Sub and enter any two number in first number and second number textbox and press execute method and you should get the desired result.</p>
<p><div style="display:block; float:left; margin: 0 15px 0 0;"><script type="text/javascript"><!--
google_ad_client = "pub-5111267738769255";
/* 300x250_Medium_Rectangle, created 6/22/09 */
google_ad_slot = "9407728766";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>This article show you how you can call method dynamically at runtime without referencing the assembly in your project. It is a very basic example but I think it will help you to understand how reflection works in .Net.</p>
<p>If you have any point you are not getting in this article please let me know i will try to explain.</p>
<p>Happy Coding!</p>
<p>Kshitij</p>
<div id="st0000000001" class="st-taf"><script src="http://taf.socialtwist.com:80/taf/js/shoppr.core.js?id=0000000001"></script><img style="border:0;margin:0;padding:0;" src="http://tellafriend.socialtwist.com:80/wizard/images/tafbutton_blue16.png" onmouseout="hideHoverMap(this)" onmouseover="showHoverMap(this, '0000000001', 'http%3A%2F%2Fkshitijsharma.net%2F2009%2F06%2F16%2Fusing-reflection%2F', 'Using+Reflection')" onclick="cw(this, {id:'0000000001',link: 'http%3A%2F%2Fkshitijsharma.net%2F2009%2F06%2F16%2Fusing-reflection%2F', title: '+Using+Reflection+' })"/></div>]]></content:encoded>
			<wfw:commentRss>http://kshitijsharma.net/2009/06/16/using-reflection/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Stored Procedures in MySQL</title>
		<link>http://kshitijsharma.net/2009/06/09/stored-procedures-in-mysql/</link>
		<comments>http://kshitijsharma.net/2009/06/09/stored-procedures-in-mysql/#comments</comments>
		<pubDate>Tue, 09 Jun 2009 08:31:18 +0000</pubDate>
		<dc:creator>Kshitij Sharma</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[store procedures]]></category>

		<guid isPermaLink="false">http://kshitijsharma.net/?p=69</guid>
		<description><![CDATA[<strong>So what exactly Stored Procedures are :</strong>
<ul>
	<li>Basically in a database management system (DBMS), a stored procedure is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database in compiled form so that it can be shared by a number of programs. The use of stored procedures can be helpful in controlling access to data (end-users may enter or change data but do not write procedures), preserving data integrity (information is entered in a consistent manner), and improving productivity (statements in a stored procedure only need to be written one time). Stored procedures have been part of Oracle, MS SQL Server, DB-2, postgreSQL and others for years but MySQL introduce Store procedures recently in version 5.xxx. MySQL stored procedures are very similar to the DB2 implementation, as both are based on the SQL:2003 standard.</li>
</ul>
]]></description>
			<content:encoded><![CDATA[<p><!--adsense#chitika_500x250_Mega_Unit--><br />
<strong><B>So what exactly Stored Procedures are :</B></strong></p>
<ul>
<li>Basically in a database management system (DBMS), a stored procedure is a set of Structured Query Language (SQL) statements with an assigned name that&#8217;s stored in the database in compiled form so that it can be shared by a number of programs. The use of stored procedures can be helpful in controlling access to data (end-users may enter or change data but do not write procedures), preserving data integrity (information is entered in a consistent manner), and improving productivity (statements in a stored procedure only need to be written one time). Stored procedures have been part of Oracle, MS SQL Server, DB-2, postgreSQL and others for years but MySQL introduce Store procedures recently in version 5.xxx. MySQL stored procedures are very similar to the DB2 implementation, as both are based on the SQL:2003 standard.</li>
</ul>
<p><span id="more-69"></span></p>
<p align="left"><strong>Why i need store procedure when i can write Queries on page/formsÂ  :</strong></p>
<ul>
<li>Consider a scenario in which you have a client/server application with centrally located database server and your application has a provision to create a voucher and you calculate tax on the amount of the voucher. What if you need to change tax rate. Either you have to change code in your form to recalculate the tax and then you need to reinstall your forms on each of the client machine or you have an option to create a procedure that calculate tax and call that procedure from your client application and thatâ€™s it. Because your application call the procedure to calculate tax you donâ€™t need to reinstall your BO (Business Objects) or client application to each of client machine. All you need to do is to change code in your procedure that calculate Tax.<!--adsense#Medium_Rectangle_left--></li>
<li>They can reduce network traffic. Complex, repetitive tasks may require getting results, applying some logic to them, and using this to get more results. If this only has to be done on the database server, there is no need to send result sets and new queries back and forth from application server to database server. Network traffic is a common bottleneck causing performance issues, and stored procedures can help reduce this. More often though, it is the database server itself that is the bottleneck, so this may not be much of an advantage.</li>
</ul>
<p><strong>Letâ€™s Start with a simple Example:</strong></p>
<p>As i described earlier a store procedure is a set of SQL Statement. Almost any valid SQL Statement can go inside a store procedure, with a few exceptions, which we will look later. I am using MySQL command line utility to write and execute procedures. You can also use MySQL Query Browser to create/modify/delete procedures. It comes with MySQL GUI Tools which are freely available on MySQL Site.</p>
<p><strong>use test; #Select Database<br />
CREATE PROCEDURE usp_test() SELECT &#8216;SP Test &#8216; as Title;<br />
</strong>This line will add a procedure called â€œusp_testâ€ in your selected database which in this case is Test. Note i use â€˜uspâ€™Â  (User store procedure) as a prefix to procedure just to distinct it with system procedures.<br />
Now letâ€™s call our newly created store procedure by using call keyword.<br />
<strong>Call usp_test();<br />
</strong>if you run this from MySQL command line utility you will get something like :</p>
<p><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-01jun081434.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_01 Jun. 08 14.34" src="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-01jun081434-thumb.gif" border="0" alt="ScreenHunter_01 Jun. 08 14.34" width="558" height="281" /></a><br />
<!--adsense#link_ad_horizontal--><br />
The procedure we just create is hardly useful, but the basics are there. <em>CREATE PROCEDURE sp_name()</em> will define the procedure, and <em>CALL sp_name()</em> will call the procedure.</p>
<p><strong>Letâ€™s move ahead : Parameters</strong></p>
<p>The real benefit of a stored procedure is when you can pass values to it, as well as retrieve information back. The concept of parameters should be familiar to anyone who has had experience with any procedural programming experience.</p>
<p>There are three types of parameter:</p>
<ul>
<li>IN: The default. This parameter is passed to the procedure, and can change inside the procedure, but remains unchanged outside.</li>
<li>OUT: No value is supplied to the procedure (it is assumed to be NULL), but it can be modified inside the procedure, and is available outside the procedure.</li>
<li>INOUT: The characteristics of both IN and OUT parameters. A value can be passed to the procedure, modified there as well as passed back again.<a href="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-02jun081730.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_02 Jun. 08 17.30" src="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-02jun081730-thumb.gif" border="0" alt="ScreenHunter_02 Jun. 08 17.30" width="547" height="338" /></a></li>
</ul>
<p><!--adsense#link_ad_horizontal--><br />
<strong>An IN Example:</strong></p>
<p>Here is an example of a stored procedure demonstrating the use of an <em>IN</em> parameter. Since <em>IN</em> is the default, there is no need to specify the parameter as such.</p>
<blockquote>
<pre>mysql&gt; CREATE PROCEDURE USP_IN(p VARCHAR(10)) SET @Name = P;
mysql&gt; CALL USP_IN(â€˜KSHITIJ SHARMAâ€™);
mysql&gt; SELECT @Name;
</pre>
<p>And you should get something like</p></blockquote>
<pre><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-01jun090823.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_01 Jun. 09 08.23" src="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-01jun090823-thumb.gif" border="0" alt="ScreenHunter_01 Jun. 09 08.23" width="592" height="334" /></a></pre>
<p><!--adsense--><br />
The session variable <em>@Name</em> is set inside of the procedure, based upon the parameter <em>P</em>, which is passed to the procedure, and remains unchanged.</p>
<p><strong>An Out Example:</strong></p>
<p><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-02jun090946.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_02 Jun. 09 09.46" src="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-02jun090946-thumb.gif" border="0" alt="ScreenHunter_02 Jun. 09 09.46" width="595" height="315" /></a></p>
<p>Here I reset <em>@Name</em> just to make sure the final result is not a legacy of the previous procedure. This time, the parameter <em>P</em> is changed inside of the procedure, while the session variable is passed to the procedure, ready to receive the result.</p>
<p><strong>An In-Out Example:</strong></p>
<pre><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-03jun091110.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_03 Jun. 09 11.10" src="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-03jun091110-thumb.gif" border="0" alt="ScreenHunter_03 Jun. 09 11.10" width="617" height="363" /></a></pre>
<p>Here, a parameter is passed to the procedure, used in the calculation, and the results are made available to the session variable <em>@Y.</em></p>
<p><strong>Getting Information from Database :</strong></p>
<blockquote>
<pre>mysql&gt; SHOW PROCEDURE STATUS;mysql&gt; SELECT * FROM INFORMATION_SCHEMA.ROUTINES;<strong></strong></pre>
</blockquote>
<p><strong>Letâ€™s do a bit more complex example :</strong></p>
<p>First, we will create a sample table.</p>
<blockquote>
<pre>mysql&gt; CREATE table tmptest(id INT, txt VARCHAR(10), PRIMARY KEY(id));
Query OK, 0 rows affected (0.11 sec)</pre>
</blockquote>
<p><strong>Delimiters, and multi-statement procedures</strong></p>
<p><!--adsense#Medium_Rectangle_right-->Stored procedures of course are not that useful if they are just one statement. The effects of all the procedures we have looked at so far could have had been duplicated much more easily with a single SQL statement. Useful procedures are much longer than that. Those of you who are on the ball may be thinking of a complication. How can we differentiate between multiple statements inside the procedure, and the end of the procedure? We have to create a different delimiter to end the CREATE PROCEDURE statement. Here is how:</p>
<blockquote>
<pre>mysql&gt; DELIMITER $$</pre>
</blockquote>
<p>Note that there is no semicolon after the &#8216;$$&#8217; symbol, which we will use as the delimiter for our purposes. You have to choose a delimiter that does not appear in your procedure, and it can be more than one character.</p>
<blockquote>
<pre>mysql&gt; CREATE PROCEDURE usp_ins (P VARCHAR(10))
    -&gt; BEGIN
    -&gt;  SET @x=CHAR_LENGTH(P);
    -&gt;  SET @y = HEX(P);
    -&gt;  INSERT INTO tmptest(id,txt) VALUES(@x,@y);
    -&gt; END$$
Query OK, 0 rows affected (0.05 sec)

mysql&gt; CALL usp_ins('ABC');
    -&gt; $$
Query OK, 1 row affected (0.00 sec)</pre>
</blockquote>
<blockquote>
<pre>mysql&gt; DELIMITER ;
mysql&gt; SELECT * FROM tmptest;
*************************** 1. row ***************************
 id: 3
txt: 414243
1 row in set (0.00 sec)</pre>
</blockquote>
<p><!--adsense#link_ad_horizontal--><br />
Note what happened when we tried to call the procedure. Because MySQL was still using the $$ symbol as a delimiter, and not the semicolon, the statement did not run after the semicolon. We first needed to close it with the piping symbol. Afterwards, we reset the delimiter back to normal, and test that the records were correctly added to the <em>tmptest</em> table.</p>
<p><strong>Procedure Variables:</strong></p>
<p>You can DECLARE variables that exist only inside the procedure, as well as assign values to them with the SET statement without using the &#8216;@&#8217; symbol, required for session variables. Here is how:</p>
<blockquote>
<pre>mysql&gt; DELIMITER $$

mysql&gt; CREATE PROCEDURE usp_variables (P INT)

-&gt; BEGIN</span><span style="font-family: Courier New;">-&gt;Â  DECLARE a INT;
-&gt;Â  DECLARE b INT DEFAULT 10;
-&gt;Â  SET a = P*b;</span><span style="font-family: Courier New;">-&gt;Â  INSERT INTO tmptest(id,txt) VALUES(a,HEX('DEF'));
-&gt; END$$ </span>

<span style="font-family: Courier New;">Query OK, 0 rows affected (0.00 sec) </span>

mysql&gt; DELIMITER ;
mysql&gt; CALL usp_variables(4);
Query OK, 1 row affected (0.00 sec) </span>
mysql&gt; SELECT * FROM tmptest;
*************************** 1. row ***************************
 id: 3
txt: 414243
*************************** 2. row ***************************
 id: 40
txt: 444546
2 rows in set (0.00 sec)</pre>
</blockquote>
<p>if you declare a variable without default (such as a ) it will be set to NULL.</p>
<p><strong>Populating Variables from table.</strong></p>
<blockquote>
<pre>mysql&gt; DELIMITER $$
mysql&gt; CREATE PROCEDURE usp_selectINvariable ()
    -&gt; BEGIN
    -&gt;  DECLARE a INT;
    -&gt;  DECLARE b VARCHAR(10);
    -&gt;  SELECT id,txt INTO a,b FROM tmptest LIMIT 1;
    -&gt;  SELECT a,b;
    -&gt; END|
Query OK, 0 rows affected (0.00 sec)

mysql&gt; DELIMITER ;
mysql&gt; CALL usp_selectINvariable();
*************************** 1. row ***************************
a: 3
b: 414243
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)</pre>
</blockquote>
<p>see how i limit the result to singleÂ  (LIMIT 1)Â  record. In next post i will show you how to iterate multiple records.</p>
<p>I hope you can now write your own store procedure in MySQL.Â  In next post of this series i will show you more complex topics, to show some of the real power of store procedures.</p>
<p><strong>Kshitij</strong></p>
<input id="gwProxy" type="hidden" />
<p><!--Session data--></p>
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" /><!--Session data--><br />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<div id="st0000000001" class="st-taf"><script src="http://taf.socialtwist.com:80/taf/js/shoppr.core.js?id=0000000001"></script><img style="border:0;margin:0;padding:0;" src="http://tellafriend.socialtwist.com:80/wizard/images/tafbutton_blue16.png" onmouseout="hideHoverMap(this)" onmouseover="showHoverMap(this, '0000000001', 'http%3A%2F%2Fkshitijsharma.net%2F2009%2F06%2F09%2Fstored-procedures-in-mysql%2F', 'Stored+Procedures+in+MySQL')" onclick="cw(this, {id:'0000000001',link: 'http%3A%2F%2Fkshitijsharma.net%2F2009%2F06%2F09%2Fstored-procedures-in-mysql%2F', title: '+Stored+Procedures+in+MySQL+' })"/></div>]]></content:encoded>
			<wfw:commentRss>http://kshitijsharma.net/2009/06/09/stored-procedures-in-mysql/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Creating a Pingback (Windows) service with VB.NET</title>
		<link>http://kshitijsharma.net/2009/06/05/creating-a-pingback-windows-service-with-vbnet/</link>
		<comments>http://kshitijsharma.net/2009/06/05/creating-a-pingback-windows-service-with-vbnet/#comments</comments>
		<pubDate>Fri, 05 Jun 2009 17:47:00 +0000</pubDate>
		<dc:creator>Kshitij Sharma</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[VB.NET]]></category>

		<guid isPermaLink="false">http://kshitijsharma.net/?p=41</guid>
		<description><![CDATA[Recently i faced lots of problem with my hosting company as almost daily my site was down due to some problems in their servers. They usually send me a link to trace my site. Basically that site provide service to ping back any URL from their servers which are located in different countries. So it [...]]]></description>
			<content:encoded><![CDATA[<p>Recently i faced lots of problem with my hosting company as almost daily my site was down due to some problems in their servers. They usually send me a link to trace my site. Basically that site provide service to ping back any URL from their servers which are located in different countries. So it is like first their US server pings the URL and sends back the results weather site is responding or not and then all of the servers located in different part of the word do the same thing and finally giving a summery. For me it was annoying to go again and again to that site and then type URL to trace it back. Furthermore they charge for their services if you wants to check your site (or any other URL) 24&#215;7. So i decided to write my own service. In this service i write the ping back results to windows log but you can always enhance this code to send mails or even SMS if your site is down.<br />
<!--adsense--><br />
So lets start and create a Windows Web Service Project</p>
<p><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/new-prj-winservice.gif"><img style="border-bottom: 0px; border-left: 0px; display: inline; margin-left: 0px; border-top: 0px; margin-right: 0px; border-right: 0px" title="New_prj_WinService" src="http://kshitijsharma.net/wp-content/uploads/2009/06/new-prj-winservice-thumb.gif" border="0" alt="New_prj_WinService" width="571" height="340" /></a><br />
<span id="more-41"></span><br />
Now rename your service1.vb file to PingBackSvr.vb and add another class code file to your project and name it PingBack.vb. After doing this your solution explorer should look like</p>
<p><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/prjview.gif"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="prjview" src="http://kshitijsharma.net/wp-content/uploads/2009/06/prjview-thumb.gif" border="0" alt="prjview" width="325" height="297" /></a></p>
<p>Now lets start code PingBack.vb</p>
<pre class="brush: vb;">
'Namespace References
Imports System
Imports System.Runtime.InteropServices
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Net.Sockets

Public Class PingBack

&lt;DllImport(&quot;wininet&quot;, CharSet:=CharSet.Auto)&gt; _
Private Shared Function InternetGetConnectedState(ByRef flags As ConnectionStatusEnum, ByVal dw As Integer) As Boolean
End Function

''' &lt;summary&gt;
''' enum to hold the possible connection states
''' &lt;/summary&gt;
&lt;Flags()&gt; _
Private Enum ConnectionStatusEnum As Integer
INTERNET_CONNECTION_MODEM = &amp;H1
INTERNET_CONNECTION_LAN = &amp;H2
INTERNET_CONNECTION_PROXY = &amp;H4
INTERNET_RAS_INSTALLED = &amp;H10
INTERNET_CONNECTION_OFFLINE = &amp;H20
INTERNET_CONNECTION_CONFIGURED = &amp;H40
End Enum

''' &lt;summary&gt;
''' method to check the status of the pinging machines internet connection
''' &lt;/summary&gt;
''' &lt;returns&gt;&lt;/returns&gt;
Private Function HasConnection() As Boolean
'instance of out ConnectionStatusEnum
Dim state As ConnectionStatusEnum = 0

'call the API
InternetGetConnectedState(state, 0)

'check the status, if not offline and the returned state
'isnt 0 then we have a connection
If (CInt(ConnectionStatusEnum.INTERNET_CONNECTION_OFFLINE) And CInt(state)) &lt;&gt; 0 Then
'return true, we have a connection
Return False
End If
'return false, no connection available
Return True
End Function

''' &lt;summary&gt;
''' method for retrieving the IP address from the host provided
''' &lt;/summary&gt;
''' &lt;param name=&quot;host&quot;&gt;the host we need the address for&lt;/param&gt;
''' &lt;returns&gt;&lt;/returns&gt;
Private Function GetIpFromHost(ByRef host As String) As IPAddress
Dim returnMessage As String = String.Empty
'IPAddress instance for holding the returned host
Dim address As IPAddress = Nothing

'wrap the attempt in a try..catch to capture
'any exceptions that may occur
Try
'get the host IP from the name provided
address = Dns.GetHostEntry(host).AddressList(0)
Catch ex As SocketException
'some DNS error happened, return the message
returnMessage = String.Format(&quot;DNS Error: {0}&quot;, ex.Message)
End Try
Return address
End Function

''' &lt;summary&gt;
''' method to check the ping status of a provided host
''' &lt;/summary&gt;
''' &lt;param name=&quot;host&quot;&gt;the host we need to ping&lt;/param&gt;
''' &lt;returns&gt;&lt;/returns&gt;
Protected Friend Function CheckSiteStatus(ByVal host As String) As String
'string to hold our return messge
Dim returnMessage As String = String.Empty

'IPAddress instance for holding the returned host
Dim address As IPAddress = GetIpFromHost(host)

'set the ping options, TTL 128
Dim options As New PingOptions(128, True)

'create a new ping instance
Dim ping As New Ping()

'32 byte buffer
Dim data As Byte() = New Byte(31) {}

'first make sure we actually have an internet connection
If HasConnection() Then
'here we will ping the host 4 times (standard)
For i As Integer = 0 To 3
Try
'send the ping 4 times to the host and record the returned data
Dim reply As PingReply = ping.Send(address, 1000, data, options)

'make sure we dont have a null reply
If Not (reply Is Nothing) Then
Select Case reply.Status
Case IPStatus.Success
returnMessage = String.Format(&quot;Reply from {0}: bytes={1} time={2}ms TTL={3}&quot;, reply.Address, reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl)
Exit Select
Case IPStatus.TimedOut
returnMessage = &quot;Connection has timed out...&quot;
Exit Select
Case Else
returnMessage = String.Format(&quot;Ping failed: {0}&quot;, reply.Status.ToString())
Exit Select
End Select
Else
returnMessage = &quot;Connection failed for an unknown reason...&quot;
End If
Catch ex As PingException
returnMessage = String.Format(&quot;Connection Error: {0}&quot;, ex.Message)
Catch ex As SocketException
returnMessage = String.Format(&quot;Connection Error: {0}&quot;, ex.Message)
End Try
Next
Else
returnMessage = &quot;No Internet connection found...&quot;
End If

'return the message
Return returnMessage
End Function
End Class
</pre>
<p>Now letâ€™s code our Service class which in this case is PinbBackSvr.vb.</p>
<pre class="brush: vb;">
Public Class PingBackSvr
Private _objPingback As PingBack
Private _status As String
Private WithEvents timer1 As New System.Timers.Timer
Private PingLog As New EventLog
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
'Uncomment this line to Debug this service
Debugger.Launch()
timer1.Enabled = True
timer1.Interval = 6000
' Me.TracePing()
End Sub

Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
Me.Timer1.Enabled = False
End Sub

Private Sub OnTimerElapsed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timer1.Elapsed
Me.TracePing()
End Sub

Private Sub TracePing()
Try
If Not Diagnostics.EventLog.SourceExists(&quot;PingBackSvr&quot;) Then
Diagnostics.EventLog.CreateEventSource(&quot;PingBackSvr&quot;, &quot;KshitijSharma.Net Ping Service Log&quot;)
End If
PingLog.Source = &quot;PingBackSvr&quot;
Me._objPingback = New PingBack
Me._status = Me._objPingback.CheckSiteStatus(&quot;www.kshitijsharma.net&quot;)
If InStr(Me._status, &quot;failed&quot;) &gt; 0 OrElse InStr(Me._status, &quot;Error&quot;) &gt; 0 OrElse InStr(Me._status, &quot;timed out&quot;) &gt; 0 Then
PingLog.WriteEntry(Me._status, EventLogEntryType.FailureAudit)
Else
PingLog.WriteEntry(Me._status, EventLogEntryType.SuccessAudit)
End If
Catch ex As Exception
PingLog.WriteEntry(ex.Message, EventLogEntryType.Error)
Finally
Me._objPingback = Nothing
PingLog = Nothing
End Try
End Sub
End Class
</pre>
<p><!--adsense--><br />
Now add a &#8216;Service Installer by right clicking design view of service.</p>
<p><img class="alignnone size-full wp-image-43" title="screenhunter_06-jun-06-1656" src="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter_06-jun-06-1656.gif" alt="screenhunter_06-jun-06-1656" width="161" height="152" /></p>
<p>Now Build your project</p>
<p>After building this service we need to install it on server.Â  we can do this with installUtil.exe utility. you can use</p>
<p><span style="color: #ff0000;">To Install</span><br />
&lt;pathofInstallUtil&gt;\installUtil.exe /i &lt;pathtoyourexe&gt;</p>
<p>To Uninstall<br />
&lt;pathofInstallUtil&gt;\installUtil.exe /u &lt;pathtoyourexe&gt;</p>
<p><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-04jun061643.gif"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="ScreenHunter_04 Jun. 06 16.43" src="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-04jun061643-thumb.gif" border="0" alt="ScreenHunter_04 Jun. 06 16.43" width="513" height="326" /></a></p>
<p>Please let me know if you need help any part of this code!<br />
Enjoy Coding!<br />
<strong>Kshitij</strong></p>
<input id="gwProxy" type="hidden" />
<p><!--Session data--></p>
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<p><!--Session data--></p>
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<p><!--Session data--></p>
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
<p><!--Session data--><br />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden"><!--Session data--></input>
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<div class='wp_likes' id='wp_likes_post-41'><a class='like' href="javascript:wp_likes.like(41);" title='' ><img src="http://kshitijsharma.net/wp-content/plugins/wp-likes/images/like.png" alt='' border='0'/>Like</a><span class='text'></span>
<div class='unlike'><a href="javascript:wp_likes.unlike(41);">Unlike</a></div>
</div>
<div id="st0000000001" class="st-taf"><script src="http://taf.socialtwist.com:80/taf/js/shoppr.core.js?id=0000000001"></script><img style="border:0;margin:0;padding:0;" src="http://tellafriend.socialtwist.com:80/wizard/images/tafbutton_blue16.png" onmouseout="hideHoverMap(this)" onmouseover="showHoverMap(this, '0000000001', 'http%3A%2F%2Fkshitijsharma.net%2F2009%2F06%2F05%2Fcreating-a-pingback-windows-service-with-vbnet%2F', 'Creating+a+Pingback+%28Windows%29+service+with+VB.NET')" onclick="cw(this, {id:'0000000001',link: 'http%3A%2F%2Fkshitijsharma.net%2F2009%2F06%2F05%2Fcreating-a-pingback-windows-service-with-vbnet%2F', title: '+Creating+a+Pingback+%28Windows%29+service+with+VB.NET+' })"/></div>]]></content:encoded>
			<wfw:commentRss>http://kshitijsharma.net/2009/06/05/creating-a-pingback-windows-service-with-vbnet/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Dynamically create controls at runtime</title>
		<link>http://kshitijsharma.net/2009/05/28/dynamically-create-controls-at-runtime/</link>
		<comments>http://kshitijsharma.net/2009/05/28/dynamically-create-controls-at-runtime/#comments</comments>
		<pubDate>Fri, 29 May 2009 04:56:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://kshitijsharma.net/?p=3</guid>
		<description><![CDATA[<table border="0">
<tbody>
<tr>
<td>Hi,
I was searching an article about creating controls at runtime based on a master table. But I couldnâ€™t find one. So I decided to write my own code and here is the result. I hope this post will help other guys who are looking to do same thing.So let's first create a master table which will store details about fields need to appear on our page.
Let's call this table tblFieldMaster.</td>
</tr>
<tr>
<td><img class="alignleft size-medium wp-image-13" title="tblFieldMaster" src="http://kshitijsharma.net/wp-content/uploads/2009/05/tabledesign-300x121.gif" alt="tblFieldMaster" width="300" height="121" /></td>
</tr>
<tr>
<td>Now Insert some data in it.</td>
</tr>
<tr>
<td><img class="alignleft size-full wp-image-12" title="screenhunter_02-may-30-1017" src="http://kshitijsharma.net/wp-content/uploads/2009/05/screenhunter_02-may-30-1017.gif" alt="screenhunter_02-may-30-1017" width="400" height="129" /></td>
</tr>
<tr>
<td>Now add a new webForm to your website project ( i assume you know how to create a website project with visual studio 2005 or 2008). Let's Name it createControl.aspx.
Add following code to newly added webform between tag.</td>
</tr></table>]]></description>
			<content:encoded><![CDATA[<p><!--adsense#chitika_500x250_Mega_Unit--></p>
<table border="0">
<tbody>
<tr>
<td>Hi,<br />
I was searching an article about creating controls at runtime based on a master table. But I couldnâ€™t find one. So I decided to write my own code and here is the result. I hope this post will help other guys who are looking to do same thing.So let&#8217;s first create a master table which will store details about fields need to appear on our page.<br />
Let&#8217;s call this table tblFieldMaster.</td>
</tr>
<tr>
<td><img class="alignleft size-medium wp-image-13" title="tblFieldMaster" src="http://kshitijsharma.net/wp-content/uploads/2009/05/tabledesign-300x121.gif" alt="tblFieldMaster" width="300" height="121" /></td>
</tr>
<tr>
<td>Now Insert some data in it.</td>
</tr>
<tr>
<td><img class="alignleft size-full wp-image-12" title="screenhunter_02-may-30-1017" src="http://kshitijsharma.net/wp-content/uploads/2009/05/screenhunter_02-may-30-1017.gif" alt="screenhunter_02-may-30-1017" width="400" height="129" /></td>
</tr>
<tr>
<td>Now add a new webForm to your website project ( i assume you know how to create a website project with visual studio 2005 or 2008). Let&#8217;s Name it createControl.aspx.<br />
Add following code to newly added webform between tag.</td>
</tr>
<tr>
<td><!--Session data--></p>
<pre class="brush: xml;">
&lt;body&gt;
&lt;form id=&quot;frmMain&quot; runat=&quot;server&quot;&gt;
&lt;div&gt;
&lt;asp:ScriptManager ID=&quot;ScriptManager1&quot; runat=&quot;server&quot;&gt;
&lt;/asp:ScriptManager&gt;
&lt;table width=&quot;550px&quot; cellspacing=&quot;1&quot; cellpadding=&quot;1&quot; class=&quot;outerBG&quot; align=&quot;center&quot;&gt;
&lt;tr&gt;
&lt;td align=&quot;center&quot;&gt;
&lt;asp:UpdatePanel ID=&quot;UpdatePanel1&quot; runat=&quot;server&quot;&gt;
&lt;ContentTemplate&gt;
&lt;asp:Panel ID=&quot;Panel1&quot; runat=&quot;server&quot; CssClass=&quot;innerTabBg&quot;&gt;
&lt;/asp:Panel&gt;
&lt;/ContentTemplate&gt;
&lt;/asp:UpdatePanel&gt;
&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/body&gt;
</pre>
<p>As you review this code i have added a scriptmanager so this form supports AJAX feature. Then i added an updatepanel and a Normal Panel inside this update panel. I will now add code to my code behind file which in this case will be createcontrol.vb.</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>
<pre class="brush: vb;">
Imports System.Data
Imports System.Data.OleDb

Partial Class createControl
Inherits System.Web.UI.Page
Private WithEvents cmdBtn As System.Web.UI.WebControls.Button
Private req As Web.UI.WebControls.RequiredFieldValidator
Private tbl As System.Web.UI.WebControls.Table
Private styl As System.Web.UI.WebControls.TableStyle
Private tr As System.Web.UI.WebControls.TableRow
Private td As System.Web.UI.WebControls.TableCell
Private txt As System.Web.UI.WebControls.TextBox
Private lbl As System.Web.UI.WebControls.Label
Private conn As OleDbConnection
Private da As OleDbDataAdapter
Private cmd As New OleDbCommand
Private ds As DataSet
Private dbPath As String = Server.MapPath('App_Data/regdb.mdb')
Private connString As String = 'Provider=Microsoft.Jet.OLEDB.4.0; Data source=' &amp; dbPath &amp; ';'
Private strSQL As String

Private Sub RenderForm()
conn = New OleDbConnection(connString)
conn.Open()
strSQL = 'Select * from tbl_IVS_Noida'
cmd.Connection = conn
cmd.CommandText = strSQL
cmd.CommandType = CommandType.Text
Dim dr As OleDb.OleDbDataReader = cmd.ExecuteReader
tbl = New Table
tbl.ID = 'tblForm'
tbl.Width = 550
'tbl.CssClass = '
Me.Panel1.Controls.Add(tbl)
While (dr.Read)
Select Case dr('Field_Type')
Case 'Character', 'Number'
tr = New TableRow
tbl.Controls.Add(tr)
td = New TableCell
td.Width = 230
lbl = New Label
lbl.Text = dr('Field_Label')
td.Controls.Add(lbl)
tr.Controls.Add(td)
td = New TableCell
td.Width = 320
txt = New TextBox
txt.ID = dr('Field_Name')
td.Controls.Add(txt)
If dr('Required') Then
req = New RequiredFieldValidator
req.ControlToValidate = txt.ID
req.ErrorMessage = txt.ID &amp; ' Is Required'
td.Controls.Add(req)
End If
tr.Controls.Add(td)
Case 'Date'

End Select
End While
'Now create Save Button
tr = New TableRow
td = New TableCell
td.ColumnSpan = 2
tr.Controls.Add(td)
cmdBtn = New Button
cmdBtn.ID = 'btnSave'
cmdBtn.Text = 'Save!'
td.Controls.Add(cmdBtn)
tbl.Controls.Add(tr)
End Sub

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
RenderForm()

End Sub

Private Sub btn_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdBtn.Click

End Sub
End Class
</pre>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>I think the code is quite self explanatory. Please ask away if you don&#8217;t get any point of this code.I hope this will help others who are looking to do same.</td>
</tr>
<tr>
<td>
<input id="gwProxy" type="hidden" />
<p><!--Session data--></p>
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" />
</td>
</tr>
</tbody>
</table>
<div id="st0000000001" class="st-taf"><script src="http://taf.socialtwist.com:80/taf/js/shoppr.core.js?id=0000000001"></script><img style="border:0;margin:0;padding:0;" src="http://tellafriend.socialtwist.com:80/wizard/images/tafbutton_blue16.png" onmouseout="hideHoverMap(this)" onmouseover="showHoverMap(this, '0000000001', 'http%3A%2F%2Fkshitijsharma.net%2F2009%2F05%2F28%2Fdynamically-create-controls-at-runtime%2F', 'Dynamically+create+controls+at+runtime')" onclick="cw(this, {id:'0000000001',link: 'http%3A%2F%2Fkshitijsharma.net%2F2009%2F05%2F28%2Fdynamically-create-controls-at-runtime%2F', title: '+Dynamically+create+controls+at+runtime+' })"/></div>]]></content:encoded>
			<wfw:commentRss>http://kshitijsharma.net/2009/05/28/dynamically-create-controls-at-runtime/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
