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.

26 November 2008

Skills needed to survive the IT Slowdown!!

You may ignore it, but have to accept the fact that global recession has also it the IT industry. It may even happen that before you open your eyes and smell the Coffee..your PINK SLIP might be ready in your Bosse's office. But hey! don't panic cause everyone knows that a highly Skilled person can never be out of work for a long time! So here are a few skills sets, which if you posses will definitely see you through this bad time!

1.Know your Framework
BE it ASP or PHP knowing the framework thoroughly will definitely put you ahead in the race. All ASP.NET developers might have already come to know that no matter how much you "think" you know ASP.NET there's already something new yet to be discovered and before you figure it out, Microsoft might have already updated the technology.

And as for PHP developers knowing a framework has become quite important. With the meteoric rise to fame of Rails, Django, and other MVC frameworks, developers have learned that they can build websites much faster with the help of these tools. Frameworks help you cut out much of the repetitive tasks that normal custom programming would require. Having knowledge of the top frameworks (Rails, Django, CakePHP, Symfony, and a few others), can give you a whole other dimension to your skill set.

2.Custom CMS themes
Designers and developers can always find work creating or customizing a CMS theme. As the popularity of CMS like Wordpress and Drupal have risen over the past years, so has the demand for creating themes for the software.

Many people use CMS to power their personal or business websites, so this work is always going to be around. A decent website needs a unique and usable design that reflects well on the brand behind it.

3.CMS Customizations and plugin development

CMS are great because it gives site owners with little technical know-how the ability to change aspects of their site on the fly with the help of modules. While most CMS platforms have a long list of modules to offer, many businesses and personal sites need more, and custom modules or plugins are the perfect solution.

Developers can have thriving businesses in CMS development and customization alone. Here are a few (and by no means all) of the top CMS platforms that could use plugin development and other customizations:

* ExpressionEngine
* Wordpress
* Drupal
* MovableType
* Joomla

4.PSD to XHTML services.
Another one of the more popular skills needed is converting Photoshop files (PSD) to XHTML files for template use. Because designers don't always know how to convert Photoshop layouts into template files, a CSS and XHTML ninja can always find work.
Because of the array of browsers now in common use and the niggling differences in how they render sites, you want to be a web developer who can build-out sites that display the same in any browser. This kind of design to code service is the most sought after of them all.

5.Javascript Plugin creation

Much like the rise of CMS and MVC frameworks, Javascript frameworks are just as popular. These Javascript frameworks are built with the ability to add custom functionality in the form of modules. If you're a developer who knows how to build custom Javascript modules for frameworks like jQuery or Dojo, you'll have plenty of work available. Here are some of the most
popular Javascript frameworks you might need to get a handle on.

* jQuery
* Scriptaculous
* Dojo
* MooTools

6.Facebook/MySpace applications-API Development
Facebook and MySpace have both opened up their platform to allow developers API access, and the demand for social network apps has been huge since then. A whole new industry for web development sprang up overnight, and hundreds of applications are now added on a daily basis. The social media application platform has been found to be very viral and potentially very lucrative.

Some of these applications are built to make money or drive brand awareness, but ultimately the applications can be very successful and viral if they're done properly. A solid developer can make a decent living creating Facebook and MySpace applications.
Social networks like Facebook require that you learn their own language of syntax, like the FBML (Facebook Markup Language), so there is a small learning curve to this skill.

7.iPhone & Mobile Applications development
Yet another platform-specific skill set, building Mobile applications can be very profitable, and much like the social media applications, a great skill for any developer to know. Making an iPhone app that is accepted into Apple's platform has an excellent chance at making great money or receiving tons of downloads.

This is a great thing for web developers because companies are starting to see the value in developing iPhone and other mobile technologies, and consequently will be wanting more and more applications developed in the future.

8.Ecommerce integration
Business web sites are always going to need ecommerce integration. Essentially, if you can take a language or framework (PHP or Rails) and fuse it with a payment gateway (like Paypal or Authorize.net), you'll do well for yourself. I'm predicting that we're going to see more paid services than free, ad-supported services being developed in the near future, as less money is
being doled out to startups.

As the economy turns sour and the ad industry starts to get a little tighter, websites that use a subscription-based revenue model will start to become more common. Having the knowledge to piece together integration with online banking services like Paypal and Google Checkout will be great skills to have.

9.Flash and Actionscript Knowledge

