Tuesday, August 28, 2012

Validate a CheckBox with a CustomValidator in ASP.NET 4.0 and C#

By default there is no validation control in ASP.NET to work with the checkbox control. However, in certain cases you may want to use validation on a checkbox such as one that would require them to accept the terms and services of a web site or registration process. To do this:
Right click the project in your solution explorer.
Select add new item
Select a web form.
Name it ‘Default.aspx’.
Click add.
Open Default.aspx up to design mode.
Drag and drop a checkbox onto the web form.
Drag and drop a customvalidator next to the checkbox.
Change the ErrorMessage property to ‘You must check the box’.
Change the ForeColor property to ‘Red’.
Check the Text property to ‘*’.
Add a line break after the customvalidator.
Drag and drop a button under the checkbox.
Add a line break after the button.
Drag and drop a validationsummary under the button.

Validating the CheckboxNext, we want to add in some simple code on the ServerValidate event of the customvalidator that we added. To do this:
Double click the customvalidator to generate the ServerValidate event method.
Add in the following code to the CustomValidator_ServerValidate event method:

Restrict Files Access From Unauthorized access using File Handlers


Create class FileProtectHandler.cs in the project and add methods as follows:

using System;
using System.Web;
using System.Web.Security;
using System.IO;

namespace Custom.Handlers
{
    /// <summary>
    /// Handles processing requests for protected web application files, such as reports/*.pdf
    /// The reports are checked by the user role to determine access.
    /// </summary>
    public class FileProtectionHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            switch (context.Request.HttpMethod)
            {
                case "GET":
                    {
                        // Is the user logged-in?
                        //if (!context.User.Identity.IsAuthenticated)
                        //{
                        //    FormsAuthentication.RedirectToLoginPage();
                        //    return;
                        //}

                        string requestedFile = context.Server.MapPath(context.Request.FilePath);
                        // Verify the user has access to the User role.
                        if (Convert.ToString(context.Session["Username"]) == "demo")
                        {
                            SendContentTypeAndFile(context, requestedFile);
                        }
                        else
                        {
                            context.Response.Redirect("~/adm/login05.aspx");
                        }

                        break;
                    }
            }
        }

        #endregion

        private HttpContext SendContentTypeAndFile(HttpContext context, String strFile)
        {
            context.Response.ContentType = GetContentType(strFile);
            context.Response.TransmitFile(strFile);
            context.Response.End();

            return context;
        }

        private string GetContentType(string filename)
        {
            // used to set the encoding for the reponse stream
            string res = null;
            FileInfo fileinfo = new FileInfo(filename);

            if (fileinfo.Exists)
            {
                switch (fileinfo.Extension.Remove(0, 1).ToLower())
                {
                    case "pdf":
                        res = "application/pdf";
                        break;
                    case "doc":
                    case "docx":
                        res = "application/msword";
                        break;
                    case "xls":
                    case "xlsx":
                        res = "application/vnd.ms-excel";
                        break;
                    case "rtf":
                        res = "application/x-rtf";
                        break;
                    case "txt":
                        res = "text/plain";
                        break;
                    case "jpeg":
                    case "jpg":
                        res = "image/jpg";
                        break;
                    case "bmp":
                        res = "image/bmp";
                        break;
                    case "png":
                        res = "image/png";
                        break;
                    case "gif":
                        res = "image/gif";
                        break;
                    default:
                        res = "application/octet-stream";
                        break;
                }

                return res;
            }

            return null;
        }
    }
}




Add the tags in the Web.config File according to the handler namespace

<handlers>
      <add name="PDF" path="*.pdf" verb="*" type="Custom.Handlers.FileProtectionHandler"  />
      <add name="docx" path="*.docx" verb="*" type="Custom.Handlers.FileProtectionHandler"  />
      <add name="doc" path="*.doc" verb="*" type="Custom.Handlers.FileProtectionHandler"  />
      <add name="xlsx" path="*.xlsx" verb="*" type="Custom.Handlers.FileProtectionHandler"  />
      <add name="xls" path="*.xls" verb="*" type="Custom.Handlers.FileProtectionHandler"  />
      <add name="rtf" path="*.rtf" verb="*" type="Custom.Handlers.FileProtectionHandler"  />
      <add name="txt" path="*.txt" verb="*" type="Custom.Handlers.FileProtectionHandler"  />
      <add name="vsd" path="*.vsd" verb="*" type="Custom.Handlers.FileProtectionHandler"  />
      <add name="jpg" path="*.jpg" verb="*" type="Custom.Handlers.FileProtectionHandler"  />
      <add name="jpeg" path="*.jpeg" verb="*" type="Custom.Handlers.FileProtectionHandler"  />
      <add name="gif" path="*.gif" verb="*" type="Custom.Handlers.FileProtectionHandler"  />
      <add name="png" path="*.png" verb="*" type="Custom.Handlers.FileProtectionHandler"  />
      <add name="bmp" path="*.bmp" verb="*" type="Custom.Handlers.FileProtectionHandler"  />
</handlers>
<httpHandlers>
<add path="*.pdf" verb="*" validate="true"  type="Custom.Handlers.FileProtectionHandler" />
      <add path="*.docx" verb="*" validate="true"  type="Custom.Handlers.FileProtectionHandler" />
      <add path="*.doc" verb="*" validate="true"  type="Custom.Handlers.FileProtectionHandler"  />
      <add path="*.xlsx" verb="*" validate="true" type="Custom.Handlers.FileProtectionHandler"  />
      <add path="*.xls" verb="*" validate="true" type="Custom.Handlers.FileProtectionHandler"  />
      <add path="*.rtf" verb="*" validate="true" type="Custom.Handlers.FileProtectionHandler"  />
      <add path="*.txt" verb="*" validate="true" type="Custom.Handlers.FileProtectionHandler"  />
      <add path="*.vsd" verb="*" validate="true" type="Custom.Handlers.FileProtectionHandler"  />
      <add path="*.jpg" verb="*" validate="true" type="Custom.Handlers.FileProtectionHandler"  />
      <add path="*.jpeg" verb="*" validate="true" type="Custom.Handlers.FileProtectionHandler"  />
      <add path="*.gif" verb="*" validate="true" type="Custom.Handlers.FileProtectionHandler"  />
      <add path="*.png" verb="*" validate="true" type="Custom.Handlers.FileProtectionHandler"  />
      <add path="*.bmp" verb="*" validate="true" type="Custom.Handlers.FileProtectionHandler"  />
    </httpHandlers>