Advertisements

Archive

Author Archive

How to access all types of server controls in ASP.Net using Javscript/JQuery OR Clear all server controls values using javascript or Jquery


How to access server side controls in ASP.Net using Javascript/JQuery

Using client side script such as JavaScript and Jquery, we can access all server side controls from ASPX page and it will get more performance on web application as it is not causing post back. While development we are frequently facing a feature to implement that “Clear All” function in the ASPX page. Suppose in a User Entry form, most probably there will be having a button for clear all values that user was trying to enter previously.

Get all textboxes, radio buttons and checkboxes  in an ASPX page from JavaScript

To access all server side textbox controls in an aspx page using JavaScript, we have to find all controls with tag name is input and type is text. Below mentioned code will access all textboxes in a aspx page from JavaScript and clear those values to empty. The type of the radio button is ‘radio’ and checkbox is ‘checkbox’.

        var elements = document.getElementsByTagName("input");
            for (var ii = 0; ii < elements.length; ii++) {
                if (elements[ii].disabled == false) {
                    if (elements[ii].type == "text") {
                        elements[ii].value = "";
                    }
                    if (elements[ii].type == "radio") {
                        elements[ii].checked = false;
                    }
                    if (elements[ii].type == "checkbox") {
                        elements[ii].checked = false;
                    }
                }
            }

Image

How to access dropdown list control in an ASPX Page using Javscript/JQuery

The tagname for the dropdownlist and listbox controls in an aspx page is ‘select’. We can access all dropdown list in a aspx page by checking tagname of each controls as same as below sample code.

var select = document.getElementsByTagName("select");
            var length = select.length;
            for (i = 0; i < length; i++) {
                for (var j = 0; j < select[i].length; j++) {
                    select[i][j].selected = false;
                }
            }

A simple example for accessing all server controls in an aspx page from javscript/jquery

We are demonstrating a sample web page containing different server controls like textbox, dropdownlist, checkbox, radiobutton, listbox etc.. and clearing all this values to default by using javscript/jquery. Here we are accessing all serverside controls without knowing their ids and names.

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”JqueryValidation.aspx.cs”

Inherits=”ExperimentLab.JqueryValidation” %>

