21 December 2008

Failed to access IIS metabase problem

Usually this problem occurs when IIS is installed after installing .NET.

Solution 1:
Uninstall .NET framework and reinstall it. I followed this procedure.

Solution 2:
Copy and paste this into the Run Command from the Start Menu.
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i

Second solution has been suggested here, but I myself did not test it.

17 December 2008

Set 'float' property of DOM element

Usual syntax of setting any style property of DOM element is

element.style.styleName = value;

For example,

var oDiv = document.createElement('div');
oDiv.style.width = "100px";
oDiv.style.height= "100px";

But as 'float' is a reserved keyword, we CAN'T follow the same convention.

oDiv.style.float = "right"; // wrong

Unfortunately, all browsers don't handle this exception in same way (disgusting!!). So, we have to set two properties like below

oDiv.style.cssFloat = "right"; // for standards compliant browsers
oDiv.style.styleFloat = "right"; // for IE and may be for some other browsers

for more about style you can follow this link.

18 November 2008

Floating Point Precision in JavaScript

There is an unusual-named function in JavaScript for floating point precision - toFixed. I am really surprised at this naming.

Function singnature:
string toFixed (noOfdigit)

Example:

var n = 3.7345;
var n1 = n.toFixed(2); // n1 = 3.73
var n2 = n.toFixed(3); // n2 = 3.735


Note: toFixed function return a string, NOT a number. So, to get a number, you have to use parseFloat function. For example,

var
n1 = parseFloat( n.toFixed(2) ) ;

08 November 2008

Static Method & Attribute in JavaScript Class

Static methods in a class can be (and is) accessed without creating any object of that class. The static methods is called like Class.staticMethod() style.

As expected, JavaScript does not have any keyword like 'static'. But fortunately, this purpose can be served. Normal methods are defined inside class or using prototype. Static methods have to be defined outside the class and without prototype property.

Here a class TemperatureConverter has 2 static methods celsiusToFahrenheit (converts temperature in celcius to that in fahrenheit ) and fahrenheitToCelsius (opposite of previous function).


// define class
function TemperatureConverter()

{
}

//define static method
TemperatureConverter.celsiusToFahrenheit = function(celsius)
{
return (celsius * 9 / 5) + 32;
}

//define static method
TemperatureConverter.fahrenheitToCelsius = function(fahrenheit)
{
return (fahrenheit - 32) * 5 / 9;
}


Example:
var f = TemperatureConverter.celsiusToFahrenheit(35);
alert("35 degree celcius = " + f +" degree fahrenheit.");

var c = TemperatureConverter.fahrenheitToCelsius(98.4);
alert("98.4 degree fahrenheit = "+ c + " degree celcius.");


Static attributes can be added in similar fashion.
TemperatureConverter.description = "A class that converts temperature between celcius and fahrenheit";

Detect Browser Window Size from JavaScript

Web programmers often require to know the browser window size. But as different browsers have different properties for this purpose, programmers get annoyed. Following code is for such programmers to make their lives easy.


function getBrowserWindowSize()
{
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' )
{
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
}
else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
{
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
}
else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
{
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}

return {width:myWidth, height:myHeight};
}


Example:
var browserWindowSize = getBrowserWindowSize();
alert("width: "+
browserWindowSize.width + " height: " + browserWindowSize.height);

07 November 2008

Interface in JavaScript

Interface contains the method signature only. No method is implemented here, all are abstract. The class(es) must implement the methods to work properly.

In JavaScript, interface concept is absent. But for the sake of well-design of project, we should follow the concept in some way.

Concept behind Interface Implementation:

  • Interface will be a super class.
  • A class will extend Interface.
  • Then the class will override the methods in Interface.
  • If by error, the methods are not overridden, then the method of Interface will be called from where an Exception is thrown. So, to stay away from exception, developer must override the methods. In this way, Interface comes in action.
