Wednesday, September 28, 2011

Remove security question answer fields from 4 createUserWizard

This can easily be done using a setting in web.config file like this:

<membership defaultProvider="MyCustomProvider">
<add name=" MyCustomProvider " type="System.Web.Security.SqlMembershipProvider"
connectionStringName="SQL" minRequiredPasswordLength="5"
requiresQuestionAndAnswer="false" />

If you are using the default membership provider of, then you can easily switch off the security
question and answer fields by adding the 'requiresQuestionAndAnswer' attribute in your web.config's
membership provider tag. I did not get this attribute in auto list but works correct after adding it works well.

Forms Authentication with roles in ASP.NET with C#

Create a New Project
Create a new project, you can use Visual Web Developer or Visual studio to do that and
create folder structure like below.

Note that I have Admin folder create, secure and easy to differentiate access based on user roles. 

Admin folder in my case will request access to those whose role is "Admin" and "User". Folder 

user will request access only to those whose role is "user" insurance binder and have access to all 

authenticated users At least, no matter what role they have. Each folder has a file. Aspx page that 

displays welcome message, as shown in the first image above.

Creating settings for Web.Config file
Add authentication option following in the web.config file in <system.web>.

  <authentication Mode = "Forms">
        <form DefaultUrl = "default.aspx" loginUrl = "~ / login.aspx" "true"
                                                                                              slidingExpiration ="" timeout = "20">

For each user to protect a specific folder, you can place fit for them, either in the parent web.config file 
(root folder) or the web.config file in the folder.Specifying paper settings for the folder in the root 
web.config file (in this case to the Administration)

<location path ="Admin">
        <allow roles = "admin" />
        <deny users="*" />

Enter this code outside <configuration> <system.web> but under the label of the root web.config file. 
Here I am specifying that if the path contains the name of the administrator folder and only users with 
"admin" roles are allowed and all other users are denied.

Specifying paper settings for the folder in the web.config file specific folder (in this case the user)
        <allow Roles = "usuario" />
        <deny Users= "*" />
    </ Authorization>
</ System.web>

Enter this code in web.config file folder user. You can specify settings for the user in the root web.config 
file also how I've done for the previous administration. This is just another way of specifying the 
configuration. This configuration should be placed on the label <configuration>.

Specify settings for the authenticated user
        <Deny Users = "?" />
    </ Authorization>
</ System.web>

Type the following code in the web.config secure folder. This is the specification that all users are denied 
anonymous this folder and only authenticated users can, regardless of their functions.

User Authentication
Assuming you have gone through my previous article mentioned, you have a login page. Now when the user 
clicks the Login button fires Authenticate method allows the code from that method.

private void get()
            string userName = loginControl.UserName;
            string password = loginControl.Password;
            bool rememberUserName = loginControl.RememberMeSet;
            // for this demo purpose, I am storing user details into xml file
            string dataPath = Server.MapPath("~/App_Data/UserInformation.xml");
            DataSet dSet = new DataSet();
            DataRow[] rows = dSet.Tables[0].Select(String.Format(" UserName = '{0}' AND Password = 

                                    '{1}'", userName, password));
            // record validated
            if (rows.Length > 0)
                // get the role now
                string roles = rows[0]["Roles"].ToString();
                // Create forms authentication ticket
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1, // Ticket version
                    userName, // Username to be associated with this ticket
                    DateTime.Now, // Date/time ticket was issued
                    DateTime.Now.AddMinutes(50), // Date and time the cookie will expire
                    rememberUserName, // if user has chcked rememebr me then create persistent cookie
                    roles, // store the user data, in this case roles of the user
                    FormsAuthentication.FormsCookiePath); // Cookie path specified in the web.config 

                                                     //file in <Forms> tag if any.
                                                 // To give more security it is suggested to hash it
                string hashCookies = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies); 

                                                             // Hashed ticket
                // Add the cookie to the response, user browser
                // Get the requested page from the url
                string returnUrl = Request.QueryString["ReturnUrl"];
                // check if it exists, if not then redirect to default page
                if (returnUrl == null) returnUrl = "~/Default.aspx";
            else // wrong username and password
                // do nothing, Login control will automatically show the failure message
                // if you are not using Login control, show the failure message explicitely

