Session Title by decree

VIEWS: 23 PAGES: 65

									ASP.NET With Visual Studio.NET



Peter Ty
MCSD, MCDBA, MCP+SB, MCSE
Developer Evangelist
Microsoft Hong Kong Ltd.
peterty@microsoft.com
Agenda
   Web Forms
   ASP.NET Applications
   Web Application Security
   Configuration and Monitoring
Web Forms
What is Web Forms?
   Code Model
   Life Cycle
   Server Side Events
   Server Controls
   Validation
Web Forms
Code Model

   Code Behind
   Logic – Presentation Separation
   Object Orientated
   Event Driven
Web Forms
ASP.NET Page Life Cycle

   Similar to Win32 Application Coding
   Events Raised as Page Created

Form_Initialize()     ~   Page_Init()
Form_Load()           ~   Page_Load()
Form_Activate()       ~   Page_PreRender()
Form_Unload()         ~   Page_Unload()
Web Forms
Server Side Events

   Runat=“server”
   <form runat=“server”>
   <input type=button id=button1
      OnServerClick=“Button1_Click”
      runat=“server” />
   Button1_Click(Sender as Object, e as
      EventArgs)
   Button1.Text = “Save”
Web Forms
Server Controls

   45 Built In Controls
   Target any HTML 3.2 browser
   Raise Events to Server
   Basic Controls
       textbox, checkbox, radio, button
   Advanced Controls
       AdRotator, Calendar, DataGrid, Validator
Web Forms
Basic Server Controls
   <asp:textbox id=text1 runat=server/>
    text1.text = “Hello World”
   <asp:checkbox id=check1
    runat=server/>
    check1.checked=True
   <asp:button id=button1
    runat=server/>
    button1_onClick()
   <asp:DropDownList id=DropDownList1
    runat=server>
    DropDownList1.SelectedItem.Text =
    “Hello”
Web Forms
Advanced Server Controls

   DataGrid
       Defined by <asp:datagrid />
       Column Sorting
       In-Line Editing
       HTML Table
       DataBinding
       Paging
Web Forms
Advanced Server Controls
   Validation
       Required Validator Control
       Range Validator Control
       Compare Validator Control
       Regular Expression Validator
       Custom Validator Control
       Example:
    <asp:RequiredFieldValidator
      ControlToValidate="txtName"
      ErrorMessage="Please Enter Your Name"
      runat="server" />
Agenda
   Web Forms
   ASP.NET Applications
   Web Application Security
   Configuration and Monitoring
ASP.NET Applications
Traditional ASP (global.asa)
   Application_OnStart
   Application_OnEnd
   Session_OnStart
   Session_OnEnd
ASP.NET Applications
Global.ASAX events
   First Request
       Application_Start
   First Request for Each User
       Session_Start
   Each Request
       Application_BeginRequest
       Application_Authenticate
       Application_EndRequest
   Application Error
       Application_Error
   User Logs Out/Session Times Out
       Session_End
   Web Server Shutdown
       Application_End
ASP.NET Applications
Global.ASAX Event Usage
   Application_BeginRequest
       Virtual Resources
       Text to be included at the start of every page
   Application_EndRequest
       Text to be added to the end of every page
   Application_Error
       Useful for sending out an email or writing to the
        event log when an error occurs that was not
        properly handled at the source of the error
ASP.NET Applications
Global.ASAX Event Usage
   Session_End
       Writing to a log file or database that a user has
        logged out at a given time
   Application_End
       Useful for writing out when the web application had
        to stop. Could write an entry out to the event log
   Application_Start
       Useful for loaded site specific configuration
        information
ASP.NET Applications
Saving Application State
 Essentially   global variables for the
  application
 Application(“CompanyName”)
 Can lock or unlock Application State
  Variables
   Application.lock
   Application(“GlobalCounter”)   = NewValue
   Application.unlock
ASP.NET Applications
Saving Session State
   Per User Variables
   Available to All Pages in the Site
   Session(“UserID”) = 5
   UserID = Session(“UserID”)
ASP.NET Applications
ASP vs. ASP .NET State
   ASP Session State
       Forces “Server Affinity”
       Dependent on cookies
       Not fault tolerant
   ASP .NET Session State
       Support for Web Gardens and Server
        Farms
       Doesn’t require cookies
       Better fault tolerance
