What’s the difference between maxRequestLength and maxAllowedContentLength

I don’t pay too much attention to what’s in the web.config so I always learn something when someone asks me how/why something works in the web.config.

When you see maxRequestLength (in system.web) and maxAllowedContentLength (in system.webServer) you ask why are 2 different attributes on length allowed.

They do serve different purposes.

maxRequestLength sets the max file upload size supported by ASP.NET.  The default size is 4096 KILOBYTES (4 MB).

maxAllowedContentLength sets the max length of content in a request supported by IIS. The default size is 30000000 BYTES (~28.6 MB).

NOTICE ONE IS IN KILOBYTES AND ONE IS IN BYTES!

Now why do you care about these settings.  If you are trying to upload large files (like images or documents) you need to be aware that you may need to adjust your maxRequestLength.  Then if files are really big you may need to adjust the maxAllowedContentLength.

What setting is the smallest takes precedence.

 

 

 

Add your own error message to a ValidationSummary

There are time where you need to display a message to the users.  Here’s how to do it with a Validation Summary on your ASP.NET page.
I use this when I want to display an error message that doesn’t come from an exception or another validation.
This is helpful when you want all messages to have the same look and feel.
You MUST have a validation summary on your page otherwise nothing happens.

Below is the code.

CustomValidator val = new CustomValidator();
val.IsValid = false;
val.ErrorMessage = "My error message for the ValidationSummary";
this.Page.Validators.Add(val);

You create create a custom validator, set it to invalid, define the error message, and add it to your page.

[tweetmeme only_single=”false”]

How to get a reference to the control that caused a post back

Here is some old code I found (in VB.NET) the will tell you what control caused the post back.

  ' Return a reference to the control that caused the last postback,
'  even from the Page_Load event!
' It requires in input a reference to the posted-back page
' (this is necessary if you want to be able to move this function in a separate 
' class
' instead of in a page's codebehind class
'
' Example:
'    Private Sub Page_Load(ByVal sender As System.Object,
'  ByVal e As System.EventArgs) Handles MyBase.Load
'        Dim postbackCtl As Control = GetPostbackControl(Me)
'        If Not postbackCtl Is Nothing Then
'            lblResult.Text = postbackCtl.ID
'        End If
'    End Sub

Function GetPostbackControl(ByVal targPage As Page) As Control
    If targPage.IsPostBack Then
        ' try to find the name of the postback control in the hidden 
        ' __EVENTTARGET field
        Dim ctlName As String = targPage.Request.Form("__EVENTTARGET")
        ' if the string is not null, return the control with that name
        If ctlName.Trim().Length > 0 Then
            Return targPage.FindControl(ctlName)
        End If
        ' the trick above does not work if the postback is caused by standard 
        ' buttons.
        ' In that case we retrieve the control the ASP-way: by looking in the 
        ' Page's Form collection
        ' to find the name of a button control, that actually is the control 
        ' that submitted the page
        Dim keyName As String
        For Each keyName In targPage.Request.Form
            Dim ctl As Control = targPage.FindControl(keyName)
            ' if a control named as this key exists,
            '  check whether it is a button - if it is, return it!
            If Not ctl Is Nothing Then
                If TypeOf ctl Is Button Then
                    Return ctl
                End If
            End If
        Next
    End If

    Return Nothing
End Function
[tweetmeme only_single=”false”]

Generic handle error method

Here is a generic handle error method I put in my catches.  It will send an email with the inner exception unless it’s null then you get the exception message.  The stack trace is included.

You should the subject from “Application Name” to whatever your application is.
Also you should check out a previous post about a generic send mail method since this method calls that one.

