Thursday, August 30, 2007

GridView

  • GridView provides a tabular grid-like view of the contents of a data source
  • The GridView is designed to leverage the new data source object model, and it works best when bound to a data source control via the DataSourceID property
  • A Grid can have delcared and auto generated columns at the same time
  • Auto-generated columns are not added to the Columns collection
  • The GridView doesn't support the AllowCustomPaging property found in DataGrid
  • Compared to the DataGrid control, the GridView provides an extended eventing model; pre/post pairs of events, with cancelling and more
  • It is declared as:

    public class Gridview : CompositeDataBoundControl, IcallbackContainer, ICallbackEventHandler

Properties of GridView Control

AllowPaging, AllowSorting

Support for Paging, Sorting

AutoGenerateColumns

Default is true

AutoGeneratexxxButton

Delete, Edit and Select buttons can be displayed with each reord

DataMember

Specifies which table to be bind from the DataSource

DataSource/DataSourceID

Indicates the bound data source control

EnableSortingAnd PagingCallbacks

 

SortDirection

 

SortExpression

 

UseAccessibleHeader

 
  • GridView has some Style properties like AlternatingRowStyle, EditRowStyle, HeaderStyle, FooterStyle, PagerStyle, RowStyle, SelectedRowStyle
  • GridView appearence properties include BackImageUrl, Caption, GridLines, PagerSettings, ShowFooter
  • Templating properties are EmptyDataTemplate and PagerTemplate
  • State Properties include: DataKeyNames, DataKeys, PageCount, SelectedIndex, SelectedRow, SelectedValue

Events Fired by the GridView Control

PageIndexChanging, PageIndexChanged

RowDeleting, RowDeleted

RowCancellingEdit

RowEditing

RowCommand

RowUpdating, RowUpdated

RowCreated

SelectedIndexChanging SelectedIndexChanged

RowDataBound

Sorting, Sorted


 

Configuring Columns

  • Columns can Programatically be defined as:


     

    BoundField field = new BoundField();

    Field.DataField = "companyname";

    Field.HeaderText = "Company Name";

    grid.ColumnFields.Add(field);


 

  • Columns can be Declaratively defines as:


     

    <columns>

    <asp:boundfield datafield="customerid" headertext="ID"/>

    </columns>

Column Types in GridView

  • GridView supports following types of columns
    • BoundField
    • ButtonField, CheckBoxField
    • CommandField
    • HyperLinkField, ImageField, TemplateField

Templated Fields

  • A TemplateField column gives each row in the grid a personalized UI that is completely defined by the page developer
  • Templates can be defined for various rendering stages, including the default view, in-place editing, header etc
  • Declared as:

    <asp:templateField headertext ="Product" >

    <itemTemplate>

    <b><%# Eval("productname")%></b> <br/>

    available in <%# Eval("quantityperunit")%>

    </itemtemplate>

    </asp:templateField>


 

Sorting Data

  • The GridView doesn't implement a sorting algorithm; instead, it relies on the data source control (or the page, if bound to an enumerable object) to provide sorted data
  • To enable the GridView's sorting capabilities, set AllowSorting property to true

Executing an Operation on a Given Row

  • A RowCommand event handler is required to handle row operations
  • GridView stores the index of the clicked row in the CommandArgument property of the GridViewCommandEventArgs structure

Wednesday, August 29, 2007

Server.Execute and Server.Transfer

Server.Execute Method

  • Execute method allows to consider an external page as a subroutine
  • When the execution flow reaches the Server.Execute call, control is passed to the specified page
  • Execution of the current page is suspended, and the external page is spawned
  • Execute method is a more useful alternative to using server-side includes
  • Execute makes control to return to the calling page once external page has been executed

Server.Transfer Method

  • Calling Transfer method causes termination of current page processing and executes the specified page
  • The control never returns to the page that called the Transfer, which is not the case with Server.Execute, where control returns to the calling page
  • Hence, any code specified after Server.Transfer call, will not be executed
  • It is efficient for two reasons, first no roundtrip to the client is requested, unlike Response.Redirect
  • Secondly, the same HttpApplication that was serving the caller request is reused