ASP.NET Applications
Configuring Session State
 Configuration   information stored in
 Web.Config
  <sessionState
    Inproc=“true”
    mode=“sqlserver”
    cookieless=“false”
    timeout=“20”
    sqlconnectionstring=“data
     source=127.0.0.1;user id=sa;password=“”
    stateConnectionString="tcpip=127.0.0.1:4
     2424" />
  </sessionState>
ASP.NET Applications
Configuring Session State
   Mode
       InProc – Conventional session variables. Stored in-
        memory on the web server.
       Stateserver – Sessions are stored on an external
        server, in memory.
       SQLServer – Sessions are stored in a SQL
        database.
   Cookieless
       Determines if Cookieless sessions should be used
       Values are true or false
   TimeOut
       Determines the default timeout for the web site
ASP.NET Applications
Configuring Session State
   SQLConnectionString
       contains the datasource, userid, and password
        parameters necessary to connect to a sql database
        that holds the session state
   stateConnectionString
       Contains information needed to connect to the
        state server.
ASP.NET Applications
Storing Data in SQL Server
 In order to setup the SQL Server to store state
  information you must run a small T-SQL script
  on the target server
 InstallSQLState.sql can be found in
  [sysdrive]\winnt\Microsoft.NET\Framework\[ve
  rsion]
 Creates the following on the server
       A database called ASPState
       Stored Procedures
       Tables in TempDB to hold session data.
   Uninstall is via
       UninstallSQLState.sql
Agenda
   Web Forms
   ASP.NET Applications
   Web Application Security
   Configuration and Monitoring
Web Application Security
Security Concepts
   Authentication
   Authorization
   Impersonation
Web Application Security
Authentication
   Windows
       Basic
       Digest
       Integrated
   Passport
   Form
Web Application Security
Windows Authentication
   Enabled For IIS Through Internet
    Services Manager
Web Application Security
Windows Authentication
   Enabled for ASP.NET Through
    Web.config

    <security>
      <authentication mode="Windows" />
    </security>
Web Application Security
Windows Authentication
   Site Can Easily Access User Name

    Dim UserName As String
    UserName = User.Identity.Name

   NT Groups Automatically Map to ASP.NET
    Roles

    If User.IsInRole(“Administrators”)
    Then…
Web Application Security
Form Authentication
   Web Site is Responsible for Security, not IIS
       Configure IIS to allow anonymous access
       Set Web.Config to force users to authenticate through a
        form
        <authentication mode="Forms">
              <forms loginUrl="Registration.aspx">
              </forms>
        </authentication>
        <authorization>
              <deny users="?" />
        </authorization>


   Any Unauthenticated User Will Get Sent to
    “Registration.aspx”
Web Application Security
Form Authentication
   You Code a Form to Collect User ID and
    Password
   To Authenticate a User:
    FormAuthentication.RedirectFromLoginPage(UserName,
    False)
   RedirectFromLoginPage
       Marks the user as authenticated
       Takes the user to the page they originally
        requested
       If the user requested the login page, takes the
        user to Default.aspx
       Can persist authentication in a cookie
Web Application Security
Form Authentication - Declarative
   For Simple Sites, You Can Store User
    ID and Password in Web.config

    <credentials passwordFormat="clear">
      <user name="MSDN" password="online" />
      <user name="Guest" password="guest" />
    </credentials>
Web Application Security
Form Authentication - Declarative
   User is Authenticated by Calling

    FormsAuthentication.Authenticate( _
      UserName, Password)
Web Application Security
Form Authentication - Programmatic
   Code is Used to Authenticate the User

SQL = “Select * From Users ” & _
    “Where UserID = „” & UserName & “‟”

If UserFoundInDataBase then
    FormAuthentication.RedirectFromLoginPage(UserNam
    e,false)
Else
    lblLoginError.Text = “User Not Found or Invalid
    Password”
end if
Web Application Security
Roles

 Jane               Page
           RD       RD Content
 John
  Jill
 Jamie    Admins    Admin Content

 Jenny
