Thursday 31 March 2011

How To Select,Insert And Update Data From XML File

----------------XML file XMLFile.xml--------------------------
<?xml version="1.0" encoding="utf-8"?>
<DocumentElement>
  <Person>
    <id>100</id>
    <Name>Sudipta</Name>
    <City>Kol</City>
    <Age>1212</Age>
  </Person>
  <Person>
    <id>101</id>
    <Name>Sudipta123</Name>
    <City>kol</City>
    <Age>26</Age>
  </Person>
  <Person>
    <id>10</id>
    <Name>Kol</Name>
    <City>Kola</City>
    <Age>10</Age>
  </Person>
</DocumentElement>
----------------Design Page : Default.aspx----------------------

<div style="font-family: Verdana; font-size: 12px">
        <table style="width: 80%" cellpadding="2" cellspacing="2" align="center">
            <tr>
            <td>
                    Id
                </td>
                <td>
                    <asp:TextBox ID="txtId" runat="server"></asp:TextBox>
                </td>
                <td>
                    Name
                </td>
                <td>
                    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                </td>
                <td>
                    City
                </td>
                <td>
                    <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
                </td>
                <td>
                    Age
                </td>
                <td>
                    <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:Button ID="btnInsertIntoXml" runat="server" Text="Insert Into Xml"
                        onclick="btnInsertIntoXml_Click" />
                </td>
            </tr>
        </table>

        <table style="width: 80%" cellpadding="2" cellspacing="2" align="center">
            <tr>
                <td>
                    Name
                </td>
                <td>
                    <asp:TextBox ID="txtUpdateName" runat="server"></asp:TextBox>
                </td>
                <td>
                    City
                </td>
                <td>
                    <asp:TextBox ID="txtUpdateCity" runat="server"></asp:TextBox>
                </td>
                <td>
                    Age
                </td>
                <td>
                    <asp:TextBox ID="txtUpdateAge" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:HiddenField ID="hidId" runat="server" />
                    <asp:Button ID="btnUpdateXml" runat="server" Text="Update Xml    " OnClick="btnUpdateXml_Click" />
                </td>
            </tr>
            <tr>
                <td style="width: 100%;" colspan="7">
                    <asp:Repeater ID="Repeater1" runat="server"
                        onitemdatabound="Repeater1_ItemDataBound"
                        onitemcommand="Repeater1_ItemCommand">
                        <HeaderTemplate>
                            <table style="width: 99%" cellpadding="4" cellspacing="1">
                                <tr style="background-color: #E0E1E1">
                                    <td style="width: 50%; font-weight: bold">
                                        Name
                                    </td>
                                    <td style="width: 35%; font-weight: bold">
                                        City
                                    </td>
                                    <td style="width: 9%; font-weight: bold">
                                        Age
                                    </td>
                                    <td style="width: 5%; font-weight: bold">
                                        Edit
                                    </td>
                                </tr>
                        </HeaderTemplate>
                        <ItemTemplate>
                            <tr>
                                <td style="width: 50%">
                                    <asp:Label ID="lblName" runat="server" Text="Label"></asp:Label>
                                </td>
                                <td style="width: 35%">
                                    <asp:Label ID="lblCity" runat="server" Text="Label"></asp:Label>
                                </td>
                                <td style="width: 9%">
                                    <asp:Label ID="lblAge" runat="server" Text="Label"></asp:Label>
                                </td>
                                <td style="width: 5%">
                                    <asp:LinkButton ID="lnkEdit" runat="server" style="text-decoration:none;">Edit</asp:LinkButton>
                                </td>
                            </tr>
                        </ItemTemplate>
                        <AlternatingItemTemplate>
                            <tr style="background-color: #E0E1E1">
                                <td style="width: 50%">
                                    <asp:Label ID="lblName" runat="server" Text="Label"></asp:Label>
                                </td>
                                <td style="width: 35%">
                                    <asp:Label ID="lblCity" runat="server" Text="Label"></asp:Label>
                                </td>
                                <td style="width: 9%">
                                    <asp:Label ID="lblAge" runat="server" Text="Label"></asp:Label>
                                </td>
                                <td style="width: 5%; " >
                                    <asp:LinkButton ID="lnkEdit" runat="server" style="text-decoration:none;" >Edit</asp:LinkButton>
                                </td>
                            </tr>
                        </AlternatingItemTemplate>
                        <FooterTemplate>
                            </table>
                        </FooterTemplate>
                    </asp:Repeater>
                </td>
            </tr>
        </table>
    </div>
