Archive

Archive for the ‘ASP.Net’ Category

FileNot Found exception – Application_Error event in Global.asax

July 28th, 2010 Anuraj P No comments

Today I got a problem from my colleague, that he is getting FileNot Found exception in Application Error event in Global.asax, which is used to log application errors. But the application was working fine and good. We thought it may be because of missing images that was referring in Stylesheets. But all the image references are valid and we couldn’t find any issue. We couldn’t find anything suspicious in stack trace.

Stack Trace from the exception

at System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String physicalPath, HttpResponse response)
at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context)
at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

After doing some search we got an option where we can find the file causing the exception. We created a string variable and put a break point over there and debugged the code. It will display the filename causing the exception. In our case it was a HTML file which was used in a Javascript to set an IFRAME source, unfortunately the developer who copied the script missed the HTML and it was causing the exception.

Here is the code.

void Application_Error(object sender, EventArgs e)
{
Exception err = Server.GetLastError();
//Insert a break point and run in debug mode.
string fileName = Context.Request.FilePath;
 Application["UnhandledException"] = err;
}

Dropdownlist FindByText Problem

July 15th, 2010 Anuraj P No comments

Today one of my colleague talked about a simple basic issue with Dropdownlist, the FindByText() method works as case sensitive. Because of this issue, we are getting some exceptions. So I starting looking for alternatives and one way I found it looping the items and compare it. Like the following.

this.ddlItems.SelectedIndex = -1;
foreach (ListItem item in this.ddlItems.Items)
{
    if (item.Text.Equals("Item", StringComparison.CurrentCultureIgnoreCase))
    {
        item.Selected = true;
        break;
    }
}

It is a nice option, I rewrote it as an extension method and works fine. Later I thought of wrting more generic FindByTextMethod() and here the extension method.

/// <summary>
/// Searches the Collection of ListItem with a ListItem.Text property contains the specified text
/// </summary>
/// <param name="items"></param>
/// <param name="text">The text to search for.</param>
/// <param name="stringComparison">One of the System.StringComparison values.</param>
/// <returns>ListItem if the collection contains the text, null otherwise.</returns>
public static ListItem FindByText(this ListItemCollection items,
    string text,
    StringComparison comparisonType)
{
    ListItem result = items.OfType<ListItem>().
        FirstOrDefault(_string => _string.Text.Equals(text, comparisonType));
    return result;
}

And you can use it like this

this.ddlItems.Items.FindByText("Item", StringComparison.CurrentCultureIgnoreCase).Selected = true;

Happy Coding ;)

Implementing ASP.Net Forms Authentication with Active Directory Membership Provider

June 29th, 2010 Anuraj P No comments

ActiveDirectoryMembership provider is used manage users against Active Directory, which helps to create Single Sign On for intranet application. Here is a basic implementation, which used to Authenticate users against Active Directory, using Login Control.

We need to modify the web.config, like the implementation of Forms Authentication in ASP.Net.

Create / Add a connection string to active directory database.

<connectionStrings>
<add name="ADConnectionString" connectionString="LDAP://DOMAIN.SUBDOMAIN/DC=DOMAIN,DC= SUBDOMAIN "/>
</connectionStrings>

Configure Membership node in the web.config with ActiveDirectoryMembershipProvider.

<membership defaultProvider="MembershipADProvider">
  <providers>
    <add name="MembershipADProvider"
         type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
         applicationName="dotnetthoughts"
         connectionStringName=" ADConnectionString "
         attributeMapUsername="sAMAccountName"/>
  </providers>
</membership>

You can also provide the Username / Password in this using connectionUsername , connectionPassword attributes.

Modify the Authentication mode and Authorization nodes for controlling the access permissions. Currently I am using Forms Authentication defaults. (default.aspx – Home Page, and Login.aspx – Login Page)

<authentication mode="Forms" />
<authorization>
    <deny users="?" />
    <allow users="*" />
</authorization>

Almost done. Now drag and drop Login control from Toolbox > Login tab to Login.aspx. Run the application, say OK to the Debug mode confirmation from Visual Studio. As we are configured the Authentication provider we don’t need to write any Code to Authentication.

If you don’t want to use login control, you can do something like this in the code behind for the authentication.

if (Membership.ValidateUser(this.txtUsername.Text, this.txtPassword.Text))
{
    FormsAuthentication.RedirectFromLoginPage(this.txtUsername.Text, false);
}
else
{
    Response.Write("Authentication failed.\nUsername / Password Invalid");
}

Thanks to Sreenaja for the initial implementation. Happy Coding :)

ASP.Net Default button and Master Pages

June 21st, 2010 Anuraj P 3 comments