Web Application Security
Roles
   Build the Application In Terms of Roles
       Access to Pages
       Custom Page Content
   After Deployment, Assign Users To
    Roles
Web Application Security
Roles
   Programmatically Assigning Users to
    Roles

Sub Application_AuthenticateRequest(ByVal Sender As
   Object, ByVal e As EventArgs)

    If request.IsAuthenticated = True Then
       sql = “select role from roles where userid=„“
             & UserID & “‟”

       „ Get Roles from Result Set
       context.User = New GenericPrincipal(user,
       roles)
    End If

End Sub
Web Application Security
Roles
   Display Content Based on Roles

    If User.IsInRole(“HumanRes”) Then
      cmdEditSalary.Visible = true
    End If
Web Application Security
Impersonation
   Windows Authentication
   Web.config

    <identity>
      <impersonation enable="true"
                     name="username"
                     password="password" />
    </identity>
Agenda
   Web Forms
   ASP .NET Applications
   Web Application Security
   Configuration and Monitoring
Configuration and Optimization
Web.Config

   Site Configuration File
   Ships with the Site
   Stores Most Configuration Options
   Eases Maintenance and Deployment
   Changes Take Effect Immediately
Configuration and Optimization
Hierarchical Configuration Architecture
   Web.Config files and their settings are
    inherited in a hierarchy
       Machine Settings (Winnt\Microsoft .NET\Version\)
       Web Application Root Directory
       Sub directories
Configuration and Optimization
Hierarchical Configuration Architecture
   Settings can be targeted at a specified set of
    files/directories by use of the <location> tag

<configuration>
    <location path=“/admin”>
      <system.web>
         <security>
             <authorization>
             <allow roles=“Admins”>
             </authorization>
         </security>
      </system.web>
    </location>
</configuration>
Configuration and Optimization
Default Configuration Settings
   Machine.config
       Tracing             Disabled
       Execution Timeout   90 Seconds
       Session State       Enabled, Inproc
       Authentication      Allow Anonymous
       Multi CPU Support   Disabled
Configuration and Optimization
Custom Configuration Settings
   Examples of Customization
       AppSettings
       CustomErrors
       Trace Settings
       Authentication
       Session Settings
       Browser Capabilities
Configuration and Optimization
Custom Configuration Settings
   Custom Setting in Config.Web

    <configuration>
      <appSettings>
            <add key="DSN" value="server=localhost…
      </appSettings>
    </configuration>


   Accessing with Code

    DSN = ConfigurationSettings.AppSettings("DSN")
Configuration and Optimization
Custom Configuration Settings
   Redirect Certain Errors to Certain
    Pages
<customErrors mode="On">
   <error statusCode="404"
   redirect="errorpage404.aspx" />
</customErrors>

<customErrors mode=“RemoteOnly">
   <error statusCode="404"
   redirect="errorpage404.aspx" />
</customErrors>
Configuration and Optimization
Custom Configuration Settings
   Tracing

    <trace enabled=“true"
          requestLimit="10"
          pageOutput=“true"
          traceMode="SortByTime"
    />
Configuration and Optimization
Custom Configuration Settings
   Trace Options
       Enabled
           Tracing information will be stored. Information can be
            accessed through
              http://site/trace.axd
       RequestLimit
           Store tracing information for this many requests
       PageOutput
           Allows trace output to also appear at the bottom of the
            page.
       TraceMode
           Allows trace information to be sorted by time or
            category.
Configuration and Optimization
Custom Configuration Settings
   Writing to the Trace Log

Trace.Write(“Page_Load”,”Entering Event”)
Trace.Warn(“GetCustomer”,”Invalid Argument”)
Configuration and Optimization
Page Output Caching
   Pages That Don’t Change Frequently
   Dramatic Performance Increase

    <%@ OutputCache Duration= "500" %>
Configuration and Optimization
Fragment Caching
   Dynamic Portions of a Page
   Data Doesn’t Change Frequently
   User Control

    <%@ OutputCache Duration=“60" %>
Configuration and Optimization
Cache API’s
   Programmatically Cache Data

    Cache.Insert( _
      Key, _
      Value, _
      CacheDependency, _
      AbsoluteExpiration, _
      SlidingExpiration, _
      Priority, _
      PriorityDecay, _
      Callback)