Flash animation can do a lot for a website. Flash can be used to create videos, interesting navigation, fun animated sequences, widgets, and many other useful things on the Internet. The flash technology can add a very professional dimension to any website, and large websites and corporations always pay to have their sites look professional, and often commission Flash animated interfaces to showcase their products. With search engines working on ways to have Flash communicated better with them, this is a skill that's sure to boom as the search technology advances.

10.Widget development - Google Gadgets

Widgets have changed how web development has been done in the past couple of years. With the advent of widgets, data has become more portable, interactive and most importantly, viral. It's in almost every web startup's business plan to include a widget or two at some point, mainly because it helps increase their audience and puts more eyeballs on their content.

Widget development requires knowing Javascript and/or flash, not to mention knowledge of the regular language that the parent site is built in.


As a Conclusion i would like to leave a message on behalf of everyone:
"I tried so hard and got so far but In The End it doesn't even matter!!!!!"

25 November 2008

Five JavaScript Best Practices

JavaScript is an extremely powerful and flexible scripting language. Unfortunately flexible, for many people, means fallible. I am going to highlight 5 best practices that you can use in any JavaScript project.

>>.First and foremost, keep your code simple, clean and well documented. This is by no means unique to JavaScript but many people seem to think it is the exception to the rule. Your code should naturally comment itself but it is also important to at least introduce every function. I recommend two versions, a fully documented and formatted version and then a compressed version that you use in production. There are a number of free online utilities that can strip out comments and pack your script. There is no need to push out the extra size required for the documentation and formatting.

>>.Second, keep your JavaScript in an external file. The only exception to this rule is if you have some very lightweight script specific to a single page or are setting up variables that cannot be done in the external JS. An external file results in greater scalability, maintainability and degradability. The correct way to reference an external JS file is as follows:

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

>>.Third, separate your JavaScript from the presentation layer. We have all heard of unobtrusive JavaScript but we still see inline script all the time. Instead of cluttering your font-end code with dozens of event handlers add them dynamically. There are exceptions to this rule so please use common sense and separate the layers when it makes sense. An example of adding an onclick event handler from JavaScript:

var div = document.getElementById('div');
div.onclick = new Function("processClick(this)");

>>.Fourth, properly define and scope variables. Many of the scripts I download hoping to use in a project I immediately throw out. The reason being that the programmer did not take the time to properly define and scope variables. Always reference the first instance of a variable by using var. Otherwise the only way someone can know if that is the first reference to that variable is by starting at the top and reading all the way down. It is also important to scope variables correctly. Don’t scope a variable on the global level unless you need it there. I also recommend differentiation of global and local variables though some kind of visual identifier such is all caps on global variables or some easily identifiable character.

>>.Fifth, don’t assume JavaScript support in the first place. Depending on your audience you may choose to disregard this suggestion but for mainstream websites I highly suggest coding with the minority in mind (an estimated 5-10% of web users do not have JavaScript enabled) and degrade your scripts gracefully. JavaScript should be considered as an added feature and not a dependency. An examples of this would be links, the most fundamental element of a web page.

<a href="javascript:processClick()">link</a>
<a href="#" onclick="javascript:processClick()">link</a>


If the user clicks the either of the links above with JavaScript disabled nothing will happen. However, with the code below they could still navigate.

<a href="link.html" onclick="processClick(); return false;">link</a>

24 November 2008

jQuery

jQuery is a lightweight open source java-script library (only 15kb in size) that in a relatively short span of time has become one of the most popular libraries on the web.

A big part of the appeal of jQuery is that it allows you to elegantly (and efficiently) find and manipulate HTML elements with minimum lines of code. jQuery supports this via a nice "selector" API that allows developers to query for HTML elements, and then apply "commands" to them. One of the characteristics of jQuery commands is that they can be "chained"
together - so that the result of one command can feed into another. jQuery also includes a built-in set of animation APIs that can be used as commands. The combination allows you to do some really cool things with only a few keystrokes.

For example, the below java-script uses jQuery to find all <div> elements within a page that have a CSS class of "product", and then animate them to slowly disappear:

$("div.product").slideUp('slow').addClass("removed");


As another example, the java-script below uses jQuery to find a specific <table> on the page with an id of "datagrid1", then retrieves every other <tr> row within the datagrid, and sets those <tr> elements to have a CSS class of "even" - which could be used to alternate the background color of each row:


$("#datagrid1 tr:nth-child(even)").addClass("even");