Server Object - HttpServerUtility


 

  • The functionality of the ASP intrinsic Server is object in ASP.net is implemented by the HttpServerUtility class
  • An instance of the type is created when ASP.net begins to process the request and is then stored as part of the request context
  • HttpServerUtility class has two properties MachineName and ScriptTimeout
  • ScriptTimeout is to get/set the time in seconds a request is allowed to process
  • Code: this.Server.ScriptTimeout = 30000;

Important methods of Server object

UrlEncode/ UrlDecode

Encodes a string (for HTTP transmission to a client) in a URL

UrlDecode decodes a string encoded for Http transmission

MapPath

Returns the physical path of a file from provided virtual path

UrlPathEncode

Encodes only path portion of the URL string

ClearError

Clears the last exception that was thrown for the request

Transfer / Execute

See below

Global.asax

GLOBAL.ASAX

  • Used by Web Applications to handle some application-level events raised by the ASP.net runtime or by registered http modules
  • Global.asax file is optional and is located in the root directory of the application
  • Only one global.asax file per application is accepted, those in sub-directories are ignored
  • When the application is started, global.asax is parsed into a source class and compiled
  • The resultant assembly is created in the temporary directory just as any other dynamically generated assembly would be
  • The class is named as ASP.global_asax and is derived from System.Web.HttpApplication
  • Any modification made during application execution causes application restart

Contents/Syntax of Global.asax

  • Four elements determine the syntax of the global.asax file
  1. Application Directives
  2. Code declaration blocks
  3. Server side <object> tags
  4. Server side includes

Application Directives

  • The global.asax supports three directives: @Application, @Import and @Assembly
  • @Import directive imports a namespace into an application
  • @Assembly directive links an assembly to the application at compile time
  • @Application supports a few attributes - Description, Language and Inherits

Code Declaration Blocks

  • A global.asax file can contain code wrapped by a <script> tag
  • <script language= "C#" runat="server" src="global.aspx.cs">

Server-Side <object> tags

  • The server-side <object> tag allows to create new objects using a declarative syntax
  • object tag can take three forms, depending on the specified type

    <object id="..." runat="server" scope=Pipeline|Application|Session class="...">

    <object id="..." runat="server" scope=Pipeline|Application|Session progid="...">

    <object id="..." runat="server" scope=Pipeline|Application|Session classid="...">

  • In first case, the object is identified by the name of the class and assembly that contains it
  • In other two cases, the object to create is a COM object identified by the progid or classid

Server-Side Includes

  • An #include directives inserts the contents of the specified file as-is into the ASP.net file that uses it
  • The directive must be enclosed in an HTML comment
  • <!-- #include file="filename"> or <!-- #include virtual="filename">

Static Properties

  • If static proerties are defined in global.asax file, they will be accessible for reading and writing by all pages in the application
  • Sample code as under:

    <script language="C#" runat="server">

    public static int Counter = 0;

    </script>

  • To access this property from a page, code as under

    Response.Write(ASP.global_asax.Counter.ToString());

Application Lifecycle


 

0

APPLICATION_START

 

1

BeginRequest

ASP.NET HTTP pipeline begins to work on the request

2

AuthenticateRequest

All the internal ASP.NET auhentication modules subscribe to this event.

If no authentication module module produced an authenticated user, an internal default authentication module is invoked to produce an identity for the unauthenticated user

3

PostAuthenticateRequest

Post authentication, all the information is stored in the HttpContext User property

4

AuthorizeRequest

Event commonly handled by application code based on business logic or other application requirements

5

PostAuthorizeRequest

The request has been authorized

6

ResolveRequestCache

ASP.net runtime verifies whether returning a previously cached page can resolve the request

If a valid cached representation is found, the request is served from cache, and calls the EndRequest handlers

7

PostResolveRequestCache

