Thursday, April 30, 2009

How To Get IP Address Of A Machine

In this post we will try to explore the Dns class which is under System.net namespace and which provides simple domain name resolution functionality. The DNS class in the System.Net namespace can be used to get the hostname of a machine or get the IP address if the hostname is already known. The DNS class provides a simple domain name resolution functionality. The DNS class is a static class that provides access to information from the Internet Domain Name System (DNS). The information returned includes multiple IP addresses and aliases if the host specified has more than one entry in the DNS database. The list is returned as a collection or an array of IPAddress objects. The following section is the code that shows how to obtain the IP address for a given host name.
The function which is used to get the host name is the GetHostName of Dns class. In the code below I have a function named DisplayHostName which is used to get the host name by calling the Dns.GetHostName function. As Dns class is a static class so you can call the function in the Dns class without creating an object of Dns class.

public void DispalyHostName()
{
try {
// Get the local computer host name.
string strHostName = Dns.GetHostName();
Console.WriteLine("Computer name :" + strHostName);
}
catch(SocketException e) {
Console.WriteLine("SocketException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
}

When calling the GetHostName function of Dns class the exception may occurred which is SocketException , when mean that error is encountered when resolving the local host name. For the code above I have remove the static key word from the DispalyHostName function, as I have to call that function in static function which is Main in console application. So here i have remove static key word.
Here is the code you can use to get the IP Address of a machine. The Dns has two overloaded function for the GetHostEntry one which takes the host name as string parameter and second one which take IP address as parameter.

public void GetIPAddess()
{
IPHostEntry IPHostEntryList;
IPHostEntryList = Dns.GetHostEntry(Dns.GetHostName() );
Console.WriteLine("GetHostEntry({0}) returns:", Dns.GetHostName() );

foreach (IPAddress currentIPAddress in IPHostEntryList.AddressList)
Console.WriteLine("IP Address: {0}", currentIPAddress);
}

The GetHostEntry method queries a DNS server for the IP address that is associated with a host name or IP address.When an empty string is passed as the host name, this method returns the IPv4 addresses of the local host.
If the host name could not be found, the SocketException exception is returned with a value of 11001 (Windows Sockets error WSAHOST_NOT_FOUND). This exception can be returned if the DNS server does not respond. This exception can also be returned if the name is not an official host name or alias, or it cannot be found in the database(s) being queried.
The ArgumentException exception is also returned if the hostNameOrAddress parameter contains Any or IPv6Any.
The GetHostEntry method assumes that if an IP literal string is passed in the hostNameOrAddress parameter that the application wants an IPHostEntry instance returned with all of the properties set. These properties include the AddressList, Aliases, and HostName. As a result, the implementation of the GetHostEntry method exhibits the following behavior when an IP string literal is passed:
  1. The method tries to parse the address. If the hostNameOrAddress parameter contains a legal IP string literal, then the first phase succeeds.
  2. A reverse lookup using the IP address of the IP string literal is attempted to obtain the host name. This result is set as the HostName property.
  3. The host name from this reverse lookup is used again to obtain all the possible IP addresses associated with the name and set as the AddressList property.
For an IPv4 string literal, all three steps above may succeed. But it is possible for a stale DNS record for an IPv4 address that actually belongs to a different host to be returned. This may cause step #3 to fail and throw an exception (there is a DNS PTR record for the IPv4 address, but no DNS A record for the IPv4 address).For IPv6, step #2 above may fail, since most IPv6 deployments do not register the reverse (PTR) record for an IPv6 address. So this method may return the string IPv6 literal as the fully-qualified domain (FQDN) host name in the HostName property.
The GetHostAddresses method has different behavior with respect to IP literals. If step #1 above succeeds (it successfully parses as an IP address), that address is immediately returned as the result. There is no attempt at a reverse lookup. (Source) .You can download the source code from here

All and any comments / bugs / suggestions are welcomed!


Sunday, April 26, 2009

Calling __dopostback function for Asp.net controls which Don't have AutoPostBack property

While working on the last two post which include the __dopostback function of the JavaScript and Jquery alert Dialog I realize that the button control of the asp.net didn't have the autopostback property which other asp.net control has. Other controls of the asp.net such as check box, DropDownList etc has autopostback property.The autopostback property is Boolean which which is set as false by default. So in case of controls which has the autopostback property and which is set to true by the developer, the asp.net will generate the __dopostback JavaScript function and also two hidden fields which are __EVENTTARGET and __EVENTARGUMENT. But in case of the asp.net button control as it does not have the autopostback property so __dopostback function and two hidden field are not generated.
Here is the code you have to write if your control on the page don't have the autopostback property to true.
In order to __dopostback function to call manually you have to set the autopostback property of the control to true. But if the auto autopostback property is not set to true then __dopostback function will not generated by asp.net. In case of Button control which don't have the autopostback property and you don't have other control on the page which has the autopostback property and is not set to true , you have to add the __dopostback function and also the hidden fields for your own in order to call the __dopostback function manually. Here is the simple HTML code with JavaScript in it, which is used to call the __dopostback function manually. Here in the code I have added the two hidden fields called __EVENTTARGET and __EVENTARGUMENT, which are used to store the event target name , ID of the control which cause the postback and the event argument , argument which you want to pass for the postback.

< html>
< body>
< form name="myForm" method="post" action="test.aspx" id="myForm">
<input type="hidden" name="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" value="" />
< input type="hidden" name="__VIEWSTATE" value="dDwtMTAwOTA0ODU1NTs7PsllCK1DzvZsK0J6OQ2dxKqmEwVs" / >
< script language="javascript">
function __doPostBack(eventTarget, eventArgument) {
var theform = document.myForm;
theform.__EVENTTARGET.value = eventTarget;
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
< /script>
< /form>
< /body>
< /html>

After the insertion of the the hidden field you must define the __dopostback function in your JavaScript section of your page. In the above code we have a __dopostback function which take the event target and event argument as parameters. In the first statement I have get the form by using the statement document.myForm, where myForm is the id of the my form which is included in my asp.net page. In the next statements I have assign event target and event argument the values which are passed to the function as parameter and at the I have called the submit function of the myForm object. Which will cause the postback to the form.
Here is the code behind statement which will attach onclick attribute to the button control. In this case cmdPostBack is the name of the button.

cmdPostBack.Attributes.Add("onclick", "CallPostBack(); return false;");

In the above code i have write return false statement in the onclick attribute of the button control, As I don't want to post back when user click the button, the page will be post back only when user click OK in the confirm dialog of the JavaScript , which is written in the CallPostBack JavaScript function. Here is the CallPostBack function definition.

function CallPostBack()
{
var returnValue= confirm('Are you sure you want to postback ?');
if(returnValue)
__doPostBack('cmdPostBack','');
}

In the above code I have passed the ID of the my Button control which is cmdPostBack which will then execute the event handler in the code behind file.
From this article hope you get understanding of how you can manually write code for the __dopostabck function. You can download the source code from here

All and any comments / bugs / suggestions are welcomed!


Saturday, April 25, 2009

jQuery Alert Dialogs And Asp.net Application

In my last post where i have give you the link and some introduction of how you can use the new Jquery plug-in which are used for the alert, confirm and the prompt dialogs.The source code of the for the plug-in which is taken from the link, which contain the detail and the example code, was in the simple HTML page. The good thing about that source code was that it contain the CSS file for the format of the dialogs, So first i was interested in changing the GUI of the dialog and then use them in my web applications. Here is the image of the default Prompt dialog which contain the textbox , and button controls.


And Below is the Prompt dialog of my web application which I have achieve by changing the Css file which is given in the Source code of the plug-in.What i did is change the back color of the container and inserted few style properties of the input field of the prompt dialog and Added two Css class for the OK and CANCEL buttons. And you can see from the image below that new prompt dialog GUI is similar to GUI of my web application. One more point is that I have change the font family to the "Segoe UI" which is one of my favorite font family and i have used that font family in my Visual Studio environment as well. It is really easy to change the GUI of the dialog as all the GUI is control from the Css file.

Now come to the working of the dialogs in the asp.net web application. For this example code I have three asp.net buttons controls and two text box control. I have named and set the text of each button according to the functionality they will perform. Show Prompt will show prompt dialog, show confirmation will show confirm dialog and show Alert will show alert dialog. The first problem i have faced when using the dialog plug-in was that I click any of the button show Prompt, show confirmation or show alert the page reload and i can't see the any of the dialog there. As you know that asp.net button control has default behavior of post back, mean when asp.net button is clicked it will it will post back to the server. And the HTML input type button will not postback.

Solve PostBack Problem
In order to see the alert dialog and disabling the postback of the button control what I did is to return false from the button JavaScript function. Here is my code to show the prompt dialog of the JQuery alert dialog.

$("#cmdShowPrompt").click(function()
{
jPrompt('Type something:', 'Initial Value', 'Prompt Dialog', function(r)
{
if (r)
jAlert('info', 'You entered ' + r , 'Information Dialog');
});
return false;
});

You can see from the above code that the click event handler of the cmdShowPrompt button will return false always so that the prompt dialog is displayed to the user. If you you remove this statement from the end of the function then you will not see the prompt dialog. If you want to disable the postback of the asp.net button control then you have to return false from that function using JavaScript. As asp.net 2.0 button control don't have any property "AutoPostBack" which other control of asp.net 2.0 have like check box and the DropDownList etc control.

Some Code Explanation
In the above code you can see that i have used the jPrompt and jAlert dialog of the Jquery Alert dialog plug-in. The first parameter to the jPrompt dialog is the Label of the text Box control in this can it is the "Type something", and second parameter is the initial value of the text box control shown in the jPrompt dialog, and third parameter is the title of the jPrompt dialog. The second dialog from the jQuery alert dialog plug-in I have used in my above code is the jAlert dialog. The jAlert dialog take the first parameter as type mean which type of alert it will be. it can be one of the following info for information, error, success and warning. The second parameter to the jAlert dialog is the message which will be shown in the body of the jAlert dialog. and the third parameter is the title of the jAlert dialog.

As you can see from the above code that I have disable the postback of the asp.net button control , what if I have the server side statements which need to be execute when user click the button, or you can say that how can I perform the database interaction on server side. After reading the comments from the site where I have downloaded the source code of the plug-in which is the A beautiful Site I found the solution.

__DoPostBack from javascript:
To solve the postback problem, I have used the knowledge of the my Calling __dopostback from JavaScript post, where i have used the __dopostback in JavaScript and force my page to postback. Here is the code of the my script of calling the jConfirm dialog, as with the other jQuery alert dialog plug-in i have return fasle fromt the click event of the cmdShowConfirmation click event.

$("#cmdShowConfirmation").click(function()
{
jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r)
{
if(r== true)
__doPostBack('cmdShowConfirmation','');
});
return false;
});

return false;
});

