Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Asp.net Authorization

Authorization decides weather  to grant access to user for specific resources or Authorization is the process of granting privilege to authenticated user

in asp.net there are two types of authorization

 File authorization:

File authorization   File authorization is performed by the FileAuthorizationModule. It checks the access control list (ACL) of the .aspx or .asmx handler file to determine whether a user should have access to the file.

 URL authorization:

URL authorization is performed by the UrlAuthorizationModule, which maps users and roles to URLs in ASP.NET applications.
With url authorization  explicitly you can allow and deny access by providing user name or role.
You can use allow and deny users elements to that under authorization tax in configuration file.

Syntax:

<authorization>
 <[allow|denyusers roles verbs />
</authorization>

 

Allow and Deny elements has following attributes:

Users: User accounts, using question mark (?)Anonymous users are identified and all authenticated users using an asterisk (*).
Roles: Identifies a role (a RolePrincipal object) for the current request that is allowed or denied access to the resource.
Verbs: Defines the HTTP verbs to which the action applies, such as GET, HEAD, and POST. The default is "*", which specifies all verbs.

Authorization examples:

Following example explains allowing and denying access to specific users and roles:

 

<authorization>
  <allow users="Nagnath,Shourya"/>
  <allow roles="Admins"/>
  <deny users="Aditya"/>
  <deny roles="Editors"/>
</authorization>


Following example allows anonymous access:

 <authorization>
            <allow users="?"/>
 </authorization>

Following example allows access to all users:

<authorization>
            <allow users="*"/>
</authorization>


The following example allows all users to perform an HTTP GET for a resource, but allows only the Nagnath identity to perform a POST operation:

<authorization>
  <allow verbs="GET" users="*"/>
  <allow verbs="POST" users="Nagnath"/>
  <deny verbs="POST" users="*"/>
</authorization>

 

 

 

ASP.NET validation controls

ASP.NET validation controls validate the input data to ensure data is correct, authenticated and valid.

Asp.net uses following ready validation controls:

a.  RequiredFieldValidator
b. RangeValidator
c. CompareValidator
d. RegularExpressionValidator
e. CustomValidator
f. ValidationSummary

BaseValidator Class

All validation control classes are inherited from the BaseValidator class hence they inherit its properties and methods.

Following are Class members of BaseValidator Class:

ValidationGroup: The logical group of multiple validators used.
ControlToValidate:  input control to validate.
Display: Indicates how the error message is shown.
EnableClientScript: Indicates whether client side validation will take.
Enable: To enable or disable validation.
ErrorMessage:Indicates error string.
Text:    Error text to be shown if validation fails.
IsValid:Indicates whether the value of the control is valid.
SetFocusOnError:It indicates whether in case of an invalid control, the focus should switch to the related input control.
Validate (): This method revalidates the control and updates the IsValid property.

 

1.  RegularExpressionValidator Control:

The RegularExpressionValidator used to validate the input text by matching against a pattern of a regular expression.

 The regular expression is set in the ValidationExpression property.

Example:

 Task Id: <input type="text" id="searchParameter" runat="server" /> 
        <asp:RegularExpressionValidator id="PageRegularExpressionValidator"
                 ControlToValidate="searchParameter"
                 ValidationExpression="^\d+"
                 Display="Static"
                 ErrorMessage="Only Numbers"
                 EnableClientScript="True"
                 runat="server"></asp:RegularExpressionValidator>

 

2.  RangeValidator Control:

The RangeValidator control used to verify that the input value falls within a predetermined range.   

Example:

page size: <input type="text" id="pageSize" runat="server" /> 
        <asp:RangeValidator ID="pageSizeRange " runat="server" ControlToValidate="pageSize"
   ErrorMessage="Enter page size(2-25)" MaximumValue="25"
   MinimumValue="2" Type="Integer">
  
</asp:RangeValidator>

 

3. CompareValidator Control:

The CompareValidator control allows you to compare the value entered by the user into an input control, such as a TextBox control, with the value entered into another input control, or with a constant value. You can also use the CompareValidator control to determine whether the value entered into an input control can be converted to the data type specified by the Type property.

Example:

    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
    <asp:TextBox ID="txtxConfirmPass" runat="server" TextMode="Password"></asp:TextBox>
  <asp:CompareValidator ID="PassCompareValidator" runat="server"
    ControlToValidate="txtxConfirmPass"
    CssClass="ValidationError"
    ControlToCompare="txtPassword"
    ErrorMessage="No Match"
    ToolTip="Password must be the same" />


4. RequiredFieldValidator Control:

This is frequently used validation control ensures input control (i.e. textbox) is compulsory required with some value or user enters a value.

For example, you can specify that users must fill in a Name text box before they can submit a registration form.

Example:

   Task ID: <input type="text" style="vertical-align: middle" id="searchParameter" runat="server" /> 
       <asp:Button runat="server" ID="btnFind"  OnClick="btnFind_OnClick" Text="Find"/>
      <asp:RequiredFieldValidator ID="SerchFieldRequiredFieldValidator" runat="server" ControlToValidate="searchParameter" ErrorMessage="Task id required"></asp:RequiredFieldValidator>

 

5. Validation Groups:

This is not validation control, ValidationGroup is property used to create some logical validation groups.

For example page is divided with some panels and each panel has some different logical functionality.

i.e Employee dashboard with leave details panel ,user detail panel , admin setting panel.

Here admin setting panel is independent and require validation for specific group of controls in that you can apply ValidationGroup like ValidationGroup=”AdminSettings”

 Example:

In this example user search controls used btnFind group.

   Employee Number: <input type="text" style="vertical-align: middle" id="searchParameter" runat="server" /> 
<asp:Button runat="server" ID="btnFind"  OnClick="btnFind_OnClick" Text="Find" ValidationGroup="btnFind" />
         <asp:RequiredFieldValidator ID="SerchFieldRequiredFieldValidator" runat="server" ControlToValidate="searchParameter" ValidationGroup="btnFind" ErrorMessage="Task id required"></asp:RequiredFieldValidator>

 

6. ValidationSummary:

The ValidationSummary control is not used to perform any validation but shows a summary of all errors in the page. The summary displays the values of the ErrorMessage property of all validation controls that failed validation.

Example:

   Employee Number: <input type="text" style="vertical-align: middle" id="searchParameter" runat="server" /> 
 <asp:Button runat="server" ID="btnFind"  OnClick="btnFind_OnClick" Text="Find" ValidationGroup="btnFind" />
         <asp:RequiredFieldValidator ID="SerchFieldRequiredFieldValidator" runat="server" ControlToValidate="searchParameter" ValidationGroup="btnFind" ErrorMessage="Task id required"></asp:RequiredFieldValidator>
    <asp:ValidationSummary ID="UserSEarchValidationSummary" runat="server"
   DisplayMode = "List" ShowSummary = "true" HeaderText="Errors:" ValidationGroup="btnFind" />

 

7. CustomValidator Control:

The CustomValidator control used to implement specific custom validation logic for the client side and the server side validation.

Example:

Server side validation:

            User Name:
<asp:TextBox runat="server" id="txtUserName" />
<asp:CustomValidator runat="server" id="userCustomVal" controltovalidate="txtUserName" onservervalidate="userCustomVal_ServerValidate" errormessage="The text must be at least 4 characters long!" />

C# function:

  protected void userCustomVal_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            if (e.Value.Length == 4)
                e.IsValid = true;
            else
                e.IsValid = false;
        }