<!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>Clear all server controls using Javascript</title>
    <style type="text/css">
        h1
        {
            font-style: italic;
            font-weight: bold;
            color: Gray;
            font-size: small;
            text-decoration: underline;
        }
        body
        {
            color: Purple;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div style="border: 1px solid black; padding: 20px; width: 60%;">
        <table>
            <tr>
                <td>
                    <h1>
                        TextBoxes</h1>
                </td>
            </tr>
            <tr>
                <td>
                    Name
                </td>
                <td>
                    <asp:TextBox ID="txtName" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    Age
                </td>
                <td>
                    <asp:TextBox ID="txtAge" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    <h1>
                        Dropdown Lists</h1>
                </td>
            </tr>
            <tr>
                <td>
                    Gender
                </td>
                <td>
                    <asp:DropDownList ID="ddlGender" runat="server" Width="150">
                        <asp:ListItem Text="Select" Value="0"></asp:ListItem>
                        <asp:ListItem Text="Male" Value="1"></asp:ListItem>
                        <asp:ListItem Text="Female" Value="2"></asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
                    Religion
                </td>
                <td>
                    <asp:DropDownList ID="DropDownList1" runat="server" Width="150">
                        <asp:ListItem Text="Select" Value="0"></asp:ListItem>
                        <asp:ListItem Text="Muslim" Value="1"></asp:ListItem>
                        <asp:ListItem Text="Christian" Value="2"></asp:ListItem>
                        <asp:ListItem Text="Hindu" Value="3"></asp:ListItem>
                        <asp:ListItem Text="Others" Value="4"></asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
                    <h1>
                        Radio Button Lists</h1>
                </td>
            </tr>
            <tr>
                <td>
                    Nationality
                </td>
                <td>
                    <asp:RadioButtonList ID="rdNationality" runat="server">
                        <asp:ListItem Text="India" Value="0" />
                        <asp:ListItem Text="Other" Value="1" />
                    </asp:RadioButtonList>
                </td>
            </tr>
            <tr>
                <td>
                    <h1>
                        Checkbox Lists</h1>
                </td>
            </tr>
            <tr>
                <td>
                    Languages Known
                </td>
                <td>
                    <asp:CheckBoxList ID="chkLanguages" runat="server">
                        <asp:ListItem Text="Malayalam" Value="0" />
                        <asp:ListItem Text="English" Value="1" />
                        <asp:ListItem Text="Spanish" Value="2" />
                    </asp:CheckBoxList>
                </td>
            </tr>
            <tr>
                <td>
                    <h1>
                        Listbox</h1>
                </td>
            </tr>
            <tr>
                <td>
                    Technical Skills
                </td>
                <td>
                    <asp:ListBox ID="lstSkills" runat="server" SelectionMode="Multiple" Width="150">
                        <asp:ListItem Text="ASP.Net" Value="1" />
                        <asp:ListItem Text="SQL Server" Value="2" />
                        <asp:ListItem Text="MVC" Value="3" />
                        <asp:ListItem Text="JQuery" Value="4" />
                        <asp:ListItem Text="Javscript" Value="5" />
                        <asp:ListItem Text="MySQL" Value="6" />
                    </asp:ListBox>
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                    <asp:Button runat="server" ID="btnClick" Text="Clear All"
                    OnClientClick="clearAllServerFields();" />
                </td>
            </tr>
        </table>
    </div>
    <script type="text/javascript" language="javascript">
        function clearAllServerFields() {

            //Code for accessing all dropdown lists and listboxes in an aspx page
            var select = document.getElementsByTagName("select");
            var length = select.length;
            for (i = 0; i < length; i++) {
                for (var j = 0; j < select[i].length; j++) {
                    select[i][j].selected = false;
                }
            }

            var elements = document.getElementsByTagName("input");
            for (var ii = 0; ii < elements.length; ii++) {
                if (elements[ii].disabled == false) {
                    //Code for accessing all textboxes in an aspx page
                    if (elements[ii].type == "text") {
                        elements[ii].value = "";
                    }
                    //Code for accessing all radio buttons in an aspx page
                    if (elements[ii].type == "radio") {
                        elements[ii].checked = false;
                    }
                    //Code for accessing all checkboxes in an aspx page
                    if (elements[ii].type == "checkbox") {
                        elements[ii].checked = false;
                    }
                }
            }
        }

    </script>
    </form>
</body>
</html>
Advertisements

How to implement Cache mechanism in ASP.Net/C# using simple example OR What is Output Caching and Fragment Caching in ASP.Net/C#

May 30, 2013 7 comments

What is Caching in ASP.NET AND How can get access to cache object?

ASP.NET Caching is used to build high-performance, scalable ASP.NET web applications by storing responses in memory. On subsequent requests, the page code is not executed and the cached output is used to serve the request. The Cache object is defined in the ‘System.Web.Caching’ namespace. You can get a reference to

the Cache object by using the Cache property of the HttpContext class in the ‘System.Web’

namespace or by using the Cache property of the Page object.

 

What are dependencies in cache and types of dependencies?

When you add an item to the cache, you can define dependency relationships that can force that

item to be removed from the cache under specific activities of dependencies. Example if the

cache object is dependent on file and when the file data changes you want the cache object to be

update. Following are the supported dependency:-

File dependency: – Allows you to invalidate a specific cache item when a disk

based file or files change.

Time-based expiration: – Allows you to invalidate a specific cache item depending

on predefined time.

Key dependency:- Allows you to invalidate a specific cache item depending when

another cached item changes.

 

What are different types of caching using cache object of ASP.NET?

You can use two types of output caching to cache information that is to be transmitted to and

displayed in a Web browser:

Page Output Caching

Page output caching adds the response of page to cache object. Later when

page is requested page is displayed from cache rather than creating the

page object and displaying it. Page output caching is good if the site is

fairly static.

Page Fragment Caching If parts of the page are changing, you can wrap the static sections as user

controls and cache the user controls using page fragment caching.

 

How will implement Page Output Caching?

Output cache functionality is achieved by using “OutputCache” attribute on ASP.NET page

header. Below is the syntax

<%@ OutputCache Duration="20" Location="Server" VaryByParam="state"VaryByCustom="minorversion" VaryByHeader="Accept-Language"%>
  • VaryByParam: – Caches different version depending on input parameters send

through HTTP POST/GET.

  • VaryByHeader: – Caches different version depending on the contents of the page

header.

  • VaryByCustom: –Lets you customize the way the cache handles page variations

by declaring the attribute and overriding the GetVaryByCustomString handler.

  • VaryByControl: –Caches different versions of a user control based on the value of

properties of ASP objects in the control.

 

Simple Example for Implementing Output Caching in ASP.Net/C#

Here we are going to demonstrate a very simple example for implementing ASP.Net Output Cache mechanism. In the below ASPX page we included Output Cache tage with duration of 20Sec. So the page will be cached for the next 20 Secs. After 20 Seconds, it will again loaded from the server.

 

Using Duration option

<%@ OutputCache Duration="20" VaryByParam="none" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OutputCaching.aspx.cs" Inherits="FragmentCaching.OutputCaching" %>
<!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>
</head>
<body>
    <form id="form1" runat="server">
   <div>
        <asp:Label ID="lblResult" runat="server"></asp:Label>        <br />
        <br />
        <asp:Button ID="btnPostBack" runat="server" Text="Post Back"  />
        <p>
            The page will be cached 20seconds, and then you can                   click Button to update datetime.
        </p>
    </div>
    </form>
</body>
</html>

 

Using VaryByControl option

<%@ OutputCache Duration="2000" VaryByControl="ddlOption" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>OutPut Cache Using VaryByControl Option</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblResult" runat="server"></asp:Label>        <br />
        <br />
        <asp:DropDownList ID="ddlOption" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlOption_SelectedIndexChanged"><asp:ListItem Selected="True">Option One</asp:ListItem>            <asp:ListItem>Option Two</asp:ListItem>
            <asp:ListItem>Option Three</asp:ListItem>
        </asp:DropDownList>
        <p>
            The page will be rendered from cache basing on the selected item of DropDownList.
            The different item has corresponding cache.
    </p>
    </div>
    </form>
</body>
</html>

 

Using VaryByCustom

<%@ OutputCache Duration="2000" VaryByCustom="browser" VaryByParam="none" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>OutPut Cache Using VaryByCustom Option</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblResult" runat="server"></asp:Label>        <br />
        <br />
        <asp:Button ID="btnPostBack" runat="server" Text="Submit" />
        <p>
            The page will be rendered from cache basing            on the version of browser, such as IE and FireFox.
        </p>
    </div>
    </form>
</body>
</html> 

Using VaryByParam

<%@ OutputCache Duration="2000" VaryByParam="productID" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="myHeader" runat="server">
    <title>OutPut Cache Using VaryByParam Option</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblResult" runat="server"></asp:Label>
        <p>
            The page will be rendered from cache until the value of QueryString named "productID" is changed or Duration is expiration.        </p>
    </div>
    </form>
</body>
</html>

 

How will implement Page Fragment Caching?

 

FragmentCaching.aspx:

Fragment caching is useful when you need to cache only a subset of a page. Navigation bars, header, and footers are good candidates for fragment caching. Here we are creating a ASPX page with two usercontrols inside it. We can control the caching of each usercontrols using fragment option as follows.

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FragmentCaching.aspx.cs" Inherits="ExperimentLab.FragmentCaching" %>
<%@ Register TagPrefix="uc1" TagName="FragmentCtrl1" Src="FragmentCtrl1.ascx" %>
<%@ Register TagPrefix="uc1" TagName="FragmentCtrl2" Src="FragmentCtrl2.ascx" %>
<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p>
            WebForm Time:
            <asp:Label ID="Time" runat="server" ForeColor="Blue"></asp:Label>
        </p>
        <p>
            <uc1:FragmentCtrl1 ID="FragmentCtrl11" runat="server"></uc1:FragmentCtrl1>
        </p>
        <p>
            <uc1:FragmentCtrl2 ID="FragmentCtrl21" runat="server"></uc1:FragmentCtrl2>
        </p>
    </div>
    </form>
</body>
</html>

 

CodeBehind

protected void Page_Load(object sender, EventArgs e)        
{           
Time.Text = "WebFormTime: " + DateTime.Now.TimeOfDay.ToString();  }

FragmentCtrl1.ascx:

<%@ OutputCache Duration="40" VaryByParam="none"%>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FragmentCtrl1.ascx.cs" Inherits="ExperimentLab.FragmentCtrl1" %>
<asp:Label ID="CacheEntryTime" runat="server"></asp:Label>

 

CodeBehind :

protected void Page_Load(object sender, EventArgs e)        
{            
CacheEntryTime.Text = "FragmentCtrl1: " + DateTime.Now.TimeOfDay.ToString();       
}

 

FragmentCtrl2.ascx:

<%@ OutputCache Duration="60" VaryByParam="none" VaryByControl="MyRadioButtonList"%>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FragmentCtrl2.ascx.cs" Inherits="ExperimentLab.FragmentCtrl2" %>
<asp:Label ID="CacheEntryTime" runat="server"></asp:Label>
<p>
    <asp:RadioButtonList ID="MyRadioButtonList" runat="server">        <asp:ListItem Selected="True">Yes</asp:ListItem>
        <asp:ListItem>No</asp:ListItem>
        <asp:ListItem>Maybe</asp:ListItem>
    </asp:RadioButtonList>
</p>
<p>
    <asp:Button ID="Button1" runat="server" Text="Submit" />
</p>

 

Code Behind :

protected void Page_Load(object sender, EventArgs e)        
{           
CacheEntryTime.Text = "FragmentCtrl2: " + DateTime.Now.TimeOfDay.ToString();       
}

How to implement CAPTCHA image validation in ASP.Net/C# OR CAPTCHA image validator Sample in ASP.Net/C#

May 6, 2013 2 comments

                                   DOWNLOAD SOURCE CODE FOR CAPTCHA IMAGE VALIDATION IN ASP.NET

What is CAPTCHA and why we are using CAPTCHA

A CAPTCHA  is a type of challenge-response test used in computing as an attempt to ensure that the response is generated by a human being. The process usually involves a computer asking a user to complete a simple test which the computer is able to grade. These tests are designed to be easy for a computer to generate but difficult for a computer to solve, but again easy for a human. If a correct solution is received, it can be presumed to have been entered by a human. A common type of CAPTCHA requires the user to type letters and/or digits from a distorted image that appears on the screen. Such tests are commonly used to prevent unwanted internet bots from accessing websites, since a normal human can easily read a CAPTCHA, while the bot cannot process the image letters and therefore, cannot answer properly, or at all.

How to implement CAPTCHA validation/CAPTCHA verification in ASP.Net/C#

CAPTCHA image can be generated using ASP.Net codes and we can validate the code that user enter with the code in the CAPTCHA image. Here we are going to do a sample application that demonstrates how to create a CAPTCHA image using C# codes and how we can validate the user inputs with the CPATCH code. We are having two aspx pages and one class .cs file in the sample application.

A very simple application sample for CPTCHA validation

In the page load, first of all we are creating a 6 digit random number and stored in the session. By using this random number we creates a image suing System.Drawing package by giving some width,height,font family and alignment of the numbers, So the user can able to view the codes in the CAPTCHA image but it is difficult to read using system.

DOWNLOAD SOURCE CODE FOR CAPTCHA IMAGE VALIDATION IN ASP.NET

Below is the Class that we used for creating a CAPTCHA image with random number

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;

namespace CaptchaImage
{
       /// <summary>
       /// Summary description for CaptchaImage.
       /// </summary>
       public class CaptchaImage
       {
              // Public properties (all read-only).
              public string Text
              {
                     get { return this.text; }
              }
              public Bitmap Image
              {
                     get { return this.image; }
              }
              public int Width
              {
                     get { return this.width; }
              }
              public int Height
              {
                     get { return this.height; }
              }

              // Internal properties.
              private string text;
              private int width;
              private int height;
              private string familyName;
              private Bitmap image;

              // For generating random numbers.
              private Random random = new Random();

              // ====================================================================
              // Initializes a new instance of the CaptchaImage class using the
              // specified text, width and height.
              // ====================================================================
              public CaptchaImage(string s, int width, int height)
              {
                     this.text = s;
                     this.SetDimensions(width, height);
                     this.GenerateImage();
              }

              // ====================================================================
              // Initializes a new instance of the CaptchaImage class using the
              // specified text, width, height and font family.
              // ====================================================================
              public CaptchaImage(string s, int width, int height, string familyName)
              {
                     this.text = s;
                     this.SetDimensions(width, height);
                     this.SetFamilyName(familyName);
                     this.GenerateImage();
              }

              // ====================================================================
              // This member overrides Object.Finalize.
              // ====================================================================
              ~CaptchaImage()
              {
                     Dispose(false);
              }

              // ====================================================================
              // Releases all resources used by this object.
              // ====================================================================
              public void Dispose()
              {
                     GC.SuppressFinalize(this);
                     this.Dispose(true);
              }

              // ====================================================================
              // Custom Dispose method to clean up unmanaged resources.
              // ====================================================================
              protected virtual void Dispose(bool disposing)
              {
                     if (disposing)
                           // Dispose of the bitmap.
                           this.image.Dispose();
              }

              // ====================================================================
              // Sets the image width and height.
              // ====================================================================
              private void SetDimensions(int width, int height)
              {
                     // Check the width and height.
                     if (width <= 0)
                           throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.");
                     if (height <= 0)
                           throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.");
                     this.width = width;
                     this.height = height;
              }

              // ====================================================================
              // Sets the font used for the image text.
              // ====================================================================
              private void SetFamilyName(string familyName)
              {
                     // If the named font is not installed, default to a system font.
                     try
                     {
                           Font font = new Font(this.familyName, 12F);
                           this.familyName = familyName;
                           font.Dispose();
                     }
                     catch (Exception ex)
                     {
                           this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
                     }
              }

              // ====================================================================
              // Creates the bitmap image.
              // ====================================================================
              private void GenerateImage()
              {
                     // Create a new 32-bit bitmap image.
                     Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);

                     // Create a graphics object for drawing.
                     Graphics g = Graphics.FromImage(bitmap);
                     g.SmoothingMode = SmoothingMode.AntiAlias;
                     Rectangle rect = new Rectangle(0, 0, this.width, this.height);

                     // Fill in the background.
                     HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White);
                     g.FillRectangle(hatchBrush, rect);

                     // Set up the text font.
                     SizeF size;
                     float fontSize = rect.Height + 1;
                     Font font;
                     // Adjust the font size until the text fits within the image.
                     do
                     {
                           fontSize--;
                           font = new Font(this.familyName, fontSize, FontStyle.Bold);
                           size = g.MeasureString(this.text, font);
                     } while (size.Width > rect.Width);

                     // Set up the text format.
                     StringFormat format = new StringFormat();
                     format.Alignment = StringAlignment.Center;
                     format.LineAlignment = StringAlignment.Center;

                     // Create a path using the text and warp it randomly.
                     GraphicsPath path = new GraphicsPath();
                     path.AddString(this.text, font.FontFamily, (int) font.Style, font.Size, rect, format);
                     float v = 4F;
                     PointF[] points =
                     {
                           new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
                           new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
                            new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),
                           new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v)
                     };
                     Matrix matrix = new Matrix();
                     matrix.Translate(0F, 0F);
                     path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);

                     // Draw the text.
                     hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray);
                     g.FillPath(hatchBrush, path);

                     // Add some random noise.
                     int m = Math.Max(rect.Width, rect.Height);
                     for (int i = 0; i < (int) (rect.Width * rect.Height / 30F); i++)
                     {
                           int x = this.random.Next(rect.Width);
                           int y = this.random.Next(rect.Height);
                           int w = this.random.Next(m / 50);
                           int h = this.random.Next(m / 50);
                           g.FillEllipse(hatchBrush, x, y, w, h);
                     }

                     // Clean up.
                     font.Dispose();
                     hatchBrush.Dispose();
                     g.Dispose();

                     // Set the image.
                     this.image = bitmap;
              }
       }
}