For the code above i have used the callback function of the jConfirm dialog which will be executed when use OK or cancel button. Depending on the user click which is either OK or cancel the callback function has the parameter r which is true if user click OK and false if user click cancel button. In the above code I will call the dopostback if user click the OK button. So I place if condition to check the value of r, if the value of r is true then call the __dopostback function and pass the id of the current control which is cmdShowPrompt.

You can download the source code from here

All and any comments / bugs / suggestions are welcomed!

Friday, April 24, 2009

jQuery Alert Dialogs

This jQuery plugin aims to replace the basic functionality provided by the standard JavaScript alert(), confirm(), and prompt() functions. What's the benefit of using custom methods? Well, a few good reasons, really: - These are completely customizable via CSS (which can make your apps look much more professional) - You can set a custom title for each dialog - IE7 users get an ugly warning and usually have to reload the page if you use a regular prompt() These methods simulate a true modal dialog box. They will automatically re-position themselves if you resize the browser window (unlike many existing dialog/lightbox-style plugins). If you include the jQuery UI Draggable plugin, the dialogs can be moved by dragging their title bars. Everything you need to produce the dialogs in the demonstration is included in the download.
Here is the syntax of the dialogs which are the alert, confirm and the prompt function. All these three functions take same number of arguments, except the Prompt function which take an extra parameter which is the value.

