Tuesday, March 24, 2009

How to draw rectangles from a given graph removing the common vertical lines using JavaScript.

Please refer
Draw line using third party java script file

As explained in above post that the third party java script file makes our task very easier to draw objects.
Now by using this java script file, I would like to share my HTML page and java script code to generate below.
Output:



Note : This is a basic HTML page, so it is not specific to technology
Input :-
User enters number of rectangles in input text box and clicks on “Generate rectangles”, to generate random rectangles.
It should generate mentioned number of rectangles with random height and width but base lined bottoms (similar to a graph).



When user clicks on “Generate button” giving number of input rectangles as 10.



Now output: When user clicks on “Generate Output”, we should draw those rectangles as shown below.




Removing the vertical lines between rectangles to display as union but at last the area of all these output rectangles should be same as are of all input rectangles.
Note:
If you would like to copy the below HTML page to run, Make sure that the third party graphics JavaScript file is downloaded into your machine and placed in this application folder where you are creating this HTML page.
Down third party JavaScript file by clicking here
wz_jsgraphics.zip download
HTML File :

<!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>Rectangles</title>
<link rel="stylesheet" type="text/css" href="Styles/Stylesheet.css" />
</head>
<body>
<div id="Canvas" style="position:relative;height:5px;width:5px;"></div>
<script type="text/javascript" language="javascript" src="wz_jsgraphics.js"></script>
<script type="text/javascript" language="javascript">
var jg = new jsGraphics("Canvas"); // Use the "Canvas" div for drawing
</script>
<script type="text/javascript" language="javascript">
var orgX=50;
var orgY=200;
var minWdth=20;
var minHght=30;
var maxWdth=60;
var maxHght=120;
var rndFactor=10;
var opShft=150;
var lnCntr=0;
var tmr=50;
var iprects=null;
var oprects=null;
var argCnt;
var inpCntr=0;
var rects=new Array();
var ipTmr=50;
var optmr=50;
var recCntr=0;
function rect()
{
var width;
var height;
var id;
var x1;
var y1;
}
function generaterectangles_clk()
{
var txtRec=document.getElementById('txtRects');
if(txtRec.value=='')
{
alert('Please enter number of rectangles to generate');
txtRec.focus();
return;
}
if(!IsNumber(txtRec.value))
{
alert('Please enter numeric value');
txtRec.focus();
return;
}
var numRects=txtRec.value;
if(numRects<3 || numRects>30)
{
alert('Number of rectangles to generate should be between 3 and 30');
txtRec.focus();
return;
}
orgX=50;
orgY=400;
argCnt=numRects;
inpCntr=0;
rects=new Array();
GenerateRects();
}

function GenerateRects()
{
inpCntr++;
if(inpCntr<=argCnt)
{
var rand_no;
var recWth,recHgt;
rand_no = Math.random();
recWth=Math.floor(minWdth+(maxWdth-minWdth)*rand_no);
recHgt=Math.floor(minHght+(maxHght-minHght)*rand_no);
var objRect=new rect();
objRect.width=recWth;
objRect.height=recHgt;
objRect.id=(inpCntr);
rects[rects.length]=objRect;
DefineRects(rects);
setTimeout('GenerateRects();',ipTmr);
}
else
{
var divdisp=document.getElementById('div_recIndx');
divdisp.style.display='none';
divdisp.innerText='';
}
}
function dispRecIndex(x1,y1,txt)
{
var divdisp=document.getElementById('div_recIndx');
divdisp.style.display='block';
divdisp.innerText=txt;
divdisp.style.left=x1;
divdisp.style.top=y1;
}
function DefineRects(argRects)
{
jg.clear();
var x1=orgX;
var y1=orgY;
var buf=5;
var crd=findPosition(document.getElementById('div_map'));
var maxY=crd[1]-buf;
var maxX=document.getElementById('div_map').offsetWidth+crd[0]-buf;
var minY=crd[1]-document.getElementById('div_map').offsetHeight;
var minX=crd[0];
var objRect=new rect();
for(i=0;i<argRects.length;i++)
{
objRect=argRects[i];
if(x1<maxX && x1>minX)
{
objRect.x1=x1;
objRect.y1=y1;
x1+=objRect.width;
}
else
{
for(j=i;j<argRects.length;j++)
argRects[j]=null;
break;
}
if(y1<maxY && y1>minY)
{
objRect.y1=maxY;
}
argRects[i]=objRect;
}
iprects=argRects;
for(i=0;i<argRects.length;i++)
{
if(argRects[i]==null)
break;
objRect=argRects[i];
var xc=new Array();
var yc=new Array();
xc[0]=objRect.x1;
yc[0]=objRect.y1;
xc[1]=objRect.x1+objRect.width;
yc[1]=objRect.y1;
xc[2]=objRect.x1+objRect.width;
yc[2]=objRect.y1-objRect.height;
xc[3]=objRect.x1;
yc[3]=objRect.y1-objRect.height;
xc[4]=objRect.x1;
yc[4]=objRect.y1;
clr=clr1;
dispRecIndex((xc[0]+xc[1])/2,(yc[0]+yc[2])/2,(i+1));
drawRect(xc,yc);
}
}




