Friday, December 26, 2008

Fill DropDownList By Using Professional Ajax (AjaxMethod Attribute and CallBack)

Hi..
Today I am going to post a very Basic but very important example .This is the example of the professional Ajax showing the usage of the "[Ajax.AjaxMethod()]" attrubute.
Here in this example i am just showing a string message and bind a dropdownList in javascript by calling the server side methods in javascript.
This is very basic example You can modify it according to your need .
Before doing all this you have to add refernce of ajax.dll in bin folder.
you can download the a sample project from HERE . This Project includs the ajax.dll also. you can get the dll from this link by downloading the sample project.

The step taken in this example are as given below.


Step 1.) Modification in web.config file
put the "< add verb="POST,GET...." in the HttpHandlers section in web.config as given below.

[system.web]
[httpHandlers]
[add verb="POST,GET" path="ajax/*.ashx"
type="Ajax.PageHandlerFactory, Ajax"/]
[/httpHandlers]


Step 2.) Make the AjaxMethod which we have to call in Javascript in Desgn file of the page Suppose we have the page
Test1.aspx in the folder "Sanjeev" (Sanjeev/Test1.aspx)
so the .cs file of the page looks like as given below..
Here the important things are :
A.) Ajax.Utility.RegisterTypeForAjax(typeof(Sanjeev_Test1));
Where "Sanjeev_Test1" is the Name of the ppartial class of the page.
B.) We have to put "[Ajax.AjaxMethod()]" attrubute before the method body.
=========================================================
using System;
using System.Data;
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 Sanjeev_Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(Sanjeev_Test1));
}
[Ajax.AjaxMethod()]
public string GetName()
{
//to alert the simple string message to test
return "Sanjeev Kumar Chauhan";
}
[Ajax.AjaxMethod()]
public DataSet getDataSet()
{
//use to get the DataSet by which we have to bind the
//DropdownList
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataColumn dcText = getDataColumn("Text");
DataColumn dcValue = getDataColumn("Value");
dt.Columns.Add(dcText);
dt.Columns.Add(dcValue);
string strName = "Name";
string strValue = "sanjeev";
for (int i = 0; i < 6; i++)
{
DataRow dr = dt.NewRow();
dr[dcText] = strName + i.ToString();
dr[dcValue] = strValue + i.ToString();
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
return ds;
}
public DataColumn getDataColumn(string ColName)
{
DataColumn dc = null;
dc = new DataColumn(ColName, System.Type.GetType("System.String"));
return dc;
}
}
==================================================
3.) the aspx file of the page :

[%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Sanjeev_Test1" %]
[!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]Untitled Page[/title]
[script language="javascript" type="text/javascript"]
// function GetTasks() //Using Call Back
// {
// Sanjeev_Test1.GetName(GetName_CallBack);
// }
//function GetName_CallBack(response)//The CallBack function
// {
// alert(response.value);
// return false;
// }
// Without Using Call Back this also works properly
function GetTasks()
{
var str = Sanjeev_Test1.GetName();
alert(str.value);
}
function getDS()
{
var resp = Sanjeev_Test1.getDataSet();
var ds = resp.value;
if(ds.Tables[0].Rows.length == 0 )
{

// document.getElementById("ddl").options.length=0;
alert("There is no Term");
}
else
{
document.getElementById("ddl").options.length=0;
if(ds.Tables[0].Rows.length ] 0 )
{
for(var i=0; i[ds.Tables[0].Rows.length; i++)
{
var o = document.createElement("option");
o.value = ds.Tables[0].Rows[i].Value;
o.text = ds.Tables[0].Rows[i].Text;
document.getElementById('ddl').add(o);
}
}
}
}
[/script]
[/head]
[body]
[form id="form1" runat="server"]
[div]
[input type="button" id="btnHTML" value="ShowName" onclick="return GetTasks();" /]
[br /]
[input type="button" value="Fill DropDown" onclick="getDS();" /]
[asp:DropDownList ID="ddl" runat="server"]
[/asp:DropDownList]
[/div]
[/form]
[/body]
[/html]
================================================================
I hope you will enjoy this.
Thanks :
Sanjeev Kumar
HelpOnDeskTeam

Monday, December 22, 2008

Show Formatted Date And Time Using Java Script...

Hello...
Today , I m here to give an example how to get the formated Date And Time using Java Script, and the Format is Like "Mon Dec 22 2008 10:52:07 PM" . so have a look on the following example...

function ShowFormattedDateAndTime()
{
var now = new Date() ;
var time=now.toLocaleTimeString();
var dayname=now.toDateString();
var totaldaytime=dayname+" "+time;
document.getElementById("Lbl").innerHTML="Draft Auto Saved at " + totaldaytime;
}


Sanjeev Kumar
HelpOn Desk Team

Friday, December 19, 2008

How to check the Date Format Using SQL SERVER 2005

Hello ...
Today , I am presenting a very Good Stored procedure as well as the UseDefined funtion and its use in the stored procedure the date formate is MM/DD/YYYY.
-- The Procedure is Used to get the Data For Event start date,Begin Time and End Time.
CREATE proc [dbo].[usp_GetEventDateTime]
(
@eventId uniqueidentifier
--The EventId corresponds to which we have to get data
)
AS
BEGIN
Select eventDateTimeId, eventDate, beginTime, endTime
,dbo.udf_IsValidEventStartTimeFormat(beginTime) As 'StartTimeFormat', dbo.udf_IsValidEventEndTimeFormat(endTime) As 'EndTimeFormat'
From EventDateTime
Where eventId = @eventId
--dbo.udf_IsValidEventStartTimeFormat is used to get the correct format of the Time
END
The UserDefined Functio IsValidEventStartTimeFormatn Is Geven As Given Below:

============================================================================
CREATE FUNCTION [dbo].[udf_IsValidEventStartTimeFormat] (@beginTime varchar(50))
RETURNS smallint
AS
BEGIN
Declare @ReturnVal smallint
Set @ReturnVal = 1
If @beginTime = '' Or @beginTime IS NULL Or
CharIndex(':',@beginTime) <> 3 Or
CharIndex(' ',@beginTime) <> 6 Or
Len(SubString(@beginTime,CharIndex(' ',@beginTime)+1,Len(@beginTime))) != 2 Or
SubString(@beginTime,CharIndex(':',@beginTime)+1,1) = ' ' Or
isnumeric(substring(@beginTime,0,CharIndex(':',@beginTime))) !=1 Or
isnumeric(SubString(@beginTime,CharIndex(':',@beginTime)+1, CharIndex(' ',@beginTime) - (CharIndex(':',@beginTime)+1) ) ) !=1
Set @ReturnVal = 0 -- If not valid time format (HH:MM AM/PM)
RETURN @ReturnVal
END
With Love..
Sanjeev Chauahn
HelpOnDesk Team

Wednesday, December 17, 2008

Display On Status Bar Of the Browser Window

Hi ...

Hi this time I am here with some easy wonder of java script . when you play with this I am sure you will enjoy this.

The 1st one is About :When we want to display the current Time in Status Bar. then You have to call the following java script function whereEver you need(Generally It will be called onload of the body in HTML)



function ShowTime()
{
var TimerKey
var now = new Date()
var Hours = now.getHours()
var Minutes = now.getMinutes()
var Seconds = now.getSeconds()
var TimeDisplay = document.getElementById("lblTime");
TimeDisplay.innerText = ((Hours > 12) ? Hours - 12 : Hours) + ((Minutes <> 12) ? " PM" : " AM")
window.status = ((Hours > 12) ? Hours - 12 : Hours) + ((Minutes <> 12) ? " PM" : " AM")
TimerKey = setTimeout("ShowTime()",1000)
}


var messageNum = 0;
function messageChanger()
{
if (messageNum ==0) {
defaultStatus = "Welcome to our Blog...";
messageNum = 1;
}
else
{
defaultStatus = "C#,JavaScript Articles";
messageNum = 0;
}
//Schedule the next message
setTimeout("messageChanger();", 3000);
}

And the 2nd one is About :When we want to display our Custom Message in Status Bar. then You have to call the following java script function whereEver you need(Generally It will be called onload of the body in HTML)

2.)


var messageNum = 0;
function messageChanger()
{
if (messageNum ==0) {
defaultStatus = "Welcome to our Blog...";
messageNum = 1;
}
else
{
defaultStatus = "C#,JavaScript Articles";
messageNum = 0;
}
//Schedule the next message
setTimeout("messageChanger();", 3000);
}

Thanks :

Sanjeev Chauhan

HelpOn Desk Team

Tuesday, December 16, 2008

use checkboxlist as checkboxsradiolist in javaScript

Hello,
In this week I got a very intresting problem and for solving it we have to use JAVAScript.
look a simple view on problem. we are using the checkbox list for selection cretieria.
we have 5 checkbox list but 2 check box list used as an radiobutton list. means user can select
one option at a time and his previous selection must be show until he choose the other next
choice.
Other three are simple in which new selction is added as we do by default.
so consentrate on problem. for solveing it i created function saveMouserOverID(control)
which get the id of control where mouse jump upon the control.
and after it created a javascript fucntion CheckUnCheckBox(crtl) wehre if control goes in to
default case it will unchech all check box expect the currently clicked check box.
b'cz this id is stored in saveMouseOverFunction();
view of the code is follows.
We can also store that id in hiddenfield and first uncheckall the checkbox and after it check
the control where id is stored in hidden field.

Thanks
HElpOnDesk Team


structure of checkboxList

[asp:CheckBoxList onClick="return CheckUnCheckBox('ssss');" ID="RS" OnSelectedIndexChanged="dosomeserverside"
RepeatColumns="setIntasuwant" CellSpacing="setIntasuwan"
runat="server" AutoPostBack="True"]
[asp:ListItem onmouseover="javascript:saveMouserOverID('0')" Text="select ALL" Value="Selectall"][ /asp:ListItem]
[asp:ListItem onmouseover="javascript:saveMouserOverID('1')" Text="helpindesk" Value="Helpondesk"][ /asp:ListItem]
[asp:ListItem onmouseover="javascript:saveMouserOverID('2')" Text="sanjeev"
Value="Sanjeev"][ /asp:ListItem]
[ /asp:ChekcBoxList/]


function saveMouserOverID(control)
{
controlid=control;

}

function CheckUnCheckBox(ctrl)
{
var checkbox = document.getElementById('ctl00_ContentPlaceHolder1_'+ctrl);
var inputlist = checkbox.getElementsByTagName("input");
var i=0;
var id;
switch(ctrl)
{
case "shape":
for(i=0; i[inputlist.length; i++)
{
//id = 'checkImage'+(parseInt(i)+parseInt('4'));
if(inputlist[i].checked)
{
if(controlid == 0 && controlid != i)
{
inputlist[i].checked = '';
// document.getElementById(id).src=imgFalse;
}
else if(controlid !=0 && i==0)
{
inputlist[i].checked = '';
//document.getElementById(id).src=imgFalse;
}
}
}
break;
case "color":
for(i=0; i[inputlist.length; i++)
{
//id = 'checkImage'+(parseInt(i)+parseInt('23'));
if(inputlist[i].checked)
{
if(controlid == 0 && controlid != i)
{
inputlist[i].checked = '';
//document.getElementById(id).src=imgFalse;
}
else if(controlid !=0 && i==0)
{
inputlist[i].checked = '';
//document.getElementById(id).src=imgFalse;
}
}
}
break;

default:
for(i=0; i[inputlist.length; i++)
{
// if(ctrl == 'weight')
// {
//
// }
// else if(ctrl == 'price')
// {
//
// }
if(inputlist[i].checked)
{
if(controlid != i)
{
inputlist[i].checked = '';

}
}
else
{
inputlist[i].checked = '';

}
}
}
}
[/script]

Friday, December 12, 2008

APPLY GOOGLE LIKE SEARCH STORED PROCEDURE

Hi..

Today I m posting a very good as well as very important Stored procedure which is used to apply the google type search in your data base here in this SP i am giving the IDs of the table in which i want to search.
Please have a look its very intersting..


CREATE PROCEDURE PROC_Google_Like_Search
(
@InputText varchar(100)
)
AS
BEGIN
SET NOCOUNT ON;

declare @SearchChar varchar(8000)
Set @SearchChar = '%'+ @InputText+ '%'--'%partner%'--, '11/11/2006'

declare @CMDMain varchar(8000), @CMDMainCount varchar(8000),@CMDJoin varchar(8000)
declare @ColumnName varchar(100),@TableName varchar(100)

declare dbTable cursor for
SELECT
Distinct b.Name as TableName
FROM
sysobjects b
WHERE id in ( 1195151303,1115151018,859150106) --*** see The Note Comment for this

-- b.type='u' and b.Name <> 'dtproperties'
--order by b.name
open dbTable
fetch next from dbTable into @TableName

WHILE @@FETCH_STATUS = 0
BEGIN
declare db cursor for
SELECT
c.Name as ColumnName
FROM
sysobjects b,
syscolumns c
WHERE
C.id = b.id and
b.type='u' and b.Name = @TableName
order by b.name

open db
fetch next from db into @ColumnName

set @CMDMain = 'SELECT ' + char(39) + @TableName + char(39) + ' as TableName,'+
' ['+ @TableName + '].* FROM [' + @TableName + ']'+
' WHERE '
set @CMDMainCount = 'SELECT Count(*) FROM [' + @TableName + '] Where '
Set @CMDJoin = ''

WHILE @@FETCH_STATUS = 0
BEGIN

set @CMDJoin = @CMDJoin + 'Convert(varchar(5000),[' +@ColumnName + ']) like ' + char(39) + @SearchChar + char(39) + ' OR '

fetch next from db into @ColumnName
end
close db
deallocate db

Set @CMDMainCount = 'If ('+ @CMDMainCount + Left(@CMDJoin, len(@CMDJoin) - 3)+ ') > 0 Begin '
Set @CMDMain = @CMDMainCount + @CMDMain + Left(@CMDJoin, len(@CMDJoin) - 3)
Set @CMDMain = @CMDMain + ' End '

Print @CMDMain

exec (@CMDMain)

fetch next from dbTable into @TableName
end
close dbTable
deallocate dbTable
END



***NOTE :-
To get the table id to be searched from the sysObject..
Select * from sysobjects where xtype='u' order by crdate desc



Thanks ...
Sanjeev Chauhan
HelpOnDesk Team

Code Help to Upload Image In Binary Format in SQL SERVER DB

Hi...

The coming post is about to How we can store image in to the database in a binary foramt.
we are very thankful to Mr. Shameem Pundeer for his kind supports ..And I hope it will be carry on in the future..


Color1 is Datagird name. On Updatecommand of datagrid we write code to upload vedio and image in sql-server database.

private void color1_UpdateCommand(object source, DataGridCommandEventArgs e)
{
int getItemID = Convert.ToInt32(color1.DataKeys[e.Item.ItemIndex]);
System.Web.UI.HtmlControls.HtmlInputFile File1 = (System.Web.UI.HtmlControls.HtmlInputFile)e.Item.Cells[0].Controls[1];
System.Web.UI.HtmlControls.HtmlInputFile File2 = (System.Web.UI.HtmlControls.HtmlInputFile)e.Item.Cells[1].Controls[1];
TextBox txt1 = (TextBox)e.Item.Cells[2].Controls[1];
TextBox txt2 = (TextBox)e.Item.Cells[3].Controls[1];


if(File1.Value != "")// to upload vedio file on sql-server database
{

string fpath = File1.PostedFile.FileName;
string fName = System.IO.Path.GetFileName(fpath);
string currPath = Request.PhysicalApplicationPath;
File1.PostedFile.SaveAs(currPath+ "/_video/" + fName);

string SqlUpdFName = "update item set fileName='" + fName + "'" + " where itemID=" + getItemID ;
int AffrowUpd = Convert.ToInt32(oDBManager.ExecuteNonQuery(SqlUpdFName));
}

if(File2.Value != "")// Upload image file to sql-server database in binary format
{
////////////////////Deleting Last Image Which has to Update////////////////////////
string SqlDelImg = "Delete from image where itemID =" + getItemID;
int rowAff3 = Convert.ToInt32(oDBManager.ExecuteNonQuery(SqlDelImg));

////////////////////////////////////////////////////////////////////////////////////

int len = File2.PostedFile.ContentLength;
double k = Convert.ToDouble(len);
byte[] pic = new byte[len];
File2.PostedFile.InputStream.Read (pic, 0, len);
string imgContentType = File2.PostedFile.ContentType;
string imgName1 = File2.Value;
SqlConnection Conn = new SqlConnection(@ConfigurationSettings.AppSettings["ConnectionString"]);

try
{
Conn.Open ();
SqlCommand cmd1 = new SqlCommand ("insert into image" + "(imageContent, imageType, imageName, imageSize, itemID) values (@imageContent,@imageType, @imageName, @imageSize, @itemID )", Conn);
cmd1.Parameters.Add ("@imageContent",pic );
cmd1.Parameters.Add ("@imageType", imgContentType);
cmd1.Parameters.Add ("@imageName", imgName1);
cmd1.Parameters.Add ("@imageSize", k);
cmd1.Parameters.Add("@itemID",getItemID);



cmd1.ExecuteNonQuery ();
}
finally
{
Conn.Close ();
}



}

if(txt1.Text != "")
{
string SqlUpdIName = "update item set itemName='" + txt1.Text + "'" + " where itemID=" + getItemID;
int affUpdRow1 = Convert.ToInt32(oDBManager.ExecuteNonQuery(SqlUpdIName));

}

if(txt2.Text != "")
{
string SqlUpdPrice = "update item set itemPrice=" + txt2.Text + " where itemID=" + getItemID;
int affUpdRow2 = Convert.ToInt32(oDBManager.ExecuteNonQuery(SqlUpdPrice));

}


color1.EditItemIndex = -1;
BindDataGrid();



}

Thanks:
Sanjeev Kumar
HelpOnDesk Team

Thursday, December 11, 2008

Getting Contant Page Value To Master Page

Hi..

Now I am going to describe How we can pass the value from content Page to its Master Page.
This code is given by One of my Best Friend Mr. Shameem Pundeer.

on master page:
< asp:Label ID="lblGetVal" Visible="false" runat="server" Text="0">
I want to get text value from content page then i have to write on content page as below
((Label)Master.FindControl("lblGetVal")).Text = Convert.ToString(star_overall);
//Where star_overall is a variable on .cs file of content page
//use this on master page

GetvalfromContant = Convert.ToInt32(lblGetVal.Text);




Enjoy Coding...
Sanjeev Chauhan
HelpOnDesk Team

Tuesday, December 9, 2008

JAVA SCRIPT IMAGE ROTATOR - SLIDE SHOW

Hi ..

Today I m going to describe you How we can do image ratation(slide Show as in flash),This is very simple and frankly I got it by googleing(he he he...).And you also enjoy this.

Here is the Code..


[html xmlns="http://www.w3.org/1999/xhtml" ]
[head runat="server"]
[title]Untitled Page[/title]

[script type="text/javascript" type="text/javascript"]

var image1=new Image()
image1.src="Images/4.JPG"
var image2=new Image()
image2.src="Images/5.JPG"
var image3=new Image()
image3.src="Images/6.JPG"

//variable that will increment through the images
var step=1
function slideit()
{
//if browser does not support the image object, exit.
if (!document.images)
return
document.images.slide.src=eval("image"+step+".src")
if (step[3)
step++
else
step=1
//call function "slideit()" every 2.5 seconds
setTimeout("slideit()",2500)
}

[/script]
[/head]
[body onload="slideit();"]
[form id="form1" runat="server"]
[div]
[img src="Images/4.JPG" name="slide" width="300" height="156" /]
[/div]
[/form]
[/body]
[/html]



Enjoy the Image Rotating..

Sanjeev Chauhan
HelpOnDesk Team

Thursday, December 4, 2008

How to create and save the XML from a String in Server

Hello ...

Once Again I m here and presenting a post .This Post is really very good when You have to create an Xml file for the flash implemrntaion .You can use this.


protected void CreateXml()
{
XmlDocument empDoc = new XmlDocument();
Response.ContentType = "text/xml";
DataSet ds = getdata("test_GetXML");
XmlDocument UpcomeDoc = new XmlDocument();
Response.ContentType = "text/xml";
if (ds.Tables[0].Rows.Count > 0)
{
try
{
////Load the XML from a String
empDoc.LoadXml("" +
"" +
"First Name" +
"Last Name" +
"
City" +
// "WA99999" +
"
");
////Save the XML data onto a file
empDoc.Save(MapPath("EmployeesNew.xml"));
Response.Write(empDoc.InnerXml);
}
catch (XmlException xmlEx)
{
Response.Write("XmlException: " + xmlEx.Message);
}
catch (Exception ex)
{
Response.Write("Exception: " + ex.Message);
}
}
}


Thax....
Sanjeev Kumar
HelpOnDesk Team

Wednesday, December 3, 2008

Sending Mail Using SMTP Server Credentials

Hi..

Here you will find the quick reference of mail Sending.
have a look and enjoy..
==================================================================
The Class File Where The Email Manager class resides...
==================================================================
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Configuration;
namespace CommonEmailManager
{
public class MailManager
{
private bool _issent;
private string _toAddress;
private string _strFileName;
public MailManager()
{
}
///
/// This Method Is used to send the mail
///

/// Contents of an e-mail
public void Send(MailContents emailcontents)
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //add port number 587
NetworkCredential mailAuth = new NetworkCredential("MyMaiId@gmail.com", "MyPwd");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = mailAuth;
MailAddress from = new MailAddress(emailcontents.FromEmailAddress, emailcontents.FromName);
MailAddress to = new MailAddress(ToAddress);
MailMessage message = new MailMessage(from, to);
message.Subject = emailcontents.Subject;
message.Body = emailcontents.Body;
message.IsBodyHtml = true;
if (emailcontents.FileName != null)
{
message.Attachments.Add(new Attachment(emailcontents.FileName));
}
try
{
client.Send(message);
IsSent = true;
}
catch (Exception ex)
{
throw ex;
}

}

///
/// This Method Is used to send the mail having with an attachment with it
///

/// Contents of an e-mail
public void SendAttachment(MailContents emailcontents)
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //add port number 587
NetworkCredential mailAuth = new NetworkCredential("MyMaiId@gmail.com", "MyPwd");
client.EnableSsl = true;client.UseDefaultCredentials = false;
client.Credentials = mailAuth;MailAddress from = new MailAddress(emailcontents.FromEmailAddress, emailcontents.FromName);
MailAddress to = new MailAddress(ToAddress);
MailMessage message = new MailMessage(from, to);
message.Subject = emailcontents.Subject;
message.Body = emailcontents.Body;
message.IsBodyHtml = true;
Attachment atch = new Attachment(emailcontents.FileName);
message.Attachments.Add(atch);
try
{
client.Send(message);
IsSent = true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
atch.Dispose();

}

}

public bool IsSent
{
get { return _issent; }
set { _issent = value; }
}
private string SMTPServerName
{
get { return ConfigurationManager.AppSettings["SMTPServer"]; }
}
public string ToAddress
{

get
{
return _toAddress;
}
set
{
_toAddress = value;
}

}
}
public struct MailContents
{
public string To;
public string FromName;
public string FromEmailAddress;
public string Subject;
public string Body;
public string FileName;

}

}


==================================================================

The Page code from where We send the Email ...And on Which WE call the emailManger.cs class methods.
==================================================================

using System;
using System.Data;
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;
using System.Data.SqlClient;
using System.Web.Mail;
using System.IO;
using CommonEmailManager;

public partial class Admin_AdminNewLetterSend : System.Web.UI.Page
{
//Do Your Code
protected void Page_Load(object sender, EventArgs e)
{
//Do Your Code
}

protected void btnSendmail_Click(object sender, EventArgs e)
{
string strMsg = string.Empty;
try
{
//targetEmailId will be get in any how...
SendingMail(targetEmailId);
strMsg = "The News Letter has been sent successfully...";
}
catch (Exception ex)
{
strMsg = "There is Some Error to send the newsletter this time .Please try again";
}
finally
{
ConfirmJScript(strMsg);
}
}
public void ConfirmJScript(string strMsg)
{
string JScript = "alert('" + strMsg + "');";
JScript = "";
ClientScript.RegisterStartupScript(this.GetType(), "JScript", JScript);
}
public void SendingMail(string TargetEmailId)
{
CommonEmailManager.MailManager emailmngr = new MailManager();
CommonEmailManager.MailContents contents = new MailContents();
string msgBody = "my Message Body(I May be HTML Body)";
contents.Body = msgBody;
contents.FromEmailAddress = "My EmailID@gmail.com";
contents.Subject = "My Meassage";
emailmngr.ToAddress = TargetEmailId;
emailmngr.Send(contents);
}

}
==================================================================

Enjoy mail Sending

Sanjeev Kumar
HelpOnDesk Team

Searching Filter With Dynamic Query

Hi.

I am little bit weak in the field of Data Base .Many of you know this yet I want to share a DB stored procedure with .This SP helps you as a template when you have to Get some data with filters.


CREATE Procedure [dbo].[AdminOngoingAuction]
(
@BidID as smallint=1 , ---ProductId as mortgage or car insurance
@State as varchar(20)='',
@City as varchar(50)='',
@Zipcode as varchar(50)='',
@BuyerFName as varchar(100)='',
@BuyerLName as varchar(100)='',
@OpeningDate as datetime=null,
@ClosingDate as datetime=null,
@BidTimes as varchar(20)='',
@LoanTerm as int=0,
@PropertyValue as money=0,
@ResidenceStatus as int=0, --Propery Use ID
@LoanPurpose as int=0,
@LoanAmount as money=0,
@StartingBid as varchar(100)='',
@CurrentBid as varchar(100)='',
@totalbids as int=-1,
@FiveMinueRule as int=0,
@FrontDebtRatio as varchar='', -----
@BackDebtRatio as varchar='', -----
@CompletedDate as datetime=null, -----
@MaxLTV as varchar(5)='', -----
@MinLTV as varchar(5)='', -----
@MaxFicoScore as varchar(5)='',
@MinFicoScore as varchar(5)='', ----
@SSN as Bigint=0,
@BuyerEmail as varchar(100)=''

)
as
Begin
declare @query as varchar(Max)

if (len(@State)>2)
select @State=statename from state where statefname=@state

set @query= 'select Distinct(AUC.loanrequestid),(''AUC0'' + convert(varchar,BOI.LoanRequestID)) as AuctionID,AUC.BuyerID,AUC.StartDate,AUC.EndDate,
(select count(id) from auction where loanrequestid=AUC.LoanRequestId and bid is not null) as Totalbids,
(select min(bid) from auction where loanrequestid=AUC.LoanRequestId) as Currentbid,
(select max(bidsubmitdate) from auction where loanrequestid=AUC.LoanRequestId) as latestBidTime,
BOI.BorrowerFirstName + '' '' + BOI.BorrowerLastName as BuyerName,
(select BUd.EmailID as BuyerEmail from buyernotification BN inner join BuyerDetails BUd
on BN.BuyerId = BUd.BuyerId where Mail =''1'' and AuctionDisabled =''1'')as BuyerEmail,
BOI.City, BOI.State, BOI.ZIPID,
MLT.LoanAmount, MLT.NoOfmonth as LoanTerm, BLP.OpeningBid as StartingBid, PRI.LoanPurposeID,
PRI.PropertyUseID, PRI.OriginalCost as PropertyValue, (MOT.MortgageType + '', '' + convert(varchar,MLT.NoOfmonth) + '', '' + LOP.LoanPurpose) as MortgageType, MOT.MortgageType, MLT.InterestRate,

PRT.PropertyType from Auction AUC
inner join borrowerinformation BOI on BOI.loanrequestid=AUC.loanrequestid
inner join buyerloanprofile BLP on BLP.loanrequestid=BOI.loanrequestid
inner join propertyinformation PRI on BLP.loanrequestid=PRI.loanrequestid
inner join PropertyType PRT on PRT.PropertyTypeID=PRI.PropertyTypeID
inner join MortgageLoanTerm MLT on MLT.loanrequestid=PRI.loanrequestid
inner join MortgageType MOT on MOT.MortgageTypeID=MLT.MortgageTypeID
inner join LoanRequest LOR on LOR.loanrequestid=PRI.loanrequestid
inner join LoanPurpose LOP on LOP.LoanID=PRI.LoanPurposeID
inner join BuyerDetails BUD on BUd.BuyerID=LOR.BuyerID

where AUC.IsDisabled is Null and AUC.IsCompleted is Null and AUC.IsChallenged is Null and AUC.adminstatus is Null
and BUD.bidtype=' + convert(varchar, @bidID)

if (@State <>'')
set @query= @query + 'and BOI.State=''' + @State + ''''
if(@City<>'')
set @query= @query + 'and BOI.city=''' + @City + ''''
if(@Zipcode<>'')
set @query= @query + 'and BOI.zipid=''' + @Zipcode + ''''
if(@BuyerFName<>'')
set @query= @query + 'and BOI.BorrowerFirstName=''' + @BuyerFName + ''''
if(@BuyerLName<>'')
set @query= @query + 'and BOI.BorrowerLastName=''' + @BuyerLName + ''''
if(@SSN>0)
set @query= @query + 'and BOI.SSN=' + convert(varchar, @SSN)
if(@BuyerEmail<>'')
set @query= @query + 'and BUD.EmailId=''' + @BuyerEmail + ''''

if isdate(@OpeningDate)=1
set @query=@query + ' and CONVERT(CHAR(10),AUC.StartDate,101)=''' + CONVERT(CHAR(10),@OpeningDate,101) + '''' if isdate(@ClosingDate)=1
set @query=@query + ' and CONVERT(CHAR(10),AUC.EndDate,101)=''' + CONVERT(CHAR(10),@ClosingDate,101) + ''''
if(@LoanTerm > 0)
set @query= @query + 'and MLT.NoOfmonth=' + convert(varchar,@LoanTerm)

if(@MinFicoScore <>'')
set @query= @query + ' and MLT.FicoScore >='+ @MinFicoScore
if(@MaxFicoScore <>'')
set @query= @query + ' and MLT.FicoScore <=' + @MaxFicoScore

if (@FiveMinueRule =1)
set @query= @query + 'and AUC.FiveMinuteRule=1'
if (@FiveMinueRule =0)
set @query= @query + 'and (AUC.FiveMinuteRule=0 or AUC.FiveMinuteRule is null)'


if (@PropertyValue>0)
set @query= @query + 'and PRI.OriginalCost <=' + convert(varchar,@PropertyValue)
if(@ResidenceStatus >0)
set @query= @query + 'and PRI.PropertyUseID=' + convert(varchar,@ResidenceStatus)
if(@LoanPurpose >0)
set @query= @query + 'and PRI.LoanPurposeID=' + convert(varchar,@LoanPurpose)
if(@LoanAmount>0)
set @query= @query + 'and MLT.LoanAmount <=' + convert(varchar,@LoanAmount)
if(@StartingBid<>'')
set @query= @query + 'and BLP.OpeningBid=''' + @StartingBid + ''''
if(@CurrentBid<>'')
set @query= @query + 'and (select min(bid) from auction where loanrequestid=AUC.LoanRequestId) =''' + @CurrentBid + ''''
if @totalbids<>-1
set @query=@query + ' and (select count(bid) from auction where loanrequestid=AUC.LoanRequestId and bid is not null) = ' + CONVERT(varchar,@TotalBids)
if @BidTimes<>''
set @query=@query + ' and (select CONVERT(CHAR(5),max(bidsubmitdate),108) from auction where loanrequestid=AUC.LoanRequestId and bid is not null) = ''' + dbo.AddTimetToBidTime(@BidTimes) + ''''

Exec(@query)

End



Enjoy...
Sanjeev Chauhan
HelpOnDesk Team

Thursday, November 27, 2008

The use Of window.opener function in Java Script .

HI All.


Today I m going to describe the use of the window.opner function .Basically It is used to update the Value Of parent page from the child pop Up page.

The fully described code is given as below.

Step 1.) Parent Page.

A.) Script of the parent page :


function goChild()
{

window.open("~\WindowOpener\ChildPage.aspx");

}



B.)HTML of this page is :

[form id="form1" runat="server"]
[div]
[asp:Label ID="lblSum" runat="server" /][br /]

[br /]
[asp:Button ID="btnChild" OnClientClick="goChild();" Text="PopUp Open" runat="server" / /]
[br /]
[/div]
[/form]

C.) The Code Behind File of the Page.

There is no need to write any line of the code for this little Example




Step 2.)child Popup page.


A.) Script of the Child popUp page

function SumAndGO(varValue)
{
self.close();
window.opener.document.getElementById('lblSum').innerHTML=varValue;
}
function Validation(varValue)
{
for(i=0; i< varValue.length ;i++)
{
alert(varValue.charCodeAt(i));
}
}



B.) HTML of this page is :

[body]
[form id="form1" runat="server"]
[div]
Number 1: [asp:TextBox onblur="Validation(this.value);" ID="TxtNum1" runat="server"][/asp:TextBox][br /]
Number 1: [asp:TextBox ID="TxtNum2" runat="server"][/asp:TextBox][br /]
[asp:Button ID="btnSum" runat="server" Text="Go For Sum" OnClick="btnSum_Click" /]
[/div]
[/form]
[/body]




c.) The Code Behind File of the Page.

protected void btnSum_Click(object sender, EventArgs e)
{
int sum = Convert.ToInt32(TxtNum1.Text) + Convert.ToInt32(TxtNum2.Text);
string Jscript = "SumAndGO(" + sum + ")";
Jscript = "";
ClientScript.RegisterStartupScript(typeof(Page), "Jscript", Jscript);
}




Regards:
Sanjeev Chauhan

Tuesday, November 25, 2008

How To Register Client Script Inside Update Panel.

Hi EveryBody...

To use client script inside an update panel at runtime, you have to use "ScriptManager.RegisterClientScriptBlock". Just check if the input parameters are right, say for example you have:

ScriptManager.RegisterClientScriptBlock(UpdatePanelName, UpdatePanelName.GetType(), "jscript", "JavaScript Function", true);

Here parameter 1: the name of your update panel (Control Name).
parameter 2: you are passing the type of control, you have GetType() function which returns the type of control
parameter 3: telling it is "jscript" you want to execute
parameter 4: the name of the JavaScript function you want to call
parameter 5: true to enclose the script block in tags; otherwise, false.

For example we can use it as given below:-

string JScript = string.Empty;
JScript = "alert('Jai Sri RamChandra ji maharaaj')";
JScript = "[script language='javascript']" + JScript + "[/script]";
ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "JScript", JScript,false);




Hope this improves your coding.

Sanjeev Chauhan

Friday, November 21, 2008

Set The Default Enter button

HI

Now some kidding with a small and easy javascript stuff.



Set The Default Enter button on any textbox when we press the Enter

// this.txtusername.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + imgbtnlogin.UniqueID + "').click();return false;}} else {return true}; "); this.txtpwd.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + imgbtnlogin.UniqueID + "').click();return false;}} else {return true}; "); this.imgbtnlogin.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + imgbtnlogin.UniqueID + "').click();return false;}} else {return true}; ");



Sanjeev Kumar

Using of Javascript Trim Functions

Hello again ..


The follwing code can be used to trim the string in java script.



function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
return stringToTrim.replace(/\s+$/,"");
}

// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+trim(myString)+"*");
alert("*"+ltrim(myString)+"*");
alert("*"+rtrim(myString)+"*");


Regards:
Sanjeev Chaudhary

How to call Javascript after pageLoad Within UpdatePanel Like ClientScript...

Hi Every Body..

Today we are here to discuss really a vary interesting topic. You will enjoy it and it is vary usefull in several conditions.
How to call Javascript after some processing in Codebehind when we are in a update panel You know. clientscript is not working with update panel and master Page. So ummm.. there is problem. after a long googleing and some RnD finally I got the sloution.
The step for solution is geiven Below...

1.) On HTML page write the follwing line of code in java script


function load() {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(testfunction);
}
In above "testfunction" is our java script function which we want to call in C# code after some processing within an Update Panel.

2.)
write the function as below:
function testfunction()
{
var i=0;
var ctrl = document.getElementById('ctl00_ContentPlaceHolder1_hid');
// Where ctl00_ContentPlaceHolder1_hid is an hiden field which is used to get updated value from code behind.
if(ctrl.value!="Some Condition")
{
// here Put your code which you want after page load..
}

}


3.)Now move to Code Behind...C# File of the page

on Page LoadEvent
protected void Page_Load(object sender, EventArgs e)
{
imgButton.Attributes.Add("onload", "load()");
// Do your Coding as per requirment...
}

4.) Look in to Click Event of the "imgButton" button

protected void imgButton_Click(object sender, ImageClickEventArgs e)
{
hid.Value=""; // Vocate the hidden field if it has some value ie. used to call script.
// do Your coding as per the requirment
If(Condtion)// The condtion on which you want to call java script..
{
//Update the value of the hidden field "hid"
hid.Value ="Your Comment as per the Condition";
}
else
{
hid.Value="";// again Vocate the hidden field...
}
imgButton.Attributes.Clear();// To prevent call script again and again.
//It is Esential.Please note that

}

5.) In the same way You can call script whenever you want just by repeating this process



Enjoy surfing our blog..

Sanjeev Kumar /Mahesh Sharma
On behalf of HelpOnDesk Team

Saturday, November 15, 2008

How to Cerate BookMark/Add Favourites in FireFox/IE

Hi EveryBody...

Today I want to discuss with you how add "Add Favourites" in IE browser or "Add BookMark" in firefox acoording to the browser.This is very Simple just go through with the following code.


[html]
[head id="Head1" runat="server"]
[title]How to Cerate BookMark/Add Favourites in FireFox/IE[/title]
[script language="JavaScript" type="text/javascript"]
function BodyOnload()
{
var myLink=document.getElementById("myLink");
if (document.all)
{
myLink.innerHTML="Add to Favorites";
}
else if (window.sidebar)
{
myLink.innerHTML="Add Bookmark";
}
}
function bookmarksite()
{
if (document.all)
{
window.external.AddFavorite(location.href, document.title);
}
else if (window.sidebar)
{
window.sidebar.addPanel(document.title, location.href, "");
}

}
[/script]

[/head]
[body onload="BodyOnload();"]
[a href="javascript:bookmarksite();" style="color: Blue;" id="myLink"]InnerHTML[/a]
[/body]
[/html]


Enjoy coding...
Sanjeev Chauhan

Wednesday, November 12, 2008

The correct script for detecting the mouse coordinates...

Hi...
Dear friend Now again I am here with a very good post which get you free from tension of calculating the co-ordinates(X and Y) of mouse clicking .

function doSomething(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
// posx and posy contain the mouse position relative to the document
// Do something with this information
}

And Also I have something more of calculating the C0-0rdinates(X and Y) of any HTML object (eg: Textbox or any other.) so I am giving you 2 javascript function look them...


function findPosX(obj)
{
var curleft = 0;
if(obj.offsetParent)
while(1)
{
curleft += obj.offsetLeft;
if(!obj.offsetParent)
break;
obj = obj.offsetParent;
}
else if(obj.x)
curleft += obj.x;
return curleft;
}

function findPosY(obj)
{
var curtop = 0;
if(obj.offsetParent)
while(1)
{
curtop += obj.offsetTop;
if(!obj.offsetParent)
break;
obj = obj.offsetParent;
}
else if(obj.y)
curtop += obj.y;
return curtop;
}







Enjoy scripting...
Sanjeev Kumar Chauhan
(On Behalf Of Help On Desk Team)

Tuesday, November 11, 2008

sp is used for get split string from coma

This Stored Procedure is used for get values from CSV.
e.g a,b,c,d,e,f is split by coma


create proc [dbo].[ufn_CountChar] ( @pInput VARCHAR(1000), @pSearchChar CHAR(1) )
as
BEGIN

/*DECLARE @vInputLength INT*/
DECLARE @vIndex INT
DECLARE @vCount INT
DECLARE @s varchar(2)
DECLARE @str varchar(10)
declare @SubStr varchar(1000)

set @SubStr=''
SET @vCount = 0
SET @vIndex = 1
/*SET @vInputLength = LEN(@pInput)*/
set @str=''

WHILE @vIndex <= len(@pInput)
BEGIN
IF SUBSTRING(@pInput, @vIndex, 1) = @pSearchChar
BEGIN
SET @vCount = @vCount + 1
set @SubStr = substring(@pInput,len(@SubStr),len( @str))
select @str
set @str=''
END
else
BEGIN
set @s=SUBSTRING(@pInput,@vindex,1)
set @str=@str+@s
print ' i m in else part'+ space(3)+ @str
if( @vIndex = len(@pInput))
begin
select @str
end

END
SET @vIndex = @vIndex + 1

END

--select @str


END
GO

ufn_CountChar 'afd,hghg,hgjgh',','

Thankks
helpondesk team

http://aspalliance.com/1125_Dynamically_Templated_GridView_with_Edit_Delete_and_Insert_Options.all

http://www.dotnetcurry.com/ShowArticle.aspx?ID=107&AspxAutoDetectCookieSupport=1

select all values in csv format

This SP is used for the create CSV values
like A,B,C,D,E

CREATE FUNCTION SEL_MAIL(@Email varchar(100))
RETURNS varchar(100)
AS
BEGIN

DECLARE @xyz VARCHAR(100)
declare @abc varchar(100)

set @abc=' '

declare selemail cursor for

select email from dataadi

open selemail
fetch NEXT from selemail into @xyz
WHILE @@Fetch_status = 0
begin


set @abc= @abc+ @xyz+','

FETCH NEXT FROM selemail INTO @xyz
END

CLOSE selemail
DEALLOCATE selemail

return @abc
END

--Sample table schema

Create table SchemaID([ID] smallint,SchemaID int NOT NULL)

--Dummy insert statements

Insert into SchemaID values (1,12)Insert into SchemaID values (1,13)Insert into SchemaID values (1,14)Insert into SchemaID values (2,15)Insert into SchemaID values (2,16)Insert into SchemaID values (2,17)Insert into SchemaID values (2,18)

--Solution

Declare @ID varchar(100)
Select @id=Coalesce(@ID + ', ', '') + Cast(SchemaID AS varchar(5)) From SchemaID Where [ID] = 1 SELECT @ID

Thanks
helpondesk team

Monday, November 10, 2008

How to print a specified div only rather than a complete page..

Hi..

This time here is some java script stuff. the follwing function is used to print the specific div from the page..
now simply call this function whereEver you want as per the requirment.


function CallPrint()
{
{
var prtContent1 = document.getElementById("ctl00_ContentPlaceHolder1_PrintALL");
//var WinPrint = window.open('','','letf=1,top=1,width=100,height=100,toolbar=0,scrollbars=0,status=0');
var WinPrint = window.open('','');
WinPrint.document.write(prtContent1.innerHTML);
//WinPrint.document.close();
WinPrint.focus();
//WinPrint.print();
//WinPrint.close();
}
}

Have a Nice Day
sanjeev Kumar...

CODE BEHIND FILE OF CUSTOM PAGING...

Hi ..

plase find the code for custom paging here it is very simple..

using System;
using System.Data;
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;
using BusenessObject;
using BusenessLogic;

public partial class CustomPaging : System.Web.UI.Page
{
BusenessObject.CustomPagingBo oCustomPaging = new CustomPagingBo();
int UserId = 1;
int PageSize = 1;
int GridCurrentPageIndex;
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["GridCurrentPageIndex"] != null && ViewState["GridCurrentPageIndex"].ToString() != "")
{
GridCurrentPageIndex = Convert.ToInt32(ViewState["GridCurrentPageIndex"]);

}
else
{
GridCurrentPageIndex = 1;

}
DisplayBottomPageLinks();
}



protected void click_PreviousPage(object sender, EventArgs e)
{
GridCurrentPageIndex = GridCurrentPageIndex - 1;
Searching();
DisplayBottomPageLinks();
}


protected void BtnShowUser_Click(object sender, EventArgs e)
{
Searching();
}

public void Searching()
{
ViewState["imgClick"] = "Image_Search";
oCustomPaging.Uid = UserId;
oCustomPaging.GridPageSize = PageSize;
oCustomPaging.GridCurrentPageIndex = GridCurrentPageIndex;
DisplayUser();
}
public void DisplayUser()
{
DataList1.DataSource = CustomPagingBl.GetImageData(oCustomPaging);
DataList1.DataBind();
ViewState["count"] = oCustomPaging.TotalRecords;
if (ViewState["GridCurrentPageIndex"] != null && ViewState["GridCurrentPageIndex"].ToString() != "")
{
GridCurrentPageIndex = Convert.ToInt32(ViewState["GridCurrentPageIndex"]);
}
else
{
GridCurrentPageIndex = 1;
}
DisplayBottomPageLinks();
}

protected void DisplayBottomPageLinks()
{
if (ViewState["GridCurrentPageIndex"] != null && ViewState["GridCurrentPageIndex"].ToString() != "")
{
GridCurrentPageIndex = Convert.ToInt32(ViewState["GridCurrentPageIndex"]);
}
else
{
GridCurrentPageIndex = 1;
}

// Following code is used for the Gridview paging
Int32 count;
int showPages = 3;// 4; or 5 or 6 as you want (This is the key variable...)
//The variable showPages is used to show the no. of Pages you want to show at One time on the page..

Panel pnlPaging = Page.FindControl("pnlPaging") as Panel;
pnlPaging.Controls.Clear();
count = Convert.ToInt32(ViewState["count"]);
GetPageLinks(pnlPaging, GridCurrentPageIndex, PageSize, count, showPages);

}
public void GetPageLinks(Panel pnlPaging,int CurrentPageIndex, int pageSize, int totalRecords, int showPages)
{
#region Paging pageIndex
LinkButton lnk;
//int pageSize = PageSize;// To Give the page size ....
int totalPages = totalRecords / pageSize;
if (totalRecords % pageSize > 0)
{
totalPages += 1;
}
if (totalPages > 1)
{

for (int i = 0; i < totalPages; i++)
{
int pageNo = i + 1;

if (i != (CurrentPageIndex - 1))
{
if (i <= showPages)
{

if (i != showPages)
{
lnk = new LinkButton();
lnk.ID = "linkpage" + pageNo.ToString();
lnk.Text = pageNo.ToString() + " ";
lnk.CausesValidation = false;
lnk.CommandArgument = pageNo.ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = pageNo.ToString();
pnlPaging.Controls.Add(lnk);


}
if (i == showPages)
{

lnk = new LinkButton();
lnk.ID = "linkpage" + pageNo.ToString();
lnk.Text = " .. ";
lnk.CausesValidation = false;

lnk.CommandArgument = pageNo.ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = pageNo.ToString();
pnlPaging.Controls.Add(lnk);
}

}
if (CurrentPageIndex > showPages)
{
int x;
pnlPaging.Controls.Clear();
lnk = new LinkButton();
lnk.ID = "linkpage1";
lnk.Text = " << ";
lnk.CausesValidation = false;
lnk.CommandArgument = "1";
lnk.CommandName = "Paging_click";
lnk.ToolTip = "1";
lnk.Command += new CommandEventHandler(lnk_Command);

pnlPaging.Controls.Add(lnk);
lnk = new LinkButton();
lnk.ID = "linkpage" + (CurrentPageIndex - 1).ToString();
lnk.Text = " .. ";
lnk.CausesValidation = false;
lnk.CommandArgument = (CurrentPageIndex - 1).ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = (CurrentPageIndex - 1).ToString();
lnk.CssClass = "Paging";
pnlPaging.Controls.Add(lnk);

for (x = 0; x < showPages; x++)
{
if ((CurrentPageIndex + x) < totalPages)
{

lnk = new LinkButton();
lnk.ID = "linkpage" + (CurrentPageIndex + x).ToString();
lnk.Text = (CurrentPageIndex + x).ToString() + " ";
lnk.CausesValidation = false;
lnk.CommandArgument = (CurrentPageIndex + x).ToString();
lnk.CommandName = "Paging_click";
lnk.ToolTip = (CurrentPageIndex + x).ToString(); ;

lnk.Command += new CommandEventHandler(lnk_Command);
pnlPaging.Controls.Add(lnk);
}
}
if (x == showPages && (CurrentPageIndex + x) <= totalPages)
{

lnk = new LinkButton();
lnk.ID = "linkpage" + (CurrentPageIndex + x).ToString();
lnk.Text = " .. ";
lnk.CausesValidation = false;
lnk.CommandArgument = (CurrentPageIndex + x).ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = (CurrentPageIndex + x).ToString();
pnlPaging.Controls.Add(lnk);
}
}
if (i == (totalPages - 1) && (CurrentPageIndex != totalPages) && (totalPages > (showPages + 1)))
{

lnk = new LinkButton();
lnk.ID = "linkpage1" + totalPages.ToString();
lnk.Text = " >> ";
lnk.CausesValidation = false;
lnk.CommandArgument = totalPages.ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = totalPages.ToString();
pnlPaging.Controls.Add(lnk);
}

if (CurrentPageIndex > (totalPages - showPages))
{

if (CurrentPageIndex == totalPages)
{
pnlPaging.Controls.Clear();
lnk = new LinkButton();
lnk.ID = "linkpage1";
lnk.Text = " << ";
lnk.CausesValidation = false;
lnk.CommandArgument = "1";
lnk.CommandName = "Paging_click";
lnk.ToolTip = "1";
lnk.Command += new CommandEventHandler(lnk_Command);
pnlPaging.Controls.Add(lnk);

lnk = new LinkButton();
lnk.ID = "linkpage" + (totalPages - (showPages + 1)).ToString();
lnk.Text = " .. ";
lnk.CausesValidation = false;
lnk.CommandArgument = (totalPages - (showPages + 1)).ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = (totalPages - (showPages + 1)).ToString();
pnlPaging.Controls.Add(lnk);
for (int x = (showPages - 1); x > 0; x--)
{
lnk = new LinkButton();
lnk.ID = "linkpage" + (totalPages - x).ToString();
lnk.Text = (totalPages - x).ToString() + " ";
lnk.CausesValidation = false;
lnk.CommandArgument = (totalPages - x).ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = (totalPages - x).ToString();
pnlPaging.Controls.Add(lnk);
}
}
else
{
pnlPaging.Controls.Clear();
lnk = new LinkButton();
lnk.ID = "linkpage1";
lnk.Text = " << ";
lnk.CausesValidation = false;
lnk.CommandArgument = "1";
lnk.CommandName = "Paging_click";
lnk.ToolTip = "1";
lnk.Command += new CommandEventHandler(lnk_Command);
pnlPaging.Controls.Add(lnk);

lnk = new LinkButton();
lnk.ID = "linkpage" + (totalPages - (showPages + 1)).ToString();
lnk.Text = " .. ";
lnk.CausesValidation = false;
lnk.CommandArgument = (totalPages - (showPages + 1)).ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = (totalPages - (showPages + 1)).ToString();
pnlPaging.Controls.Add(lnk);
for (int x = showPages; x > 0; x--)
{
lnk = new LinkButton();
lnk.ID = "linkpage" + (totalPages - x).ToString();
lnk.Text = (totalPages - x).ToString() + " ";
lnk.CausesValidation = false;
lnk.CommandArgument = (totalPages - x).ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = (totalPages - x).ToString();
pnlPaging.Controls.Add(lnk);
}

lnk = new LinkButton();
lnk.ID = "linkpage1" + totalPages.ToString();
lnk.Text = " >> ";
lnk.CausesValidation = false;
lnk.CommandArgument = totalPages.ToString();
lnk.CommandName = "Paging_click";
lnk.ToolTip = totalPages.ToString();
lnk.Command += new CommandEventHandler(lnk_Command);
pnlPaging.Controls.Add(lnk);

}
}
}

else
{
if (i == (CurrentPageIndex - 1))
{
lnk = new LinkButton();
lnk.ID = "linkpage" + pageNo.ToString();
lnk.Text = pageNo.ToString() + " ";
lnk.CausesValidation = false;
lnk.ToolTip = pageNo.ToString();
//lnk.Attributes["OnClick"] = "return false;";
lnk.Enabled = false;
lnk.Style["cursor"] = "text";
pnlPaging.Controls.Add(lnk);

}
}

}
}


#endregion
}
void lnk_Command(Object sender, CommandEventArgs e)
{
Panel pnlPaging = (Panel)Page.FindControl("pnlPaging");
ViewState["linkId"] = e.CommandArgument.ToString();
if (e.CommandName == "FirstPaging_click")
{
GridCurrentPageIndex = Convert.ToInt32(e.CommandArgument);
ViewState["GridCurrentPageIndex"] = GridCurrentPageIndex;
}
else if (e.CommandName == "Paging_click")
{
GridCurrentPageIndex = Convert.ToInt32(e.CommandArgument);
ViewState["GridCurrentPageIndex"] = GridCurrentPageIndex;
}
Searching();
LinkButton lnk = (LinkButton)pnlPaging.FindControl("linkpage" + ViewState["linkId"].ToString());
lnk.Enabled = false;

}
}




Thanks :
Sanjeev Chauhan
HelpOnDesk Team

STORED PROCEDURE FOR CUSTOM PAGING...

Hi EveryBody...
I am again here with my new post.The follwing post is for how to write a good stored procedure for custom paging.I m not saying that it is the best SP..can assure you that is good enough.the SP is here..


CREATE PROC USP_DEMO_PAGING
(
@UID INT,
@GridCurrentPageIndex INT,
@GridPageSize INT
)
AS
BEGIN

DECLARE @LastDisplayingRecordIndex int -- To store the index number of last displayed records in Grid in .NET page. For next page it will start by increment last index by 1.
DECLARE @MaxDisplayingRecordIndex int -- To store upto which index records should be display.

SET @LastDisplayingRecordIndex = @GridPageSize * (@GridCurrentPageIndex-1)
SET @MaxDisplayingRecordIndex = @GridPageSize * @GridCurrentPageIndex

-- VARIABLE DECLARATION FOR DYNAMIC QUERY PARTS TO BE USED IN PAGING

DECLARE @SelectQueryWhere varchar(500)-- Used to put the condtion of lower and higher record index
DECLARE @QueryCount varchar(max) -- Used to count the total records.

DECLARE @SelectMainQuery varchar(500) -- To store the selected column part of the SELECT statement
DECLARE @SelectMainQueryResultSet varchar(7000) -- To store the result set query with Row_Number
DECLARE @SelectWhereCreteria varchar(4000)
DECLARE @SelectJoinPart varchar(max)
DECLARE @SelectOrderByPart varchar(255)



SET @SelectQueryWhere = ') _Results WHERE RowNumber > ' + Convert(varchar,@LastDisplayingRecordIndex) + ' And RowNumber <= ' + Convert(varchar,@MaxDisplayingRecordIndex)
SET @SelectOrderByPart='' -- Please mentioned If any

SET @QueryCount = 'SELECT count(UID) from userImage' -- It Used for Counting all the Records

SET @SelectMainQuery ='SELECT ImageID,UID,USERNAME,USERIMAGE,ROW_NUMBER()over (order by ImageID) AS RowNumber from userImage'
SET @SelectJoinPart =''-- There is any Joins Please put here
SET @SelectWhereCreteria = ' where UId = '+ Convert(varchar,@UID)--Here You Can put Your Calculated Where Creteria
SET @SelectMainQueryResultSet = @SelectMainQuery + @SelectJoinPart + @SelectWhereCreteria
SET @SelectMainQueryResultSet = 'SELECT * FROM ('+ @SelectMainQueryResultSet + @SelectQueryWhere + @SelectOrderByPart
SET @QueryCount = @QueryCount + @SelectJoinPart + @SelectWhereCreteria

EXEC(@SelectMainQueryResultSet)
--PRINT @SelectMainQueryResultSet

EXEC(@QueryCount)

--PRINT @QueryCount
END


Happy Coding...
truely yours:
Sanjeev Chaudhary

Thursday, November 6, 2008

How To Make Loan Calculator For Financial Sites

Hi Friends...
Today I'm going to describe you How to make a good loan calculator.That returns you the TotalAmortization Amount and the total Time period in Months as well as in Years Also..
so now the time for having a look on the code and change it according to your need...Code is below:-


///
/// Purpose:This is used for calculating the MortgageLoan...
///

/// Sanjeev Chauhan
/// November 6,2008
///
///
protected void btnCalculate_Click(object sender, EventArgs e)
{
#region The Concept And Formula Derivation By Sanjeev

/*For this I have used the Following Formula Which I have Derived After a long calculation
BY USING THIS FORMULA WE CAN CALCULATE THE UNKNOWN TERM...
(1+ R/12)pow T = 12x/(12x-PR)
FOR CALUCULATING THE TOTAL MORTGAGE AMOUNT WE CAN USE THE FOLLOWING FORMULA
A =P(1+r/12)^T
OR U CAN SAY
A =P(1+r/12)^T

WHERE P= Primary Amount ,A=Final Amount ,T= Total Amount
R=Rate(rate/100(convert to points from %age)) ,x = MOnthly Installing Amount
*/

#endregion

double dblAmount, dblTotalAmt, dblInstallment, dblRate, dblTime;
dblAmount = Convert.ToDouble(txtAmount.Text);
dblInstallment = Convert.ToDouble(txtMontlypayment.Text);
dblRate = Convert.ToDouble(txtRate.Text) / 100;
double logBasevalue = 1 + (dblRate / 12);
double logValue = (12 * dblInstallment) / (12 * dblInstallment - (dblAmount * dblRate));
dblTime = Math.Log(logValue, logBasevalue);
double roundMonth = Math.Round(dblTime);
roundMonth = roundMonth < dblTime ? roundMonth + 1 : roundMonth;
double dblYear =roundMonth / 12;
double roundYear = Math.Round(dblYear, 1);
string strYear = Convert.ToString(roundYear);
dblTotalAmt = Math.Round((dblInstallment * dblTime), 2);
lblMonths.Text = roundMonth.ToString();
lblYears.Text = strYear.Substring(0, strYear.LastIndexOf('.') + 2);
lblTotalAmount.Text = dblTotalAmt.ToString();

}



Enjoy Blogging..

Sanjeev Chaudhary

Monday, October 20, 2008

get the information about the operating system name space System.Environment

The class System.Environment is used to retrieve information about the operating system. Some of the static members of this class are as follows:
1) Environment .OSVersion - Gets the version of the operating system
2) Environment .GetLogicalDrives() - method that returns the drives
3) Environment .Version - returns the .NET version running the application
4) Environment .MachineName - Gets name of the current machine
5) Environment .Newline - Gets the newline symbol for the environment
6) Environment .ProcessorCount - returns number of processors on current machine
7) Environment .SystemDirectory - returns complete path to the System Directory
8) Environment .UserName - returns name of the entity that invoked the application

Thanks
Help on Desk Team

JAVASCRIPT FOR REFRESH PARENT and UPDATE WINDOW FROM CHILED WINDOW

HI
HERE WE HAVE JAVASCRIPT FOR REFRESH PARENT and UPDATE WINDOW FROM CHILED WINDOW
AND CHANGE PARENT WINDOW CONTROL VALUE FROM CHILED WINDOW AFTWER SOME OPRATION .

a) refresh parent window:-
window . opener . location . reload();

function refreshParent() {
window . opener . location . reload();

window . opener . location . href = window . opener . location . href;

if (window . opener . progressWindow)

{
window . opener . progressWindow . close()
}
// window . close();
return false;
}

[asp:Button ID="btn2" runat="Server" Text="refreshParent" OnClientClick="refreshParent();" /]

b) PASS VALUE FROM CHILD WINDOW TO PARENT WINDOW

protected void btn_Click(object sender, EventArgs e)
{
//{window.opener.location.reload(); }
int intSum;

intSum = Convert . ToInt32(txt1 . Text) + Convert.ToInt32(TextBox1 . Text);

Page.ClientScript . RegisterStartupScript(this.GetType(), "close", "");
// lbl is control of parent window

}


c)

protected void btnSum_Click(object sender, EventArgs e) { //SumAndGO(varValue) int sum = Convert.ToInt32(TxtNum1 . Text) + Convert.ToInt32(TxtNum2 . Text); string Jscript = "SumAndGO(" + sum + ")"; Jscript = ""; ClientScript.RegisterStartupScript(this . GetType(), "Jscript", Jscript); }


Thanks
Help on desk

Wednesday, October 15, 2008

How to read a webpage from onother website

//-
using System.IO;
using System.Text;
using System.Net;



string ddate = string.Empty;

WebRequest req = WebRequest.Create("http://www.helpondesk.com/exaple");
WebResponse resp = req.GetResponse();

Stream s = resp.GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.ASCII);
string doc = sr.ReadToEnd();

Thanks
Helpondesk Team

Complete example of create Thumbnail when we uplaod image

how to create a thumnain while we are uploading a new image


Code in aspx page

protected void Button1_Click(object sender, EventArgs e)
{
string filename = string.Empty;
string imagename = string.Empty;

string imgtype = string.Empty;
thumbnail thumb = new thumbnail();
filename = fileUpload.PostedFile.FileName;
imagename = filename.Substring(filename.LastIndexOf("\\") + 1, (filename.LastIndexOf(".") - 1) -

(filename.LastIndexOf("\\")));
imgtype = filename.Substring(filename.LastIndexOf("."));

string str = thumb.UploadImage(imagename, imgtype, Server.MapPath(@"Images\Actual\"),

Server.MapPath(@"Images\Thumbnail\"), fileUpload,95,143);

}

code in HTML part :-

< asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" / >

< asp:FileUpload ID="fileUpload" runat="server" / >

Code in class file

using System;
using System.Data;
using System.Configuration;
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;
//----
using System.Drawing;
using System.Drawing.Imaging;

///
/// Summary description for thumbnail
///

public class thumbnail
{
public thumbnail()
{
//
// TODO: Add constructor logic here
//
}


public string UploadImage(string filename, string filetype, string str_folder_name_main, string str_folder_name_small,

FileUpload fileupload1, int width, int heigh)
{

if (fileupload1.PostedFile.ContentType == "image/pjpeg" || fileupload1.PostedFile.ContentType == "image/jpeg" ||

fileupload1.PostedFile.ContentType == "image/bmp" || fileupload1.PostedFile.ContentType == "image/gif")
{
fileupload1.PostedFile.SaveAs(str_folder_name_main + filename + filetype);
CreateThumbnail(str_folder_name_main + filename + filetype, width , heigh , str_folder_name_small + filename +

filetype);
// CreateThumbnail(str_folder_name_main + filename + filetype, 250, 300, str_folder_name_large + filename +

filetype);
return "1";
}
else
{
return "2";
}
}

public void CreateThumbnail(string lcFilename, int lnWidth, int lnHeight, string OutputFilename)
{
System.Drawing.Bitmap bmpOut = null;
Bitmap loBMP = new Bitmap(lcFilename);
ImageFormat loFormat = loBMP.RawFormat;
decimal lnRatio;
int lnNewWidth = 0;
int lnNewHeight = 0;
lnNewWidth = lnWidth;
lnNewHeight = lnHeight;
bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
Graphics g = Graphics.FromImage(bmpOut);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
loBMP.Dispose();

bmpOut.Save(OutputFilename, ImageFormat.Jpeg);
bmpOut.Dispose();


}

public bool checkImageType(HtmlInputFile FileUpload1)
{
if (FileUpload1.PostedFile.ContentType == "image/pjpeg" || FileUpload1.PostedFile.ContentType == "image/jpeg" ||

FileUpload1.PostedFile.ContentType == "image/bmp" || FileUpload1.PostedFile.ContentType == "image/gif")
{
return true;
}
else
{
return false;
}
}

}

Thanks
helpondesk Team

Tuesday, September 9, 2008

Google Maps JavaScript API Example

Hi...
Toady I'll describe you How to use google map in your own web site.It's very very simple..Just paste this in you HTML (design)of the as[x page.

[title]Google Maps JavaScript API Example[/title]

[script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAlE4RDKqdaG_395uP5F3n5BSgLbdfLkC76Qf-PydYQ5rbBnOoOBQ5b6VRo9cSRp89ONhWflXcFjLUkA"
type="text/javascript"][/script]

[script type="text/javascript"]
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
geocoder = new GClientGeocoder();
var address ='[%=address %]'
//address variable is usedused for the Address to be serched
//code behind declaretion of 'address' Varialbe as follows
//protected string address = string.Empty; in partial class.. give the value ot it in any Event.
showAddress(map, geocoder, address);
//showAddress(map, geocoder, "76 9th ave new york");
}
}

function showAddress(map, geocoder, address)
{
if (geocoder) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not Valid Address ");

} else {

map.setCenter(point, 13);
var baseIcon = new GIcon();
baseIcon.shadow = "images/red_star.gif";

baseIcon.iconSize = new GSize(19, 18);
baseIcon.shadowSize = new GSize(19, 18);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);

// Creates a marker whose info window displays the letter corresponding
// to the given index.
function createMarker(point, index) {
// Create a lettered icon for this point using our icon class
var letter = String.fromCharCode("A".charCodeAt(0) + index);
var icon = new GIcon(baseIcon);
icon.image = "red_star.gif";
var marker = new GMarker(point, icon);

GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(address);
});
return marker;
}
map.addOverlay(createMarker(point, 13));
}
}
);
}
}
[/script]



With Love...
Sanjeev Kumar Chauhan

Friday, September 5, 2008

To change The color of the Grid View Row on Mouse Move...

Hi...
I am going to describe you ,How to change the color/style of the Gridview row on mouse move .For this You need only add RowCreated event in the HTML of the Gridview plus just paste the following code to your CodeBehind of your page.


protected void YourGridView_RowCreated(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#00BFFF'"); e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;");
}

}


Enjoy Coding...
Thanks And Regards:
Sanjeev Chauhan

Sunday, August 31, 2008

disabe refresh page by f5 or shortcut like ctrl + R

[script]
// Just add this script to the header
function showDown(evt) {
evt = (evt) ? evt : ((event) ? event : null);
if (evt) {
if (event.keyCode == 8 && (event.srcElement.type != "text" && event.srcElement.type != "textarea" && event.srcElement.type !=

"password")) {
// When backspace is pressed but not in form element
cancelKey(evt);
}
else if (event.keyCode == 116) {
// When F5 is pressed
cancelKey(evt);
}
else if (event.ctrlKey && (event.keyCode == 78 || event.keyCode == 82)) {
// When ctrl is pressed with R or N
cancelKey(evt);
}
}
}

function cancelKey(evt) {
if (evt.preventDefault) {
evt.preventDefault();
return false;
}
else {
evt.keyCode = 0;
evt.returnValue = false;
}
}

// Additional code for NS
if (navigator.appName=="Netscape") {
document.addEventListener("keypress",showDown,true);
}
document.onkeydown = showDown;
[/script]

Saturday, August 23, 2008

java script for creating numeric text box

Hi,
This script is used for creating text box which will take only intergers as input.


function checkIt(evt) {

var lblmsg = document.getElementById('lblmainphone');

evt = (evt) ? evt : window.event
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode ] 31 && (charCode [ 48 || charCode ] 57)) {
status = "This field accepts numbers only."

lblmsg.innerHTML = "This field accepts numbers only.";

return false
}
status = ""
lblmsg.innerHTML = "";
return true
}

how to call in text box.


[asp:TextBox ID="txtabtHomeMorgTerm" runat="server" CssClass="inputbox" onKeyPress="return checkIt(event)"][/asp:TextBox]

Thanks
HelpOnDeskTeam

Thursday, August 21, 2008

Custom paging as google stylye paging

using System;
using System.Data;
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;
//---------
using BusenessLogic;
using BusenessObject;

public partial class MaheshPagingWithHelpofsanjeev : System.Web.UI.Page
{
BusenessObject.CustomPagingBo oCustomPaging = new CustomPagingBo();
int UserId = 1;
int PageSize = 1;
// static int TotalRows;
int GridCurrentPageIndex;
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["GridCurrentPageIndex"] != null && ViewState["GridCurrentPageIndex"].ToString() != "")
{
GridCurrentPageIndex = Convert.ToInt32(ViewState["GridCurrentPageIndex"]);
//LinkButton btnPrePage_Top = Page.FindControl("btnPrePage_Top") as LinkButton;
// btnPrePage_Top.Enabled = true;
}
else
{
GridCurrentPageIndex = 1;
// LinkButton btnPrePage_Top = Page.FindControl("btnPrePage_Top") as LinkButton;
// btnPrePage_Top.Enabled = false;

}
DisplayBottomPageLinks();

}

protected void DisplayBottomPageLinks()
{
if (ViewState["GridCurrentPageIndex"] != null && ViewState["GridCurrentPageIndex"].ToString() != "")
{
GridCurrentPageIndex = Convert.ToInt32(ViewState["GridCurrentPageIndex"]);
}
else
{
GridCurrentPageIndex = 1;
}

// Following code is used for the Gridview paging
Int32 count;
int showPages = 3;// 4; or 5 or 6 as you want (This is the key variable...)
//The variable showPages is used to show the no. of Pages you want to show at One time on the page..
LinkButton lnk;
Panel pnlPaging = Page.FindControl("pnlPaging") as Panel;
pnlPaging.Controls.Clear();
count = Convert.ToInt32(ViewState["count"]);
int pageSize = 1;
int totalPages = count / pageSize;
if (count % pageSize > 0)
{
totalPages += 1;
}
if (totalPages > 1)
{

for (int i = 0; i < totalPages; i++)
{
int pageNo = i + 1;

if (i != (GridCurrentPageIndex - 1))
{
if (i <= showPages)
{

if (i != showPages)
{
lnk = new LinkButton();
lnk.ID = "linkpage" + pageNo.ToString();
lnk.Text = pageNo.ToString() + " ";
lnk.CausesValidation = false;
lnk.CommandArgument = pageNo.ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = pageNo.ToString();
// lnk.CssClass = "Paging";
pnlPaging.Controls.Add(lnk);


}
if (i == showPages)
{

lnk = new LinkButton();
lnk.ID = "linkpage" + pageNo.ToString();
lnk.Text = " .. ";
lnk.CausesValidation = false;

lnk.CommandArgument = pageNo.ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = pageNo.ToString();
//lnk.CssClass = "Paging";
pnlPaging.Controls.Add(lnk);
}

}
if (GridCurrentPageIndex > showPages)
{
int x;
pnlPaging.Controls.Clear();
lnk = new LinkButton();
lnk.ID = "linkpage1";
lnk.Text = " << ";
lnk.CausesValidation = false;
lnk.CommandArgument = "1";
lnk.CommandName = "Paging_click";
lnk.ToolTip = "1";
//lnk.CssClass = "Paging";
lnk.Command += new CommandEventHandler(lnk_Command);

pnlPaging.Controls.Add(lnk);
lnk = new LinkButton();
lnk.ID = "linkpage" + (GridCurrentPageIndex - 1).ToString();
lnk.Text = " .. ";
lnk.CausesValidation = false;
lnk.CommandArgument = (GridCurrentPageIndex - 1).ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = (GridCurrentPageIndex - 1).ToString();
lnk.CssClass = "Paging";
pnlPaging.Controls.Add(lnk);

for (x = 0; x < showPages; x++)
{
if ((GridCurrentPageIndex + x) < totalPages)
{

lnk = new LinkButton();
lnk.ID = "linkpage" + (GridCurrentPageIndex + x).ToString();
lnk.Text = (GridCurrentPageIndex + x).ToString() + " ";
lnk.CausesValidation = false;
lnk.CommandArgument = (GridCurrentPageIndex + x).ToString();
lnk.CommandName = "Paging_click";
lnk.ToolTip = (GridCurrentPageIndex + x).ToString(); ;

lnk.Command += new CommandEventHandler(lnk_Command);
// lnk.CssClass = "Paging";
pnlPaging.Controls.Add(lnk);
}
}
if (x == showPages && (GridCurrentPageIndex + x) <= totalPages)
{

lnk = new LinkButton();
lnk.ID = "linkpage" + (GridCurrentPageIndex + x).ToString();
lnk.Text = " .. ";
lnk.CausesValidation = false;
lnk.CommandArgument = (GridCurrentPageIndex + x).ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = (GridCurrentPageIndex + x).ToString();
//lnk.CssClass = "Paging";
pnlPaging.Controls.Add(lnk);
}
}
if (i == (totalPages - 1) && (GridCurrentPageIndex != totalPages) && (totalPages > (showPages + 1)))
{

lnk = new LinkButton();
lnk.ID = "linkpage1" + totalPages.ToString();
lnk.Text = " >> ";
lnk.CausesValidation = false;
lnk.CommandArgument = totalPages.ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = totalPages.ToString();
//lnk.CssClass = "Paging";
pnlPaging.Controls.Add(lnk);
}



if ((GridCurrentPageIndex == totalPages) && (totalPages > (showPages + 1)))
{
int x;
pnlPaging.Controls.Clear();
lnk = new LinkButton();
lnk.ID = "linkpage1";
lnk.Text = " << ";
lnk.CausesValidation = false;
lnk.CommandArgument = "1";
lnk.CommandName = "Paging_click";
lnk.ToolTip = "1";
lnk.Command += new CommandEventHandler(lnk_Command);
//lnk.CssClass = "Paging";
pnlPaging.Controls.Add(lnk);

lnk = new LinkButton();
lnk.ID = "linkpage" + (GridCurrentPageIndex - showPages).ToString();
lnk.Text = " .. ";
lnk.CausesValidation = false;
lnk.CommandArgument = (GridCurrentPageIndex - showPages).ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = (GridCurrentPageIndex - showPages).ToString();
//lnk.CssClass = "Paging";
pnlPaging.Controls.Add(lnk);

for (x = (showPages - 1); x > 0; x--)
{

lnk = new LinkButton();
lnk.ID = "linkpage" + (GridCurrentPageIndex - x).ToString();
lnk.Text = (GridCurrentPageIndex - x).ToString() + " ";
lnk.CausesValidation = false;
lnk.CommandArgument = (GridCurrentPageIndex - x).ToString();
lnk.CommandName = "Paging_click";
lnk.Command += new CommandEventHandler(lnk_Command);
lnk.ToolTip = (GridCurrentPageIndex - x).ToString();
// lnk.CssClass = "Paging";
pnlPaging.Controls.Add(lnk);

}

}



}
else
{
if (i == (GridCurrentPageIndex - 1))
{
lnk = new LinkButton();
lnk.ID = "linkpage" + pageNo.ToString();
lnk.Text = pageNo.ToString() + " ";
lnk.CausesValidation = false;
lnk.ToolTip = pageNo.ToString();
//lnk.Attributes["OnClick"] = "return false;";
lnk.Enabled = false;
//lnk.ForeColor = System.Drawing.Color.Gray;
// lnk.CssClass = "Paging";
pnlPaging.Controls.Add(lnk);

}
}

}
}



}

protected void click_PreviousPage(object sender, EventArgs e)
{
GridCurrentPageIndex = GridCurrentPageIndex - 1;
Searching();
DisplayBottomPageLinks();
}
void lnk_Command(Object sender, CommandEventArgs e)
{
Panel pnlPaging = (Panel)Page.FindControl("pnlPaging");
ViewState["linkId"] = e.CommandArgument.ToString();
if (e.CommandName == "FirstPaging_click")
{
GridCurrentPageIndex = Convert.ToInt32(e.CommandArgument);
ViewState["GridCurrentPageIndex"] = GridCurrentPageIndex;
}
else if (e.CommandName == "Paging_click")
{
GridCurrentPageIndex = Convert.ToInt32(e.CommandArgument);
ViewState["GridCurrentPageIndex"] = GridCurrentPageIndex;
}
Searching();
LinkButton lnk = (LinkButton)pnlPaging.FindControl("linkpage" + ViewState["linkId"].ToString());
lnk.Enabled = false;
if (GridCurrentPageIndex == 1)
{
// LinkButton btnPrePage_Top = Page.FindControl("btnPrePage_Top") as LinkButton;
// btnPrePage_Top.Enabled = false;
}

}

protected void BtnShowUser_Click(object sender, EventArgs e)
{
Searching();
}

public void Searching()
{
ViewState["imgClick"] = "Image_Search";
oCustomPaging.Uid = UserId;
oCustomPaging.GridPageSize = PageSize;
oCustomPaging.GridCurrentPageIndex = GridCurrentPageIndex;
DisplayUser();
}
public void DisplayUser()
{
DataList1.DataSource = CustomPagingBl.GetImageData(oCustomPaging);
DataList1.DataBind();
ViewState["count"] = oCustomPaging.TotalRecords;
if (ViewState["GridCurrentPageIndex"] != null && ViewState["GridCurrentPageIndex"].ToString() != "")
{
GridCurrentPageIndex = Convert.ToInt32(ViewState["GridCurrentPageIndex"]);
}
else
{
GridCurrentPageIndex = 1;
}
DisplayBottomPageLinks();
}

#region sp used for paging
/*
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROC [dbo].[USP_DEMO_PAGING]
(
@UID INT,
@GridCurrentPageIndex INT,
@GridPageSize INT
)
AS
BEGIN

DECLARE @LastDisplayingRecordIndex int -- To store the index number of last displayed records in Grid in .NET page. For next page it will start by increment last index by 1.
DECLARE @MaxDisplayingRecordIndex int -- To store upto which index records should be display.

SET @LastDisplayingRecordIndex = @GridPageSize * (@GridCurrentPageIndex-1)
SET @MaxDisplayingRecordIndex = @GridPageSize * @GridCurrentPageIndex

-- VARIABLE DECLARATION FOR DYNAMIC QUERY PARTS TO BE USED IN PAGING

DECLARE @SelectQueryWhere varchar(500)-- Used to put the condtion of lower and higher record index
DECLARE @QueryCount varchar(max) -- Used to count the total records.

DECLARE @SelectMainQuery varchar(500) -- To store the selected column part of the SELECT statement
DECLARE @SelectMainQueryResultSet varchar(7000) -- To store the result set query with Row_Number
DECLARE @SelectWhereCreteria varchar(4000)
DECLARE @SelectJoinPart varchar(max)
DECLARE @SelectOrderByPart varchar(255)



SET @SelectQueryWhere = ') _Results WHERE RowNumber > ' + Convert(varchar,@LastDisplayingRecordIndex) + ' And RowNumber <= ' + Convert(varchar,@MaxDisplayingRecordIndex)
SET @SelectOrderByPart='' -- Please mentioned If any

SET @QueryCount = 'SELECT count(UID) from userImage' -- It Used for Counting all the Records

SET @SelectMainQuery ='SELECT ImageID,UID,USERNAME,USERIMAGE,ROW_NUMBER()over (order by ImageID) AS RowNumber from userImage'
SET @SelectJoinPart =''-- There is any Joins Please put here
SET @SelectWhereCreteria = ' where UId = '+ Convert(varchar,@UID)--Here You Can put Your Calculated Where Creteria
SET @SelectMainQueryResultSet = @SelectMainQuery + @SelectJoinPart + @SelectWhereCreteria
SET @SelectMainQueryResultSet = 'SELECT * FROM ('+ @SelectMainQueryResultSet + @SelectQueryWhere + @SelectOrderByPart
SET @QueryCount = @QueryCount + @SelectJoinPart + @SelectWhereCreteria

EXEC(@SelectMainQueryResultSet)
--PRINT @SelectMainQueryResultSet

EXEC(@QueryCount)

--PRINT @QueryCount
END





*/

#endregion sp used for paging
}