Monday, August 22, 2011

ASP.NET: Moving ViewState to bottom of page

If you wanted to move the ViewState to the bottom of the page in order to get Google to pay more attention to 
my page and less to the wad of Base64'ed ViewState. 
 
protected override void Render(System.Web.UI.HtmlTextWriter writer) 
{
    System.IO.StringWriter stringWriter = new System.IO.StringWriter();
    HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
    base.Render(htmlWriter);
    string html = stringWriter.ToString();
    int StartPoint = html.IndexOf("<input name="\"__VIEWSTATE\"");</pre" type="\"hidden\"" />
    if (StartPoint >= 0) 
    {
        int EndPoint = html.IndexOf("/>", StartPoint) + 2;
        string viewstateInput = html.Substring(StartPoint, EndPoint - StartPoint);
        html = html.Remove(StartPoint, EndPoint - StartPoint);
        int FormEndStart = html.IndexOf("") - 1;
        if (FormEndStart >= 0) 
        {
            html = html.Insert(FormEndStart, viewstateInput);
        }
    }
    writer.Write(html);
}
 
This method averaged out at 0.000995s. It consistently beat the Regex 
one, even though the Regex one was very simple, the Regexes were 
precompiled. 

Page Life Cycle in ASP.NET

An important article on the different methods and order they are executed during the load of an .aspx web page. ASP.NET.
In this article, we are going to discuss the different methods and order they are executed during the load of an .aspx web page.
When a visitor first requests an .aspx page on your server, the server sends it to the HTTP Pipeline. The HTTP Pipeline handles all processes involved in converting all of the application code into HTML to be interpreted by the browser. The first class initiated is called HttpRuntime. This class finds a free HttpApplication object to start processing the request. The HttpApplication object then runs the appropriate handler assigned in the web.config and machine.config files for the requested extension.
The extension .aspx can be handled by the HandlerClass or HandlerFactory class. The HttpApplication objects starts the IHttpHandler interface which begins processing the application code by calling the processRequest() method.


The processRequest() method then calls the FrameworkInitialize() method which begins building the control trees for the requested page. Now the processRequest() method cycles through the page's life cycle in the order listed below.
Methods Description
Page_Init Page Initialization
LoadViewState View State Loading
LoadPostData Postback Data Processing
Page_Load Page Loading
RaisePostDataChangedEvent PostBack Change Notification
RaisePostBackEvent PostBack Event Handling
Page_PreRender Page Pre Rendering Phase
SaveViewState View State Saving
Page_Render Page Rendering
Page_Unload Page Unloading
The first processed method is Page_Init(). Once the control tree has been created, the controls declared in the .aspx file are initialized. The controls can modify some of the settings set in this method to be used later in the page life cycle. Obviously no other information is available to be modified at this time.
The next processed method is LoadViewState(). The Viewstate contains stored information that is set by the page and controls of the page. This is carried to and from every aspx page request per visitor.

The next processed method is LoadPostData(). These are values associated with the HTML form elements the visitor has typed, changed or selected. Now the control has access to this information which can update their stored information pulled from the Viewstate.
The next processed method is Page_Load(). This method should look familiar and is usually the most common used method on the server side application code for an .aspx file. All code inside of this method is executed once at the beginning of the page.
The next processed method is RaisePostDataChangedEvent(). When a visitor completes a form and presses the submit button, an event is triggered. This change in state signals the page to do something.
The next processed method is RaisePostBackEvent(). This method allows the page to know what event has been triggered and which method to call. If the visitor clicks Button1, then Button1_Click is usually called to perform its function.


The next processed method is Page_PreRender(). This method is the last chance for the Viewstate to be changed based on the PostBackEvent before the page is rendered.
The next processed method is SaveViewState(). This method saves the updated Viewstate to be processed on the next page. The final Viewstate is encoded to the _viewstate hidden field on the page during the page render.
The next processed method is Page_Render(). This method renders all of the application code to be outputted on the page. This action is done with the HtmlWriter object. Each control uses the render method and caches the HTML prior to outputting.
The last processed method is Page_Unload(). During this method, data can be released to free up resources on the server for other processes. Once this method is completed, the HTML is sent to the browser for client side processing.
Now you should have a little bit better understanding of the order of methods executed in the request of an .aspx file.

Wednesday, August 10, 2011

Default Values Table for ASP.NET

The following table shows the default values of value types returned by the default constructors. Default constructors are invoked by using the new operator, as follows:
int myInt = new int();
The preceding statement has the same effect as the following statement:
int myInt = 0;
Remember that using uninitialized variables in C# is not allowed.

Value type

Default value

bool

false

byte

0

char

'\0'

decimal

0.0M

double

0.0D

enum

The value produced by the expression (E)0, where E is the enum identifier.

float

0.0F

int

0

long

0L

sbyte

0

short

0

struct

The value produced by setting all value-type fields to their default values and all reference-type fields to null.

uint

0

ulong

0

ushort

0