In the above method, I used the UserInformation.xml file that contains the credentials and role information to the user.

I Reding xml file and get all the users credentials in the data set and using the method of DataTable.Select, I'm
filtering based on user registration and password. If you find a record, then I'm adding the entry into FormsAuthentication cookie encrypt and then redirected to the requested URL in your otherwise the default page.

Note that I have not used standard method FormsAuthentication.RedirectFromLoginPage FormsAuthenticate
method to redirect the login page after authentication of users, not to establish the role of users in the cookie and I will not be able to validate users based on the paper. To add functions to users in the authentication ticket, I used the FormsAuthenticationTicket class and pass the required data as parameter (Note that the roles are passed as constructor parameter FormsAuthenticationTicket UserData).

So far we have set the forms authentication ticket with the required data, including user roles in the cookie, now how to retrive the information about each request and that a request comes from the paper type? So we must use the event Global.asx Application_AuthenticateRequest file. See the code below.
protected void Application_AuthenticateRequest(object sender, EventArgs e)
              // Check if the safety information that exists for this request
            if (HttpContext. Current.User != null)
                // Check if the user is authenticated, any authenticated cookie (ticket) which exists to this user
                if (HttpContext. Current.User.Identity.IsAuthenticated)
                    // Check if authentication is done by FormsAuthentication
                    if (HttpContext. Current.User.Identity is FormsIdentity)
                        // Get roles for this application stored entry
                        // Get the user's identity
                        FormsIdentity identity =(FormsIdentityHttpContext.Current.User.Identity;
                        // Get the ticket authetication ways for the user
                        FormsAuthenticationTicket ticket  = identity.Ticket;
                        // Get the roles stored in the entry as UserData
                        String [] roles = ticket.UserData.Split (',');
                        // Create generic principal and assign it to the current request
                        HttpContext.Current.User = new System.Security.Principal. GenericPrincipal (identity, roles);

This even after checking the user exists, he / she is authenticated and the user type is FormsIdentity identy
number, I am getting the actual identity of the user and get the ticket I have put in the time Authentiacting.
Once you have authenticated the note, I just got the UserData of the bill, which was divided for the papers
(remember he had kept the papers as comma separated values). Now we have the current users roles so we
can move to the current user in the GenericPrincipal the current identity and assign this to the user object
curent. This allows us to use the IsInRole method to check whether a user belongs to a particular function
or not.

How to check if the user has a particular role?

To check whether a user belongs to a particulr paper, use the code below. This code returns true if the current
 record is from the user is authenticated and has a role as an administrator.

HttpContext. Current.User.IsInRole ("admin")

How to check if the user is authenticated?

To check whether the user is authenticated or not, use the code below.

HttpContext. Current.User.Identity.IsAuthenticated

For authenticated user name

HttpContext. Current.User.Identity.Name

If you've followed the steps, you should try runnig application. Try logging in as administrator you can access all pages (Admin, User, insurance, home). Try to login as a user and the user can access, home insurance, but not management. Try logging in as safe and you will be able to access a secure home, but the non-administrator. Try to visit all the links and you can access links Home only.

Friday, September 23, 2011

A potentially dangerous Request.Form value was detected from the client

Server Error in '/' Application.

A potentially dangerous Request.Form value was detected from the client (txtCode="<br/>").
Description: Request Validation has detected a potentially dangerous client input value, and processing of 
the request has been aborted. This value may indicate an attempt to compromise the security of your application, 
such as a cross-site scripting attack. To allow pages to override application request validation settings, set the 
requestValidationMode attribute in the httpRuntime configuration section to requestValidationMode="2.0". 
Example: <httpRuntime requestValidationMode="2.0" />. After setting this value, you can then disable request
validation by setting validateRequest="false" in the Page directive or in the <pages> configuration section. 
However, it is strongly recommended that your application explicitly check all inputs in this case. For more 
information, see 

Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form 
value was detected from the client (txtCode="<br/>").

You have to do little modification to you application to get this fixed. 
1. Add <httpRuntime requestValidationMode="2.0" /> in your application web.config
   under <system.web>.
    <httpRuntime  requestValidationMode="2.0"/>

2. Add RequestValidation="false" on your page or in web.config <pages> 
<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest = "false"

to work this for whole application do in web.config as:
    <httpRuntime  requestValidationMode="2.0"/>
    <pages validateRequest ="false"></pages> 

Parameters Vs Arguments

The parameter refers to any statement in the parentheses following the function
name in a function declaration or definition, the argument is any expression
inside the parentheses of a function call.

Defination 1.parameter procedure used in
      2.arguments used in the procedure call

This example demonstrates the difference between a parameter and an argument:

void foo (int a, char b) / / b are parameters,
here the procedure is to define

int main ()
foo (5, 'a') / / 5 and 'a' are the arguments,
Here the procedure is called
return 0;

Tuesday, September 20, 2011

Response.Redirect cannot be called in a Page callback - DevExpress


DevExpress Web controls generates callback to refresh the controls and pass data between events. When we using some Callback panel or ASPxGridView callbacks event methods then we cannot call Respose.Redirect method to navigate between pages. If we use these methods then it will raise exception.


To avoid these exception use the ASPxWebControl.RedirectOnCallback method to rather than pages.Response.Redirect() because it does not work in a callback. Let you have created a callback with “MYCallback_Callback” event handler method then at the callback method you should use below ASPxWebControl.RedirectOnCallback method to redirect on another page.

DevExpress.Web.ASPxClasses.ASPxWebControl.RedirectOnCallback("~/MyPage.aspx?id="+ e.Parameter);

You will not be able to use Response.Redirect () or Server.Transfer () in a callback to check if the control has a client event can be used instead, if this event can use window.location.replace("MyPage.aspx"), using JavaScript on the client to move to another page.

Monday, September 19, 2011

Hot to Get Public Key Token of Assembly Within Visual Studio Solution( Components etc)

In Visual Studio, go to the Tools menu and choose External Tools.
That brings up a new dialog window.  Click the Add button and add the following:
Title: Get &PublicKeyToken
Command: C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\sn.exe
The path of sn.exe could be change according to Visual studio version or windows version.
At my work computer i got at C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin and
C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\ directories
in windows XP operating system.
Arguments: -Tp $(TargetPath)
Check the Use Output Window checkbox.  The final looks like this:
Create a project and sign it using a strong name key by opening properties of the project and go to the Signing section and do as in the diagram.

Then choose Tools / Get PublicKeyToken, and in the output window you will see something like the following:
Microsoft (R) .NET Framework Strong Name Utility  Version 3.5.21022.8
Copyright (c) Microsoft Corporation.  All rights reserved.

Public key is

Public key token is 9589fa1be527eb6c
Just copy the last value and put it into your assembly's 5-part name.
It could be achieved by  loading ildasm, copying the public key token, and then manually removing
the spaces from that value.  Or, more recently, loading up Reflector and loading the assembly just to
get the public key token.  Never even thought of this time saver, just using sn.exe from Visual Studio
as an external tool.

Windows Forms Data Binding - Data Binding Interfaces

.NET provides a standard set of interfaces related to data binding. Each of these interfaces is described next:
Any class that implements the IList interface must support a list of homogenous types. That is, all list items must be of the same type. The first item in the list always determines the type. Some of the base classes that implement IList include Array, ArrayList, CollectionBase, DataView, and DataViewManager.
Typed IList
Similar to IList, the list must be of homogenous types. However, the type of the items in the list must be known at compile time.
IList and IComponent
When a class implements both IList and IComponent, the class can be data bound at design time.
This interface allows an object to “act” like a list for data binding purposes. The implemented object is not an instance of IList, but it should be able to provide one. The DataSet and DataTable classes both implement this interface. IListSource provides a single property and a single method, which are described next:
ContainsListCollection: Indicates whether the collection is a collection of IList objects. For the DataSet implementation, this property returns True, because the DataSet class contains a collection of collections. For the DataTable implementation, this property returns False, because the DataTable class contains a collection of objects. In simple terms, implement this property to indicate how deep to go for returning a bindable list.

GetList: Returns the IList object that will be data-bound. The DataSet class uses this property to return a DataViewManager object. The DataTable class uses this property to return a DataView object.
This interface allows a collection object to expose its items’ properties. This interface is useful in situations where the public properties of the collection object should be different from the properties available for data binding. This interface is also necessary during complex binding when a list is empty but you still need to know the property names of the list items. (Remember, the IList class alone uses the data type of the first item in the list.) This is useful when columns headers should be created for empty lists.
This interface offers change notification when the list or list items have changed. There is one property, SupportsChangeNotification, which indicates whether this interface’s ListChanged event should be raised. The ListChangedEventArgs class contains a property named ListChangedType that describes the type of change that occurred. The available ListChangedType enumeration members are as follows:
ItemAdded: An item has been added to the list. The index of the new item is the value of the NewIndex property of the ListChangedEventArgs class.
ItemChanged: An item in the list has been changed. The index of the changed item is the value of the NewIndex property of the ListChangedEventArgs class.
ItemDeleted: An item has been removed from the list. The index of the deleted item is the value of the NewIndex property of the ListChangedEventArgs class.

ItemMoved: An item has been moved to another location within the list. The previous index is the value of the OldIndex property of the ListChangedEventArgs class. The new index is the value of the NewIndexproperty of the ListChangedEventArgs class.
PropertyDescriptorAdded: A PropertyDescriptor object has been added.
PropertyDescriptorChanged: A PropertyDescriptor object has been changed.
PropertyDescriptorDeleted: A PropertyDescriptor object has been deleted.
Reset: The list has a lot of changes and controls should refresh themselves.
This interface supports transaction-like operations. It allows objects to specify when changes should be made permanent. Hence, it allows changes to be rolled back. The DataGrid control is one control that opts to call methods of this interface. The following methods are defined in this interface:
BeginEdit: Signals that an edit operation has started. Any changes to the object should be temporarily stored after this method has been called. When implementing this method, be sure that back-to-back calls are non-destructive. That is, the method itself should not cause any changes to any temporary objects.
CancelEdit: Cancels any changes made after the BeginEdit call. In other words, all temporary objects can be destroyed when this method is called.
EndEdit: Commits any changes made after the BeginEdit call. Once this method is called, changes cannot and should not be rolled back.

The following example illustrates the
IEditableObject class with an implementation of a Customer class.
using System.ComponentModel;
public class Customer : IEditableObject
    private bool _transactionStarted = false;
    private string _originalFirstName;
    private string _originalLastName;
    private string _originalPhoneNumber;
    public string FirstName
            return _firstName;
            _firstName = value;
    public string LastName
            return _lastName;
            _lastName = value;
    public string PhoneNumber
            return _phoneNumber;
            _phoneNumber = value;
    public void BeginEdit()
        if (!_transactionStarted)
            _transactionStarted = true;
            _originalFirstName = _firstName;
            _originalLastName = _lastName;
            _originalPhoneNumber = _phoneNumber;
    public void CancelEdit()
        if (_transactionStarted)
            _transactionStarted = false;
            _firstName = _originalFirstName;
            _lastName = _originalLastName;
            _phoneNumber = _originalPhoneNumber;
    public void EndEdit()
        if (_transactionStarted)
            _transactionStarted = false;
            _originalFirstName = "";
            _originalLastName = "";
            _originalPhoneNumber = "";
This interface offers custom error information to which controls can bind. During data binding, this allows controls to retrieve specific error information from the data source itself. For example, if a particular column in a DataTable object has an Integer type, setting a field to a string value for this column will cause the data source to return an appropriate error. This interface provides the following two properties:
Error: Returns an error message indicating what is wrong.
Item: An indexer that gets the error message for the specified column name or property name.