Web Applications - PowerPoint PPT Presentation

1 / 79
About This Presentation
Title:

Web Applications

Description:

Active Server Pages (ASP) is a server-side scripting ... Posted Back Page. Event starts, control is transferred to. the server event-handling function. ... – PowerPoint PPT presentation

Number of Views:94
Avg rating:3.0/5.0
Slides: 80
Provided by: ron7
Category:

less

Transcript and Presenter's Notes

Title: Web Applications


1
Web Applications
  • Rong Li

2
  • Objectives
  • ASP.NET
  • Web Forms
  • a. Server controls
  • b. Database connection
  • c. Delegates
  • d. Create a web control

3
ASP
  • Active Server Pages (ASP) is a server-side
    scripting technology enabling dynamic web pages.
    An ASP page contains HTML markup and server-side
    scripts that generate HTML content dynamically.
    The server-side scripts run when a request for
    the ASP page arrives at the web server.

4
ASP.NET
  • ASP.NET pages are compiled .NET components and
    execute at native code speed. ASP.NET allows
    developers to use any .NET targeted language such
    as C, VB.NET and Managed C.
  • For ASP.NET pages to execute, IIS needs to be
    properly configured with FrontPage extensions

5
Example 1 -- Hello
  • Write the following code with any text editor and
    save it with .aspx (ASP.NET).
  • Hello There!!!!!!!!
  • StringBuilder strnew StringBuilder("Hello ")
  • str.Append("World...")
  • Response.Write(str.ToString())

6
  • With Windows Explorer, right-click on
  • the directory where the file has been saved.
  • Select properties.
  • Click on the Web Sharing tab.

7
  • 5. Select the Share this folder option to view
    the Edit Alias dialog
  • Press OK to accept the default settings

8
  • From start menu, select run and type
  • http//localhost/nameofdir/filename.aspx
  • in the examplehttp//localhost/hello/hello.aspx

9
Web Forms
  • Web Forms are GUI-based applications displayed
    in browsers via HTML and inherit from
    System.Web.UI
  • Web Forms implement a programming model in which
    web pages are dynamically generated on a web
    server for delivering to a browser over the
    Internet.
  • With Web Forms, HTML pages are created with
    static content, and C code generates dynamic
    content.
  • Web Forms are designed to run on any browser,
    with the server rendering the correct
    browser-compliant HTML.

10
  • Web Forms divide the user interface into two
    parts the visual part or user interface (UI),
    and the logic that lies behind it. The UI page is
    stored in a file with the extension .aspx. The
    logic (code) for that page can be stored in a
    separate code-behind C source file.

11
Web Form Events
  • Web Forms are event-driven.
  • A method that responds to a event is called event
    handler.
  • Event handlers are delegates
  • Most events are typically handled on the server .

12
Postback versus non-postback events
  • Postback events cause the form to be posted back
    to the server immediately .
  • Non-postback events are cached by the control
    until the next time that a postback event occurs.

13
Responding to Postback Events
  • A button object automatically postback when
    clicked. No code is needed unless you do
    something more than postback to the server.
    Normally, the Web is stateless, but ASP.NET
    provides assistance. When a page is posted, a
    hidden element named ViewState is automatically
    added to the page. The element represents the
    state of the form. When the page is redrawn on
    the client, ASP.NET uses the ViewState to return
    the controls to the previous state.

14
Web Form Life Cycle
  • Every request for a page made from a web server
    causes a chain of events at the server. These
    events constitute the life cycle of the page and
    all its components. The life cycle of a page is
    marked by the following events
  • Initialize
  • Load ViewState
  • Process Postback Data
  • Load

15
  • Send Postback Change Modifications
  • Handle Postback Events
  • PreRender
  • Save State
  • Render
  • Dispose

16
Web Form event life cycle


17
Statelessness
  • Web application are stateless
  • Each page request is self-contained operation
  • 1. connection is opened
  • 2. request is posted
  • 3. result is returned
  • 4. connection is closed

18
Example 2 -- Button Event In Web Form
  • runat"server" Text"Log in"
  • protected void btn1_Click(object sender,
    System.EventArgs e)
  • label1.TexttextBox1.Text
  • textBox1.Text""