Nullable Types in C#

Nullable types are instances of the System.Nullable<T> struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable can be assigned the values true false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

class NullableExample
{
    static void Main()
    {
        int? num = null;
        if (num.HasValue == true)
        {
            System.Console.WriteLine("num = " + num.Value);
        }
        else
        {
            System.Console.WriteLine("num = Null");
        }

        // y is set to zero
        int y = num.GetValueOrDefault();

        // num.Value throws an InvalidOperationException if num.HasValue is false
        try
        {
            y = num.Value;
        }
        catch (System.InvalidOperationException e)
        {
            System.Console.WriteLine(e.Message);
        }
    }
}
 
The example will display the output:
num = Null
Nullable object must have a value.

Using Structs in ASP.NEt

The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color. Although it is just as convenient to represent a point as a class with Auto-Implemented Properties, a struct might be more efficient in some scenarios. For example, if you declare an array of 1000 Point objects, you will allocate additional memory for referencing each object; in this case, a struct would be less expensive. Because the .NET Framework contains an object called Point, the struct in this example is named "CoOrds" instead.

public struct CoOrds
{
    public int x, y;

    public CoOrds(int p1, int p2)
    {
        x = p1;
        y = p2;
    }
} 
 
It is an error to define a default (parameterless) constructor for a struct. It is also an error to initialize an instance field in a struct body. You can initialize struct members only by using a parameterized constructor or by accessing the members individually after the struct is declared. Any private or otherwise inaccessible members can be initialized only in a constructor.
When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. In such a case, there is no constructor call, which makes the allocation more efficient. However, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.
When a struct contains a reference type as a member, the default constructor of the member must be invoked explicitly, otherwise the member remains unassigned and the struct cannot be used. (This results in compiler error CS0171.)
There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class Object. A struct can implement interfaces, and it does that exactly as classes do.
You cannot declare a class using the keyword struct. In C#, classes and structs are semantically different. A struct is a value type, while a class is a reference type. For more information, see Value Types.
Unless you need reference-type semantics, a small class may be more efficiently handled by the system if you declare it as a struct instead.
 

Structure vs Classes in ASP.NET

Structs share most of the same syntax as classes, although structs are more limited than classes:
  • Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
  • A struct cannot declare a default constructor (a constructor without parameters) or a destructor.
  • Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. This is important to remember when working with collections of value types such as Dictionary<string, myStruct>.
  • Structs are value types and classes are reference types.
  • Unlike classes, structs can be instantiated without using a new operator.
  • Structs can declare constructors that have parameters.
  • A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.
  • A struct can implement interfaces.
  • A struct can be used as a nullable type and can be assigned a null value.

Sunday, August 7, 2011

HTTP Status and Error Codes

HTTP Status and Error Codes


During your HTTP sessions, you'll receive various numbered codes from Web servers. When connected via HTTP, CuteFTP displays these codes in the log window. Some codes represent errors. Most others simply communicate the status of the connection. Here are brief explanations for the most common status and error codes.
The list below are standard HTTP codes. Numbers outside this list are proprietary to the Server or Client that you are using.

Error or Status Code Description
100 Series Informational - These status codes indicate a provisional response. The client should be prepared to receive one or more 1xx responses before receiving a regular response.
100 Continue.
101 Switching protocols.
Description
200 Series Success - This class of status codes indicates that the server successfully accepted the client request.
200 The client request has succeeded. This status code indicates that the Web server has successfully processed the request.
201 Created.
202 Accepted.
203 Non-authoritative information.
204 No content.
205 Reset content.
206 Partial content.


300 Series Redirection - The client browser must take more action to fulfill the request. For example, the browser may have to request a different page on the server or repeat the request by using a proxy server.
302 Object moved.
304 Not modified. The client requests a document that is already in its cache and the document has not been modified since it was cached. The client uses the cached copy of the document, instead of downloading it from the server
307 Temporary redirect.


400 Series Client Error - An error occurs, and the client appears to be at fault. For example, the client may request a page that does not exist, or the client may not provide valid authentication information.
400 Bad request.
401 Access denied.
401.1 Logon failed. The logon attempt is unsuccessful, probably because of a user name or password that is not valid.
401.2 Logon failed due to server configuration.
401.3 Unauthorized due to ACL on resource. This indicates a problem with NTFS permissions. This error may occur even if the permissions are correct for the file that you are trying to access. For example, you see this error if the IUSR account does not have access to the C:\Winnt\System32\Inetsrv directory.
401.4 Authorization failed by filter.
401.5 Authorization failed by ISAPI/CGI application.
401.7 Access denied by URL authorization policy on the Web server. This error code is specific to IIS 6.0.
403 Forbidden.
403.1 Execute access forbidden. The following are two common causes of this error message:
  • You do not have enough Execute permissions. For example, you may receive this error message if you try to access an ASP page in a directory where permissions are set to None, or you try to execute a CGI script in a directory with Scripts Only permissions.
  • The script mapping for the file type that you are trying to execute is not set up to recognize the verb that you are using (for example, GET or POST).
