Friday, January 25, 2008

How To Open ModalPopup on page Load in ASP.NET

Wednesday, January 16, 2008

JavaScript Get Key Values Or Code On KeyDown

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Find KeyCode</title>

    <script language="JavaScript">
        function TriggeredKey(e) {
            var keycode;
            if (window.event) keycode = window.event.keyCode;
            alert("keycode: " + keycode);
        }
    </script>

</head>
<body onkeydown="TriggeredKey(this)">
</body>
</html>
Special Keyboard Key(s) Code

KeyCode
Backspace      8
Tab            9
Enter         13 
Shift         16 
Ctrl          17 
Alt           18 
Pause/Break   19 
Caps Lock     20 
Esc           27 
Page Up       33 
Page Down     34 
End           35 
Home          36 
Left Arrow    37 
Print Screen  44
Delete        46
F1            112
F2            113
F3            114
F4            115
F5            116
F6            117
F7            118
F8            119
F9            120
F10           121
F11           122
F12           123

Restrict User From Ctrl Key Press

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Restrict Ctrl Key Press</title>

    <script>
        function Restrict() {
            if ((window.event.keyCode == 17)) {
                alert("Ctrl Key Press In !" + '\r\n' + "Add Your Own Code Here"); // Add Your Code Here
            }
        }
    </script>

</head>
<body onload="JavaScript:document.body.focus();" onkeydown="Restrict()">
</body>
</html>

Get Mouse Position Using JavaScript

<html>
<body>

    <script language="JavaScript">

        document.onmousemove = getCoordinate;
        var mosX = 0;
        var mosY = 0;
        function getCoordinate(e) {
            mosX = event.clientX + document.body.scrollLeft;

            //clientX Property Sets or retrieves the x-coordinate of the mouse
            //pointer's position relative to the client area of the window,
            //excluding window decorations and scroll bars
            //scrollLeft Property Sets or retrieves the distance between the
            //left edge of the object and the leftmost portion of the content
            //currently visible in the window.

            mosY = event.clientY + document.body.scrollTop;

            //clientY Property Sets or retrieves the y-coordinate of the mouse
            //pointer's position relative to the client area of the window,
            //excluding window decorations and scroll bars.
            //scrollTop Property Sets or retrieves the distance between the top
            //of the object and the topmost portion of the content currently
            //visible in the window.

            document.title = "(X Co-Ordinate » " + mosX + ") ( " + "Y Co-ordinate » " + mosY + ")";
            document.getElementById('dx').innerHTML =
"Mouse X ==» " + mosX + "<br>" + "Mouse Y ==» " + mosY;

            return true
        }

    </script>

    <div id="dX">
    </div>
</body>
</html>

Dynamically Increase The Size Of The TextBox Using JavaScript

<html>
<head>

    <script>
        function incr() {
            var len = document.getElementById('txt').value;
            document.getElementById('txt').style.width = 75 + len.length * 4 + 'px';
        }
    </script>

    <body>
        <input type='text' id='txt' onkeydown='incr()' style='width: 75px' />
    </body>
</html>

Trap F1 key in IE, ByPass Showing Help Window

<html>
<head>
<script>
function ByPass()
{
var kCode = window.event.keyCode;
       if(kCode == 112)
      {
             alert('F1 Clicked'); // Alter Code As Your Wish
       }
}
</script>
</head>
<body onhelp="return false;" onkeydown="ByPass()">
</body>
</html>