jAlert( message, [title, callback] )
jConfirm( message, [title, callback] )
jPrompt( message, [value, title, callback] )

You can find detail of the alert plug-in by clicking here . And download the examples from there.

All and any comments / bugs / suggestions are welcomed!


Thursday, April 23, 2009

Calling __doPostBack in our own javascript

One of the most important features of the ASP.NET environment is the ability to declare controls that run on the server, and post back to the same page. Remember the days of classic ASP? We would create a form which would accept the user's input, and then we would most probably have to create another page that would accept all those inputs, either through HTTP GET or POST, and perform some kind of validation, display and action. Sometimes, even a third page was necessary to perform our actions. This wasted a lot of time and complicated things when you had to make a change. But of course, this is not necessary any more with ASP.NET. There is no need to create second pages that accept the inputs of the first, process them and so on. Form fields and other controls can be declared to run on the server, and the server simply posts the page back to itself and performs all the validation, display and actions. Our life as web developers has become a million times better. But how exactly is this done?
When a control is declared to run on the server, a VIEWSTATE is created which remembers the ID of that control, and the method to call when an action is performed. For example, let's say we input this HTML on a page:

< html>
< head>
< body>
< form runat="server" id="myForm">
< asp:linkbutton id="Test" runat="server" text="Create Text file" onclick="Test_Click">
< /form>
< /body>
< /html>

This is a very simple page. We declare only one web control, a linkbutton, to run on the server, with an ID of Test and we assign a method called Test_Click to run when the link is clicked on the page. The linkbutton has to be wrapped inside a form that runs on the server as well. We save the above as an ASPX page and then we browse to it. The HTML that gets created looks like this:

< html>
< body>
< form name="myForm" method="post" action="test.aspx" id="myForm">
<input type="hidden" name="__EVENTTARGET" value="" />
< input type="hidden" name="__VIEWSTATE" value="dDwtMTAwOTA0ODU1NTs7PsllCK1DzvZsK0J6OQ2dxKqmEwVs" / >
< script language="javascript">
function __doPostBack(eventTarget, eventArgument) {
var theform = document.myForm;
theform.__EVENTTARGET.value = eventTarget;
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
< /script>
< a id="Test" href="javascript:__doPostBack('Test','')"> Create Text file< >
< /a>
< /form>
< /body>
< /html>

Our link calls the javascript function __doPostBack when clicked (that's 2 underscore symbols in front of it). You do not write this function, instead it is generated by the ASP.NET engine and automatically included in our page. It submits the form to the same page, and accepts 2 arguments:
  1. eventTarget: the control doing the submission
  2. eventArgument: any additional information for the event
For example, our generated link button, is telling the javascript function that the control submitting the form is the one with ID=Test, and no further information is needed for the second argument. The javascript function is actually setting 2 hidden form fields with these 2 arguments: __EVENTTARGET and __EVENTARGUMENT. When the form is submitted back to the server, the server reads these 2 hidden form fields and decides what submitted the form and performs the necessary action. In this case, the server will determine that the linkbutton performed the action, and will execute the Test_Click method.
Lastly, I should point out that at least one control needs to be set to Visible, for the server to generate the __doPostBack function in our page. Even if we have numerous web controls declared to run on the server, but they are all set to Visible=false, then the javascript function will not be included and we will not be able to perform any actions. You can test this out, by changing the linkbutton source code to this and looking at the source code generated when it runs:
We can also call the __dopostback function manually by ourselves. Here is the code example how we can call the __dopostback in javascript.

< script language="javascript">
function MyPostBackFunction() {
__doPostBack('ControlID','Arguments');
}
< /script>

Here is the code behind statements which are used to get the target name and also the argument is passed from the do postback call.

string strPostBackControlName = Request.Params.Get("__EVENTTARGET");
string strEventArgument = Request.Params.Get("__EVENTARGUMENT");


The above article is take from this link

All and any comments / bugs / suggestions are welcomed!

Saturday, April 18, 2009

Using responseText in Ajax Call

The response can come in many different forms, such as XML, plain text, (X)HTML, or JavaScript Object Notation (JSON). Depending on the data format that you receive, there are two different ways to handle it: with responseText or with responseXML. The responseText method is used for all formats that are not based on XML. It returns an exact representation of the response as a string. Plain text, (X)HTML, and JSON are all formats that use responseText. Using this method on plain text or HTML is trivial: (Source)
For this post i will use the responseText property to get the data return by the Ajax call. For this example i have used the northwind database and in that database i have used the two tables which are orders and the Employees table. I have used DropDownList control which is used to fill with the countries name from the order and i have used the distinct select statement to get the countries name from the order table. Next i have the div control which will show the detail of order which is get from the order table based on the country name. When use select the country name from the DropDownList then the detail of that country is display in the div control.
First i have fill the country DropDownList control by selecting the distinct shipCountry form the order table and also attaching the onChange event to the country DropDownList country, The onChange is the name of the JavaScript function which will be called when ever value in the country DropDownList is changed. This is registered against the onchange JavaScript event. Here is the complete JavaScript. In the onChange function have called the showCustomer function which will take the country name as input parameter.

function onChange(CurrentItem)
{
showCustomer(CurrentItem.value);
}

//xmlHttp object
var xmlHttp

function showCustomer(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");

return;
}
var url="OrderDetail.aspx";
url=url+"?Country="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
var divDetail = document.getElementById("");
divDetail.innerHTML = xmlHttp.responseText;
}
}
In the showCustomer function i have initialize the xmlHttp object which is declared globally in the JavaScript. I have called the GetXmlHttpObject function which will check the browser and then return the xmlHttp object depending on the browser. I have not paste the GetXmlHttpObject function here, you can find it in the source code of this project. Next i have check the xmlHttp object for null, if the xmlHttp object is null then no need to go further just display the message to user and return. If the xmlHttp object is not null then next i have created the url which will be used to call the page. In this case i have call the OrderDetail.aspx page for the Ajax call and also pass the country in the query string and a random number in the query string so that each time the call goes to the OrderDetail.aspx it will treat it as new call each time. Next i have attach the onreadystatechange function to the xmlHttp object so that when the state of the 4 mean our request is complete , we can check the responseText project to get the our result, which is return from the Ajax call. For detail of the onreadystatechange and the state of the request click here.
In the OrderDetail code behind file what did is to get the country name from the query string and then query the sql server to get the detail of the order based on the country name. For fetching the detail of the order based on the country name i have used the order table and also the employees table to get the employee name from that. Then after the successful of the sql query i have store the return values in the data reader object. and the loop through the data reader read() function call i have generate the html table which will be as it is shown on the client side.
After the return from the server in the onreadystatechange function , when the state of the request return 4 I have get the div control and then assign the xmlHttp.reponseText to the innerHTML property of the div control and the over loop is complete based on the DropDownList onchange event.

You can download the source code from here. you can read more about the responseText more by clicking here
All and any comments / bugs / suggestions are welcomed!

Empty Data Template of GridView Control

In my web projects i have given the end user the option to search the records. Some times user criteria match and some times not. When user selected search criteria is match we use to display the user result in the grid view control but if user criteria is not match and we have not record found for the user search, then use hide the grid view and display message to user that your search criteria didn't return any record or something like that.
After some time i search learning more about the grid view control, to search what are the feature offered by the grid view control. i came across the EmptyDataTemplate of the grid view control and in this post i will discuss EmptyDataTemplate of grid view control.The empty data row is displayed in a GridView control when the data source that is bound to the control does not contain any records. You can define your own custom user interface (UI) for the empty data row by using the EmptyDataTemplate property. To specify a custom template for the empty data row, first place EmptyDataTemplate tags between the opening and closing tags of the GridView control. You can then list the contents of the template between the opening and closing tags. To control the style of the empty data row, use the EmptyDataRowStyle property. Alternatively, you can use the built-in UI for the empty data row by setting the EmptyDataText property instead of this property.(Source)
Now let us start with our example of how to use the EmptyDataTemplate in the grid view control. For this post i have added a grid view control in the page and then two button control, one is the Fill grid view button which is used to fill the grid view control and second one is the Empty grid view control which is used to show the message or you can say which return no data in the datasource of the the grid view control. Here is the output of the grid i have added in my page. when the grid is filled.


