Friday, September 18, 2009

Refreshing page after some specific interval

If you have requirement such as you want to refresh your page after every few seconds or minutes, you are reading right blog. I found it very easy to implement. Please go through below example and you will get the exact idea.

Server side code

protected void Page_Load(object sender, EventArgs e)
{
Response.AddHeader("refresh", "5");
}

Client side code

<html>
<head>

<script language="javascript" type="text/javascript">
function fn()
{
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10){
minutes = "0" + minutes
}
if (seconds < 10){
seconds = "0" + seconds
}
document.getElementById("div1").innerHTML = hours + ":" + minutes + ":" + seconds
}
</script>

</head>
<body onload="fn();">
<div>
<div id="div1" />
</div>
</body>
</html>

In the above example I have implemented client side watch, which refreshes every five seconds. The only line of code required to write to submit the page is Response.AddHeader("refresh", "5");, other is just custom logic.

happy coding... :)

Monday, September 14, 2009

Relative path issue with client tags ( ~ is not working )

You can continue using a client tag such as <img>, <link>, etc. with the "~" tilde with below solution.


You just need to use the System.Web.VirtualPathUtility.ToAbsolute("~") method to convert the ~ to the Application Path.


So, if your file is located at "~/images/default.jpg" and you need to specify this path in a client tag like <img>, ASP.NET would not allow you to use this path unless you use a Server Control like <asp:Image>.


To continue using the client tag you can use:
<img src="<%=System.Web.VirtualPathUtility.ToAbsolute("~")%>/images/ default.jpg" />


This would be resolved to "/MyApplication/images/default.jpg" where the first forward slash (/) stands for the WebSite root. Thus, the tilde "~" is effectively resolved to "/MyApplication"


Alternatively, Control.ResolveClientUrl can be used. For example,


<img src='<%= ResolveClientUrl("~/images/default.jpg")%>' />