1 / 62

ASP.NET 2.0

ASP.NET 2.0. Chapter 2 Introduction to Programming. Objectives. Integrate Programming and Web Forms. The Web Form is a web page that can contain: HTML controls (<p>) Client-side scripts including JavaScript

ulema
Télécharger la présentation

ASP.NET 2.0

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ASP.NET 2.0 Chapter 2 Introduction to Programming

  2. Objectives ASP.NET 2.0, Third Edition

  3. Integrate Programming and Web Forms • The Web Form is a web page that can contain: • HTML controls (<p>) • Client-side scripts including JavaScript • ASP.NET controls – these run on the web server and are rendered as HTML and JavaScript on the client • HTML server (<p runat=“server” id=“P1”></p> • Web server controls (<asp:calendar runat=“server” id=“Calendar1” /> • Controls can be written manually or user can use the visual tools to add them to the Web Form ASP.NET 2.0, Third Edition

  4. Integrate Programming and Web Forms (continued) • Compiled server programs • Inline in the page using <% %> delimiters • Embedded • Usually at the top of the page with <script> tags • Set the runat=“server” property • Change the language to VB • Code behind the page • Filename has the extension .aspx.vb • Separating server programming and Web Forms allows you to alter your presentation tier without interfering with how the page is processed by the business programming code ASP.NET 2.0, Third Edition

  5. Configure the Page Directive • Set the default page-level properties • Default Language property set to VB indicates the code behind the page is written in Visual Basic .NET <%@ Page Language="VB" %> • File location is identified by the CodeFile property • Inherits property indicates that the code behind the page inherits the partial class <%@ Page Language="VB" CodeFile="Login.aspx.vb" Inherits="Login" title=" Login Page" AutoEventWireup="false" %> ASP.NET 2.0, Third Edition

  6. Where to Place Your Programming Statements • Only server controls interact with the code behind the page (web server and HTML server controls) • Must set the ID property • Must set the runat=“server” property • Line continuation character is the underscore • Do not break strings across lines • Concatenate strings with & or + ASP.NET 2.0, Third Edition

  7. Using Variables and Constants in a Web Form • Variable declaration • Declaration keywords define what parts of the web application will have access to the variable • Variable name refers to the name of the variable as well as a section of memory in the computer • Data type identifies what kind of data the variable can store such as integer or string of characters • Multiple variables declare on a separate line, or use a single line • Declare variables before used • Explicit property of the Page directive configures the page to require you to declare all variables before use ASP.NET 2.0, Third Edition

  8. Declaring a Variable • Declaring a variable is the process of reserving the memory space for the variable before it is used in the program • Scope identifies what context the application can access the variable • Where your web application defines the variable determines where the variable can be used within the application • Local variables • Defined within a procedure • Used only where they were declared • Persist in memory while the procedure is being executed • More readable, easier to maintain, require less memory • Choose local variables unless multiple procedures require them ASP.NET 2.0, Third Edition

  9. Declaring a Variable (continued) • Module-level variables • Defined in the class but outside the procedures • Used by any procedures in the page • Not available to other Web Forms • Any procedure within the page can set or use value • Reserve memory space before it is used • When page loads, memory allocated and a value assigned • After page unloads, memory can be reallocated ASP.NET 2.0, Third Edition

  10. Declaring a Variable (continued) • Keywords specify the scope of the variable • Dim: With no other keyword, its use will mean the variable is public • Public: Defines variable global or public, available outside the Web Form • Friend: Defines variables used only within the current web application or project • Protected: Defines variables used only by the procedure where declared ASP.NET 2.0, Third Edition

  11. Declaring a Variable (continued) • Variable Names • Cannot use any of the Visual Basic .NET commands or keywords as your variable name • Must begin with a letter • Cannot use a period or space within a variable name • Avoid any special characters in a variable name except for the underscore • Store values in variables using the assignment operator, which is the equal sign (=) Dim CompanyName As String = "Barkley Builders" ASP.NET 2.0, Third Edition

  12. Declaring Constants • Assign a value that does not change • Tax rates • Shipping fees • Mathematical equations • Const keyword is used to declare a constant • Naming rules for variables also apply • Usually all uppercase • Must assign the value when you declare the constant Const TAXRATE As Integer = 8 ASP.NET 2.0, Third Edition

  13. Working with Different Data Types • Text and Strings • Numeric • Date • Boolean • True -1 • False 0 ASP.NET 2.0, Third Edition

  14. Working with Text Data • Character text stored in strings and chars • Char data type stores a single text value as a number between 0 and 65,535 • String data type stores one or more text characters • Social Security numbers, zip codes, and phone numbers • Numbers stored as text strings are explicitly converted to numerical data before using in an arithmetic expression • Assign a string a value; the value must be within quotation marks • Stored as Unicode and variable in length ASP.NET 2.0, Third Edition

  15. Strings • Modify string using methods of the String object • Replace – replaces one string with another • Concatenation joins one or more strings Dim ContactEmail As String = CompanyEmail.ToString() & "<br />" • Plus sign (+) represents the addition operator for mathematical equations and is used with non-strings; technically can be used instead of &, but it is not recommended ASP.NET 2.0, Third Edition

  16. Working with Numeric Data • Data Types • Byte – integer between 0 and 255 stored in a single byte • Short – 16-bit number from –32,768 to 32,767; uses two bytes • Integer – 32-bit whole number; uses four bytes • Long – 64-bit number; uses eight bytes • Single – single-precision floating point (decimal); uses four bytes • Double – larger decimal numbers; requires eight bytes • Decimal – up to 28 decimal places; used to store currency • Mathematical methods • Such as Floor, Ceiling, Min, and Max, Sqrt, Round, Truncate • Add, Equals, Divide, Multiply, and Subtract • Can use arithmetic operators (such as + = / * - ) ASP.NET 2.0, Third Edition

  17. Working with Numeric Data (continued) • System.String.Format method • Predefined Formats • Number (N) is used to format the number using commas • Currency (C or c) will insert the dollar symbol and two decimals • Percent (P) will format the number as a percent • Fixed number (F or f) represents a fixed number with two decimals System.String.Format("{0:C}", 1234.45) String.Format("{0:P}", 1234.45) Format("Percent", 1234.45) • User-defined format style with a mask • 0 to represent a digit, pound (#) to represent a digit or space • 1,231 and $24.99 and 5.54% Format(1231.08, "#,###") Format(24.99, "$#,###.##") Format(0.0554, "0.00%") ASP.NET 2.0, Third Edition

  18. Working with Date and Time • System.DateTime enclosed within a pair of pound signs Dim MyBirthday As DateTime MyBirthday = #3/22/2008# • Local time • MyBirthday.UtcNow • UCT is Coordinated Universal Time (Greenwich Mean Time-GMT) • String.Format • d and D masks short and long date formats • t or T masks short and long time formats Dim ShippingDate As DateTime = #3/12/2008# Format(ShippingDate, "d") • User-defined format style with a mask Format(MyDT, "m/d/yyyy H:mm") 9/9/2007 17:34 ASP.NET 2.0, Third Edition

  19. Converting Data Types • System.Convert class • CInt function to convert string –CInt(strVariable) • Narrowing conversions • Convert a decimal to an integer; you may lose some data • Convert 23.50 to 23; you lose the .50 • Overflow exception is thrown • Not allowed by default because data could be lost • Convert 23.00 to 23; no data is lost, the .00 digits are not significant and no exception is thrown • Widening conversion • Convert 25 to 25.00; no data is lost • Allowed because no data loss occurs • Set the Strict property of the Page directive to True to stop narrowing conversion that would result in data loss • Convert data types explicitly when narrowing conversions occur ASP.NET 2.0, Third Edition

  20. Working with Web Collections • Each item in the collection is also referred to as an element • A collection is like a movie theatre – both containers • Refer to the movie theatre as a whole or to an individual seat • Each seat has its own number to locate the seat • Items in the collection can be any valid data type such as a string or an integer, an object, or even another collection • Used to decrease processing every time the web application had to retrieve the list • The Systems.Collections namespace defines collections including the ArrayList, HashTable, SortedList, Queue, and Stack ASP.NET 2.0, Third Edition

  21. The ArrayList • Create an ArrayList Dim StateAbbrev As New ArrayList StateAbbrev.Add("IL") StateAbbrev.Add("MI") StateAbbrev.Add("IN") • Modify ArrayList items StateAbbrev.Insert(0, "OK") StateAbbrev.Remove("OK") • Iterate through the list Dim iPos as Integer iPos = StateAbbrev.IndexOf("OK") Dim MyCount As Integer MyCount = StateAbbrev.Count For I = 0 to MyCount -1 MyStates.Text = StateAbbrev(I) & "<br />" Next ASP.NET 2.0, Third Edition

  22. The HashTable • HashTable creates index of items using an alphanumeric key like an encyclopedia • Modify ArrayList items Dim HT1 As New HashTable() HT1.Add("1", "Mrs. Marijean Richards") HT1.Add("2", "1160 Romona Rd") HT1.Add("3", "Wilmette") HT1.Add("4", "Illinois") HT1.Add("5", "60093") • Iterate through the list Dim CustomerLabel as String For each Customer in HT1 CustomerLabel &= Customer.Value & "<br />" Next Customer ASP.NET 2.0, Third Edition

  23. Working with Web Objects to Store Data • HTTP protocols – send and receive data • Data is transmitted in the header in the data packet • Date and time • Type of request (Get or Post) • Page requested (URL) • HTTP version • Default language • Referring page • IP address of the client • Cookies associated with that domain • User agent – used to identify the client software • Can add custom data fields • Programmatically access the information that is transferred with the request and response using various programming objects ASP.NET 2.0, Third Edition

  24. Using the Request Object to Retrieve Data from the Header • HTTP collects and stores the values as a collection of server variables • Request object of the Page class retrieves data sent by the browser • Server variables can be retrieved by using an HTTPRequest object with Request.ServerVariables("VARIABLE_NAME") • Always in uppercase • System.Web.HttpRequest class mapped to Request property of Page object • Use Page.Request.PropertyName or Request.PropertyName Request.Url, Request.UserHostAddress, Request.PhysicalPath, Request.UrlReferrer.Host • User agent provides a string to detect the browser version • JavaScript – string parsed to locate browser application name and version • System.Web.HttpBrowserCapabilities class detects specific features directly Dim MyBrowser as String = Request.Browser.Browser & "<br />" & _ Request.Browser.Type & "<br />" & Request.Browser.Version & "<br />" & _ Request.Browser.Platform ASP.NET 2.0, Third Edition

  25. Using the Request Object to Retrieve Data from the Header (continued) • Request object to retrieve form data from the header • Form collection • QueryString collection • If Form method is Get, results are HTML encoded and appended with a question mark to the URL requested as a single string called the QueryString www.course.com/index.aspx?CompanyName=Green%20River&Industry=Electronics • Value is retrieved and assigned to a Label control Label1.Text = Request.QueryString("CompanyName") ASP.NET 2.0, Third Edition

  26. Using the Request Object to Retrieve Data from the Header (continued) • QueryString • Only valid URL characters, has a fixed limit length, and not appropriate to send sensitive or personal information • URL will not support spaces and special characters • Manually encode and decode a string using:[R2 Server.UrlEncode(“The String”)[ Server.UrlDecode(“The%20String”) • List of System.Web.HttpRequest variables and properties view Quickstart Class Browser at www.asp.net/QuickStart/util/classbrowser.aspx ASP.NET 2.0, Third Edition

  27. Accessing From Field Data • Access the value properties of the form field directly for Server controls • Property name varies • CompanyName.Value • Cross-page posting sends data from one form to another by setting the PostBackUrl property of an ImageButton, LinkButton, or Button control to the new page • Detect if the user came from another page by determining if the Page.Previous property is null ASP.NET 2.0, Third Edition

  28. Working with the Response Object • Response object is mapped to System.Web.HttpResponse class • All data sent is sent via the HttpResponse class or via the Response object • IP address of the server and the name and version number of the web server software • Cookies collection sends cookies that are written by the browser in a cookie file • Status code indicates the browser request was successful or any error • Access status codes with a custom error message page • Methods • WriteFile method sends entire contents of a text file to the web page • Write method sends a string to the browser including text, HTML tags, and client script Dim strMessage as String = "Green River Electronics<br/>" Response.Write(strMessage) ASP.NET 2.0, Third Edition

  29. Working with the Response Object (continued) • Response object redirects the browser to another page with server-side redirection • Visitor never knows that he or she has been redirected to a new page • Browser is redirected using the HTTP headers Response.Redirect("http://www.course.com/") • Keep the ViewState information, and insert true as the second parameter Server.Transfer("Page2.aspx", true) ASP.NET 2.0, Third Edition

  30. Session Objects • Session object maintains session state across a single user’s session • Session variables stored in the server’s memory accessed only within the session • Cannot change the value and stored in a special session cookie • Cannot track across multiple sessions • SessionID is a unique identifier determined by several factors, including the current date and IP addresses of the client and server Session("Session ID") = Session.SessionID Session("Number") = Session.Count.ToString Session.Timeout = "30" ASP.NET 2.0, Third Edition

  31. Session Objects (continued) • Application variables are released from memory when web application is stopped, web server is stopped, or when the server is stopped Session("Member ID") = TextBox1.Text Session("Date of visit") = DateTime.Now.ToShortDateString Session("URL requested") = Request.Url.ToString Session("Server") = _ Request.ServerVariables("SERVER_NAME").ToString • Save state information in session variables or in __VIEWSTATE • ViewState – persisted across browser requests stored with HTML code only about the server controls • Serialized into a base64-encoded data string and not encrypted and can be viewed ViewState("Publisher") = "Course Technology" • Retrieve the value Dim MyPublisher As String = CStr(ViewState("Publisher")) ASP.NET 2.0, Third Edition

  32. Design .NET Web Applications • Windows and Web Applications are different • Web application used in a browser or an Internet-enabled device • Visual Basic .NET is a programming language • ASP.NET is technology used to develop dynamic web applications within the .NET Framework • .NET Framework consists of a common language runtime (CLR) and a hierarchical set of base class libraries • A class is a named logical grouping of code • Class definition contains the functions, methods, and properties that belong to that class ASP.NET 2.0, Third Edition

  33. Web Applications Architecture ASP.NET 2.0, Third Edition

  34. Organization of Classes in the .NET Framework • Base class libraries are groups of commonly used built-in classes stored in executable files • Accessed from any .NET application • Contain fundamental code structures and methods to communicate with system and applications • Organized in hierarchical logical groups called namespaces • System namespace is at the top of the namespace hierarchy, and all built-in classes inherit from it • Web controls located within the System.Web.UI.Control.WebControl namespace ASP.NET 2.0, Third Edition

  35. Programming with Visual Basic .NET • Linear programming – executed sequentially in a single file • Procedural programming – used decision control structures, functions, and procedures to control the execution order • Decision control structures used conditional expressions to determine which block of code to execute • Object-oriented programming (OOP) – methods stored in classes can be reused throughout your web application ASP.NET 2.0, Third Edition

  36. Event Driven Programming • This is an extension of OOP • The ‘main’ program sets up a collection of ‘listeners’ • When something happens in the environment, an appropriate listener is informed • This usually means that a particular procedure or function is called CBS 5/12/08

  37. Model-View-Controller • Architecture of an interactive system • MVC • Model is the collection of objects representing the data and the processing logic for that data • View is the collection of objects that make the visible interface • Controller is the collection of objects that responds to user interaction • When we create classes it will almost always be in the Model • Exception: frame classes are implicitly created for us CBS 5/12/08

  38. Creating a Class • The source file for the class ends in .vb, placed in a directory named App_Code Public Class MyClass Private CompanyName As String = "Green River Electronics“ ASP.NET 2.0, Third Edition

  39. Using a Class in ASP.NET • Create an instance of the class • Instantiation is the process of declaring and initializing an object from a class • Use the class – need to import on the first line in the code behind the page Imports MyClass() ASP.NET 2.0, Third Edition

  40. Using a Class • Declare a variable to store the object, and New to identify that this is an object based on a class definition • In the class in the sample code below, the MyNewClass object is based on the MyClass class Dim MyNewClass As New GreenRiverWeb.MyClass() • New object can access all of the variables, properties, functions, and procedures defined within MyClass Label1.Text = MyNewClass.CompanyName ASP.NET 2.0, Third Edition

  41. Using a Procedure • Procedures contain one or more programming statements and are executed when called by another procedure or when an event occurs (event procedure) • Pass zero or more arguments, called parameters, in a comma delimited list and data type • Subprocedure can be called from other locations and reused • Subprocedures do not return values • Cannot be used in an expression value • Declared using the keyword Sub • Exit Sub statement to stop the subprocedure ASP.NET 2.0, Third Edition

  42. Creating Subprocedures • Example Note use _ to split lines) Sub SubprocedureName(CompanyName As String, _ TotalEmployees As Integer) Programming statements go here End Sub • Call the subprocedure [Call] SubprocedureName("Green River Electronics", 3400) ASP.NET 2.0, Third Edition

  43. Creating Event Procedures • Event procedure is attached to an object with events • Not executed until triggered by an event • Event handler intercepts an event • An underscore (_) is used to separate the object name and the event name Sub objectName_event(Sender As Object, _ e As EventArgs) Programming statements go here End Sub ASP.NET 2.0, Third Edition

  44. Page Events • Page lifecycle and events occur in order • Can intercept event handlers within event procedure • Page_Init – initializes the page framework hierarchy, creates controls, deserializes the ViewState, and applies the previous settings to the controls • Page_Load – loads Server controls into memory • Determine if the page has previously been loaded • Page.IsPostback property • Page_PreRender – immediately before control hierarchy is rendered • Page_Unload – page is removed from the memory ASP.NET 2.0, Third Edition

  45. Creating Functions • Function is a block of code that is grouped into a named unit • Built-in functions .NET Framework – mathematical, date and time, string, and formatting functions or create your own function with a unique name • End Function statement identifies the end of the function • Leave the function with Exit Function statement • Returns one value using the Return statement (same data type) Public Function GetDiscount(CustomerState As String) As Integer Dim MyDiscount as Integer If CustomerState = "MI" then MyDiscount = 10 Else MyDiscount = 5 End If Return MyDiscount End Function • Parameter and data type passed when you call the function Dim MembershipFee As Integer MembershipFee = 100 - GetDiscount("MI") ASP.NET 2.0, Third Edition

  46. Creating a Property Method • Property method sets value of a variable defined in an object • Used to expose private variables defined within the class • All new objects inherit same properties as the original Public ReadOnly Property StoreName() As String Get Return StoreName End Get End Property • Retrieve property lblContact.Text = ch2_classname.StoreName.ToString() ASP.NET 2.0, Third Edition

  47. Programming Control Structure • Control statements determine both whether and how an action statement is executed, and the order • Decision control structures alter the execution order of action statements on the basis of conditional expressions • Conditional expression is evaluated by the program as true or false • If Then and Select Case statements • Loop structures repeat action statements on the basis of conditional expressions • While, Do While, For Next, and For Each • Can nest any of programming control structures ASP.NET 2.0, Third Edition

  48. If Then Statement • Two options for altering the order If (MyBrowser.ToString = "IE") Then Response.Write("You are running Internet Explorer.") Else Response.Write("You are running a different browser.") End If • Boolean expression uses comparison operators (“true” or “false”) If (MemberDuesPaid.Checked = True) Then If (Page.IsPostback = True) Then If (DuesPaid.Value < DuesOwed.Value) Then If (RadioButtonList1.SelectedIndex > -1) Then • Can include logical operators in the conditional expressions If ((a = 1) And (b = 2)) Then If ((a = 1) Or (b = 2)) Then If Not Page.IsPostBack Then ASP.NET 2.0, Third Edition

  49. Select Case Statement • Select Case used to include multiple conditions Select Case TxtRole.Value Case "Manager" Response.Redirect("Manager.aspx") Case "Admin" Response.Redirect("Admin.aspx") Case Else Response.Redirect("Member.aspx") End Select ASP.NET 2.0, Third Edition

  50. While Loop • While loop repeats a block of code while conditional expression is true or Nothing • Exit While – escape the loop to stop an infinite loop Dim I As Integer = 0 While i < 10 i += 1 Response.Write(i) End While ASP.NET 2.0, Third Edition

More Related