Friday, January 30, 2009

C# Codebehind hiding pages or page content

I recently developed a project at my job which discloses candidate information to the public on cases where the filer was bought to hearing.

The form I designed used a ton of CSS to make the form look like a desktop application. It will be published in April 2009 at http://www.pdc.wa.gov/home/enforcement/searchdb. My problem was that the agency felt that some fields should not be visible to the public. My task was a simple solution.

I figure internal users will use the same page as external users. If I can capture the ip address of the internal user then I can display the labels and textboxes, other users will get the default setting of visible=false;

Here's the code.

string sAddress = Request.ServerVariables["REMOTE_ADDR"].ToString();
if (sAddress == "127.0.0.1")
sAddress = "192.168.1.127"; // handles ip ranges for debugging
int iAddress = sAddress.Length;
string sRemoteAddress = sAddress.Remove(10, iAddress - 10);
if (sRemoteAddress == "192.168.1")
{

//Do something
}
else
{
Response.Redirect("~/default.aspx");
}


Here's how it works.

Request.ServerVariables["REMOTE_ADDR"] gets the current connections ip address and returns the ipaddres to the string sAddress.

Because I was using the application in my visual studio project I didn't want to keep getting redirected to my home page, so I added some code to check to see if I have a local ip of 127.0.0.1. If so, then manually give me the ip address of 192.168.1.127.

Here's were it gets tricky.
int iAddress = sAddress.Length

sAddress.Length returns the number of characters in the ipaddress. I did this because the length could vary in an ipaddress. It passes the length to iAddress which is type int.

Next I drop all the characters from the beginning of the 10th character to the end of iaddress length - 10.

This will drop the last octate of the ip address and then check the string sRemoteAddress value against my ip address in my if statement.

This works really great to redirect users if you have a page published to the internet where both internal and external users are visiting the site, but you don't want external users seeing the page.

Now, I can add to my statement something like this instead of the long if statement:
if(sRemoteAddress != "192.168.1")
Response.Redirect("~/default.aspx");

or if I wanted to hide a few controls like labels and textboxes add them to the list:

if(sRemoteAddress == "192.168.1")
{
Label.Visible = true;
TextBox1.Visible = true;
}

or
set a global variable of type bool like this:

bool _diplayobjects = false;

Now in my if statement do this:

if(sRemoteAddress == "192.168.1")
{
_displayobjects = true;
}
else
{
// redirect the page
}

Label1.Visible = _displayobjects;
TextBox.Visible = _displayobjects;

No comments: