28 December 2008

GridView Custom Pager Template

This is a Custom GridView Pager Template with DropDownList for pagination , Next-Previous, First-Last navigation and TextBox with save button to control the Page Size.
I had searched many site for this functionality. Finally after referring a few good examples I came up with the following according to my need.


****************************HTML*****************************

<PagerTemplate>
<div id="pager" >
<asp:DropDownList ID="ddlPageSelector" runat="server" AutoPostBack="true">
</asp:DropDownList>
View
<asp:TextBox ID="txtPageSize"
runat="server" Width="25px" EnableViewState="true"></asp:TextBox>

results per page <asp:LinkButton ID="lnkSavePageSize" runat="server"
OnClick="lnkSavePageSize_click"><strong>Save</strong></asp:LinkButton>
|
<asp:Label ID="lblNumber" runat="server"></asp:Label> |

<asp:LinkButton Text="First" CommandName="Page" CommandArgument="First" runat="server" ID="btnFirst" />

<asp:LinkButton Text="Previous" CommandName="Page" CommandArgument="Prev" runat="server" ID="btnPrevious" /> -

<asp:LinkButton Text="Next" CommandName="Page" CommandArgument="Next" runat="server" ID="btnNext" />

<asp:LinkButton Text="Last" CommandName="Page" CommandArgument="Last" runat="server" ID="btnLast" />

</div>
</PagerTemplate>



******************************CODE BEHIND************************
//need to bind the following event with your gridview control

protected void myGridView_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{

SetPagerButtonStates(myGridView, e.Row, this);

}
}

//This is a custom function
public void SetPagerButtonStates(GridView gridView, GridViewRow gvPagerRow, Page page)
{


int pageIndex = gridView.PageIndex;
int pageCount = gridView.PageCount;

LinkButton btnFirst = (LinkButton)gvPagerRow.FindControl("btnFirst");
LinkButton btnPrevious = (LinkButton)gvPagerRow.FindControl("btnPrevious");
LinkButton btnNext = (LinkButton)gvPagerRow.FindControl("btnNext");
LinkButton btnLast = (LinkButton)gvPagerRow.FindControl("btnLast");
Label lblNumber = (Label)gvPagerRow.FindControl("lblNumber");
TextBox txtPageSize = (TextBox)gvPagerRow.FindControl("txtPageSize");
lblNumber.Text = "Pages " + Convert.ToString(pageIndex+1) + " of " + pageCount.ToString();

btnFirst.Enabled = btnPrevious.Enabled = (pageIndex != 0);
btnNext.Enabled = btnLast.Enabled = (pageIndex < (pageCount - 1));

if (btnNext.Enabled == false)
{
btnNext.Attributes.Remove("CssClass");
}
DropDownList ddlPageSelector =
(DropDownList)gvPagerRow.FindControl("ddlPageSelector");
ddlPageSelector.Items.Clear();

for (int i = 1; i <= gridView.PageCount; i++)
{

ddlPageSelector.Items.Add(i.ToString());

}

ddlPageSelector.SelectedIndex = pageIndex;
txtPageSize.Text = gridView.PageSize.ToString();

//Used delegates over here
ddlPageSelector.SelectedIndexChanged += delegate
{

gridView.PageIndex = ddlPageSelector.SelectedIndex;

gridView.DataBind();

};
}

protected void lnkSavePageSize_click(object sender, EventArgs e)
{
GridViewRow pagerRow = myGridView.BottomPagerRow;
TextBox temp1= (TextBox)pagerRow.FindControl("txtPageSize");
if(temp1.Text!="")
{
myGridView.PageSize = Convert.ToInt32(temp1.Text);
}


}

Link for Reference:Click Here

26 December 2008

Javascript RegExp Function

JavaScript provides a very useful function for client side user input validation. This function uses regular expressions for validation against the input.
If you are a PHP developer then you must have knowledge of this feature, whereas for ASP.NET 2.0 we already have the regular expression validator control which also uses similar regular expressions.
A simple example of the RegExp is as follows:

<script type="text/javascript" langusge="javascript">

function validate_phone(obj)
{

//for US phone number format: (xxx) xxx-xxxx

var RegExp=/\(\d{3}\)\ \d{3}-\d{4}/;

if(RegExp.test(obj.value))
{

return true;
}
else
{

obj.select();
obj.focus();
return false;
}
}