javascript function for invoking button click event

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>javascript function for invoking btnclick event</title>

    <script language="javascript" type="text/javascript">
        function TrigButton() {
            if (window.event.keyCode == 13) {
                if (document.getElementById('txt').value.length > 0) {
                    document.getElementById('bt').focus();
                    document.getElementById('bt').click();
                }
            }
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:textbox id="txt" runat="server" onkeydown="TrigButton()"></asp:textbox>
        <asp:button id="bt" runat="server" text="Button" onclientclick="javascript:alert('Button Triggered');"
            onclick="bt_Click" />
    </div>
    </form>
</body>
</html>

How To Use Sleep Function Using JavaScript

<html>
<head>

    <script language='javascript'>
        function sleep() {

            var Sleep = setTimeout("alert('Hi Have A Nice Time And Day ')", 2000);
            // 2000 Millisecond(2 sec)

        }
    </script>

    <body onload='sleep()'>
        Alert Box Will Be Displayed After 2 Seconds the Body is Loaded
    </body>
</html>

Restrict Numberic Input In TextBox

<html>
<head>

    <script language="javascript">
        function blockNum(e) {
            var keyVal = (window.event) ? event.keyCode : e.keyCode;
            if (window.event) keyVal = window.event.keyCode;
            if ((keyVal > 47 && keyVal < 58) || (keyVal > 95 && keyVal < 107)) {
                return false;
            }
        }
    </script>

</head>
<body onload="javascript:document.getElementById('txt').focus();">
    <input type="text" id='txt' onkeydown="return blockNum(this);" />
</body>
</html>

Restrict Alphabet Input In TextBox

<html>
<head>

    <script language="javascript">
        function blockChar(e) {
            var keyVal = (window.event) ? event.keyCode : e.keyCode;
            if (window.event) keyVal = window.event.keyCode;
            if ((keyVal > 64 && keyVal < 93)) {
                return false;
            }
        }
    </script>

</head>
<body onload="javascript:document.getElementById('txt').focus();">
    <input type="text" id='txt' onkeydown="return blockChar(this);" />
</body>
</html>

Restrict Alphabet Input In TextBox Using Regular Expression

<html>
<head>

    <script language="javascript">
        function blockChar() {
            var str = document.getElementById('txt').value;
            str = str.replace(/[^\d]*/g, '');
            document.getElementById('txt').value = str;
        }
    </script>

</head>
<body onload="javascript:document.getElementById('txt').focus();">
    <input type="text" id='txt' onkeyup="blockChar();" />
</body>
</html>

How TO Add copy to clipboard Button On Page

<html>
<head>
</head>
<body>
    <textarea id='clipText'>
Enter Text And Click Button To Copy Text To ClipBoard</textarea><br />
    <input type="button" id='bt' onclick="clipboardData.setData('Text',document.getElementById('clipText').value);"
        value="Copy" />
    <input type="button" onclick="clipboardData.clearData('Text');" value="Clear" />
    <input type="button" onclick="alert(clipboardData.getData('Text'));" value="Paste" />
</body>

How To Block F5(Refresh) Key In IE and Firefox

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Block F5 Key In IE & Mozilla</title>

    <script language="JavaScript">

        var version = navigator.appVersion;

        function showKeyCode(e) {
            var keycode = (window.event) ? event.keyCode : e.keyCode;

            if ((version.indexOf('MSIE') != -1)) {
                if (keycode == 116) {
                    event.keyCode = 0;
                    event.returnValue = false;
                    return false;
                }
            }
            else {
                if (keycode == 116) {
                    return false;
                }
            }
        }

    </script>

</head>
<body onload="JavaScript:document.body.focus();" onkeydown="return showKeyCode(event)">
</body>
</html>

Sample source code for JavaScript Page Processing

We have provided below sample source code for JavaScript Page Processing in Asp.Net. You can copy and paste it in your pages to create the sample application. Code for Processing Page (PageProcessor.aspx)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Please wait...We Are Processing Your Request..</title>

    <script>
        function PageOnLoad() {
            location.href = "<%=PageToLoad%>";
            document.images['imgsrc'].src = "Images/Loading.gif";
        }
    </script>

</head>
<body bottommargin="0" leftmargin="0" rightmargin="0" topmargin="0" onload="PageOnLoad();">
    <form id="form1" runat="server">
    <div>
        <table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%">
            <tr>
                <td height="50" class="NormalText" align="center" valign="bottom">
                    <h3>
                        We are processing your request. Please wait..
                    </h3>
                </td>
            </tr>
            <tr>
                <td align="center" height="250" valign="top">
                    <img src="" name="imgsrc" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>
Source Code of code-behind file (PageProcessor.aspx.cs)
  protected string PageToLoad;

    protected void Page_Load(object sender, EventArgs e)
    {
        PageToLoad = Request.QueryString["PageId"];
    }

Tuesday, January 15, 2008

Trapping close of IE window in ASP.NET

Trap window close event for IE browser
Let's say you want to trap the window close event for the web browser
so that you can give a confirmation dialog asking if the user is sure
to leave the page.The problem is that there is no onclose event for the
window object.The closest event might be onunload since it fires immediately
before the window object is unloaded. However, when the onunload event fires
it is too late to display a JavaScript alert. Therefore, we need an event that
fires prior to a page being  unloaded, which is onbeforeunload.
Define onbeforeunload event in your page <BODY> element as follows:

<BODY onbeforeunload="HandleOnClose()">

Then, add the following JavaScript code into the <HEAD> section of your
ASPX page:


<script type="text/javascript">
       function HandleOnClose() {
           if (event.clientY < 0) {
               event.returnValue = 'Are you sure you want to leave the page?';
           }
       } 
       
   </script>
The trick here is to check clientY property of the event object, which is used to set or retrieve the y-coordinate of the mouse pointer's position relative to the client area of the window, excluding window decorations and scroll bars. This way, you can detect if the user clicked on X button to close the page, or clicked on Refresh button to refresh the page, etc. This approach does not handle key events such as Alt-F4 that lets the user close the window by using the keyboard. You have to handle keyboard events separately
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>

  <script type="text/javascript">
      function HandleOnClose() {
          if (event.clientY < 0) {
              event.returnValue = 'Are you sure you want to leave the page?';
          }
      }
     
  </script>

</head>
<body  onbeforeunload="return HandleOnClose()">
</body>
</html>

Wednesday, January 9, 2008

How To Create your own CustomValidation Control In ASP.net 2.0

how to derive your custom control from a base class and add your own features. In this article we'll demonstrate how to derive a class from the BaseValidtor class to create your own validator control. Why would you do this? Well, in short the validator controls collection is very good, but as you will find they don't cover every type of validation you will need to do. You can use the custom validtor control to accomidate this, but if you need to do validtation in multiple places within your web application or even multiple web applications and sites then this isn't such a good solution. Instead, I would recommend creating a custom validation control and using that - why? Because it's cleaner! As previously mentioned this is an example of a very simple control. This validator control is derived from the base class BaseValidator . There is one properties added to the BaseValidator Email and the contents of the ControlToValidator must be this values. EmailValidator.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

namespace EmailValidator
{
 public class EmailValidator : BaseValidator
 {
     protected string strEmail;


     public string Email
     {

         set
         {
             strEmail = value;
         }


     }

     protected override bool EvaluateIsValid()
     {
         string val = this.GetControlValidationValue(this.ControlToValidate);
         string pattern = @"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)
?@[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$";
         System.Text.RegularExpressions.Match match =
Regex.Match(val.Trim(), pattern, RegexOptions.IgnoreCase);
         if (match.Success)
         {

             return true;

         }
         else
         {

             return false;

         }

     }




 }
}
EvaluateIsValid
This method contains the code used to determine validity. The return value
is boolean. If false is returned then then the ControlToValidate will not
have a valid value; otherwise true.
GetControlValidationValue
This method gets the value associated with a specified INPUT control.
The return value is a string and it expects a parameter which should be the
ID of the INPUT control. You retrieve the INPUT controls ID property using the
following property

ControlToValidate
This property contains the ID property of the INPUT control the validation
control should validate.
How To Use create a new application in VS.net and add the below code in aspx page.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Register Assembly="EmailValidator" Namespace="EmailValidator" TagPrefix="ccl" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
      <div>
          <asp:TextBox ID="txt" runat="server"></asp:TextBox>
          <ccl:EmailValidator ControlToValidate="txt" runat="server" ID="SS"
ErrorMessage="Envalid Email Address"
              Text="*">
          </ccl:EmailValidator>
          <asp:Button ID="btn" runat="server" Text="Submit" />
      </div>
  </form>
</body>
</html>

How To Upload Multiple Files

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

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

    <script type="text/javascript">
        //This function Creates the clone of the file upload control to upload images when 
        //clicked on AddAnother link.The function first get the reference of the file upload 
        //control "myElement1" added in HTML and the refernce of the td where we want to add 
        //the new control and then creates the clone of this referenced file upload.
        //The vale attribute of this newly created control is set to null as it contains 
        //the value of previously entered.The unique id and name is assigned to it and then 
        //added in the TD. Before inserting the BR tag is also inserted
        //so the the control should be added in next line.
        function addImageFile() {
            var fileInput = document.getElementById('tdFileInputs');
            var fileInput = document.getElementById("myElement1");
            var newFileInput = fileInput.cloneNode(true);
            newFileInput.value = null;
            newFileInput.id += 'A'; // A unique id
            newFileInput.name = newFileInput.id;
            if (document.all) {
                var br = document.createElement("<br>");
                tdFileInputs.appendChild(br);
            }
            tdFileInputs.appendChild(newFileInput);
            return false;
        }
   
    </script>

</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data">
    <div>
        <table>
            <tr>
                <td id="tdFileInputs">
                    <input type="file" id="myElement1" name="myElement1" />
                </td>
            </tr>
        </table>
        <a href="#" onclick="addImageFile();">Add</a>
        <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

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

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string baseImageLocation = Server.MapPath("UserImages\\");
        HttpFileCollection files = Request.Files;
        for (int i = 0; i < files.Count; i++)
        {
            HttpPostedFile file = files[i];
            string fileExt = Path.GetExtension(file.FileName).ToLower();
            string fileName = Path.GetFileName(file.FileName);
            if (fileName != "")
            {
                if (fileExt == ".jpg" || fileExt == ".gif")
                    file.SaveAs(baseImageLocation + fileName);

            }
        }
    }
}

