Monday 29 July 2013

Framework and Platform

SOFTWARE FRAMEWORK
In computer programming, a software framework is an abstraction in which software providing generic functionality can be selectively changed by additional user-written code, thus providing application-specific software. A software framework is a universal, reusable software platform to develop applications, products and solutions. Software frameworks include support programs, compilers, code libraries, tool sets, and application programming interfaces (APIs) that bring together all the different components to enable development of a project or solution.
Frameworks contain key distinguishing features that separate them from normal libraries:
  1. inversion of control – In a framework, unlike in libraries or normal user applications, the overall program's flow of control is not dictated by the caller, but by the framework.[1]
  2. default behavior – A framework has a default behavior. This default behavior must be some useful behavior and not a series of no-ops.
  3. extensibility – A framework can be extended by the user usually by selective overriding or specialized by user code to provide specific functionality.
  4. non-modifiable framework code – The framework code, in general, is not allowed to be modified, excepting extensibility. Users can extend the framework, but not modify its code

Tuesday 23 July 2013

Row Command Event in Grid View



<asp:GridView ID="GridView1" runat="server"
                                        onrowcommand="GridView1_RowCommand" CellPadding="1" CellSpacing="2"
                                        GridLines="None" Width="850px">
                                        <Columns>
                                        <asp:TemplateField>
                                        <HeaderTemplate>Delete</HeaderTemplate>
                                        <ItemTemplate>
                                            <asp:Button ID="Button1" runat="server" Text="Delete" CommandName="DeleteRow"
                                                CommandArgument='<%#Eval("Message ID") %>' Height="24px" Width="81px" />
                                            <asp:ConfirmButtonExtender ID="ConfirmButtonExtender1" runat="server" TargetControlID="Button1" ConfirmText="You want to delete this Message.">
                                            </asp:ConfirmButtonExtender>
                                            </ItemTemplate>
                                           
                                            </asp:TemplateField>
                                             
                                              <asp:TemplateField>
                                       <HeaderTemplate>Read</HeaderTemplate>
                                            <ItemTemplate>
                                                <asp:Button ID="Button2" runat="server" Text="Read" CommandName="Select"
                                                    CommandArgument='<%#Eval("Message ID") %>' Height="25px" Width="80px" />
                                            </ItemTemplate>
                                            </asp:TemplateField>
                                        </Columns>
                                        <HeaderStyle BackColor="Blue" ForeColor="White" Height="40px"
                                            HorizontalAlign="Center" />
                                        <RowStyle Height="30px" HorizontalAlign="Center" />
                                    </asp:GridView>

Command Argument contail same value as you are specifying in select command
if u rename any column by as keyword in select command then command argument will use renamed name  for ex original data column is Message_Id  you retrieve it as Message ID then command argument will use Message ID not Message_Id.


in code file

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
           
           
            if (e.CommandName == "DeleteRow")
            {
                int index =Convert.ToInt32(e.CommandArgument);
                //GridViewRow row = GridView1.Rows[index];
                //GridView1.DeleteRow(index);
                con = new MySqlConnection(ss);
                con.Open();
                cmd = new MySqlCommand("delete from message where Message_Id=@mid", con);
                cmd.Parameters.Add(new MySqlParameter("mid", index));
                cmd.ExecuteNonQuery();
                con.Close();
               
            }


        }

Validate a TextBox to contain only particular data

This code validate a text box to cantain only alphabets.
If u want to change then you can replace IsLetter to any type .


  protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        if (TextBox1.Text.All(chr => char.IsLetter(chr)))
        {
          
                Label1.Text = "ok";
           
        }
        else
        {
            Label1.Text = "not ok";
           
        }
    }

INDEX (Clustered and Non Clustered)

An index is an on-disk structure associated with a table or view that speeds retrieval of rows from the table or view. An index contains keys built from one or more columns in the table or view. These keys are stored in a structure (B-tree) that enables SQL Server to find the row or rows associated with the key values quickly and efficiently.
A table or view can contain the following types of indexes:
When multiple databases and multiple tables are joined, it's referred to as a cluster

  • Clustered
    • Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order.
    • The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.
  • Nonclustered
    • Nonclustered indexes have a structure separate from the data rows. A nonclustered index contains the nonclustered index key values and each key value entry has a pointer to the data row that contains the key value.
    • The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.
    • You can add nonkey columns to the leaf level of the nonclustered index to by-pass existing index key limits, 900 bytes and 16 key columns, and execute fully covered, indexed, queries. For more information, see Create Indexes with Included Columns.

      Both clustered and nonclustered indexes can be unique. This means no two rows can have the same value for the index key. Otherwise, the index is not unique and multiple rows can share the same key value. For more information, see Create Unique Indexes.

      Indexes are automatically maintained for a table or view whenever the table data is modified.

