ASP.NET 4.0 Julie Iskander MSC. Communication and Electronics
Course Outlines  User Controls  Validation Controls  State Management
User Controls “Always DRY”
User Controls (.ascx)  A small section of page that can include static HTML code, web server controls.  No <html>,<head>,<body>,<form> tag  Can be reused in multiple pages  Can have properties and events  Have same Page events, and same Page properties Session, Application,……,etc
User Control  Step: 1. Create a .acsx file, add your controls 2. Write your code-behind logic 3. On your .aspx a. Register the user control b. Add it to the design
Step 1
Step 2
Step 3
Convert from an HTML to an aspx page
Validation Controls
Validation Controls  Validates using client-side JavaScript first, if valid posts back and validates using server-side code.  Must be bound to an input control  CauseValidation property of controls  Inherits from BaseValidator Class (System.Web.UI.WebControls)
Validation Controls
Convert from an HTML to an aspx page
Regular Expression
Custom Validator
Custom Validator
Validation Groups
Validation Groups
Validation Group (BONUS Question)  What if I added a new button with no validation group?  How to make sure a control is always validated, regardless of the validation group of the clicked button? 1- The button will validate controls with no validation group only, if none is found the page is postback as valid 2- Create multiple validators for the control, one for each validation group and one with no validation group
State Management “The art of retaining information between requests”
To Windows Form developers, ASP. NET seems like continuous running applications!!! A Clever ILLUSION
State Management  Solution to stateless nature of HTTP  To persist information between requests.  Store information over the lifetime of the application  Methods used ◦ Cross-Page Posting ◦ View state ◦ Query String ◦ Cookies ◦ Session State
ViewState  Uses a hidden field  Property of Page object, a dictionary collection of name/value pairs  Store information for multiple postback within same page.  Stores serializable objects only
ViewState Collection  To save value ◦ this.ViewState[“ButtonClicked”]=1;  To retrieve value ◦ int count = (int)this.ViewState[“ButtonClicked”];
Convert from an HTML to an aspx page
ViewState  To use ViewState to retain member variables. It is recommended to ◦ Save values in Page.PreRender ◦ Retrieve values in Page.Load  Preserves the illusions of continous application  cost??  Another limitation  bound to one specific page
Cross-Page Posting  To transfer information from one page to another using postback mechanism  Can lead you to create pages that are tightly coupled to one another and difficult to enhance and debug.  The page will be posted with all control values, even the hidden viewstate values.
Page1 Page2  In an IButtonControl  Access Page1 through ◦ PostBackUrl Property = “url PreviousPage Property of page2” Cross-Page Posting
Convert from an HTML to an aspx page
Query String  Is the portion of the URL after the question mark.  Limitations: ◦ Strings, which must contain URL-legal characters ONLY. ◦ Information is clearly visible . ◦ Can be modified by the user. ◦ Many browsers impose a limit on the length of a URL (usually from 1 to 2 KB).  Must be placed in the URL by you, using a special HyperLink control, or you can use a Response.Redirect() ◦ “MyPage.aspx?ID=3”  To retrieve the values sent use QueryString dictionary collection in the Request object, ◦ string ID = Request.QueryString["ID"];
Cookies  Small files that are created in the web browser’s memory or the clients hard drive.  Stores only strings.  Accessible and readable  Can be disabled in the browser.  System.Net  If no expiry date, the cookie is not permenant.
Cookies  Creating cookies and storing information
Cookies  Retrieving information from cookies
Convert from an HTML to an aspx page
Session State  User-specific  Heavyweight state management method  Support any type of objects  Stored in the server memory in a dictionary collection of name/value pair  Instance of System.Web.SessionState.HttpSessionState class  Adv.  never stored on client (Secure) global over the entire application  Unique SessionID for each user stored ◦ Using Cookies ◦ Using modified URLs ◦ Only part of the session sent to the client
Session State  Session is lost when: 1. Close or restart browser 2. Use a different browser 3. Timeout due to inactivity 4. Call Session.Abandon();  Session.Timeout  default 20 minutes  Disadvantages  Information is stored in the server memory  Affect performance with increased usage
Convert from an HTML to an aspx page
Session State
Convert from an HTML to an aspx page
SQL Server Data Store for SessionState  Slowest SessionState storage  Command to create Database Store  Configure the web.config to use it
Application State  Application object   Instance of System.Web.HttpApplicationState class  Store global objects that any client can access, Stored in a dictionary of name/value pairs  Never timeout, unless the application restarts  Support any type of objects  Retains information on the server.
Convert from an HTML to an aspx page
ASP.NET Application and Global Events
Application Events  Global.asax ◦ event handling global events events of Application class. ◦ Can access all properties and methods of Application object ◦ No HTML or ASP.NET tags. ◦ ONE AND ONLY ONE for each application
Application Events  PerRequest Events ◦ Application_BeginRequest() ◦ Application_EndRequest()  PerSession Events ◦ Session_Start() ◦ Session_End()  Special Events ◦ Application_Start() ◦ Application_End() ◦ Application_Error()
Convert from an HTML to an aspx page
ASP.NET Configuration
ASP.NET Configuration  XML-based files  Machine level ◦ machine.config  [windows]Microsoft.NetFramework[Version]C onfig ◦ Root web.config  All applications inherit these configurations
ASP.NET Configuration  Per Application ◦ web.config  In root application directory ◦ web.config in subdirectories
ASP.NET Configuration
Reading Assignment #2  Read ASP.NET Application Life Cycle Overview for IIS 7.0 http://msdn.microsoft.com/en- us/library/bb470252.aspx#GlobalAsax  Custom Validators  Rich Controls ◦ Calendars ◦ Sitemaps ◦ menus
Report #2  Show a simple example of creating and retrieving cookies in javascript.  How can you load a User Control in code?
Lab #2  Add validations to the registration form, Name(Required) and Age(between 18 and 120) at least.  Add site map to the site (Self Study)  In book.aspx, ◦ Create a UserControl (DateTimeControl.aspx) to display the current date and time on the top-right of the page. It must be refreshed every second without postback. ◦ The checked books are added to the Shopping Cart when checkout is pressed the chosen books are displayed in a new checkout.aspx page . ◦ Create a user control to count number of visitors and add it to the footer of all pages
Lab Hints  Add events to dynamic controls  Cast the object sender of the event to the wanted control  Use Javascript and/or jQuery for the user control  Try Trace=true in Page directive, to help in debugging
Bonus  In book.aspx ◦ When next and back is clicked the previously checked books must stay checked so as the user can know what he already chose.
REFERENCES  [1] Beginning ASP.NET 4 In C# 2010, Matthew Macdonald, Apress  [2] Web Application Architecture Principles, Protocols And Practices, Leon Shklar And Richard Rosen, Wiley  [3] Professional AS P.NE T 4 In C# And VB, Bill Evjen, Scott Hanselman And Devin Rader, Wiley  [4] Pro ASP.NET In C# 2010, Fourth Edition,matthew Macdonald, Adam Freeman, And Mario Szpuszta, Apress

