Thursday, June 14, 2007

How to Handle browser “Back” button using ASP.NET

Handling browser "Back" button using ASP.NET
 
To disable browser "Back" button
 
1) Very first and simplest way to disable the browser back button is  
 
<script language="JavaScript">
  javascript:window.history.forward(0);                     
</script>
 
  Using this user can't use back button from browser to see previous page.
 
2)  Here if user redirect to error page then on the body onload we can call the following function so that user can not use back button at all, here we are redirecting same page again and again.
 
<script language="JavaScript">   
    function DisablingBackFunctionality()
    {
        var URL;
        var i ;
        var QryStrValue;
        URL=window.location.href ;
        i=URL.indexOf("?");
        QryStrValue=URL.substring(i+1);
        if (QryStrValue!='X')
        {
            window.location=URL + "?X";
        }
    }
</script>
  
To close the browser window
 
Following are the alternate to handle browser "Back" button, like if you have an error in your application and you are redirecting to error page now from this error page user should not use browser back button to see the previous page.
We have to close the window by giving some alert error message, below some script to do so
 
1) To close the browser use
 
window.close() OR  this.close()  OR  document.close()
 
2) To close the browser without prompt use
           
window.opener = top;
window.close(); OR this.close()  OR  document.close()
  
3) If you want to give some alert message to close the page and if user click "OK" then close the browser then call following function in body  onload="check_form()"
 
<script language="JavaScript">
      var submitted=false;
      function check_form()
{
            if (submitted == true)
{
  alert ("Form already submitted") ;
  return false;
            }
      else
{
            submitted = true ;
      document.frmError.submit();
window.status ="Session expired. Please restart";
      window.opener = top;
alert("Please close this window.");
      window.close();
      }
      }
</script>
 
4) If you want to close the browser automatically after few second then use following script in your aspx page
 
<script language="JavaScript">
 
   var bloodythief = 5;
    {
      alert("Window will close after 5 second.");
      window.setTimeout("window.close()",bloodythief*1000);
      window.opener = top;
    }
 
  </script>
 
 
5)If you want ot disable browser Referesh or F5 button then use following script in your aspx page
 
    <script>       
  window.history.forward(1);
        document.attachEvent("onkeydown", my_onkeydown_handler);
        function my_onkeydown_handler()
        {
            switch (event.keyCode)
      {
            case 116 : // 'F5'
            event.returnValue = false;
            event.keyCode = 0;
            window.status = "We have disabled F5";
            break;
            }
          }             
      </script>
 
Redirect to login page
 
6) All the above solution not seem to be compatable in other browser (Mozilla,Netscape etc), actually Window.close() function not works properly in others browser.To work in properly in other browser you have to close the parent window then open new window, it's kind of redirecting to login page if session expire.
 
This Supports all browsers.
 
<script language="JavaScript">
   
        function RedirectToLoinPage()
        {
            window.opener=self;
            var URL = window.location.href;
            if (URL.indexOf('Session') == -1)
            {
                alert('Not authorized to view this application.');
            }
            else
            {
                alert('Session expired.');
            }
            window.close();
            window.open('Login.aspx','Login','');
            }
</script>
 
8) Another way to close the browser in other browsers
 
<script language="JavaScript">
function closeMe()
{
var win=window.open("","_self");
win.close();
}
</script>
 
Imp: if the user has disabled JavaScript, then above java script won't work.
When user use "back" button to see previous page and submitting that page again then handle in the code behind also and redirect him to login page.
 
Session.Abandon() method to expire session and check in each page page_load event if (!Session.IsNewSession && Session["UserId"] == null) if session is null then redirect to login page.


Get the Yahoo! toolbar and be alerted to new email wherever you're surfing.

Wednesday, May 09, 2007

How to calculate value with regular expression using C#.NET 2,0 Ex: (A+B) *C

How to calculate value with regular expression using C#.NET 2,0

Some time it require to calculate value with expression
For example if i write (A+B)*C in the textbox, i want some function calculate this value with formula.

For this purpose you can use two DLLs 1) Microsoft.JScript.dll and 2) Microsoft.Vsa.dll
This is available in (Visual Studio 2005 DOTNET version 2.0)

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ folder.

Namespace
using Microsoft.JScript;
using Microsoft.JScript.Vsa;
using Microsoft.Vsa;

Variable
private
static VsaEngine engine = VsaEngine.CreateEngine();