Sunday 21 July 2013

Validation in ASP.NET using JAVA SCRIPT Or Restrict the Length of Control

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

<!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:Button ID="Button1" runat="server" Text="Button" OnClientClick="validate()" />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <script type="text/javascript">
    function validate() {
        var textbox = document.getElementById('<% = TextBox1.ClientID %>').value;
        var drop = document.getElementById('<%=DropDownList1.ClientID %>').value;
        if (textbox == "") {
            alert("enter the value");
document.getElementById('<% = TextBox1.ClientID %>').focus();
            return false;
        }
        if (drop == "Select") {
            alert("selectany value ");
            return false;
        }
    }
</script>
        <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem>Select</asp:ListItem>
            <asp:ListItem>yes</asp:ListItem>
            <asp:ListItem>no</asp:ListItem>
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

Fore more visit http://www.codeproject.com/Tips/404274/Client-Side-Validation-using-JavaScript
If u want to restrict the length then use

  var drop = document.getElementById('<%=DropDownList1.ClientID %>').value.Length

then compare length to any number 

Saturday 20 July 2013

To select top nth record in sql server

select top 1 *  from ( select top 2 * from abc order by id desc  )sub order by id asc

it will select top 2nd from bottom

for seleting top 3rd from above

select top 1 *  from ( select top 3 * from abc order by id asc  )sub order by id desc



from Top

select top 1* from  (select Top 4 id from test1 order by id asc) sub order by id desc

from Bottom

select top 1* from  (select Top 4 id from test1 order by id desc) sub order by id asc

Monday 8 July 2013

Delete multiple Records in Gridview using CheckBoxes

<asp:GridView ID="gvAll" runat="server"
    AutoGenerateColumns = "false" Font-Names = "Arial"
    Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" 
    HeaderStyle-BackColor = "green" AllowPaging ="true"  
    OnPageIndexChanging = "OnPaging" DataKeyNames = "CustomerID"
    PageSize = "10" >
   <Columns>
    <asp:TemplateField>
        <HeaderTemplate>
            <asp:CheckBox ID="chkAll" runat="server"
              />
        </HeaderTemplate>
        <ItemTemplate>
            <asp:CheckBox ID="chk" runat="server"
             />
        </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "ContactName"
       HeaderText = "Contact Name"/>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "Country"
       HeaderText = "Country"/>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "City"
       HeaderText = "City"/>
   </Columns>
   <AlternatingRowStyle BackColor="#C2D69B"  />
</asp:GridView>
<asp:HiddenField ID="hfCount" runat="server" Value = "0" />
<asp:Button ID="btnDelete" runat="server" Text="Delete Checked Records"
   OnClientClick = "return ConfirmDelete();" OnClick="btnDelete_Click" />
You’ll notice above I have added a template field with checkboxes also I have added a check all checkbox in the Header Template of the ASP.net GridView Control. There’s a hidden field to store the count of the selected records and a delete button to trigger the delete operation. Paging is enabled for the GridView and there’s OnPageIndexChanging event that will be described later. CustomerID is assigned to the DataKeyNames property of the GridView which will allow us to uniquely identify each row
Data Binding the ASP.Net GridView control
I have used the Customers table from the Northwind Database for this example. The Customers table has some relationships with other tables hence it will not allow delete directly without removing the foreign key references. Hence to make it simple will create a new table called TestCustomers and use that instead. To create a clone table execute the following query.
SELECT * INTO TestCustomers
FROM Customers
The above query will create a new table TestCustomers and copy all the records from Customers table into TestCustomers. Thus now we can use it for out tutorial. The following function is used to databind the ASP.Net GridView control
C#
private void BindGrid()
{
    string constr = ConfigurationManager
                .ConnectionStrings["conString"].ConnectionString;
    string query = "select * from TestCustomers";
    SqlConnection con = new SqlConnection(constr);
    SqlDataAdapter sda = new SqlDataAdapter(query, con);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    gvAll.DataSource = dt;
    gvAll.DataBind();
}
VB.Net
Private Sub BindGrid()
    Dim constr As String = ConfigurationManager _
                    .ConnectionStrings("conString").ConnectionString()
    Dim query As String = "select * from TestCustomers"
    Dim con As New SqlConnection(constr)
    Dim sda As New SqlDataAdapter(query, con)
    Dim dt As New DataTable()
    sda.Fill(dt)
    gvAll.DataSource = dt
    gvAll.DataBind()
End Sub
Maintaining the state of Checkboxes while paging
This is the core part of this example since its job is to keep track of the selected rows irrespective of which page it belongs and also maintain the state of the checkboxes while pagination so that user selections are not lost when he navigates from one page to another.
To facilitate this i have made use of the following two functions
1. GetData
The GetData function simply retrieves the records for which the user has checked the checkbox, adds them to an ArrayList and then saves the ArrayList to ViewState
C#
private void GetData()
{
    ArrayList arr;
    if (ViewState["SelectedRecords"] != null)
        arr = (ArrayList)ViewState["SelectedRecords"];
    else
        arr = new ArrayList();
    CheckBox chkAll = (CheckBox)gvAll.HeaderRow
                        .Cells[0].FindControl("chkAll");
    for (int i = 0; i < gvAll.Rows.Count; i++)
    {
        if (chkAll.Checked)
        {
            if (!arr.Contains(gvAll.DataKeys[i].Value))
            {
                arr.Add(gvAll.DataKeys[i].Value);
            }
        }
        else
        {
            CheckBox chk = (CheckBox)gvAll.Rows[i]
                               .Cells[0].FindControl("chk");
            if (chk.Checked)
            {
                if (!arr.Contains(gvAll.DataKeys[i].Value))
                {
                    arr.Add(gvAll.DataKeys[i].Value);
                }
            }
            else
            {
                if (arr.Contains(gvAll.DataKeys[i].Value))
                {
                    arr.Remove(gvAll.DataKeys[i].Value);
                }
            }
        }
    }
    ViewState["SelectedRecords"] = arr;
}
VB.Net
Private Sub GetData()
    Dim arr As ArrayList
    If ViewState("SelectedRecords") IsNot Nothing Then
         arr = DirectCast(ViewState("SelectedRecords"), ArrayList)
    Else
         arr = New ArrayList()
    End If
    Dim chkAll As CheckBox = DirectCast(gvAll.HeaderRow _
                    .Cells(0).FindControl("chkAll"), CheckBox)
    For i As Integer = 0 To gvAll.Rows.Count - 1
       If chkAll.Checked Then
             If Not arr.Contains(gvAll.DataKeys(i).Value) Then
                 arr.Add(gvAll.DataKeys(i).Value)
             End If
       Else
             Dim chk As CheckBox = DirectCast(gvAll.Rows(i).Cells(0) _
                                            .FindControl("chk"), CheckBox)
             If chk.Checked Then
                If Not arr.Contains(gvAll.DataKeys(i).Value) Then
                     arr.Add(gvAll.DataKeys(i).Value)
                End If
             Else
                If arr.Contains(gvAll.DataKeys(i).Value) Then
                     arr.Remove(gvAll.DataKeys(i).Value)
                End If
             End If
       End If
    Next
    ViewState("SelectedRecords") = arr
End Sub
GetData is called in the Page Load event of the ASP.Net web page in the following way
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
        GetData();
    BindGrid();
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If IsPostBack Then
         GetData()
    End If
    BindGrid()
End Sub
2. SetData
The SetData function simply restores the saved state of the checkboxes from the ViewState
C#
private void SetData()
{
    int currentCount = 0;
    CheckBox chkAll = (CheckBox)gvAll.HeaderRow
                            .Cells[0].FindControl("chkAll");
    chkAll.Checked = true;
    ArrayList arr = (ArrayList)ViewState["SelectedRecords"];
    for (int i = 0; i < gvAll.Rows.Count; i++)
    {
        CheckBox chk = (CheckBox)gvAll.Rows[i]
                        .Cells[0].FindControl("chk");
        if (chk != null)
        {
            chk.Checked = arr.Contains(gvAll.DataKeys[i].Value);
            if (!chk.Checked)
                chkAll.Checked = false;
            else
                currentCount++;
        }
    }
    hfCount.Value = (arr.Count - currentCount).ToString(); 
}
VB.Net
Private Sub SetData()
  Dim currentCount As Integer = 0
  Dim chkAll As CheckBox = DirectCast(gvAll.HeaderRow _
                        .Cells(0).FindControl("chkAll"), CheckBox)
  chkAll.Checked = True
  Dim arr As ArrayList = DirectCast(ViewState("SelectedRecords") _
                                        , ArrayList)
  For i As Integer = 0 To gvAll.Rows.Count - 1
     Dim chk As CheckBox = DirectCast(gvAll.Rows(i).Cells(0) _
                                         .FindControl("chk"), CheckBox)
     If chk IsNot Nothing Then
         chk.Checked = arr.Contains(gvAll.DataKeys(i).Value)
         If Not chk.Checked Then
                chkAll.Checked = False
         Else
                currentCount += 1
         End If
     End If
  Next
  hfCount.Value = (arr.Count - currentCount).ToString()
End Sub
The SetData method is called up in the OnPageIndexChanging event of the ASP.Net GridView in the following way
C#
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
    gvAll.PageIndex = e.NewPageIndex;
    gvAll.DataBind();
    SetData();
}
VB.Net
Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
    gvAll.PageIndex = e.NewPageIndex
    gvAll.DataBind()
    SetData()
