Tuesday, April 29, 2008

Client side validation on button click using Customvalidator

<asp:Panel ID=pn runat=server  DefaultButton=imagebutton1>
               <table width="620" height="60" cellpadding="0" class=tablesearchborder cellspacing="0">
                      <tr>
                        <td align="center" valign="middle"  background="images/searchnew.gif">
                                     <table width="620" height=55px cellpadding="0" cellspacing="0">
         <tr>
                              <td height="15"></td>
                              <td></td>
                              <td></td>
                              <td></td>
                              <td></td>
                              <td></td>
                            </tr>
       
                            <tr>
                              <td width="1"></td>
                              <td width="7" class="head1"> </td>
                              <td width="36" class="head1"> </td>
                              <td width="67" class="head1">Search</td>
                              <td width="382"><span class="searchboxdata">
                              <asp:TextBox runat=server    ID=ksearch  ValidationGroup=ks  CssClass="txt"></asp:TextBox>
                             
                              </span></td>
                              <td width="83" align=left><asp:ImageButton ID="ImageButton1"  ValidationGroup=ks Width=38 Height=24   ImageUrl="images/gobutton.gif"   OnClick="go"   runat=server/></td>
                            </tr>
                            <tr>
                              <td></td>
                              <td class="head1"> </td>
                              <td class="head1"> </td>
                              <td class="head1"> </td>
                              <td class="marquee">
                               <asp:RadioButtonList ID=rb RepeatColumns=2 ValidationGroup=ks RepeatDirection=Horizontal runat=server>
                           <asp:ListItem Value="KH" >Keyword/Bussiness/category</asp:ListItem>
                           <asp:ListItem Value="PH">Phone</asp:ListItem>
                            </asp:RadioButtonList>
                           </td>
                              <td> </td>
                            </tr>
                        </table>
                      
                        </td>
                      </tr>
                    </table>
                </asp:Panel>
             
             <asp:CustomValidator ID="cu" ValidationGroup=ks runat=server ControlToValidate=ksearch ValidateEmptyText=true ClientValidationFunction="check" ></asp:CustomValidator>
           <script language=javascript>

function check(source, arguments)
{
var box1 = document.getElementById('<%= ksearch.ClientID %>').value;
var box2 = document.getElementById('<%= rb.ClientID+"_0"');
// box2=box2+"_0";
// alert(box2.checked);
if(box2.checked==true)
{
if(box1=="")
{
alert("Please Enter a Keyword, Business or Category");
arguments.IsValid =false;
}
else
arguments.IsValid = true;
}
else
{
if(box1.length11 )
{
alert("Please Enter Phone Number(min:6 digit and max:10) ");
arguments.IsValid =false;
}
else
{ if(IsNumeric(box1))
arguments.IsValid = true;

else
{alert("Please Enter Only numeric Number ");
arguments.IsValid=false;
}
}
}
}
function IsNumeric(strString)
// check for valid numeric strings
{
var strValidChars = "0123456789";
var strChar;
var blnResult = true;

if (strString.length == 0)
return false;

// test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++)
{
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1)
{
blnResult = false;
}
}
return blnResult;
}

Wednesday, April 23, 2008

Autosuggestion, autocomplete textbox data from server(using ajax.dll)

lt;style type="text/css">
.Table
{
background-color:yellow;
font-family:Verdana;
font-size:10px;
width:200px;
}
.DefaultRowColor
{background-color:gray;
}
.HighlightRow

{background-color:#eeeeee;
}
</style>
</

head><

body>
<form id="form1" runat="server">
<div><

script language="javascript" type="text/javascript">var

word ='';
var

UP = 38; var

DOWN = 40; var

ENTER = 13;var

index = -1; var

TAB = 9; var

BACKSPACE = 8; var

table = null; var
rows = null;var
selectedRow = null;function
GetProducts(e)
{var
keynumvar

keycharvar

numcheckif

(window.event)// IE
{keynum = e.keyCode
}
else

if(e.which)// Netscape/Firefox/Opera
{keynum = e.which
}
keychar = String.fromCharCode(keynum)
numcheck = /d/
// If the down key is pressed
if

(keynum == DOWN)
{MoveCursorDown();
return;
}
else

if(keynum == UP)
{MoveCursorUp();return;
}
else

if(keynum == ENTER)
{if(IsFireFox())
{document.getElementById("txtSearch").value = selectedRow.childNodes[1].innerHTML;
}
else
{document.getElementById("txtSearch").value = selectedRow.innerText;
}
document.getElementById("results").innerHTML = '';
// false is returned so that the postback won't occur when the return key is pressedreturn false;
}if

(keynum != DOWN && keynum != UP && keynum >= 65 && keynum <= 90)
{ index=-1;
word = word + keychar;
}
else
if(keynum == BACKSPACE)
{index=-1;word=document.getElementById("txtSearch").value;
word = word.substring(0,word.length-1);
}
// Call the server side method

auto.GetSearhItmes(word,RecieveServerData_CallBack);
}function
IsFireFox()