private static void HandleError(Exception ex)
        {
            String errorMessage = String.Empty;

            if (ex.InnerException != null)
            {
                errorMessage = ex.InnerException.ToString();
            }
            else
            {
                errorMessage = ex.Message.ToString();
            }

            var trace = new System.Diagnostics.StackTrace(ex);

            StringBuilder errorBodyString = new StringBuilder();

            errorBodyString = errorBodyString.Append("Exception:" + errorMessage);
            errorBodyString = errorBodyString.Append("<br />");
            errorBodyString = errorBodyString.Append(trace);

String Subject = "Application Name";
            String Body = errorMessage;

           // sendNotification(Subject, errorBodyString.ToString());
        
[tweetmeme only_single=”false”]

How to add a row click event to a gridview

So I ran across the problem of I need a web page to do something if a user clicked a row in a grid.
It wasn’t going to work for the user to click a button, the whole row had to be clickable.

Adding a row data bound event solved the problem.
I also change the background color on mouse over (and mouse out).

When the user clicks the row they get redirected to a page (with a query string parm so I know what row they clicked on).

 

   1: protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)

   2: {

   3:     if (e.Row.RowType == DataControlRowType.DataRow)

   4:     {

   5:         e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#ceedfc'");

   6:         e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=''");

   7:         e.Row.Attributes.Add("style", "cursor:pointer;");

   8:         e.Row.Attributes.Add("onclick", "location='detail.aspx?id=" + e.Row.Cells[0].Text + "'");

   9:     }

  10: }

Clear Controls on screen

Here is a method that will clear all the controls on your screen (as long as it matches one of the controls in the method).  It recursively calls itself until all the controls are clear.

Here is an example of how you call it:
ClearControlsOnScreen(this.Page);

  public void ClearControlsOnScreen(Control parent)
        {
            try
            {
                foreach (Control _ChildControl in parent.Controls)
                {
                    if ((_ChildControl.Controls.Count > 0))
                    {
                        ClearControlsOnScreen(_ChildControl);
                    }
                    else
                    {

                        TextBox textbox = _ChildControl as TextBox;
                        if (textbox != null)
                        {
                            textbox.Text = string.Empty;
                        }

                        DropDownList dropdownlist = _ChildControl as DropDownList;
                        if (dropdownlist != null)
                        {
                            dropdownlist.ClearSelection();
                        }

                        CheckBox checkBox = _ChildControl as CheckBox;
                        if (checkBox != null)
                        {
                            checkBox.Checked = false;
                        }

                        CheckBoxList checkBoxList = _ChildControl as CheckBoxList;
                        if (checkBoxList != null)
                        {
                            checkBoxList.ClearSelection();
                        }

                        GridView gridView = _ChildControl as GridView;
                        if (gridView != null)
                        {
                            gridView.DataSource = null;
                            gridView.DataBind();
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                throw ;
            }
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Need to run jQuery and Mootools side by side

You can run both jQuery and Mootools libraries on the same site, but there is a trick.

Add the link jQuery.noConflict(); to that last line in your jQuery js libary (jquery-1.3.2.min.js)

This will change the namespace that jQuery uses from $ to jQuery.  This way jQuery and Mootools won’t step all over each other.

You do have to change all your jQuery functions to use jQuery instead of $.

I assume this works also if you trying to integrate jQuery with the ASP.NET Ajax libraries, but I have not tested it in that scenario.

Here is a link explaining in more detail.
http://docs.jquery.com/Core/jQuery.noConflict

How to programmatically determine the current method name

If you want to determine the current method in code (C#) here is the line of code you need.

MethodInfo.GetCurrentMethod().Name

This call will return the current method name as a string.  (It is from the namespace System.Reflection).

Why is this helpful?  If you write a generic logging routine and want to log the current method this is a big help.  So you don’t need to modify your log error call (in your catch) with anything not generic (like hard coding your method name).

 

Here is an example of this.

String currentMethodName = MethodInfo.GetCurrentMethod().Name;

 

If this line is in the Page_Load method, it returns “Page_Load”

Change row color in Gridview on mouse over

If you have the need to change the row color of a row in a gridview when you mouse over (and mouse out) you can add some code to the RowDataBound event.

Here is a sample:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{
//Only apply to data rows
if (e.Row.RowType == DataControlRowType.DataRow)
{

//Add mouse over event to change row background color
e.Row.Attributes.Add(“onmouseover”, “this.style.backgroundColor=’Yellow'”);

//Add mouse out event to change row background color back to white
e.Row.Attributes.Add(“onmouseout”, “this.style.backgroundColor=White”);

}

}

Here is the blog site where I found this sample.

Eliminate the Modal popup flicker

One problem with Ajax modal popup is that when the page first loads up whatever is on the popup panel will flicker on the screen.
The slower your pc or connection is the more pronounced the flicker.

After doing some research, I found the answer on this blog (it has an example).  It turns out to be really simple.  Just add style=”display:none” on your pop panel.

Poof, no more flicker.