function generateoutput_clk()
{
if(iprects==null)
return;
var argRects=new Array();
for(i=0;i<iprects.length;i++)
{
if(iprects[i]==null )
break;
var objRect=iprects[i];
var obj=new rect();
obj.x1=objRect.x1;
obj.y1=objRect.y1;
obj.width=objRect.width;
obj.height=objRect.height;
obj.id=objRect.id;
argRects[i]=obj;
}
var prx1,pry1,crx1,cry1;
for(i=0;i<argRects.length;i++)
{
if(argRects[i]==null )
continue;
var currect=argRects[i];
for(var j=i-1;j>=0;j--)
{
if(argRects[j]==null)
continue;
var prvrect=argRects[j];
if(iprects[j].height<=iprects[i].height)
break;
if(prvrect.y1!=currect.y1)
continue;
if(iprects[j].height==iprects[i].height && j==i-1)
{
currect.width=currect.width+iprects[j].width;
iprects[j]=null;
argRects[j]=null;
continue;
}
currect.x1=prvrect.x1;
currect.y1=prvrect.y1;
currect.width=currect.width+prvrect.width;
if(prvrect.y1-prvrect.height<=currect.y1-currect.height)
{
prvrect.y1=currect.y1-currect.height;
prvrect.height=prvrect.height-currect.height;
}
argRects[i]=currect;
}
for(var j=i+1;j<argRects.length;j++)
{
if(argRects[j]==null)
continue;
var nxtrect=argRects[j];
if(nxtrect.y1!=currect.y1)
continue;
if(iprects[j].height<iprects[i].height)
break;
if(iprects[j].height==iprects[i].height && j==i+1)
{
currect.width=currect.width+iprects[j].width;
iprects[j]=null;
argRects[j]=null;
continue;
}
currect.width=currect.width+iprects[j].width;
if(nxtrect.y1-nxtrect.height<=currect.y1-currect.height)
{
nxtrect.y1=currect.y1-currect.height;
nxtrect.height=nxtrect.height-currect.height;
}
argRects[i]=currect;

}
}

oprects=argRects;
recCntr=0;
drawOp();
}
function drawOp()
{
var argRects=oprects;
if(oprects==null)
return;
var i=recCntr;
if(argRects[i]!=null)
{
objRect=argRects[i];
var xc=new Array();
var yc=new Array();
xc[0]=objRect.x1;
yc[0]=objRect.y1+opShft;
xc[1]=objRect.x1+objRect.width;
yc[1]=objRect.y1+opShft;
xc[2]=objRect.x1+objRect.width;
yc[2]=objRect.y1-objRect.height+opShft;
xc[3]=objRect.x1;
yc[3]=objRect.y1-objRect.height+opShft;
xc[4]=objRect.x1;
yc[4]=objRect.y1+opShft;
clr=clr1;
drawRect(xc,yc);
dispRecIndex((xc[0]+xc[1])/2,(yc[0]+yc[2])/2,(i+1));
}
else
{
var divdisp=document.getElementById('div_recIndx');
divdisp.style.display='none';
divdisp.innerText='';
}
recCntr++;
if(recCntr<=argRects.length)
setTimeout('drawOp();',optmr);
}
</script>

<script type="text/javascript" language="javascript">
function IsNumber(argText)
{
var nums='0123456789';
for(i=0;i<argText.length;i++)
{
if(nums.indexOf(argText.charAt(i))==-1)
return false;
}
return true;
}

var clr="red";
var clr1='red';
var clr2='green';
var clr3='blue';
var strk=2;
function drawRect(xc,yc)
{
jg.setStroke(strk);
jg.setColor(clr);
jg.drawPolygon(xc,yc);
jg.paint();
}

function findPosition(element)
{
var left = 0;
var top = 0;

if (element != null)
{
while (element.offsetParent)
{
left += element.offsetLeft;
if (element.offsetParent.scrollLeft) {left -= element.offsetParent.scrollLeft; }
top += element.offsetTop;
if (element.offsetParent.scrollTop) { top -= element.offsetParent.scrollTop; }
element = element.offsetParent;
}
left += element.offsetLeft + document.body.scrollLeft - document.body.clientLeft + 7;
top += element.offsetTop + document.body.scrollTop - document.body.clientTop;
}

return [left,top];
}

</script>
<script type="text/javascript" language="javascript">
function DisplayText(argText)
{
var obj=document.getElementById('div_map');
var divdwn=document.getElementById('div_download');
divdwn.style.display='block';
divdwn.innerText=argText;
var crd=findPosition(obj);
divdwn.style.left=crd[0];
divdwn.style.top=crd[1]+40;
document.getElementById('btnDisp').style.display='block';
}
</script>


<table id="maintable" style="width:800px;">
<tr class="tr_header">
<td style="width:40%;text-align:right;">Number of Input Rectangles :</td><td><input type="text" id="txtRects" /> 
</td>
</tr>
<tr>
<td class="tr_header" style="text-align:center;" colspan="2">
<input type="button" value="Generate Rectangles" class="cssbutton" style="width:200px" onclick="generaterectangles_clk();"/>
<input type="button" value="Generate Output" class="cssbutton" style="width:200px;" onclick="generateoutput_clk();"/>
 
</td>

</tr>
<tr>
<td colspan="2">
 <br />
<div id="div_map" style="width:800px;height:600px;border: 3px solid #ccc; " >

</div>
</td></tr>
</table>
<div id="div_download" class="div_down" style="position:absolute;height:500;display:none"></div>
<div id="div_recIndx" style="position:absolute;height:50;display:none"></div>
</body>
</html>

Auto amount format using java script

I would like to share my java script function that validates user input while entering amount in a specific amount field text box.
Things to validate
1) Is it always positive amount?
2) Should not allow user to enter characters other than (0123456789-.).
3) Should not allow user to type “.”, if value in text box already has “.”.
4) Should not allow user to type “-”, if value in text box already has “-”.
5) Should insert “-“at zero (0) index when user types “-“at index other than zero.