</script>

Note: Passing a correct regular expression is very important. You can find various regular expressions according to your need by Googling around. Also note that the regular expression must be inside the / / i.e var RegExp=/ /;

24 December 2008

Regular Expression for File Upload Validation

This is a Regular Expression for validating the file upload HTML/ASP.NET control on the client side using JavaScript!

" ^.+\.(([jJ][pP][eE]?[gG]) | ([gG][iI][fF]) | ([bB][mM][pP­]) | ([pP][nN][gG]) |([wW][mM][fF]))$ "

As you can see you can specify any file format between the | | fields which stand for OR.
You can use this function in ASP.NET 2.0 with the Regular Expression Validator or can use the JavaScript RegExp function for PHP.

Note: Its always a good idea to validate the user input on the server side!!

22 December 2008

Using Session variables in Javascript

One of the common problems Web Developers face is interaction between client side and server side scripts. With the advent of AJAX it has become very simple.
But there are situations were we need to change the JavaScript variables dynamically without changing the rest of the script. For example some flash elements require JavaScript variables for their functionality like keeping track of the tabs.
This can be achieved very easily through the use of session variable as follows:

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

function myFunction()
{
var var1=21;
var var2=<%=Convert.ToString(Session["myVariable"])%>
------
------
------

}

</script>

All you need to do is assign the session variable with the value you want on the page load in code behind.

I was quiet curious and also tried the vice verse i.e assigning a Session Variable in JavaScript. But it doesn't work !!!! Have to use alternate methods. If any one knows a way of doing so..Please Comment

21 December 2008

Working with HTML Div element

When i started my Web development career all i knew about HTML was table,td,tr,css and a few other tags. Most of the times i used ASP.NET components, without much tweaking. But soon i came across Web 2.0 techniques and realized the advantages of using Div elements + advance CSS handling. And so i began (again!) .......

To my initial horror i just couldn't get any thing in write place. Div' s overlapping each other, validation alerts flying all over the place, page changing structure after postback,.....just to name a few problems. But i had to focus, do my homework and start correctly. After reading some useful articles on the NET (You can find many!) and taking some expert tips from our lead designer, i finally started getting things write.

Now i was writing less HTML code as most things were configured through CSS. Just required to apply proper classes to the DIV's or give id's to them. You can follow any of the methods classes/id's but using same id's on same page is not W3C complaint. Also the most important thing that i realized about div's is that it's more cross browser compliant hence saves a lot of time configuring your web page for different browsers. Web pages look more cleaner than before.
So now i think that i have started off with WEB 2.0 (WEB 3.0 buzz already round the corner!!).
The learning path just got longer......................................................

11 December 2008

Rounded Corner Box Using Div and CSS

Ever since the advent of WEB 2.0, the way web pages have been designed has changed significantly. People these days go for more of a soft look to their pages with rounded corners every where. One of the best way of designing rounded corner box is by using div and CSS combination. Here is a sample code for the same...

<style type="text/css">

.round_box {
background: url(round_tl.png) no-repeat top left;
}
.round_top {
background: url(round_tr.png) no-repeat top right;
}
.round_bottom {
background: url(round_bl.png) no-repeat bottom left;
}
.round_bottom div {
background: url(round_br.png) no-repeat bottom right;
}
.round_content {
background: url(round_r.png) top right repeat-y;
}

.round_top div,.round_top,
.round_bottom div, .round_bottom {
width: 100%;
height: 15px;
font-size: 1px;
}
.round_content, .round_bottom {
margin-top: -19px;
}
.round_content { padding: 0 15px; }

</style>

<body>

<div class="round_box">
<div class="round_top"><div></div></div>
<div class="round_content">
<p>Your Content Here</p>
</div>
<div class="round_bottom"><div></div></div>
</div>

</body>

Note: You must have the correct image for cornering your pages!

I have found a great site that auto generates the HTML Code,CSS and corner images according to your choices for Absolutely FREE!! Check it out : RoundedCornr

10 December 2008

Using Div to generate Table Like Structure