End Sub
Deleting multiple selected rows
Now when the delete button is clicked by the user the following event if triggered
C#
protected void btnDelete_Click(object sender, EventArgs e)
{
    int count = 0;
    SetData();
    gvAll.AllowPaging = false;
    gvAll.DataBind(); 
    ArrayList arr = (ArrayList)ViewState["SelectedRecords"];
    count = arr.Count;
    for (int i = 0; i < gvAll.Rows.Count; i++)
    {
        if (arr.Contains(gvAll.DataKeys[i].Value))
        {
            DeleteRecord(gvAll.DataKeys[i].Value.ToString());
            arr.Remove(gvAll.DataKeys[i].Value);
        }
    }
    ViewState["SelectedRecords"] = arr;
    hfCount.Value = "0";
    gvAll.AllowPaging = true;
    BindGrid();
    ShowMessage(count);
}
VB.Net
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim count As Integer = 0
    SetData()
    gvAll.AllowPaging = False
    gvAll.DataBind()
    Dim arr As ArrayList = DirectCast(ViewState("SelectedRecords") _
                                    , ArrayList)
    count = arr.Count
    For i As Integer = 0 To gvAll.Rows.Count - 1
        If arr.Contains(gvAll.DataKeys(i).Value) Then
              DeleteRecord(gvAll.DataKeys(i).Value.ToString())
              arr.Remove(gvAll.DataKeys(i).Value)
        End If
    Next
    ViewState("SelectedRecords") = arr
    hfCount.Value = "0"
    gvAll.AllowPaging = True
    BindGrid()
    ShowMessage(count)
End Sub
In the above event handler I am simply looping through the GridView and checking if the record exists in the ArrayList, if the record exists then it is simply deleted using the DeleteRecord method. Finally I display the a JavaScript Alert Box to notify the user that the delete operation is finished using the ShowMessage method
DeleteRecord Method
The delete record method simply deletes the record from the database table based on CustomerID.
C#
private void DeleteRecord(string CustomerID)
{
    string constr = ConfigurationManager
                .ConnectionStrings["conString"].ConnectionString;
    string query = "delete from TestCustomers " +
                    "where CustomerID=@CustomerID";
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand(query, con);
    cmd.Parameters.AddWithValue("@CustomerID", CustomerID);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
}
VB.Net
Private Sub DeleteRecord(ByVal CustomerID As String)
    Dim constr As String = ConfigurationManager _
                        .ConnectionStrings("conString").ConnectionString
    Dim query As String = "delete from TestCustomers where" & _
                                " CustomerID=@CustomerID"
    Dim con As New SqlConnection(constr)
    Dim cmd As New SqlCommand(query, con)
    cmd.Parameters.AddWithValue("@CustomerID", CustomerID)
    con.Open()
    cmd.ExecuteNonQuery()
    con.Close()
End Sub
ShowMessage Method
 The ShowMessage method simply displays the amount of records deleted through a JavaScript Alert
C#
private void ShowMessage(int count)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("<script type = 'text/javascript'>");
    sb.Append("alert('");
    sb.Append(count.ToString());
    sb.Append(" records deleted.');");
    sb.Append("</script>");
    ClientScript.RegisterStartupScript(this.GetType(),
                    "script", sb.ToString());
}
VB.Net
Private Sub ShowMessage(ByVal count As Integer)
     Dim sb As New StringBuilder()
     sb.Append("<script type = 'text/javascript'>")
     sb.Append("alert('")
     sb.Append(count.ToString())
     sb.Append(" records deleted.');")
     sb.Append("</script>")
     ClientScript.RegisterStartupScript(Me.GetType(), _
                        "script", sb.ToString())
End Sub
Client Side Scripting
I have made use of some JavaScript methods for the following methods
1.  Check-all checkbox functionality
2.  Confirmation before delete.
Check-all checkbox functionality
Check-all checkbox functionality has already explained by me in past. You can simply refer my article
Confirmation before delete
It would be a great feature to display a confirm box to the user stating that these many rows or records selected by you will be deleted. If the user presses OK delete operation will be performed else not. The following JavaScript function does it for us.
<script type = "text/javascript">
    function ConfirmDelete()
    {
       var count = document.getElementById("<%=hfCount.ClientID %>").value;
       var gv = document.getElementById("<%=gvAll.ClientID%>");
       var chk = gv.getElementsByTagName("input");
       for(var i=0;i<chk.length;i++)
       {
            if(chk[i].checked && chk[i].id.indexOf("chkAll") == -1)
            {
                count++;
            }
       }
       if(count == 0)
       {
            alert("No records to delete.");
            return false;
       }
       else
       {
            return confirm("Do you want to delete " + count + " records.");
       }
    }
</script>