[Note: both of these samples were adapted from code snippets in the excellent jQuery in Action book]

Providing the ability to perform selection and animation operations like above is something that a lot of developers have been begging for years. Such simplicity has never been offered before by any other development environment or library.

As a result even Microsoft has accepted this technology and they have already began shipping their Visual Studio 2008 package with jQuery preinstalled and with full support for it including intellisense. According to Scott Gu (Microsoft Developer, Blogger) - Microsoft is even working on adding new features and bug fixes to the jQuery Library.

22 November 2008

How to Set MaxLength of a Multiline TextBox

Ever tried setting up the maxlength property of a ASP.NET Multiline TextBox and ended up finding out that its doesn't work at all!! HEre's a simple solution using Javascript..
You can use the below script to set up the maxlength of a Multiline TextBox or even a HTML TextArea Tag:

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

function ismaxlength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
if (obj.getAttribute && obj.value.length>mlength)
obj.value=obj.value.substring(0,mlength)
}
</script>

Inside any textarea you wish to add a "maxlength" attribute to, simply do the following:

<textarea maxlength="40" onkeyup="return ismaxlength(this)" ></textarea>
or
<asp:TextBox ID="txt1" runat="server" maxlength="40" onkeyup="return ismaxlength(this)" />

The part in green is what you should add, with "40" obviously being the maximum number of characters accepted by this textarea.
Note: In ASP.NET setting up the maxlength might not work. Hence you should replace the textbox with a textarea and run it as a server control using runat="server"

21 November 2008

Hide/Show Div Elements Using JavaScript

JavaScript can be used to bring interactivity to you web pages by performing client side scripting. Using the style property of an HTML element, the element can be hidden or shown to the user based upon the required condition. For Example:

<script>
function setDiv(id)
{
if(document.getElementById(id).value==0)
{
document.getElementById('myDiv').style.display='none';
}
else
{

document.getElementById('myDiv').style.display='block';
}
}
</script>

This function can be called on any event of another HTML element as:

<select id="mySelect" name="mySelect" onchange="setDiv(this.id)">
<option>Select one</option>
<option value="0">Hide</option>
<option value="1">Show</option>
</select>

<div id="myDiv" name="myDiv" style="display:none;">
<span>Hi......!!!!!!! </span>
</div>

You can place any thing inside the myDiv element. Further more buy using some jQuery you can even add some animation effects.

18 November 2008

Using T-SQL to Simplify Coding

A sign of a good web developer is determined by his knowledge of SQL. Generally speaking if you know SQL well (be it SQL Server or MySQL) chances are that most of your coding will be reduced dramatically saving you lots of time and also increasing website performance.
Take for example if you wanted to change the status of a registered user from Active to De active or vice verse on the click of a single button and you are using a int field for it in the database( 0 and 1). Now as a novice what I used to do is run a SELECT query and get the user status field. Then compare the status in client side scripting language, and then again run a Update query to change the user status.
But as i studied more on SQL i found out that this could be done just by using a single query/stored procedure and only passing the id of the user to the query as follows(for SQL Server):

Create Procedure changeStatus
@ID integer
BEGIN
Declare @status integer
Select @status= status from UserTable where UserId=@ID
if @status=1
Update UserTable set status=0 where UserId=@ID
ELSE
Update UserTable set status=1 where UserId=@ID
END
END

So you see this has saved me a lot of time and coding. Also modification also becomes easy. Hence if you still think that SQL knowledge is not that important for Development; its time to wake up and brush up on YOUR SQL SKILLS!!!!!!

15 November 2008

What is Web 2.0?

Ever since i started with Web Development, I have been constantly coming across this WEB2.0 word..be it websites, blogs or online pop ups. I neglected it for a long time until finally decided to read about it.
Well here's a few things i found out about WEB 2.0
1. Its not a technology or Web Standard. It's just a way of how new Web Applications are developed.
2. Most of the Web 2.0 buzz has been related to Google Technology as its constantly making big progress towards making Web Applications more and more like desktop apps.
3.Web 2.0 is quite an old term and has been regularly re-phrased.
4. Use of technology such as AJAX, Silverlight, Flash etc.
They have some good stuff written about WEB 2.0 on Wikipedia. You might want to see for learning more.
So this WEB 2.0 term really doesn't mean much to us developers as long as we keep our imaginations flying and showing our creative work....May be as i write this blog post some extra minded people may even be talking about WEB 3.0, 4.0 ,5.0 ......

12 November 2008

