Sunday 2 August 2015

What are the different validators in ASP.NET?

Validations are the most important part of websites and software. By using validations we can restrict users to enter any Invalid data into your database. There are many  validation techniques available do validate form data like JQUERY validations, server side validations. In Asp .Net microsoft has provided us great validation controls.  In this series of articles we will explore validation controls provided by microsoft.


  1. Required field Validator
  2. Range Validator
  3. Compare Validator
  4. Custom Validator
  5. Regular expression Validator
  6. Summary Validator

1.     Required field Validator
The RequiredFieldValidator is actually very simple, and yet very useful. You can use it to make sure that the user has entered something in a TextBox control.

Step1: Create TextBox control, Validation Control and Button.
Step2: Use ErrorMessage property of RequiredFieldValidator and enter message you want to display.
Step3: Use ControlToValidate property of RequiredFieldValidator and enter id of TextBox which you want to validate.
Step4: Use ForeColor property of RequiredFieldValidator and enter name of the color you want to use

<table border="0" cellpadding="0" cellspacing="0">
        <tbody><tr>
            <td>
                <b>Enter Your Name </b>
                <asp:textbox runat="server" id="txtTestForRequiredField">
            </asp:textbox></td>
        </tr>
        <tr>
            <td>
                <asp:requiredfieldvalidator id="RequiredFieldValidator1" forecolor="Red" errormessage="Please enter your name" controltovalidate="txtTestForRequiredField" runat="server">
            </asp:requiredfieldvalidator></td>
        </tr>
        <tr>
            <td>
                <asp:button id="Button1" text="Save" runat="server">
            </asp:button></td>
        </tr>
    </tbody></table>.




What is the difference between Server.Transfer and Response.Redirect?


In Server.Transfer page processing transfers from one page to the other page without making a round-trip back to the client’s browser. This provides a faster response with a little less overhead on the server. The clients url history list or current url Server does not update in case of Server.Transfer.

Response.Redirect is used to redirect the user’s browser to another page or site. It performs trip back to the client where the client’s browser is redirected to the new page. The user’s browser history list is updated to reflect the new address.

What is ASP Dot Net?


It is a framework developed by Microsoft on which we can develop new generation web sites using web forms(aspx), MVC, HTML, JavaScript, CSS etc. Its successor of Microsoft Active Server Pages(ASP). Currently there is ASP.NET 4.5, which is used to develop web sites. There are various page extensions provided by Microsoft that are being used for web site development. Eg: aspx, asmx, ascx, ashx, cs, vb, html, XML etc.

What is delegate???

Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.

Syntax of Delegate & Methods Declaration

Check below sample code for delegate declaration and methods declaration

public delegate int Delegatmethod(int a,int b);

public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x + y;
}
}

















If you observe above code I declared Delegatmethod method with two parameters which matching with methods declared in Sampleclass class.

Complete Example

public delegate int DelegatSample(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();

DelegatSample delgate1 = sc.Add;
int i = delgate1(10, 20);
Console.WriteLine(i);
DelegatSample delgate2 = sc.Sub;
int j = delgate2(20, 10);
Console.WriteLine(j);
}
}
























Output

Whenever we run above code we will get output like as shown below


Add Result : 30
Sub Result : 10

What is the use of Delegates?

Suppose if you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.

Delegates are two types

      -   Single Cast Delegates
      -  Multi Cast Delegates

Single Cast Delegates

Single cast delegate means which hold address of single method like as explained in above example.

Multicast Delegates



Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=

Multicast delegates will work only for the methods which have return type only void. If we want to create a multicast delegate with return type we will get the return type of last method in the invocation list

Check below sample code for delegate declaration and methods declaration



Syntax of Multicast Delegate & Method Declaration

Check below sample code for multicast delegate declaration and methods declaration


public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
If you observe above code I declared MultiDelegate method with void return type.

Complete Example


public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}
Output



Whenever we run above code we will get output like as shown below


Addition Value : 15
Subtraction Value : 5
Multiply Value : 50


how to create stored procedure using asp.net for beginner.



for example: first of all we have to create table.

Table- StudentInfo

