Friday, October 31, 2008

Oracle function that returns table row details.

Oracle function that accepts table name,primary key field name,primary key field value as input parameters
CREATE OR REPLACE FUNCTION Getrowdetails
(
TableName VARCHAR,
primarykey VARCHAR,
primarykeyvalue VARCHAR
)
RETURN VARCHAR
AS
--To return details of a row in table with primary key field name and value mentioned
tempColname user_tab_cols.COLUMN_NAME%TYPE;
usercursor sys_refcursor;
tempVar VARCHAR2(20000);
tempValueString VARCHAR2(25000);
BEGIN
tempValueString:=tempValueString||'
';
--Iterating for each column in the specific table and getting details for specific row for
-- that column
OPEN usercursor FOR SELECT column_name FROM user_tab_cols WHERE UPPER(table_name)=UPPER(TableName) ORDER BY column_id;
LOOP
FETCH usercursor INTO tempColname;
EXIT WHEN usercursor%NOTFOUND;
EXECUTE IMMEDIATE 'select '||tempColname||' from '||TableName||' where '||primarykey||' = '''||primarykeyvalue||''''INTO tempVar;
IF(tempVar IS NOT NULL) THEN
tempValueString:=tempValueString||'
'||tempColname||' -- > '||tempVar||'
';
ELSE
tempValueString:=tempValueString||'
'||tempColname||' -- > NULL
';
END IF;
END LOOP;
--Retuning the details of the row
RETURN tempValueString;
END;
/

This function returns details concatenating with delimeter (New Line character),

Thursday, October 30, 2008

Oracle function to find whether a string has special characters?

This function expects a varchar input paramter for which it returns "0" if input string has special characters else returns 1.
CREATE OR REPLACE FUNCTION Containssplchrs(argValue IN VARCHAR)
RETURN NUMBER
AS
tempValue VARCHAR(1);
tempActValues VARCHAR(40);
tempRtrnValue NUMBER;
tempLength NUMBER;
BEGIN
tempActValues:=' ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
tempLength:=LENGTH(argValue);
IF(argValue IS NULL) THEN
RETURN 1;
END IF;
FOR I IN 1.. tempLength
LOOP
tempValue:=SUBSTR(UPPER(argValue),i,1);
tempRtrnValue:=INSTR(tempActValues,tempValue);
IF(tempRtrnValue=0) THEN
RETURN 0;
END IF;
END LOOP;
RETURN 1;
RETURN tempLength;
END;
/

Tuesday, October 28, 2008

Java script function to validate from and to dates?

fid indicates from date text box id and tid is to date text box id
function DateLsEq(fid,tid)
{
var msg="From date is greater than To date";
try
{
var fval=document.getElementById(fid).value;
var tval=document.getElementById(tid).value;
if(fval=='' && tval=='')
{
return true;
}
var fdts=null;
var tdts=null;
if(fval!='')
{
if(fval.indexOf(".")!=-1)
{
alert('--Not a valid Date(dd/mm/yyyy)');
document.getElementById(fid).focus();
return false;
}
fdts=fval.split("/");

}
if(tval!='')
{
if(tval.indexOf(".")!=-1)
{
alert('--Not a valid Date(dd/mm/yyyy)');
document.getElementById(tid).focus();
return false;
}
tdts=tval.split("/");
}
if(tdts!=null)
{
if(tdts[1].length==1)
{
alert('--Not a valid Date(dd/mm/yyyy)');
document.getElementById(tid).focus();
return false;
}
if(tdts[0].length==1)
{
alert('--Not a valid Date(dd/mm/yyyy)');
document.getElementById(tid).focus();
return false;
}
if(!isInteger(tdts[2]) || !isInteger(tdts[1])|| !isInteger(tdts[0]))
{
alert('--Not a valid Date(dd/mm/yyyy)');
document.getElementById(tid).focus();
return false;
}
if(!IsValidDate(tval))
{
document.getElementById(tid).focus();
return false;
}
}
if(fdts!=null)
{
if(fdts[1].length==1)
{
alert('--Not a valid Date(dd/mm/yyyy)');
document.getElementById(fid).focus();
return false;
}
if(fdts[0].length==1)
{
alert('--Not a valid Date(dd/mm/yyyy)');
document.getElementById(fid).focus();
return false;
}
if(!isInteger(fdts[2]) || !isInteger(fdts[1]) || !isInteger(fdts[0]))
{
alert('--Not a valid Date(dd/mm/yyyy)');
document.getElementById(fid).focus();
return false;
}
if(!IsValidDate(fval))
{
document.getElementById(fid).focus();
return false;
}
}
if(tdts!=null && fdts!=null)
{
if(tdts[2]<=fdts[2])
{
if(tdts[2]<fdts[2])
{
alert(msg);
document.getElementById(fid).focus();
return false;
}
if(tdts[1]<=fdts[1])
{
if(tdts[1]<fdts[1])
{
alert(msg);
document.getElementById(fid).focus();
return false;
}

if(tdts[0]<fdts[0])
{
alert(msg);
document.getElementById(fid).focus();
return false;
}

}
}
}
return true;
}
catch(e)
{
alert('--Not a valid Date(dd/mm/yyyy)');
return false;
}
}

Monday, October 27, 2008

How to import Data base Dump? - Oracle

When we set up oracle server , we should create a data base going to data base configuration tool provided by Oracle.
When a data base is created, go to command prompt and type "imp" or go to bin directory available inside oracle folder where we can find imp.exe and double click on it.
It prompts for user name and password. Where we have to provide user name of the schema that is created with the creation of data base.
Note: You can import a data base dump file into the data base shema through a user who has DBA privileges.

Once proper username/password@Databasename is provided, it prompts for the data base dump file path for which we can drag and drop the dump file available onto the prompt command window.
Once this is done, we should press enter , which continues importing data base dump file.
It also prompts for few options like to import entire dump file, to compress extents, etc...we can also observe it shows the charater set of the imported data base dump file ,destination data base character set, from user of the data base dump file etc...
Once the import is completed it automatically closes the window where user shall continue using the schema.

Saturday, October 25, 2008

How to show hyperlink on mouse over?

There can be instants in web sites where when user places mouse cursor over a component like label should then display a hyper link and on click of which should open a window.

For this kind of requirement it is better to apply style sheet on mouse over of label and java script to open a window on click.

Style sheet :-

Mouse out style sheet

.lbl_mouseout
{
text-decoration:none;
color:Black;
}

Mouse over style sheet

.lbl_mouseover
{
text-decoration:underline;
cursor:hand;
color:Blue;
}


In aspx.cs page

//Javascript to handle mouse and mouse out events
lbl.Attributes.Add("onmouseover", "this.className='lbl_mouseover'");
lbl.Attributes.Add("onmouseout", "this.className='lbl_mouseout'");

//Javascript to handle on click of the label
lbl.Attributes.Add("onclick", "window.open('destinationurl.aspx'");

How to create procedure in Oracle.

Stored procedure is a data base object which has some syntax defined to make it undestand by the server to perform actions upon request.
Simillarly we have functions,triggers,views etc... called as data base objects that are once if compiled can be used to perform functionalities required.

Syntax for creating a stored procedure.

Create or Replace [Procedure Name]
(
Input/Output parameters list
)
as
[Variable declarations]
begin
[procedure body]
end;

Example:-
Procedure to find sum of 2 numbers
Create or Replace Procedure SumNos
(
a1 in number,//Input parameter
a2 in number,//Input parameter
a3 out sys_refcursor //Output parameter
)
as
tempSum number; //Variable declaration
begin
//Procedure body
tempSum:=a1+a2;
// To open a3 cursor and fill the result set from below select query
open a3 for
select tempSum as 'Sum' from dual;
end;


The above stored procedure can be copied and pasted directly in sql plus to create procedure in data base.
Note: It says create or replace which means if there exists a procedure with same name then it will be relaced with this new procedure content.

Friday, October 24, 2008

What does character set mean?

When we have applications that run globally but share a unique data base , it should be taken care to choose a character set while proposing or defining data base.
This is because there will different type of characters globally that has to saved in data base and understand them.
"WE8MSWIN1252 " is default character set data base considers when we create a data base , it has to be changed to "AL32UTF8" which is global character set.
There are different character sets available.
Note:- Usually developers find a fault after data base has been installed on client side.That is say suppose developer has created C1 character set initially on client side later required to change to C2 then we should pretty sure as C2 should be Super set of C1.
I mean all characters available in C1 should be in C2 else data corruption comes into picture because it may not find some characters.

When you create data base:-









Thursday, October 23, 2008

How to shift Items between List Boxes?

Output:-




In aspx Page :-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShiftingListBoxes.aspx.cs" Inherits="ShiftingListBoxes" %>

<!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 Page</title>
<script type="text/javascript" language="javascript">



function fnMoveItems(lstbxFrom,lstbxTo)
{
var varFromBox = document.all(lstbxFrom);
var varToBox = document.all(lstbxTo);
if ((varFromBox != null) && (varToBox != null))
{
if(varFromBox.length < 1)
{
alert('There are no items in the source ListBox');
return false;
}
if(varFromBox.options.selectedIndex == -1) // when no Item is selected the index will be -1
{
alert('Please select an Item to move');
return false;
}
while ( varFromBox.options.selectedIndex >= 0 )
{
var newOption = new Option(); // Create a new instance of ListItem
newOption.text = varFromBox.options[varFromBox.options.selectedIndex].text;
newOption.value = varFromBox.options[varFromBox.options.selectedIndex].value;
varToBox.options[varToBox.length] = newOption; //Append the item in Target Listbox
varFromBox.remove(varFromBox.options.selectedIndex); //Remove the item from Source Listbox
}
}
ShowCounts();
return false;
}

function DoesItemExist(opt,lst)
{
for(var i=lst.options.length-1;i>=0;i--)
{
if(lst.options[i].value==opt.value && lst.options[i].text==opt.text )
{
return true;
}
}
return false;
}
function fnMoveAllItems(lstbxFrom,lstbxTo)
{

var varFromBox = document.all(lstbxFrom);
var varToBox = document.all(lstbxTo);

for(var i=varFromBox.options.length-1;i>=0;i--)
{
var opt=document.createElement('option');
opt.text=varFromBox.options[i].text;
opt.value=varFromBox.options[i].value;
if(DoesItemExist(opt,varToBox)==false)
varToBox.options.add(opt,i);
varFromBox.options.remove(i);
}
ShowCounts();
return false;
}

function ShowCounts()
{

var varlistRight = document.getElementById('listRight');
var varlistLeft = document.getElementById('listLeft');
var llcnt=GetCount(varlistLeft);
var lrcnt=GetCount(varlistRight);
document.getElementById('lbllistLeft').innerText="Count : "+llcnt+"/"+varlistLeft.options.length;
document.getElementById('lbllistRight').innerText="Count : "+lrcnt+"/"+varlistRight.options.length;
}

function GetCount(lst)
{
var cnt=0;
for(var i=lst.options.length-1;i>=0;i--)
{
if(lst.options[i].selected)
cnt++;
}
return cnt;
}
function lstChnge(obj,lbl)
{
var llcnt=GetCount(obj);
document.getElementById(lbl).innerText="Count : "+llcnt+"/"+obj.options.length;
}
</script>
</head>
<body onload="ShowCounts();">
<form id="form1" runat="server">
<table width="50%">
<tr>
<td align="center">
<asp:ListBox ID="listLeft" runat="server" Height="109px" Width="103px" SelectionMode="Multiple" onchange="lstChnge(this,'lbllistLeft');">
<asp:ListItem Value="0">Ashish</asp:ListItem>
<asp:ListItem Value="1">Badrinath</asp:ListItem>
<asp:ListItem Value="2">Chaminda</asp:ListItem>
<asp:ListItem Value="3">Dravid</asp:ListItem>
<asp:ListItem Value="4">Goutham</asp:ListItem>
<asp:ListItem Value="5">Irfan</asp:ListItem>
<asp:ListItem Value="6">Lakshman</asp:ListItem>
<asp:ListItem Value="7">Nehra</asp:ListItem>
<asp:ListItem Value="8">Sehwag</asp:ListItem>
<asp:ListItem Value="9">Tendulkar</asp:ListItem>
<asp:ListItem Value="10">Yuvraj</asp:ListItem>
</asp:ListBox>
<label id="lbllistLeft" ></label>
</td>

<td>
<table width="100%">
<tr align="center">
<td align="center"><asp:Button ID="btnAddRight" runat="server" Text=">" Width="22px" /></td></tr>
<tr align="center"><td align="center"><asp:Button ID="btnAddRightAll" runat="server" Text=">>" /></td></tr>
<tr align="center"><td align="center"> <asp:Button ID="btnAddLeft" runat="server" Text="<" Width="23px" /></td></tr>
<tr align="center"><td align="center"><asp:Button ID="btnAddLeftAll" runat="server" Text="<<" Width="24px" /></td></tr>
</table>
</td>



<td align="center">
<asp:ListBox ID="listRight" runat="server" Height="110px" Width="102px" SelectionMode="Multiple" onchange="lstChnge(this,'lbllistRight');"></asp:ListBox>

<label id="lbllistRight" ></label>
</td>
</tr>
</table>


</form>
</body>
</html>

In Code Behind Page:-

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

public partial class ShiftingListBoxes : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnAddRight.Attributes.Add("onclick", "return fnMoveItems('listLeft','listRight')");
btnAddLeft.Attributes.Add("onclick", "return fnMoveItems('listRight','listLeft')");
btnAddRightAll.Attributes.Add("onclick", "return fnMoveAllItems('listLeft','listRight')");
btnAddLeftAll.Attributes.Add("onclick", "return fnMoveAllItems('listRight','listLeft')");

}

}
}

Wednesday, October 22, 2008

How to add Page break?

When response is written to browser, it considers the response depending upon the type of content.
The type of content might be Html or Doc or Xls or pdf etc...
When the content type is Doc , it opens the response string with Microsoft Word document similarly if it is pdf it opens the response string with Acrobat Reader.

So to implement page break style has to be written which can be under stood by browsers like Internet Explorer or Fire Fox.
Where as the content written to Doc or Pdf though the Page break style is applied it cannot apply page break.

Ex:-

style="page-break-before:always;" is what should be applied to have a page break before this line, else style="page-break-after:always;" to have a page break after this line.

Tuesday, October 21, 2008

Java script calculator.










<!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>
<title>Untitled Page</title>
<script type="text/javascript">
var a=0;
var b=0;
var preop='+'
var blnOned=false;
var blnRefDisp=true;
var prevKey='';
function PerformCalc()
{
if(preop=='+')
{
a=parseFloat(a)+parseFloat(b);
}
if(preop=='-')
{
a=parseFloat(a)-parseFloat(b);
}
if(preop=='*')
{
a=parseFloat(a)*parseFloat(b);
}
if(preop=='/')
{
a=parseFloat(a)/parseFloat(b);
}
}
function IsOperatorPressed(val)
{
if(val=='/' || val=='*' || val=='-' || val=='+')
{
return true;
}
return false;
}
function CalPress(iddval)
{
var valOt=document.getElementById('txtOutPut');
if(iddval!='On')
{
if(blnOned==false)
{
return;
}
}
if(iddval=='On')
{
valOt.value='0';
document.getElementById('btnOnOff').value='Off';
preop='+';
a=0;
b=0;
blnOned=true;
return;
}
else if(iddval=='C')
{
valOt.value=0;
preop='+';
a=0;
b=0;
return;
}
else if(iddval=='Off')
{
document.getElementById('btnOnOff').value='On';
valOt.value='';
preop='+';
a=0;
b=0;
blnOned=false;
return;
}
if(iddval=='=')
{
blnRefDisp=true;
PerformCalc();
valOt.value=a;
}
else if(IsOperatorPressed(iddval))
{
blnRefDisp=true;
if(prevKey=='=')
{
b=0;
}
else
{
if(prevKey!=iddval)
{
PerformCalc();
valOt.value=a;
}
}
preop=iddval;
}
else
{
if(prevKey=='=')
{
a=0;
}
if(blnRefDisp==true)
{
b=iddval;
}
else
{
if( b=='0')
b=iddval;
else
b=b+iddval
}
valOt.value=b;
blnRefDisp=false;
}
prevKey=iddval;
}


//functions on key press div
function keyPrss()
{

var val=String.fromCharCode(event.charCode ? event.charCode : event.keyCode);
if(event.keyCode==44)
{
return false;
}
if(event.keyCode>=42 && event.keyCode<=57)
{
CalPress(val);
return true;
}
if(event.keyCode==27)
{
CalPress('C');
return true;
}
if(event.keyCode==111)
{
CalPress(document.getElementById('btnOnOff').value);
return true;
}
if(event.keyCode==13)
{
CalPress('=');
return true;
}
return false;

// document.getElementById('lblTest').innerText=event.keyCode;
}
</script>
</head>
<body>
<label id="lblTest" runat="server"></label>
<div style="text-align: center" onkeypress="keyPrss()">
<table border="2">
<tr>
<td colspan="4">
<input id="txtOutPut" type="text" style="width:80%;text-align:right" readonly="readonly"/></td>
</tr>
<tr>

<td>
<input id="btnSqrt" style="width: 100px;color:Red;display:none;" type="button" value="Sqrt" onclick="CalPress(this.value);" /></td>


<td>
<input id="btnClear" style="width: 100px;color:Red" type="button" value="C" onclick="CalPress(this.value);" /></td>
<td colspan="2">
<input id="btnOnOff" style="width: 100px;color:Red" type="button" value="On" onclick="CalPress(this.value);"/></td>
</tr>
<tr>
<td style="width: 100px">
<input id="btn7" style="width: 50px;color:Blue" type="button" value="7" onclick="CalPress(this.value);"/></td>
<td style="width: 100px">
<input id="btn8" style="width: 50px;color:Blue" type="button" value="8" onclick="CalPress(this.value);"/></td>
<td style="width: 100px">
<input id="btn9" style="width: 50px;color:Blue" type="button" value="9" onclick="CalPress(this.value);"/></td>
<td style="width: 100px">
<input id="btnDiv" style="width: 50px;color:Red" type="button" value="/" onclick="CalPress(this.value);"/></td>
</tr>
<tr>
<td style="width: 100px">
<input id="btn4" style="width: 50px;color:Blue" type="button" value="4" onclick="CalPress(this.value);"/></td>
<td style="width: 100px">
<input id="btn5" style="width: 50px;color:Blue" type="button" value="5" onclick="CalPress(this.value);"/></td>
<td style="width: 100px">
<input id="btn6" style="width: 50px;color:Blue" type="button" value="6" onclick="CalPress(this.value);"/></td>
<td style="width: 100px">
<input id="btnMul" style="width: 50px;color:Red" type="button" value="*" onclick="CalPress(this.value);"/></td>
</tr>
<tr>
<td style="width: 100px">
<input id="btn1" style="width: 50px;color:Blue" type="button" value="1" onclick="CalPress(this.value);"/></td>
<td style="width: 100px">
<input id="btn2" style="width: 50px;color:Blue" type="button" value="2" onclick="CalPress(this.value);"/></td>
<td style="width: 100px">
<input id="btn3" style="width: 50px;color:Blue" type="button" value="3" onclick="CalPress(this.value);"/></td>
<td style="width: 100px">
<input id="btnSub" style="width: 50px;color:Red" type="button" value="-" onclick="CalPress(this.value);"/></td>
</tr>
<tr>
<td style="width: 100px">
<input id="btn0" style="width: 50px;color:Blue" type="button" value="0" onclick="CalPress(this.value);"/></td>
<td style="width: 100px">
<input id="btnDot" style="width: 50px;color:Blue" type="button" value="." onclick="CalPress(this.value);"/></td>
<td style="width: 100px">
<input id="btnEq" style="width: 50px;color:Red" type="button" value="=" onclick="CalPress(this.value);"/></td>
<td style="width: 100px">
<input id="btnAdd" style="width: 50px;color:Red" type="button" value="+" onclick="CalPress(this.value);"/></td>
</tr>
</table>
</div>

</body>
</html>

Sunday, October 19, 2008

How to select multiple check boxes?

Using java script it is possible to check/uncheck multiple check boxes at once in a page using a single "Select All" check box.
Checking/UnChecking this check box sets the status of the available Item check boxes.
(SelecT All check box which calls a specific funtion when user clicks on it)
Select All<input type="checkbox" id="chk_select_all" onclick="select_All_chks(this);" />

(Item check boxes which are to be checked/unchecked at once with the help of above "Select All" check box.

Select <input type="checkbox" id="chk_select1" title='Item'/>
Select <input type="checkbox" id="chk_select2" title='Item'/>
Select <input type="checkbox" id="chk_select3" title='Item'/>

//Function that gets called when user cliks on "Select All" Check box.
function select_All_chks(obj)
{
//Iterating through elements available in the current document whose tag name is "input".
for(var i=0;i<document.body.getElementsByTagName('input').length;i++)
{
//Condition if the items title is 'Item' (Item check boxes)
if(document.body.getElementsByTagName('input')[i].title=='Item')
{
//Setting the status of the item check boxes according to the "Select All" check box.
document.body.getElementsByTagName('input')[i].checked=obj.checked;
}
}
}

How to use Confirm box?

We have confirm function in javascript simillar to alert in javascript.
alert box just provides a message box with only "OK" button.
Confirm box provides a message box with "OK" and "Cancel" buttons.

There might be certain requirements to handle this ok and cancel events.That is to handle the ok/cancel button click events.

When user clicks on "OK" button , it returns true (boolean) and for "cancel" it returns false (boolean).
So following execution is an example to handle such confirm box.

Example:-

function test()
{
if(confirm('Are you male?'))
alert('You are Male');
else
alert('You are Female');
}

This says, when user clicks on "OK" button which is on the confirm box (Accepting that user is male) displays an alert box saying "You are Male" else displaya an alert box saying "You are Female".

Saturday, October 18, 2008

File operations using java script?

IE by microsoft has provided an activex object for this file operations (Scripting.FileSystemObject).
Synrax:-
var obj=new ActiveXObject("Scripting.FileSystemObject");

This object obj can be used to read/write/append data to text file.
Example:-
var fso=new ActiveXObject("Scripting.FileSystemObject");
var file= fso.CreateTextFile(FilePath,true);
file.writeline('Hai');
file.close();

This creates a text file on the specific file path mentioned and writes data("Hai").

var fso=new ActiveXObject("Scripting.FileSystemObject");
if(fso.FileExists(FilePath)
{
var file = fso.OpenTextFile(FilePath,8,false);
file.writeline('Friends');
file.close();
}

This appends text to an existing text file, where (8) says to append text to an existing file.

if(fso.FileExists(FilePath))
{
var file=fso.OpenTextFile(FilePath,1,false);
alert(file.readAll());
file.close();
}

This reads content from the text file and displays an alert box, where (1) indicates to read content from file.

Friday, October 17, 2008

How to read Xml file using java script?

Microsoft has provided an activex object for this functionality that is to load and read and xml file using Internet explorer.

It is "Microsoft.XMLDOM".
Example:

var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load("ImageDescription.xml");
var Root=xmlDoc.documentElement;

Initially we have to create instance to that activex object, we can set the process as asynchrous while loading the xml onto client memory.
Later we need to sepcifcy the xml file name located at local path to the application or the html file.
Now this instance through which we have created the xml dom object , can be used to read elements using tag names or attribute etc... from the loaded xml file (ImageDescription.xml).


for(var rt=0;rt<Root.childNodes.length;rt++)
{
if(Root.childNodes[rt].nodeName=='Test node name')
{
.....
So using this document element object (Root), we can iterate through the xml tree nodes , and perform logical actions.

Thursday, October 16, 2008

sql query to insert multiple rows - Oracle

Sql optimiser creates a perfect execution plan according to the query written by user.
The way the query is written logically helps in performance of an application.
Suppose there is a requirement to insert multiple records from a table to another table or a set records retrieved from a result set after running "select" query to a table.
Usually we start developing source code as
1) Retrieves records from select statement to a data table (Front end or application server memory) using data set or oracle reader.
2)Loop through the rows and read the field values into a variable .
3) Now run a sql query that inserts these field values creating a new record at destination table.

When the number of rows that are to be inserted are increased this definitely degrades the performance of the application.

Also Instead of spending more time in constructing these steps, it is reliable to build an effective sql query that does this task.

When a "select" sql auery is runned in oracle or sql , the result set is always a table, also ac coring to our example the destination is a table into which we need to insert records.
Ex:-
select '1' as num from dual;
This query returns as table which has one column (num) and one row (1).

So this table can be used to insert a single record into a table which has one column and of type number.

That is
insert into destination_table
(select '1' as num from dual);
This is just a simple example, where as in real time we may have multiple tables which result in a single table after running sql query and can be inserted into a single oracle table.

Wednesday, October 15, 2008

To_date in oracle

Applications which are build with .Net or Java and oracle as back end usually face problems while assigning values to the date parameters sent thtough oracle procedure.

To_Date() oralce function converts from string type to date (oracle) type using format string.
Syntax:-

To_date(date(string),format(string))
simillarly
To_char() oracle function converts from a type (date,float, etc...) to a char type.

when date parameter value is sent to procedure from .Net or oracle, either it can be declared as date or varchar with specific format hard coded.

Ex:-


Select to_date('14/05/2008','dd/MM/yyyy') from dual;
displays the date but from the date object that is created in the above query.

Slect to_char(sysdate,'dd/MM/yyyy') from dual;
converts current (system date) to string using dd/MM/yyyy format and displays the formated date.

Tuesday, October 14, 2008

How to create a job in Oracle?

Creating jobs in data base are very practical when applications are closed or not running but business needs to run a sql script to do manupilations or calculations and send mails to users etc...

Syntax :-
Sys.dbms_job.submit(job: out binary_integer,what:in varchar2,next_date:in date,
Interval: in varchar2,
no_parse: in Boolean,instance : in binary _integer,force: in Boolean);


Example:-

DECLARE
X NUMBER;
BEGIN
SYS.DBMS_JOB.SUBMIT
(
job => X
,what => '
insert into test
(
select decode(max(num),null,1,(max(num)+1)) from test);'
,next_date => to_date('10/11/2008 23:30:08','mm/dd/yyyy hh24:mi:ss')
,interval => 'TRUNC(SYSDATE+30)'
,no_parse => FALSE
);
:JobNumber := to_char(X);
END;

This job when once created, it inserts record into test table every time periodically.

Sunday, October 12, 2008

How to develop slide show using java script?

Assign all the necessary images or snaps to an array , which can be retrieved based upon index.

In java script we have function called setTimeout which behaves like Thread.sleep.

Example:-
function hi()
{
alert('Hi');
}
var tmr=setTimeout("hi()",2000);
Here user gets an alert box sayinh hi , 2 seconds after the page has been loaded.

Simillarly , for every time the function is called for slide show, increment a variable and index , after incrementing call a function that reads the items from an array based on index that gives image url. Now assign this image url to an "img" tag whose src is updated to the new Image url.


The most generic method for building a slide show is using an xml file, that has tags defined for images with comments,rating,src etc... ,on page load reading the image attributes from xml file and loading into array with specific indexes.

Later with this time out function you can read those images. Also you can switch off the slide show with another function that clears the timer.

Ex:-
clearTimeout(tmr);

Saturday, October 11, 2008

How to upload videos on to web site?

You tube is very help ful at this instatnt where you can upload your videos which you are willing to propose in your site.
You tube provides shock wave video player which is available at specific url.
When you upload you video in You tube it gives you the url of the video which you have uploaded and can access with that url (You can observe video at right hand side beside your video in you tube site).


For example i have created a sample html page which uses that you tube video url and displays in my web site.
Ex :-

My favourite video




Code:-
<html>
<head>
</head>
<body>
My favourite Video


<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/bOOMPj9zudE&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><embed

src="http://www.youtube.com/v/bOOMPj9zudE&hl=en&fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="425" height="344"></embed></object>
</body>
</html>

Display status using java script

This is a sample Html page that displays text box. When user enters value in that text box and clicks on the available button, progress bar displays the status


<html>
<head>
<script>
var tmr;
var mxloop=10;
var curvl=0;
function test()
{
curvl=curvl+1;
var window_width=Math.round(((curvl/mxloop)*100),2);
if(curvl>mxloop)
{
window.clearTimeout(tmr);
curvl=0;
return;
}
displayProgress(window_width)

tmr=window.setTimeout("test();", parseInt(document.getElementById('txtval').value));

}
function displayProgress(percent)
{
document.getElementById('prgs').innerHTML='<DIV ID="percent" STYLE="filter: alpha (opacity=30);text-align:center;position: absolute;width:' + percent+ '%;vertical-align: middle;background-color:green;"></div><center>'+percent+'%</center>';
}
</script>
</head>
<body>
<input type="text" id="txtval"/>
<input type="button" id="btn" onclick="test();" value="start"/>
<br/>
<div id="prgs" style="border:2px solid black;width:10%;fore-color:black;">
</div>

</body>

</html>

Friday, October 10, 2008

Building Stack with Console

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{


using System;
class Node
{
public Node objNode;
public Object objObject;
public Node(Node argNode, Object argObj)
{
objNode = argNode;
objObject = argObj;
}

}
class ExStack
{

Node objNode = null;
public void Push(Object argObject)
{
objNode = new Node(objNode, argObject);
}
private bool IsNumber(string strValue)
{
try
{
int.Parse(strValue);
return true;
}
catch (Exception exp)
{
return false;
}
}
public Object this[int Index]
{
set
{
Node objInnNode = GetNode(Index);
if (objInnNode != null)
{
objInnNode.objObject=value;
}
}
get
{
Node objInnNode=GetNode(Index);
if (objInnNode != null)
{
return objInnNode.objObject;
}
return null;
}
}

public Node GetNode(int intIndex)
{
Node objInnerNode = objNode;
while (objInnerNode != null)
{
if (intIndex == 0)
return objInnerNode;
else
{
objInnerNode = objInnerNode.objNode;
intIndex--;
}
}
return null;
}
public Object Pop()
{
if (objNode != null)
{
Object objVal = objNode.objObject;
objNode = objNode.objNode;
return objVal;

}
return null;
}


class Test
{

static void Main()
{
ExStack objLclExStack = new ExStack();

while (true)
{
Console.WriteLine("Enter Some Value");
Console.WriteLine(" 1 to view details\n 2 to Exit\n3 to Pop\n 4 to access with Index \nOther Value to Push");
string strValue = Console.ReadLine();
if (strValue == "1")
{
if (objLclExStack != null)
{
Node objLclNode = objLclExStack.objNode;
while (objLclNode != null)
{
if (objLclNode != null)
{
Console.Write(objLclNode.objObject.ToString() + " -- >");
}
else
{
break;
}
objLclNode = objLclNode.objNode;
}
}
Console.WriteLine(" ");
}
else if (strValue == "2")
{
break;
}
else if (strValue == "3")
{
Object obj = objLclExStack.Pop();
if (obj != null)
{
Console.WriteLine(obj.ToString());
}
else
{
Console.WriteLine("No Elemnts To Pop");
}
}
else if (strValue == "4")
{
Console.WriteLine(" Enter Index To View");
strValue = Console.ReadLine();
while (!objLclExStack.IsNumber(strValue))
{
Console.WriteLine("Please Enter valid Index To View");
strValue = Console.ReadLine();
}
Object objValue= objLclExStack[int.Parse(strValue)];

if (objValue != null)
{
Console.WriteLine("Value at Index " + strValue + " is " + objValue.ToString());
Console.WriteLine("Do you like to edit Y or N");
string strNewValue = Console.ReadLine();
if (strNewValue == "Y")
{
Console.WriteLine("Please Enter Value");
strNewValue = Console.ReadLine();
objLclExStack[int.Parse(strValue)] = (Object)strNewValue;
}
}
else
{
Console.WriteLine("Index " + strValue + " does not exist");
}
}
else
{
objLclExStack.Push((Object)strValue);
}
}
}
}
}
}

Thursday, October 9, 2008

Serialization

To provide persistence of an object similar to stroing real time data into data base, seriliazation is used.

Namespace is System.Runtime.Serialization.

The object what we are trying to persist ,its class should be serializable.

For example
Hashtable class is serializable whose object can be persisted. Where Hashtable is a predefined refernce type.


When coming to user defined class following the syntax to make class serializable.


using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
namespace name1
{
[Serializable()]
class example
{
//Class Implementation
}
}


Example Code :

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
namespace Learnings
{
[Serializable()]
class Topic
{
private string _topicName;
private string _topicDesc;
private string _topicProposedBy;
private DateTime _topicProposedDate;
public string TopicName
{
set
{
_topicName = value;
}
get
{
return _topicName;
}
}

public string TopicDescription
{
set
{
_topicDesc = value;
}
get
{
return _topicDesc;
}
}

public string TopicProposedBy
{
set
{
_topicProposedBy = value;
}
get
{
return _topicProposedBy;
}
}


public DateTime TopicProposedDate
{
set
{
_topicProposedDate = value;
}
get
{
return _topicProposedDate;
}
}


}
}

So now an object created for class Topic can be serialized and persisted.

Tuesday, October 7, 2008

How to call java script functions in code behind pages?

When web server receives request, it constructs the response string that has to be rendered on to client browser.
This response string is build not just based upon aspx page but also aspx.cs. So developer can call java script functions not only from aspx page but also from aspx.cs provided the syntax or the approach is different.

Example :-
If I want to show a message using alert box (javascript) upon button click , I can call the alert box javascript function just on button click of appropriate button.

This button might be a Html (input type=”button”) type button or asp button (asp:Button). What ever the case it is at the moment they are rendered to browser they seems to be Html (input type=”button”) type button.
So I can do in the following way to display alert box.
<input type=”button ” id=”btnTest ” value=”Test ” onclick=”alert(‘Hi’);”/>
in aspx page


Else I can do in aspx.cs page as
btnTest.Attributes.Add("OnClick", "alert('Hi');"); in page load event.


The above 2 give the same response to the browser but the way web server constructs the response is different.

In first case web server need not bother exclusively to add onclick event where as in other case form the page load event it finds that an onclick (client event) is required to be considered for “btnTest” button.

Finally the response string gets builded in simmilar manner to handle client on click event once rendered on to client browser.

This is a sample, there are many functionalities or instants that we cannot add client events like click,mouse down,mouse over etc.. directly on aspx page but can handle from aspx.cs page.

Monday, October 6, 2008

How to choose oracle data base (back end) or .NET, java (front end programming) to implement logic?

We might have been experienced many circumstances or waver when to use an oracle procedure or .net function to implement a logic.
Let us see what oracle does upon request:

Oracle has 3 different kinds of processes running at its end to run or execute certain requests.
1) Back ground process.
2) Server process.
3) Network process.

The processes listed have there own importance and designed to improve performance. Oracle data base has fine defined memory structures which support best manner to manage, organise, manipulate, etc data based on request from user.
Example :-
When user provides a sql select query to run at oracle server, it does not do blindly retrieve data from disk based on applied logical query. Instead it has an algorithm to go through the steps in an organised manner to send data.
It has library cache and dictionary cache buffers which stores recent oracle queries and data from it respectively. So oracle optimises the process of handling user requests or queries and improves performance.

When the logic or requirement if the developer is to manipulate (insert/delete/update) data or get a value based upon the data available in oracle tables (also need to join tables) , etc.. it is better to use oracle procedures/functions which improve performance , as sql optimiser helps it.

The advantages of using Oracle objects for implementing for such kind of logics which are dependant upon the available data in data base and other kind are
1) sql optimiser plays a vital role to improve performance.
2) Compiling the oracle objects also helps developer to provide proper sql syntaxes.
3) If any table objects are dropped from database sets the dependant objects state to invalid or which need to be complied again. This helps user to find such dependant procedures/functions and implement them.
4) If the application set up along with data base is installed on client machine, later if developer needs to fix an issue related to logic implemented, In case of front-end programming language (java, .net) developer needs to build the set up again and install it at client environment. Where as using data base objects like procedures.funtions developer can just provide sql scripts that should be runned at client data base serer to reflect the changes.


We shall see many requirements like in a grid we should provide a sorting button in header for each data column, on click of which we should sort the data available at that column and update the grid.

For such requirement we usually do is we use data table in .net , apply it to a data view object ,sort the data view and bind the updated data view to the grid.
For which CLR should handle the memory to sort the data.

Where as if we use oracle, by calling the same query to retrieve data and applying “order by” clause at end of the query select query, bind to grid is more efficient
This is because as said , if we use a select query oracle first looks into dictionary cache if data available for that query, library cache whether same query is used earlier and if found immediately assigns the execution plan to the optimiser, which retrieves data. If user sorts the same column again next time (running same query in oracle data base) definitely will have faster response from web server.

Sunday, October 5, 2008

How to display log out message when user logs out from the system?

There are different ways to intimate the user when he/she logs out from the system.
The log out button should be placed in a master page which is used by all application pages. When user clicks on that log out button , system should redirect to log in page.


At this moment when page redirects to login page, developer can send a flag or query string which helps the login page load function to read that query string and display the message accordingly.


Example:-

Master page used by application pages,

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<table><tr><td align="right"><asp:LinkButton ID="lnkLogout" Text="Logout" runat="server" OnClientClick="location.href='Login.aspx?Logout=Y';return false;"></asp:LinkButton></td></tr></table>

<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
</asp:contentplaceholder>
</div>
</form>
</body>
</html>

You can observe the link button in the master page on client click of which loads login page with query string Logout=’Y’, that helps login page to display meesage.
Application page (App1.aspx) which uses the above master page

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="App1.aspx.cs" Inherits="App1" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">


Welcome to application page1
</asp:Content>



Login Page:

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

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr><td align="center"><asp:Label ID="lblMsg" runat="server"></asp:Label></td></tr>
<tr><td align="center">Log In Page</td></tr>
<tr><td align="center"><asp:Button ID="btnLogin" runat="server" Text="Log In" OnClick="btnLogin_Click" /></td></tr>

</table>

</div>
</form>

</body>
</html>
In the login page the label (lblMsg) is used to display message accordingly.

Code behind file of the login page (Login.aspx.cs):

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

public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Logout"] != null && Request.QueryString["Logout"].ToString().ToUpper()=="Y")
{
lblMsg.Text = "You have logged out from the system";
}

}

protected void btnLogin_Click(object sender, EventArgs e)
{
Response.Redirect("App1.aspx", false);
}
}

Page load event in this calss file reads the query string (Logout) which when says “Y” , assigns text to the message label.

Output :-
When login page Is opened













when user clicks on “Log In” button :











When user clicks on “log out” button :









This is because, the query string contains “Logout” key in the url and because of which the page displays the appropriate message.

How to use web cntrol library?

Web control library is a project which is help full for developer to build his custom controls like drop down list, grid view etc…
Please refer earlier blog regarding custom controls.

To add a web control library









Right click on your solution and click on add new project.
In new project template you can find “WebControlLibrary” under windows tab.


Building this web control library project creates .dll file which can be used in a web application by adding this dll as reference.

I shall build a Web control which shall render a html button onto browser.
Upon clicking on the button available in UI it displays the current date with an alert box.

Code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyControls
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]
public class MyControl1 : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]

protected override void RenderContents(HtmlTextWriter output)
{
//This function is called by web server when an instance is created for this web control.
So this function is basically to prepare html content that can be rendered on to browser upon adding to this output HtmlTextWriter.
//Here I am writing a input button tag and java script click to it to display current date.
string strResponse = "<input type='button' value='What is todays date?' id='btnDate' onclick='var dt=new Date();alert(dt);'/>";
output.Write(strResponse);
}
}
}

After writing the web control code I shall build the web control library project .
After successful build I shall add refernce to web site under projects tab.









After adding the reference I shall open Test.aspx page in desing view of which I can find the “MyControl1” under mycontrol components tab,












As soon as I drag and drop that “MyControl1” the aspx page automatically registers that dll and I can use it as a normal web control.


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

<%@ Register Assembly="MyControls" Namespace="MyControls" TagPrefix="cc1" %>

<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<cc1:MyControl1 runat="server">
</cc1:MyControl1>
</div>
</form>
</body>
</html>

Now upon running the application.












So I am using my custom build button control which shall display current date. So when ever I do applications that need this functionality I shall add this web control reference and re use it instead of re building the functionality.

Saturday, October 4, 2008

What is user control?

What ever the control it is, the ultimate need is provide information to the user through web browser by displaying content in effective manner. For this micro soft has developed few controls like grid view, repeater, list view, dropdown list etc.. Which are predefined controls and each has its own importance.

Where user defined controls are the one which developers build on there own according to requirement.

They might be usercontrols or controls that are build with web control library.

User controls are similar to aspx pages but extension is ascx page, which are build very specific or pointed to business requirement.

Example :-

Build a generic panel when giving date of birth as input should display the day (Thursday or Friday...).

In this case i will use a usercontrol which can be placed as a panel in aspx page and also can be used in many pages when and there required. (Code re usability).

Where as controls that are build with web control library are like dropdown list controls which developer can design his own component, which he can mention the rendering HTML content when response is thrown by server to browser.




I am creating a UserControl for above stated example (Date Of Birth)








<%@ Control Language="C#" AutoEventWireup="true" CodeFile="DOB.ascx.cs" Inherits="DOB" %>
Day :
<asp:Label ID="lblDay" runat="server"></asp:Label>

Iniside ascx page html content

In Code behind page

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

public partial class DOB : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{

}
//public variables to which date,month,year are assigned from parent page to display day
public int intDate = 0, intMonth = 0, intYear = 0;
public bool ShowDay
{
set
{
//Propoerty defined which when set to true after assigning values to abive variables
// shows/displays day
if (value)
{
//array defined with days based on indexes
string[] objDays = new string[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
//Datetime object creation with the variable values
DateTime objDateTime = new DateTime(intYear, intMonth, intDate);
//Displaying day fromm array based on day of the week index from date time object
lblDay.Text = objDays[Convert.ToInt32(objDateTime.DayOfWeek)].ToString();
}
}

}
}


Now I am opening aspx page (Default.aspx) to use the abive day user control.
In aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="~/DOB.ascx" TagName="Cal" TagPrefix="c1" %>
<!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 Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr><td>Date :</td><td><asp:TextBox ID="txtDate" runat="server"></asp:TextBox></td></tr>
<tr><td>Month :</td><td><asp:TextBox ID="txtMonth" runat="server"></asp:TextBox></td></tr>
<tr><td>Year :</td><td><asp:TextBox ID="txtYear" runat="server"></asp:TextBox></td></tr>
<tr><td><asp:Button ID="btnDisplayDay" runat="server" Text="Day?" OnClick="btnDisplayDay_Click" /></td><td>
<c1:Cal runat="server" ID="cl1" />
</td></tr> <tr><td></td><td></td></tr>
</table>

</div>
</form>
</body>
</html>



In code behind page

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 _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnDisplayDay_Click(object sender, EventArgs e)
{
//cl1 is the ID of the user control instance from aspx page
cl1.intDate = int.Parse(txtDate.Text);
cl1.intMonth = int.Parse(txtMonth.Text);
cl1.intYear = int.Parse(txtYear.Text);
cl1.ShowDay = true;

}
}

Output :










I shall create a new blog with the next topic that is using web control library tomorrow.

Cheers,
Srinivas

Friday, October 3, 2008

What is the difference between Array List and Hash Table?

Array list and hash table are the collection objects whose basic necessacity is to collect or hold a group of objects need not be of same type.

They are similar to what we say arrays in C- Programming or java or any programming languages.
Arrays are only capable of storing specific types which are predefined on declaration. Where as Array list or hash table shall store objects of any type and need not be predefined.

Arrays declaration should include its maximum size capability at the time of declaration, where array list or hash table shall increase there size dynamically based upon the objects added or collected using IList interface.

(Please refer my earlier post regarding value and reference type Refernce type and value type).

Arrays are similar to value types where as Array lists and Hash table are reference types that is different reference variables for Array list or Hash table (object) can be used in entire application to access same array list or Hash table object. Where as for Arrays you can have only one value type variable to access specific array location.

So at last I mean to say that the above are few of the reasons why Array lists and Hash tables are driven into enough existence.

Then what is the reason behind creating both Array list and Hash table.




The main difference is Array list implements IList interface where as Hash table implements IDictionary interface.

The interface names it self explains why there are Array list and Hash table collections.
Example : -


List out all the names in a class whose age is above 20.

In this case I use array list.

List out all the names in a class whose age is above 20 and also should be identified with there Roll Numbers.

In this case I use Hash table.




So hash table is similar to a dictionary to retrieve a value (Student names) based upon a unique key (Roll No). Array list is blindly adding items or values (Student names) but not required to bother to identify.
Also Values added to a hash table can be duplicates but key should not be.
In the above example you cannot a student more than once with his roll number, which will throw an exception saying key value pair already exists.


The values we add to a array list or hash table, similarly key to hash table can be any type (object of user defined or frame work defined object or primitive data type).


Syntax :-

Array List

ArrayList objList=new ArrayList();
objList.Add(“Srinivas”);
objList.Add(“Bharani”);
“Srinivas”,”Bharani” ->Items or Values.


Hash Table

HashTable objHashTable=new HashTable();
objHashTable.Add(1,“Srinivas”);
objHashTable.Add(2,“Bharani”);
1,2-> Keys
“Srinivas”,”Bharani” -> Values.

Thursday, October 2, 2008

How to use Cookies in web applications?

Cookies are similar to variables but stored at client side (browser), helps in executing light weight functionalities instead of pinging the server.

Example:-
We use a cookie flag which helps in identifying whether the user has logged in or logged out. If user log out from the application, then he cannot click on back button at the top of the browser to reload the previous application page.


I shall check out in the page load of application page, the value of cookie. If it says that user has logged out then I shall redirect to login page else continue loading the page.

Function to add cookies.
function AddCookie(cName,cValue)
{
document.cookie=cName+"="+cValue+"; path=/";
}

document.cookie indicates that the cookie should be added to current document.
Cname the parameter plays a role as key and stores the cvalue received in the function.Where as “path/” indicates the availability or accessbility of the cookie added.
If Path says “/” then it mean that cookie varaible can be access in the whole application else only in that specific page.
Also we have attribute called “Expiry” which terminates the cookie at specific time interval after creation.

Function to retrieve value from document cookies based on cookie name (Key)

function GetCookieValue(cName)
{
var allcks=document.cookie;
var cks=allcks.split(";");
for(var i=0;i<cks.length;i++)
{
var cok=cks[i];
while(cok.charAt(0)==" ")
{
cok=cok.substring(1,cok.length);
}
if(cok.indexOf(cName)==0)
{
var val=cok.substring(cName.length+1,allcks.length);
return val;
}
}
return " ";
}

Since there can be multiple cookies at an instant for a document, we should split those cookies with “;” and again retrieve the cookie name from each splitted cookie.

If the name sent matches with the cookie then retrieving the cookie value and returning it.


Application Page
function CheckForLogin()
{
var val=GetCookieValue("Login");
if(val!='y')
{
location.href="../Login.aspx";
}
}


I shall place the above fnction in “onload” event of body in the application page to check before loading.
<body onload=" CheckForLogin ();”>
If the flag says that user has not logged in then redirecting to login page.



Login Page
function RemoveLogin()
{
AddCookie("Login","n");
}

<body onload="RemoveLogin();">
In the same fashion in “onload” event of login page I shall addcookie with flag saying that User has logged it.


User clicking on Login button

function AddLogin()
{
AddCookie("Login","y");
}


As soon as user log in’s into application clicking on “Login” button I shall again add cookie satting login flag as user has logged in.
Calling the above javascript function on click evet of login button.

Wednesday, October 1, 2008

How to display progress bar using JavaScript?

Progress bar is very important to update the user about the status of long running processes.
We shall do it for many desktop applications, since it is very easy to get the status at that instant and update in user interface.
When you use web applications that are not the case, when user interacts with server it reloads the page after the response is completed and then updates the client browser.

So best way of handling it similar to a desktop application is using XMLHttpRequestObject. (Please refer to my earlier posts regarding xmlhttp request
http://programmerfindings.blogspot.com/2008/09/what-is-xmlhttprequest.html).
Where I shall set a timer on client browser, such that for every tick it calls a server page using XmlHttp object and retrieves the response in percentage about the process status and displays it in the user interface along with progress bar using DHTML.

Ex:-
//This is like timer which calls the “DisplayPaymentsStatus” function for //every 2000 milliseconds. Which I shall initiate before starting the //process or when user clicks on button.
Var tmrPaySts=window.setTimeout("DisplayPaymentsStatus();",2000);

function DisplayPaymentsStatus()
{
try
{
var xmlHttp=getAjaxObject();
if(xmlHttp==null)
{
CalPysPrcs(false);
return;
}

if(xmlHttp!=null)
{
var url="../XmlHttp.aspx?For=5";
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {

if(IsNumeric(xmlHttp.responseText))
{
//showing progress bar
document.getElementById('prgs').style.display=’block’;
//calling a javascript function which updates the progress
//bar in UI according to the percentage recived thrpugh response text
ShowProcessPercent(xmlHttp.responseText);
document.getElementById('lblPayStatus').innerText='Processing';
if(xmlHttp.responseText==”100”)
{
document.getElementById('prgs').style.display=’none’;
document.getElementById('lblPayStatus').innerText=’’;
alert(‘Process completed’);
//stoping or disabling timer

clearTimeout(tmrPaySts);

}
}
else
{
//Hiding the progress bar
//IF response text is other than numercic, it is the
//message which I am sending from serverpage if any //error
document.getElementById('prgs').style.display=’none’;
document.getElementById('lblPayStatus').innerText=’’;
alert(xmlHttp.responseText);
//stoping or disabling timer
clearTimeout(tmrPaySts);
}
}
}

xmlHttp.send(null);
}

}
catch(e)
{
alert(e);
CalPysPrcs(false);
//stoping or disabling
clearTimeout(tmrPaySts);

}
}


function ShowProcessPercent(percent)
{
try
{
percent=Math.round (percent ,2);
//Based upon the percentage the function recoevs through parameter, //it generates dynamic html (DHTML) creating a “DIV tag|” inside a //label. The width of the div tag is updates according to the //percentage.
document.getElementById('prgs').innerHTML='<DIV ID="percent" STYLE="filter: alpha (opacity=60);text-align:center;position: absolute;width:' + percent+ '%;vertical-align: middle;background-color:#d4ded8;"></div><center><b>'+percent+'%</b></center>';
}
catch(e)
{
CalPysPrcs(false);
}
}

I will place this div tag in html page which is the boundary for progress bar.
<div id="prgs" style="border:2px solid black;width:100%;display:none;">

</div>


Output :