Best Browser For Web Development




Which is the best browser for web development?
The Browser war may be at its highest intense level ever right now with Internet Explorer,
Mozilla Firefox, Opera, Safari haven released their latest versions promising a lot to the
customers and Google haven jumped into the arena with its latest Chrome browser with all new
neat javascript supporting technology.
But all these new web browsers have also put us web developers into a great jepoardy!!! As we have to make sure that our web site runs similarly in all of the above (at least these 3 browsers). Even the testers are having hard time looking at 3 to 5 different windows of the same page at the same time(Good luck to them too!!).

In this all chaos the one browser that i trust and use for my development purpose is Mozilla

Firefox (latest version). Some of its best features are:
1.Tabbed browsing....Now every one seems to have this one
2.Support for Addon Tools and Themes
3.Definately faster browsing speed than IE
4.Huge open source development team!!

Apart from this Firefox is also well responsive to CSS and Javascript. It also has very
powerful web development Adon tools which are worth mentioning here.
1.FireBug-For tracking CSS,Javascript & HTML
2.Web Developer Bar -Provides advanced features including error reporting of Javscript
3.Html Validator -W3C standard HTML validator

One may now think that i am trying to promote Mozilla here, but honestly i have tried IE, Firefox 3 & Chrome, and Firefox surpasses them all with a great margin (provided you install the addons).
Also i would like to mention that Google Chrome seems to be quite promising browser and will definately catch up within a year or so. One unique feature of chrome that i found is that
even if one tab in a window hangs/freezes for some reason you don't have to close the entire
window (I experimented this by putting a javascript into a endless loop)
I havent played with Safari or Opera yet (never needed to!!) but if you readers have
anything worth mentioning about them please feel free to post.
Right now MOZILLA FIREFOX IS THE BEST FOR ME!!

11 November 2008

Javascript function to open a popup

This is a very important and handy javascript to open a popup window, useful in showing small bits of information to user without taking them to different page.

<script> function popup(url) { newwindow=window.open(url,'popup_name','height=500,width=400,left=100,top=100 resizable=yes,scrollbars=yes,toolbar=yes,status=yes'); if(window.focus){newwindow.focus();} } </script>

This function can be called on any event like mouse click by passing the url of the page to be opened in a popup.
Please Note: Firefox does not allow the popup window to be non resizable, hence this feature can not be seen in Mozilla Firefox.

10 November 2008

FCKeditor Common Problem

FCKeditor Problem:
A Potential Dangerous Request Form value was detected from client("")

FCKeditorFCKeditor is great free Web-based HTML text editor to integrate into your website for HTML
editing. Be it ASP.NET or PHP it provides quite a host of features like
fileupload, stylesheets, image uploads etc.
But a very nagging problem that is associated with Fckeditor while using in ASP.NET is the above
titled error.
This error is mostly received when a page containing the Fckeditor server control is loading and
suddenly the user clicks on any other link/button on the page before the current page loads
completely.
Keep in mind that this is a ASP.NET security feature.
A very simple solution to this problem is to set the Page Directives ValidateRequest property to
false. This can be set in the first line of the aspx page as follows..

<%@ Page language="C#" CodeFile="index.aspx" Inherits="Index.aspx.cs" ValidateRequest="false" %>

Note: ValidateRequest is a ASP.NET security mechanism that protects a website from Cross Side Scripting attacks. Disabling this would leave your site vulnerable to such attacks! You can find more about this CSC by googling around.

07 November 2008

Multiple web applications

Disabling web.config Inheritance for Child Applications in Subfolders in ASP.NET 2.0!!
(making multiple web applications work together)


Each ASP.NET Web Application has its own configuration file called web.config file.
In fact every directory in ASP.NET application can have one. Settings in each web.config file apply to the pages in the directory where its placed, and all the subdirectories of that directory.

This is called Configuration Inheritance.

So if you create an ASP.NET application and set its web.config file, add custom HttpHandlers, UrlRewriting module etc and try to create another ASP.NET Web Application in the subfolder, you can end up having problems because application in the subfolder will inherit all the settings from its parent web.config.

So if you for example setup UrlRewriter module in your root web applications like this:

<httpModules>

<add name="UrlRewriteModule" type="UrlRewritingNet.Web.UrlRewriteModule, UrlRewritingNet.UrlRewriter"/>

<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</httpModules>