Tuesday, January 8, 2008

How To Convert ArrayList To DataSet

How to convert an arraylist to dataset or datatable so that I can filter or make a select distinct from it or Bind it to Gridview.
public DataSet ConvertArrayListToDataSet()
   {
       DataSet dsTemp = new DataSet();
       DataTable Tables = new DataTable();
       dsTemp.Tables.Add(Tables);

       dsTemp.Tables[0].Columns.Add("val", System.Type.GetType(
       "System.String"));

       foreach (string str in arraylistcontainer)
       {
           if (str != string.Empty)
           {
               DataRow myRow = dsTemp.Tables[0].NewRow();
               myRow[0] = str;
               dsTemp.Tables[0].Rows.Add(myRow);
           }

       }
   }

Sunday, January 6, 2008

How To Use ICallback & JSON In ASP.NET

ICallback & JSON based Javascript Serialization Whilst working in asp.net sometimes we need to call server side methods asynchronously without have postback either it is full page postback or partial page postback so thanks to asp.net team to provide implementation of ICALLBACK very easily. ICALLBACK ICALLBACK is lightweight process, It uses well known xmlhttp object internally to call server side method, it doesn’t cause page postback so doesn’t cause page rendering so we to show output

ICallback & JSON based Javascript Serialization

Whilst working in asp.net sometimes we need to call server side methods asynchronously without have postback either it is full page postback or partial page postback so thanks to asp.net team to provide implementation of ICALLBACK very easily.