Configuration and Optimization
Cache API’s
   Key
       String used to look up the cached item
   Value
       Item or object to store in the cache
   CacheDependency
       Cache item can automatically expire when
        a file, directory, or other cache item
        changes
Configuration and Optimization
Cache API’s
   AbsoluteExpiration
       Cache item can expire at some fixed time
        (midnight, for example)
   SlidingExpiration
       Cache item can expire after a certain amount of
        inactivity
   Priority
       When forcing items from the cache, which items
        should go first
   PriorityDecay
       Within a given priority range, does this item
        expire fast or slow
Configuration and Monitoring
Monitoring ASP.NET Applications
   Monitoring Tool Integration
       Performance Monitor
       Tracing Support
       Service Control and Monitoring
Configuration and Monitoring
Performance Counters
   Some Counters are now more
    application specific as oppossed to
    server specific for traditional ASP
   Counter Groups
       Global Performance Counters
       Application Specific Counters
Configuration and Monitoring
Global Performance Counters
   Global Performance Counters
       Application Restarts
       Applications Running
       Requests Queued
       Request Wait Time
Configuration and Monitoring
Application Specific Counters
   Application Performance Counters
       Cache Total Entries
       Cache Total Hit Ratio
       Request Bytes in Total
       Requests Executing
       Requests Timed Out
       Sessions Timed Out
Configuration and Monitoring
PerformanceCounter Class
   The PerformanceCounter class allows
    you to access counter data from code

    Dim Req_Bytes_Total As New
      PerformanceCounter(“asp .net
      applications", “Request Bytes Out
      Total”, _Total_)
    Dim s as Integer
    S = Req_Bytes_Total.NextValue()


   The same code can be used to retrieve
    standard counters as well
Configuration and Monitoring
Tracing
   Tracing
       Timing information between successive
        trace output statements
       Information about the server control
        hierarchy
       The amount of viewstate used
       Render size of controls on your page
Configuration and Monitoring
Tracing
   Enable Tracing for a specific page

    <%@ Page trace=true Language="vb"
       AutoEventWireup="false"
       Codebehind="Write_Trace_Info.aspx.vb"
       Inherits="Opt_Monitor.Write_Trace_Info"%>


   Writing Custom Trace Statements

    Trace.Write(“Custom Trace”, “Begin Load
      DataSet”)
Configuration and Monitoring
Accessing Services
   ServiceController class
       Allows you to access locally or remote services
           Constructor
              Takes ServiceName as Parameter
           Methods
              Stop
              Start
              Pause
              WaitForStatus
                   Srv.WaitForStatus(ServiceControllerStatus.
                    Stopped, System.TimeSpan.FromSeconds(30))
                   Allows you to easily wait for the service state to
                    change to the desired state before continuing
           Properties
              MachineName
                 Gets or sets the machine name
Configuration and Monitoring
Checking Service State
   Checking the Service State
    Protected Sub CheckServiceState(ByVal ServiceName
       As String) as String
            Dim Srv As New
       ServiceController(ServiceName)
       Select Case Srv.Status
                 Case ServiceControllerStatus.Running
             CheckServiceState = "Started"
                 Case ServiceControllerStatus.Stopped
             CheckServiceState = "Stopped"
          Case Else
              CheckServiceState = "Unknown"
            End Select
       End Sub
For More Information…
   MSDN Web Site at
       msdn.microsoft.com
   ASP.NET Related Sites at
       msdn.microsoft.com/library/dotnet/cpguide/cpconaspwebfor
        ms.htm
       msdn.microsoft.com/library/dotnet/cpguide/cpconaspnetapp
        lications.htm
       msdn.microsoft.com/library/dotnet/cpguide/cpconaspstatem
        anagement.htm
       msdn.microsoft.com/library/dotnet/cpguide/cpconoptimizing
        aspapplications.htm
       msdn.microsoft.com/library/dotnet/cpguide/cpconsecuringa
        spnetwebapplications.htm
       msdn.microsoft.com/library/dotnet/cpguide/cpconaspcachin
        gfeatures.htm
       msdn.microsoft.com/library/dotnet/cpguide/cpconaspnetcon
        figurationconcepts.htm

								
To top