Pages

Thursday, September 4, 2008

How to restrict HTML/Javascript tags using Javascript and ASP.NET

There is a security threat that people use scripting tags into the input fields in order to hack/malfunction the application, you may use the steps described below in order to restrict the user not to enter these kind of tags:

Add a text box in your asp.net page/control

<asp:TextBox ID="txtComments" runat="server"></asp:TextBox>

Then add an attribute for OnClick and OnKeyPress events

txtComments.Attributes.Add("OnClick", "return RestrictHTMLTags();");

Now you've to define the function RestrictHTMLTags in order to restrict the HTML tags

function RestrictHTMLTags()
{
txt_box=document.getElementsByTagName('INPUT');
for (txt_0=0; txt_0 < txt_box.length; txt_0++)
{
if (txt_box[txt_0].type=='text')
{
var str1=parseInt(txt_box[txt_0].value.indexOf('<'))
var str2=parseInt(txt_box[txt_0].value.indexOf('>'))
if (str1 >= 0 || str2 >= 0 )
{
alert("HTML or JavaScript tags are not allowed")
txt_box[txt_0].value='';
txt_box[txt_0].focus();
return false;
}
}
}
return true;
}

That's how you restrict the user not to enter the restricted tags. Waiting for your comments on this article

Wednesday, September 3, 2008

How to format currency value entered in a text box using Javascript and ASP.NET

You might be in a situation where you want to display the value entered by user in a proper currency format e.g. if user entered 10000 and you want to format it like 10,000. In order to do so you've to follow these steps:

First add a text box in your asp.net page/control

<asp:TextBox ID="txtTotal_Amount" runat="server"></asp:TextBox>

Then add an attribute for OnKeyUp and OnKeyPress events

txtTotal_Amount.Attributes.Add("OnKeyUp", "OnCurrencyValueKeyUp(this);");
txtTotal_Amount.Attributes.Add("OnKeyPress", "OnCurrencyValueKeyUp(this);");

Now you've to define the function OnCurrencyValueKeyUp in order to handle the formatting

function OnCurrencyValueKeyUp(input)
{
if(input.value.toString().length == 1 && input.value.toString() == '0')
input.value = input.value.replace('0','');

var num = input.value.replace('.','');
num = input.value.replace(/\,/g,'');
if((!isNaN(num)|| num=='-') && num != '-0')
{
if(num.indexOf('.') > -1)
{
num = num.split('.');
num[0] = num[0].toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'');
if(num[1].length > 2)
{
num[1] = num[1].substring(0,num[1].length-1);
}
input.value = num[0]+'.'+num[1];
}
else
{
input.value = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'') };
}
else
{
input.value = input.value.substring(0,input.value.length-1);
}
input.value = input.value.toString().replace(/\$|\ /g,'');
input.value = input.value.toString().replace('.','');
input.value = input.value .toString().replace('-,','-');

}

That's it, just run your application and try it. Waiting for your comments on this article

Tuesday, July 29, 2008

How to: use Infragistics UltraWebGrid RowEditTemplate using Javascript in ASP.NET 2.0 (C#)

Infragistics UltraWebGrid is an important tool in 'NetAdvantage for ASp.NET' Suite. UltraWebGrid has built in AJAX functionality, along with enhanced performance and improved GUI.

In this article we'll learn how to use UltraWebGrid's RowEditTemplate using JavaScript. But I'll be showing the necessary code to be modified.

You have to register the assembly in the page you wish to use UltraWebGrid using 'Register' Tag

Then you have to add the UltraWebGrid to your page

<igtbl:ultrawebgrid id="UWGItems" runat="server" width="100%" height="150px" browser="Xml" oninitializelayout="UWGItems_InitializeLayout"></igtbl:ultrawebgrid>

In your codefile define the UWGItems_InitializeLayout method

protected void UWGItems_InitializeLayout(object sender, Infragistics.WebUI.UltraWebGrid.LayoutEventArgs e)
{
// The InitializeLayout event is called when the grid binds to data. Many of these
// settings can be set at design time, rather then run time, via the property window.
// For this sample, these properties are set in code so that the settings are more easily visible.

// Turn on addnew, update and delete for the grid
e.Layout.AllowAddNewDefault = AllowAddNew.Yes;
e.Layout.AllowUpdateDefault = AllowUpdate.Yes;
e.Layout.AllowDeleteDefault = AllowDelete.Yes;

//Add the AddNew button
e.Layout.AddNewBox.Hidden = false;
e.Layout.Bands[0].AddButtonCaption = "Add New";
e.Layout.Bands[0].AddButtonToolTipText = "Click here to Add New.";


//// The Primary key field in most cases is an autogenerated number and will not be updated or set by the user. This
//// will prevent user action to modify the value
e.Layout.Bands[0].Columns.FromKey("Sr").AllowUpdate = AllowUpdate.No;

//// The DataKeyField of the Band should be set to PrimaryKey of the underlying table. To set the DataK
e.Layout.Bands[0].DataKeyField = "Sr";


}

In your page's Page_load event you can bind the grid to any data source e.g.

this.UWGItems.DataSource = this.TempDt;
this.UWGItems.DataBind();

Assuming that we've four columns in TempDT:
1) Sr. Serial Number
2) ItemName
3) ItemCode
4) Amount