And in your child web application (in subfolder) you are not using UrlRewriteModule, then if you try to run the child Web Application in your browser, you will get error like this:
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: Could not load file or assembly 'UrlRewritingNet.UrlRewriter' or one of its dependencies. The system cannot find the file specified. (d:\Projects\VS\AspDotNetFaqProject\Website\web.config line 89)

Source Error:

Line 88: <httpModules>
Line 89: <add name="UrlRewriteModule" type="UrlRewritingNet.Web.UrlRewriteModule, UrlRewritingNet.UrlRewriter"/>
Line 90: <add name="ScriptModule" type="System.Web.Handlers.ScriptModule,

System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
Line 91: </httpModules>


What happens here is that because UrlRewriteModule is configured in the parent's folder web.config file, this setting is inherited by the child application's web.config file, and because of this ASP.NET is looking for the UrlRewriteModule DLL file in the BIN directory, and off course its not there.

Luckily, there is a easy solution to this problem.

First thing you can do is to remove the problematic HttpModule in your child application web.config file using the remove command like this:

<httpModules>

<remove name="UrlRewriteModule" />

</httpModules>

This would remove the handler and your application would run fine.
Or you could use <clear/> command like this:

<httpModules>

<clear/>

</httpModules>

This would clear all the HttpModules in your child application.

But what to do when there are many settings in your root web.config file that you don't want to be propagated to your child applications?

Here is the solution:
With the <location> attribute with inheritInChildApplications set to false in your root web.config file you can restrict configuration inheritance.
So, by wrapping a section of your web.config file in <location> attribute you can instruct ASP.NET not to inherit those settings to child applications/folders and their web.config files.

In fact you can wrap the whole <system.web> section in one <location> attribute and disable configuration inheritance so none of the parent settings from <system.web> will be inherited to the child applications you create in subfolders.

Here is how to use this in practice:

<location path="." inheritInChildApplications="false">

<system.web>
...

</system.web>
</location>

NOTE: Do remember that if you do this, you need to manually insert all the settings you need in the <system.web> for your child applications because none of the settings from the root web.config will be propagated...

01 November 2008

Enforcing SSL Security For WebPages

Many times we need to add SSL security to few of our web pages for secure transactions.
Now initailly when i wanted to do so i tried to hard code the link by using "https://mylink.com ". But if the user typed the link as "http://mylink.com" the page still opened in non secure mode.
To overcome this problem i found a simple function that automatically detects if the page is in secure mode or not and then force it to go into secure mode.

Here is the code for ASP.NET 2.0:

protected void ForceHTTPS()
{
if(!Request.IsSecureConnection)
{
string server_name=HttpUtility.UrlEncode(Request.ServerVariables["SERVER_NAME"]);
string forceurl="https://"+ server_name + Request.FilePath;
Response.Redirect(forceurl);
}
}


and for PHP 5:

function ForceHTTPS()
{
if($_SERVER['HTTPS']!="on")
{
$forceurl="http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
header("location:$forceurl");
exit;
}
}

These can be very handy when only a few web pages need SSL.
Note: Please make sure that the server has a valid SSL certificate( need to purchase) for https:// to work other wise you will get page not found error or certificate expired error.

30 October 2008

Importance of Javascript

If you are a fresh web developer and just finished learning your very first server side scripting language aka ASP.NET, then you probably must be thinking why in the world should i learn another client side language aka Javascript. I mean you probably can get most of the things done by using the all mighty "ASP.NET" technology, can't you?
Well its time to get a reality check!! No web developer these days can survive without knowing javascript...take my word for it!!
Even i used to think the same way but soon realized that its not possible to stay without js. Take for example you want to show a alert message or get a confirmation from the user on the client side. You might think that using MessageBox.Show() would do the trick but it fails on many occasion as its a windows class library function. Instead you have to write something like this. in the head section of your html document inside the scripts tab("script").

var ans= confirm("Are you sure you want to do this?")
if(ans==true)
----
else
----

Well this is a good example for very first starters and you might find many other stuff accross the internet.
My point remains that you cannot ignore javascripts and start learning it immediately. A good webiste to get started is www.w3schools.com.

12 October 2008

Starting Web Development

As a fresh web developer myself, i have been facing many new challenges and hurdles during my development career. This blog has been started to discuss about any minor or major difficulties that any web developer would come across.. I would be regularly posting any code or examples of my work/importance to share it with others.
Also would like my reader to post their problems may it be of any nature.
Currently i am following ASP.NET 2.0 and PHP5.