DOWNLOAD SOURCE CODE FOR CAPTCHA IMAGE VALIDATION IN ASP.NET

How to implement SQL Bulk Copy in SQL Server OR Bulk insert into SQL Server using SQL BulkCopy

October 17, 2012 1 comment

SqlBulkCopy for insert multiple rows of data into table in SQL Server

Sometimes we need to insert bulk amount of data into a table in SQL. We can insert bulk data to SQL in different methods. Here we are going to demonstrate how to insert large amount of data using SQL Bulk Copy method.

Example of SQL BulkCopy method

Here we are going to insert multiple rows of sample data into Employee table. First of all create a table in SQL named Employee. After that  create sample data for employee table and finally this multiple rows of employee data insert into table using SQL bulk copy method.

Create a Table in SQL 

CREATE TABLE Employee
(
ID INT,
EmpName varchar(200),
Department varchar(200),
DOB DateTime
);

SQLMulkCopy Example in SQL Server

SQLMulkCopy Example in SQL Server

C# Code to generate sample data and insertion using SQL Bulk Copy

private void loadDataBySQLBulkCopy()
        {
            DataTable dtTblEmployee = new DataTable();
            dtTblEmployee.Columns.Add("ID", typeof(Int32));
            dtTblEmployee.Columns.Add("EmpName", typeof(String));
            dtTblEmployee.Columns.Add("Department", typeof(String));
            dtTblEmployee.Columns.Add("DOB", typeof(DateTime));

            DataRow dtrow = dtTblEmployee.NewRow(); // Create New Row
            dtrow["ID"] = 1; //Bind Data to Columns
            dtrow["EmpName"] = "Wazeem";
            dtrow["Department"] = "Admin";
            dtrow["DOB"] = "1990-10-16 12:00:00.000";
            dtTblEmployee.Rows.Add(dtrow);

            dtrow = dtTblEmployee.NewRow(); // Create New Row
            dtrow["ID"] = 2; //Bind Data to Columns
            dtrow["EmpName"] = "Aslam";
            dtrow["Department"] = "HR";
            dtrow["DOB"] = "1987-05-16 12:00:00.000";
            dtTblEmployee.Rows.Add(dtrow);

            dtrow = dtTblEmployee.NewRow(); // Create New Row
            dtrow["ID"] = 3; //Bind Data to Columns
            dtrow["EmpName"] = "John";
            dtrow["Department"] = "Finance";
            dtrow["DOB"] = "1992-12-11 12:00:00.000";
            dtTblEmployee.Rows.Add(dtrow);

            dtrow = dtTblEmployee.NewRow(); // Create New Row
            dtrow["ID"] = 4; //Bind Data to Columns
            dtrow["EmpName"] = "Mishal";
            dtrow["Department"] = "Infra structure";
            dtrow["DOB"] = "1989-04-01 12:00:00.000";
            dtTblEmployee.Rows.Add(dtrow);

            SqlBulkCopy bulkCopy = new SqlBulkCopy(
                "server=TEST;database=TEST;uid=test;password=test",
                SqlBulkCopyOptions.TableLock);
            bulkCopy.DestinationTableName = "dbo.Employee";
            bulkCopy.WriteToServer(dtTblEmployee);

        }