ICALLBACK

ICALLBACK is lightweight process, It uses well known xmlhttp object internally to call server side method, it doesn’t cause page postback so doesn’t cause page rendering so we to show output at client side we need to make output html ourselves and render controls manually.

ICALLBACKEVENTHANDLER

ICALLBACK implemented in asp.net by using ICALLBACKEVENTHANDLER interface has two methods, one of them used to be call from javascript (client side code) and other one return result asynchronously back to javascript function.

We just need to perform some action through server side code at server side and needs to return results but results could are in instance or object of any class which could be not easy for javascript code to handle easily so here we prefer JSON which stands for Javascript Object Notation.

JSON

JSON is lightweight data-interchange format. ASP.NET gives good support for JSON as well, it’s rapidly adopting because of its lightweight and easy to readable by human and machine as well.

CALLBACK SERVER SIDE CODE

Let’s first implement ICALLBACKEVENTHANDLER to call server side method asynchronously step by step J

Implement Server Side (C#) Page/Control class by System.Web.UI.ICallbackEventHandler

Following are definition of two methods which needs to implement:

RaiseCallbackEvent method invoke by thru javascript function

public void RaiseCallbackEvent(string eventArgument)

{

//to do code here

}

GetCallbackResult method invoke itself when processing of RaiseCallbackEvent method completed

public string GetCallbackResult()

{

return "";

}

In Page_Load or Page_Init event

Following statements are used to register client side methods.

CallServer(arg, context) as name implies would use to call/raise server side method which was RaiseCallbackEvent string eventArgument)

ReceiveServerData(arg, context) would use to get result through arg parameter by GetCallbackResult()

protected void Page_Load(object sender, EventArgs e)

{

ClientScriptManager scriptMgr = Page.ClientScript;

String cbReference = scriptMgr.GetCallbackEventReference(this, "arg", "ReceiveServerData", "");

String callbackScript = "function CallServer(arg, context) {" + cbReference + "; }";

cm.RegisterClientScriptBlock(this.GetType(),"CallServer", callbackScript, true);

}

CALLBACK CLIENT SIDE CODE