Source Code
public static object Eval(string Expression)
{
try
{
return Microsoft.JScript.Eval.JScriptEvaluate(Expression, engine);
}
catch (Exception x)
{
return "ERROR! " + Expression + x.Message;
}
}

How to Call this function

string val = "10*20+(20-8)"
Eval(val); // this will give result --> 212

val = "(10*20)+(20-8)*9-(90/40)"
Eval(val); // this will give result --> 305.75

How to use PrincipalPermission-Demand in ASP.NET 2.0

How to use PrincipalPermission-Demand Security in ASP.NET 2.0

NameSpace
using
System.Security.Permissions;

Variable
string[] roles = new string[10];

Source Code
protected void Page_Load(object sender, EventArgs e)
{
string user = "TestUser";
System.Security.Principal.IIdentity id = System.Security.Principal.WindowsIdentity.GetCurrent();

if
(!IsPostBack)
{
//System.Collections.Generic.List<string> lstUser = userDetails.GetUserDetails(user);
// User role you can access from database and keep in list or array
roles.SetValue("Admin" , 0);
ViewState["Roles" ] = roles;
}

if (ViewState["Roles"] != null )
roles = (string[])ViewState["Roles"];
System.Threading.Thread.CurrentPrincipal =
new System.Security.Principal.GenericPrincipal (id, roles);
}

[PrincipalPermission principalPerm = new PrincipalPermission (id, roles)]
private void DisplayPDF(string filePath)
{
}

Best link to do ASP.NET 2.0 Security Practices
http://msdn2.microsoft.com/en-us/library/ms998372.aspx

Tuesday, May 08, 2007

How to create LinkButton at runtime in C#.net

How to create LinkButton at runtime in C#.net
Server Side Code
Namespace
using System.IO;
Method
private void CreateLinkToDownload()
{
System.IO.DirectoryInfo dir =
new System.IO.DirectoryInfo("c:\backup\");
FileInfo[] files = dir.GetFiles("*.*");
if (files.Length > 1)
{
for (int count = 0; count < files.Length; count++)
{
//Open the link to download these file
LinkButton btnLnk = new LinkButton();
btnLnk.Text = files [count].ToString() + " <br>";
btnLnk.Visible = true;
btnLnk.CommandName = files [count].ToString();
btnLnk.Command += new CommandEventHandler(this.LinkButton_Click);
btnLnk.ID = arrLink[count].ToString();
// tdDownloadFiles == table defination in the client side with
// runat =server
this.tdDownloadFiles.Controls.Add(btnLnk);
}
}
}
protected void LinkButton_Click(object sender, CommandEventArgs e)
{
StartDownLoad(e.CommandName);
}
private void StartDownLoad(string filePath)
{
try
{
filePath = "C:\backup\"+ filePath;
//To download the file
FileInfo myFile = new FileInfo(filePath);
Response.Clear();
//To display open/save dialog box
Response.AddHeader("Content-Disposition", "attachment; filename=" + myFile.Name );
//Add the length into dialog box header (comment below line if you
// don't want pop up dialog box)
Response.AddHeader("Content-Length", myFile.Length.ToString());
Response.ContentType = "application/octet-stream";
//Response.ContentType = "application/pdf";
//write file into stream
Response.WriteFile(myFile.FullName);
Response.Flush();
Response.End();
}
catch (ThreadAbortException)
{ //ignore this }
catch (Exception Ex)
{ throw Ex; }
}
Client Side Code
<table border="0" id="trDownloadLonk" runat="server" width="100%">
<tr>
<td colspan="2">You can download following file</td>
</tr>
<tr>
<td id="tdDownloadFiles" runat="server" colspan="2"></td>
</tr>
</table>

Monday, May 07, 2007

"Server Application Unavailable" in ASP.NET

Error: "Server Application Unavailable" ASP.NET

Solution: Do the following steps to resolve this error

1) Go to Visual Studio Command prompt
//Stop IIS
2)> iisreset /stop
//Stop the ASP.NET state service if it is running.
3)> net stop aspnet_state
//Delete the ASPNET account.
4)> net user ASPNET /delete
//Create a new ASPNET account with a temporary password.
5)> net user ASPNET 1pass@word /add
//Type 1pass@word when you are prompted for the temporary password."
6)runas /profile /user:ASPNET cmd.exe
//Reregister ASP.NET and the ASPNET account.
// Before this steps start "server" service from Services
7) aspnet_regiis -i
//Restart IIS.
8) iisreset /start