How to merge two data tables in ASP.Net/C# OR Merge 2 DataTables and store in a new one in ASP.Net/C#

October 14, 2012 Leave a comment

Merge multiple data-tables data into a another data-table using C#/ASP.Net

Here we are going to demonstrate a sample application which shows merge two data tables  in ASP.Net. In this sample we are having two data tables with some data and merge data of each tables data. We binds first data table to a data grid second one to another grid and third data grid binds with merged data table.

Merge data tables in C#/ASP.Net

Merge data tables in C#/ASP.Net

 

ASPX Page for Example of merge two datatables in C#/ASP.Net

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MergeDataTable.aspx.cs"
 Inherits="ExperimentLab.MergeDataTable" %>
<!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>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 First DataTable
 <asp:GridView ID="gdDataTableOne" runat="server" /><br />
 Second DataTable
 <asp:GridView ID="gdDataTableTwo" runat="server" /><br />
 Merged DattaTable
 <asp:GridView ID="gdDataTableMergedData" runat="server" /><br />
 </div>
 </form>
</body>
</html>
-*******

CODE BEHIND Page for Merge datatable in C#/ASP.Net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace ExperimentLab
{
 public partial class MergeDataTable : System.Web.UI.Page
 {
 DataTable dtOne = new DataTable();
 DataTable dtTwo = new DataTable();
protected void Page_Load(object sender, EventArgs e)
 {
 fillDataTableOne();
 fillDataTableTwo();
 mergeDataTables();
 }
private void mergeDataTables()
 {
 dtOne.Merge(dtTwo, false);
 gdDataTableMergedData.DataSource = dtOne;
 gdDataTableMergedData.DataBind();
 }
private void fillDataTableOne()
 { 
 dtOne.Columns.Add("EmpID", typeof(Int32));
 dtOne.Columns.Add("EmployeeName", typeof(string));
 dtOne.Columns.Add("Department", typeof(string));
 dtOne.Columns.Add("City", typeof(string));
DataRow dtOnerow = dtOne.NewRow(); // Create New Row
 dtOnerow["EmpID"] = 1; //Bind Data to Columns
 dtOnerow["EmployeeName"] = "Ram";
 dtOnerow["Department"] = "Admin";
 dtOnerow["City"] = "Kochi";
 dtOne.Rows.Add(dtOnerow);
dtOnerow = dtOne.NewRow(); // Create New Row
 dtOnerow["EmpID"] = 2; //Bind Data to Columns
 dtOnerow["EmployeeName"] = "Mahesh";
 dtOnerow["Department"] = "Finance";
 dtOnerow["City"] = "Delhi";
 dtOne.Rows.Add(dtOnerow);
dtOnerow = dtOne.NewRow(); // Create New Row
 dtOnerow["EmpID"] = 3; //Bind Data to Columns
 dtOnerow["EmployeeName"] = "Raj";
 dtOnerow["Department"] = "Admin";
 dtOnerow["City"] = "Kolkata";
 dtOne.Rows.Add(dtOnerow);
dtOnerow = dtOne.NewRow(); // Create New Row
 dtOnerow["EmpID"] = 4; //Bind Data to Columns
 dtOnerow["EmployeeName"] = "Virbal";
 dtOnerow["Department"] = "HR";
 dtOnerow["City"] = "Mumbai";
 dtOne.Rows.Add(dtOnerow);
gdDataTableOne.DataSource = dtOne;
 gdDataTableOne.DataBind();
 }
private void fillDataTableTwo()
 {
dtTwo.Columns.Add("EmpID", typeof(Int32));
 dtTwo.Columns.Add("EmployeeName", typeof(string));
 dtTwo.Columns.Add("Department", typeof(string));
 dtTwo.Columns.Add("City", typeof(string));
DataRow dtTworow = dtTwo.NewRow(); // Create New Row
 dtTworow["EmpID"] = 5; //Bind Data to Columns
 dtTworow["EmployeeName"] = "John";
 dtTworow["Department"] = "Delivery";
 dtTworow["City"] = "Goa";
 dtTwo.Rows.Add(dtTworow);
dtTworow = dtTwo.NewRow(); // Create New Row
 dtTworow["EmpID"] = 6; //Bind Data to Columns
 dtTworow["EmployeeName"] = "Jacob";
 dtTworow["Department"] = "Finance";
 dtTworow["City"] = "Kolkata";
 dtTwo.Rows.Add(dtTworow);
dtTworow = dtTwo.NewRow(); // Create New Row
 dtTworow["EmpID"] = 7; //Bind Data to Columns
 dtTworow["EmployeeName"] = "Srini";
 dtTworow["Department"] = "HR";
 dtTworow["City"] = "Jaipur";
 dtTwo.Rows.Add(dtTworow);
dtTworow = dtTwo.NewRow(); // Create New Row
 dtTworow["EmpID"] = 8; //Bind Data to Columns
 dtTworow["EmployeeName"] = "Gopal";
 dtTworow["Department"] = "InfraStructure";
 dtTworow["City"] = "Chennai";
 dtTwo.Rows.Add(dtTworow);
gdDataTableTwo.DataSource = dtTwo;
 gdDataTableTwo.DataBind();
 }
 
 }
}




How to implement Password validation in ASP.Net/C# OR Implement Password strength using Jquery in ASP.Net

October 10, 2012 1 comment

 

DOWNLOAD SOURCE CODE FOR PASSWORD STRENGTH CHECKER

How to show Password Strength image to user in ASP.Net

Register/change password pages on most of the application showing password strength information to user while entering password in the textbox. It allows to user to enter a strong password for register the pages. We can implement Password Strength Checker in different methods in ASP.Net application. Its better to do it in the client side itself so that user doesn’t feels post back in the page.

Implement Password Strength Checker using Jquery

Here we are going to demonstrate a sample application to implement Password Strength Checker using Jquery. The application shows the status of entered password by each alphabet changes in the textbox such as Week, Good, Strong etc..

Password_Strength_Checker

ASPX/HTML Page for Password Strength Checker  

<!DOCTYPE html>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title>jQuery Validation Plugin Password Extension demo</title>
 <link rel="stylesheet" type="text/css" media="screen" href="../jquery.validate.password.css" />
 <script type="text/javascript" src="../lib/jquery.js"></script>
 <script type="text/javascript" src="../lib/jquery.validate.js"></script>
 <script type="text/javascript" src="../jquery.validate.password.js"></script>
 <script id="demo" type="text/javascript">
 $(document).ready(function () {
 $("#register").validate();
 $("#password").valid();
});
</script>
 <style>
 label, input
 {
 float: left;
 }
 input
 {
 margin-left: 1em;
 }
 label.error
 {
 display: none !important;
 }
 .password-meter
 {
 float: left;
 }
 </style>
