Professional ASP.NET 1.1 [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Professional ASP.NET 1.1 [Electronic resources] - نسخه متنی

Alex Homeret

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
توضیحات
افزودن یادداشت جدید


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">








  • ASP.NET

    There are many changes to take into account when looking purely at ASP pages. The most obvious are the server controls and the postback architecture. These have been covered extensively in earlier chapters of the book, so now we'll move on to other features that still exist in ASP.NET, but are different from ASP. We'll also abbreviate explanations of changes that are explained in detail elsewhere in this book, and instead provide a summary and reference to them. Since ASP.NET is fully class-based, we'll also provide references to the underlying classes, so you can easily find full information in the documentation, or look up the classes in tools such as WinCV and ILDasm.


    Preparing the Way


    Before we delve into the changes in detail, here's a quick list of things you can do now, in your current ASP pages, to pave the way for migrating to ASP.NET:



    • Use only a single language within each ASP page



    • Use Option Explicit to enforce declaration of variables



    • Use <script> blocks for function declaration instead of <% %> blocks



    • Avoid render functions



    • Use the Call keyword for calling functions, to force the use of parentheses around arguments



    • Avoid default properties, such as Recordset("column") instead of Recordset.Fields("column").Value



    • Explicitly close open resources (such as the file system or recordsets)





      Note

      These are only relevant to server-side code – client-side code is still browser related.




    Many of these are best practices anyway, but we all tend to take shortcuts. Adhering to this list will ease your migration path. You'll be looking at these in detail as you go through the chapter.


    Intrinsic Objects


    Most ASP intrinsic objects remain available and unchanged, providing excellent support for existing applications. However, there are changes to some properties and methods, as well as the addition of new ones. One significant change is the removal of the ASPError object, as error handling is now managed by exceptions.

    The Application Object


    ASP.NET application state handling is implemented by the HttpApplicationState class in the System.Web namespace. Although ASP.NET supports ASP functionality by way of the Contents and StaticObjects collections, there are some minor differences that may confuse you if you check the documentation. The reason is HttpApplicationState is a first class object that implements a collection (used to hold the items in application state). Therefore methods such as Remove and RemoveAll are members of the HttpApplicationState object itself. However, to preserve compatibility, there is also a Contents property, which simply points back to the parent object. Thus, the following lines of code are equivalent.

    In VB.NET, the code is:


    Application.Remove("Item1")
    Application.Contents.Remove("Item1")

    The code in C# is:


    Application.Remove("Item1");
    Application.Contents.Remove("Item1");

    The first line in these code examples is what you'd see in .NET code samples, whereas the second line is how you'd do it in ASP. However, because compatibility has been preserved, they both work.

    New features of the application object are shown in the following table. Note that although there are explicit Add and Get methods, the existing way of accessing the collection still works fine:































    Property/Method


    Description


    AllKeys


    Returns an array of strings containing the names of stored application state members.


    Count


    Returns a count of items in application state.


    Add


    Adds a new item to the state.


    Clear


    Removes all items from the state. This is equivalent to RemoveAll, and is provided as part of the standard collection handling features.


    Get


    Returns an individual item (either by name or by ordinal).


    GetKey


    Returns the key for the supplied ordinal.


    Set


    Updates the value of a stored item.


    Objects in Application State


    In ASP it was always taboo to store single-threaded objects in application state, which was a real problem for Visual Basic programmers developing components. Given that the .NET languages (including Visual Basic) allow the production of free-threaded components, has this problem now gone away? Well, to a degree yes, as long as you understand the following:



    • You can store free-threaded components as long as they provide thread synchronization.



    • You can store single-threaded components if you use Lock and Unlock to protect against thread blocks.



    • Application state has no guaranteed durability. The application domain can be torn down at any time (synchronized restart for example), so for durability you need an external store.



    By and large, the storage of objects in Application state is discouraged because of the resources used, and the potential for scalability and performance problems. However, the storage of scalar type data (such as string) is a great way to get some performance improvement, as long as it is used carefully. You might think that the classic case of wanting to store Recordsets in application state is now easy, since you can store the XML from a DataSet, but remember that memory (although cheap) is finite. Frequent use of a 10Mb set of data stored in application state may give great benefits, but 100Mb may not. This sort of scenario needs full testing before the implications are really known.

    The Session Object


    Session state is implemented by the HttpSessionState class in the System.Web.SessionState namespace. The Contents and StaticObjects follow the same rules as Application state – the structure of the class is different from ASP, but access works in the same way. Thus, the following examples are equivalent. In VB.NET:


    Session.Remove("Item1")
    Session.Contents.Remove("Item"1)

    In C#:


    Session.Remove("Item1");
    Session.Contents.Remove("Item1");

    The changed and new features of the session object are shown in the following table:




















































    Property/Method


    Description


    Count


    Returns a count of items in session state.


    IsCookieless


    Indicates whether or not session state is being handled in a cookieless manner.


    IsNewSession


    Indicates whether or not the session has been created with the current request.


    IsReadOnly


    Indicates whether or not the session is read -only.


    IsSynchronized


    Indicates whether or not access to the session state values is thread safe.


    Mode


    Indicates how session state is being stored. Will contain one of the SessionStateMode constants:

    InProc, for in process

    Off, for no session state

    StateServer, for the out -of -process state service

    SQLServer, for SQL Server


    SessionID


    In ASP.NET the SessionID property returns a String (as opposed to a Long in ASP)


    SyncRoot


    An object that provides synchronous access to the session contents.


    Add


    Adds a new item to the session state.


    Clear


    Removes all items from the session state. This is equivalent to RemoveAll, and is provided as part of the standard collection handling features.


    CopyTo


    Copies the contents of the session state to an array of strings.


    Equals


    Compares an object in session state with the supplied one to see if they are the same.


    Remove


    In ASP, the Remove method could take either the key name of the item or its index. In ASP.NET, you can only supply the name. To remove by index use the RemoveAt method.


    RemoveAt


    Removes an item at the selected ordinal.


    The Request Object


    The request is implemented by the HttpRequest class in the System.Web namespace. All of the existing properties and methods are supported, although there are some notable exceptions regarding the use of collections (see in the following table) where the appropriate ASP 3.0 ServerVariables equivalent has been mentioned. New and changed properties or methods are detailed in corresponding fonts as follows:






















































































































    Property


    Description


    AcceptTypes


    Returns a string array of the MIME types supported by the client. For ASP this could be extracted from the comma separated ServerVariables HTTP_ACCEPT entry.


    ApplicationPath


    The virtual application path.


    Browser


    Returns an HttpBrowserCapabilities object describing the features of the browser.


    ClientCertificate


    Returns an HttpClientCertificate object (as opposed to an array of values in ASP).


    ContentEncoding


    The character set of the entity body.


    ContentLength


    The length (in bytes) of the request. Equivalent to CONTENT_LENGTH.


    ContentType


    The MIME type of the request. Equivalent to CONTENT_TYPE.


    Cookies


    Returns an HttpCookieCollection object (as opposed to an array of values in ASP).


    FilePath


    The virtual path of the request. Equivalent to SCRIPT_NAME.


    Files


    Returns an HttpFileCollection of uploaded files (for multi - part form posts).


    Filter


    Identifies the stream filter to use for the request. All content will be passed through the filter before being accessible by the page.


    Form


    Returns a collection (NameValueCollection) of Form contents. Accessing this collection is different from accessing the Form collection under ASP (see the Request Collections sections).


    Headers


    A collection (NameValueCollection) of HTTP headers. In ASP these values are space -separated name:value pairs; in .NET they can be accessed via HTTP_name.


    HttpMethod


    The HTTP method used for the request. Equivalent to REQUEST_METHOD.


    InputStream


    A Stream containing the input for the request.


    IsAuthenticated


    Indicates whether or not the user has been authenticated.


    IsSecureConnection


    Indicates whether or not the connection is using HTTPS. Equivalent to HTTPS in ASP.


    Params


    A combined collection of QueryString, Form, ServerVariables, and Cookies.


    Path


    The virtual path of the request. Equivalent to PATH_INFO.


    PathInfo


    Additional path information.


    Physical ApplicationPath


    The physical path of the application root. Equivalent to APPL_PHYSICAL_PATH.


    PhysicalPath


    The physical path of the request. Equivalent to PATH_TRANSLATED.


    QueryString


    Returns a collection (NameValueCollection) of QueryString contents. Accessing this collection is different from accessing the QueryString collection under ASP (see the Request Collections section later in the chapter).


    RawUrl


    The raw URL of the request. Equivalent to RAW_URL.


    RequestType


    The HTTP method used for the request. Equivalent to REQUEST_METHOD.


    TotalBytes


    The number of bytes in the input stream.


    Url


    A Uri object containing details of the request. A Uri object (from the System namespace) encapsulates information about a specific resource, such as port and DNS information.


    UrlReferrer


    A Uri object detailing referrer information.


    UserAgent


    The browser user agent string. Equivalent to HTTP_USER_AGENT.


    UserHostAddress


    The IP address of the user. Equivalent to REMOTE_ADDR.


    UserHostName


    The DNS name of the user. Equivalent to REMOTE_NAME.


    UserLangauges


    An array of langauges preferences. Equivalent to HTTP_ACCEPT_LANGUAGE.


    BinaryRead


    Returns a Byte array containing the binary information sent to the server. In ASP the return type is variant.


    MapImage Coordinates


    Maps the image -field parameter to x and y coordinates.


    MapPath


    Maps the virtual path to a physical path. The method is now overloaded taking two forms. The first is the same as ASP where the parameter is the URL of the virtual path. The second takes three parameters: the virtual path, the virtual base directory for relative resolution, and a Boolean indicating whether or not the virtual path may belong to another application.


    SaveAs


    Saves the HTTP request to disk.


    Some of this information is still available through the ServerVariables collection, but has now been abstracted out into more accessible properties.

    The Request object supports collections for accessing the contents of a form or query string, and there are some major implications where those contents contain elements of the same name. This is typically the case where check boxes, radio buttons, or multi-select list boxes are used. For example, consider the following ASP form:


    <form action="foo.asp" method="post">
    Select your favorite editor:
    <select name="editor" multiple="multiple">
    <option>Notepad
    <option>Textpad
    <option>Visual Studio .NET
    </select>
    <p/>
    <input type="submit" value="Send">
    </form>

    To extract the selected values from the multi-select list you could use:


    For item = 1 To Request.Form("editor").Count
    Response.Write Request.Form("editor")(item) & "<br/>"
    Next

    However, this code will not work in ASP.NET, as a NameValueCollection represents the form contents. There are two points about this:



    • The collection is zero based



    • You have to explicitly get the values



    For example:


    Dim item As Integer
    For item = 0 To Request.Form.GetValues("editor").Length - 1
    Response.Write (Request.Form.GetValues("editor")(item) & "<br/>")
    Next

    Here you have to use the GetValues() method of the collection, and index into that (using a base of 0) to get the required value.

    The Response Object


    The response to a request is implemented by the HttpResponse class. Like the request, all existing functionality is kept, with the following changes or additions:





















































































    Property/Method


    Description


    BufferOutput


    Indicates whether or not to buffer output. This is the same as the Buffer property, and is the preferred method of changing buffering in ASP.NET.


    Cache


    Returns an HttpCachePolicy object, containing details about the caching policy of the current response.


    CacheControl


    Although still supported, this property is deprecated in favor of the HttpCachePolicy methods.


    ContentEncoding


    Identifies the character set of the output. The value can be one of those listed in the Encoding enumeration (ASCIIEncoding, UnicodeEncoding, UTF7Encoding, UTF8Encoding).


    Cookies


    Returns a collection (HttpCookieCollection) of HttpCookie objects (as opposed to an array of attributed values in ASP). The ASP cookie attributes appear as properties of the HttpCookie object.


    Expires


    Although still supported, this property is deprecated in favor of the HttpCachePolicy methods.


    ExpiresAbsolute


    Although still supported, this property is deprecated in favor of the HttpCachePolicy methods.


    Filter


    The Stream object that acts as the output filter. All output will go through this filter before being returned to the client.


    Output


    Returns a TextWriter object through which custom output can be returned to the client.


    OutputStream


    Returns a Stream object representing the raw data of the content body.


    Status


    Sets the HTTP status code to return to the client. This property has been deprecated in favor of the StatusDescription property.


    StatusCode


    The HTTP status code of the response.


    SuppressContent


    Indicates whether or not content is to be returned to the client.


    AddFileDependencies


    Adds a group of file names to the dependency list upon which the response is based. Changes to these files will invalidate the output cache.


    AddFileDependency


    Adds a single file name to the dependency list upon which the response is based. Changes to this file will invalidate the output cache.


    AddHeader


    This method has been deprecated in favor of the AppendHeader method.


    AppendHeader


    Appends an HTTP header to the content stream. This method is preferred over AddHeader.


    ApplyAppPathModifier


    Applies the Cookieless Session ID to a given relative or virtual path. This allows HREFS with fully qualified names to be modified to include the current Session ID.


    BinaryWrite


    Writes binary data (a Byte array) to the output stream. In ASP this is a variant array.


    ClearContent


    Clears the content from the buffer stream.


    ClearHeaders


    Clears the headers from the buffer stream.


    Close


    Closes the socket connection to the client.


    Redirect


    This method is now overloaded. The first form is the same as ASP, taking a URL, and the second form takes a URL and a Boolean indicating whether or not Response.End is called after the redirection.


    Write


    This method is overloaded, and can take one of four sets of parameters:

    A Char

    An Object

    A String

    A Char array, along with the start index and number of characters to write


    WriteFile


    Writes the specified file directly to the output stream.


    The Server Object


    The Server object is implemented by the HttpServerUtility class in the System.Web namespace. The additions and changes are detailed as follows:














































    Property/Method


    Description


    MachineName


    Returns the name of the server.


    ClearError


    Clears the previous exception.


    CreateObject


    This method is now overloaded. The original form taking a string of the ProgID is still allowed, as well as the new form taking a Type object.


    CreateObjectFromClsid


    Creates an instance of a COM object from the Class identifier (CLSID).


    Execute


    This method is now overloaded. The original form taking a string of the path of the new request is still allowed, as well as the new form taking the path and a TextWriter used to capture the output. This allows requests to be executed and then manipulated.


    GetLastError


    This now returns an Exception object (as opposed to an ASPError object in ASP).


    HtmlDecode


    Decodes an HTML encoded string.


    HtmlEncode


    This method is now overloaded, with an additional form taking a string to encode and a TextWriter into which the encoded text should be placed.


    Transfer


    This method is now overloaded, with an additional form taking a string for the path, and a Boolean to indicate whether or not the Form and QueryString collections should be preserved across the transfer.


    UrlDecode


    Decodes an HTML encoded URL.


    UrlPathEncode


    Encodes only the URL portion of a string (as opposed to UrlEncode which encode the URL and any QueryString).


    UrlEncode


    This method is now overloaded, with an additional form taking a string of the URL to encode, and a TextWriter into which the encoded URL is placed.


    The ASPError Object


    The ASPError object has been removed, as errors are now represented by exceptions. For example, the following code extracts the last error:


    Dim lastError As Exception
    lastError = Server.GetLastError()
    Response.Write("Error was: " & lastError.Message)

    The ObjectContext Object


    The ObjectContext object in ASP is designed for the integration of ASP pages with external transacted components, such as those in Microsoft Transaction Server (MTS) or COM+ Services. Within ASP.NET you have the ability to run pages with ASP Page Compatibility, by setting a page directive:


    <%@ Page AspCompat="true" %>

    This allows the page to be run on a single threaded apartment (STA) thread, allowing it to call STA components, such as those written in VB6. This is particularly useful for those components that reference the ASP intrinsic objects and generate HTML.

    The Page Object


    The Page object (in the System.Web.UI namespace) was not a part of ASP, but plays an important role in ASP.NET. The Page is the parent object for the objects mentioned above, apart from the ObjectContext. Many of the features of the page you'll already have seen (such as the IsPostBack and IsValid properties), and the rest are extensively documented in the help files. We mention this object here in case you see code such as Page.Session, Page.Response, or Page.Request, and wonder how the objects relate.


    Page Changes


    Along with changes to the common objects, the structure and usage of ASP pages have changed. You've already seen how the event model and postback architecture changes the layout of pages, so what you'll concentrate on here are the things that need changing from existing ASP pages.

    Single Language Per Page


    I've never actually seen any code that used more than one server-side language, but with ASP.NET you must use a single language per page. If you need to use multiple languages you'll have to use User Controls or custom controls, which can be in any language.





    Note

    The single language per page rule only affects individual pages – multiple pages in an application can be in different languages.


    Script Blocks


    Procedures in ASP.NET pages have to reside within proper script tags. So, the following is no longer allowed:


    <%
    Sub Foo()
    ...
    End Sub
    %>

    Instead you must use:


    <script language="VB" runat="server">
    Sub Foo()
    ...
    End Sub
    </script>

    You can still use the <% %> tags for inline placement of variables or function results.

    Code Render Functions


    The changes to script block usage mean that render functions are no longer allowed. Render functions are where the body of a function actually contains HTML. For example:


    <% Sub ShowSeparator() %>
    <img src="sep.gif" width="100%"></img>
    <% End Sub %>

    This now has to be:


    <script language="VB" runat="server">
    Sub ShowSeparator()
    Response.Write("<img src='sep.gif' width='100%'></img>")
    End Sub
    </script>

  • / 243