"The Div tag defines a division or a section in an HTML document. The Div tag is often used to group block-elements to format them with styles"- offical defination by W3Schools.
If you are new to using div elements then the very first problem that you might face is generating the table,tr,td structure using only div's (since you were so hooked up on the old Table structure). But the fact is that using div's you can (and will) save lot of HTML coding (after learning few simple tricks), plus the div elements are also very very flexible.
Here's a basic code snippet to get you started with...

<style type="text/css">

.tablediv {
display: table;
border:1px solid #666666;
border-spacing:5px;/*cellspacing:poor IE support for this*/
border-collapse:separate;
}

.rowdiv {
display: table-row;
width:auto;
}

.celldiv {
float:left; /*fix for IE since display:inline doesn't work */
display: table-cell;

}

</style>

/* Style can be used in HTML as follows:*/

<body>

<div class="tablediv" style="width:500px;">
<div class="rowdiv" style="width:100%;">
<div class="celldiv" style="width="50%;"> one cell/td in a table</div>
<div class="celldiv" style="width="50%;"> one cell/td in a table</div>
</div>
</div>

</body>

08 December 2008

Calculate Latitude-Longitude using Google API

Google API provide a nifty tool for calculations the latitude and longitude of the place based upon the address. These geographical data can be used for Google Map Generation. Make sure that you read the Google Maps API documents before starting.

//code for using google maps to calculate latitude and longitude dynamically

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

var geocoder;
var map;
var xmlHttp;

// this function has to be called when page loads..FOR IE facing Operation aborted problem call this function at end of page before </body> tag & make sure google map version is 2.118 or greater

function load()
{
map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(0,0), 8);//temporay center
geocoder = new GClientGeocoder();
}

//call this function after validations have been performed and true
function showAddress(address)
{
var flag_addr1=0;
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
if (geocoder)
{

geocoder.getLatLng(address, function(point)
{

if (!point)
{
alert("Address " +address+" not found");
flag_addr1 = 0;

}
else
{

//hidden fields on the webform , inside a form(postback values used for updating database)
document.getElementById("lat").value = point.lat().toFixed(5);
document.getElementById("lng").value = point.lng().toFixed(5);
flag_addr1 = 1;
//setTimeout("document.frm_add_place.submit()",2000);

document.frm_add_place.submit(); //used to submit form only when correct address is found

}
}
);
}

}
</script>

Note: You can call the showAddress() JavaScript function before a user submits a form and pass values entered by user like state,city,zip code, street address.
The values in the hidden fields lat,lng can be used to store in database for dynamic map generation.

07 December 2008

Generate Google Maps Dynamically

Generate Google Maps Dynamically using SQL database

Google Maps - have become an essential part of web development. Almost every client here and there is now requesting for some of the Google Map functionality to be incorporated into their web site. A common place for Google Maps is on the Contact US pages. Here's the detailed for all your need.

The following illustrate the use of Google Map API to dynamically generate the required points who's details are stored in the database and each points are selected using SQL Queries

// JavaScript Document
//Code for google maps to dynamically add various points, set their center and set auto zoom levels
//Also change the icons

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

var iconBlue = new GIcon();
iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconBlue.iconSize = new GSize(12, 20);
iconBlue.shadowSize = new GSize(22, 20);
iconBlue.iconAnchor = new GPoint(6, 20);
iconBlue.infoWindowAnchor = new GPoint(5, 1);


var iconRed = new GIcon(G_DEFAULT_ICON);
iconRed.shadow = 'http://www.google.com/mapfiles/shadow50.png';

iconRed.iconSize = new GSize(20, 34);
iconRed.shadowSize = new GSize(37, 34);
iconRed.iconAnchor = new GPoint(9, 34);
iconRed.infoWindowAnchor = new GPoint(9, 2);