ASP.NET Lecture 2

  • 1.
    ASP.NET 4.0 Julie Iskander MSC.Communication and Electronics
  • 2.
    Course Outlines  UserControls  Validation Controls  State Management
  • 3.
  • 4.
    User Controls (.ascx) A small section of page that can include static HTML code, web server controls.  No <html>,<head>,<body>,<form> tag  Can be reused in multiple pages  Can have properties and events  Have same Page events, and same Page properties Session, Application,……,etc
  • 5.
    User Control  Step: 1. Create a .acsx file, add your controls 2. Write your code-behind logic 3. On your .aspx a. Register the user control b. Add it to the design
  • 6.
  • 7.
  • 8.
  • 9.
    Convert from anHTML to an aspx page
  • 10.
  • 11.
    Validation Controls  Validatesusing client-side JavaScript first, if valid posts back and validates using server-side code.  Must be bound to an input control  CauseValidation property of controls  Inherits from BaseValidator Class (System.Web.UI.WebControls)
  • 12.
  • 14.
    Convert from anHTML to an aspx page
  • 15.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
    Validation Group (BONUS Question) What if I added a new button with no validation group?  How to make sure a control is always validated, regardless of the validation group of the clicked button? 1- The button will validate controls with no validation group only, if none is found the page is postback as valid 2- Create multiple validators for the control, one for each validation group and one with no validation group
  • 22.
    State Management “The artof retaining information between requests”
  • 23.
    To Windows Form developers, ASP. NET seems like continuous running applications!!! A Clever ILLUSION
  • 24.
    State Management  Solutionto stateless nature of HTTP  To persist information between requests.  Store information over the lifetime of the application  Methods used ◦ Cross-Page Posting ◦ View state ◦ Query String ◦ Cookies ◦ Session State
  • 25.
    ViewState  Uses ahidden field  Property of Page object, a dictionary collection of name/value pairs  Store information for multiple postback within same page.  Stores serializable objects only
  • 26.
    ViewState Collection  To save value ◦ this.ViewState[“ButtonClicked”]=1;  To retrieve value ◦ int count = (int)this.ViewState[“ButtonClicked”];
  • 27.
    Convert from anHTML to an aspx page
  • 28.
    ViewState  To use ViewState to retain member variables. It is recommended to ◦ Save values in Page.PreRender ◦ Retrieve values in Page.Load  Preserves the illusions of continous application  cost??  Another limitation  bound to one specific page
  • 29.
    Cross-Page Posting  Totransfer information from one page to another using postback mechanism  Can lead you to create pages that are tightly coupled to one another and difficult to enhance and debug.  The page will be posted with all control values, even the hidden viewstate values.
  • 30.
    Page1 Page2  In an IButtonControl  Access Page1 through ◦ PostBackUrl Property = “url PreviousPage Property of page2” Cross-Page Posting
  • 31.
    Convert from anHTML to an aspx page
  • 32.
    Query String  Is the portion of the URL after the question mark.  Limitations: ◦ Strings, which must contain URL-legal characters ONLY. ◦ Information is clearly visible . ◦ Can be modified by the user. ◦ Many browsers impose a limit on the length of a URL (usually from 1 to 2 KB).  Must be placed in the URL by you, using a special HyperLink control, or you can use a Response.Redirect() ◦ “MyPage.aspx?ID=3”  To retrieve the values sent use QueryString dictionary collection in the Request object, ◦ string ID = Request.QueryString["ID"];
  • 33.
    Cookies  Small filesthat are created in the web browser’s memory or the clients hard drive.  Stores only strings.  Accessible and readable  Can be disabled in the browser.  System.Net  If no expiry date, the cookie is not permenant.
  • 34.
    Cookies  Creating cookies and storing information
  • 35.
    Cookies  Retrieving information from cookies
  • 36.
    Convert from anHTML to an aspx page
  • 37.
    Session State  User-specific Heavyweight state management method  Support any type of objects  Stored in the server memory in a dictionary collection of name/value pair  Instance of System.Web.SessionState.HttpSessionState class  Adv.  never stored on client (Secure) global over the entire application  Unique SessionID for each user stored ◦ Using Cookies ◦ Using modified URLs ◦ Only part of the session sent to the client
  • 38.
    Session State  Session is lost when: 1. Close or restart browser 2. Use a different browser 3. Timeout due to inactivity 4. Call Session.Abandon();  Session.Timeout  default 20 minutes  Disadvantages  Information is stored in the server memory  Affect performance with increased usage
  • 39.
    Convert from anHTML to an aspx page
  • 40.
  • 41.
    Convert from anHTML to an aspx page
  • 42.
    SQL Server DataStore for SessionState  Slowest SessionState storage  Command to create Database Store  Configure the web.config to use it
  • 43.
    Application State  Application object   Instance of System.Web.HttpApplicationState class  Store global objects that any client can access, Stored in a dictionary of name/value pairs  Never timeout, unless the application restarts  Support any type of objects  Retains information on the server.
  • 44.
    Convert from anHTML to an aspx page
  • 47.
  • 48.
    Application Events  Global.asax ◦ event handling global events events of Application class. ◦ Can access all properties and methods of Application object ◦ No HTML or ASP.NET tags. ◦ ONE AND ONLY ONE for each application
  • 51.
    Application Events  PerRequest Events ◦ Application_BeginRequest() ◦ Application_EndRequest()  PerSession Events ◦ Session_Start() ◦ Session_End()  Special Events ◦ Application_Start() ◦ Application_End() ◦ Application_Error()
  • 52.
    Convert from anHTML to an aspx page
  • 53.
  • 54.
    ASP.NET Configuration  XML-basedfiles  Machine level ◦ machine.config  [windows]Microsoft.NetFramework[Version]C onfig ◦ Root web.config  All applications inherit these configurations
  • 55.
    ASP.NET Configuration  Per Application ◦ web.config  In root application directory ◦ web.config in subdirectories
  • 56.
  • 57.
    Reading Assignment #2 Read ASP.NET Application Life Cycle Overview for IIS 7.0 http://msdn.microsoft.com/en- us/library/bb470252.aspx#GlobalAsax  Custom Validators  Rich Controls ◦ Calendars ◦ Sitemaps ◦ menus
  • 58.
    Report #2  Showa simple example of creating and retrieving cookies in javascript.  How can you load a User Control in code?
  • 59.
    Lab #2  Addvalidations to the registration form, Name(Required) and Age(between 18 and 120) at least.  Add site map to the site (Self Study)  In book.aspx, ◦ Create a UserControl (DateTimeControl.aspx) to display the current date and time on the top-right of the page. It must be refreshed every second without postback. ◦ The checked books are added to the Shopping Cart when checkout is pressed the chosen books are displayed in a new checkout.aspx page . ◦ Create a user control to count number of visitors and add it to the footer of all pages
  • 60.
    Lab Hints  Addevents to dynamic controls  Cast the object sender of the event to the wanted control  Use Javascript and/or jQuery for the user control  Try Trace=true in Page directive, to help in debugging
  • 61.
    Bonus  In book.aspx ◦ When next and back is clicked the previously checked books must stay checked so as the user can know what he already chose.
  • 62.
    REFERENCES  [1] BeginningASP.NET 4 In C# 2010, Matthew Macdonald, Apress  [2] Web Application Architecture Principles, Protocols And Practices, Leon Shklar And Richard Rosen, Wiley  [3] Professional AS P.NE T 4 In C# And VB, Bill Evjen, Scott Hanselman And Devin Rader, Wiley  [4] Pro ASP.NET In C# 2010, Fourth Edition,matthew Macdonald, Adam Freeman, And Mario Szpuszta, Apress