HTML Page:
<!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" language="javascript">
//list of characters that are to be allowed for a valid double value (either positive or negative)
var PosDoubleChars=".0123456789";
var NegDoubleChars="-.0123456789";
//function that add's events to the given text box control to handle it for amount validations
function AmountControl(obj,msg,blnNeg)
{
//Checking if textbox control should allow negative or positive double values
if(blnNeg)
AllowNegDouble(obj);
else
AllowPosDouble(obj);
//setting on focus out event to automatically format given input anount
obj.onfocusout=function(){ValidateAmount(obj,msg,blnNeg);};
}

function AllowNegDouble(obj)
{
AllowChars(obj,NegDoubleChars);
}

function AllowPosDouble(obj)
{
AllowChars(obj,PosDoubleChars);
}

function AllowChars(obj,argChrs)
{
//adding key press evet to restrict user from entering characters other than mentioned list
//of double characters
obj.onkeypress=function(){return CheckChar(obj,event.keyCode,argChrs);}
}

//checking the character code to allow it.

function CheckChar(obj,kyCd,argChrs)
{
if(argChrs==PosDoubleChars)
{
if(kyCd>=46 && kyCd<=58 )
{
if(kyCd==47)
{
return false;
}
if(kyCd==46)
{
for(var i=0;i<obj.value.length;i++)
{
if(obj.value.charAt(i)=='.')
{
return false;
}
}
}
return true;

}
return false;
}
if(argChrs==NegDoubleChars)
{
if((kyCd>=46 && kyCd<=58) || (kyCd==45))
{
if(kyCd==47)
{
return false;
}
if(kyCd==45)
{
if(obj.value.indexOf('-')!=-1)
{
return false;
}
else
{
obj.value='-'+obj.value;
return false;
}
}
if(kyCd==46)
{
for(var i=0;i<obj.value.length;i++)
{
if(obj.value.charAt(i)=='.')
{
return false;
}
}
}
return true;

}
return false;
}
}

//validating and fomratting amount
function ValidateAmount(obj,msg,blnNeg)
{
obj.value=replaceAll(obj.value,',','');
var amtval=obj.value;
if(amtval=='')
return true;
var numb=obj.value.substr(0,obj.value.indexOf('.'));
if(numb.length<=16)
obj.value=FormatAmount(parseFloat(obj.value).toFixed(4));
if(obj.value=="NaN")
obj.value="0.00";
return true;
}
//to replace specific character with speific character in given input string
function replaceAll(wrd,frm,to)
{
var Char;
var fnl='';
for (i = 0; i < wrd.length ; i++)
{
if (wrd.charAt(i)==frm)
{
fnl+=to;
}
else
fnl+=wrd.charAt(i);
}
return fnl;
}
//auto formatting
function FormatAmount(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
</script>
</head>
<body>
Amount : <input type="text" id="txtAmount" />
<script>
//I am calling the above created function saying ‘txtAmount’ as amount control //that should handle all above validations.
//It should allow negative decimals as I said true
AmountControl(document.getElementById('txtAmount'),'Please enter valid amount',true);
</script>
</body>

</html>
UI :



Intput:





1) It it allowing me to enter negative value but if once"-" is typed in middle it is automatically getting inserted at beginning and not allowing to type “-“ again if the amount is already negative.
2) It is allowing me to type "." But if amount is already having decimal it is not allowing to type “." again if the amount is already negative.

3) Not allowing me to type characters other than specified (0123456789-.).

4) Automatically formatting amount by rounding off to 4 decimals if user focuses out from the amount text box.
Output:




How to draw layout of a rectangular graph using Javascript ?

Please refer
Draw line using third party java script file
As explained in above post that the third party java script file makes our task very easier to draw objects.
Now by using this java script file, I would like to share my HTML page and java script code to generate below.
Output:




Note : This is a basic HTML page, so it is not specific to technology
Input :-
User enters number of rectangles in input text box and clicks on “Generate rectangles”, to generate random rectangles.
It should generate mentioned number of rectangles with random height and width but base lined bottoms (similar to a graph).



When user clicks on “Generate button” giving number of input rectangles as 10.



Now output: When user clicks on Display Layout, we should draw only the outline or layout of the given input graph.



Note:
If you would like to copy the below HTML page to run, Make sure that the third party graphics JavaScript file is downloaded into your machine and placed in this application folder where you are creating this HTML page.
Down third party JavaScript file by clicking here
wz_jsgraphics.zip download

HTML File :

<!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>Rectangles</title>
<link rel="stylesheet" type="text/css" href="Styles/Stylesheet.css" />
</head>
<body>
<div id="Canvas" style="position:relative;height:5px;width:5px;"></div>
<script type="text/javascript" language="javascript" src="wz_jsgraphics.js"></script>
<script type="text/javascript" language="javascript">
var jg = new jsGraphics("Canvas"); // Use the "Canvas" div for drawing
</script>
<script type="text/javascript" language="javascript">
var orgX=50;
var orgY=200;
var minWdth=20;
var minHght=30;
var maxWdth=60;
var maxHght=120;
var rndFactor=10;
var lnCntr=0;
var tmr=50;
var iprects=null;
var argCnt;
var inpCntr=0;
var rects=new Array();
var ipTmr=50;
var optmr=50;
var recCntr=0;
function rect()
{
var width;
var height;
var id;
var x1;
var y1;
}
function generaterectangles_clk()
{
var txtRec=document.getElementById('txtRects');
if(txtRec.value=='')
{
alert('Please enter number of rectangles to generate');
txtRec.focus();
return;
}
if(!IsNumber(txtRec.value))
{
alert('Please enter numeric value');
txtRec.focus();
return;
}
var numRects=txtRec.value;
if(numRects<3 || numRects>30)
{
alert('Number of rectangles to generate should be between 3 and 30');
txtRec.focus();
return;
}
orgX=50;
orgY=400;
argCnt=numRects;
inpCntr=0;
rects=new Array();
GenerateRects();
}