<script language=javascript type=text/javascript>

function ReceiveServerData(arg, context)

{

alert(arg);

}

function CallSrv()

{

CallServer('get customer', '');

}

script>

<input type=”button” value=”get customer” onclick=”CallSrv()” />>

Thants it. These are the steps which you need to use to call and get result from server side code using ICALLBACK.

Now we will go ahead for some very easy steps for JSON based javascript serialization to return results in javascript easily parseable format.

Suppose we have following class whose object we need to return to javascript function through javascriptserialization.

SAMPLE CLASS

public class Customer

{

public string Name;

public int Age;

}

JSON CODE

declare string jsonResult;

at class level, which would be use to contain final result and return.

After some sample code in both methods code will look like the following:

public void RaiseCallbackEvent(string eventArgument)

{

//populate Customer object to return

Customer customer = new Customer();

customer.Name = "Muhammad Adnan";

customer.Age = 24;

//javascript serialization of Customer object

System.Web.Script.Serialization.JavaScriptSerializer jss;

jss = new System.Web.Script.Serialization.JavaScriptSerializer();

//stringbuilder to contain serialized customer object

System.Text.StringBuilder sbCustomer = new System.Text.StringBuilder();

jss.Serialize(customer, sbCustomer);

jsonResult = sbCustomer.ToString();

}

public string GetCallbackResult()

{

return jsonResult;

}

Asynchronously output would be within a millisecond and without Postback J

Conclusion:

Callback is lightweight technique used to call server side methods asynchronously from javascript without any postback and reloading/rendering of unnecessary parts of page and unnecessary code.

JSON is lightweight data interchange format to make server side class’ objects easily parse able by client side code to show output on browser.

हाउ To Open NewWindow From CodeBehind Using ASP.NET

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Collections;
using System.Web.UI;
namespace com.StadiumRoar.Utility
{

   public class Utilities
   {
       public static void OpenPopUp(System.Web.UI.WebControls.WebControl opener,
   string PagePath, string windowName, int width, int height)
       {
           string clientScript;
           string windowAttribs;
           //Building Client side window attributes with width and height.//
           //Also the the window will be positioned to the middle of the screen//
           windowAttribs = "width=" + width + "px,"
  + "height=" + height + "px,"
  + "left=\'+((screen.width -"
  + width + ") / 2)+\',"
  + "top=\'+ (screen.height - "
  + height + ")/ 2+\'";

          //***Building the client script- window.open, with additional parameters***///
           clientScript = "window.open(\'" + PagePath + "\',\'"
 + windowName + "\',\'"
 + windowAttribs + "\');return false;";
           //regiter the script to the clientside click event of the 'opener' control*****///
           opener.Attributes.Add("onClick", clientScript);
       }
   }
}
How To Use This Method 1. Add Button controls in aspx page. <asp:Button ID="btn" runat="server" Text="Open Pop Up" /> 2.Add Below code in Page_load of the aspx page. Utilities.OpenPopUp(btn, "PoppEmail.aspx", "EmailPro", 700, 500);

Friday, January 4, 2008

How To Disable a button untill processing is complete

Here's the scenario - let's say you have an Insert subroutine, called 'doInsert'. You want to immediately disable the Submit button, so that the end-user won't click it multiple times, therefore, submitting the same data multiple times. For this, use a regular HTML button, including a Runat="server" and an 'OnServerClick' event designation - like this: < id="Button1" onclick="">=true;" type="button" value="Submit - Insert Data" name="Button1" runat="server" onserverclick="doInsert"> Then, in the very last line of the 'doInsert' subroutine, add this line: Button1.enabled="True"

How To Add Google Map to Your Web Application

Here is an example of how you can add a map to any contact us page or blog quickly and easily. •First you need a google api key ,which is free. You can find it,along with other documentation at http://www.google.com/apis Follow the instructions to "Sign up for a google API key". You'll need a gmail account, and to enter your domain name. This key can then only be used on pages served from that domain name. Along with your key, Google will give you a bit of starter code. Now create a new web application in vs.net and copy the highlited code in head section of your .aspx page.(replace [YOURKEY] with actual key)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GoogleMap.aspx.cs"
    Inherits="GoogleMap" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="http://maps.google.com/maps?file=api&v=2&key=