-------------Cs Page :Default.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.Xml.XPath;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    DataSet ds = new DataSet("XmlData");
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            PopulateRepeter();
        }
    }

    private void PopulateRepeter()
    {
        ds.ReadXml(Server.MapPath("XMLFile.xml"));
        dt = ds.Tables[0];
        Repeater1.DataSource = dt;
        Repeater1.DataBind();
    }

    protected void btnUpdateXml_Click(object sender, EventArgs e)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(Server.MapPath("XMLFile.xml"));
        XmlNodeList nodeList = xmlDoc.SelectNodes("DocumentElement/Person[id='" + hidId.Value.ToString() + "']");
        nodeList[0].ChildNodes[1].InnerText = txtUpdateName.Text;
        nodeList[0].ChildNodes[2].InnerText = txtUpdateCity.Text;
        nodeList[0].ChildNodes[3].InnerText = txtUpdateAge.Text;
        xmlDoc.Save(Server.MapPath("XMLFile.xml"));
        PopulateRepeter();
    }
    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Label lblName = (Label)e.Item.FindControl("lblName");
            if (lblName != null)
            {
                lblName.Text = dt.Rows[e.Item.ItemIndex]["Name"].ToString();
            }
            Label lblCity = (Label)e.Item.FindControl("lblCity");
            if (lblCity != null)
            {
                lblCity.Text = dt.Rows[e.Item.ItemIndex]["City"].ToString();
            }
            Label lblAge = (Label)e.Item.FindControl("lblAge");
            if (lblAge != null)
            {
                lblAge.Text = dt.Rows[e.Item.ItemIndex]["Age"].ToString();
            }
            LinkButton lnkEdit = (LinkButton)e.Item.FindControl("lnkEdit");
            if (lnkEdit != null)
            {
                lnkEdit.CommandName = "Edit";
                lnkEdit.CommandArgument = dt.Rows[e.Item.ItemIndex]["Id"].ToString() + "," + dt.Rows[e.Item.ItemIndex]["Name"].ToString() + "," + dt.Rows[e.Item.ItemIndex]["City"].ToString() + "," + dt.Rows[e.Item.ItemIndex]["Age"].ToString();
            }

        }
    }
    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        string[] field = e.CommandArgument.ToString().Split((",").ToCharArray());
        if (e.CommandName == "Edit")
        {
            hidId.Value = field[0].ToString();
            txtUpdateName.Text = field[1].ToString();
            txtUpdateCity.Text = field[2].ToString();
            txtUpdateAge.Text = field[3].ToString();

        }

    }
    protected void btnInsertIntoXml_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("XMLFile.xml"));
        XmlNode node = doc.CreateNode(XmlNodeType.Element, "Person", null);
        XmlNode Id = doc.CreateElement("id");
        Id.InnerText = txtId.Text.Trim();
        XmlNode Name = doc.CreateElement("Name");
        Name.InnerText = txtName.Text.Trim();
        XmlNode City = doc.CreateElement("City");
        City.InnerText = txtCity.Text.Trim();
        XmlNode Age = doc.CreateElement("Age");
        Age.InnerText = txtAge.Text.Trim();
        node.AppendChild(Id);
        node.AppendChild(Name);
        node.AppendChild(City);
        node.AppendChild(Age);
        doc.DocumentElement.AppendChild(node);
        doc.PreserveWhitespace = true;
        doc.Save(Server.MapPath("XMLFile.xml"));
        PopulateRepeter();
    }
}

Friday 25 March 2011

How To Use JSON Datasource (in WebService) in Asp.net

JSON
JSON (an acronym for JavaScript Object) is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript programming language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for most programming languages.
The JSON format was originally specified by Douglas Crockford, The official Internet media type for JSON is application/json. The JSON filename extension is .json.
---------------------------------------------------------
Efficiency
JSON is primarily used for communicating data over the Internet, but has certain inherent characteristics that may limit its efficiency for this purpose. Most of the limitations are general limitations of textual data formats and also apply to XML and YAML. For example, despite typically being generated by an algorithm (by machine), parsing must be accomplished on a character-by-character basis. Additionally, the standard has no provision for data compression, interning of strings, or object references. Compression can, of course, be applied to the JSON formatted data (but the decompressed output typically still requires further full parsing for recognizable keywords, tags and delimiters).
---------------How To Implement  JSON ----------------
Download jquery-1.3.2.min.js  and past it in the js folder in your web application
http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.3.2.min.js&downloadBtn
--------------- Page Design
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Jeson Test</title>
    <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript">
        function testJson() {
            $.ajax({
                type: "POST",
                url: "Json.asmx/TestJSON",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                $("#jsonResponse").html(msg);
                    var data = eval("(" + msg.d + ")");
                    var t = "<table border=1> <tr>" +
                      "<td> <strong>Name</strong></td> <td> " +
                      "<strong>Company</strong></td> <td> " +
                      "<strong>Address</strong></td> <td> " +
                      "<strong>Phone</strong></td> <td> " +
                      "<strong>Country</strong></td> </tr> ";
                      jQuery.each(data, function(rec) {
                        t = t + " <tr> <td> " + this.Name + "</td> <td> " +
                            this.Company + "</td> <td> " + this.Address +
                             "</td> <td> " + this.Phone + "</td> <td> " + this.Country + "</td> </tr> ";
                    });
                    t = t + " </table> ";
                    $("#jsonDiv").html(t);
                },
                error: function(msg) {
                }
            });
        };
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="testjson" type="button" value="Test JSON Call" onclick="testJson()" />
        <br />
        <div id="jsonDiv" style="display: block;">
        </div>
    </div>
    </form>