{return (navigator.appName == 'Netscape');
}
function
MoveCursorUp(){
selectedRow = null;
table = document.getElementById("MyTable");
if(table == null) return;
rows = table.getElementsByTagName("TR");
if(index > 0)
{index--;SetDefaultRowColor();
selectedRow = rows[index];
selectedRow.className = 'HighlightRow'
}
}function

MoveCursorDown()
{selectedRow = null;
table = document.getElementById("MyTable");
if(table == null) return;
rows = table.getElementsByTagName("TR");
if(index < rows.length)
{
if(index < rows.length -1)
{index++;
SetDefaultRowColor();
selectedRow = rows[index];
selectedRow.className = 'HighlightRow';
}}}function

SetDefaultRowColor()
{for(i=0;i<rows.length;i++)
{rows[i].className = 'DefaultRowColor';
}
}function

RecieveServerData_CallBack(response)
{ var ds = response.value;
if(ds==null)
{document.getElementById("results").style.visibility="hidden";
}
elseif(ds != null && typeof(ds) == "object" && ds.Tables != null)
{var s = new Array();
s[s.length] = "<table border='0' cellpadding='0' cellspacing='0' id='MyTable' class='Table'>";
for(var i=0; i<ds.Tables[0].Rows.length; i++)
{s[s.length] = "<tr>";
s[s.length] = "<td>" + ds.Tables[0].Rows[i].keywordname + "</td>";
s[s.length] = "</tr>";
}s[s.length] = "</table>";
//tableDisplay.innerHTML = s.join("");
document.getElementById("results").innerHTML =s.join("");
document.getElementById("results").style.visibility="visible";
}
else
{alert("Error. [3001] " + response.request.responseText);
}}</

script>
Enter Search Text: <input type="text" onkeydown="return GetProducts(event)" id="txtSearch" name="txtSearch" autocomplete=off />

<div id=results></div>
auto.aspx.cs codebehind file
using
System;using
System.Data;using System.Data.SqlClient;using
System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using
System.Web.UI;using
System.Web.UI.WebControls;using
System.Web.UI.WebControls.WebParts;using
System.Web.UI.HtmlControls;public
partial class auto : System.Web.UI.Page{SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);protected void Page_Load(object sender, EventArgs e)
{Ajax.Utility.RegisterTypeForAjax(typeof(auto));
}
[Ajax.AjaxMethod()]
public DataSet GetSearhItmes(string str)
{DataSet ds = new DataSet();
if (str.Length > 0)
{SqlDataAdapter da = new SqlDataAdapter("select keywordname from keyword where keywordname like @text+'%'", con);
da.SelectCommand.Parameters.Add("@text", SqlDbType.VarChar).Value = str;
da.Fill(ds);}
else
ds = null;
return ds;
}
}


Saturday, April 12, 2008

export dataset in multiple excelsheet in asp.net

<asp:TextBox ID="txtname" runat="server"></asp:TextBox

<asp:Button ID="Export" runat="server" Text="Export" OnClick="Export_Click" />

public void DataSetToExcelSheet(DataSet source, string fileName)

 {

string strPath = Server.MapPath("ExcelFile"); //folder get pathSystem.IO.StreamWriter excelDoc = new System.IO.StreamWriter(strPath+"/" + fileName);

const string startExcelXML = "<xml version>rn<Workbook "

+"xmlns="urn:schemas-microsoft-com:office:spreadsheet"rn"

+ " xmlns:o="urn:schemas-microsoft-com:office:office"rn "

+ "xmlns:x="urn:schemas- microsoft-com:office:"

+ "excel"rn xmlns:ss="urn:schemas-microsoft-com:"

+ "office:spreadsheet">rn <Styles>rn "

+ "<Style ss:ID="Default" ss:Name="Normal">rn "

+ "<Alignment ss:Vertical="Bottom"/>rn <Borders/>"

+ "rn <Font/>rn <Interior/>rn <NumberFormat/>"

+ "rn <Protection/>rn </Style>rn "

+ "<Style ss:ID="BoldColumn">rn <Font "

+ "x:Family="Swiss" ss:Bold="1"/>rn </Style>rn "

+ "<Style ss:ID="StringLiteral">rn <NumberFormat"

+ " ss:Format="@"/>rn </Style>rn <Style "

+ "ss:ID="Decimal">rn <NumberFormat "

+ "ss:Format="0.0000"/>rn </Style>rn "

+ "<Style ss:ID="Integer">rn <NumberFormat "

+ "ss:Format="0"/>rn </Style>rn <Style "

+ "ss:ID="DateLiteral">rn <NumberFormat "

+ "ss:Format="mm/dd/yyyy;@"/>rn </Style>rn "

+ "</Styles>rn ";

const string endExcelXML = "</Workbook>";

int rowCount = 0;

int sheetCount = 1; //Sheet

excelDoc.Write(startExcelXML);

excelDoc.Write("<Worksheet ss:Name="sheet" + sheetCount + "">");

excelDoc.Write("<Table>");

excelDoc.Write("<Row>");

for (int x = 0; x < source.Tables[0].Columns.Count; x++)

{

excelDoc.Write("<Cell ss:StyleID="BoldColumn"><Data ss:Type="String">");

excelDoc.Write(source.Tables[0].Columns[x].ColumnName);

excelDoc.Write("</Data></Cell>"); }

excelDoc.Write("</Row>");

foreach (DataRow x in source.Tables[0].Rows)

{

rowCount++; //if the number of rows is > 64000 create a new page to continue output

if (rowCount == 64000)

{

rowCount = 0;

sheetCount++;

excelDoc.Write("</Table>");

excelDoc.Write(" </Worksheet>");

excelDoc.Write("<Worksheet ss:Name="Sheet" + sheetCount + "">");

excelDoc.Write("<Table>"); }

excelDoc.Write("<Row>"); //ID=" + rowCount + "

for (int y = 0; y < source.Tables[0].Columns.Count; y++)

{ System.Type rowType;

rowType = x[y].GetType();

switch (rowType.ToString())

{

case "System.String":

string XMLstring = x[y].ToString();

XMLstring = XMLstring.Trim();

XMLstring = XMLstring.Replace("&", "&");

XMLstring = XMLstring.Replace(">", ">");

XMLstring = XMLstring.Replace("<", "<");

excelDoc.Write("<Cell ss:StyleID="StringLiteral">" + "<Data ss:Type="String">");

excelDoc.Write(XMLstring);

excelDoc.Write("</Data></Cell>");

break;

case "System.DateTime":

//Excel has a specific Date Format of YYYY-MM-DD followed by

//the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000

//The Following Code puts the date stored in XMLDate

//to the format above

DateTime XMLDate = (DateTime)x[y];

string XMLDatetoString = ""; //Excel Converted Date

XMLDatetoString = XMLDate.Year.ToString()

+ "-"

+ (XMLDate.Month < 10 ? "0"

+ XMLDate.Month.ToString() :

XMLDate.Month.ToString())

+ "-"

+

(XMLDate.Day < 10 ? "0"

+

XMLDate.Day.ToString() :

XMLDate.Day.ToString())

+ "T"

+

(XMLDate.Hour < 10 ? "0" +

XMLDate.Hour.ToString() :

XMLDate.Hour.ToString())

+ ":"

+

(XMLDate.Minute < 10 ? "0" +

XMLDate.Minute.ToString() :

XMLDate.Minute.ToString())

+ ":"

+

(XMLDate.Second < 10 ? "0" +

XMLDate.Second.ToString() : XMLDate.Second.ToString())

+ ".000";

excelDoc.Write("<Cell ss:StyleID="DateLiteral">"

+

"<Data ss:Type="DateTime">");

excelDoc.Write(XMLDatetoString);

excelDoc.Write("</Data></Cell>");

break;

case "System.Boolean":

excelDoc.Write("<Cell ss:StyleID="StringLiteral">"

+

"<Data ss:Type="String">");

excelDoc.Write(x[y].ToString());

excelDoc.Write("</Data></Cell>");

break;

case "System.Int16":

case "System.Int32":

case "System.Int64":

case "System.Byte":

excelDoc.Write("<Cell ss:StyleID="Integer">" +

"<Data ss:Type="Number">");

excelDoc.Write(x[y].ToString());

excelDoc.Write("</Data></Cell>");

break;

case "System.Decimal":

case "System.Double":

excelDoc.Write("<Cell ss:StyleID="Decimal">"

+

"<Data ss:Type="Number">");

excelDoc.Write(x[y].ToString());

excelDoc.Write("</Data></Cell>");

break;

case "System.DBNull":

excelDoc.Write("<Cell ss:StyleID="StringLiteral">"

+

"<Data ss:Type="String">");

excelDoc.Write("");

excelDoc.Write("</Data></Cell>");

break;

default:

throw (new Exception(rowType.ToString() + " not handled."));

}

}

excelDoc.Write("</Row>");

}

excelDoc.Write("</Table>");

excelDoc.Write(" </Worksheet>");

excelDoc.Write(endExcelXML);

excelDoc.Close();

}

protected void Export_Click(object sender, EventArgs e)

{

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);

SqlDataAdapter sda = new SqlDataAdapter("select top 100000 regid,companyname from registration order by regid", con);

DataSet ds = new DataSet();

sda.Fill(ds);

DataSetToExcelSheet(ds, txtname.Text+".xls");

}

Friday, April 11, 2008

display custum text using case in sqlserver

SELECT FirstName, LastName,
       CASE WHEN sex ='M' THEN 'MALE'
            WHEN sex = 'F' THEN 'FEMALE'
            ELSE 'Undefined'
       END As Sex

FROM Employees

find Nth highest salary of employee by procedure

[sourcecode language="sql"]
Create proc GetNthmaxsalary
(
@high int
)
as
set nocount on
SELECT TOP 1 emp1.salary FROM ( SELECT DISTINCT TOP @high salary FROM emp ORDER BY salary DESC) as emp1 ORDER BY emp1.salary
go

}
[/sourcecode]

Creating Updated google New Using Google Rss in show in datagrid

in aspx page u write

[sourcecode language="html"]
<asp:DataList id="myDataGrid" Width=200px runat=server>

<ItemTemplate><%#Eval("description") %></ItemTemplate>

</asp:DataList>

[/sourcecode]


in codebehind
[sourcecode language="csharp"]
protected void Page_Load(object sender, EventArgs e)
{myDataGrid.DataSource = RssFeed.getrssdata().Tables[3];
myDataGrid.DataBind();

}

[/sourcecode]




[sourcecode language="csharp"]
public class RssFeed{

public RssFeed(){}

public static DataSet getrssdata()

{XmlTextReader reader = new XmlTextReader("http://news.google.com/news?ned=in&output=rss");

DataSet ds = new DataSet();

ds.ReadXml(reader);

return ds;

}

}
[/sourcecode]

using Ajax.dll show data from Database at time interval

[sourcecode language="html"]

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

<!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>Untitled Page</title></head>
<body onload="getDataSet();">
<form id="form1" runat="server">
<script language=javascript>

function getDataSet()
{
showdata.getdata(GetDataSet_callback);
}

function GetDataSet_callback(response)
{
var ds = response.value;

if(ds != null && typeof(ds) == "object" && ds.Tables != null)

{var s = new Array();

s[s.length] = "<table border=1>";

for(var i=0; i<ds.Tables[0].Rows.length; i++){

s[s.length] = "<tr>";

s[s.length] = "<td>" + ds.Tables[0].Rows[i].companyname + "</td>";

s[s.length] = "<td>" + ds.Tables[0].Rows[i].address + "</td>";

s[s.length] = "<td>" + ds.Tables[0].Rows[i].email1 + "</td>";

s[s.length] = "</tr>";

}

s[s.length] = "</table>";

tableDisplay.innerHTML = s.join("");

}

else{

alert("Error. [3001] " + response.request.responseText);

}

window.setTimeout(getDataSet,3000);

}

</script>

<div id="tableDisplay"></div>

<input type=button id="btn" onclick="getDataSet()" value="show" />

</form>
</body>
</html>
[/sourcecode]


[sourcecode language="csharp"]

using System;
using System.Data;
using System.Data.SqlClient;
usingSystem.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class showdata : System.Web.UI.Page
{
public static int i = 0;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());

protected void Page_Load(object sender, EventArgs e)

{Ajax.Utility.RegisterTypeForAjax(typeof(showdata));

}

[Ajax.AjaxMethod()]

public DataSet getdata()

{SqlDataAdapter cmd = new SqlDataAdapter("select companyname,address,email1 from registration where regdate=@cdate", con);

cmd.SelectCommand.Parameters.Add("@cdate", SqlDbType.DateTime).Value = Convert.ToDateTime("2/26/2007").AddDays(i++); ;

DataSet ds = new DataSet();

cmd.Fill(ds);

return ds;

}

}
[/sourcecode]

Thursday, April 10, 2008

Rediff Tab Code —Most Usefull

See Code

Caching data -fast performance

public class CacheSearch
{
protected DataSet _ds;
protected string ksearch;

public CacheSearch()
{
}

public static DataSet GetAlldataCIdKeyid(int cid, int kid)
{
return GetAlldataCityIdKeyid(HttpContext.Current, cid, kid);
}
protected static DataSet GetAlldataCityIdKeyid(HttpContext context, int cid, int kid)
{
string ksearchkey = “cachkey_” + cid.ToString() + “_” + kid.ToString();
DateTime expiration = DateTime.Now.AddMinutes(10);
DataSet allcidkey = context.Cache[ksearchkey] as DataSet;
if (allcidkey == null)
{
allcidkey = KEYWORDSEARCH.keysearchcidkeyid(cid, kid);
context.Cache.Add(ksearchkey, allcidkey, null, expiration, TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);

}
return allcidkey;
}

}



public class KEYWORDSEARCH
{
public static DataSet keysearchcidkeyid(int cid, int keyid)
{
DATALAYER dl = new DATALAYER();
dl.AddParameter(”@cid”, cid);
dl.AddParameter(”@kid”, keyid);
return dl.ExecuteDataSet(”getkeysearch”);
}
}

and codehind of page u write code which bind to datagrid
DataSet ds = CacheSearch.GetAlldataCIdKeyid(cid,kid);

this ds bind with datagrid and show better performance



here Datalayer is connection class if u want to according ur need u change

Recursively find control from previous page

hi

i study more time asp.net starter kit and i found best code for finding previous page server control.

But from prevoius page you must use postbackurl on button or use server.transfer(”go.aspx”);

The code is follow……..

public sealed class Util{
private Util(){}
public static Control FindControlRecursively(string controlID, ControlCollection controls){

if (controlID == null || controls == null)
return null;
foreach (Control c in controls)
{ if (c.ID == controlID)
return c;
if (c.HasControls())
{
Control inner = FindControlRecursively(controlID, c.Controls);
if (inner != null)
return inner;
}

}

return null;
}
}

Wednesday, April 9, 2008

Recursively find control from previous page

hi

i study more time asp.net starter kit and i found best code for finding previous page server control.

But from prevoius page you must use  postbackurl on button  or use  server.transfer("go.aspx");

The code is follow........

 

[sourcecode language="csharp"]

public sealed class Util{

private Util()
{

}
public static Control FindControlRecursively(string controlID, ControlCollection controls)
{

if (controlID == null || controls == null)
return null;
foreach (Control c in controls){
if (c.ID == controlID)
return c;
if (c.HasControls()){
Control inner = FindControlRecursively(controlID, c.Controls);
if (inner != null)
return inner;}
}

return null;
}
[/sourcecode]


Caching data -fast performance

[sourcecode language="csharp"]
public class CacheSearch
{
protected DataSet _ds;
protected string ksearch;

public CacheSearch()
{
}
public static DataSet GetAlldataCIdKeyid(int cid, int kid)
{
return GetAlldataCityIdKeyid(HttpContext.Current, cid, kid);
}
protected static DataSet GetAlldataCityIdKeyid(HttpContext context, int cid, int kid)
{
string ksearchkey = "cachkey_" + cid.ToString() + "_" + kid.ToString();
DateTime expiration = DateTime.Now.AddMinutes(10);
DataSet allcidkey = context.Cache[ksearchkey] as DataSet;
if (allcidkey == null)
{
allcidkey = KEYWORDSEARCH.keysearchcidkeyid(cid, kid);
context.Cache.Add(ksearchkey, allcidkey, null, expiration, TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);

}
return allcidkey;
}

}

public class KEYWORDSEARCH
{
public static DataSet keysearchcidkeyid(int cid, int keyid)
{
DATALAYER dl = new DATALAYER();
dl.AddParameter("@cid", cid);
dl.AddParameter("@kid", keyid);
return dl.ExecuteDataSet("getkeysearch");
}
}
[/sourcecode]
and codehind of page u write code which bind to datagrid

[sourcecode language="csharp"]
DataSet ds = CacheSearch.GetAlldataCIdKeyid(cid,kid);
[/sourcecode]
this ds bind with datagrid and show better performance

here Datalayer is connection class if u want to according ur need u change
AJAX, asp, Asp.net, asp.net and sql server security, Asp.net IntemIndex, C#, Css, DataBinder.Eval, DataKeyNames, Datalist, Datapager, DataSet, DataTable, DropDownList, FindControl, gridview, JavaScript, jquery, Listview, Paging, Regex, RegularExpression, Repeater, Server side validation, Sql Server, timer, timercallback, Validation, XML, xmlnode, XPath