19
  • Follow the steps that is mentioned in the
    previous example to execute the program.
  • Output

20
  • Input data into textbox then click button

21
  • The language attribute indicates that the
    language used on the code-behind page is C
  • runat"server
  • Any tag that includes this attribute is
    considered a server-side control to be executed
    by the ASP.NET framework on the server

22
  • To Create A Web Form
  • Setting initial properties
  • Page_Load event is fired every time when a Web
    Form is loaded. ASP.NET can differentiate the
    first time the page displayed from subsequent
    displayed pages after a client postback of the
    page to the server. Every Web Form page has the
    property IsPostBack, which is true if the page is
    being loaded in response to a client postback,
    and false if it is being loaded for the first
    time.
  • Data binding
  • bind controls to data when the data was
    modified, the controls responded automatically.

23
Server Controls
24
(No Transcript)
25
(No Transcript)
26
Validation Controls
27
Example 3 Products Using VS
  • Launch VS as usual
  • Select Visual C projects and ASP.NET Web
    Application and give a name for the project in
    Location text field, OK

28
  • 3. Create a form that looks like the following
    Change the property of TextBox control to
    MultiLine

29
  • 5. Add a new WebForm2, right click on the
    application

30
  • 6. Backe to WebForm1, change NavigateUrl of
    HyperLink property to WebForm2.aspx, OK

31
  • 7. Right click on WebForm1.aspx in Solution
    Explorer, select View Code. Then add the
    following code
  • class AddItem
  • string item ""
  • string description ""
  • public string Item
  • get
  • return item
  • public string Description
  • get
  • return description
  • public void SetInfo(string item, string
    description)
  • this.item item
  • this.description description

32
  • class AddList
  • Hashtable list new Hashtable()
  • public void Add(AddItem tditem)
  • list.Add(tditem.Item,
  • tditem.Description)
  • public void Remove(AddItem tditem)
  • list.Remove(tditem.Item)
  • public ICollection TaskList
  • get
  • return list.Values

33
  • 7. Right click on Global.asax and select View
    Code. Add following code
  • protected void Application_Start(Object sender,
    EventArgs e)
  • AddList addlistnew AddList()
  • Application.Add("list",addlist)

34
  • Global.asax
  • When execute Web application, the ASP.NET
    framework creates an application object. The
    application object is an instance of the class
    defined in Global.asax. The first time the
    application is run, ASP.NET calls the
    Application_Start method. If stop the Web server
    or update files in a project, the object will
    call the Application_End method.

35
  • 8. Add following code to WebForm1.aspx
  • void ClearFields()
  • txtItem.Text ""
  • txtDescription.Text ""
  • private void btnTask_Click(object sender,
    System.EventArgs e)
  • AddItem item new AddItem()
  • item.SetInfo(txtItem.Text,
  • txtDescription.Text)
  • Application.Lock()
  • AddList list (AddList)Application"list"
  • list.Add(item)
  • Application.UnLock()
  • ClearFields()

36
  • 9. Back to WebForm2, create a WebForm looks like
    the following

37
  • 10. Double click on WebForm2 and add the
    following code
  • private void Page_Load(object sender,
    System.EventArgs e)
  • AddList list (AddList)Application"list"
  • ListBox.DataSource list.TaskList
  • ListBox.DataBind()

38
  • 11. Select Debug Start or push F5 to compile
    and run. Type item and description then click
    Add Item

39
  • 12. To view the list click either View List
    hyperLink or button

40
Application Use Oracle Database
  • Needs to install oracle8i or higher version.
  • Needs to install Oracle Data Provider
  • --See detail in Oracle Data Provider Section.

41
Example 4Application connects to oracle database
  • Launch Visual Studio as before
  • Create a WebForm1 which looks like the following

42
  • 3. Drag OracleDataAdapter into WebForm
  • 4. Click Next

43
  • 5. Provide database information and test
    connection and OK

44
  • 6. Leave default setting, Click Next

45
  • 7. Click Query Builder

46
  • 8. Select a table to be used, then click add and
    then close buttons