SID
int
Name
Varchar(100)
Class
Varchar(100)
FatherName
Varchar(100)
Address
Varchar(200)
ContactNo
bigint

In which table  SID(columns) is an identity .
syntax here..

create table StudentInfo
(
SID                 int identity(1,1),
Name              varchar(100),
Class               varchar(100),
FatherName    varchar(100),
Address           varchar(200),
ContactNo.      bigint
)

execute in sql...

now we learn how to insert data using stored procedure.

first of all we should be know what is stored procedure.  please read my previous article in which i have written about procedure.

Now we  have to create stored procedure. when you create stored procedure you can use these two words proc/procedure for creating the procedure

Create proc sp_studentinfo
@Name      varchar(100),
@Class       varchar(100),
@FatherName  varchar(100),
@Address         varchar(200),
@Contact          bigint
as
      begin
             
          insert into StudentInfo(Name,Class,FatherName,Address,Contact) values(@Name,@Class,@FatherName,@Address,@Contact)

end

here studentinfo.aspx.cs page


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class student : System.Web.UI.Page
{
    SqlConnection con = new           SqlConnection(ConfigurationManager.AppSettings["ConString"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("sp_studentinfo", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Name",txtname.Text);
        cmd.Parameters.AddWithValue("@Class", txtclass.Text);
        cmd.Parameters.AddWithValue("@Address",txtaddress.Text);
        cmd.Parameters.AddWithValue("@FatherName",txtefname.Text);
        cmd.Parameters.AddWithValue("@Contact", txtmob.Text);
        con.Open();
        int i=cmd.ExecuteNonQuery();
        if (i == 1)
        {
            Label1.Text = "Data Successfully inserted...";
        }
        else
        {
            Label1.Text = "Try Again";
        }
        con.Close();

    }
}

here studentinfo.aspx



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


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1
        {
            width: 100%;
        }
        .auto-style2
        {
            height: 23px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <table class="auto-style1">
            <tr>
                <td>Name</td>
                <td>
                    <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="auto-style2">Class</td>
                <td class="auto-style2">
                    <asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
                </td>
                <td class="auto-style2"></td>
            </tr>
            <tr>
                <td class="auto-style2">Father Name</td>
                <td class="auto-style2">
                    <asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
                </td>
                <td class="auto-style2"></td>
            </tr>

            <tr>

                <td class="auto-style2">Address</td>
                <td class="auto-style2">
                    <asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
                </td>
                <td class="auto-style2"></td>
            </tr>
            <tr>
                <td class="auto-style2">Contact</td>
                <td class="auto-style2">
                    <asp:TextBox ID="txtmob" runat="server"></asp:TextBox>
                </td>
                <td class="auto-style2"></td>
            </tr>
            <tr>
                <td class="auto-style2"></td>
                <td class="auto-style2"></td>
                <td class="auto-style2"></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                </td>
                <td>&nbsp;</td>
            </tr>
        </table>
    
    </div>
    </form>
</body>
</html>



Wednesday 29 April 2015

What is Stored Procedure??


SQL Server Stored Procedure

(Introduction) 
 
Overview
A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again.  So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a stored procedure and then just call the stored procedure to execute the SQL code that you saved as part of the stored procedure.
In addition to running the same SQL code over and over again you also have the ability to pass parameters to the stored procedure, so depending on what the need is the stored procedure can act accordingly based on the parameter values that were passed.
Take a look through each of these topics to learn how to get started with stored procedure development for SQL Server.
You can either use the outline on the left or click on the arrows to the right or below to scroll through each of these topics.

how to get country Name using IP Address in asp.net

 public string GetCountryByIP(string ipAddress)
    {
        string strReturnVal;
        //string ipResponse = IPRequestHelper("http://api.ipinfodb.com/v3/ip-country/?key=(api key deleted for security purposes)&ip=" + ipAddress);
        //string ipResponse = IPRequestHelper("http://iplocationtools.com/ip_location_api.php?ip={0}" + ipAddress);
        string ipResponse = IPRequestHelper(" http://ip-api.com/xml/?ip=" + ipAddress);
 

        //return ipResponse;
        XmlDocument ipInfoXML = new XmlDocument();
        ipInfoXML.LoadXml(ipResponse);
        XmlNodeList responseXML = ipInfoXML.GetElementsByTagName("query");

        NameValueCollection dataXML = new NameValueCollection();

        dataXML.Add(responseXML.Item(0).ChildNodes[2].InnerText, responseXML.Item(0).ChildNodes[2].Value);

        strReturnVal = responseXML.Item(0).ChildNodes[1].InnerText.ToString(); // Contry
        strReturnVal += "(" + responseXML.Item(0).ChildNodes[2].InnerText.ToString() + ")";  // Contry Code
        return strReturnVal;
    }

    public string IPRequestHelper(string url)
    {

        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();

        StreamReader responseStream = new StreamReader(objResponse.GetResponseStream());
        string responseRead = responseStream.ReadToEnd();

        responseStream.Close();
        responseStream.Dispose();

        return responseRead;
    }

Get Data from Gridview into Datatable in Asp.net using C#, VB.NET

Categories: Asp.net , C#.Net , Gridview , VB.NET , XML
Introduction:

Here I will explain how to get data from gridview to datatable in asp.net using c#, vb.net or fetch or get gridview data and insert into datatable in asp.net or get gridview data into dataset using c#, vb.net with example.

Description:
 
In previous articles I explained insert selected gridview rows into database in asp.net, take database backup in sql server 2008, encrypt and decrypt passwords in sql server 2008, Google Map show info windows when click on marker in asp.net, Delete multiple rows in gridview using checkbox in asp.net and many articles relating to gridview, asp.net, c#,vb.net and jQuery. Now I will explain how get data from  gridview to datatable in asp.net using c#, vb.net.

To get data from gridview and insert into datatable we need to write the code like as shown below

C# Code


DataTable dt = new DataTable();
dt.Columns.Add("userid", typeof(int));
dt.Columns.Add("username", typeof(string));
dt.Columns.Add("firstname", typeof(string));
dt.Columns.Add("lastname", typeof(string));
dt.Columns.Add("designation", typeof(string));
foreach (GridViewRow row in gvDetails.Rows)
{
int userid = int.Parse(row.Cells[0].Text);
string firstname = row.Cells[1].Text;
string lastname= row.Cells[2].Text;
string username = row.Cells[3].Text;
string designation = row.Cells[4].Text;
dt.Rows.Add(userid,username,firstname, lastname, designation);
}

VB.NET Code


Dim dt As New DataTable()
dt.Columns.Add("userid", GetType(Integer))
dt.Columns.Add("username", GetType(String))
dt.Columns.Add("firstname", GetType(String))
dt.Columns.Add("lastname", GetType(String))
dt.Columns.Add("designation", GetType(String))
For Each gvrow As GridViewRow In gvDetails.Rows
'Find checkbox control in gridview for particular row
Dim chkSelect As CheckBox = DirectCast(gvrow.FindControl("chkSelect"), CheckBox)
'Condition to check checkbox selected or not
If chkSelect.Checked Then
Dim userid As Integer = Integer.Parse(gvrow.Cells(1).Text)
Dim username As String = gvrow.Cells(2).Text
Dim firstname As String = gvrow.Cells(3).Text
Dim lastname As String = gvrow.Cells(4).Text
Dim designation As String = gvrow.Cells(5).Text
dt.Rows.Add(userid, username, firstname, lastname, designation)
End If
Next

If you want to check it in complete example first design one table EmployeeInfo in your database as shown below



Now create one new web application and open your aspx page and write the code like as shown below


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Insert Gridview Data to Database in Asp.net using SQLBulkCopy</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:gridview id="gvDetails" runat="server">
<headerstyle backcolor="#df5015" font-bold="true" forecolor="White">
</headerstyle></asp:gridview>
</div>
<br />
<asp:button font-bold="true" id="btnInsert" onclick="btnInsert_Click" runat="server" text="Insert Gridview Data"><br />
<asp:label id="lblMsg" runat="server">
</asp:label></asp:button></form>
</body>
</html>

Now right click on your application à Select Add New Item à Select XML file à Give name as “sample.xml” and click OK

Once we add xml file open it and write code like as shown below



<users>
<user>
<userid>1</userid>
<firstname>Suresh</firstname>
<lastname>Dasari</lastname>
<username>SureshDasari</username>
<designation>Team Leader</designation>
</user>
<user>
<userid>2</userid>
<firstname>Mahesh</firstname>
<lastname>Dasari</lastname>
<username>MaheshDasari</username>
<designation>Software Developer</designation>
</user>
<user>
<userid>3</userid>
<firstname>Madhav</firstname>
<lastname>Yemineni</lastname>
<username>MadhavYemineni</username>
<designation>Business Analyst</designation>
</user>
</users>

After completion of xml file now open aspx page codebehind behind file and add following namespaces

C# Code


using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

After completion of adding namespaces you need to write the code like as shown below


DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Bind Data to Gridview
GetXMLData();
}
}
// This method is used to get xml node values and bind to gridview
protected void GetXMLData()
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("Sample.xml"));
dt = ds.Tables[0];
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
// Insert data in database using SqlBulkCopy
protected void btnInsert_Click(object sender, EventArgs e)
{
String strConnection = "Data Source=Suresh;Initial Catalog=MySampleDB;Integrated Security=True";
DataTable dt = new DataTable();
dt.Columns.Add("userid", typeof(int));
dt.Columns.Add("username", typeof(string));
dt.Columns.Add("firstname", typeof(string));
dt.Columns.Add("lastname", typeof(string));
dt.Columns.Add("designation", typeof(string));
foreach (GridViewRow row in gvDetails.Rows)
{
int userid = int.Parse(row.Cells[0].Text);
string firstname = row.Cells[1].Text;
string lastname= row.Cells[2].Text;
string username = row.Cells[3].Text;
string designation = row.Cells[4].Text;
dt.Rows.Add(userid,username,firstname, lastname, designation);
}
using (SqlConnection con = new SqlConnection(strConnection))
{
con.Open();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "EmployeeInfo";
sqlBulk.WriteToServer(dt);
con.Close();
}
lblMsg.Text = "Details Inserted Successfully";
lblMsg.ForeColor = System.Drawing.Color.Green;
}