These columns will be shown in your UltraWebGrid along with the * with each row for row editing and an 'Add New' button at the bottom of the grid. By clicking on '*' or 'Add New' Button will open up the RowEditTemplate which we'll be using later in this article.

Define the RowEditTemplate for your UltraWebGrid by adding the following lines of code to your Grid HTML

<bands>
<igtbl:ultragridband>
<rowedittemplate>
<table border="0" width="100%">
<tbody><tr>
<td colspan="2" align="center">Item Description</td>
</tr>
<tr>
<td align="right">Item Name:</td>
<td align="left"><input id="tmplItemName" size="50"

columnkey="ItemName" type="text"></td>
</tr>
<tr>
<td align="right">Code:</td>
<td align="left"><input id="tmplItemCode" disabled="disabled"

value="821311" size="8" type="text"></td>
</tr>
<tr>
<td align="right">Amount:</td>
<td align="left"><input id="tmplItemAmount" size="18"

columnkey="Amount" type="text"></td>
</tr>
<tr>
<td>
</td>
<td align="left">
<input id="igtbl_reOkBtn" class="button"

onclick="ValidateTemplate();igtbl_gRowEditButtonClick(event);" style="width: 67px;" value="OK"

type="button">
<input id="igtbl_reCancelBtn" class="button"

onclick="igtbl_gRowEditButtonClick(event);" style="width: 67px;" value="Cancel"

type="button">
</td>
</tr>
</tbody></table>
</rowedittemplate>
</igtbl:ultragridband>
</bands>

You may wish to validate the boxes on OK button click, you can define your ValidateTemplate() function and put necessary code according to your requirements

The function call igtbl_gRowEditButtonClick(event); is UltraWebGrid's built in call that will handle the 'OK' or 'Cancel' button click

In between your <displaylayout></displaylayout> tags, you've to add a line which describes some client side functions

<clientsideevents dblclickhandler="DblClick" beforerowtemplateclosehandler="BeforeRowTemplateClose"

afterrowtemplateclosehandler="AfterRowTemplateClose"></clientsideevents>

What happens when a user double clicks on any row or item, our function will just return 1 without doing anything means that there would be no operation in that case

// called when a cell, row label, or column header is double clicked
function DblClick(tableName, itemName)
{
return 1;
}

Our Purpose is to handle the RowEditTemplate using javascript, This following function will be called just before the RowEditTemplate is being closed.
We'll be showing the next serial id and code using javascript, rest of the columns will be mapped automatically

function BeforeRowTemplateClose(gridName,rowId,bSaveChanges)
{
if(bSaveChanges)
{
var ActiveRow = igtbl_getActiveRow(gridName);
var oGrid = igtbl_getGridById(gridName);
var MaxCount=0;
var arr = rowId.split("_");
var ActualRowID = arr[arr.length-1];
var RowsCounter = oGrid.Rows.length;

for(c = 0; c < RowsCounter; c++)
{
var row = oGrid.Rows.getRow(c);
var CounterCell = row.getCell(0);
if(CounterCell.getValue()!=null)
MaxCount=CounterCell.getValue();
else if(CounterCell.getValue()==null && ActualRowID!=c)
oGrid.Rows.remove(c);
}
if(ActiveRow != null)
{
// Obtain the Cell object for Sr Column and Update the Cell value
if(ActiveRow.getCell(0).getValue()==null)
ActiveRow.getCell(0).setValue(MaxCount+1);
// Obtain the Cell object for Code Column and Update the Cell value
ActiveRow.getCell(2).setValue("821311");

}
}
}

if(bSaveChanges):
OK button of RowEditTemplate is clicked

var ActiveRow = igtbl_getActiveRow(gridName);
Get the active row of grid by specifying grid name

var arr = rowId.split("_");
var ActualRowID = arr[arr.length-1];
Split the row ID and get the actual rowID

