Archive

Archive for the ‘ASP.Net’ Category

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: , , ,

System.InvalidOperationException – The length of the string exceeds the value set on the maxJsonLength property.

April 16th, 2010 Anuraj P No comments

Yesterday I got a problem from one of my friend; he is getting a Javascript exception from some Ajax Page methods. The exception occurred when he tried to return a very long string from web method. The exception was like this.

Error: Sys.Net.WebServiceFailedException: The server method ‘WebServiceMethod’ failed with the following error: System.InvalidOperationException– Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

After doing some searching we resolved it. You can resolve this error by modifying the web.config file, and add / modify the Configuring JSON Serialization.

<configuration>
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="5000"/>
      </webServices>
    </scripting>
  </system.web.extensions>
</configuration>

The default length is 102400.
You can get more information about this from MSDN : http://msdn.microsoft.com/en-us/library/bb763183.aspx

Compiler Error Message: CS0016: Could not write to output file – Access is denied.

April 14th, 2010 Anuraj P No comments

Last Sunday the Support guys in my machine, updated the OS(Windows Vista) and monday onwards while running my web application, I got a strange error,

Compiler Error Message: CS0016: Could not write to output file - Access is denied.

Compiler Error Message: CS0016: Could not write to output file - Access is denied.

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0016: Could not write to output file ‘c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\myapp\xxxxx\xxxxx\App_GlobalResources.xxxxxxx.dll’ — ‘Access is denied. ‘

I was not done anything in the Global Resources file, but it was showing the error related to this. After doing some searching, I found it can be an issue with Antivirus software. I stopped the Antivirus software and tried, but still the problem was there. Later I found it was related to permission issue in the Temp folder. To resolve this.

  1. Go to %Systemroot%, normally C:\WINDOWS or C:\WINNT
  2. Right-click the Temporary folder (mine is C:\WINDOWS\Temp) and select Sharing and Security.
  3. Select the Security tab and take a look at the list of “Group or user names:”
  4. NETWORK SERVICE should be in the list. If it is not, click Add and type Network Service in the text box.
  5. Make sure NETWORK SERVICE have Full Control in the Permissions list. Click OK.
  6. Restart IIS (Run iisreset)

If your machine doesn’t have NETWORK SERVICE or NETWORK SERVICES Group, look for “IIS_IUSRS” and apply same permissions.

How To Convert XMLNodeList To DataTable

April 14th, 2010 Anuraj P No comments

After doing an XPath selection using .Net, using XmlDocument.SelectNodes(), it will return XMLNodeList class, sometimes we required to convert the XMLNodeList to Data Table for binding purposes. I couldn’t find a direct way, only way is using looping through the Nodes.

/// <summary>
    /// Converts an XMLNodelist object to data table.
    /// </summary>
    /// <param name="xmlNodeList">The XMLNodeList to convert to DataTable.</param>
    /// <param name="Columns">The columns required for the DataTable, using this parameter the
    /// data will be fetched from xmlnodelist.</param>
    /// <returns>DataTable with columns specified in the Columns parameter</returns>
    public DataTable XmlNodeListToDataTable(XmlNodeList xmlNodeList, string[] Columns)
    {
        //Creating the DataTable.
        using (DataTable dataTable = new DataTable("DataTable"))
        {
            //Adding data Table columns based on the columns parameter
            foreach (string column in Columns)
            {
                dataTable.Columns.Add(column);
            }
            //Adding rows with values.
            DataRow dataRow;
            foreach (XmlNode node in xmlNodeList)
            {
                dataRow = dataTable.NewRow();
                foreach (string column in Columns)
                {
                    dataRow[column] = node.SelectSingleNode(column).InnerText;
                }
                dataTable.Rows.Add(dataRow);
            }
            return dataTable;
        }
    }

You can also create the columns dynamically, but you need to check for duplicate Data Columns.