Retrieving the COM class factory ......failed due to the following error: 80040154.

Retrieving the COM class factory for component with CLSID .....failed due to the following error: 80040154.

This error occuer when you reference unregistered DLL in your solution.

Solution: Register you dll using regsvr32.exe utility then add the reference again.

> regsvr32 Mydll.dll /u --For unregister
> regsvr32 Mydll.dll --For register

Hope this will help

Ritesh Kesharwani

Friday, May 04, 2007

Failed to access IIS metabase on XP

"Failed to access IIS metabase" on XP

This error occur when you work with dotnet 2.0, run the follwoing exe for ASPNET account.

>aspnet_regiis -ga ASPNET

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -ga ASPNET

How to calculate download Speed using C#.net and java script code

How to calculate download Speed using C#.net and java script code
1) using C#.net code
private void CalculateDownloadTime(double fileSizeMB,double fileSizeKB,int speed,ref int timeHour,ref int timeMinute,ref int timeSec)
{
double downloadTime = 0;
if (fileSizeMB != 0)
{
downloadTime = (fileSizeMB * Constant.FILE_SIZE_KB * 8.192) / speed;
}
else if (fileSizeKB != 0)
{
downloadTime = (fileSizeMB * 8.192) / speed;
}
timeHour = Convert.ToInt32(downloadTime) / 3600;
timeMinute = (Convert.ToInt32(downloadTime) % 3600) / 60;
timeSec = Convert.ToInt32(downloadTime) % 60;
}
Example to call above function
int timeHour =0;
int timeMinute =0;
int timeMinute =0;
CalculateDownloadTime(30,0,56, ref timeHour, ref timeMinute, ref timeMinute);
2) using Java Script
<script language="JavaScript" type="text/javascript">
<!--
var speeds = new Array(
new Array("9.6 Modem", "9.6"),
new Array("14.4 Modem", "14.4"),
new Array("19.2 Modem", "19.2"),
new Array("28.8 Modem", "28.8"),
new Array("33.6 Modem", "33.6"),
new Array("56 Kb Modem", "56"),
new Array("Single Channel ISDN (64Kbps)", "64"),
new Array("Dual Channel ISDN (128Kbps)", "128"),
new Array("Asymmetric DSL (ADSL)", "384"),
new Array("Single-pair HDSL (S-HDSL)", "768"),
new Array("Consumer DSL (CDSL)", "1024"),
new Array("T1", "1544"),
new Array("HDSL", "1544"),
new Array("T3", "46080"),
new Array("Very high-speed DSL (VDSL)", "52224"),
new Array("OC1", "53248"),
new Array("100 Base-T (fast ethernet)", "102400"),
new Array("ATM", "158720"),
new Array("OC3", "159744"),
new Array("1000 Base-T", "1024000")
);
function compute (form, scale)
{
if (form.size == null form.size.length == 0)
{
alert("Please enter a valid filesize.");
return;
}
var size = parseFloat(form.size.value);
for (var i = 1; i <= speeds.length; i++)
{
var time = size * scale * 8.192 / speeds[i - 1][1];
var hours = Math.floor(time / 3600);
var minutes = Math.floor((time % 3600) / 60);
var seconds = Math.floor(time % 60);
form[i + "hour"].value = hours;
form[i + "minute"].value = minutes;
form[i + "second"].value = seconds;
}
}
//--></script>
Example to call above (compute) function
For file Size MB --> compute(30,1024)
For file size KB --> compute(30,1)

How to download file from Server and How to Display PDF file in new browser using C#.net

How to download file from Server and How to Display PDF file in new browser using C#.net
NameSpace
using System.IO;
1) Download files from file server into client machine with dialog box (Save/Open)
private void StartDownLoad(string filePath)
{
try
{
filePath = "C:\backup\" + filePath;
//to download the file
FileInfo myFile = new FileInfo(filePath);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + myFile.Name );
Response.AddHeader("Content-Length", myFile.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(myFile.FullName);
Response.Flush();
Response.End();
}
catch (Exception Ex)
{
throw Ex;
}
}
2) Display PDF document into new web browser without dialog box
(below methods works fine with Acrobat Reader 5.0)
private void DisplayPDF(string filePath)
{
try
{

string file_Path = @"C:\backup\standards.pdf";
Response.Buffer = false; //transmitfile self buffers
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
//transmitfile keeps entire file from loading into memory
Response.TransmitFile(file_Path);
//Or
FileInfo my_File = new FileInfo(file_Path);
Response.WriteFile(my_File.FullName);

Response.End();
}
catch (Exception Ex)
{
throw Ex;
}
}
Note: If pdf file size if big then above method will take time to display pdf in the browser; in that case we have to read pdf in bytes and flush or refersh while reding; use follwoing method in case of big pdf file