Here is the output of the grid when no data is return from the datasource. You see that both the empty and the filled data grid have similar GUI. For the emptyDataTemplate i have use html table so that the no record found message or emptydDataTemplate looks similar to the grid when it is filled.


You can download the source code from here
All and any comments / bugs / suggestions are welcomed!

Sunday, April 12, 2009

Selecting All checkBox in GridView Control Asp.net

Many of the user who use the hotmail, yahoo or gmail they may observe for each email they have provide the checkbox so that you can select the email and then you can perform you action either delete the email, move the email to other folder etc. They also provide the option of selecting the all emails and perform one action to the all selected email records.
Today in this post i will show you how you can select all the checkbox in the grid like yahoo, hotmail and the gmail accounts. For this post i have just one grid view control which consist of two columns one for the checkbox and the second for the subject. I have added checkbox in the header of the grid so that when user click on that checkbox all the checkboxs in the grid view are checked and when that checkbox is unchecked then all the checkboxs in the grid view control are unchecked.
Let us start with our example code. I have bind the grid in the Page_Load event.By setting the DataSource property of the grid view control and after setting the grid view dataSource property i have called the DataBind() method of the grid view control. Here is the code which is used to add the click attribute of the checkbox which is added in the header to select all the checkbox and then depending on the value of the this checkbox all the checkboxs are unchecked.
if (e.Row.RowType == DataControlRowType.Header)
{
CheckBox chkSelectAll = (CheckBox)e.Row.FindControl("chkSelectAll");
if (chkSelectAll != null)
chkSelectAll.Attributes.Add("onclick", "SelectAll(this);");
}
In the code above i have place if condition to check the header row of the grid view control. Then i have find the chkSelectAll check box control which is placed in the header row of the grid view control, the return control is converted to the checkbox and placed in the chkSelectAll checkbox control. In the next statement i have place the if condition to check the if the control is found or not. if found than i have added the onclick attribute to the chkSelectAll checkbox and place JavaScript function SelectAll, The SelectAll JavaScript function will take the current control as parameter so i pass this object to the function. The above code is place in the RowDataBound event of the grid view control.
Here is the SelectAll function code in the JavaScript, which is placed in the JavaScript tag.

function SelectAll(chkSelectAll)
{
// get datagrid by passed the clientID of the grid
var myGridView = document.getElementById('<%= grdvOrders.ClientID %>');

//Get all the input control in the grid.
var gridViewInputControls = myGridView.getElementsByTagName("input");

for(var intCounter=0;intCounter<=gridViewInputControls.lenght ; )
{
if(gridViewInputControls[intCounter].type == 'checkbox')
{
if(chkSelectAll.checked==true)
gridViewInputControls[intCounter].checked=true;
else
gridViewInputControls[intCounter].checked=false;
}
intCounter= intCounter+1;

}
}
In the above code i have get the grid view control by passing the client id of the grid view control which in this, as i have set the id of the control grdvOrders so i placed the grdvOrders.ClientID in the getElementById function call. in the next statement i have get all the input control in the grid by using the getElementByTagName function and passing the input as parameter and place the return control in the gridViewInputControls variable. And then i have loop through the gridViewInputControls array and in the for loop i have place the if condition to check the type of the control as i need to set the checked property of the checkbox , so i have place the type of control to checkbox. In the if condition i have check the checked property of the passed checkbox which is the placed in the header of the grid view control and user can use that checkbox to checked/unchecked all the checkbox in that column. If the selectAll checkbox is check then all the checkboxs are marked as check and if the selectAll checkBox is unchecked then all the checkboxs are marked as unchecked.

Note: if you have more then one checkbox in you grid like i have only one checkbox foreach row, but if there is situation where you have more then one checkboxs then you have to check name of the checkbox as well in the if condition where i have check the type of the input control.Here is change code if you have more then one checkbox for each row.

if((gridViewInputControls[intCounter].type == 'checkbox') &&
(gridViewInputControls[intCounter].id.indexOf("chkSelect") !=-1))
{
if(chkSelectAll.checked==true)
gridViewInputControls[intCounter].checked=true;
else
gridViewInputControls[intCounter].checked=false;
}



In the above code i have place extra condition to true in the if condition in order to perform check/unchecked the check box, in the above if condition chkSelect is the name of the checkbox which is placed in the grid view control and which need to be checked/unchecked.

You can download the source code from here
All and any comments / bugs / suggestions are welcomed!

Saturday, April 11, 2009

DropDownList Binding in GridView Asp.net