Client side validation:

            User Name:
<asp:TextBox runat="server" id="txtUserName" />
<asp:CustomValidator runat="server" id="userCustomVal" controltovalidate="txtUserName" ClientValidationFunction="UserValidation" errormessage="The text must be at least 4 characters long!" />

JavaScript function:

 <script type="text/javascript">
       //syntax 
        function SomeFunction(source, arguments) {
           //user validation logic
        }
    Example:
functionValidateUserName(sender, args) {
var txtUserLength = $('c4u-user').val().length;
if (txtUserLength ==4) {
args.IsValid = true;
    } else {
//return false;
args.IsValid = false;
    }
}
    </script>

Difference between abstract class and interface

Interface:

An interface looks like a class which contains only the declaration of methods, properties, events or indexers and has no implementation for any member.

An interface can be member of class and namespace and interface has below members:

 a.      Methods

b.      Properties

c.       Indexers

d.      Events

Abstract class:

Class uses keyword abstract that enables you to create class members that are incomplete and must be implemented in a derived class.

When a method is declared as abstract in the base class then every derived class of that class must provide its own definition for that method.

Difference between abstract class and interface

Features

Interface

Abstract

Access modifiers

Access modifier is not allowed with interface members everything is default public.

Interface class name you can declare with public and internal access modifier.

An abstract class can contain access modifiers for members i.e functions, properties etc.

Multiple inheritance

A class may inherit several interfaces.

You cannot achieve Multiple inheritances with abstract class.

Implementation

Only declaration is allowed in interface.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Fields and constants

No field and constant implementation in interface.

Implementation allowed.

Use of keyword static, virtual, abstract or sealed.

You cannot use these keywords with interface.

Virtual, abstract allowed with static class but static keyword not allowed.

Use

If multiple class shares method signatures then it is better to use Interfaces.

Reuse of some common methods with new implementation then use abstract class.

Abstract class allows partial implementation.

 

Speed

Compare to abstract speed is less.

Fast

Adding functionality

If you add method to an interface we have to track all classes and implement method in those classes.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.