[YOURKEY]" type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[
        function showMap()
         {
                if (GBrowserIsCompatible()) {
                var map = new GMap2(document.getElementById("map"));
                map.addControl(new GSmallMapControl());
                map.setCenter(new GLatLng(31.95216223802497, -7.71875), 1);
            }
        }
    //]]>
    </script>

</head>
<body onload="showMap();" onunload="GUnload()">
    <form id="form1" runat="server">
        <div id="map" style="width: 500px; height: 300px">
        </div>
    </form>
</body>
</html>

How To Export Datatable To CSV Format in ASP.NET

  1. Create a new Web Application in VS.NET
  2. Add a button control to the page .
  3. write down following code in the click event of the button
    protected void Button1_Click(object sender, EventArgs e)
    {

        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

        SqlConnection conn = new SqlConnection(strConn);

        SqlDataAdapter da = new SqlDataAdapter("select * from tablename ", conn);

        DataSet ds = new DataSet();

        da.Fill(ds, "tbl");

        GridView1.DataSource = ds.Tables["tbl"].DefaultView;

        GridView1.DataBind();

        DataTable dt = ds.Tables["Emp"];

        CreateCSVFile(dt, "c:\\csvData.csv");

    }

 public void CreateCSVFile(DataTable dt, string strFilePath)
    {
        // Create the CSV file to which grid data will be exported.
        StreamWriter sw = new StreamWriter(strFilePath, false);
        // First we will write the headers.

        int iColCount = dt.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);
        // Now write all the rows.
        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();
    }

How To Send Email Through Gmail In ASP.NET

  1. Create a web application in VS.NET
  2. Add a button control on the Page
  3. Import namespace System.Mail
  4. Write down following code in the click event of the button
protected void SendMail()
    {
        //Create Mail Message Object with content that you want to send with mail.
        MailMessage MyMailMessage = new MailMessage
                          ("test@gmail.com", "myfriend@domain.com",
                          "This is the mail subject", "Just wanted to say Hello");
        MyMailMessage.IsBodyHtml = false;
        //Proper Authentication Details need to be passed when sending email from gmail
        NetworkCredential mailAuthentication = new NetworkCredential("test@gmail.com", "myPassword");
        //Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
        //For different server this details changes and you can
        //get it from respective server.
        SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
        //Enable SSL
        mailClient.EnableSsl = true;
        mailClient.UseDefaultCredentials = false;
        mailClient.Credentials = mailAuthentication;
        mailClient.Send(MyMailMessage);

    }

How To See The Path Of The Parsed class generated by ASP.NET

  1. Add Debug="true" to your @Page directive.

  2. Place <%= GetType().Assembly.Location %>somewhere on your page

This will print the location of the assembly generated for your page. If you go to that directory, you will also see source code files (*.cs or *.vb) that contain the class definitions

How to Register User Controls and Custom Controls in Web.config