Binding DropDownList asp.net 2.0 control which is placed in the GridView control is very easy and many of you know how to bind the DropDownList which is placed in the GridView Control.But there may some people who are beginner to the web development and didn't know how to bind the DropDownList which is placed in the GridView control.
For this code example which is simple one i have added one GridView Control in the main form. The GridView has only two columns one is to display the name of the order and the second which is used to show the status of the Order and I have place the DropDownList control for the status of the order. In the Page_Load event of the form you can bind the the GridView control to the what ever your data source. And then you can bind the DropDownList control in the RowDataBound Event of the GridView. Here is the code of the RowDataBound event of the GridView control.
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlDropDownList = (DropDownList)e.Row.FindControl("ddlDropDownList");
if (ddlDropDownList != null)
{
ddlDropDownList.DataSource = GetOrderStatus();
ddlDropDownList.DataTextField = "Status";
ddlDropDownList.DataValueField = "StatusID";
ddlDropDownList.DataBind();
}
}
In the above code of the GridView RowDataBound event what i did is the to check the RowType of the current Data Bound Row, Here i place the DataRow type check so that i can only perform the action on the DataRow type rows. Next after the if condition i have search for the DropDownList control in the current row by using the FindControl function of the current row and passing the name of the DropDownList control. After the i have place the if condition to check where DropDownList control is found or not.If found then ,set the DataSource of the DropDownList control and set the DataTextField and DataValueField of the DropDownList control and at the end call the DataBind of the DropDownList control.
For user here is the complete list of the DataControlRowType named constant.
Member NameDescription
HeaderA header row of a data control. Header rows cannot be data-bound.
FooterA footer row of a data control. Footer rows cannot be data-bound.
DataRowA data row of a data control. Only DataRow rows can be data-bound.
SeparatorA row separator. Row separators cannot be data-bound.
PagerA row that displays pager buttons or a pager control. Pager rows cannot be data-bound.
EmptyDataRowThe empty row of a data-bound control. The empty row is displayed when the data-bound control has no records
to display and the EmptyDataTemplate template is not null reference ( Nothing in Visual Basic).
The DataControlRowType enumeration identifies the function of rows in a data control. It is used by the DetailsView and GridView controls to distinguish between rows that display data and rows that display other user interface (UI) elements, such as a header row, row separator, or pager buttons.
You can use the DataControlRowType enumeration to identify the type of a GridViewRow or DetailsViewRow object when you enumerate through a GridViewRowCollection or DetailsViewRowCollection collection. If you are writing a data control that creates rows, you can use the DataControlRowType enumeration to identify the function of different rows in the control.

Note: I have used the DataTable which is created in the code and i have set the status and statusID of the data table you can replace your Column names which status and statusID.

You can download the source code from here
All and any comments / bugs / suggestions are welcomed!

How To Determine the Operating System Service Pack Level in Visual C# .NET

To determine the operating system service pack and some information about the operating system i first read and then i search is there any other way in the managed code to do so without using the window API. Then i come across the following finding.
The System.Environment class contain the OSversion property which contain the following operating system related information. The Platform, ServicePack, Version and the VersionString properties are expose to get those information.
Console.WriteLine("PlatformID : "+Environment.OSVersion.Platform);
Console.WriteLine("Service Pack: "+Environment.OSVersion.ServicePack);
Console.WriteLine("Version: "+Environment.OSVersion.Version);
Console.WriteLine("Version String: "+Environment.OSVersion.VersionString);
The Environment.OSVersion.Platform property return the PlatformID enumeration to help determine whether the current operating system or development platform supports your application. Here is the list of the PlatformID named constant.
Member NameDescription
Win32SThe operating system is Win32s. Win32s is a layer that runs on 16-bit versions of Windows to provide access
to 32-bit applications.
Win32WindowsThe operating system is Windows 95 or later.
Win32NTThe operating system is Windows NT or later.
WinCEThe operating system is Windows CE.
UnixThe operating system is Unix.
XboxThe development platform is Xbox 360.
MacOSXThe operating system is Macintosh.
All and any comments / bugs / suggestions are welcomed!

Wednesday, April 8, 2009

Display drive information using DriveInfo Class

DriveInfo class in .NET Framework is very useful class you can use to get information about the system drives. It has many properties and methods to query drive information such as drive type, drive format, total size or total free space. In the following Tutorial I will show you how to use this class in .NET Windows Application. Here is the list of the properties available in DriveInfo class.

NameDescription
AvailableFreeSpaceIndicates the amount of available free space on a drive.
DriveFormatGets the name of the file system, such as NTFS or FAT32.
DriveTypeGets the drive type.
IsReadyGets a value indicating whether a drive is ready.
NameGets the name of a drive.
RootDirectoryGets the root directory of a drive.
TotalFreeSpaceGets the total amount of free space available on a drive.
TotalSizeGets the total size of storage space on a drive.
VolumeLabelGets or sets the volume label of a drive.
Here is the code which you can use to access the properties of the driveInfo object. In the code below i have used the DriveInfo.GetDrives() function which will retrieves all logical drive names on a computer. You can use this information to iterate through the array and obtain information on the drives using other DriveInfo methods and properties. In the next statement the foreach loop is used to go through each object in the drive array. Then in the foreach loop if condition is place to check the IsReady property of the drive object. The IsReady indicates whether a drive is ready. For example, it indicates that a CD is in a CD drive or that a removable storage device is ready for read/write operations. If you do not test whether a drive is ready, and it is not ready, querying the drive using DriveInfo will raise an IOException.
DriveInfo[] drives = DriveInfo.GetDrives();
int intListCounter = 0;
foreach (DriveInfo drive in drives)
{
if (drive.IsReady)
{
lstDriveInfo.Items.Add(drive.Name);
lstDriveInfo.Items[intListCounter].SubItems.Add(drive.DriveFormat);
lstDriveInfo.Items[intListCounter].SubItems.Add(drive.TotalSize.ToString());
lstDriveInfo.Items[intListCounter].SubItems.Add(drive.TotalFreeSpace.ToString());
intListCounter++;
}
}
The DriveFormat property has either NTFS or FAT32 value, The formatting of the drive. And here is the list of enumeration of driveType enum.
Member Name
Description
UnknownThe type of drive is unknown.
NoRootDirectoryThe drive does not have a root directory.
RemovableThe drive is a removable storage device, such as a floppy disk drive or a USB flash drive.
FixedThe drive is a fixed disk.
NetworkThe drive is a network drive.
CDRomThe drive is an optical disc device, such as a CD or DVD-ROM.
RamThe drive is a RAM disk.
Hope you get some understanding of the DriveInfo class. You can download the source code from here
All and any comments / bugs / suggestions are welcomed!

