ASP NET and Web Services

Document Sample
ASP NET and Web Services Powered By Docstoc
					                                 FIS Incorporated
                          ASP.Net and Web Services Notes
The following comments and examples apply to ASP.NET 2.0. The examples were created used
ASP.NET Express Edition (see

A simple ASP.NET application has:

    1. A web file with extension .aspx that contains the Web pages GUI
    2. An optional code-behind file containing code to support the display/function of the web
       page. The file is names the same as the web page with a .apsx.vb (assuming VB is used)

The code in the code-behind file can actually be incorporated in the web file. The purpose of the
code-behind file is to promote code reuse.

The ubiquitous “Hello World”

A very simple ASP page that initially displays a page with one ASP button and label and when
clicked redisplays the page with “Hello World” is below. Note that ASP controls are handled
differently that ‘regular’ HTML buttons

Web File named HelloWorld.aspx

<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="HelloWorld.aspx.vb" Inherits="_Default" %>
<-- above denotes page to be processes as ASP page, VB is used,
codebehind file name given, and class ‘HelloWorld’ to inherit from -->
<-- AutoEventWireup=”false” tells VB to generate the Page_Load and
Page_Init events without Handles keywords. Always set to false -->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<html xmlns="" >
<head runat="server">
    <title>Hello World</title>
    <form id="form1" runat="server">
        <-- asp:Button indicates ASP control that is to run at server --
        <asp:Button ID="Button1" runat="server" Text="Click Me"
Width="124px" /><br />
        <br />
        <asp:Label ID="Label1" runat="server"
Width="212px"></asp:Label>&nbsp;<br />
        <br />

Code-behind file named HelloWorld.aspx.vb

Partial Class _Default

                                 FIS Incorporated
                          ASP.Net and Web Services Notes
      Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Button1.Click
        ' When button1 clicked on page the server processes the click
and assigns “Hello World” to asp Label1
        Label1.Text = "Hello World"
    End Sub

End Class

Validation Controls

A validation control determines if the data entered in another control is in the proper format. A
validator is converted to JavaScript (as referred to as ECMAScript – European Computer
Manufacturer’s Association) and is executed on the client.

If the client does not support scripting or scripting is disabled the validation is performed on the

The following shows a simple page with entry for a phone number, including area code.
Validation controls will check to see 1) a phone number value is entered, and 2) the phone
number is entered with the format nnn-nnn-nnnn. The validators are executed on the client prior
to the postback to the server when the ‘Submit’ button is pressed. If either validator fails an error
message is diplayed.

Assuming a phone number is entered and of the correct format, the server postback logic is
executed. The page is redisplayed with a validation message based on the value of the phone

Validator.aspx file

<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="Validator.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<html xmlns="" >
<head runat="server">
    <title>Untitled Page</title>
<body style="position: absolute">
    <form id="form1" runat="server">
    <div title="Field Validation">
        <asp:Label ID="lblPhoneNumber" runat="server" Text="Please enter
your phone number, area code first below:"
           Width="353px"></asp:Label><br />
        <br />
        <asp:TextBox ID="tbPhoneNumber"
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="tbPhoneNumber"
           ErrorMessage="Invalid number. Please

                                 FIS Incorporated
                          ASP.Net and Web Services Notes
        <br />
        (format nnn-nnn-nnnn)&nbsp;&nbsp; &nbsp; &nbsp;
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" ErrorMessage="Invalid number. Please reenter."
        <br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit"
Width="83px" /><br />
        <br />
        &nbsp;<asp:Label ID="lblVerifiedNumber" runat="server"
Visible="False" Width="284px"></asp:Label></div>

Validator.aspx.vb file

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
        If IsPostBack Then
            If (tbPhoneNumber.Text = "123-456-7890") Then
                 lblVerifiedNumber.Text = "Number is validated"
                 lblVerifiedNumber.Text = "Number not validated. Try
            End If
            lblVerifiedNumber.Visible = True
        End If
    End Sub

End Class

Maintaining Session Information and State

Values can be held across pages using several mechanisms
Save values in ‘hidden’     A general method for saving values. Not ASP specific
Set EnableViewState=true A APS.NET feature to retain a Web controls value when a postback

                                 The web control value is contained in a hidden field named
                                 _VIEWSTATE and stores the all Web control data values as an
                                 encoded string

                                 The ASP.NET IDE handles the storing of values automatically
Save values in Cookies           A non-ASP specific feature that save keyword/value pairs on the

                                 FIS Incorporated
                          ASP.Net and Web Services Notes
                                 client between callbacks to the server. The cookie logic is
                                 implemented in the server ASP.NET code

                                 Creating a cookie
                                 Dim cookie As HttpCookie
                                 cookie = new HttpCookie(keyword, value)

                                 Retrieving values from cookies

                                 Dim cookies As HttpCookieCollection
                                 Dim keyword as String
                                 Dim value as String
                                 cookies = Request.Cookies

                                 If (((cookies Is Nothing) = False) AndAlso cookies.Count > 0) Then
                                     For i = 0 to cookies.Count - 1
                                      keyword = cookies(i).Name
                                      value = cookies(i).Value

                                 Note: If session tracking is enabled (ie EnableSessionState="True"
                                 property is set in the .aspx page ) then the first cookie (index 0) is
                                 the session id cookie – APS.NET_SessionId) ????

                                 Cookie properties:
                                 Name – Returns a string with cookies name.
                                 Value – Returns a string with the cookies value
                                 Domain – Returns a string giving domain of web server from which
                                 cookie was loaded
                                 Expires – Returns a DateTime object of when the cookie expires
                                 Path - Returns a string with URL prefix for the cookie
                                 Secure – Returns Boolean indicating if cookie should be transmitted
                                 via a secure protocol

HttpSessionState                 Enables session tracking via the HttpSessionState class. An
                                 HttpSessionState object stores values in keyword/value pairs like
                                 cookies, but the values can be objects other than strings.

                                 Adding values to HttpSessionState object

                                 Values are added via the Session object
                                 Session.Add(keyword, value)

                                 Obtaining values from the Session object.

                                 sessionid = Session.SessionID

                                 FIS Incorporated
                          ASP.Net and Web Services Notes
                                 timeout = Session.Timeout
                                 If Session.count <> 0 Then
                                    For i = 0 to Session.Count – 1
                                       keyname = Session.Keys(i)
                                       Value = Session(keyname)
                                 End If

                                 Session properties
                                 Count – number of keyword/value pairs in Session object
                                 IsNewSession – Boolean to indicate whether the session was
                                 created during the loading of the current page
                                 IsReadOnly – Boolean to indicate if Session object is read only
                                 SessionId – Returns session’s unique ID
                                 Timeout – Specifies the maximum number of minutes a session can
                                 be inactive before the session expires. Default is 20 minutes.

Adding Web User Controls

A web user control could be something as simple as an image or more complex like a menu bar.
Changes to the user control are therefore isolated. Only the web user control file needs to be
maintained as opposed to all web pages that use the control.

Web user controls are defined to the web page via <%@ Register webcontrol %> directive.

Web user controls consist of 2 pages – the ASCX and the code behind file (assuming you use a
code-behind file).

The web page the uses/displays the web control
<%@ Register TagPrefix=”Header” Tagname=”MyWebControl” Scr=”MyWebControl.ascx” %>
<!--somewhere down in your html code -->
<Header:MyWebControl id=”MyWebControl1” runat=”server” >
MyWebControl.ascx file - assumes an image

<@ Control Language = “vb” AutEventWireup=”false” Codebehind=”MyWebControl.ascx.vb”
Inherits=”Project.MyWebControl” TargetSchema=”” %>
<asp:Control id=”mycontrol” runat=”sever”

MyWebControl.ascx.vb – include any code like any other code behind file

Web Services

A web service is a class running on one machine that responds to requests for information
originating from another machine.

Common data formats and protocols such as XML and HTTP are used for data communication.

                                 FIS Incorporated
                          ASP.Net and Web Services Notes
In .NET the method calls are implemented using SOAP – Simple Object Access Protocol. SOAP
is an XML formatted message than can be transferred via HTTP.

The .Net class developed is placed in the application \bin directory.
More than one method can be implemented in a Web Service. The methods are executed via
RPC – Remote Procedure Calls. The methods are marked with a WebMethod attribute, and via
this attribute the method is exposed for use via other classes through an RPC.

A web service is composed of 1 or 2 parts: a ASMX file and, if you want the executable code in a
separate file, the code-behind file. The ASMX file can be viewed in any browser can contains
information on the use of the web service methods and optionally the method logic. Optionally the
code-behind file provides the implementation of the methods