for(c = 0; c < RowsCounter; c++)
{
var row = oGrid.Rows.getRow(c);
var CounterCell = row.getCell(0);
if(CounterCell.getValue()!=null)
MaxCount=CounterCell.getValue();
else if(CounterCell.getValue()==null && ActualRowID!=c)
oGrid.Rows.remove(c);
}
Loop through the grid till the RowsCounter, traverse through each row go till the last row, get the SerialNumber value and assign it to MaxCount, if the CounterCell's value is null then delete that un-necessary row

if(ActiveRow != null)
{
// Obtain the Cell object for Sr Column and Update the Cell value
if(ActiveRow.getCell(0).getValue()==null)
ActiveRow.getCell(0).setValue(MaxCount+1);
// Obtain the Cell object for Code Column and Update the Cell value
ActiveRow.getCell(2).setValue("821311");

}
Check if the ActiveRow is not null and active row's cell 0 has null value then place the new SerialNumber by adding 1 to MaxCount we already calculated.
We may wish to display some static code to the ItemCode column, for that purpose we've to place that value to active row's cell no. 2 which is the ItemCode column.

Now you may wish to display the total of amounts entered in the Amount column, for this you will be writing javascript

function 'AfterRowTemplateClose'
function AfterRowTemplateClose(tableName,itemName)
{
var oGrid = igtbl_getGridById(tableName);
var RowsCounter = oGrid.Rows.length;
//loop through grid values to calculate the total
var Amount=0;
for(c = 0; c < RowsCounter; c++)
{
var row = oGrid.Rows.getRow(c);
if(row.getCell(1).getValue()!=null)
{
var AmountCellVal = row.getCell(3).getValue();
Amount += parseInt(GetAmount(AmountCellVal));
}
}
// Obtain the txtTotalAmount textbox and update its value
document.getElementById('<%=txtTotalAmount.ClientID.ToString()%>").value=Amount;
}

Get the grid using
var oGrid = igtbl_getGridById(tableName);
Get the row counte using
var RowsCounter = oGrid.Rows.length;
Loop through the grid, find the last column of the grid which is infact the amount column, add all the amounts
for(c = 0; c < RowsCounter; c++)
{
var row = oGrid.Rows.getRow(c);
if(row.getCell(1).getValue()!=null)
{
var AmountCellVal = row.getCell(3).getValue();
Amount += parseInt(GetAmount(AmountCellVal));
}
}

// Obtain the txtTotalAmount textbox and update its value
document.getElementById('<%=txtTotalAmount.ClientID.ToString()%>").value=Amount;

Waiting for your comments on this article

Thursday, July 17, 2008

Working with Anthem.NET

Anthem.NET is an open source cross platform AJAX toolkit for the ASP.NET 1.1 and 2.0 development environment. Anthem.NET controls library has built in AJAX functionality and all credit goes to Jason Diamond who had the great idea to encapsulate AJAX functionality into regular Web Form controls. By using the Anthem.NET controls we can get rid of the typical postbacks.

All you have to do is download the Anthem.NET project source code from the following URL:

http://anthemdotnet.com/downloads.aspx

This source code includes different projects for VS.NET 2003, 2005, Examples and Extensions.

There are multiple ways to include Anthem.NET into your project:

1) You can add a reference to your project by browsing to the Anthem-2005 (if we take an example to integrate the Anthem.NET in our VS.NET 2005 project) and open the file named 'Anthem-2005.csproj'

2) Alternatively you can seperately compile the Anthem-2005, generate the dll, copy and place it in your bin directory.

Now what happens if we want to use those Anthem.NET controls to our ASP.NET Web Application.

First of all you have to register that Anthem assembly to your page using

<%@ Register TagPrefix="anthem" Namespace="Anthem" Assembly="Anthem" %>

Add an anthem:Button to your page:



Add a label to your page that would be used to show the current time without a postback whenever the above button is clicked



The attribute 'AutoUpdateAfterCallBack="true"' updates the control after every callback

Now add an event handler attribute for button's click as you do with your normal ASP.NET Button



Do necessary coding in the event handler

void btnDisplayTime_Click(object sender, EventArgs e)
{
lblDisplayTime.Text = DateTime.Now.ToString();
}

By running your web application you can see the result that the lable will be updated without having any postback. Working with Anthem.NET is as easy as your normal ASP.NET controls library.

There is a problem that sometimes when you want to use Response.Redirect with Anthem.NET Controls, it doesnt work, Jason Diamond has given a way around for this problem.

You can use the following line of code in order to change the location of window.

Anthem.Manager.AddScriptForClientSideEval("window.location = 'http://www.google.com';");


Waiting for your comments on this article