Editor's Notes

  • #5 Standardize repeated content across all pages, reuse header, footer and navigation controls
  • #10 TestControl pageTryUserControl pageDateTimeControl
  • #15 Validation page
  • #28 CounterNoViewState pageCounterViewState page
  • #29 Deserialization happens before Page.LoadCost  enlarged page size, slower transmission times!!
  • #32 CrossPagePosting pageCrossPagePosting2 page
  • #37 Cookie page
  • #38 SessionID (unique 120-bit identifier)Everytime you make a request you get a new sessionID. It is not saved until you store some information in the session collection.(slight performance enhancement)Common usage in shopping cartsUsing Cookies a cookie named ASP.NET_SessionIdUsing Modified URL for clients that don’t support cookies, session ID inserted in URLhttp://localhost/lect2/(S(bn3gnc55vu3sqffghdf))/Cookieless.aspx
  • #39 Add a logout button which cancels session using Session.Abandon()
  • #40 SessionState pageSessionState2 page
  • #41 State Provider is any class that implements IHttpSessionState interface
  • #42 Furniture session example
  • #44 acts as a static variable conceptCan be used in counting number of visitors with the global.asaxHeavy traffic can cause inaccuracy and in consistence of data, using Lock() and UnLock() can solve the problem but cause a slow down Can count number of created sessions or how many requests received
  • #45 ApplicationState pageCount number of times an operation is executed
  • #49 ASP.NET creates a pool of application objects (1 to 100 objects, acc. To system and available threads) when the application domain is first loaded and uses one to serve each request. Each request gets exclusive access to one of these objects and when the request ends, the object is reused.
  • #53 Global.asax page