function GenerateRects()
{
inpCntr++;
if(inpCntr<=argCnt)
{
var rand_no;
var recWth,recHgt;
rand_no = Math.random();
recWth=Math.floor(minWdth+(maxWdth-minWdth)*rand_no);
recHgt=Math.floor(minHght+(maxHght-minHght)*rand_no);
var objRect=new rect();
objRect.width=recWth;
objRect.height=recHgt;
objRect.id=(inpCntr);
rects[rects.length]=objRect;
DefineRects(rects);
setTimeout('GenerateRects();',ipTmr);
}
else
{
var divdisp=document.getElementById('div_recIndx');
divdisp.style.display='none';
divdisp.innerText='';
}
}
function dispRecIndex(x1,y1,txt)
{
var divdisp=document.getElementById('div_recIndx');
divdisp.style.display='block';
divdisp.innerText=txt;
divdisp.style.left=x1;
divdisp.style.top=y1;
}
function DefineRects(argRects)
{
jg.clear();
var x1=orgX;
var y1=orgY;
var buf=5;
var crd=findPosition(document.getElementById('div_map'));
var maxY=crd[1]-buf;
var maxX=document.getElementById('div_map').offsetWidth+crd[0]-buf;
var minY=crd[1]-document.getElementById('div_map').offsetHeight;
var minX=crd[0];
var objRect=new rect();
for(i=0;i<argRects.length;i++)
{
objRect=argRects[i];
if(x1<maxX && x1>minX)
{
objRect.x1=x1;
objRect.y1=y1;
x1+=objRect.width;
}
else
{
for(j=i;j<argRects.length;j++)
argRects[j]=null;
break;
}
if(y1<maxY && y1>minY)
{
objRect.y1=maxY;
}
argRects[i]=objRect;
}
iprects=argRects;
for(i=0;i<argRects.length;i++)
{
if(argRects[i]==null)
break;
objRect=argRects[i];
var xc=new Array();
var yc=new Array();
xc[0]=objRect.x1;
yc[0]=objRect.y1;
xc[1]=objRect.x1+objRect.width;
yc[1]=objRect.y1;
xc[2]=objRect.x1+objRect.width;
yc[2]=objRect.y1-objRect.height;
xc[3]=objRect.x1;
yc[3]=objRect.y1-objRect.height;
xc[4]=objRect.x1;
yc[4]=objRect.y1;
clr=clr1;
dispRecIndex((xc[0]+xc[1])/2,(yc[0]+yc[2])/2,(i+1));
drawRect(xc,yc);
}
}



</script>

<script type="text/javascript" language="javascript">
function IsNumber(argText)
{
var nums='0123456789';
for(i=0;i<argText.length;i++)
{
if(nums.indexOf(argText.charAt(i))==-1)
return false;
}
return true;
}

var clr="red";
var clr1='red';
var clr2='green';
var clr3='blue';
var strk=2;
function drawRect(xc,yc)
{
jg.setStroke(strk);
jg.setColor(clr);
jg.drawPolygon(xc,yc);
jg.paint();
}

function findPosition(element)
{
var left = 0;
var top = 0;

if (element != null)
{
while (element.offsetParent)
{
left += element.offsetLeft;
if (element.offsetParent.scrollLeft) {left -= element.offsetParent.scrollLeft; }
top += element.offsetTop;
if (element.offsetParent.scrollTop) { top -= element.offsetParent.scrollTop; }
element = element.offsetParent;
}
left += element.offsetLeft + document.body.scrollLeft - document.body.clientLeft + 7;
top += element.offsetTop + document.body.scrollTop - document.body.clientTop;
}

return [left,top];
}

</script>
<script type="text/javascript" language="javascript">
function DisplayText(argText)
{
var obj=document.getElementById('div_map');
var divdwn=document.getElementById('div_download');
divdwn.style.display='block';
divdwn.innerText=argText;
var crd=findPosition(obj);
divdwn.style.left=crd[0];
divdwn.style.top=crd[1]+40;
document.getElementById('btnDisp').style.display='block';
}
</script>