private void DisplayPDF(string filePath)
{

filePath = @"D:\All\CSC\CSC\Contents\wake1.pdf",

Response.ClearContent();
Response.ContentType = "application/pdf";
//Get the File path from product Library Tab
FileStream oStrm = new FileStream(filePath,FileMode.Open, FileAccess.Read);
byte[] arbData = new byte[10000];
int nC = 0;
//Conert PDF file to byte
while (0 != (nC = oStrm.Read(arbData, 0, 10000)))
{
Response.OutputStream.Write(arbData, 0, nC);
Response.OutputStream.Flush();
Array.Clear(arbData, 0, nC);
Response.Flush();
}
Response.End();

}
Another way of opening Large PDF files, actually following method will read PDF file from server and write into the browser
Calling function to open PDF or any others files like: doc, wmv, xls etc. content type would be change according to file format like: for doc file content type would be "
application/msword" etc
How to use
viewDocument("C:\Temp\123.pdf","application/pdf")
Implementation
public void viewDocument(string filePath, string contentType)
{
if (contentType.Contains("pdf"))
{
Int32 bufferInByte = 2500;
Response.ClearHeaders();
Response.ClearContent();
Response.Clear();
Response.ContentType = contentType;
Response.BufferOutput = true;
Response.Buffer = true;
Response.AppendHeader("Accept-Ranges", "bytes");
Response.StatusCode = 200;
Response.AppendHeader("Content-Type", contentType);
FileStream oStrm = new FileStream(filePath, FileMode.Open, FileAccess.Read);
long lEndPos = oStrm.Length;
Response.AppendHeader("Content-Length", oStrm.Length.ToString());
Response.AppendHeader("Accept-Header", oStrm.Length.ToString());
Response.AppendHeader("connection", "close");
if (Request.HttpMethod.Equals("HEAD"))
{
Response.Flush();
return;
}
byte[] arbData = new byte[bufferInByte];
int nC = 0;
//Conert PDF file to byte
while (0 != (nC = oStrm.Read(arbData, 0, bufferInByte)))
{
if (nC <>(ref arbData, nC); }
if (Response.IsClientConnected){
Response.BinaryWrite(arbData);
Array.Clear(arbData, 0, nC);
Response.Flush();
if (nC <>(ref arbData, bufferInByte); }
}
else {
break;
}
}
oStrm.Close();
Response.Flush();
}
else
{
//to download others file
FileInfo myFile = new FileInfo(filePath);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + myFile.Name);
Response.AddHeader("Content-Length", myFile.Length.ToString());
Response.ContentType = ConfigurationManager.AppSettings["DefaultContentType"].ToString();
Response.WriteFile(myFile.FullName);
Response.Flush();
Response.End();
}
}
Get the file size in MB/KB and Byte
private string GetFileSize(string filePath, ref double fileSizeMB, ref double fileSizeKB)
{
const int FILE_SIZE_MB = 1048576;
const int FILE_SIZE_KB = 1024;
lblError.Text = string.Empty;
double fileSize = 0;
if (filePath.Length > 0)
{
FileStream FSIn = new FileStream(filePath.ToString(), FileMode.Open
, FileAccess.Read);
BinaryReader rFSIn = new BinaryReader(FSIn);
fileSize = FSIn.Length;
fileSize = Math.Round(fileSize, 2);
FSIn.Close();
rFSIn.Close();
fileSizeMB = fileSize / FILE_SIZE_MB;;
if (Math.Round(fileSizeMB,1) == 0.0)
{
fileSizeKB = fileSize / FILE_SIZE_KB;
fileSizeKB = Math.Round(fileSizeKB, 2);
if (fileSizeKB == 0)
return fileSize + " Byte";
else
return fileSizeKB + " KB";
}
else
{
fileSizeMB = Math.Round(fileSizeMB,2);
return fileSizeMB + " MB";
}
}
else
{
lblError.Text = "FILE_NOT_FOUND Error";
return fileSize + "";
}
}