</head>
<body>
 <form id="register">
 <div>
 Password Strength Checker Demo Using JQuery.. 
powered by <a href="http://tuvian.con">
 tuvian</a>
 </div>
 <br />
 <br />
 <label for="password">
 Password:</label>
 <input class="password" name="password" id="password" />
 <div class="password-meter">
 <div class="password-meter-message">
 &nbsp;</div>
 <div class="password-meter-bg">
 <div class="password-meter-bar">
 </div>
 </div>
 </div>
 </form>
</body>
</html>

 

DOWNLOAD SOURCE CODE FOR PASSWORD STRENGTH CHECKER

 

How to create breadcrumbs in ASP.Net/C# OR Show Navigations for each pages in ASP.Net/C# OR How to implement Sitemap in ASP.Net

October 2, 2012 4 comments

DOWNLOAD SOURCE CODE FOR BREADCRUMB EXAMPLE IN ASP.NET

What is breadcrumbs and what is the use of it?

Breadcrumbs typically appear horizontally across the top of a web page, often below title bars or headers. They provide links back to each previous page the user navigated through to get to the current page or-in hierarchical site structures-the parent pages of the current one. Breadcrumbs provide a trail for the user to follow back to the starting or entry point. A greater-than sign (>) often serves as hierarchy separator, although designers may use other glyphs <http://en.wikipedia.org/wiki/Glyph>  (such as » or >), as well as various graphical treatments.