If request can not be served from the cache, and the procedure continues

An Http handler corresponding to the requested URL is created at this point. A .aspx page will cause an instance of Page class to be generated

8

PostMapRequestHandler

Event fires once HttpHandler gets created

9

AcquireRequestState

Module associated to this event tries to retrieve state information from the request

10

PostAcquireRequestState

The state information (session/application) has been acquired

11

PreRequestHandlerExecute

Fired immidiately prior to executing the handler for a given request

12

PostRequestHandlerExecute

Event is raised when the handler has generated the response text

13

ReleaseRequestState

Event raised when handler releases the state information and prepares to shut down. Also used by the session state module to update the dirty session state if necessary

14

PostReleaseRequestState

The updated state is persisted

15

UpdateRequestCache

ASP.net runtime determines whether the generated output, now also properly filtered by registered modules, should be cached to be reused with upcoming idnetical requests

16

PostUpdateRequestCache

The page has been saved to the output cache if it was configured to do so

17

EndRequest

Final step in HTTP pipeline. The control passes back to the HttpRuntime object, which is responsible for the actual forwarding of the response to the client

0

APPLICATION_END

 

Debug and Trace

DEBUG CLASS

  • Namespace System.Diagnostics
  • Provides a set of methods and properties that help in debugging the code
  • This class can not be inherited, i.e it is sealed
  • This class provides methods to display an Assert dialog box, and to emit an assertion that will always fail
  • Provides write methods in various flavors like Write, WriteLine, WriteIf, WriteLineIf
  • To enable debugging in C#, add the /d:DEBUG flag to the compiler command line
  • or, add #define DEBUG to the top of the code file
  • Debug is DISABLED in release builds by default, so no executable code is generated for Debug methods

TRACE CLASS

  • Namespace System.Diagnostics
  • Provides a set of methods and properties that help in tracing the execution of the code
  • Methods and properties of Trace class can be used to monitor the health of an application running in real-life settings
  • Tracing helps in isolating problems and fixing them without disturbing a running system
  • To enable Tracing in C#, add the /d:TRACE flag to the compiler command line
  • or, add #define TRACE to the top of the code file
  • In VS2005 trace is ENABLED by default. Therefore, code is generated for all Trace methods in both release and debug builds
  • To set the AutoFlush and IndentSize in Web.Config, specify trace settings as under:

    <configuration>

    <system.diagnostics>

    <trace autoflush="false" indentsize="3">

    </system.diagnostics>

    </configuration>

Sunday, August 26, 2007

DataView Object

DATAVIEW OBJECT

  • The DataView class represents a customized view of DataTable
  • The relationship between DataTable and DataView are governed by the rules of a well-known design pattern; the document/view model
  • The DataTable ojects act as the document, whereas the DataView behaves as the view
  • At any moment there can be multiple views for the same underlying data
  • The view is implemented by maintaining a separate array with the indexes of the original rows that match the criteria set on the view
  • By default, the table view is unfiltered and contains all the records included in the table
  • A DataView does not contain copies of the table's rows. It is limited to storing an array of indexes that is updated whenever any of the filter properties are set


 

IMPORTANT PROPERTIES OF DATAVIEW CLASS

AllowDelete / AllowEdit / AllowNew

Get or set permissions to allow row operations in view

ApplyDefaultSort

Permission to allow default sorting

RowFilter

G/sets the expression used to filter out rows in the view

Sort

G/sets the sorting of the view in terms of columns and order

Table

G/sets the source DataTable for the view

DataViewManager

Gets the DataViewManager object associated with this view


 

IMPORTANT METHODS OF DATAVIEW CLASS

AddNew

Add a new row to the view and the underlying table

BeginInit / EndInit

Begin / End initialization of the view, used for multiple changes

Delete

Delete the row at specified index, deletes row in table too

Find

Finds a row using specified key value

FindRows

Returns an array of row objects that match specified key value

GetEnumerator

Returns an enumerator object for the DataView