<script type="text/javascript" language="javascript">
function rect()
{
var x1,y1,x2,y2,x3,y3,x4,y4;
}
function GetRectangles()
{
if(iprects==null)
return;
var rectCrds=new Array();
for(i=0;i<iprects.length;i++)
{
var objRect=iprects[i];
var objrect=new rect();
objrect.x3=objRect.x1;
objrect.y3=objRect.y1-objRect.height;
objrect.x2=objRect.x1+objRect.width;
objrect.y2=objRect.y1;
objrect.x1=objrect.x3;
objrect.y1=objrect.y2;
objrect.x4=objrect.x2;
objrect.y4=objrect.y3;
rectCrds[i]=objrect;
}
return rectCrds;
}
function sortRects(rects)
{
for(var c=0;c<rects.length;c++)
{
var rect=rects[c];
for(var k=c+1;k<rects.length;k++)
{
var tmprect=rects[k];
if(tmprect.x1<rect.x1)
{
rects[c]=tmprect;
rects[k]=rect;
}
}
}
return rects;
}
function DisplayLayout()
{
lnCntr=0;
var rectCrds=GetRectangles();
rectCrds=sortRects(rectCrds);
var xc=new Array();
var yc=new Array();
var cnt=-1;
var prevRect=null;
var nextRect=null;
for(var c=0;c<rectCrds.length;c++)
{
var actRec=rectCrds[c];
if(c+1==rectCrds.length)
nextRect=null;
else
nextRect=rectCrds[c+1];
if(c==0)
{
cnt++;
xc[cnt]=actRec.x1;
yc[cnt]=actRec.y1;
cnt++;
xc[cnt]=actRec.x3;
yc[cnt]=actRec.y3;
if(nextRect!=null && nextRect.x1<actRec.x4)
{
cnt++;
xc[cnt]=nextRect.x1;
yc[cnt]=actRec.y3;
}
else
{
cnt++;
xc[cnt]=actRec.x4;
yc[cnt]=actRec.y4;
}
}
if(nextRect!=null)
{
if((nextRect.x1/actRec.x2)==1 && (actRec.y2/nextRect.y1)==1)
{
cnt++;
xc[cnt]=nextRect.x3;
yc[cnt]=nextRect.y3;
cnt++;
xc[cnt]=nextRect.x4;
yc[cnt]=nextRect.y4;
}
else
{

if(nextRect!=null)
{

if(nextRect.x3==actRec.x4)
{
cnt++;
xc[cnt]=nextRect.x3;
yc[cnt]=nextRect.y3;
cnt++;
xc[cnt]=nextRect.x4;
yc[cnt]=nextRect.y4;
}
else if(nextRect.x3<actRec.x4)
{
if(nextRect.y3<actRec.y3)
{
xc[cnt]=nextRect.x3;
yc[cnt]=actRec.y3;
cnt++;
xc[cnt]=nextRect.x3;
yc[cnt]=nextRect.y3;
cnt++;
xc[cnt]=nextRect.x4;
yc[cnt]=nextRect.y4;
}
else
{
cnt++;
xc[cnt]=actRec.x4;
yc[cnt]=actRec.y4;
if(actRec.x4<nextRect.x4)
{
cnt++;
xc[cnt]=actRec.x4;
yc[cnt]=nextRect.y3;
cnt++;
xc[cnt]=nextRect.x4;
yc[cnt]=nextRect.y4;
}
else
{
cnt++;
xc[cnt]=actRec.x2;
yc[cnt]=actRec.y2;
c++;
}

}
}
else
{
if(prevRect!=null && prevRect.x2>actRec.x2)
{
cnt++;
xc[cnt]=actRec.x2;
yc[cnt]=prevRect.y3;
cnt++;
xc[cnt]=nextRect.x1;
yc[cnt]=prevRect.y3;
}
else
{
cnt++;
xc[cnt]=actRec.x2;
yc[cnt]=actRec.y2;
cnt++;
xc[cnt]=nextRect.x1;
yc[cnt]=nextRect.y1;
}
cnt++;
xc[cnt]=nextRect.x3;
yc[cnt]=nextRect.y3;
cnt++;
xc[cnt]=nextRect.x4;
yc[cnt]=nextRect.y4;

}


}

}
}
else
{
if(prevRect!=null && actRec.x2>prevRect.x2)
{
cnt++;
xc[cnt]=actRec.x2;
yc[cnt]=actRec.y2;
}
}
prevRect=actRec;

}
cnt++;
xc[cnt]=xc[0];
yc[cnt]=yc[0];
lyx=xc;
lyy=yc;

drawLines();
}
var lyx=new Array();
var lyy=new Array();
var lyclr="black";
var lystrk=4;
function drawLines()
{
jg.setColor(lyclr);
jg.setStroke(lystrk);
jg.drawLine(lyx[lnCntr],lyy[lnCntr],lyx[lnCntr+1],lyy[lnCntr+1]);
lnCntr++;
jg.paint();
if(lnCntr<lyx.length)
{
setTimeout("drawLines()",tmr);
}
}

</script>
<table id="maintable" style="width:800px;">
<tr class="tr_header">
<td style="width:40%;text-align:right;">Number of Input Rectangles :</td><td><input type="text" id="txtRects" /> 
</td>
</tr>
<tr>
<td class="tr_header" style="text-align:center;" colspan="2">
<input type="button" value="Generate Rectangles" class="cssbutton" style="width:200px" onclick="generaterectangles_clk();"/>
 
<input type="button" value="Display Layout" id="btnLayout" onclick="DisplayLayout();" style="width:200px" class="cssbutton"/>
</td>

</tr>
<tr>
<td colspan="2">
 <br />
<div id="div_map" style="width:800px;height:600px;border: 3px solid #ccc; " >

</div>
</td></tr>
</table>
<div id="div_download" class="div_down" style="position:absolute;height:500;display:none"></div>
<div id="div_recIndx" style="position:absolute;height:50;display:none"></div>
</body>
</html>

How to draw lines using java script?

I have goggled about this and found an excellent third party JavaScript file which is when referred helps to create a line or poly line (continuous lines with start and end point) very easily.
Please click on this link to down load Third party JavaScript file.
wz_jsgraphics.zip download

Please click on this link to explore the members this third party javascript file has
wz_jsgraphics members

Ex:-

I would like to write an HTML file that draws a line on button click using above down loaded JavaScript file.
Note:
If you would like to copy the below HTML page to run, Make sure that the third party graphics JavaScript file is downloaded into your machine and placed in this application folder where you are creating this HTML page.
Down third party JavaScript file by clicking here
wz_jsgraphics.zip download