Sunday, April 5, 2009

How to Get All table names of a DataBase

While working in sql server and writing queries in the Query analyzer I often need to go to the Object browser window and go through the database and then find out the name of the table to which i need to write query. Then i start my search on how to find the table name by using any command in the query analyzer. And here is the solution to my problem, now i can find whole list of the table names which are in the database. which is found from this source
USE NORTHWIND
SELECT * FROM information_schema.tables
ORDER BY table_TYPE
Contains one row for each table in the current database for which the current user has permissions. The INFORMATION_SCHEMA.TABLES view is based on the sysobjects system table. To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name. And here is the second way you can use to get list of table names from database of northwind. And here is the output of the above command.


As you can see that it consist of the following columns.
Column nameData typeDescription
TABLE_CATALOGnvarchar(128)Table qualifier.
TABLE_SCHEMAnvarchar(128)Table owner.
TABLE_NAMEsysnameTable name.
TABLE_TYPEvarchar(10)Type of table. Can be VIEW or BASE TABLE.
Or you can use the sysobjects directly and get more information about the objects contained in the database. The sysobjects contains one row for each object (constraint, default, log, rule, stored procedure, and so on) created within a database. From the below select command i have set the type of the return value to 'U', which only return me the values of the tables contained in the database.
USE NORTHWIND
SELECT * FROM sysobjects
WHERE TYPE='U'
Here is the list of possible values for the type column
  • C = CHECK constraint
  • D = Default or DEFAULT constraint
  • F = FOREIGN KEY constraint
  • FN = Scalar function
  • IF = Inlined table-function
  • K = PRIMARY KEY or UNIQUE constraint
  • L = Log
  • P = Stored procedure
  • R = Rule
  • RF = Replication filter stored procedure
  • S = System table
  • TF = Table function
  • TR = Trigger
  • U = User table
  • V = View
  • X = Extended stored procedure
By removing the where clause from the above select statement you can get all the objects.Hope you will get some idea of how to get the information of the object in the database.
All and any comments / bugs / suggestions are welcomed!

Saturday, April 4, 2009

Convert String To Enum Instance in C#

Converting a string to enum is quite easy one, but it need some attention when converting from string to enum. I will try to explain you how you can convert from a string to enum type. For this post i have same enum Type which is EmployeeType which i have used in my previous post which is Convert Integer To Enum Instance in C# .EmployeeType enum type consist of four named constants which are Manager, Grunt, Contractor and the VicePresident and i have set the integer value for the named constant which are 1, 2, 3 and 4 respectively.
enum EmployeeType
{
Manager = 1,
Grunt = 2,
Contractor = 3,
VicePresident = 4,
}
Below is the example code you can use to convert from string value to enum instant. In the first statement i have "Manager" string value to be converted from string to enum instant and i have used the Enum.Parse function to convert from string to enum instant. The Enum.Parse function will take the type of enum to which you want to create the output and the second one is the string value which is used to parse. The Enum.Parse has one overloaded function which will take a Boolean value either true of false. In the next statement i have used the overloaded function of the Enum.Parse function to give some information about the overloaded function to you people.
EmployeeType manager= (EmployeeType)Enum.Parse(typeof(EmployeeType),"Manager");
EmployeeType contractor = (EmployeeType)Enum.Parse(typeof(EmployeeType),"contRACtor",true);
Console.WriteLine("Volume Member: {0}\t Value: {1}", manager, (byte)Enum.Parse(typeof(EmployeeType), manager.ToString()));
Console.WriteLine("Volume Member: {0}\t Value: {1}", contractor, (byte)Enum.Parse(typeof(EmployeeType), contractor.ToString()));
Console.ReadKey();
As you can see in the above code that i have passed "contRACtor" and also pass the true value to the Enum.Parse function. Which mean that Enum.Parse function will ignore the case of the string and convert it to the respective enum Instant. And of course not forget to pass the type of enum to which you want to create the output.
Above code is simple one as we are converting the string value which are defined in the EmployeeType , what about if we pass the "Managers" or some other value which is not given in the EmployeeType, then for that case it will throw ArgumentException Exception. To avoid Argument Exception we have alternative ways to check if the string value exist in the enumeration or not. Below is the one way you can use this technique to avoid the Argument Exception.
string strValue = "Manager";
Boolean blnIsExist = Enum.IsDefined(typeof(EmployeeType), strValue);
if (blnIsExist)
{
EmployeeType manager = (EmployeeType)Enum.Parse(typeof(EmployeeType), strValue );
Console.WriteLine("Volume Member: {0}\t Value: {1}", manager, (byte)Enum.Parse(typeof(EmployeeType), manager.ToString()));
}
else
Console.WriteLine("Not Found");
In the code above i have use the Enum.IsDefined function to check the string value in the enumeration of EmployeeType. it will return true in the above case as i have pass right value to the IsDefined function which is the "Manager", by checking the Boolean value which is return by the IsDefined function we can avoid the argument exception. But using this techinque has a draw back ,which is if you pass the value which is in the enumeration say you pass the value "manager", the IsDefined function will return false for it as it didn't match with any names constant, because characters in the passed string must have the same case as the enumeration member name. To avoid such situation we can use use another technique by checking the string value in the enumeration. Here is the list of code you can use over come the case sensitive of the input string.
string strValue = "manager";
Boolean blnIsExist =CheckStringValueInEnum(strValue);
if (blnIsExist)
{
EmployeeType manager = (EmployeeType)Enum.Parse(typeof(EmployeeType), strValue,true );
Console.WriteLine("Volume Member: {0}\t Value: {1}", manager, (byte)Enum.Parse(typeof(EmployeeType), manager.ToString()));
}
else
Console.WriteLine("Not Found");


