29 June 2011

Maximum Request Length Exceeded ASP.NET

I got this error Maximum request length exceeded while i was trying to upload several files, or a single big size file. As default, max file upload size is 4MB.
We can easily have a solution by not touching our asp.net c# source code.

Just add a single line of code in your Web.config file, and you are done.

<configuration>
  <system.web>
    <httpRuntime maxRequestLength="32768" />
  </system.web>
</configuration>


Now we will not get maximum request length exceeded error in asp.net.

14 April 2011

C# Convert String to Integer

Converting string to int is simple in c#. There are two comman ways to convert string to int.
  • Convert.ToInt32
  • Int32.TryParse
Here is the screen shot of our string to int converter sample application:


Note that our integer number must be between −2,147,483,648 and +2,147,483,647 range.

The c# source code to convert string to integer:
private void btnConvert_Click(object sender, EventArgs e)
{
int numValue = 0;
string strValue = string.Empty;

strValue = tbInput.Text.Trim();

try
{
numValue = Convert.ToInt32(strValue);
lblResult.Text = numValue.ToString();
}
catch (Exception exc)
{
tbInput.Text = string.Empty;
lblResult.Text = string.Empty;
MessageBox.Show("Error occured:" + exc.Message);
}
}       

private void btnTryParse_Click(object sender, EventArgs e)
{
ConvertToIntTryParse();
}

private void ConvertToIntTryParse()
{
int numValue = 0;
bool result = Int32.TryParse(tbInput.Text, out numValue);
if (true == result)
lblResult.Text = numValue.ToString();
else
MessageBox.Show("Cannot parse string as int number");
}

I think IntTryParse is better to convert string to int, because it handles the parse error inside and returns bool value if the string is parsable to int.
IntTryParse return boolean value, so that if it parses the string it returns true, else returns false.

Note the parsing string with Convert.ToInt32 may cause a FormatException if the parse string value is not suitable.