Html File :
<!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>Line</title>
</head>
<body>
<div id="Canvas" style="position:relative;height:5px;width:5px;"></div>
<script type="text/javascript" language="javascript" src="wz_jsgraphics.js"></script>
<script type="text/javascript" language="javascript">
var jg = new jsGraphics("Canvas"); // Use the "Canvas" div for drawing
function btn_Draw_Clk()
{
jg.setStroke(2);
jg.setColor('red');
jg.drawLine(10,50,300,200);
jg.paint();
}
</script>

<input type="button" value="Draw Line" id="btnDraw" onclick="btn_Draw_Clk();" />
<div id="div_map" style="width:800px;height:1000px;border: 3px solid #ccc; " >

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

User interface:




When user clicks on the “Draw Line” button:







There is nothing great on my side to draw a line :), but I was just referring the third party JavaScript file. We can also draw many other objects like rectangle, polygon, point, eclipse, circle.

I would like to share my more work examples using this third party in next posts.

Friday, March 13, 2009

Session Timeout problem for Long running processes

There could multiple functionalities or processes in a business or multiple businesses with multiple processes that could run for a very long time.
So if these kinds of business are accessed using web server, definitely session time out could create some problems.
To avert these session time outs, I would like to propose a solution that could be 100% effectual if the web application runs on Intranet.
Mostly long running process deal with database, so I would like to go on by considering the below system or level of communication that happens.



Since, web server halts the response until the records are completely inserted into the database.user may experience session time out after some time gap.
To avoid this, solution I believe that could be better for LAN based web applications is



We cannot do this for Internet as it is not really good option to open thread for each world wide request.

Wednesday, March 11, 2009

Oracle procedure to generate records as per binary tree.

We are aware about binary tree structure which looks like



So each node in this binary tree has its respective Childs (2).
We can generate these relations among nodes as database records.
For example:
Node 7 has Node 14 and Node 15 has child nodes, so
The table should have



Step1)
I have created a table saying “tree”.

CREATE TABLE TREE (
PRNT NUMBER,
CHLD NUMBER);
Where PRNT column holds the parent node number and CHLD holds child node number.
Step 2)
I have created an oracle procedure which expects “argMaxLevel” as input number.
This is to generate the nodes of a binary tree to certain level, that is





Oracle procedure
CREATE OR REPLACE PROCEDURE Createchlds(argMaxLevel IN NUMBER)
AS
BEGIN
DELETE FROM TREE;
FOR i IN 2 .. POWER(2,(argMaxLevel))-1
LOOP
INSERT INTO TREE VALUES(FLOOR(i/2),i);
END LOOP;
COMMIT;
END;
/


Step 3)
I said
Exec Createchlds(20), which should then generate nodes to level 20
And number of nodes generated are 108575 (Power(2,20))-1.

Output:-



You can observe there are 1 record missing
1) That record is node 1 which is not inserted as there is no associated parent record to point.




The last child record should be (power(2,20)-1) which is 1048575 and it is perfect from above screen shot.
The record with maximum child node is 1048575

Tuesday, March 10, 2009

Sql query to get records associated to a node in tree

I have seen few guys querying regarding this kind of stuff in orkut communities.
I found this has a solution to resolve.
Query is like
Example :-




It is very similar to chain marketing.
The below sql functions help us to get the associated child nodes for the given node.
Step1:
I have created a table saying “tree”.

CREATE TABLE TREE (
PRNT NUMBER,
CHLD NUMBER);
Test data :





Step 2:
My sql function
CREATE OR REPLACE FUNCTION Getchilds(argC1 IN VARCHAR)
RETURN VARCHAR IS
CURSOR c1 IS SELECT chld FROM TREE WHERE prnt=argC1;
tmpChld VARCHAR(10);
tmpReturn VARCHAR(100);
tmpSubChilds VARCHAR2(100);
BEGIN
OPEN c1;
tmpReturn:=NULL;
LOOP
FETCH c1 INTO tmpChld;
EXIT WHEN c1%NOTFOUND;
IF(tmpReturn IS NULL) THEN
tmpReturn:=tmpChld;
ELSE
tmpReturn:=tmpReturn||','||tmpChld;
END IF;
tmpSubChilds:=Getchilds(tmpChld);
IF(tmpSubChilds IS NOT NULL) THEN
tmpReturn:=tmpReturn||','||tmpSubChilds;
END IF;
END LOOP;
RETURN tmpReturn;
END;
/


I am using recursion technique here to get the Childs associated to the current node.


Output:-
Sql Query

select Getchilds(1) as Childs from dual




select Getchilds(2) as Childs from dual



Monday, February 23, 2009

How to get Nth maximum value using sql query?

Please refer
To find 2nd maximum value using sql query in Prog. Finidngs .

I would like to take the same table considered in above link to find Nth maximum value.

Let us consider a database table named “Test” and which has a column named “C1”.
Let the data type of C1 be Number
Script:-

CREATE TABLE test
(
c1 NUMBER
)
I have inserted some random data using
INSERT INTO TEST
SELECT ROUND(dbms_random.value(1,1000),0) FROM dual
Multiple times to insert multiple records.
I have inserted 66 records into this test table



Data (first 30 records)



So we can observe that there are many number of records among which the record with maximum value of C1 with my test data is
select max(c1) from test
983




Now my intention is to find a record whose c1 value should be the highest nth value.
Query:-
I would like to get the 10th highest value of C1 from test table highlighted in below screen shot.
SELECT * FROM TEST ORDER BY c1 DESC




So,
SELECT c1 FROM
(SELECT ROWNUM AS MAXINDEX,c1 FROM
(SELECT * FROM TEST ORDER BY c1 DESC)) WHERE MAXINDEX=10
helps me to get the Nth maximum value.
Innermost query gives me set of records from Test table in descending order of C1 column, the next inner query helps to identify the ordered records based on “Rownum”.
Using this rownum, external query can identify specific record at Nth position.
My test data which has 10th maximum value is
853
So i am getting 10th highest value from the column of the table.