Last few days I was(am) busy with one pure ASP.Net application(why its pure because we are not using any 3rd party controls, ajax nothing. Everything is postbacking ;) ). Today I got a weird bug from one of my QC team saying when ever they presses ENTER button, focus is on any textbox, it popups Help window from our application. In our application, end users can open the Help window, by clicking on some help images icons provided in the application. These images are displayed using ASP Image button controls (If you are using ASP Image controls this problem will not occur, but in our application, we need to disable it some scenarios, so can’t use ASP Image). After searching I found the issue with the default button property of ASP.Net, which helps us to submit the form using Enter Key. In my page ASP.Net considering the Help image button as default button for the Page. We can set the default button to our submit button using various methods. Set the default button property of the FORM, or create a Panel control over the controls and set the default button property of the Panel.

<form id="form1" runat="server" defaultbutton="cmdSubmit">
<asp:Panel runat="server" ID="plMain" DefaultButton="cmdSubmit">

Form tag also supports “defaultfocus” this property allows to focus to control, on Page Load.

<form id="form1" runat="server" defaultbutton="cmdSubmit" defaultfocus="txtUser">

If you are using Master Pages, there will be some slight difference because, the Form tag will not be available in the content Pages. It can fix using code behind, using FindControl method.

(Page.Master.FindControl("Form1") as HtmlForm).DefaultButton = this.cmdSubmit.UniqueID;

Also you can do something like this

Page.Master.Page.Form.DefaultButton = cmdSubmit.UniqueID;

Happy Coding :)

Pass your own arguments to the ClientValidationFunction in a CustomValidator

May 30th, 2010 Anuraj P No comments

Last few days I am working on an ASP.Net, where I can create Grids, Dropdown lists with Post back :) , and the best part is browser compatibility, client only requires compatible with IE. Yes it was a refresher course for me, I revisited GridView templates, Page.IsPostback checking etc. Today I got a requirement like I need to validate few radio buttons. I searched for an implementation, I found we can use required field validator for RadioButtonList, but in my case it was Radio buttons (Initially it was RadioButtonList, but due to some customization issues, I changed it to Radio Buttons). Then I implemented a custom validator, and in the client validation function I hardcoded the Radio Button ids, because for the client validation function we can’t pass the parameters to the function. Same problem again I faced in a GridView, where the problem I found was I won’t get the client id of the radio button in the Item template. :( After doing some research I found we can extend the custom validator control using Validation Framework. And here is the implementation. Using this we can add properties to the source / sender parameter in the client side validation function.

function ValidateRadioButtons(source, arguments) {
    var radio1 = document.getElementById(source.Radio1);
    var radio2 = document.getElementById(source.Radio2);
    var radio4 = document.getElementById(source.Radio4);
    var radio3 = document.getElementById(source.Radio3);
    var result = radio1.checked || radio2.checked || radio3.checked || radio4.checked;
    arguments.IsValid = result;
}

This is the JavaScript function which implements the validation logic. You can get the controls as part of the Source object. To get the Source.Radio1, you need to register the Radio1 as ClientValidator attribute. You can do some C# code like this.

protected void Page_Load(object sender, EventArgs e)
{
    this.Page.ClientScript.RegisterExpandoAttribute(customCheck.ClientID, "Radio1", this.radio1.ClientID, false);
    this.Page.ClientScript.RegisterExpandoAttribute(customCheck.ClientID, "Radio2", this.radio2.ClientID, false);
    this.Page.ClientScript.RegisterExpandoAttribute(customCheck.ClientID, "Radio3", this.radio3.ClientID, false);
    this.Page.ClientScript.RegisterExpandoAttribute(customCheck.ClientID, "Radio4", this.radio4.ClientID, false);
}

And the ASPX Code is like this

<asp:CustomValidator runat="server" ID="customCheck" ClientValidationFunction="ValidateRadioButtons"
        ErrorMessage="Choose any option" />

And here is the Output code generated for the custom validator.

Custom validator output rendering

Custom validator output rendering

Happy Coding.

Convert string to enum

April 19th, 2010 Anuraj P No comments

Sometimes we may need to read a Config value using ConfigurationSettings.AppSettings and assign it to a Enum. This function helps to convert a string to Enum.

/// <summary>
/// Function to retrive Enum value by giving the corresponding string value.(This method is case sensitive)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns>Enum value</returns>
public static T ToEnum<T>(string value)
{
    //This method will throw error if the case of the value is different from the
    //enum value.
    if (Enum.IsDefined(typeof(T), value))
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }
    throw new ArgumentException("Value doesn't exists in the Enum");
}
Categories: .Net, .Net 3.0 / 3.5, ASP.Net Tags: , , ,