// this function has to be called when page loads..FOR IE facing Operation aborted problem call this function at end of page before </body> tag & make sure google map version is 2.118 or greater.
function load()
{
if (GBrowserIsCompatible())
{

var queryparameters="";

var map = new GMap2(document.getElementById("mapsearch"));//name of maps div on page.must be unique
var bounds = new GLatLngBounds();
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());

map.setCenter(new GLatLng(0,0, 15); //temporaray center

GDownloadUrl("getCoordinates.php?"+queryparameters, function(data) {

var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++)
{
//sample XML file data retrieved from getCoordinates.php which fires a query and generates an XML file that is echoed back;

//below is all the data tto be shown in ballon on the map
var CenterName = markers[i].getAttribute("CenterName").replace("'", "′");
var Street = markers[i].getAttribute("Street").replace("'", "′");
var City = markers[i].getAttribute("City").replace("'", "′");
var State = markers[i].getAttribute("State").replace("'", "′");
var ZipCode = markers[i].getAttribute("ZipCode");
var Phone = markers[i].getAttribute("Phone");
var Website = markers[i].getAttribute("Website");
var point = new GLatLng(parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("langitude")));


var marker = createMarker(point,CenterName,Street,City,State,ZipCode,i);
map.addOverlay(marker);
bounds.extend(point);
//marker.setImage('../markerIcons/largeTDBlueIcons/blank.png'); can be used for single image
}

//these functions automatically set the zoom levels and map center
map.setZoom(map.getBoundsZoomLevel(bounds));
map.setCenter(bounds.getCenter());
});

}
}

function redirect(CenterName,Street,City,State,ZipCode,point)
{

window.open("http://maps.google.com/maps?near="+Street+","+City+","+State + " "+ ZipCode+"&geocode=CTmv3KDtfEkVFUq6QgIdO865-CHwxO4kUuJYPQ&q=" + document.getElementById('txtsearch').value +"&f=li&hl=en&dq=shopping+centers+loc:"+Street+"&sll="+point);

}

function createMarker(point,CenterName,Street,City,State,ZipCode,index)
{

//Select a marker icon dynamically palced on server
var letter = String.fromCharCode("A".charCodeAt(0) + index); //for lettered icons
var num=index+1; //for numbered icons
var letteredIcon = new GIcon(iconRed);
letteredIcon.image = "../markerIcons/largeTDBlueIcons/marker" + num + ".png"; //location of icon image

// Set up our GMarkerOptions object

markerOptions = { icon:letteredIcon };
var marker = new GMarker(point, markerOptions);

var to_str="http://maps.google.com/maps?li=d&hl=en&f=d&iwstate1=dir:to&daddr="+Street+","+City+","+State+" "+ZipCode+"&iwloc=1";
var from_str="http://maps.google.com/maps?li=d&hl=en&f=d&saddr="+Street+","+City+","+State+" "+ZipCode+"&iwstate1=dir:from&iwloc=1";

var html = "<b>" + CenterName + "</b><br/>" + Street + "<br/>" + City + "," + State + " " + ZipCode + "<br/><br/>Get Direction:<a href='"+to_str+"' target='_blank'>To Here </a> <a href='"+from_str+"' target='_blank'>From Here</a><br/> Search near:<input type='text' name='txtsearch' id='txtsearch' value='' /><input type='button' name='Search' id='Search' value='Search' onclick='redirect(\""+CenterName+"\",\""+Street+"\",\""+City+"\",\""+State+"\",\""+ZipCode+"\",\""+point+"\");'/>" ;

GEvent.addListener(marker, 'click', function(){
marker.openInfoWindowHtml(html);
});

return marker;
}

</script>

05 December 2008

Randomly Rotate Array Elements

Array shuffling can be at times quiet confusing especially if you want to do it randomly. But hears a simple code function in C# which uses the Array.Reverse function that will save the day :

protected void myFunction()
{
Array test = new Array('abc','asd','yyj','jsd','jrd','tyf','qwe','asd');
Random random = new Random();
int index1=random.Next(0, test.Length);

}

protected Array RotateArrayFromLeft(Array ArrayToBeRotated, int N)
{
int a_length = ArrayToBeRotated.Length;
if ((N >= 0) && (N <= a_length))
{
Array.Reverse(ArrayToBeRotated, 0, N);
Array.Reverse(ArrayToBeRotated, N, alength - N);
Array.Reverse(ArrayToBeRotated);
}
return ArrayToBeRotated;
}
Note: This function shuffles a array from its left position, you can modify it according to your
needs.

03 December 2008

Dynamic Meta Tags


Meta tags are HTML or XHTML elements used to provide structured meta data about a Web page. Meta tags can be used to specify page description, keywords and any other Meta Data not provided through the other head elements and attributes.
Meta tags prove to be an important source of information for search engine's and hence for your Web pages to be properly listed in search engine results proper Search Engine Optimization is necessary.
Meta tags can be added Dynamically in ASP.NET by using following code which uses the System.Web.UI.HtmlControls class:

HtmlMeta meta = new HtmlMeta();
meta.Name = "meta-name"; //eg keywords, description
meta.Content = "content";
Page.Header.Controls.Add(meta);

In PHP we will need to echo the values in the head section of the Web page as follows:

<head>
<meta name="<?php echo $name; ?>" content="<?php echo $content; ?>" />
</head>

For more information on Meta Elements you can check out Wikipedia.

01 December 2008

Dynamic Thumbnail Generation


Thumbnail creation is an very important process for websites incorporating image upload functionality.
User can upload any type of image to the server which needs to be re-sized according to our web page designs.
Following is the code required for the task in ASP.NET 2.0:



void create_thumb(String file_path,int pre_width,int pre_height)
{
System.Drawing.Image myImage;
System.Drawing.Image oThumbNail;
int newHeight, newWidth;

Graphics oGraphic;
Rectangle oRectangle;

myImage = System.Drawing.Image.FromFile(Server.MapPath("images") + "/" + file_path);

if (myImage.Height < pre_height && myImage.Width < pre_width)
{
newWidth = myImage.Width;
newHeight = myImage.Height;
}
else
{
if (myImage.Height > myImage.Width)
{
newHeight = pre_height;
newWidth = ((myImage.Width * pre_height) / myImage.Height);
}
else if (myImage.Height < myImage.Width)
{
newWidth = pre_width;
newHeight = ((myImage.Height * pre_width) / myImage.Width);
}
else
{
newWidth = pre_width;
newHeight = ((myImage.Height * pre_width) / myImage.Width);
}
}



if (myImage.PixelFormat == PixelFormat.Indexed)
oThumbNail = new Bitmap(newWidth, newHeight, myImage.PixelFormat);
else
oThumbNail = new Bitmap(newWidth, newHeight);
oGraphic = Graphics.FromImage(oThumbNail);
oGraphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
oGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
oGraphic.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
oRectangle = new Rectangle(0, 0, newWidth, newHeight);
oGraphic.DrawImage(myImage, oRectangle);
Response.ContentType = "image/Jpeg";
oThumbNail.Save(Server.MapPath("images/Thumbnails") + "/" + file_path,System.Drawing.Imaging.ImageFormat.Jpeg);

myImage.Dispose(); //needed to free the resources and file handles
}


Following is the code required for the task in PHP:

function create_thumb($file_path,$pre_width,$pre_height)
{
list($orig_width, $orig_height) = getimagesize($file_path);
$target_path="images/thumbnails/"

if ($orig_height < $pre_height && $orig_width < $pre_width)
{
$newWidth = $orig_width;
$newHeight = $orig_height;
}
else
{
if($orig_height > $orig_width)
{
$newHeight = $pre_height;
$newWidth = (($orig_width * $pre_height) / $orig_height);
}
else if ($orig_height < $orig_width)
{
$newWidth = $pre_width;
$newHeight = (($orig_height * $pre_width) / $orig_width);
}
else
{
$newWidth = $pre_width;
$newHeight = (($orig_height * $pre_width) / $orig_width);
}
}

$image_p = imagecreatetruecolor($newWidth, $newHeight);

if($file_ext=='gif' || $file_ext=='GIF')
$image = imagecreatefromgif($file_path);

if($file_ext=='png' || $file_ext=='PNG' )
$image = imagecreatefrompng($file_path);

if($file_ext=='jpeg' || $file_ext=='jpg')
$image = imagecreatefromjpeg($file_path);

imagecopyresampled($image_p, $image, 0, 0, 0, 0, $newWidth, $newHeight, $orig_width,$orig_height);

if($file_ext=='jpeg' || $file_ext=='jpg' || $file_ext=='JPG' )
imagejpeg($image_p, $target_path.$newname, 100);

if($file_ext=='gif' || $file_ext=='GIF')
imagegif($image_p, $target_path.$newname, 100);

if($file_ext=='png' || $file_ext=='PNG')
imagepng($image_p, $target_path.$newname);


}

Note: This function is designed to first save the image to a location on server and then
generated thumbnails and save in a separate folder. You can customize it according to your need.