How to get second maximum value using sql query?

Let us consider a database table named “Test” and which has a column named “C1”.
Let the data type of C1 be Number
Script:-

CREATE TABLE test
(
c1 NUMBER
)
I have inserted some random data using
INSERT INTO TEST
SELECT ROUND(dbms_random.value(1,1000),0) FROM dual
Multiple times to insert multiple records.
I have inserted 66 records into this test table



Data (first 30 records)



So we can observe that there are many number of records among which the record with maximum value of C1 with my test data is
select max(c1) from test
983




Now my intension is to find a record whose c1 value is second highest value.
Query:-
Inner query gives the maximum value available which is 983, so now i am saying to find max value again but whose value should be less than 983 (value from inner query).
Obviously, it is next maximum value.
SELECT MAX(c1) FROM TEST where c1<(SELECT MAX(c1) FROM TEST)
946
So i am getting second highest value from the column of the table.


Progress bar in windows applications .NET.

.NET frame work supports few classes that help to place Progress bar in User Interface of windows applications.




I am creating a windows form that displays this progress bar.
User interface (Windows form) :




Code :










using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace DeleteSvn
{
public partial class frmPrgs : Form
{
public frmPrgs()
{
InitializeComponent();
}

private void btnStart_Click(object sender, EventArgs e)
{
//Get input counter value
intCounter = Convert.ToInt32(txtTime.Text);
//set this counter value as maximum value for the progress bae
prg.Maximum = intCounter;
//start a thread that sleeps for every 1 second and updates the progress bar
//to next step after each second
Thread objThread = new Thread(this.RunThread);
//start the thread
objThread.Start();
}
int intCounter = 0;
delegate void UpdPrcs(string strStatusint,int intStep);
private void UpdateProcess(string strStatus, int prcStep)
{
if (InvokeRequired)
{
BeginInvoke(new UpdPrcs(this.UpdateProcess), new object[] { strStatus,prcStep});
return;
}
//Updating the components available in wodnows form from the thread
prg.Value=prcStep;
lblStaus.Text = "Status : " + strStatus;
if (prcStep == intCounter)
{
prg.Value = 0;
lblStaus.Text = "Done!";
MessageBox.Show("Done!");
}
}
private void RunThread()
{
int i = 0;
//increment counter and update UI with the status of counter and progress bar
while (i < intCounter)
{
i++;
UpdateProcess(i + " / " + intCounter, i);
Thread.Sleep(1000);
}

}
}
}
Output:-

When I click on start button after giving value as 10,
So it increments progress bar for each second and when time reaches 10 seconds progress bar is done with 100% and displays message box.










How to implement sorting using .NET Grid view.

ASP.NET Grid view control helps developer to implement technique of sorting a column very easily and effectively.
Grid view has an attribute saying “AllowSorting” which is Boolean and when set to true enables sorting functionality for the grid.
I would like to create a asp.net page that has
1) Text box (Expecting count from user to generate random number from 1 to 100).
2) Button (User when clicks on the button after entering count in the text box, it generates random numbers and bind to grid view).
3) Grid view to display generated random numbers and provide sorting technique.
My aspx page



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

}
protected void grdSort_Sorting(object sender, GridViewSortEventArgs e)
{
BindGrid(e.SortExpression,(e.SortDirection==SortDirection.Ascending)?"Asc":"Desc");
}
private void BindGrid(string strSortExp,string strSortDire)
{
int intCount = Convert.ToInt32(txtCount.Text);
DataTable dt = Session["DT"] as DataTable;
if (dt == null)
{
Random objRandom = new Random();
DataRow dRow = null;
dt = new DataTable();
dt.Columns.Add(new DataColumn("Num", System.Type.GetType("System.Int32")));
for (int i = 1; i < intCount; i++)
{
dRow = dt.NewRow();
dRow["Num"] = objRandom.Next(100);
dt.Rows.Add(dRow);
}
Session["DT"] = dt;
}
DataView objView = new DataView(dt);
objView.Sort= strSortExp + " " + strSortDire;
grdSort.DataSource = objView;
grdSort.DataBind();
}
private void BindGrid()
{
int intCount = Convert.ToInt32(txtCount.Text);
DataTable dt = Session["DT"] as DataTable;
if (dt == null)
{
Random objRandom = new Random();
DataRow dRow = null;
dt = new DataTable();
dt.Columns.Add(new DataColumn("Num", System.Type.GetType("System.Int32")));
for (int i = 1; i < intCount; i++)
{
dRow = dt.NewRow();
dRow["Num"] = objRandom.Next(100);
dt.Rows.Add(dRow);
}
Session["DT"] = dt;
}
grdSort.DataSource = dt;
grdSort.DataBind();
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
Session["DT"]=null;
BindGrid();
}
}
Aspx page:

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

<!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>Sorting</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table><tr><td>
Count :
</td> <td><asp:TextBox ID="txtCount" runat="server"></asp:TextBox></td></tr>
<tr><td> </td><td><asp:Button ID="btnGenerate" runat="server" Text="Generate" OnClick="btnGenerate_Click" /></td></tr>
<tr><td colspan="2">
<asp:GridView ID="grdSort" runat="server" AllowSorting="true" OnSorting="grdSort_Sorting">

</asp:GridView>
</td></tr>
</table>
</div>
</form>
</body>
</html>

Output:-









How to read entity value from Xml File .NET?