403.2 Read access forbidden. Verify that you have Read access to the directory. Also, if you are using a default document, verify that the document exists.
403.3 Write access forbidden. Verify that you have Write access to the directory
403.4 SSL required. Use HTTPS instead of HTTP to access the page.
403.5 SSL 128 required.
403.6 IP address rejected.
403.7 Client certificate required. You do not have a valid client certificate installed
403.8 Site access denied.
403.9 Too many users. The number of users who are connected to the server exceeds the connection limit.
403.10 Invalid configuration.
403.11 Password change.
403.12 Mapper denied access. The page that you want to access requires a client certificate, but the user ID that is mapped to your client certificate has been denied access to the file.
403.13 Client certificate revoked.
403.14 Directory listing denied.
403.15 Client Access Licenses exceeded.
403.16 Client certificate is untrusted or invalid.
403.17 Client certificate has expired or is not yet valid.
403.18 Cannot execute requested URL in the current application pool. This error code is specific to IIS 6.0.
403.19 Cannot execute CGIs for the client in this application pool. This error code is specific to IIS 6.0.
403.20 Passport logon failed. This error code is specific to IIS 6.0.
404 Not found. This error may occur if the file that you are trying to access has been moved or deleted.
404.0 File or directory not found.
404.1 Web site not accessible on the requested port.
404.2 Web service extension lockdown policy prevents this request.
404.3 MIME map policy prevents this request.
405 HTTP verb used to access this page is not allowed (method not allowed).
406 Client browser does not accept the MIME type of the requested page.
407 Proxy authentication required.
412 Precondition failed.
413 Request entity too large.
414 Request-URL too long.
415 Unsupported media type.
416 Requested range not satisfiable.
417 Execution failed.
423 Locked error.


500 Series Server Error - The server cannot complete the request because it encounters an error.
500 Internal server error. You see this error message for a wide variety of server-side errors.
500.12 Application is busy restarting on the Web server. Indicates that you tried to load an ASP page while IIS was in the process of restarting the application. This message should disappear when you refresh the page. If you refresh the page and the message appears again, it may be caused by antivirus software that is scanning your Global.asa file.
500.13 Web server is too busy.
500.15 Direct requests for Global.asa are not allowed.
500.16 UNC authorization credentials incorrect. This error code is specific to IIS 6.0.
500.18 URL authorization store cannot be opened. This error code is specific to IIS 6.0.
500.100 Internal ASP error. You receive this error message when you try to load an ASP page that has errors in the code.
501 Header values specify a configuration that is not implemented.
502 Bad Gateway. Web server received an invalid response while acting as a gateway or proxy. You receive this error message when you try to run a CGI script that does not return a valid set of HTTP headers.
502.1 CGI application timeout.
502.2 Error in CGI application.
503 Service unavailable. This error code is specific to IIS 6.0.
504 Gateway timeout.
505 HTTP version not supported.

HTTP 403 Error and Substatus Error Codes for IIS

In the HTTP protocol used on the World Wide Web, 403 Forbidden is an HTTP status code returned by a web server when a user requests a web page or media that the server does not allow them to. In other words, the server can be reached, but the server declined to allow access to the page. This response is returned by the Apache web server when directory listings have been disabled. Microsoft IIS responds in the same way when directory listings are denied. (This response may also be returned by the server if the client issued a WebDAV PROPFIND request but did not also issue the required Depth header, or issued a Depth header of infinity.)
403 Substatus Error Codes for IIS

    403.1 - Execute access forbidden.
    403.2 - Read access forbidden.
    403.3 - Write access forbidden.
    403.4 - SSL required.
    403.5 - SSL 128 required.
    403.6 - IP address rejected.
    403.7 - Client certificate required.
    403.8 - Site access denied.
    403.9 - Too many users.
    403.10 - Invalid configuration.
    403.11 - Password change.
    403.12 - Mapper denied access.
    403.13 - Client certificate revoked.
    403.14 - Directory listing denied.
    403.15 - Client Access Licenses exceeded.
    403.16 - Client certificate is untrusted or invalid.
    403.17 - Client certificate has expired or is not yet valid.

Source :- http://en.wikipedia.org/wiki/HTTP_403

Friday, August 5, 2011

What is delegates and how do we use them in asp.net?

The delegate is used to declare a reference type that can be used to encapsulate a named or an anonymous method. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure. In asp.net we are using delegates to create custom events for custom controls.
For example, custom pager control most likely needs to have PageChanged event.
We can declare it like this:

public delegate void PageChangedHandler(object sender, EventArgs e);
public event PageChangedHandler PageChanged;

Then whenever we need to fire event:

if (PageChanged != null) // Checks if user assigned any event handler
    PageChanged(this, new EventArgs());

And then we can use our custom pager control as follow:

<cc:PostsPager ID="PostsPager" runat="server" OnPageChanged="PostsPager_PageChanged" />