Wednesday, October 31, 2007

JavaScript Timers with setTimeout and setInterval Methods

Here, i would like to share with you how to use the JavaScript's settimeout(), clearTimeout(), setInterval() and clearinterval() methods to set timers and create delayed actions.

setTimeout()

The general syntax of window.setTimeout() method is:

setTimeout(expression, timeout);
where expression is the JavaScript code to run after timeout miliseconds have elapsed.
setTimeout() return a numeric timeout ID that can be used to track the timeout. This is most commonly used with the clearTimeout() method.
After setTimeout() is called, execution of the following script will continue normally. The expression in setTimeout() will be run when pass the timeout period.

For example, the following code sets up an alert box to appear after 3 seconds and disable the button when a button is clicked. After 3 seconds, the alert appears. When click the [ok] button of the alert, the button will enable again.
<script language="javascript">
function alertClickHandler()
{
setTimeout('showAlert()', 3000);
document.getElementById("btnClickMe").disabled = true;
}

function showAlert()
{
alert('3 seconds time out');
document.getElementById("btnClickMe").disabled = false;
}
</script>

<input type="button" name="btnClickMe" id="btnClickMe" value="Click me" onclick="alertClickHandler();" />

Try it! Click the button below and wait 3 seconds.



clearTimeout()

The window.clearTimeout() method is used to cancel a timer before it goes off. It's syntax is:
clearTimeout(timeoutId);
where timeoutId is the timeout ID returned from the setTimeout() method call.

For example, the following code sets up an alert box to appear after 3 seconds when a button is clicked, but the visitor can click the same button before the alert appears and cancel the timeout.
<script language="javascript">
var timeoutID = 0;

function alertTimerClickHandler()
{
if (document.getElementById("btnClick").value == "Try click me!")
{
timeoutID = setTimeout('showAlertTimer()', 3000);
document.getElementById("btnClick").value = "Click me to stop the timer!";
}
else
{
clearTimeout(timeoutID);
document.getElementById("btnClick").value = "Try click me!";
}
}

function showAlertTimer()
{
alert('Time out! You did not stop the timer.');
document.getElementById("btnClick").value = "Try click me!";
}
</script>

<input type="button" name="btnClick" id="btnClick" value="Try click me!" onclick="alertTimerClickHandler();" />

Try it! Click the button below to start the timer and click it again within 3 seconds to cancel it.



setInterval()

The setInterval() function is very same to setTimeout() even the their syntax is similar. It's syntax is:
setInterval(expression, interval);
The difference is setTimeout() triggers expression only once but setInterval() keeps triggering expression again and again unless stop it.

clearInterval()

If want to cancel a setInterval(), call clearInterval() method. It's syntax is like below:
clearInterval(intervalId);
where intervalId is the interval ID returned from the setInterval() method call.

Here's a simple example using both setInterval() and clearInterval. When visitor click the button at below, the following code start to count up and display it until visitor click the button again to stop it.
<script language="javascript">
var intervalID = 0;
var count = 0;

function startCountUp()
{
if (document.getElementById("btnClickInterval").value != "Stop count up!")
{
document.getElementById("divCount").innerHTML = count;
intervalID = setInterval('displayCountUp()', 1000);
document.getElementById("btnClickInterval").value = "Stop count up!";
}
else
{
clearInterval(intervalID);
count = 0;
document.getElementById("btnClickInterval").value = "Restart count up!";
}
}

function displayCountUp()
{
count += 1;
document.getElementById("divCount").innerHTML = count;
}
</script>

<div id="divCount" style="font-size: 20px; color: orange;"></div>
<input type="button" name="btnClickInterval" id="btnClickInterval" value="Start count up!" onclick="startCountUp();" />


Try it! Click the button below to start count up and click it again to stop it.

0

Wednesday, October 24, 2007

Import Data from Excel File using VB .NET

The following is the sample code how to query an Excel spreadsheet from an ASP.NET page using VB .NET:

Dim strConn As String
Dim da As OleDbDataAdapter
Dim ds As New DataSet

strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
         "Data Source=C:\test.xls;Extended Properties=""Excel 8.0;"""
da = New OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn)
da.TableMappings.Add("Table", "Excel")
da.Fill(ds)

dataGrid1.DataSource = ds.Tables(0).DefaultView
dataGrid1.DataBind()
da.Dispose()
Note:
   -  The code above is just select data from Sheet1(Worksheet) only.

If you want to select data from first sheet in the Excel workbook, need to get the name of the first sheet first.
To get the name of the first sheet in the Excel workbook, refer code below:
Dim dao_dbE As dao.DBEngine
Dim dao_DB As DAO.Database
Dim strFirstSheetName As String

dao_dbE = New dao.DBEngine
dao_DB = dao_dbE.OpenDatabase("C:\test.xls", False, True, "Excel 8.0;")
strFirstSheetName = dao_DB.TableDefs(0).Name
da0_DB.Close()
Note:
   -  Using code above Microsoft DAO 3.5 Library is needed.
   -  From the Project menu, click References, click Add Reference...
      and then select the Microsoft DAO 3.5 Library to add it.

So, complete code should like below:
Dim strConn As String
Dim da As OleDbDataAdapter
Dim ds As New DataSet
Dim dao_dbE As dao.DBEngine
Dim dao_DB As DAO.Database
Dim strFirstSheetName As String

dao_dbE = New dao.DBEngine
dao_DB = dao_dbE.OpenDatabase("C:\test.xls", False, True, "Excel 8.0;")
strFirstSheetName = dao_DB.TableDefs(0).Name
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
         "Data Source=C:\test.xls;Extended Properties=""Excel 8.0;"""

da = New OleDbDataAdapter("SELECT * FROM [" & _
          strFirstSheetName & "]", strConn)
da.TableMappings.Add("Table", "Excel")
da.Fill(ds)

dataGrid1.DataSource = ds.Tables(0).DefaultView
dataGrid1.DataBind()

da.Dispose()
da0_DB.Close()

Good Luck!!!

Saturday, October 20, 2007

User.Identity.Name Returns Empty String in ASP .NET

If you try to get currently logged on user name with User.Identity.Namein ASP.NET, but the return value is empty string.
The following is syntax accesses this variable in C# .NET:

string strUserName = User.Identity.Name;

This problem occurs because if you use Anonymous Access security to access the .aspx page. This problem can also occurs if you give the Anonymous user access in the <authorization> section of the Web.config file.

Solution:
Check the authentication mode in the Web.config file.

If the authentication mode is Forms-based authentication:
<authentication mode="Forms" />
To solve this problem just deny access to the Anonymous user in the Web.config file, user the following syntax:
<authorization>
   <deny users = "?" /> <!-- This denies access to the Anonymous user -->
   <allow users = "*" /> <!-- This allows access to all users -->
</authorization>

If the authentication mode is Windows-based authentication:
<authentication mode="Windows" />
To solve this problem, use the following steps:

1. Go to Internet Services Manager, right-click the .aspx file or the Web Project folder, and then click Properties.
2. If you clicked Properties for the Web Project folder, click the Directory Security tab. If you clicked Properties for the .aspx file, click the File Security tab.
3. Under Anonymous Access and authentication control, click Edit.
4. In the Authentication methods dialog boc, clear the Anonymous Access check box, and then select either theBasic, the Digist or the Integrated (NT Challenge/Response) check box.
6. Click OK to close both dialog boxes.


Friday, October 19, 2007

Calling Javascript Function from Code Behind(.vb)

This is the function at html page:

<script language="javascript">
   function test(){
      //Add the function code here
   }
</script>

To call this javascript function from code behind(.vb), Use Page.RegisterStartupScriptfunction like the following code:

Dim strScript As string = "<script language='javascript' id='myClientScript'>test();</script>"
Page.RegisterStartupScript("callTest", strScript)