Please refer regarding entities at
How to create an entity in xml file at Prog. Findings
How to create an entity in xml file using .NET functions at Prog. Findings

As said about entities in above links, each entity defined in an xml file can be identified and referred using entity name.
Ex:-


&Entity1; in an inner text of a xml tag says Desc when it is loaded.

So to read these entity values we can refer them using there respective names.
Below function is to read entity value for a given entity name.
public string GetEntityValue(string strEntityName)
{
if (_xmlDocument != null)
{
return _xmlDocument.DocumentType.Entities.GetNamedItem(strEntityName).InnerText;
}
return String.Empty;
}

Below function is to get Entity name based upon given entity value.

public string GetEntityName(string strEntityValue)
{
string strEntityName = String.Empty;
if (_xmlDocument != null)
{
for (int i = 0; i < _xmlDocument.DocumentType.Entities.Count; i++)
{
if(_xmlDocument.DocumentType.Entities.Item(i).InnerText.Trim()==strEntityValue.Trim())
return _xmlDocument.DocumentType.Entities.Item(i).Name;
}
}
return strEntityName;
}
Below function is to get a lost all available entities with in an xml file.

public ArrayList GetEntityNames()
{
ArrayList objListEntities = new ArrayList();
if(_xmlDocument!=null)
{
for (int i = 0; i < _xmlDocument.DocumentType.Entities.Count; i++)
{
objListEntities.Add(_xmlDocument.DocumentType.Entities.Item(i).Name);
}
objListEntities.Sort();
}
return objListEntities;
}

This function returns array list which can further be used to bind list of values to drop down list.

Friday, February 20, 2009

How to create entity in an Xml file .NET?

Please refer
Entity in Prog.Findings

.NET frame work has provided classes and methods which can be used to create entities in an xml file. I mean to create or delete or update an entity.

Below function is to delete an entity that exists in an xml file.

public void DeleteEntity(string strEntityName,bool blnChkForDependants)
{
if (_xmlDocument != null)
{
XmlDocumentType _oldXmlDocumentType = _xmlDocument.DocumentType;
if(blnChkForDependants)
{
TextReader tr = new StreamReader(FilePath);
if (tr.ReadToEnd().Contains("&" + strEntityName + ";"))
{
tr.Close();
throw new Exception("Sorry you cannot delete this entity, there exists dependants on this " + strEntityName + " entity in xml file");
}
tr.Close();
}
string _strExistingSubSet = _oldXmlDocumentType.InternalSubset;
string _strFromEntity = _strExistingSubSet.Substring(_strExistingSubSet.IndexOf(" int intEntityEndIndex = _strFromEntity.IndexOf(">");
string _strEntityString = _strFromEntity.Substring(0,intEntityEndIndex+1);
_strExistingSubSet = _strExistingSubSet.Replace(_strEntityString, String.Empty);
XmlDocumentType _newXmlDocumentType = _xmlDocument.CreateDocumentType(_oldXmlDocumentType.Name, _oldXmlDocumentType.PublicId, _oldXmlDocumentType.SystemId, _strExistingSubSet);
_xmlDocument.ReplaceChild(_newXmlDocumentType, _oldXmlDocumentType);
_xmlDocument.Save(FilePath);
}
}
Below function is to save an exisiting entity or create new entity in xml file
public void SaveEntity(string strEntityName,string strValue)
{
if (_xmlDocument != null)
{
XmlNode objEntityNode = _xmlDocument.DocumentType.Entities.GetNamedItem(strEntityName);
if (objEntityNode != null)
{
XmlDocumentType _oldXmlDocumentType = _xmlDocument.DocumentType;
string _strExistingSubSet = _oldXmlDocumentType.InternalSubset;
string _strFromEntity = _strExistingSubSet.Substring(_strExistingSubSet.IndexOf(" int intEntityEndIndex = _strFromEntity.IndexOf(">");
string _strEntityString = _strFromEntity.Substring(0, intEntityEndIndex + 1);
_strExistingSubSet = _strExistingSubSet.Replace(_strEntityString,"").Trim();
XmlDocumentType _newXmlDocumentType = _xmlDocument.CreateDocumentType(_oldXmlDocumentType.Name, _oldXmlDocumentType.PublicId, _oldXmlDocumentType.SystemId, _strExistingSubSet);
_xmlDocument.ReplaceChild(_newXmlDocumentType, _oldXmlDocumentType);
}
else
{
XmlDocumentType _oldXmlDocumentType = _xmlDocument.DocumentType;
XmlDocumentType _newXmlDocumentType = _xmlDocument.CreateDocumentType(_oldXmlDocumentType.Name, _oldXmlDocumentType.PublicId, _oldXmlDocumentType.SystemId, _oldXmlDocumentType.InternalSubset + "\n ");
_xmlDocument.ReplaceChild(_newXmlDocumentType, _oldXmlDocumentType);
}
_xmlDocument.Save(FilePath);
}

}

How to add launch condition while preparing set up in Visual studio

Please refer for preparing set up at
Prog. Finidngs (Set up)
I am creating separate project in visual studio editor and choosing an
.exe file for which I am willing to prepare set up.



One of Visual studio configuration properties help to check whether the client machine (which is about to install this .MSI file) has required installations or
Prerequisites software’s to support current installing application.
For example for the set up file which I am preparing now when it gets installed, the machine should have abc.exe file in alphabets folder of Program files.
This is called as launch condition.
I have clicked on the set up project and clicked on “Launch Condition Editor”.



I am adding my launch condition as said before.









Now I am building my solution and installing the set up file created in my set up project folder.



As soon as I click on the set up file created I am getting a message box and not able to install the set up.