47
  • 9. Check all columns, click OK

48
  • 10. Click Finish

49
  • 11. In DataGrid properties window, click column
    to set columns name of dataGrid
  • 12. Select Bound Colunm in available column then
    click button
  • 13. Type into Header text and Data Field, OK

50
  • 14. Add following code to the project
  • using System.Data.OracleClient
  • private ArrayList students
  • private void Page_Load(object sender,
    System.EventArgs e)
  • if(Session"students"null)
  • studentsnew ArrayList()
  • else
  • students(ArrayList)Session"students"
  • DataGrid1.Visibletrue
  • DataGrid1.DataSourcestudents
  • DataGrid1.DataBind()

51
  • private void Button1_Click(object sender,
    System.EventArgs e)
  • oracleConnection1 new OracleConnection(oracl
    eConnection1.ConnectionString)
  • oracleConnection1.Open()
  • string cmdstr"select from student where
    major ""'"TextBox1.Text"'"
  • OracleCommand cmd new OracleCommand(cmdstr,orac
    leConnection1)
  • OracleDataReader reader cmd.ExecuteReader()
  • int i1
  • while(reader.Read()i
  • i
  • Student studentnew Student(reader.GetString(0),
  • reader.GetString(1),
  • reader.GetString(2),
  • reader.GetString(3))
  • students.Add(student)
  • DataGrid1.Visibletrue
  • DataGrid1.DataSourcestudents
  • DataGrid1.DataBind()

52
  • public class Student
  • string snum,sname, city, major
  • public Student(string snum,string sname,string
    city,string major)
  • this.snamesname
  • this.snumsnum
  • this.citycity
  • this.majormajor
  • public string MAJOR
  • get
  • return major
  • set
  • majorvalue
  • public string SNAME
  • get
  • return sname

53
  • 15. Push F5 to compile and run

54
  • 16. Input major and search.

55
Delegates
  • Delegates are user-defined data types. Once a
    delegate is declared, you can create instances of
    it and pass a function as a parameter to the
    constructor.
  • Delegates can only store functions that match in
    declaring the delegate. Use delegate variable to
    invoke functions that the delegate stores.
  • The purpose of delegates is for making callback
    methods.

56
  • Two types of eelegates
  • Delegates derived from the class System.Delegate
  • Delegates derived from the class
    System.MulticastDelegate

57
Firing Delegates Asynchronously
  • Two ways to execute a delegate asynchronously
  • Write code for waiting until the delegate
    finishes executing. It works fine for executing
    multiple functions asynchronously, each in
    different threads, and wait for their completion
  • Let the system notify when the delegate is done.
    It works for executing one function
    asynchronously, all others in the main thread
    when the delegate is executing.

58
Example 5 Using Delegates
  • Launch Visual Studio .NET as previous example.
    Select visual C projects and ASP.NET Web
    Application. Give a name for the project as
    delegatesExample.

59
  • 2. Create a Web Form looks like as follows

60
  • 3. Right click on WebForm1.aspx, select view
    code. Then add a class into it. And a delegate
    definition for invoking Task1 or Task2.
  • namespace delegatesExample
  • //class WebForm1 code
  • class Tasks
  • public bool Task1(string desc)
  • System.Threading.Thread.
  • Sleep(5000)
  • return true
  • public static bool Task2(string desc)
  • System.Threading.Thread.
  • Sleep(5000)
  • return true
  • delegate bool TaskDel(string desc)

61
  • 4. Click on WebForm1.aspx on the top of the web
    form. Double click on Synchronous task button.
    Add the following code.
  • private void Button1_Click(object sender,
    System.EventArgs e)
  • Tasks tsks new Tasks()
  • System.DateTime dt1 System.DateTime.Now
  • tsks.Task1("Calling Task1...")
  • Tasks.Task2("Calling Task2...")
  • System.DateTime dt2 System.DateTime.Now
  • System.TimeSpan tm dt2 - dt1
  • Label2.Text tm.TotalSeconds.ToString()

62
  • 5. Double click on Asynchronous task button. Add
    the following code.
  • private void Button2_Click(object sender,
    System.EventArgs e)
  • Tasks tsks new Tasks()
  • TaskDel del1 new TaskDel(tsks.Task1)
  • TaskDel del2 new TaskDel(Tasks.Task2)
  • System.DateTime dt1 System.DateTime.Now
  • IAsyncResult ar1 del1.BeginInvoke("Calling
    Task1...",null,null)
  • IAsyncResult ar2 del2.BeginInvoke("Calling
    Task2...",null,null)
  • System.Threading.WaitHandle handles
  • new System.Threading.WaitHandle
    ar1.AsyncWaitHandle,ar2.AsyncWaitHandle
  • System.Threading.WaitHandle.WaitAll(handles)
  • System.DateTime dt2 System.DateTime.Now
  • System.TimeSpan tm dt2 - dt1
  • Label2.Text tm.TotalSeconds.ToString()

63
  • Note
  • Every delegate object has a BeginInvoke function
    and an EndInvoke function as well as the Invoke
    function, which is used for synchronous operation.

64
Output
65
Example 6--Create a web control
  • Launch Visual Studio as before, but select visual
    C projects and Web Control Library, give a
    project name as MyControl and location, OK

66
  • 2. Add variable declaration into the project also
    add using System.Collections at very beginning
  • private string text
  • private int _rows10
  • private int _cols5
  • Cell, _cells
  • Hashtable hsCells new Hashtable()

67
  • 3. Add a class into the project
  • public class Cell
  • private string _text
  • WebCustomControl1 _parent
  • private int _row, _col
  • string _key
  • public Cell(WebCustomControl1 parent,int row,
    int col)
  • _parent parent
  • _row row
  • _col col
  • public string Text
  • get
  • return _text
  • set
  • _text value

68
  • public int Row
  • get
  • return _row
  • public int Column
  • get
  • return _col
  • public string Key
  • get
  • return _key
  • set
  • _key value
  • _parent.SetCellKey(_key,_row,_col)

69
  • 4. Add methods into the project
  • public Cell thisint row, int col
  • get
  • return _cellsrow,col
  • public void CreateGrid()
  • _cells new Cell_rows,_cols
  • for (int r 0 r
  • for(int c 0 c
  • _cellsr,c new Cell(this,r,c)

70
  • public Cell thisstring key
  • get
  • Cell retVal null
  • string cellIndex (string)hsCellskey
  • if (cellIndex ! null cellIndex ! "")
  • string coords cellIndex.Split('')
  • int r System.Convert.ToInt32(coords0)
  • int c System.Convert.ToInt32(coords1)
  • retVal _cellsr,c
  • return retVal

71
  • Category("Appearance"), DefaultValue(10)
  • public int Rows
  • get
  • return _rows
  • set
  • _rows value
  • CreateGrid()
  • Category("Appearance"), defaultValue(5)
  • public int Columns
  • get
  • return _cols
  • set
  • _cols value
  • CreateGrid()

72
  • 5. Overwrite code in Render() method
  • protected override void Render(HtmlTextWriter
    output)
  • output.AddStyleAttribute(
  • HtmlTextWriterStyle.BorderCollapse,"collapse")
  • base.RenderBeginTag(output)
  • output.Write(DrawGrid())
  • base.RenderEndTag(output)

73
  • 6. Push F5 to compile it
  • 7. Select Tools Add/Remove Toolbox Items

74
  • 8. Click Browse to find the file

75
  • 9. Click Open, then OK

76
  • 10. Add a WebForm to test it. Select File Add
    Project New Project. Then select Visual C
    Project and ASP.NET Web Application

77
  • 11. The control has been added to Toolbox

78
  • 12. WebForm consumes the control

79
References
  • C Web Development with ASP.NET
  • Jose Mojica
  • ASP.NET By Example
  • Steven A. Smith
  • .NET Framework Essentials
  • Thuan Thai Hoang Q. Lam
  • Programming C
  • Jesse Liberty
  • C Unleashed
  • Joseph Mayo
  • C and the .NET Framework
  • Robert Powell Richard Weeks
Write a Comment
User Comments (0)
About PowerShow.com