The display of the ASMX file on a browser contains:

    1. A link to the Service Description, an XML document (conforms to WSDL – Web Service
       Decription Language) that details how a web service behaves. The WSDL document
       defines the methods that the web service makes available and the ways the calling client
       can execute those methods and receive the reply.

    2. A list of methods that are provided by the service. Clicking on any method displays a test
       page where parameters can be entered and the service method can be executed on
       clicking the ‘Invoke’ button.

    3. Sample request and response messages using SOAP, HTTP GET and HTTP POST
       protocols (the protocols are also sometimes referred to as the wire protocol or wire format

SOAP is the default protocol for web services in .NET. SOAP supports a wider variety of data
types such as DataSet, DateTime, XmlNode, arrays, and user-defined data types – compared to
the other protocols.

An application that uses a web service consists of a proxy class (representing the web service)
and the client application that interacts with the web service.

The proxy class handles the call(s) to the web service and passing of method values and
receiving the results of the web service.

Examples of a web service are below. It is a simple service that concatenates 2 strings together

Concatenate.asmx with method logic included (no code behind file)

<%@ WebService Language="VB" Class="Concatenate" %>

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

<WebService(Namespace := "")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
Public Class Concatenate
    Inherits System.Web.Services.WebService

   <WebMethod(Description:="Concatenate 2 strings together")> _
   Public Function Concat(ByVal firstString As String, ByVal
secondString As String) As String

                                 FIS Incorporated
                          ASP.Net and Web Services Notes
       Return firstString & secondString
    End Function

End Class
VB.NET program that uses the Concatenate web service. Note a Web reference to
Concatenate.asmx was added to the project. The form had 2 input fields for the strings to
concatenate, a result field, and a submit button.

Imports System.ComponentModel
Imports System.Web.Services.Protocols

Public Class Form1
    Private remoteConcatenate As localhost.Concatenate

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
        remoteConcatenate = New localhost.Concatenate
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExecute.Click
        tbResults.Text = remoteConcatenate.Concat(tbString1.Text,

      End Sub

    Private Sub tbString1_TextChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles tbString1.TextChanged

    End Sub
End Class

Session Tracking in Web Services

Session tracking can be used by clients of Web services in the same manner as a client of an
ASP.Net web user.

The client must have enabled cookies so that a session id can be received from and returned to
the web service.

The web service will utilize session info based on each method defined to use session tracking.

Service.vb – A web service that returns the time along with a session id, concatenated with prior

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

                                 FIS Incorporated
                          ASP.Net and Web Services Notes

<WebService(Namespace:="")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
     Inherits System.Web.Services.WebService

    <WebMethod(EnableSession:=True, Description:="Return current
(server) time plus all prior times you asked for time")> _
    Public Function GetTheTime() As String
        Dim allTimes As String
        allTimes = CType(Session("time"), String)
        If allTimes Is Nothing Then
             allTimes = GetCurrentTime() & "|" & Session.SessionID
             allTimes = GetCurrentTime() & "|" & Session.SessionID & "|"
& allTimes
        End If
        Session.Add("time", allTimes)
        Return allTimes
    End Function

    Public Function GetCurrentTime() As String
        Return String.Format("{0:D2}:{1:D2}:{2:D2}", _
                 DateTime.Now.Hour, DateTime.Now.Minute, _
    End Function
End Class

DisplayTimeFromService.vd – A VB.NET app that calls the service. Remember to define the
service via Project/Add Web Reference

Imports System.Net
Imports System.Web

Public Class ServerTimeClient
    Private timeServer As localhost.Service
    Dim cookies As CookieCollection
    Dim keyword As String
    Dim value As String

    Private Sub btnGetTime_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnGetTime.Click
        Dim i As Integer
        Dim serverUri As System.Uri = Nothing
        Dim cookieString As String = ""
        Uri.TryCreate(timeServer.Url(), UriKind.Absolute, serverUri)
        tbDisplayTime.Text = timeServer.GetTheTime()
        cookies = timeServer.CookieContainer.GetCookies(serverUri)
        If ((cookies Is Nothing) = False) Then
            For i = 0 To cookies.Count - 1
                 cookieString &= cookies(i).ToString()
        End If

                                 FIS Incorporated
                          ASP.Net and Web Services Notes
            If (cookieString <> "") Then
            End If

      End Sub

      Public Sub New()

            ' This call is required by the Windows Form Designer.

            ' Add any initialization after the InitializeComponent() call.
            timeServer = New localhost.Service()
            timeServer.CookieContainer = New CookieContainer()

      End Sub

    Private Sub ServerTimeClient_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub
End Class

Miscellaneous Defaults

Local projects                                         http://localhost

                                                       Using IIS the default directory is


Shared By: