Friday, December 18, 2009

SQL Database compare software

Here is free databse compare software for Access / MY SQL / Sql Serve , Compare application will allow you to compare the structure of two SQL server databases and display all the differences between them.. The structure viewer is included on same , you can find the comparison and acoording to that you can choose to exclude that comparioson of given fields , constraints .This is a lightweight version compared to version 2.0, it very small and portable.

>Download Here

Wednesday, December 9, 2009

Find Maximum Connections for SQL Server.

- If you want to know how many connection get happen with your database then you can easily get those number using this technique.

Select @@MAX_Connections as MaxConn

Using this you will get the Max number of connection get allowed on an instance of sql server.

- now if you want to know how many attempted connection are then

Select @@Connections as TotalNumberOfLogin

It will gives you all the number of connection was happen when the sql server get started , that may be a successful or unsuccessful connections also.

- You can also check this all using this system store procedure call

Exec sp_monitor

This will gives you result on when server get running , cpu time , usage , amount of data sending receiving , total number of read write operation done plus is there any error on connection like that .

Friday, December 4, 2009

Format DateTime in Gridview.

Gridview is using mostly , now i have come up with some small but very important task on how to display Proper date time on Gridview , Basically we are defining standard date time option (date + time) , but some time we only want to display date in this case you can follow the below format.Format Date on Bound Column in Grid View

Suppose you want DOB in short date format without time , then you can simply use DataFormatString ="{0:d}" for Short Date
like this

<asp:BoundField DataField="DOB" HeaderText="DOB" DataFormatString = "{0:d}" />

if you are using above this setting then also it will not work ,coz by default the html encode is turned ON to prevent the Cross site Scripting attack , so for that you need to add one more property as HtmlEncode ="false".

<asp:BoundField DataField="DOB" HtmlEnclode="False" HeaderText="DOB" DataFormatString = "{0:d}" />

if You want Logn Date you can use - DataFormatString = "{0:D}"
if You want Logn Time you can use - DataFormatString = "{0:T}"

If you are using Template comlumn and you want to make your date string in short format then also you can use this suppose your item templates is

<ItemTemplate >
<asp:Label ID="DOB" runat="server" Text='<%# Bind("DOB") % >'> </asp:Label >
</ItemTemplate >

Then also you can use like this way:

<asp:Label ID="DOB" runat="server" Text='<%# Bind("DOB","{0:D}") % >'> </asp:Label >

Following table will show some date formating ways in Gridview column.

Format Pattern




Short date



Long date

Sunday, August 11, 2008


Short time

3:32 PM


Long time

3:32:00 PM


Full date/time
(short time)

Sunday, August 11, 2008 3:32 PM


Full date/time
(long time)

Sunday, August 11, 2008 3:32:00 PM


General date/time
(short time)

8/11/2008 3:32 PM


General date/time
(long time)

8/11/2008 3:32:00 PM

m or M

Month day

August 11

r or R

RFC 1123

Sun, 11 Aug 2008 8:32:00 GMT


Sortable date/time



Universable sortable date/time

2008-08-11 15:32:00z


Universable sortable date/time

Sunday, August 11, 2008 11:32:00 PM

y or Y

Year month

August, 2008

thanx you,

Wednesday, November 25, 2009

How to know SQL Server version and Edition

some time we just install the sql server , but still we don't know which type of version it is and edition also , basically we need that when we are upgrating current version of new version. Current there is sql server 2008 is there in market,

now how to determine which version of sql 2008 is running out machine,
- run the following T-SQL statement,

SELECT SERVERPROPERTY ('productlevel') ,SERVERPROPERTY('productversion'), SERVERPROPERTY ('edition')

you will get the result like :
RTM | 10.0.1600.22 | Enterprise Edition

RTM is product level which means - 'Release To Manufacturing'.
but what is means of RTM - is a stage on which the distribution of process begins CD of
that product get created and retial packs and then product will get shipp , this is very
long process and because of that RTM date is mostly ahead of the final release date.

10.0.1600.22 means product version.

Enterprise Edition means its a Edition there are some other editions are also there like
Developer,standard ,web,Express ,Workgroup , 64- bit Edition .

The following table lists the Sqlservr.exe version number.

Release Sqlservr.exe
RTM 2007.100.1600.0
SQL Server 2008 Service Pack 12007.100.2531.0

Wednesday, November 18, 2009

Check for valid Internet Connection using C#

on many application we need internet connectio , such as smart client to send receive the data, now in this case below code will help you to make sure that you have proper internet connection or not , the conecpt is like very simple, at first we simply check that if the user has network connection and according to that it will return Success / Fail message.

Now i just ping the two website ( , which will ping that site and return fail or success message.

public bool GetIsConnAvail()
var success = false;
string StatusMsg;
if (NetworkInterface.GetIsNetworkAvailable() == false)
return success;
string[] Mysite = { "", ""};
using (var ping = new Ping())
foreach (var url in Mysite)
var replyMsg = ping.Send(url, 300);
if (replyMsg.Status == IPStatus.Success)
success = true;
StatusMsg = "Connection Found..."
StatusMsg = "Internet Connection not Found on your machine..."


catch (Exception ex)
return success;

i thing this code will surely help you to search your connection faster than other ways.

Tuesday, November 10, 2009

video on web2.0

hi , i just found very nice vodeo on web2.0

another video on web2.0 , its really very informative

Wednesday, November 4, 2009

Generate Sitemap using ASP

Sitemap is very important factor of web site , you can say its a list of pages of web site accessible to user. it Organize in hierarchical fashion. basically it helps the visitors and mostly on search engine bots to find the perticular page on you site. it improve seo of site , it works just like the dynamic access to site. basically sitemap in xml format.

Here i have created one sample application that can read xsl file and according to that it generate sitemap of your site.
on my Excel file i have place all the links of my sites.
now how to get this ,
1 .open your site say
2. now on your web developer toolbar (Mozilla addon) on Information section > click view link information it will open open page and in that you can find all the site links
3. copy that on excel file and save it ,

now write application that read a data from excel and generate sitemap

< %

Const adOpenStatic = 3
Const adLockPessimistic = 2
Dim cnnExcel
Dim rstExcel
Dim I
Dim iCols

Set cnnExcel = Server.CreateObject("ADODB.Connection")
cnnExcel.Open "Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq="&Server.MapPath("1.xls")&";DefaultDir="&Server.MapPath(".")&";" Set rstExcel = Server.CreateObject("ADODB.Recordset")
rstExcel.Open "SELECT * FROM [Sheet1$]", cnnExcel
iCols = rstExcel.Fields.Count
xmlData = ""
xmlData = xmlData&""
Do While Not rstExcel.EOF
xmlData = xmlData& ""
xmlData = xmlData& ""& rstExcel.Fields.Item(0).Value & "" & vbCrLf
xmlData = xmlData& "
xmlData = xmlData& "
Set rstExcel = Nothing

Set cnnExcel = Nothing
% >

Run this file and view source code of this file , save view source file as a "Sitemap.xml"

Friday, October 16, 2009

File comparison tool free download.

sometime we need to compare two file ,like comparing coding or some text like that , in that time if the document is too long then Comparing this will be very difficult .

here i found very nice file comparison tool call Turtoise SVN .
Turtoise SVN is Free and it can provide file comparison facility same as popular beyond compare tool.

1. Download the SVN the two file you want to make the comparison. here i have created two files test1 &test2

3. now select two file right click on mouse , and select "Diff" option on same ,

4. It will show you the difference between two files.

that's it falk,

Wednesday, October 14, 2009

Check Page.IsValid at Client Side using C#

when i was designing a registration form i run into this case, what i want is if user press register
button, then that button get disable to avoid multiple click on registration button.

now if error occurred on the client side never call any server-side function so in this case the disable button will remain disable as it is, now to overcome

such problem we have to identify whether Page is error free on the client-side.

To find out this simply check on Disable Submit Button.

//write your code here.

function DisableClick() {
var obj = 'btnUpd';
if (Page_IsValid) {
document.getElementById(obj).disabled = true;
txt = txt + 1;
message = 'Please Wait......(' + txt + ')!';
document.getElementById(obj).value = message;
var t = setTimeout('DisableClick()', 600);
document.getElementById(obj).disabled = false;
document.getElementById('PleaseWait').style.display = 'none';
document.getElementById(obj).value = "Register";

hope it will work you,

Thursday, October 8, 2009

Twitter API from C# .Net

Twitter is one of the Great and friendly site ,Twitter has an API implementation that is very simple to understand and use. if you want to friends friends timelie of user you can use that from here


Ones you find the RSS of friends , you can get the 3 Keywords
1 . Statuses - what are you working on ?
2. friends_timeline - what do you need ?
3. RSS - in which format you need Rss
API supoorting in xml , json, rss, atom you can choose one of that .

Methods supported: See Twitter API

There are many objects supported, but the above format applies for only a few like Statuses, User, Direct Messages. there rest all other are mostly similar.

right now i am working on complete set of wrappers using this api, so it will be easy ,plz leave a comment if you want any help

Saturday, October 3, 2009

Google Maps Api

There are lot many service provided by Google ,

Google map

is one of that , which can be used to discover the world through your application , you can used this for many other purpose just like bookmarking you city,state, your Company and many more.

here is Google api you can integrate with you .net application, below is code how you can do that but The first thing if you wanted a google map Api key for Local server testing you may download here.

"ABQIAAAA5HHs8lZl18SY-r1Jm1qy-hQpDmmpk8q921mRIPG4qgOvy0T09hTGvwPs_FnHiEq78dTl61JP9JQQtw" this is test key for yout local server and IIS (701.00 bytes)

Thursday, October 1, 2009

ASP.NET AJAX and the MS Virtual Earth Control

i was just refering some site regarding on

Microsoft Virtual Earth Control

.so i just found very nice and simple article on "Master/Detail with ASP.NET AJAX and the MS Virtual Earth Control" written by matt berseth , its really nice

This application allows users to browse zip-codes using the Virtual Earth Map Control , on below pics you can see how to accomplish this , The example uses PageMethods to fetch the latitude and longitudes for the zip-codes , if you want more about PageMethods
just google it out or else refer it here

Live Demo | Download

Monday, September 28, 2009

Captcha ASP.NET 2.0 Server Control

Captcha control is used to validate user in terms of avoiding spamming on message or comments or registration or so on . implement Captcha on your application , below are the steps how u can do that

Installation instruction:

1. Unzip the downloaded file.
2. Copy MSCaptcha.dll and MSCaptcha.xml files to your /bin application directory.
3. add reference to mscaptcha.dll file.
4. Modify your web.config file, by adding this line to &l;httphandlers> section:
<add verb="GET" path="CaptchaImage.axd" type="MSCaptcha.CaptchaImageHandler, MSCaptcha"/>

5.Add MSCaptcha control to your Visual Studio toolbox (optional)

how to use on Page

1. Add line to your .aspx file:
<%@ Register Assembly="MSCaptcha" Namespace="MSCaptcha" TagPrefix="cc1" % >

2. add the control whenever you want:

<cc1:CaptchaControl ID="ccJoin" runat="server" CaptchaBackgroundNoise="none" CaptchaLength="5" CaptchaHeight="60" CaptchaWidth="200" CaptchaLineNoise="None" CaptchaMinTimeout="5" CaptchaMaxTimeout="240" / >

3. Add this on your CS file to check or Validate enter captcha is right or wrong

if (!ccJoin.UserValidated)
//Inform user that his input was wrong ...

now its look like this way :

Download Here..

Captcha ASP.NET 2.0

Friday, September 25, 2009

css techniques

on web application CSS is playing very important role . And it is being used more and more often. Cascading Style Sheets has many advantages
like layout, design of the page,presented on the page and so on

here i have some collections of stuffs on CSS technique .


Drop Cap – Capital Letters with CSS


Define Image Opacity with CSS


How to Create a Block Hover Effect for a List of Links


Pullquotes with CSS


CSS Diagrams


Footer Stick


CSS Image Map


CSS Image Pop-Up


CSS Image Replacement for Buttons

Link Thumbnail


CSS Map Pop


PHP-based CSS Style Switcher


CSS Unordered List Calender

CSS-Based Tables: Techniques


Printing Web-Documents and CSS

look at here more

System.IndexOutOfRangeException was unhandled (Message="Index was outside the bounds of the array.")

on C# or we are using array,Array is one of the best way to mentain collection of data together and proper way ,

here is one Error which get call whenever some problem with size and all

The exception that is thrown when an attempt is made to access an element of an array with an index that is outside the bounds of the array. This class cannot be

.NET arrays have base 0 and should be kept in mind when coding.

ones you got this error you have to resize your array size, accroding to your requirements

Wednesday, September 23, 2009

CSV to XML Conversion using LINQ

on C#, if we want to Convert CSV to XML then you can use Language Integrated Query (LINQ) can be used to convert a CSV file to XML. Here is the sample CSV file that needs to be converted

below example code reads the CSV file to an array. LINQ is used to loop through the array and the contents are written as XML using XElement (System.XML.Linq).

public void ConvCSVToXML()


String[] FileContent = File.ReadAllLines(@"D:\Proj\jquery.csv");

String XMLNS = "";

XElement Inv = new XElement("type", from

items in FileContent

let fields = items.Split(',')

select new XElement("fadein",

new XElement("Tab", fields[0]),

new XElement("ProgressBar", fields[1]),

new XElement("ToolTip", fields[2]),

new XElement("Menu", fields[3]),


File.WriteAllText(@"D:\Proj\jquery.xml", XMLNS + Inv.ToString() );

using this you can convert your CSV file xml using C# and C# Convert CSV To XML, .NET CSV To XML

Tuesday, September 22, 2009

How to get the Upper Bound of an Array in C#

hi, if you'r using asp, vbscript and all then you have option call UBound
which will return a UpperBound value of Array. but on C#, you dont have that option call Ubound ,for that you can use GetUpperBound() option - Gets the upper bound of the specified dimension in the Array.

here is an Example which can show how to use GetUpperBound()

For i = MyArray.GetLowerBound(0) To MyArray.GetUpperBound(0)

Next i

like this way you can use both option call GetLowerBound & GetUpperBound ,
GetLowerBound will return lower bound you have to pass (int value)
0 - 1st arrayvalue, 1- 2ndarrayvalue like that,

thank you.

Saturday, September 19, 2009

Download data using FTP or HTTP with C#

If you want to download data via FTP or HTTP then you can use this solution. you can Use the System.Net.WebClient to achieve this. The URI determines whether a file (file://) , FTP (FTP://) or HTTP (HTTP:// or HTTPS://) scheme is to be used.

On .Net2.0 there is an Async Version get added which will allows you download data asynchronously as a background task using its own thread from the thread pool. WebClient object can handle one async download at a time. its not useful for downloading many files concurrently , but if you want to do this then you can use multiple WebClient objects. if you want to Cancel the current download using CancelAsync.

There are Several Methods:

1. OpenRead - returns a System.IO.Stream
OpenReadAsync - async downloading use the handler OpenReadCompleted

2. DownloadData - returns a ByteArray
DownloadDataAsync - use handler DownloadDataCompleted

3. DownloadFile - Saves to a local file
DownloadFileAsync - use handler DownloadFileCompleted

4. DownloadString - returns a String ( introduced in .net 2.0)
DownloadStringAsync - use handler DownloadStringCompleted

Here is Sample code:

using System.IO;
using System.Net;
using System.Text.RegularExpressions;

string remoteUri = "";
WebClient client = new WebClient();
string str = client.DownloadString(remoteUri);

** if you are using proxy then you need extra code to code around it.
on my next post i will tell you how you can download data using Proxy.
Downloading data over FTP, Downloading data over HTTP, FTP, HTTP, Net.WebClient

Friday, September 18, 2009

JQuery Plugins and Demos for Developers.

hello ,i have again come up with some collection of jquery plugins with Demos , hope u like it.

1. jGoogle
jGoogle will wrap google AJAX search APIs in a single jQuery plugin to extract usable data.
on the first version they have included GImageSearch option
- View demo
- View Source

2. Virtual jQuery Keyboard
jquery Virtual Keyboard is one of the good feature for preventing keystrokes , it will very dangerous when you enter some bank account and password like information , virtual keyboard will play very imp role here, you can't get the stoke on your log ,
-View Demo

3. Scrolling with Load Effects.
when we have lots of content then its not looking good when we are showing them in one and too long panel, instead of that we can show loading effects the it also look beautiful and cool
- View demo

4. Tablesorter 2.0
When we showing the records on table then sorting is one of the basic option , to show the records like date wise , increasing decrease order and so on like this feature you can add here
- View demo

5. jQuery Right-click Plugin
This plugin enable you to detect the event when user get click right button of mouse . so as per the click you can do your operation like disable the right click and so on or adding any information to drop down when clicking right click
-View demo

6. Jquery: Progress Bar
Progress bar is one of the cool feature that use can use anywhere where you are data get retrieve from database and if it will take too much time to load that page , in this case you can show loading like Effects so user can understand that page is being lead
- view Demo

7. jQuery Feed Menus
Feed is used for bookmarking and all other purpose , you can show multiple feed under one category , so you can use your space and its also look nice
- view Demo

8. gShuffle
The plugin animation is triggered every time the Shuffle button is clicked. Each time, the code will choose two squares to switch positions with one another.
- view Demo

9 -Mark It Up
MarkItUp, you can convert text areas into powerful HTML, BBCode or Wiki editor.

hope you like it ,
will add more on it, if you found anything could be related with this plz add on comments

Friday, September 11, 2009

Jquery ToolTip

Tooltip is one of the Cool & useful feature in Jquery , its mostly used for showing
Additional information for that records , you can use that anywhere like showing Customer information, Suggestion for form fillup , for zoom image and many more

here are some collection of tooltips .

1. Bottom slide tooltip

2. jQuery Tooltip Plugin



5.BoxOver Tooltip


7.EZPZ jQuery Tooltip

8. CSS Globe jQuery Tooltip plugin

hope u like it

Thursday, September 10, 2009

SQL : Count String Occurrence

in SQl server, we dont have any function which can return the number of words in a perticular string .but from small tricks we can do that . now Consider here we can separating the character on space basis

example :

declare @Str VARCHAR(2000)
SET @Str = 'Hi this is Test line which count no of spaces.'
select LEN(@Str) - LEN(Replace(@Str,' ', '')) + 1

Above query will return value 10 , but if the words are separate by more than one space then it will aslo count that space. but its wrong as per the answer.
in that case Create one function which can keep multiple spaces as a single space and return proper result

Below is a Function which can remove white space and all and retrun peoper result.

CREATE FUNCTION [dbo].[WordCount] ( @inStr VARCHAR(4000) )


SET @Index = 1
SET @WordCount = 0

WHILE @Index <= LEN(@InStr)
SET @Char = SUBSTRING(@InStr, @Index, 1)
SET @PrevChar = CASE WHEN @Index = 1 THEN ' '
ELSE SUBSTRING(@InStr, @Index - 1, 1)

IF @PrevChar = ' ' AND @Char != ' '
SET @WordCount = @WordCount + 1

SET @Index = @Index + 1

RETURN @WordCount

now you can use that WordCount Function

SET @String = 'Hi this is Test line which count no of spaces.'
SELECT [dbo].[WordCount] ( @String )

Above Query will return Result 10 not any other,
hope you like this ,

Tuesday, September 8, 2009

SQL : how to sort ip Address.

ip address, is one of the key point to identify the user. now if your storing ip address on your database with the VARCHAR datatype with length of 25. guess you have 1 lakh's of records of different ip address and you want to sort that.

Then your sorting query will be

select [ipadd] as IpAddress from ip order by [ipadd]

now in this case it will return a result something like this


something like that but actually its not your answer , it get sorted on first no. so becasue of that your result get warry.on actual basic the result should come in this format


now how to achieve this use some technique here

select [IPAdd] from ip
order by CAST(PARSENAME([IPAdd], 4) AS INT),

now check this you get above result
thank you.

Monday, September 7, 2009

publish multiple websites using one solution.

on Visual Studio you can publish only one website at a time otherwise there is a clash between one website with multiple website.if you want to do that means on startup of one website other website also publish . for that you need to do some setting on Solutional Level.

follow the steps :
1- on proejct Solution just right click it & select Product Dependencies.
2- select Dependencies tab.
3- select your main website(startup one) from Dropdown.
4- now check all the web service on "Depends on" section
that you can decide how many site you want to publish at a time of this main site.
5- click ok

now whenever you publish that main site , then it will prompt publish window for all other depended site ,then all other mention site will also get publish , if you dont want to publish that you do the same above procedure to deactivated that ,

that's all...

Thursday, September 3, 2009

About XmlPreloadedResolver

when using Silverlight then XmlPreloadedResolver meaning is very useful, its a new type which can be useful when your working with XML . on XmlPreloadedResolver it has the Ability to load the DTD without call to network. This type manually maintain the DTD cache and all other with xml streams. XmlPreloadedResolver includes RSS1.0 and XHTML1.0 Defination of DTD.

sample code on how to work with XmlPreloadedResolver

String strDtd = "";
XmlPreloadedResolver resolver = new XmlPreloadedResolver();
resolver.Add(resolver.ResolveUri(null, "nameofDTD.dtd"), strDtd);
XmlReaderSettings rs = new XmlReaderSettings();
rs.XmlResolver = resolver;
rs.DtdProcessing = DtdProcessing.Parse;
XmlReader reader = XmlReader.Create("samplexml.xml", rs);

now you can also set the DTD sets Enable using XmlKnownDtds enumeration.
XmlKnownDtds is used with the XmlPreloadedResolver to identify the well-known DTD

the following example shos preloading Xhtml1.0 DTd into the XmlReaderSettings object
here there is no need of network call to parse the Xhtml will done automatically.

XmlReaderSettings settings = new XmlReaderSettings();
//define the Setting object to parsing DTD
settings.DtdProcessing = DtdProcessing.Parse;
// Define preloading Xhtml10 DTD
settings.XmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10);
//suppose read the sample.html file using XmlReader
XmlReader reader = XmlReader.Create("sample.html", settings);
// and load using XDocument object
XDocument document = XDocument.Load(reader);

for more refer to :

Wednesday, September 2, 2009

Highlight Gridview's Row on mouseHover

in Gridview we have seen most of the time we one we take move hover to any row , size of that row or background color or any animation get happen you can do that using css, or java script also.

here i have do that using java script

function gvHigh(tRow,showAct)
if (showAct)
{ = '#ff32ss';
{ = '#ffffff';

function urlloca(Url)
document.location.href = Url;

and Define onrowCreated function like this and put your code behind here

protected void gv1_onRowCreated(object sender, EventArgs e)
foreach (GridViewRow gvRow in gv1.Rows)
gvRow.Attributes["onmouseover"] = "highlight(this, true);";
gvRow.Attributes["onmouseout"] = "highlight(this, false);";
HttpResponse myHttpResponse = Response;
HtmlTextWriter myHtmlTextWriter = new HtmlTextWriter(myHttpResponse.Output);


that's it it will help you.
thank you.

Monday, August 31, 2009

set meta tags to master page from Child Page

Meta tag ,title, keywords ,Description and all are very assential on each page , if your using with Master page then also its possible some people think that how it can be? master page means one page and it get call on each child page creation.but you can also add the keyword , title and all with each pertucular page if you'r using master page then also.

Below are the Steps you need to follow


Create oen Content place holder on your master page with in HEAD section

<head id="Head_Demo" runat="server">
<asp:ContentPlaceHolder runat="server" id="Contentplace_Demo"> </asp:ContentPlaceHolder>
</head >

2 -

on Your Child page put this code :

<asp:Content runat="server" ContentPlaceHolderID="ContentHeaders" ID="Content_Demo" >
<META name="keywords" content="<%=pgKeywords%>">
<META name="description" content="<%=pgDescription%>">

3 -

on content page's(Child page) open CodeBehind and Declare this :
Declare variables as below in the global declaration section

Protected pgKeywords As String = ""
Protected pgTitle As String = ""
Protected pgDescription As String = ""

Now set the New title, Desc and all as per the your req. copy that code on page_load Event

pgKeywords = "keywords Content Goes here "
pgTitle = "title Content Goes here"
pgDescription = "Description Content Goes here"

or you can also refer this set mata tags

that's it
hope it will helps you

Friday, August 28, 2009

How to get Mouse Cursor Position

There is no Certain way to find the Cursor position of mouse within the Browser.
W3c standards say that you can get the position when event is triggered by event.clientX and same for clientY. to find out the Distance between left n Top


Its works fine on IE6 , Netsacape , Firefox , Opera 7+ and all othe browser.
in IE uses two Different ways to scroll the position of pages they are using Document.body.ScrollLeft and same for the ScrollTop. this is in Before version

of 6
Some of the Browser used PageXOffset & PageYOffset.

Here is Function call MouseX() and MouseY() which can calculate the X and Y Co-ordinates of same,

function mXbar(action) {
if (action.pageX) return action.pageX;
else if (action.clientX)
return action.clientX + (document.documentElement.scrollLeft ?document.documentElement.scrollLeft :document.body.scrollLeft);
else return null;
function mYbar(action) {
if (action.pageY) return action.pageY;
else if (action.clientY)
return action.clientY + (document.documentElement.scrollTop ?document.documentElement.scrollTop :document.body.scrollTop);
else return null;

there are few more ways to calculate the cursor position event.ScrenX or event.screenY
these feature are not thee in Netscape4 and IE old version, but in new version of ie 7 + they have all such feature,

Tuesday, August 18, 2009

Best Ajax , Jquery ,Css Calendar collections

Calendar is one of the requirement while taking a input from user in terms of
Data of Birth , Start Journey , Admission Date and so many .its a Essential Control in terms of all the Application Development.

here are the some cool and nice collections of calendar most of them are in ajax, css , and Jquery . hope you like it .

1. VLA Calendar

2. ASP.Net calendar

3. Date Input Calendar

4. using Prototype date picker

5. Jquery Calendar

6. Date and Time Picker

hope u like this collection , will keep on updating ,
if u know any one in this plz send a comment on it,

Thursday, August 13, 2009

Handle Master page Click Event on Content Page

In ASP.net2.5 there a new concept knowns as Master Page , with the help of that you can
customize you'r repeteative work. Create a one Master page and use that page on all the other pages. Its really very good tech to crear your coding and clear your logic also.

now sometime we have a LinkButton define on Master page which can be work as a "Link to the Customer information " and this can be change depend on customer role. and that LinkButton action we want in the Contenet page.

Supoose we have LinkButton call "linkFromMasterPage" on Master Page. Here is small code which can helps you to do same .


Public LinkButton linkFromMasterPage(){

Get {

Return linkFromMasterPage;



Now next Process is reference the Master Page as a casted object in the Content page.
here CusMasterPg is a Class of Maste Page.

CusMasterPg cm = ((CusMasterPg) (Master));

Now you can easily access the all the methods, public properties of Master page class.
so next stpe is handle the button Event on your content page

protected void Page_Load(object sender, EventArgs e)
If (!(IsNothing(cm))) {

cm.linkFromMasterPage.Click += New EventHandler(linkFromMasterPage_Click);


next thing is define actual method handle on your page.

Protected void linkFromMasterPage_Click(Object sender, System.EventArgs e){

// write Perform Business Logic Here

thats all , you can do same thing for User Controls also for Handle Master page Click Event on Content Page.

Wednesday, August 12, 2009

ASP.NET Cross Site Scripting Toolkit

hi i have found some very much useful related with the Cross site Scripting.
cross site scripting is very common method to hack a site, most of the hacker get hack the site with the some basic scripting techniques.

now Microsoft get Introduce the Toolkit to Prevent the Cross-site Scripting not exactly preventing but you can say some basic level of Prevention. this toolkit is supposed to be offer some extra good efforts against the type if attack.

Cross Site Scripting may be done using -
1. via QueryString
2. via Text box entry
and so many

download Microsoft Anti-Cross Site Scripting Library toolkit here

Silverlight-based Local Impact Map

It is one of the Great and very Interestig web application devlope by Microsoft ,
there are some reason to devlop this.

The Local Impact Map are conatin around 400+ Stories about the Program of Microsoft around the world.In that you can see it includes the Photos videos and more and more Visual Effects.

It is very interesting and easy to use , i like the one of that feature of Deep Zooming of Map, its really cool and very fast , Its not a ' free mouse-wheelin ' where you can zoom the Preticular location , they are taking advantage of Deep Zooming of image along with zoomo for Controlled Transition.

Microsoft’s Silverlight-based Local Impact Map

plz have a look at this cool Local Imapct of Map

Wednesday, August 5, 2009

ASP Format Date and Time

while coding on ASP we required date and time most of the time, how to get this is very basic and well known to the most of the Programmers, but how to get the only specific date , time in required format is a main task ,

for that we have inbuild function call FormatDateTime() .

now we very well knows if we want to get current date and time then we can use now()

<%dim TodayDnT
TodayDnT = now()

if you want the Result of same then use <% Response.write(TodayDnT) %>
so it will return result as : - 8/5/2009 12:11 PM

now we have the option to format that
1. Using 0

Response.write FormatDateTime(TodayDnT,0)

Result : - 8/5/2009 12:11:10 PM

2. Using 1

Response.write FormatDateTime(TodayDnT,1)

Result :- Wednesday, August 12, 2009 (long date )

3. Using 2

Response.write FormatDateTime(TodayDnT,2)

Result: - 8/5/2009 (short date)

4. using 3

Response.write FormatDateTime(TodayDnT,3)

Result : - 12:11:10 PM (long time)

5. using 4

Response.write FormatDateTime(TodayDnT,4)

Result : - 11:10 (current time in 24 format (hh:mm)

If you want to change the Date and Time according to international location then
use session.lcid property

Ex : - <% session.lcid=1036 %>
which will set the Date n Time in French Format

here is the List of all the
International Location

Monday, August 3, 2009

Debugging for ASP.NET Applications

If you are using Visual Studio2005 and if you want to enable debugging in the project properties Then Follow the Stpes
In VS 2005, use the <Project> Property Pages to set project properties :
here is the way to do
- Right click on Solution Explore of Project,Then Open the Property Pages by and selecting Property Pages.
- Select Start Option tab
- Under Debuggers, make sure the ASP.NET box is selected.

You can also enable the debugging using web.config file

- Inside the <compilation> tag, you will create the debug attribute.
- specify attribute as a "debug", not "Debug" or "DEBUG" because the are very Case-Sensitive so please take care of that.
- Set debug option as a true.

Here is a sample Web.config file

<compilation defaultLanguage="VB" debug="true" numRecompilesBeforeAppRestart="15">

<compiler language="C#;Csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,system, Version=1.0.5000.0, Culture=neutral,

PublicKeyToken=b77a5c561934e089" />
<compiler language="VB;VBScript" extension=".cls" type="Microsoft.VisualBasic.VBCodeProvider,system, Version=1.0.5000.0, Culture=neutral,

PublicKeyToken=b77a5c561934e089" />

<add assembly="ADODB" />
<add assembly="*" />

<add namespace="System.Web.UI" />
<add namespace="System.Web" />
<add namespace="System.Web.UI.WebControls" />
<add namespace="System.Web.UI.HtmlControls" />

Like that you can set the Debugging option using web.config file also and using GUI also.

Saturday, August 1, 2009

Loop through Session ,Application ,form Variable

In Classic asp sometime we need to retrieve all the Session Application and Request object variable, in this case we can use Loop through technique which will generate all the Session variable , application variable , and Request variable are used in current page do this need to simply put this line on your page


dim i
For Each i in Session.Contents
Response.Write(i & "<br />")

dim i
For Each i in Session.StaticObjects
Response.Write(i & "<br />")

it will Display all the Session Contents / session staticobjets are used in current page .


dim i
For Each i in Application.Contents
Response.Write(i & "<br />")

this will iterate all the Application content are being used in current page.


for each x in Request.form
Response.Write("<br>" & x & " = " & Request.form(x))

this will generate all the Request variable


for each name in Request.ServerVariables
Response.write ""&name &"-------------"& Request.ServerVariables(name) &"<br>"

it will loop with the all the Server Variable.

Thursday, July 30, 2009

Export XML from SQL using a Stored Procedure.

1) Generate a file with the text-editor like:


Save it as c:\temp\template.tpl

2) Open Query Analyzer and type:

sp_makewebtask @outputfile = 'c:\temp\myxmlfile.xml',
@query = 'select * from sysobjects for xml auto',
@templatefile = 'c:\temp\template.tpl'

The result is a XML-File!

More ^

Wednesday, July 29, 2009

Move Seleted Records using Checkbox in GridView

Hi ,

here is nice tutorial or you can say very simple example on how you can
delete or move the records from the Gridview

Move/Delete content From GridView

hope u like it ,

Monday, July 27, 2009

Hide Show Div

hi this is cool and simple javascript stuffs which HIDE and Show Details
using Div

<script language="javascript">
function toggle() {
var ele = document.getElementById("togText");
var text = document.getElementById("ShowText");
if( == "block") { = "none";
text.innerHTML = "Click Me";
else { = "block";
text.innerHTML = "Hide It";

Click Here to View Details
<a id="ShowText" href="javascript:toggle();">
Click Me </a>
<div id="togText" style="display: none">
< h1 > Hi, Kiran hows you? Hope u like this Cool stuff. < /h1 >

hope you like it ,

Friday, July 24, 2009

Set Favicon in different Browser

we have seen most of the site has Fevicon which describe the addtional information
about the site , Addtion in the sence it could be logo,company Profile, company production,web site application, and so many .

here are the top most Example of the fevicon sites

now how u can do this

its very simple to do , just u need to add some line's of code and be ready with small icon image, u can also add animated image in fevicon

add this part in between <head> </head> Section

<link rel="shortcut icon" href="images/favicon.ico">

now some time this code will not work on most of the Browser like IE old version
in this case u can add this line

<link rel="shortcut icon" href="images/favicon.ico" type="image/" *gt;

any other query plz comment on it.

Thursday, July 23, 2009

Mini-URL on CodePlex using C#

if u want to minimize / Shrink / Shorten URL , then its a very good technique to do this then. its also useful as per the security and many others aspects.

its very useful for the developer to create a simple URL for there web application / url redirection services like tinyurl

- you can download that sample ASP.Net MVC Application from here

- Project Description

hope u like that .

Wednesday, July 22, 2009

Eliminate Duplicate records from the Grid View

Most of the time we need to delete duplicate entries from GridView, in this case we can delete it manually also or using onRowcreate also we can remove that .

suppose Mr.Xyz has has more than 2 Account in site and we want to show
in GridView Person and RelatedBlogs like this

and in this case we dont want to repeat Person name on each row.
- I have a data source

DataTable dtsource = new DataTable();

//Adding columns to datatable
dtsource.Columns.Add("Related Blog");

//Adding records to the datatable
dtsource.Rows.Add("kiran", "");
dtsource.Rows.Add("kiran", "webdevlopmenthelp");
dtsource.Rows.Add("kiran", "");
dtsource.Rows.Add("mark", "");
dtsource.Rows.Add("mark", "");

put the below code in codebehind

private void GenerateUniqueData(int cellno)
//Logic for unique names

//Step 1:

string initialnamevalue = grdUniqueNames.Rows[0].Cells[cellno].Text;

//Step 2:

for (int i = 1; i < grdUniqueNames.Rows.Count; i++)

if (grdUniqueNames.Rows[i].Cells[cellno].Text == initialnamevalue)
grdUniqueNames.Rows[i].Cells[cellno].Text = string.Empty;
initialnamevalue = grdUniqueNames.Rows[i].Cells[cellno].Text;

on GridView define property OnRowCreated="GenerateUniqueData" it will search the record via cell and set the Person name as a empty or person name

Caching in ASP.NET


is one of the best technique of persisting the data in memory for immediate access to requesting program calls.Caching is about storing data in memory the first time it is requested and then re-using it for the following requests for a specified period of time.

Why Caching is important ?

Every time we have to querying database for each request is not cost-effective in terms of server resources, hence is lot better to cache or persist the data to avoid this costly loss of in this case we are imporve the system performance and avoid the consistancy.

ASP.Net Provides the flexibility in terms of caching at different levels.

  • Fragment Caching

  • in this case caching a user control that can be used in a base web form page.if you have used include files in the traditional ASP model then this caching model is like caching these include files separately. In ASP.NET more often this is done through User Controls. Initially even though one feels a bit misleading, this is a significant technique that can be used especially when implementing "n" instances of the controls in various *.aspx pages. We can use the same syntax that we declared for the page level caching as shown above, but the power of fragment caching comes from the attribute "VaryByControl". Using this attribute one can cache a user control based on the properties exposed.

    Syntax: <%@ OutputCache Duration="60" VaryByControl="DepartmentId" %>

    The above syntax when declared within an *.ascx file ensures that the control is cached for 60 seconds and the number of representations of cached control is dependant on the property "DepartmentId" declared in the control.

    Add the following into an *.ascx file. Please note the use of tag "Control" and the cache declaration.

    <script runat="server">
    private int _Departmentid=0;
    public int DepartMentId
    get{return _Departmentid;}
    set{_Departmentid =value;}
    //Load event of control
    void Page_Load(Object sender, EventArgs e)
    lblText.Text = "Time is " + DateTime.Now.ToString() + " for Department id = "
    + _Departmentid + "\n";
    <asp:Label id="lblText" runat="server"></asp:Label>

    Add the following to an *.aspx file. Please note the way "Register" tag is used;

    the declaration of control using syntax <[TagPrefix]:[TagName]>

    <%@ Page Language="C#" Trace="true" %>
    <%@ Register TagPrefix="CacheSample" TagName="Text" Src="CachingControl.ascx" %>
    <script runat=server>
    void Page_Load(Object sender, EventArgs e)
    this.lbltime.Text ="Base form time is " + DateTime.Now.ToString() + "\n";
    <asp:Label id="lbltime" runat="server"></asp:Label>
    <CACHESAMPLE:TEXT id="instance1" runat="Server" DepartMentId="0">
    <CACHESAMPLE:TEXT id="instance2" runat="Server" DepartMentId="1">

  • Application Level Caching

  • With Page level Output caching one cannot cache objects between pages within an application. Fragment caching is great in that sense but has limitations by using user controls as means to do. We can use the Cache object programmatically to take advantage of caching objects and share the same between pages. Further the availability of different overloaded methods gives a greater flexibility for our Cache policy like Timespan, Absolute expiration etc. But one of the biggest takes is the CacheDependancy. This means that one can create a cache and associate with it a dependency that is either another cache key or a file.

    Find below the snippet that uses CacheDependancy. Here what I have done is to provide a list view of existing employees. You need to create a Database in Sql Server, setup some data before you can continue. The schema scripts are enclosed in the article.

    Add database connection value in Web.Config and change the value as per your setup.

    <add key="conn" value="Data Source=vishnu;trusted_connection=yes;Initial Catalog=Users"/>

    First I get the dataset into which I fill the user list. But before this I check for the cache initially if it exists I directly cast it to a dataset, if not create a cache again.

  • Page Level Output Caching

  • This is at the page level and one of the easiest means for caching pages. This requires one to specify Duration of cache and Attribute of caching.

Syntax: <%@ OutputCache Duration="60" VaryByParam="none" %>

The above syntax specifies that the page be cached for duration of 60 seconds and the value "none" for VaryByParam* attribute makes sure that there is a single cached page available for this duration specified.

so at last Caching is a technique that definitely improves the performance of web applications if one is careful to have a balance in terms of which data needs to be cached and parameter values for expiration policy.

hope this article helps you to imporve your applicaiton performance and best result ever

- you can find more information here
- how to perform Cache Optimization

Tuesday, July 21, 2009

IsPostBack property

IsPostBack-Gets a value indicating whether the page is being loaded in response to a client postback, or if it is being loaded and accessed for the first time.

when the page is loaded in order to determine whether the page is being rendered for the first time or is responding to a postback. If the page is being rendered for the first time, the code calls the Page..::.Validate method.


private void Page_Load()
if (!IsPostBack)
// Validate initially to force asterisks
// to appear before the first roundtrip.


protected void Page_Load(object sender, EventArgs e)
if (!Page.IsPostBack)
Response.write("2nd Time Visisted..");

protected void PageDataBind(string SearchProduct)
SqlDataAdapter SDA ;
DataSet ds = new DataSet();
String sql = "select * from Emp where ID ='"+ DropDownList.SelectedItem.Text +"'";
SDA.Fill(ds, "productDetails");
ShowId.DataSource = ds;

when loading of the page, the control doesn't go through the redundant action of re-loading the control. It loads it only once, at the initial page load. Once the page is loaded, the click event from the button (or however you post back) is considered to be a postback. Yes, the page gets reloaded, but, by surrounding your data population with this statement, the page knows that the initial data loading was already done, so it doesn't happen any more, and it gets maintained throughout any subsequent post back. The second, and most rewarding thing that happens is that the selection which was made by the end user is maintained throughout the post back. This is the pay-off - by doing it with the If/Then Page.IsPostBack statement, your selection carries through to your query and the query returns the results you wanted in the first place.

Monday, July 20, 2009

Filter User via IP

its a good technique to Restrict user to view your website , this task can be done with the help of checking of user's IP Address and match with our database and if user get found under
that IP then you can set Denied Access to them .

But in this case you need a Live IP Address database,
there are so many website are there they are provides free IP Address database range .

and with the help of that u can Denied user.

here are the List of free IP address database sites

Simply download that.

1. Create one IP check function
2. take user Ip address

in ASP : - Ip =Request.Servervariables("REMOTE_HOST")
in C# : - String ipAddress = (Request.ServerVariables["REMOTE_ADDR"]);

3. then check if user's Ip address is there in you'r database , depend on that
you can prevent user.

hope it will helps you,

open new window in GridView using OnRowCreated

In GridView using "OnRowCreated" function we can add onClick function.

here is the sample code

html code

<asp:TemplateField HeaderText="Header 3">
<asp:Label ID="Label1" runat="server" Text="Click Me"></asp:Label>

and CodeBehind is

protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
Label l = (Label)e.Row.FindControl("Label1");
if (l != null)
string script = "'Default.aspx');";
l.Attributes.Add("onclick", script);

run the Application and click "Click Me" it will open new window , indirectly we are adding
OnClick Event in That Row.

Saturday, July 18, 2009

import contact list from gmail,yahoo,rediffmail

yes , use can retrieve the contact list from mail server like Gmail, Rediff , Hotmail , AOL and all others They are providing free API to do this, u simply download the Application at your end and pass the parameter like (ID,Password) .

Gmail :

google code API

Yahoo / Live / Rediff

Yahoo / Live / Rediff

Rediff API
Rediff API

Zip application

opencontactsnet OpenContact.NET 1.0 file released:

AOL Guide to Integrating OpenAuth
happy coding.......

CountDown Timer

Hi , here is cool triks of CountDown timer, mostly its useful in website while validating time like online exam, date time , game countdown , and so many

Below is the code needed to display count down in HTML page using javascript.

You define container for the count down (either <span> or <div> tag) and the initial value, and the code updates the time automaticlly in the format HH:MM:SS

You can also control the style of the container using standard CSS, as demonstrated in the below and attached code.

To activate the count down in one of your existing pages you
have to follow two steps:

1. include the attached CountDown.js file with:

<script type="text/javascript" src="CountDown.js"> <script>

2. have such javascript in the section:

<script type="text/javascript">
function WindowLoad(event) {
ActivateCountDown("CountDownPanel", 100);

where "CountDownPanel" is the ID of the container
(i.e. you should have <span> or <div> with this ID) and 100 is the time in seconds to be counted.

here is CountDown.js file -------------------------------

var _countDowncontainer=0;
var _currentSeconds=0;

function ActivateCountDown(strContainerID, initialValue) {
_countDowncontainer = document.getElementById(strContainerID);

if (!_countDowncontainer) {
alert("count down error: container does not exist: "+strContainerID+
"\nmake sure html element with this ID exists");

window.setTimeout("CountDownTick()", 1000);

function CountDownTick() {
if (_currentSeconds <= 0) {
alert("your time has expired!");

window.setTimeout("CountDownTick()", 1000);

function SetCountdownText(seconds) {
_currentSeconds = seconds;

//get minutes:
var minutes=parseInt(seconds/60);

seconds = (seconds%60);

//get hours:
var hours=parseInt(minutes/60);

minutes = (minutes%60);

//build text:
var strText = AddZero(hours) + ":" + AddZero(minutes) + ":" + AddZero(seconds);

_countDowncontainer.innerHTML = strText;

function AddZero(num) {
return ((num >= 0)&&(num < 10))?"0"+num:num+"";

Friday, July 17, 2009

Twitter API in C#

I used C# and WCF, but I could have just as easily used an ASMX web service. This code is fairly simple.

Note: This code will not run as listed. You have to have a password. This code has that as a shared variable, but I'm not showing that to you, seriously. I hope that this is of some help to you.

public void SubmitUserStatus(string username, string tweet)
// encode the username/password
string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
// determine what we want to upload as a status
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet);
// connect with the update page
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("");
// set the method to POST
request.Method = "POST";
// thanks to argodev for this recent change!
request.ServicePoint.Expect100Continue = false;
// set the authorisation levels
request.Headers.Add("Authorization", "Basic " + user);
request.ContentType = "application/x-www-form-urlencoded";
// set the length of the content
request.ContentLength = bytes.Length;
// set up the stream
Stream reqStream = request.GetRequestStream();
// write to the stream
reqStream.Write(bytes, 0, bytes.Length);
// close the stream

for more information on Twitter API
Link :
Orignally posted from this Article

Wednesday, July 15, 2009

Use XMLHTTP Object in C#

The XMLHttpRequest object can be used by scripts to programmatically connect to their originating server via HTTP. you can use this XMLHTTP object in C#.

follow the steps to do thi.

1. Add New Refrence to the Microsoft,Ver3.0 (Msxml 3/4) in your project.

how to add new Refrence

2. import the Namespace Using MSXML2;

3. now add this code in codebehind

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 MSXML2;

public partial class MSXML : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)


protected void Button1_Click(object sender, EventArgs e)
// to get page data (using msxml4)
XMLHTTP40 http = new XMLHTTP40();"GET", ""+TextBox1.Text+"", false, null, null);
string value = http.responseText;

4.Add this code in Html

<form id="form2" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>

Tuesday, July 14, 2009

Pass multiple parameter using HyperLink field in GridView

While using Hyperlink field u can send multiple parameter in Gridview , and then u can retrive it using QueryString Parameter.

here in this Example when user will click on username then it will redirect to{0}&city={1} this page
and it will pass customer id and city .

<asp:SqlDataSource id="datasource1" runat="server" SelectCommand="SELECT CustomerID, CompanyName, City FROM Customers"

<asp:GridView id="gridview1" DataSourceID="datasource1" runat="server"

<asp:BoundField DataField="CustomerID" HeaderText="BoundField" />

"{0}&city={1}" />


Detecting Client IP address

To keep track of Visitor's Record such as IP address and all
then u can use this way ,
it will display the Client proxy ip address , if the client is using Proxy server.

if (Context.Request.ServerVariables["HTTP_VIA"] != null)
IP = Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
IP = Context.Request.ServerVariables["REMOTE_ADDR"].ToString();

Monday, July 13, 2009

Paging with DataList Control

DataList is a data bound list control that displays items using certain templates defined at the design time.The content of the DataList control is manipulated by using templates sections such as FooterTemplate, HeaderTemplate, ItemTemplate, SelectedItemTemplate ,AlternatingItemTemplate, EditItemTemplate and SeparatorTemplate

PagedDataSource, is a class that encapsulates the paging related properties for data-bound controls such as DataGrid, GridView, DataList, DetailsView.

Now lets take an Example of Displaying Country on Datalist with Paging


1. Create Datalist for Country

<asp:DataList ID="dlCountry" runat="server">
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Country_Code") %>'></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Country_Name") %>'></asp:Label>

<asp:DataList ID=" dlPaging" runat="server" OnItemCommand="dlPaging _ItemCommand">
<asp:LinkButton ID="lnkbtnPaging" runat="server" CommandArgument='<%# Eval("PageIndex") %>' CommandName="lnkbtnPaging" Text='<%# Eval("PageText") %>'></asp:LinkButton>

2. now on Code Behind write a method to fetch data from the Country’s table.

private void BindGrid()
string sql = "Select * from Country Order By Country_Name";
SqlDataAdapter da = new SqlDataAdapter(sql, “Yourconnectionstring”);
DataTable dt = new DataTable();

pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = Convert.ToInt16(ddlPageSize.SelectedValue);
pds.CurrentPageIndex = CurrentPage;
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;

dlCountry.DataSource = pds;


3.Call this BindGrid method in the Page load event.

protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)

4.Declare a PagedDataSource object at page scope.
PagedDataSource pds = new PagedDataSource();

5. create new property call CurrentPage to maintain the latest selected page index.
and pu this code on it.

public int CurrentPage

if (this.ViewState["CurrentPage"] == null)
return 0;
return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());

this.ViewState["CurrentPage"] = value;


6.write a method ‘doPaging’ to create a list of page numbers.

private void doPaging()
DataTable dt = new DataTable();
for (int i = 0; i < pds.PageCount; i++)
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = i + 1;

dlPaging.DataSource = dt;

7. create new paging event

protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
if (e.CommandName.Equals("lnkbtnPaging"))
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());

8. Previous And Next Button Events

protected void lnkbtnPrevious_Click(object sender, EventArgs e)
CurrentPage -= 1;

protected void lnkbtnNext_Click(object sender, EventArgs e)
CurrentPage += 1;

9.Change PageSize Dynamically

protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
CurrentPage = 0;

10.HighLight Selected Page Number

protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
lnkbtnPage.Enabled = false;
lnkbtnPage.Font.Bold = true;

view Demo here

Javascript Calendar.


is a one of Gread fucntion while retriveing date from user end , there are lot many use of calendar ex- date of Brith , Order date , Shipping Date and lot many..

in this case selecting proepr date is very imp , in term's of DD/MM/YYYY, some where using YYYY/MM/DD or MM/DD/YYYY , so in this case its its not undustable for the End user to Write Proper date in Text Box , but if you use Drop down in term of (DD/MM/YY or MM/DD/YY ) then its useful for the user ,

here i found some great Javascript code to do same ,

1.Ajax enabled DatePicker v4 :

2. VLA Calendar version 2

3.Customizable calendar component


5. Fancy moo tools date picker

6. Clean Calendar

7. Date picker Widget

8. Yet another JQuery Calendar

9.Simple one

hope this collection likes you.

Friday, July 10, 2009

Simple File Uploads in ASP.NET

uploading a single file from the client machine to your server.

watch live video here How to Upload

Thursday, July 9, 2009

automation for microsoft application using C#

Automation client for Microsoft Excel by using C#.
its a very basic requirement in Client side automation for Microsoft Application like
Excel / Word / OutLook / Powerpoint and all.

To Automate Excel application using C# have a look on this Article

Known Issues with Automation

Because the CLR uses a garbage collector for memory management, and because your RCW is itself a managed object, the lifetime of your Automation object is not guaranteed to can get the actual help from here

317109 : Office Application Does Not Quit After Automation from Visual Studio .NET Client


in sql if we declare column as a Identity columen,as if we want to retrieve the last inserted value then use this

All SQL Server functions that retrieve the last inserted value into the Identity column of a table - @@IDENTITY, SCOPE_IDENTITY, IDENT_CURRENT are similar functions in that they return the last value inserted into the IDENTITY column of a table.

Use SCOPE_IDENTITY() , if you are not sure, if some triggers are going to be written or not on a table. Or, even better, use IDENT_CURRENT(tablename) to be more specific.

for more details

Wednesday, July 8, 2009

Export Gridview to xls

Now you can Export content from GridView to Excel file

1. Create one Button "Export"

<asp:Button id="Export" Text="Export" onClick="Export_Click"> </asp:Button>

2. Add this on Export Event

protected void Export_Click(object sender, EventArgs e)
Response.AddHeader("content-disposition", "attachment;filename=ExportData.xls");
Response.Charset = String.Empty;
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter SWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmWr = new HtmlTextWriter(SWrite);

that's it

Tuesday, July 7, 2009

Limiting Data from GridView

while Desinging GridView we want some special effets like (coloring , bold, Setting width , height )
and so many , you can do this by handling event like RowCreated and implementing event handler for it OnRowCreated.

<asp:GridView ID="ctlGridView" runat="server" OnRowCreated="OnRowCreated" />

And in your code behind you can add

protected void OnRowCreated(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
string Comments = (String)DataBinder.Eval(e.Row.DataItem, "Comment");
if (Comments != null)
if (Comments.Length > 30)
Comments = Comments.Substring(0, 40) + "...";
e.Row.ForeColor =;


in that on "Comment" filed , i just simply minimize the string uptp 40 character and make it as a "RED" color.
like that you can add more feature as u want.

How To Access Content From MasterPage in ASP.NET

hi , some time we required some content from master page.
lets say we have created menu bar in Master page and i want to use that menu bar in some page
consider(Details.aspx) and my master page is ("MasterPanel.master) , now how to access master page content
to display the Menu.


<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPanel.master.cs" Inherits="MasterPanel" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head id="Head1" runat="server">
<title>: Master Demo: </title>
<form id="form1" runat="server">
<table border="0" style="width: 100%">
<td style="width: 100%">
<li>Open </li>
<li>Save </li>


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Details.aspx.cs"
Inherits="Details" <b><font color=red>MasterPageFile="~/MasterPanel.master"</font></b> %>
<asp:Content ID="Det" runat="Server" ContentPlaceHolderID="ContentPlaceHolder1">

//Menu source will come


in Details.aspx we have add MasterPageFile as "~/MasterPanel.master" so it will inclue all the
content from master page . by using <asp:Content> you can place that menu where you want in
Details.aspx page

That's it

Happy coding ......

Monday, July 6, 2009

How to Access Outlook Emails with ASP.NET ,C#

on my first post, i have covered how to add Refrences
on you'r .net application
now we require same thing to Send / Receive Mail via outlook using ASP.NET.
To acquire these, all you need is Interop.Outlook.dll.

Stpes :
1. Create one Project as "OutlookSendReceive" .
2. include "Bin" folder on same , right click on it , select Add refrence
then click tab "COM " and select " Microsoft Outlook 11.0 " click ok

3. it will add assemblies on you'r web.config page

<add assembly="Microsoft.Office.Interop.Outlook, Version=, Culture=neutral, PublicKeyToken=71e9bce111e29c34"/>

4. Define
"using Microsoft.Office.Interop.Outlook;
using System.Text;"

5. copy that code on Page_load() event

Microsoft.Office.Interop.Outlook.Application nOutlook;
Microsoft.Office.Interop.Outlook.NameSpace oNs;
Microsoft.Office.Interop.Outlook.MAPIFolder oFldr;

nOutlook = new Microsoft.Office.Interop.Outlook.Application();
oNs = nOutlook.GetNamespace("MAPI");

//getting mail folder from inbox
oFldr = oNs.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
Response.Write("Total Mail in Inbox :" + oFldr.Items.Count + "
Response.Write("Total Unread items = " + oFldr.UnReadItemCount);
foreach (Microsoft.Office.Interop.Outlook.MailItem oMessage in oFldr.Items)
StringBuilder str = new StringBuilder();
str.Append("<table><tr><td><b>Sender :</b></td><td>");
str.Append(oMessage.SenderEmailAddress.ToString() + "</td></tr>");

//Define Additional Information of Message
str.Append("<tr><td><b>Date :</b></td><td>" + oMessage.SentOn.ToShortDateString() + "</td></tr>");
if (oMessage.Subject != null)
str.Append("<tr><td><b>Subject :</b></td><td>" + oMessage.Subject.ToString() + "</td></tr>");


catch (System.Exception ex)
Response.Write("Execption generated:" + ex.Message);
oFldr = null;
oNs = null;
nOutlook = null;

like this way you can access Outlooks mail ,
thank you,
will come up more on how to access gmail /yahoo mail directly