Thursday, July 10, 2014

Difference Between String And String Builder?

string 

String is immutable. Immutable means once we create string object we cannot modify. Any operation like insert, replace or append happened to change string simply it will discard the old value and it will create new instance in memory to hold the new value.


string str = "hi";
// create a new string instance instead of changing the old one
str += "test";
str += "help";

String Builder

String builder is mutable it means once we create string builder object we can perform any operation like insert, replace or append without creating new instance for every time.


StringBuilder sb = new StringBuilder("");

sb.Append("hi");
sb.Append("test ");
string str = sb.ToString();


Differences


String
StringBuilder
It’s an immutable
It’s mutable
Performance wise string is slow because every time it will create new instance
Performance wise stringbuilder is high because it will use same instance of object to perform any action
In string we don’t have append keyword
In StringBuilder we can use append keyword
String belongs to System namespace
Stringbuilder belongs to System.Text namespace

What is Serialization

Serialization:

It Is The Process of Converting Complex Objects into Stream Of Bytes For Storage.


Advantage:

Using serialization is the ability to transmit data across the network in a cross-platform-compatible format, as well as saving it in a persistent or non-persistent storage medium in a non-proprietary format.

Serialization is used by Remoting, Web Services SOAP for transmitting data between a server and a client. The Remoting technology of .NET makes use of serialization to pass objects by value from one application domain to another.

De-serialization is the reverse; it is the process of reconstructing the same object later.


Types of Serialization

Serialization can be of the following types:

1.Binary Serialization

2.SOAP Serialization

3.XML Serialization



Binary Serialization:


Binary serialization is a mechanism which writes the data to the output stream such that it can be used to re-construct the object automatically. The term binary in its name implies that the necessary information that is required to create an exact binary copy of the object is saved onto the storage media.

Difference between Binary serialization and XML serialization is that Binary serialization preserves instance identity while XML serialization does not. In other words, in Binary serialization the entire object state is saved while in XML serialization only some of the object data is saved. 

Binary serialization can handle graphs with multiple references to the same object; XML serialization will turn each reference into a reference to a unique object

SOAP Serialization:


The SOAP protocol is ideal for communicating between applications that use heterogeneous architectures. In order to use SOAP serialization in .NET we have to add a reference to System.Runtime.Serialization.Formatters.Soap in the application. The basic advantage of SOAP serialization is portability. The SoapFormatter serializes objects into SOAP messages or parses SOAP messages and extracts serialized objects from the message. 


XML Serialization:


· According to MSDN, "XML serialization converts (serializes) the public fields and properties of an object or the parameters and returns values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document.



· XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format (in this case, XML) for storage or transport. Because XML is an open standard, the XML stream can be processed by any application, as needed, regardless of platform." Implementing XML Serialization in .Net is quite simple.

Search Gridview Rows Based On Header Text Box Values Using OntextChanged And Like Command


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

<!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:GridView ID="grd" AutoGenerateColumns="False" runat="server" BackColor="#DEBA84"
            BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">
            <Columns>
                <asp:TemplateField HeaderText="id">
                    <HeaderTemplate>
                        <asp:TextBox ID="txtid" runat="server" OnTextChanged="ontxtid" AutoPostBack="true"></asp:TextBox>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblid" runat="server" Text='<%#bind("id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="fname">
                    <HeaderTemplate>
                        <asp:TextBox ID="txtfname" runat="server" OnTextChanged="ontxtfname" AutoPostBack="true"></asp:TextBox>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblfname" runat="server" Text='<%#bind("fname") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="lname">
                    <HeaderTemplate>
                        <asp:TextBox ID="txtlname" runat="server" OnTextChanged="ontxtlname" AutoPostBack="true"></asp:TextBox>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblnamel" runat="server" Text='<%#bind("lname") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Description">
                    <HeaderTemplate>
                        <asp:TextBox ID="txtdes" runat="server"></asp:TextBox>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <%# Eval("description").ToString().Replace("&","</br>")%>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
            <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FFF1D4" />
            <SortedAscendingHeaderStyle BackColor="#B95C30" />
            <SortedDescendingCellStyle BackColor="#F1E5CE" />
            <SortedDescendingHeaderStyle BackColor="#93451F" />
        </asp:GridView>
    </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.Configuration;
using System.Data;
using System.Data.SqlClient;

public partial class grid : System.Web.UI.Page
{
    string xxx = ConfigurationManager.ConnectionStrings["aaa"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SqlConnection con = new SqlConnection(xxx);
            SqlCommand cmd = new SqlCommand("select * from Des");
            cmd.Connection = con;
            SqlDataAdapter dap = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            grd.DataSource = ds;
            grd.DataBind();
            //return ds;
           
        }
    }
    protected void ontxtid(object sender, EventArgs e)
    {

        if (grd.HeaderRow != null)
        {
            TextBox txti = (TextBox)grd.HeaderRow.FindControl("txtid");
            SqlConnection con = new SqlConnection(xxx);
            SqlCommand cmd = new SqlCommand("select * from des where id like '" + txti.Text + "%'");
            cmd.Connection = con;
            SqlDataAdapter dap = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            grd.DataSource = ds;
            grd.DataBind();

        }
    }
    protected void ontxtfname(object sender, EventArgs e)
    {

        if (grd.HeaderRow != null)
        {
            TextBox txtf = (TextBox)grd.HeaderRow.FindControl("txtfname");
            //TextBox txti = (TextBox)grd.HeaderRow.FindControl("txtid");
            SqlConnection con = new SqlConnection(xxx);
            SqlCommand cmd = new SqlCommand("select * from des where fname like '" + txtf.Text + "%'");
            cmd.Connection = con;
            SqlDataAdapter dap = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            grd.DataSource = ds;
            grd.DataBind();
        }
    }
    protected void ontxtlname(object sender, EventArgs e)
    {

        if (grd.HeaderRow != null)
        {
            TextBox txtl = (TextBox)grd.HeaderRow.FindControl("txtlname");
            //TextBox txti = (TextBox)grd.HeaderRow.FindControl("txtid");
            SqlConnection con = new SqlConnection(xxx);
            SqlCommand cmd = new SqlCommand("select * from des where lname like '" + txtl.Text + "%'");
            cmd.Connection = con;
            SqlDataAdapter dap = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            grd.DataSource = ds;
            grd.DataBind();
        }
    }

 
}
 ----------------------------------------------------------------------------------
<connectionStrings>
              <add name="aaa" connectionString="Data Source=KCLINK-45-PC\SQLEXPRESS;Initial Catalog=naresh;Integrated Security=True" providerName="System.Data.SqlClient"/>
       </connectionStrings>
       <system.web>
<connectionStrings>

----------------------------------------------------------------------------
CREATE TABLE [dbo].[des](
      [id] [int] IDENTITY(1,1) NOT NULL,
      [fname] [varchar](50) NULL,
      [lname] [varchar](50) NULL,
      [description] [varchar](200) NULL,
 CONSTRAINT [PK_des] PRIMARY KEY CLUSTERED
(
      [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


Wednesday, July 9, 2014

Create DataTable dynamically and bind to GridView in ASP.Net

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

<!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:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
    </Columns>
</asp:GridView>
    </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.Data;

public partial class grdview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                            new DataColumn("Name", typeof(string)),
                            new DataColumn("Country",typeof(string)) });
            dt.Rows.Add(1, "Naresh", "India");
            dt.Rows.Add(2, "XXX", "India");
            dt.Rows.Add(3, "AAAA", "France");
            dt.Rows.Add(4, "MMMMM", "Russia");
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
 
}