</body>
</html>
----------------Web service
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class Json : System.Web.Services.WebService {
    public Json () {}
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string TestJSON()
    {
        Employee[] e = new Employee[3];
        e[0] = new Employee();
        e[0].Name = "Sudipta Sanyal";
        e[0].Company = "Esolz";
        e[0].Address = "Kolkata";
        e[0].Phone = "1204675";
        e[0].Country = "India";
        e[1] = new Employee();
        e[1].Name = "Protom Nandi";
        e[1].Company = "Esolz";
        e[1].Address = "Kolkata";
        e[1].Phone = "1204675";
        e[1].Country = "India";
        e[2] = new Employee();
        e[2].Name = "Tanmay Chak";
        e[2].Company = "Esolz";
        e[2].Address = "Kolkata";
        e[2].Phone = "1204675";
        e[2].Country = "India";
        return new JavaScriptSerializer().Serialize(e);
    }  
}
----------------Employee Class 
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public class Employee
{
    public string Name { get; set; }
    public string Company { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
    public string Country { get; set; }
}

Wednesday 23 March 2011

How To Used AutoCompleteExtender in Asp.net

Download AjaxControlToolkit.dll 
Add the Dll in the ToolBox Item
Add One Web-Service WebService.asmx
-----------------Design page
<body>
    <form id="form1" runat="server" autocomplete="off">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
              <cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" ServiceMethod="UseAutoComplete"
                    ServicePath="WebService.asmx" TargetControlID="TextBox1" MinimumPrefixLength="0">
                </cc1:AutoCompleteExtender>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
-----------------WebService.cs Code


using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Web.SessionState;
using System.Collections.Generic;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebService : System.Web.Services.WebService {
    public WebService () {
    }
    [WebMethod]
    public string[] UseAutoComplete(string prefixText, int count)
    {
        count = 10;
        List<string> responses = new List<string>();
        for (int i = 0; i < count; i++)
            responses.Add(prefixText + (char)(i + 65));
        return responses.ToArray();
    }  
}
--------Add This In WebConfig File
  <system.web.extensions>
    <scripting>
      <webServices>
        <!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
        <!--
      <jsonSerialization maxJsonLength="500">
        <converters>
          <add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
        </converters>
      </jsonSerialization>
      -->
        <!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
        <!--
        <authenticationService enabled="true" requireSSL = "true|false"/>
      -->
        <!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
           and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
           writeAccessProperties attributes. -->
        <!--
      <profileService enabled="true"
                      readAccessProperties="propertyname1,propertyname2"
                      writeAccessProperties="propertyname1,propertyname2" />
      -->
      </webServices>
      <!--
      <scriptResourceHandler enableCompression="true" enableCaching="true" />
      -->
    </scripting>
  </system.web.extensions>

Friday 18 March 2011

How To Reduce Or Delete Log Files From Database


use master
select * from sysdatabases
---For See the database name
BACKUP LOG databasename WITH TRUNCATE_ONLY
---Right Click on Database Go to files And see the DatabaseLog file name
use Database
DBCC SHRINKFILE(DatabaseLog_log,1)
--If my database name is SS
BACKUP LOG SS WITH TRUNCATE_ONLY
DBCC SHRINKFILE(SS1_log,1)

OR
Shrinking a log file to a specified target size

USE AdventureWorks2012;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE AdventureWorks2012
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (AdventureWorks2012_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE AdventureWorks2012
SET RECOVERY FULL;
GO  

Wednesday 16 March 2011

How To Insert Bulk Data In DataBase Using Xml

This is a Xml Text
declare @Xml as xml
set @Xml ='<DocumentElement>
<RootName>
<Id>1</Id>
<Name>Sudipta Sanyal</Name>
<Address>KolKata</Address>
<Phone>1234567890</Phone>
</RootName>
<RootName>
<Id>2</Id>
<Name>Sudipta Sanyal2</Name>
<Address>KolKata2</Address>
<Phone>12345678902</Phone>
</RootName>
</DocumentElement>'
-------------------This is a Temp Table
declare @Temp as table
(
Id int,
Name nvarchar(50),
Address nvarchar(50),
Phone nvarchar(50)
)
----------------This is The query by which You can insert into database bulk data
insert into @Temp (Id,Name,Address,Phone)
select
cast (SS.query('data(Id)') as nvarchar(200)) as Id,
cast (SS.query('data(Name)') as nvarchar(200)) as Name,
cast (SS.query('data(Address)') as nvarchar(200)) as Address,
cast (SS.query('data(Phone)') as nvarchar(200)) as Phone
from @Xml.nodes('DocumentElement/RootName') as Sudipta(SS)
--------------If u want to select data then
select * from @Temp


Tuesday 15 March 2011

Fastest trim in javascript

function trim(value) {var temp = value;var obj = /^(\s*)([\W\w]*)(\b\s*$)/;if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }var obj = / +/g;temp = temp.replace(obj, " ");if (temp == " ") { temp = ""; }return temp;}

How Do You Use This Function :
var a = trim(document.getElementById('TextBoxID').value);

How To Connect MySql Databse With Asp.net

Download the exe file from this http://dev.mysql.com/downloads/connector/odbc/3.51.html
for the MySQL ODBC 3.51 Driver
may be you have to register this site for download the exe.

After run the exe try this code :
--------------------------------------
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Odbc;


public partial class _Default : System.Web.UI.Page
{
    string sConString = "Driver={MySQL ODBC 3.51 Driver};" + "Server=localhost;" + "Database=test;" + "user id=;" + "password=";
    OdbcConnection oConnection = new OdbcConnection(sConString);
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (oConnection.State != ConnectionState.Open)
            {
                oConnection.Open();
            }
        }
        catch
        {
        }
        finally
        {
            oConnection.Close();
        }

    }
}
------------------

Saturday 12 March 2011

How To Fetch Next 10 Years From Database


DECLARE    @yearFrom SMALLINT,@yearTo SMALLINT,@lenthOfyear SMALLINT
set @lenthOfyear=10
SELECT @yearFrom =year( getdate())set @YearTo = @yearFrom+@lenthOfyear SELECT
CAST(temp.Number + @yearFrom AS CHAR(4)) as [Year]FROM(SELECT    Number
FROM    master..spt_values
WHERE    Type = 'P'AND Number <= @YearTo - @YearFrom) AS temp



How To Create A Cursor


declare @Script_Code nvarchar(400),@Script_Name nvarchar(400),@rownum nvarchar(400)
declare @Script_Code1 nvarchar(400),@Script_Name1  nvarchar(400)
declare @Counter int
set @Counter=0
DECLARE db_cursor CURSOR FOR 
select shareName,ShareCode,rownum
 from (
select  distinct row_number() over (order by ShareCode asc) as rownum, shareName,ShareCode from Table_3 )Temp
order by rownum asc 

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @Script_Code,@Script_Name,@rownum
WHILE @@FETCH_STATUS = 0  
BEGIN  
print @Counter
update Test1 set Script_Name=UPPER(@Script_Name) where Script_Code=@Script_Code
print @Script_Code
set @Counter=@Counter+1
print @Counter

FETCH NEXT FROM db_cursor INTO @Script_Code,@Script_Name,@rownum
END  
CLOSE db_cursor  
DEALLOCATE db_cursor  

Some Basic On Asp.net

What is the sequence in which ASP.NET events are processed?
Following  is the sequence in which in which the events occur:
1Page_Init
2.Page Load
3.Control Events
4.Page Unload events

How can we identity that the page is Post Back?
Page object has an "IsPostBack" property,which can be checked to know that is the page posted back.

What is event bubbling?
Server control like Datagrid,DataList and Repeater can have other child controls inside them.
Example Datagrid can have combobox inside datagrid.These child control do not raise there events by themselves ,rather they pass event to the container parent which passed to the page "ItemCommand" events.
As the child control send events to parent it is termed as event bubbling

What is the difference between "Web.config" and "Machine.config" ?
"Web.config" files apply settings to each web application while "Machine.config" file apply settings to all ASP.Net application

What is a SESSION AND APPLICATION object?
Session object store information between HTTP request for a particular user, while application object are global across users.

What is difference between "Server.transfer" and "Response.redirect"?
"Response.redirect" sends message to the browser saying that it to move to some different page while server.transfer does not send any message to the browser but redirects the user directly from the server itself.

Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...