In previous versions of ASP.NET developers imported and used both custom server controls and user controls on a page by adding <%@ Register %> directives to the top of pages like so: <%@ Register TagPrefix="scott" TagName="header" Src="Controls/Header.ascx" %> <%@ Register TagPrefix="scott" TagName="footer" Src="Controls/Footer.ascx" %> <%@ Register TagPrefix="ControlVendor" Assembly="ControlVendor" %> <html> <body> <form id="form1" runat="server"> <scott:header ID="MyHeader" runat="server" /> </form> </body> </html> Note that the first two register directives above are for user-controls (implemented in .ascx files), while the last is for a custom control compiled into an assembly .dll file. Once registered developers could then declare these controls anywhere on the page using the tagprefix and tagnames configured. This works fine, but can be a pain to manage when you want to have controls used across lots of pages within your site (especially if you ever move your .ascx files and need to update all of the registration declarations. Solution: ASP.NET 2.0 makes control declarations much cleaner and easier to manage. Instead of duplicating them on all your pages, just declare them once within the new pages->controls section with the web.config file of your application: <?xml version="1.0"?> <configuration> <system.web> <pages> <controls> <add tagPrefix="scottgu" src="~/Controls/Header.ascx" tagName="header"/> <add tagPrefix="scottgu" src="~/Controls/Footer.ascx" tagName="footer"/> <add tagPrefix="ControlVendor" assembly="ControlVendorAssembly"/> </controls> </pages> </system.web> </configuration>

How To Get HTML from a URL

You need to get the HTML returned from a web server in order to examine it for items of interest. For example, you could examine the returned HTML for links to other pages or for headlines from a news site.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace ConsoleApplication1
{
  class Program
  {
      static void Main(string[] args)
      {
          Console.WriteLine(GetHtmlFromUrl("http://www.google.com"));
          Console.Read();
      }
      public static string HostName2IP(string hostname)
      {
          // Resolve the hostname into an iphost entry using the Dns class.
          IPHostEntry iphost = System.Net.Dns.GetHostEntry(hostname);
          // Get all of the possible IP addresses for this hostname.
          IPAddress[] addresses = iphost.AddressList;
          // Make a text representation of the list.

          StringBuilder addressList = new StringBuilder();
          // Get each IP address.
          foreach (IPAddress address in addresses)
          {
              // Append it to the list.
              addressList.AppendFormat("IP Address: {0};", address.ToString());
          }
          return addressList.ToString();
      }
      public static string GetHtmlFromUrl(string url)
      {
          if (string.IsNullOrEmpty(url))
              throw new ArgumentNullException("url", "Parameter is null or empty");

          string html = "";
          HttpWebRequest request = GenerateHttpWebRequest(url);
          using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
          {

              // Get the response stream.
              Stream responseStream = response.GetResponseStream();
              // Use a stream reader that understands UTF8.
              using (StreamReader reader =
              new StreamReader(responseStream, Encoding.UTF8))
              {
                  html = reader.ReadToEnd();
              }

          }
          return html;
      }
      public static HttpWebRequest GenerateHttpWebRequest(string UriString)
      {
          // Get a Uri object.
          Uri Uri = new Uri(UriString);
          // Create the initial request.
          HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(Uri);
          // Return the request.
          return httpRequest;
      }
  }
}

How To Convert a Hostname to an IP Address

You have a string representation of a host (such as www.google.com ), and you need to obtain the IP address from this hostname.

   using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

namespace ConsoleApplication1
{
  class Program
  {
      static void Main(string[] args)
      {
          Console.WriteLine(HostName2IP("www.google.com"));
          Console.Read();
      }
      public static string HostName2IP(string hostname)
      {
          // Resolve the hostname into an iphost entry using the Dns class.
          IPHostEntry iphost = System.Net.Dns.GetHostEntry(hostname);
          // Get all of the possible IP addresses for this hostname.
          IPAddress[] addresses = iphost.AddressList;
          // Make a text representation of the list.

          StringBuilder addressList = new StringBuilder();
          // Get each IP address.
          foreach (IPAddress address in addresses)
          {
              // Append it to the list.
              addressList.AppendFormat("IP Address: {0};", address.ToString());
          }
          return addressList.ToString();
      }
  }
}

How To Convert an IP Address To Hostname

You have an IP address that you need to resolve into a hostname.

Use the Dns.GetHostEntry method to get the hostname for an IP address. In the following code, an IP address is resolved, and the hostname is accessible from the HostName property of the IPHostEntry:

 using System;
using System.Net;

//…
// Use the Dns class to resolve the address.
IPHostEntry iphost = Dns.GetHostEntry("127.0.0.1");

// HostName property holds the hostname.
string hostName = iphost.HostName;

// Print out name.
Console.WriteLine(hostName);

How To Get Information for All Drives on a System

Your application needs to know if a drive (HDD, CD drive, DVD drive, etc.) is available and ready to be written to and/or read from. Additionally, it would be nice to know if you have enough available free space on the drive to write information to.

Use the various properties in the DriveInfo class as shown here:

 public static void DisplayAllDriveInfo()
{
   foreach (DriveInfo drive in DriveInfo.GetDrives())
   {
       if (drive.IsReady)
       {
           Console.WriteLine("Drive " + drive.Name + " is ready.");
           Console.WriteLine("AvailableFreeSpace: " + drive.AvailableFreeSpace);
           Console.WriteLine("DriveFormat: " + drive.DriveFormat);
           Console.WriteLine("DriveType: " + drive.DriveType);
           Console.WriteLine("Name: " + drive.Name);
           Console.WriteLine("RootDirectory.FullName: " +
               drive.RootDirectory.FullName);
           Console.WriteLine("TotalFreeSpace: " + drive.TotalFreeSpace);
           Console.WriteLine("TotalSize: " + drive.TotalSize);
           Console.WriteLine("VolumeLabel: " + drive.VolumeLabel);
   }
   else
   {
           Console.WriteLine("Drive " + drive.Name + " is not ready.");
   }
}
}
Of particular interest are the IsReady and AvailableFreeSpace properties. The IsReady property determines if the drive is ready to be queried, written to, or read from. The AvailableFreeSpace property returns the free space on that drive in bytes.

How To Compare Version Information of Two Executable Modules

You need to programmatically compare the version information of two executable modules. An executable module is a file that contains executable code such as an .exe or .dll file. The ability to compare the version information of two executable modules can be very useful to an application in situations such as:

  • Trying to determine if it has all of the "right" pieces present to execute

  • Deciding on an assembly to dynamically load through reflection

  • Looking for the newest version of a file or .dll from many files spread out in the local filesystem or on a network

Use the CompareFileVersions method to compare executable module version information. This method accepts two filenames, including their paths, as parameters. The version information of each module is retrieved and compared. This file returns a FileComparison enumeration, defined as follows: public enum FileComparison { Same = 0, Newer = 1, // File1 is newer than File2 Older = 2, // File1 is older than File2 Error = 3 } The code for the CompareFileVersions method is shown below with proper commenting. public static FileComparison CompareFileVersions(string file1, string file2) { FileComparison retValue = FileComparison.Error; // Do both files exist? if (!File.Exists(file1)) { Console.WriteLine(file1 + " does not exist"); } else if (!File.Exists(file2)) { Console.WriteLine(file2 + " does not exist"); } else { // Get the version information. FileVersionInfo file1Version = FileVersionInfo.GetVersionInfo(file1); FileVersionInfo file2Version = FileVersionInfo.GetVersionInfo(file2); // Check major. if (file1Version.FileMajorPart > file2Version.FileMajorPart) { Console.WriteLine(file1 + " is a newer version"); retValue = FileComparison.Newer; } else if (file1Version.FileMajorPart <> { Console.WriteLine(file2 + " is a newer version"); retValue = FileComparison.Older; } else // Major version is equal, check next… { // Check minor. if (file1Version.FileMinorPart > file2Version.FileMinorPart) { Console.WriteLine(file1 + " is a newer version"); retValue = FileComparison.Newer; } else if (file1Version.FileMinorPart <> { Console.WriteLine(file2 + " is a newer version"); retValue = FileComparison.Older; } else // Minor version is equal, check next… { // Check build. if (file1Version.FileBuildPart > file2Version.FileBuildPart) { Console.WriteLine(file1 + " is a newer version"); retValue = FileComparison.Newer; } else if (file1Version.FileBuildPart <> { Console.WriteLine(file2 + " is a newer version"); retValue = FileComparison.Older; } else // Build version is equal, check next… { // Check private. if (file1Version.FilePrivatePart > file2Version.FilePrivatePart) { Console.WriteLine(file1 + " is a newer version"); retValue = FileComparison.Newer; } else if (file1Version.FilePrivatePart < file2Version.FilePrivatePart) { Console.WriteLine(file2 + " is a newer version"); retValue = FileComparison.Older; } else { // Identical versions Console.WriteLine("The files have the same version"); retValue = FileComparison.Same; } } } } } return retValue; }

Not all executable modules have version information. If you load a module with no version information using the FileVersionInfo class, you will not provoke an exception, nor will you get null back for the object reference. Instead, you will get a valid FileVersionInfo object with all data members in their initial state (which is null for .NET objects).

Assemblies actually have two sets of version information: the version information available in the assembly manifest and the PE (Portable Executable) file version information. FileVersionInfo reads the assembly manifest version information.

The first action this method takes is to determine whether the two files passed in to the file1 and file2 parameters actually exist. If so, the static GetVersionInfo method of the FileVersionInfo class is called to get version information for the two files.

The CompareFileVersions method attempts to compare each portion of the file's version number using the following properties of the FileVersionInfo object returned by GetVersionInfo:

FileMajorPart

The first 2 bytes of the version number

FileMinorPart

The second 2 bytes of the version number

FileBuildPart

The third 2 bytes of the version number

FilePrivatePart

The final 2 bytes of the version number

The full version number is comprised of these four parts, making up an 8-byte number representing the file's version number.

The CompareFileVersions method first compares the FileMajorPart version information of the two files. If these are equal, the FileMinorPart version information of the two files is compared. This continues through the FileBuildPart and finally the FilePrivatePart version information values। If all four parts are equal, the files are considered to have the same version number. If either file is found to have a higher number than the other file, it is considered to be the latest version.