Sunday, June 24, 2012

Restrict File download to unauthorized users

Following code is for allowing only the registered(logged in) users to download files
Step 1: Create a file Handler.ashx and write the following code. Since I am not using form authentication, I am checking the session variables which are set once the user successfully logs in. Please note the implementation of IRequiresSessionState interface, this is because the HttpHandler cannot access session parameters on its own.
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; using System.Web.Security; using System.Web.SessionState; public class Handler : IHttpHandler,IRequiresSessionState { public void ProcessRequest (HttpContext context) { try { if (context.Session["user"] != null) { string filename = context.Request.QueryString["File"]; //Validate the file name and make sure it is one that the user may access context.Response.Buffer = true; context.Response.Clear(); context.Response.AddHeader("content-disposition", "attachment; filename=" + filename); context.Response.ContentType = "octet/stream"; context.Response.WriteFile("~/downloads/" + filename); } else context.Response.Redirect("~/Default.aspx"); } catch (NullReferenceException ex) { context.Response.Redirect("~/Default.aspx"); } catch (System.Exception ex) { context.Response.Write(ex.ToString()); } } public bool IsReusable { get { return true; } } }
Step 2: There is a file titled Default.aspx from which users log in into the system and sets the session variable
protected void Button1_Click(object sender, EventArgs e) { //validation related code goes here Session["user"] = "TEST"; Response.Redirect("~/downloads.aspx"); }
Step 3: The html code in downloads.aspx
<a href="Handler.ashx?File=annex8.pdf">Click Here</a>

Further Reading
Here as well

Inheritence in C#, overriding base class

In the following code I am overriding the MasterPage class's onLoad event. What I am doing is, I check whether session variables have been set i.e. if the user has actually logged in into the system. I have created the baseclass titled baseClass.
public class baseClass : System.Web.UI.MasterPage
{
 public baseClass()
 {
  //
  // TODO: Add constructor logic here
  //
 }
    protected override void OnLoad(EventArgs e)
    {
        try
        {
            if (Session["usrPrivilege"].ToString().Equals("ADMIN"))
            {
                base.OnLoad(e);
            }
            else

                Response.Redirect("~/Default.aspx");
        }
        catch (NullReferenceException ex)
        {
            Response.Redirect("~/Default.aspx");
        }
        catch
        {
            base.OnLoad(e);
        }
        
    }
}
Now in the masterpage I wrote the following code, in this way I am sparing the onLoad eventhandler of my masterpage from checking session related information
public partial class Pages_ADMIN_MasterPage :baseClass
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
          
            if (IsPostBack == false)
            {
                //My code goes here
            }
        }
         
        catch (System.Exception ex)
        {
                 //My code for exception handling
        }
    }
}
For further reading you can click here

How to get Type of Exception in C#

Many times we have different ways to handle different kind of errors so we need to know the type of error that has occurred in the system. Here's a simple example in ASP.NET
protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["usrPrivilege"].ToString().Equals("USER"))
            {
                //Your Code goes here
            }
        }
        catch (NullReferenceException ex)
        {
            Response.Redirect("~/login.aspx");
        }
        catch (AccessDeniedException ex) 
        {
          //Do something else
        }
        catch (System.Exception ex)
        {
               //Code for other type of exception
        }
    }

Friday, June 22, 2012

ASP.NET textboxes that take only numerical values as input

Following is a javascript code snippet for your ASP.NET test.aspx page. Please note the script checkNumber is for non-decimal numbers while checkNumber is for decimal numbers.


<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>User Page</title>
    
    <script language="javascript" type="text/javascript">

function checkNumber(textBox, textEvent )
{
    var  code = textEvent.which; // Netscape Method
    
    if (code == null)
    {
        code = textEvent.keyCode;//IE 4 Method
    }
    
    if(code==13)
    {
    
        
        obj.focus();
        
    }
    if(!((code >= 48 && code <= 57) || (code == 8)))
    {
        return false;
    }
    return true;
}
function checkNumberWithDecimal(textBox, textEvent )
{
    var  code = textEvent.which; // Netscape Method
    if (code == null)
    {
        code = textEvent.keyCode;//IE 4 Method
    }
    if(code==13)
    {
    
        //var obj= getFrmObject(textBox);
        obj.focus();
        
    }
    if(!((code >= 48 && code <= 57) || (code == 8)||(code==46)))
    {
        return false;
    }
    return true;
}

</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        <div style="float:left">Registration No</div>
        <div style="float:left"><asp:TextBox ID="txtRegNo" runat="server"></asp:TextBox></div>
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>
And following is your code on

Page_Load

protected void Page_Load(object sender,EventArgs e)
{
      txtRegNo.Attributes.Add("OnKeyPress", "javascript:return                                     checkNumber(this,event);");

}     

Reading Excel File in C# dot Net



using System;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using Microsoft.Office.Interop.Excel;




private void Page_Load(object sender,EventArgs e)
{
      operateExcel("C:\\EXCEL.xls");
}
private void operateExcel(string pth)
    {
       
        DataSet dtset = new DataSet("MYEXCEL");
        try
        {
            //lvContent.Items.Clear();
            Workbook wbok = app.Workbooks.Open(pth, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);


            wbok = app.Workbooks.Open(pth, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            //WorksheetClass wshts = (Worksheets)wbok.Worksheets;

            Sheets wshts = wbok.Worksheets;
            Worksheet wsht = (Worksheet)wshts.get_Item(1);
         

            System.Data.DataTable dtbl = new System.Data.DataTable("MYEXCEL");
            dtset.Tables.Add(dtbl);

            DataColumn col = new DataColumn();
         
            col.ColumnName = "COL1";
            dtbl.Columns.Add(col);

            col = new DataColumn();
            col.ColumnName = "COL2";
            dtbl.Columns.Add(col);

            col = new DataColumn();
            col.ColumnName = "COL3";
            dtbl.Columns.Add(col);

           
            for (int i = 2; i < 10000 && wasLastnull < 3; i++)
            {
               
                Range rnge = wsht.get_Range("A" + i.ToString(), "I" + i.ToString());
                System.Array myvalues = (System.Array)rnge.Cells.Value2;
                System.Array vals = (System.Array)rnge.Cells.Value2;
                string a1 = "", a2 = "", a3 = "" ;
                try
                {
                   
                        a1 = vals.GetValue(1, 1).ToString();
                        a2 = vals.GetValue(1, 2).ToString();
                        a3 = vals.GetValue(1, 3).ToString();
                        DataRow dr = dtbl.NewRow();
                        dr["COL1"] = a1.ToString();
                        dr["COL2"] = a2.ToString();
                       dr["COL3"] = a3.ToString();
                      dtbl.Rows.Add(dr);
                       count = count + 1;
                    }

                catch (System.Exception ex)
                {
                    Label1.Text = ex.ToString() + "ERROR";
                }
           }
           
            app.Workbooks.Close();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wsht);

            System.Runtime.InteropServices.Marshal.ReleaseComObject(wbok);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
             
        }
        catch (System.Exception ex)
        {

        }
    }

Thursday, June 21, 2012

Display div alongside with links on mouse move and hide when mouse moves out

Literally I prefer to use ToolTip text or title attribute when I need to display simple information however many times we need a div element to do the trick to meet our business requirement. I had found following script in some site few months back but I do not remember which but with hope it might help others, I have pasted it here.

  <script type="text/javascript" language="JavaScript">

var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function UpdateCursorPosition(e)
       cX = e.pageX; cY = e.pageY;
}
function UpdateCursorPositionDocAll(e)
    cX = event.clientX; cY = event.clientY;
}
if(document.all) 
    document.onmousemove = UpdateCursorPositionDocAll; 
}
else 
    document.onmousemove = UpdateCursorPosition; 
}
function AssignPosition(d) {
if(self.pageYOffset) {
 rX = self.pageXOffset;
 rY = self.pageYOffset;
 }
else if(document.documentElement && document.documentElement.scrollTop) {
 rX = document.documentElement.scrollLeft;
 rY = document.documentElement.scrollTop;
 }
else if(document.body) {
 rX = document.body.scrollLeft;
 rY = document.body.scrollTop;
 }
if(document.all) {
 cX += rX; 
 cY += rY;
 }
d.style.left = (cX+10) + "px";
d.style.top = (cY+10) + "px";
}
function HideContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "none";
}
function ShowContent(d,cnt) {
if(d.length < 1) { return; }
var dd = document.getElementById(d);
AssignPosition(dd);
dd.style.display = "block";
dd.innerHTML=cnt;
}
function ReverseContentDisplay(d) {
if(d.length < 1) { return; }
var dd = document.getElementById(d);
AssignPosition(dd);
if(dd.style.display == "none") { dd.style.display = "block"; }
else { dd.style.display = "none"; }
}
</script>

The div Element

Setting text of the div element in runtime

protected void Page_Load(object sender,EventArgs e)
   {
    string content="I am loaded in runtime ";
    lnk1.Attributes.Add("onmouseover", 
"javascript:return ShowContent('myDiv','" + content + "'); return true;");
   lnk1.Attributes.Add("onmouseout", "javascript:return 
HideContent('myDiv'); return true;");

   }

Adding Controls in Run Time

There are many ways to add controls in runtime in ASP.NET, however the one I love is using the placeholder control. Its easy, you can place it inside the div element or td element of a table and add controls without worrying where the controls will appear inside the page. So add a placeholder inside the div element and add controls. Following code snippet shows you how to add Label Control during runtime

Adding Controls in runtime in C# ASP.NET

protected void Page_Load(object sender, EventArgs e) { addControls(); } protected void addControls(); { for(int i=0;i<5;i++) { Label lbl = new Label(); lbl.ID = "lbl" + app_code + "_" + priv_code; lbl.ToolTip = dsPriv.Tables[0].Rows[j][4].ToString(); lbl.Style.Add("margin-left", "40px"); lbl.Text = dsPriv.Tables[0].Rows[j][3].ToString(); PlaceHolder1.Controls.Add(lbl); LiteralControl lCntrl = new LiteralControl("
"); PlaceHolder1.Controls.Add(lCntrl); } }
and that's it