Typical breadcrumbs look like this:

 Home page > Section page > Subsection page

How to implement breadcrumbs in ASP.Net/C# pages

In order to implement breadcrumbs in ASPX pages, we can use new pages called sitemaps. In ASP.NET the menu can be stored in a file to make it easier to maintain. This file is normally calledweb.sitemap, and is stored in the root directory of the web.

DOWNLOAD SOURCE CODE FOR BREADCRUMB EXAMPLE IN ASP.NET

BREADCRUMB EXAMPLE IN ASP.NET

Example for implementing sitemaps in ASP.Net/C# pages

We are going to demonstrate sample ASP.Net application for implementing Breadcrumbs in ASPX pages. First of all create a new ASP.Net project and create three pages home.aspx, aboutus.aspx  and contactus.aspx.  Then create a sitemap file by “Add New item > SiteMap” and mention the hierarchy of the pages in the sitemaps as follows

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

  <siteMapNode url="Default.aspx" title="Home"  description="Home Page">
    <siteMapNode url="ContactUs.aspx" title="Contact US" 
                 description="Contact US Page" />
    <siteMapNode url="About.aspx" title="About"  description="About " >
      <siteMapNode url="AboutCompany.aspx" title="About Company" 
                   description="About Our Company" />
      <siteMapNode url="AboutService.aspx" title="About Service" 
                   description="About Our Services" />
    </siteMapNode>
  </siteMapNode>