Here we will develop an Interface UI. There are 2 methods in UI - draw(width,height) and remove(). A classe Button will implement UI.


function UI()
{

this.draw = function(width, height)

{
throw "You must implement draw function";

}

this.remove = function()

{
throw "You must implement remove function";

}

}



Button.prototype = new UI;
function Button(text)
{

this._text = text;

this.button = null;

this.draw = function(width, height)
{
this.button = document.createElement("input");
this.button.setAttribute("type","button");
this.button.setAttribute("value",this._text);
this.button.style.width = width + "px";
this.button.style.height = height + "px";
document.body.appendChild(this.button);
}

this.remove = function()
{
if (this.button != null)
{
document.body.removeChild(this.button);
this.button = null;
}
}


}

OOP in JavaScript : Inheritance

There is no direct keyword (like 'extends' in Java) in JavaScript for inheritance. But its purpose can be served through 'prototype' attribute. Here, firstly an sample code is shown and then related points are described.

Sample Code of Inheritance:


function SuperClass(name)
{
this._name = name;

this.getName = function()
{

return this._name;

}
}


// inheritance occurs here

SubClass.prototype = new SuperClass;
function SubClass(name, address)
{

// calling constructor of super class

SuperClass.call(this,name);

//new attributes

this._address = address;

this.getAddress = function()

{
return this._address;

}
}




Object Creation & Usage:
Please observe the following code.

var sub = new SubClass("Alor Chhota","Mohammadpur");

alert("Name: " + sub.getName());
alert("Address: " + sub.getAddress());



Extending Super Class in Sub Class:
The following command asks to extend SuperClass in SubClass.
SubClass.prototype = new SuperClass;

Passing Parameters to SuperClass Constructor:
If you see the above code, you'll find the following line -
SuperClass.call(this,name);

This is actually the call of SuperClass constructor. Look closely at the sent parameters. The first parameter must be 'this' (SubClass) and the parameters of SuperClass will follow it. More descriptively, 2nd paramter of 'call' function is actually the 1st parameter of SuperClass, 3rd of call is 2nd of SuperClass etc.

OOP in JavaScript : Class

The OOP (Object Oriented Programming) concept is really poor in JavaScript. Fortunately, it supports class concept, although the keyword 'class' is not used. 'function' keyword serves the purpose of 'class'. There are several ways to implement class. Here I'm showing the simplest one (in my opinion).

Creating Class:
The following code creates a Person class with 4 attributes[ name, father, mother & address] and 2 methods [getName() & setAddress(address)].


function Person(name, father, mother, address)
{
this._name = name;
this._father = father;
this._mother = mother;
this._address = address;

this.getName = function()
{
return this._name;
}

this.setAddress = function(address)
{
this._address = address;
}

}

Note:
  • The attributes are created and accessed through 'this' keyword.
  • Person function is the constructor of the class which takes 4 parameters.
  • The constructor (or function) can't be overloaded like C++ or Java.

Creating Instance (Object):
It's simple enough to understand from the following code.

var p1 = new Person("Ahona Saha", "Anup Kumar", "Snigdha Saha", "Bogra");
var p2 = new Person("Ananyo Mounota", "Asim Kumar Saha", "Aparna Saha", "Narsingdi");



Accessing Attributes and Calling Methods:
The attributes can be accessed like below-
alert(p1._name);

Method calling is similar.
alert(p2.getName());

You can also change the attribute value.
p1._address = "Sariakandi, Bogra";

Note:
  • There is no Encapsulation in JavaScript i.e. any attributes is accessible from anywhere.
  • Interesting (and sometime disgusting) thing is, you can add attributes to an object anytime from anywhere (not necessarily from class). For example- if you want to add another attribute '_gender' with object p1, you can do it like below
    p1._gender = "female";

Add Icon in Website

The icon of a website represents it's identity. Users easily identify/detect website through the icon. A sample is shown below

You can add your icon in your wesite like below:


<head>
<link rel="SHORTCUT ICON" href="http://localhost:8080/images/badhan.ico">
<title>Badhan, A Voluntary Blood Donors' Organization</title>
</head>

18 October 2008

Url related tasks in JavaScript

It’s very common to pass some inputs to a web page through (parameter,value) pair in the url. A sample url might be like the following-

http://www.mywebpage.com?username=Alor%20Chhota&country=Bangladesh

If you look closely to the url, you’ll find the following facts

§ (Parameter, value) pair appears like ParamName=ParamValue style.

§ First parameter is preceeded by ‘?’ and later parameters are preceeded by ‘&’. Note: first parameter may also be preceeded by ‘#’. It restricts the page from loading again even after changing the url.

§ The value of the parameter username is “Alor%20Chhota”, although actually it is “Alor Chhota”. Here the space character has been replaced by “%20”. In fact, space and some other characters are not shown in actual form, rather they appear in encoded form. So to get the actual value, we must decode those values.

Here in this blog, the JavaScript implementaion of the following two classes has been given.

§ UrlEncoderDecoder : Responsible for encoding & decoding of url

§ UrlManager : Responsible for finding a parameter value from a url. It uses the above class.

Using these classes, the parameter value can easily be extracted.


Class : UrlEncoderDecoder

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

function UrlEncoderDecoder()
{
// public method for url encoding
this.encode = function (string)
{
return escape(this._utf8_encode(string));
}

// public method for url decoding
this.decode = function (string)
{
return this._utf8_decode(unescape(string));
}

// private method for UTF-8 encoding
this._utf8_encode = function (string)
{
string = string.replace(/\r\n/g,"\n");
var utftext = "";

for (var n = 0; n < string.length; n++)
{

var c = string.charCodeAt(n);

if (c < 128)
{
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048))
{
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else
{
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}

// private method for UTF-8 decoding
this._utf8_decode = function (utftext)
{
var string = "";
var i = 0;
var c = c1 = c2 = 0;

while ( i < utftext.length )
{
c = utftext.charCodeAt(i);
if (c < 128)
{
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224))
{
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else
{
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}


Class : UrlManager
==============
function UrlManager()
{
this.urlEncoderDecoder = new UrlEncoderDecoder();
this.getParamValueFromUrl = function (Url, ParamName)
{
var regexS = "[\\?&#]"+ParamName+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( Url );
if( results == null )
return "";
else
return this.urlEncoderDecoder.decode(results[1]);
}
};

Sample Code:
============
var myUrlManager = new UrlManager();
var url = window.location.href; // current url
var userName = myUrlManager.getParamValueFromUrl(url, "username");
var country = myUrlManager.getParamValueFromUrl(url, "country");


10 October 2008

Printing Using C#

I'm impressed about a tutorial on Printing Using C#. This is a nice tutorial consisting 7 pages. It not only describes the printing commands in C#, but also shows an easy-to-use framework of printing. I have followed the instructions stated there and built the project which can be downloaded from here.

22 September 2008

Send Spam-free Email using ASP.NET

Sorry, the previous blog contains a class which has been deprecated. Please use the namespace System.Net.Mail instead of System.Web.Mail;

Moreover, mails sent in previous way were being marked as spam in GMail. Use a real mail server to reduce the probability of being spam. Here Google mail server has been used along with GMail account and password.

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";

MailMessage mail = new MailMessage("from@mail.com", "to@mail.com", "Subject", "Body");
smtp.Credentials = new System.Net.NetworkCredential("user@gmail.com", "password");
smtp.EnableSsl = true;
smtp.Send(mail);

Note:

  1. ‘from’ address will not work, rather "user@gmail.com" will be the sender.
  2. It is not assured that mail will not be marked as spam.

Send Email using ASP.NET

In ASP.NET (using C#), it is very easy to send email. You need to include the namespace 'System.Web.Mail'. The rest is as follows-

MailMessage mailMsg = new MailMessage();
mailMsg.To = "ToSomeone@mail.com";
mailMsg.From = "FromSomeone@mail.com";
mailMsg.Subject = "subject of mail";
mailMsg.Body = "body of mail";

SmtpMail.Send(mailMsg);

Attachment:
Sending attachment is also simple.

MailAttachment attachment = new MailAttachment("FilePath");
mailMsg.Attachments.Add(attachment);


Note: The FilePath is the path in Server, not in client. So if you want to send attachment, first save the file in server temporarily, send mail and then delete the temporary file.

21 September 2008

How to upload file using ASP.NET in C#

UploadFile.aspx:

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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Pagetitle>
head>

<body>
<form id="form1" runat="server">
<div>
<input id="FileChooser" type="file" runat="server" />
<asp:Button ID="ButtonUpload" runat="server" Text="Upload" OnClick="ButtonUpload_Click" /><br />
<br />
<asp:Label ID="LabelStatus" runat="server" Width="36px">asp:Label>div>
form>
body>
html>

UploadFile.aspx.cs:

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

public partial class UploadFile : System.Web.UI.Page
{
private string uploadDirectory = @"D:\Testing projects\FileUpload\UploadedFiles";

protected void ButtonUpload_Click(object sender, EventArgs e)
{
if (this.FileChooser.PostedFile.ContentLength == 0)
this.LabelStatus.Text = "Can\'t upload zero length file.";
else
{
string fileName = this.getFileNameFromPath(this.FileChooser.PostedFile.FileName);
this.FileChooser.PostedFile.SaveAs(this.uploadDirectory + "\\"+ fileName);
this.LabelStatus.Text = "Uploaded to " + this.uploadDirectory;
}
}

private string getFileNameFromPath(string path)
{
int i = path.LastIndexOf('\\');
if (i == path.Length-1)
return null;
if (i < 0)
return path;
return path.Substring(i + 1);
}
}


14 September 2008

HTTrack : Website Copier

Wanna download all pages inside a website? Wanna download tutorial like sites where there are lots of pages inside a directory? Then you can use HTTrack. I found it extremely useful.

LateX: Download Link for Style files (*.sty)

While I was working on other's LateX file (*.tex), I found that some style files (*.sty) are missing. Then after googling, I found a useful link for downloading style files.

for example, if you look for fancyhdr.sty type the following url in browser.

http://www-hep2.fzu.cz/tex/texmf-dist/tex/latex/fancyhdr/

Note: Look at the url, the name of the style file stays at the end.

28 July 2008

Find Mouse Coordinate (position) in JavaScript

function MouseCoords(ev)
{
ev = ev || window.event; // remove browser dependency
if(ev.pageX || ev.pageY)
return {x:ev.pageX, y:ev.pageY};
else if (ev.clientX || ev.clientY)
{
var posx = ev.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
var posy = ev.clientY + document.body.scrollTop + document.documentElement.scrollTop;
return { x:posx , y:posy };
}
return { x:-1 , y:-1 }; // invalid/unknown mouse event
}


Note: This function does not work for mouse scrolling in Mozilla FireFox 2.0 or previous versions.

Detect Right Button Click in JavaScript

function IsRightButtonClicked(e) // e : mouse event
{
var rightclick = false;
e = e || window.event;
if (e.which)
rightclick = (e.which == 3);
else if (e.button)
rightclick = (e.button == 2);
return rightclick;
}

Disable Default Right Click Menu of Browsers

Observe the attribute oncontextmenu="return false;". It causes the default right click popup menu to be disabled. It can be used on body tag too.

<html>
<
head>
<
title>Disable Default Right Click Menutitle>
head>
<
body>
Right click on the following images to observe the effect.<br />
<img src="http://lh5.ggpht.com/alorChhota/R8qXNVDlYMI/AAAAAAAAATA/YS_ab1pnwII/s144/SDSL%20Picnic007.jpg" oncontextmenu="return false;" />
<img src="http://lh5.ggpht.com/alorChhota/R8qXNVDlYMI/AAAAAAAAATA/YS_ab1pnwII/s144/SDSL%20Picnic007.jpg" />
div>
form>

body>

html>

Note: In Opera, default right click popup menu can’t be disabled.

Validation from JavaScript before Form Submit

Look at the attribute of form tag onsubmit="return validate();".

<html>
<
head>
<
title>Validate before submittitle>
<script language=javascript>
function validate()
{
var v = document.getElementById("SearchString").value;
if(v.length == 0)
{
alert("No input given");
return false;
}
return true;
}

script>
head>

<body>

<form name="myform" action="http://www.google.com/search" method="GET" onsubmit="return validate();">

Search String: <input type="text" id="SearchString" size="25" value="" name="q">
<br> <input type="submit" value="Search in Google"><br>
div>
form>
body>
html>

24 July 2008

Browser Detection in JavaScript

The greatest challenge in web programming, in my opinion, is to make your website compatible to all browsers. [I say - A new browser or even a new version of an old browser is a new pain to programmer.]. Whatever, browser detection is a very important task for web programmer. Following is the JavaScript code to detect browser and OS.

var BrowserDetect = {

init: function ()

{

this.browser = this.searchString(this.dataBrowser) || "An unknown browser";

this.version = this.searchVersion(navigator.userAgent)

|| this.searchVersion(navigator.appVersion)

|| "an unknown version";

this.OS = this.searchString(this.dataOS) || "an unknown OS";

},

searchString: function (data)

{

for (var i=0;i {

var dataString = data[i].string;

var dataProp = data[i].prop;

this.versionSearchString = data[i].versionSearch || data[i].identity;

if (dataString) {

if (dataString.indexOf(data[i].subString) != -1)

return data[i].identity;

}

else if (dataProp)

return data[i].identity;

}

},

searchVersion: function (dataString)

{

var index = dataString.indexOf(this.versionSearchString);

if (index == -1) return;

return parseFloat(dataString.substring(index+this.versionSearchString.length+1));

},

dataBrowser: [

{ string: navigator.userAgent,

subString: "OmniWeb",

versionSearch: "OmniWeb/",

identity: "OmniWeb"

},

{

string: navigator.vendor,

subString: "Apple",

identity: "Safari"

},

{

prop: window.opera,

identity: "Opera"

},

{

string: navigator.vendor,

subString: "iCab",

identity: "iCab"

},

{

string: navigator.vendor,

subString: "KDE",

identity: "Konqueror"

},

{

string: navigator.userAgent,

subString: "Firefox",

identity: "Firefox"

},

{

string: navigator.vendor,

subString: "Camino",

identity: "Camino"

},

{ // for newer Netscapes (6+)

string: navigator.userAgent,

subString: "Netscape",

identity: "Netscape"

},

{

string: navigator.userAgent,

subString: "MSIE",

identity: "Explorer",

versionSearch: "MSIE"

},

{

string: navigator.userAgent,

subString: "Gecko",

identity: "Mozilla",

versionSearch: "rv"

},

{ // for older Netscapes (4-)

string: navigator.userAgent,

subString: "Mozilla",

identity: "Netscape",

versionSearch: "Mozilla"

}

],

dataOS : [

{

string: navigator.platform,

subString: "Win",

identity: "Windows"

},

{

string: navigator.platform,

subString: "Mac",

identity: "Mac"

},

{

string: navigator.platform,

subString: "Linux",

identity: "Linux"

}

]

};

BrowserDetect.init();

Now BrowserDetect.browser, BrowserDetect.version & BrowserDetect.OS will contain the browser name, browser version and OS name respectively.

 

© 2007 t!ps n tr!cks: 2008



Template unik dari rohman


---[[ Skip to top ]]---