VB.NET Code


Imports System.Data
Imports System.Web.UI.WebControls
Imports System.Data.SqlClient
Partial Class VBCode
Inherits System.Web.UI.Page
Private dt As New DataTable()
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
'Bind Data to Gridview
GetXMLData()
End If
End Sub
' This method is used to get xml node values and bind to gridview
Protected Sub GetXMLData()
Dim ds As New DataSet()
ds.ReadXml(Server.MapPath("Sample.xml"))
dt = ds.Tables(0)
gvDetails.DataSource = dt
gvDetails.DataBind()
End Sub
' Insert data in database using SqlBulkCopy
Protected Sub btnInsert_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim strConnection As [String] = "Data Source=Suresh;Initial Catalog=MySampleDB;Integrated Security=True"
Dim dt As New DataTable()
dt.Columns.Add("userid", GetType(Integer))
dt.Columns.Add("username", GetType(String))
dt.Columns.Add("firstname", GetType(String))
dt.Columns.Add("lastname", GetType(String))
dt.Columns.Add("designation", GetType(String))
For Each row As GridViewRow In gvDetails.Rows
Dim userid As Integer = Integer.Parse(row.Cells(0).Text)
Dim firstname As String = row.Cells(1).Text
Dim lastname As String = row.Cells(2).Text
Dim username As String = row.Cells(3).Text
Dim designation As String = row.Cells(4).Text
dt.Rows.Add(userid, username, firstname, lastname, designation)
Next
Using con As New SqlConnection(strConnection)
con.Open()
Dim sqlBulk As New SqlBulkCopy(strConnection)
'Give your Destination table name
sqlBulk.DestinationTableName = "EmployeeInfo"
sqlBulk.WriteToServer(dt)
con.Close()
End Using
lblMsg.Text = "Details Inserted Successfully"
lblMsg.ForeColor = System.Drawing.Color.Green
End Sub
End Class

</div>