</siteMap>

Once we created sitemap and mentioned the hierarchy of the pages we need to map this sitemaps into all pages that we need to show navigation as follows.

<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
    <asp:SiteMapPath ID="SiteMap1" runat="server">
    </asp:SiteMapPath>

Sample Application of Navigation Menu/Bread Crumbs  

web.sitemap

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
  <siteMapNode url="Default.aspx" title="Home"  description="Home Page">
    <siteMapNode url="ContactUs.aspx" title="Contact US" 
                 description="Contact US Page" />
    <siteMapNode url="About.aspx" title="About"  description="About " >
      <siteMapNode url="AboutCompany.aspx" title="About Company" 
                   description="About Our Company" />
      <siteMapNode url="AboutService.aspx" title="About Service" 
                   description="About Our Services" />
    </siteMapNode>
  </siteMapNode>
</siteMap>

 About.aspx

<%@ Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="About.aspx.cs" Inherits="BreadCrumb.About" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
    <asp:SiteMapPath ID="SiteMap1" runat="server">
    </asp:SiteMapPath>
    <h2>
        Welcome TO About US Page
    </h2>
    <br />
    <a href="AboutCompany.aspx" runat="server">About Our Company</a>
    <br />
    <a id="A1" href="AboutService.aspx" runat="server">About Our Services</a>
</asp:Content>

Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="BreadCrumb._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:SiteMapPath ID="SiteMap1" runat="server">
    </asp:SiteMapPath>
    <h2>
        Welcome to HOME PAGE
    </h2> 
</asp:Content>

 

 

AboutCompany.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
    CodeBehind="AboutCompany.aspx.cs" Inherits="BreadCrumb.AboutCompany" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
    <asp:SiteMapPath ID="SiteMap1" runat="server">
    </asp:SiteMapPath>
    <h2>
        This is the Page showing about our Company
    </h2>
</asp:Content>

AboutService.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
    CodeBehind="AboutService.aspx.cs" Inherits="BreadCrumb.AboutService" %>
 <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
    <asp:SiteMapPath ID="SiteMap1" runat="server">
    </asp:SiteMapPath>
    <h2>
        This is the Page showing about our Service
    </h2>
</asp:Content>
-


            DOWNLOAD SOURCE CODE FOR BREADCRUMB EXAMPLE IN ASP.NET
%d bloggers like this: