ASP.net: TabContainer Maintain Selected Tab Index with Cookies

Methods for reading the cookie created by the clientside script and setting the ActiveTabIndex of the TabContainer.

        private void ReadIndexCookie()
        {
            if (Request.Cookies[CookieName] != null && Request.Cookies[CookieName].Value != null)
            {
                int index;
                int.TryParse(Request.Cookies[CookieName].Value, out index);
                CurrentIndex = index;
                return;
            }
 
            CurrentIndex = 0;
        }
 
        private void SetCurrentTab()
        {
            tcStoreEditor.ActiveTabIndex = CurrentIndex;
        }

Call the two methods in the Page_Load.

        protected void Page_Load(object sender, EventArgs e)
        { 
            if (!Page.IsPostBack)
            {
                //Some Method Calls Here
            }
 
            ReadIndexCookie();
            SetCurrentTab();
        }

JavaScript code which hooks to the TabContainer’s OnClientActiveTabChanged=”OnTabChanged” event. When that event is fired the selected tab index is pulled and written to the cookie.

<script type="text/javascript">

function Set_Cookie(name, value, expires, path, domain, secure) {
// set time, it's in milliseconds
var today = new Date();
today.setTime(today.getTime());

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));

document.cookie = name + "=" + escape(value) +
((expires) ? ";expires=" + expires_date.toGMTString() : "") +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
((secure) ? ";secure" : "");
}


function OnTabChanged(sender, args) {
var tabControl = $get("").control;
var currentIndex = tabControl.get_activeTabIndex();
Set_Cookie("", currentIndex, "", "", "", "");
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
width: 450px;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

ASP.net: Programmatically Checking Items in a CheckBoxList

        private void CheckItems()
        {
            foreach (string item in itemsList)
            {
                for (int i = 0; i < ckblstItems.Items.Count; i++)
                {
                    if (ckblstItems.Items[i].Text.Equals(item))
                    {
                        ckblstItems.Items[i].Selected = true;
                    }
                }
            }
        }

ASP.net: Login Control Styling Convert to Template

If you are looking for an easy way to style the ASP.net Login Control and don’t want to use all the built-in control properties because you want unfettered access to all the elements that make up the Login Control all you have to do is the following.

  1. Open the ascx or aspx page which holds the Login Control.
  2. Switch to design view.
  3. Right-click the actual Login Control on the design surface and in the context menu select “Convert to Template”.

Visual Studio will automatically add the “LayoutTemplate” element to the Login Control markup and populate it with all the controls and elements that made up the control as it was setup at the time of conversion.
You now have access to everything you need to extensively style the Login Control to your liking.

ASP.net: Adding Re-Captcha to your Forms

In order to stop malicious applications (robots) from submitting your forms over and over again creating extremely painful data and performance problems the best thing you can do is add captcha to your forms.

Captcha stands for “Completely Automated Public Turing test to tell Computers and Humans Apart”. It uses an image containing deformed text which is impossible for computers to read but can be deciphered by a human. When submitting a form the user must enter the text correctly which is validated by the Captcha control. If the text is correct the validation passes if not it fails. When the validation fails the form cannot be submitted.

A nice free Captcha library and services is the ReCaptcha services which is completely free and extremely easy to use.

1. Download the library

2. Register for an API key

3. Add a reference to that library

4. Register the control on the page


5. Add the control to the page


<recaptcha:RecaptchaControl
      ID="recaptcha"
      runat="server"
      PublicKey=""
      PrivateKey=""
      />

6. Validate the ReCaptcha control in a form event

            recaptcha.Validate();

            if (!recaptcha.IsValid)

            {

                e.Cancel = true;

            }

            else

            {

                recaptcha.Visible = false;

            }

ASP.net: Changing Forms Authentication Defaults

By default ASP.net expects to find the Login.aspx page in the root directory of the application. When a request comes in for a protected resource and the user is not authenticated or authorized to access that resource it will automatically redirect the user to /Login.aspx so the user can login.
Personally I do not like to place all of my Membership pages in the root of the application. I like a little order to my madness and prefer to place the Login.aspx page in a folder like Registration which is publicly accessible. But if you try to place the Login.aspx page in any folder except the root of the application you will see an error stating the page cannot be found when you try to access a protected resource. This is because of the default settings discussed above.
To fix this you simply need to alter the default setup for Forms Authentication by adding some configuration entries to your web.config as follows.


<forms loginUrl="/Registration/Login.aspx"
protection="All"
timeout="30"
name="AppNameCookie"
path="/FormsAuth"
requireSSL="false"
slidingExpiration="true"
defaultUrl="default.aspx"
cookieless="UseCookies"
enableCrossAppRedirects="false"/>

  • loginUrl: allows you to alter the default location of your Login.aspx page

You can look up the rest of the attributes by going to the MSDN documentation for ASP.net Membership.

ASP.net: Disabling Form Auto-Complete in Browsers

We have all experienced our favorite browser asking us if it should save the data we just entered into a form on a web page so it can auto-complete / auto-populate that information the next time we visit the page.
Unfortunately, our browsers are not intelligent enough to think about security on their own and therefore they like to cache anything typed into a form including our passwords. This of course poses a security risk that not many web developers think about when building applications.
For obvious security reasons turning the auto-complete functionality off for all password input fields in a form is a great idea. In fact it is such a great idea it should be second nature to all developers creating forms with any input fields accepting sensitive information (passwords, SSN, account numbers, etc… ).
To turn the auto-complete functionality of on ASP.net TextBox controls you use the AutoCompleteType attribute. Simply add it to your TextBox markup in your aspx or ascx file like so.
Markup Method:

<asp:TextBox id="tbPassword" runat="server" TextMode="Password" Columns="35" AutoCompleteType="Disabled">

Or if you prefer to do it in code you can alter the AutoCompleteType property of the TextBox control in your C# code like so:

Code-Behind Method:

tbPassword.AutoCompleteType = AutoCompleteType.Disabled;

Now the above is what the MSDN documentation tells you to do to turn auto-complete off. But I must say in one of my applications, a rather complicated one, setting the AutoCompleteType property of the ASP.net control to Disabled did not cause the actual HTML attribute of “autocomplete” to be rendered with the off value. I spent time trying to figure out why it was never added to the final HTML output but could not find a reason.

In this particular case I ended up giving in and just adding the attribute to the control manually as follows:

Code-Behind Method:

tbPassword.Attributes.Add("autocomplete", "off");

You can also turn auto-complete off for all input fields in an entire form by adding the “autocomplete” attribute to the From directly and setting its value to “off”.

Markup Method:

<form autocomplete="off">

Note: the “autocomplete” attribute we have been discussing here is not found in the actual HTML documentation for either the “input” or “form” tags as defined by the W3C which means that it is selectively implemented by browsers and therefore not universally functional across all browsers.