private static Boolean CheckStringValueInEnum(string pstrValue)
{
foreach (string strEmployeeType in Enum.GetNames(typeof(EmployeeType)))

if (string.Compare(strEmployeeType, pstrValue, true) == 0)
return true;
return false;
}
In the above code i have passed "manager" string value to the function CheckStringValueInEnum which will check the passed string in the EmployeeType enumeration by comparing the passed string to the string value of the enumeration names constant. In the CheckStringValueInEnum function i have used the Enum.GetNames function which will return the string array of names . I have used the string.compare function by passing the two string value and the third one which is of type Boolean to indication of ignoring the case of the string characters. Here it will return true and i have also pass true to the Enum.Parse method to ignore the case of the input string so that string parsing can take place by ignoring the case of the input string.By using this technique we can avoid the exception. As i have console test application and the main function of the console is static , so the CheckStringValueInEnum is also static so that it can be called in the main function.
All and any comments / bugs / suggestions are welcomed!


Thursday, April 2, 2009

Convert Integer To Enum Instance in C#

Enums are a powerful construction in C# and other programming languages when you are working with finite sets such as fruits, days of the week or colors. Visual Studio's Intellisense is very nice with Enums because it lists all the options for the programmer to choose from. And you can choose the enum which you required at any specific time of code.
For this post I have a EmployeeType enum type which has four named constants which are Manager, Grunt, Contractor and the VicePresident and i have set the integer value for the named constant which are 1, 2, 3 and 4 respectively. Suppose we have an integer value and we want to convert to the EmployeeType enum and then display the enum value in the form of sting to the user.
enum EmployeeType
{
Manager = 1,
Grunt = 2,
Contractor = 3,
VicePresident = 4,
}
To over come this problem of to convert from integer value to a give enum type C# has the Enum.ToObject method. Let me explain how it work and what parameter it will take. In the code below i have set the value of the integer to 3 and the variable which hold the value is "intValue" , The Enum.ToObject method takes two arguments. The first is the type of the enum you want to create as output. The second field is the int to convert. Obviously, there must be a corresponding Enum entry for the conversion to succeed.
int intValue = 3;
EmployeeType ConvertedValue = (EmployeeType)Enum.ToObject(typeof(EmployeeType), intValue);
Console.WriteLine(ConvertedValue.ToString());
Console.ReadKey();
As you can see from the above code that i have cast the return value of the Enum.ToObject function to my EmployeeType, because the Enum.ToObject function will return the System.Object type and you have to convert it to your enum type. Here is the another piece of code which will show you how you can check if the name constant value exist in the enum or not.
int intValue = 5;
EmployeeType ConvertedValue = (EmployeeType)Enum.ToObject(typeof(EmployeeType), intValue);
Boolean blnIsExist = Enum.IsDefined(typeof(EmployeeType), ConvertedValue);
if (blnIsExist)
{
Console.WriteLine("Value is define in named Constant");
Console.WriteLine(ConvertedValue.ToString());
}
else
Console.WriteLine("Not Found");
The above code is simple one, i have first convert the integer value to the EmployeeType enum and then in the next statement it will check whether the converted value exist in the EmployeeType enum or not by using the IsDefined function of the Enum class which will return true if the value exist in the given enum otherwise it will return false. Depending on the return value of the IsDefined function it will display message.In the above case it will display "Not Found" message as the integer value is 5.

All and any comments / bugs / suggestions are welcomed!