.NET Notes

ASP.net

Version 0.14 by Samar 23/10/2003

  1. asp+ (asp+ vs. asp;directives, objects)
  2. Web Forms (Types, Server Ctrls: System.Web.UI.HtmlControls, System.Web.UI.WebControls, User Ctrls, Custom Ctrls)
  3. ADO.net (ado.net Layers + Items, System.Data, T-SQL, Transactions)
  4. Security (State Mgt: App, Sessn; Authenticn & Authorizn: anon, etc, User Info, Cookies, Clt-Side Scriptg, Passport; Unmanaged Code; COM, COM+)
  5. Testing (Types of Test, Debugging & Errors: Debug & Trace, Exception Handlg, Help)
  6. Xml & Xslt
  7. Globalization
  8. Web Server (IIS, Performance & Optimization: Cache + Caching, Buildg & Deploymt: Windows Installer, Xcopy)
  9. Xml Web Services (System.Web.Services)

I. asp+

a. asp+ vs. asp

asp.net/asp+ : - a unifd web dev platform providg services necessary for enterprise-class web apps [msdn]; a prog framewk built on the CLR usable on server to build powerful web apps.

ASP.NET
WebForms Web Services
WinForms
Framework Classes
Common Language Runtime

    Componts of .net framework:
  1. CLR (common lang. runtime): execn engine, manages code at exec time (mem mgt, thrd execn., code exec, code safety verifn, compiln, auto app installn, auto garbage collectn, high security, etc.): compiles assembly (dll) to final state at runtime.
  2. .net framewk class lib: OO collectn of reusable types, complete set of win prog classes
| .net code |-----> | dll (in MSIL) | -------> | CLR |
           compiled        assembly             compile to native code
                                                + execs

    Types of Applications:
  1. Web Apps (System.Web): provide server content to clients via web browser; ASP.net, web forms. Web apps has 3 parts: content: web forms, html, prog logic: dlls, web cfg info: Web.config, css.; webapp defd by iis = any file exectd within a set of folders on website
  2. Web services (System.Web.Services): provide server processg services to other apps; XML Web Services
  3. Internet-enabled apps (System.Net): standalone apps incorporatg web info to provide user services (help, updates, etc.); Winforms
  4. Peer-to-peer apps (System.Net & System.Net.Sockets): standalone apps usg web to communicate with other users runng own instances of app.
    asp.net process flow :
  1. http request sent to iis; iis starts asp_wp.exe if not already runng; asp_wp.exe loads assemblies of web form; assemblies respond to user. aspnet_isapi.dll (c:\Windows\Microsoft.NET\Framework\1.1...\aspnet_isapi.dll) used to call aspnet worker process [webb.76, 421]
  2. xspisapi.dll filter intercepts request, passes it to xspwp.exe XSP worker process.
  3. xspwp hands request to correct HTTPModule (isapi filter replacemts, classes takg pt in every request) & HTTPHandler (end pt of web request processg, = isapi extensns)
  4. aspx pg read from hd/cache & exec
  5. JavaScript required by asp.net to call serverside code; JavaScript disabled --> asp.net cannot call serverside code
  6. Document.EnableSessionState = true | false | ReadOnly - (pg maintns session state | not | pg cannot create/modify sessn vars)

c. Directives

d. Built-in Objects

    Navign Methods
  1. Response.Redirect {=hyperlink} Response.Redirect("f.aspx");
  2. hyperlink: use NavigateURL, no serverside evts, if evts requd then use LinkButton/ImageButton [webb.195]
  3. Server.Transfer {end currt form, goto new form iff to aspx}; canstore src p info if preserveForm = true --> QueryString, ViewState & evt proc info avail to destinatn form.
  4. Server.Execute {goto new webform, still displayg currt webform iff aspx};
  5. Window.Open {new browser wdw in clt-side code, but appearnace canbe ctrlld from server};

II. Web Forms (System.Web.UI) Web Form = cross html page + Winform; define UI of web app., but unlike WinForms run on webserver.

a. Categories of Webforms

WebForms vs. WinForms

Feature WebForms WinForms
Tools cant use Win ctrls WinForms
UI browser-depdt -
Lifetime sent to browser + discarded exist aslong as requd
Executn exec pts reside on webserver -

web forms : - scalable server-side CLR prog model to dynamically generate web pages; for UI of web aps, uses RAD (rapid app. dev.); .aspx extension
    Categories:
  1. web server ctrls System.Web.UI.WebControls (asp.net-defined input ctrls, more abstract + flexible with more features than html server ctrls: <asp:... runat="server">)
  2. html ctrls System.Web.UI.HtmlControls (standd html visual elemts; html web server ctrls: <input type=Text|Password|Checkbox|Radio|Button|Submit |Reset|File(button uploadg file)|Hidden|Image > , validatn ctrls (Page.IsValid set after validn), user ctrls)
  3. user ctrls/pagelets: a webforms pg used as a server ctrl; custom, reusable ctrls created similar to web forms, cannot be requested independantly.
  4. data ctrls (db) System.Data
  5. sys. componts (server sys-level events)

Server Ctrls vs. HTML Ctrls

server ctrls = superset of html ctrls [webb.157]

feature server ctrl html ctrl
server evts cantrigger only page-level evts on server (postback)
state mgt maintained across requests not maintained, mustbe stored
adaptn auto-detect browser + display adaptn no auto-adaptn
props more than html html attribs
    11 Files Genertd by vs when new webforms project created (bold files only are shown in vs Solution Explorer) [webb.62]
  1. AssemblyInfo.cs: all attribs written to compiled assembly, incl. versn, co, guid.
  2. Global.asax: global evts occurg in web app, (eg. ...OnStart), only 1 Global.asax/oroject, residg in project root folder.
  3. Global.asax.cs: ocde used in Global.asax
  4. Web.config: webserver proj settgs
  5. Styles.css: style defs for generatd html (iff vb, not vc#)
  6. WebForm1.aspx: visual descriptn of webform
  7. WebForm1.aspx.cs: code-behind pg, evt handlers
  8. WebForm1.aspx.resx: xml resrcs used by the webform
  9. Myproject.vsdisco: descriptn of webservices provided by this proj; for dyn.discovery of webservices (.asmx)
  10. Myproject.csproj: project file listg diles + settgs used at tesign time
  11. Myproject.csproj.webinfo: file tracks root virtual folder for the web app.
    Events in webapp lifecycle : webform short life, webapp lives aslong as active sessions [webb.65,70, 69]
  1. Page_Init - first step in webform's lifecycle
  2. Page_Load - server ctrls loaded onto pg; viewstate info avail
  3. Page_PreRender - pg abt tobe rendered, before viewstate saved
  4. pg life:
  5. Page_Unload - unloaded from mem
  6. Page_Disposed - last evt. in life of pg; pg released from mem
    2 Layout Options for webforms:
  1. Grid layout (deflt): absolute positn;
  2. Flow layout: relative toother elemts; Design Wdw > webform > Properties > Document Obj > pageLayout

b. Server Controls

System.Web.UI.HtmlControls
HTML-specific controls; add id + runat="server" attribs to html ctrls --> vs.net handles html elemts as html ctrls
  1. HtmlAnchor : <a> <a ID="AnchorButton" OnServerClick="f" runat="server">
  2. HtmlButton : renders as an html 4.0 <button>: <button OnServerClick="f" runat=server> <I> a button </I></b></button>
  3. HtmlForm : to process postback requests
  4. HtmlGenericControl : all unknown html server ctrls not directly represented by this html server ctrl (eg. <span>, <div> <body> <p> etc.)
  5. HtmlImage
  6. HtmlInputButton <input type= button|reset|submit>
  7. HtmlInputCheckBox
  8. HtmlInputFile
  9. HtmlInputHidden
  10. HtmlInputImage
  11. HtmlInputRadioButton
  12. HtmlInputText (passwd)
  13. HtmlInputText (txt)
  14. HtmlSelect
  15. HtmlTable
    <%@ Page Language="C#" AutoEventWireup="True" %> <html> <head> ... 
    <table id="myTable" Border="1" BorderColor="black" runat="server"> ... 
    <script runat="server">
    myTable.BgColor = aselect.Value;
    myTable.Border = Convert.ToInt32(bselect.Value);
    myTable.BorderColor = cselect.Value; </script>
    
  16. HtmlTableCell
  17. HtmlTableRow
  18. HtmlTextArea
    System.Web.UI.WebControls (ASP.NET Web sever ctrls)
  19. { WebControl } (asp: prefix + runat="server") [prosise.238]
    I. Simple Ctrls
  20. HyperLink - 2 types: i) txt hyperlk: <asp:HyperLink Text="click" NavigateUrl= "http://www.x.com" runat="server" /> ; --> <a href> ii) img hyperlk: <asp:HyperLink id="xid" ImageUrl="f.jpg" NavigateUrl="http://www.xyz.com" Text="xyz.com" {tooltip} Target="_new" {open pg in new window} runat="server"/> --> <a href><img></a>
  21. Image : --> <img> ; not server side ctrl and does not expose Click evt; doesnt respond to user evts
    <asp:Image id="id_Image" runat="server" 
     AlternateText="txt"  {used by XP Narrator + accessibility sw}
     ImageUrl="f.jpg" 
     ImageAlign="NotSet|Left|Right|BaseLine|Top|Middle|
                        Bottom|AbsBottom|AbsMiddle|TextTop" /> ... 
    xImage.ImageAlign = ImageAlign.Right;
    
      Displayg Graphics :
    1. bg : Webform: Background whole p; or Panel: BackImageUrl for regnal imgs xImage.ImageUrl = "f.jpg";
    2. fg: Image
    3. button: use ImageButton for clickable img
    4. AdRotator
  22. Label (disply txt in set locatn): <asp:Label id="id_Label" Text="hello" runat="server"/> --> html prod'd: <span> hello </span>
    Label l = new Label();
    l.BorderStyle = BorderStyle.Solid;  l.Text = "This is a new Label"; 
    Page.Controls.Add(l);
    
  23. Panel (container for other cntrls) --> <div>
    <asp:Panel id="xPanel" runat="server" BackColor="gainsboro" 
    HorizontalAlign="Center" Height="200px" Width="300px"> ... 
    xPanel.Visible=false; xPanel.Controls.Add(b);
    xPanel.Visible = oCheckBox.Checked; 
    xPanel.Controls.Add(new LiteralControl("<br>"));
    
  24. RadioButton (mutually excl. lists; subclass of CheckBox)
    <asp:RadioButton id=rb1 Text="a" Checked="True" GroupName="xgroup" runat="server" />
    <asp:RadioButton id=rb2 Text="b" GroupName="xgroup" runat="server"/>
    ... if (rb1.Checked) ... 
    
  25. Table, TableRow, TableCell
    <asp:Table id="xTable" CellPadding=10 GridLines="Horizontal | Vertical | Both" 
      CellPadding="3" CellSpacing="3" BackImageUrl="f.jpg" 
      BackColor="green" {inherits from WebControl}
      BorderStyle="Dotted" BorderWidth="2" runat="server">
      <asp:TableRow>
        <asp:TableCell Text="(0,0)"> Row 0, Col 0 </asp:TableCell>
        <asp:TableCell> Row 0, Col 1 </asp:TableCell>
      </asp:TableRow>
    <asp:Table> ... 
    
    MyTable.Rows[0].Cells[0].Text = "cell 1"; 
    MyTable.Rows[1].Cells[1].Text = "cell 1"; ... 
    TableRow tr = new TableRow();  TableCell tc = new TableCell();
    oTableRow.Cells.Add(oTableCell);  // cells collectn
    oTable.Rows.Add(oTableRow);       // rows collectn
    
    TableItemStyle MyTableItemStyle = new TableItemStyle();
    MyTableItemStyle.HorizontalAlign = HorizontalAlign.Center;
    MyTableItemStyle.VerticalAlign = VerticalAlign.Middle;
    MyTableItemStyle.Width = Unit.Pixel(100);
    
  26. TextBox : <asp: TextBox ID="id_TextBox" runat="server" />
    <asp:TextBox ID="id_TextBox" Rows="2" {ignored unless TextMode=MultiLine}
      Columns="2" MaxLength="3" {max.no.chars} 
      ReadOnly="true" {unchangeable txt} Wrap="true" {multi-line?} Text="txt" 
      TextMode="SingleLine {deflt} | MultiLine | Password" 
      OnTextChanged="f" runat="server"/>
    ... int i = Convert.ToInt32(id_TextBox.Text);
        int i = int.Parse(args.Value); 
        id_TextBox.Text = "string";  // get/set data
      <script language="C#" runat="server"> 
      void f(Object o_sender, EventArgs e) { ... }  </script>
    
    II. Button Ctrls
  27. 1. Button (push button) - 2 types:
    1.cmd btn: 
    <asp:Button id="id_Button" Text="Sort" CommandName="xc" 
    CommandArgument="xcarg" OnCommand="f" runat="server"/> ...
     void f(Object o, CommandEventArgs e)
     { switch(e.Commandname)
       { case "xc": ... if((string)e.CommandArgument == "xcarg") ... break;
         case "mySubmit": ... break;
         default: ... break; }                     }
    2.submit btn: OnClick = serverside evt
    <asp:Button id="xid" Text="submit" OnClick="f" runat="server"/>
    
  28. 2. LinkButton - (hyperlink style button) <asp:LinkButton id="id_lb" Text="Click" Font-Name="Verdana" Font-Size="14pt" OnClick="f" runat="server"/>
  29. 3. ImageButton (shows img, responds to mouse clicks): <asp:ImageButton ImageUrl="f.jpg" runat="server" />
    <asp:ImageButton id="id_ImageButton" runat="server" AlternateText="atxt" 
        ImageAlign="left" ImageUrl="f.jpg" OnClick="f"/> 
    <asp:ImageButton id="bImageButton" runat="server" 
     AlternateText="btxt" ImageUrl="f.jpg" OnCommand="f" 
     CommandName="xcmd" CommandArgument="Ascending"/>/> ...
    void f(object o_sender, CommandEventArgs e)
     {  if (e.CommandName == "Sort") ... 
        if (e.CommandName == "Sort" && e.CommandArgument.ToString() == "Ascending") ... 
        Console.WriteLine("x: " + e.X.ToString() + "y: " + e.Y.ToString());  } ...
    void f(object o_sender, ImageClickEventArgs e) // just EventArgs for other 2 buttons
     { ... e.X ... e.Y ... } // coords
    
    III. List Ctrls
  30. ListControl : abstract baseclass forall data-bound list-type ctrls = (CheckBoxList | DataList | DropDownList | ListBox | RadioButtonList) cancontain ListItem | ComboBox [aspalliance.com]
  31. 1. CheckBoxList
    <asp:CheckBoxList id="myid" AutoPostBack="True" CellPadding="5" CellSpacing="5" 
     RepeatColumns=2  RepeatDirection="Vertical" RepeatLayout="True" TextAlign="Right" 
     OnSelectedIndexChanged="f" runat="server>>
     <asp:ListItem> Item 1 </asp:ListItem>
     <asp:ListItem> Item 2 </asp:ListItem>
    </asp:CheckBoxList>
    
  32. 2. DataList : show dataset data
    <asp:DataList id="xDataList" BorderColor="black" CellPadding="5" 
    CellSpacing="5" RepeatDirection="Vertical" RepeatLayout="Table" 
    RepeatColumns="3" {no.cols.} ShowBorder="True" runat="server">
       <HeaderStyle BackColor="#aaaadd"> </HeaderStyle>
       <AlternatingItemStyle BackColor="Gainsboro"></AlternatingItemStyle>
       <HeaderTemplate> List of items </HeaderTemplate>
       <ItemTemplate> 
           Description: <%# DataBinder.Eval(Container.DataItem, "StringValue") %>
           Price: <%# DataBinder.Eval(Container.DataItem, "CurrencyValue", "{0:c}") %>
           <asp:Image id="ProductImage" 
            ImageUrl='<%# DataBinder.Eval(Container.DataItem, "ImageValue") %>'
           runat="server"/>
       </ItemTemplate>
    </asp:DataList>
    ...
    xDataList.DataSource = CreateDataSource();
    xDataList.DataBind();
    
  33. 3. DropDownList (readonly txt in dropdown list fmt)
    <asp:DropDownList id="xDropDownList" AutoPostBack="True" 
      OnSelectedIndexChanged="f_sic" runat="server">
      <asp:ListItem Selected="True" Value="White"> White </asp:ListItem>
      <asp:ListItem Value="Silver"> Silver </asp:ListItem>
    </asp:DropDownList> ... void f_sic(Object sender, EventArgs e) { ... }
                            aDropDownList.Items.Add("txt");
    
  34. 4. ListBox (single data item in selectable list ctrl; single or multiple readonly item selection.)
    <asp:ListBox id="xListBox" Rows="6" Width="100px" runat="server"
     SelectionMode="Single|Multiple" onSelectedIndexChanged="f" AutoPostBack="true">
      <asp:ListItem Selected="True">Item 1 </asp:ListItem>
      <asp:ListItem>Item 2 </asp:ListItem>
      <asp:ListItem>Item 3 </asp:ListItem>
    </asp:ListBox> ... 
    xListBox.SelectionMode  = ListSelectionMode.Multiple; 
    xListBox.Items.Add(aTextBox.Text);
    ... xListBox.SelectedItem.Text; { rets ListItem | null }
    
  35. 5. RadioButtonList (single-selection radio button grp canbe dynamically generatd thro data bindg)
    <asp:RadioButtonList id=oRadioButtonList runat="server">
     <asp:ListItem>Item 1 </asp:ListItem> <asp:ListItem>Item 2 </asp:ListItem>
    </asp:RadioButtonList> ... 
    oRadioButtonList.RepeatDirection = RepeatDirection.Horizontal; 
    oRadioButtonList.RepeatLayout = RepeatLayout.Flow | Table;
    oRadioButtonList.SelectedIndex {which butt checked}
    ... foreach (ListItem xListItem in oRadioButtonList.Items)
        { if(oListItem.Selected) { ... oListItem.Text ... }
    
  36. - ListItem : (option item in selectable list ctrl
  37. - CheckBox : <asp:CheckBox id="xid" runat="server" AutoPostBack="True" Text="myText" TextAlign="Right" OnCheckedChanged="f"/> ... if(id_CheckBox.Checked) { id_CheckBox.Checked.ToString(); } {is selected?}
    IV. Data-bound Ctrls
  38. Repeater (data-bound list control allowg custom layout by repeatg a specifd template for each item; dsply rows ofother ctrls usg template for appearance)
    <asp:Repeater id=aRepeater runat="server">
     <HeaderTemplate><table><tr><td> col1 <td> col2 </td></tr></HeaderTemplate>
     <ItemTemplate>
       <tr><td> <%# DataBinder.Eval(Container.DataItem, "Name") %> </td>
           <td> <%# DataBinder.Eval(Container.DataItem, "Ticker") %> </td></tr>
     </ItemTemplate>
     <FooterTemplate> </table> </FooterTemplate>
    </asp:Repeater>
    
  39. DataGrid : show dataset as assortmt of rows called items (7 types: normal, alternatg, header, pager, footer, currtly seleced item, currtly edited item) usg template for apperance
     ... Page_Load(){
    MyDataAdapter.Fill(oDataSet); 
    oDataGrid.DataBind(); }
    
    <asp:DataGrid id="xDataGrid" BorderColor="black" BorderWidth="1" 
       CellPadding="3" AutoGenerateColumns="true" runat="server">
      <HeaderStyle BackColor="#00aaaa"></HeaderStyle>
      <FooterStyle BackColor="#00aaaa"></FooterStyle>
      <Columns>
        <asp:BoundColumn HeaderText="Item" DataField="StringValue"/>
        <asp:BoundColumn HeaderText="Number" DataField="IntegerValue">
           <ItemStyle BackColor="yellow"></ItemStyle>
      </Columns>
    </asp:DataGrid> ... 
    DataTable dt = new DataTable();
    dt.Columns.Add(new DataColumn("IntegerValue|StringValue|CurrencyValue", 
                   typeof(Int32|string|double)));
    DataRow dr;
    for(...) dr = dt.NewRow(); dr[0] = i; dt.Rows.Add(dr);
    DataView dv = new DataView(dt); ...
    xDataGrid.DataSource = CreateDataSource();
    xDataGrid.DataBind();
    
    V. Calendar Ctrls
  40. Calendar : single month of cal on web page
    <form runat="server">
    <asp:Calendar id="myCalendar" runat="server"  SelectionMode="DayWeekMonth"
     ShowGridLines="false" {deflt booleans shown}    ShowDayHeader="true" {d of w: mon, ...}     
     ShowNextPrevMonth="true" {goto next/prev m}     ShowTitle="true" {n of mon.}
     OnPreRender="f_pr" {fired 1x before entire cal sent to html strm}
     OnDayRender="f_dr" {fired as each d rendered}
     OnSelectionChanged="f_osc" {if selectd d/w/m changed}
     OnVisibleMonthChanged="f_vmc"/> {new m selectd}
    
      <TitleStyle BackColor="Blue" ForeColor="White" Font-Bold="True"></TitleStyle>
      <DayStyle ...>  {dts in shown m}             <DayHeaderStyle ...> {mon, tue...}
      <TodayDayStyle ...>                          <SelectedDayStyle ...>
      <OtherMonthDayStyle ...> {dts noton shown m} <WeekendDayStyle ...>
      <SelectorStyle ...> {wk+m dt seln col.}      <NextPrevStyle ..> {navign ctrls}
    </asp:Calendar>
    </form> ...
    myCalendar.SelectionMode = CalendarSelectionMode.DayWeekMonth;
    myCalendar.ShowNextPrevMonth = false; ...
    f_DayRender(Object o, DayRenderEventArgs e)
    { // addg dropdown list to calendar cell
      aDropDownList.Items.Add("vacation");
      aDropDownList.Items.Add("vacation");
      e.Cell.Controls.Add(aDropDownList);   }
    
  41. AdRotator
    <asp:AdRotator id="xid" runat="server" Target="_self" AdvertisementFile="xAdFile.xml"/>
    xAdFile.xml:
    <Advertisements>
      <Ad>  
        <ImageUrl> f.jpg </ImageUrl>
        <NavigateUrl> http://www.ebay.com </NavigateUrl>
        <AlternateText> ebay.com: alt attrib of img </AlternateText>
        <Keyword> auction </Keyword>
        <Impressions> 80 </Impressions> 
      </Ad>
    </Advertisements>
    
    VI. Validatn Ctrls
  42. 1. CompareValidator (cmp entries of 2 ctrls)
    <asp:CompareValidator id="myCompareValidator" ControlToValidate="textbox1" 
    ControlToCompare="textbox2" EnableClientScript="False" 
    Type="String|Integer|Double|Date|Currency" runat="server"/>
    ... myCompareValidator.Validate();
    
  43. 2. CustomValidator : (chk val of i/p ctrl usg clt-side/serverside/both devr-defd scripts) only validn ctrl allowg validn of 2 ranges (RangeValidator: 1 range; CompareValidator: chk against constant/prop of other ctrl)
    <asp:CustomValidator id="xid" ControlToValidate="xtextbox" Display="Static" 
    OnServerValidate="f_s"  {serverside validn}
    ClientValidationFunction="f.js | vb"  {clt-side validn}
    ErrorMessage="uneven nu." {detailed descriptn of error}
    Text="error" {brief error msg} runat="server"/>
    ... f(object o_src, ServerValidateEventArgs e) ... 
    
  44. 3. RangeValidator : (chk if value within a single range: v1 < val < v2)
    <asp:RangeValidator id="myRV" ControlToValidate="aTextBox" MinimumValue="1" 
     MaximumValue="10" EnableClientScript="false" Text="mustbe 1 to 10" 
     Type="Integer|Double|String|Date|Currency" runat="server"/> 
     ... if (Page.IsValid) ...
    
  45. 4. RegularExpressionValidator (chk if entry = spec fmt)
    <asp:RegularExpressionValidator id="myREV" ControlToValidate="aTextBox" 
    ValidationExpression="\d{5}" Display="Static" ErrorMessage="mustbe 5 digits" 
    EnableClientScript="False" runat="server"/>
    ... if (Page.IsValid) ...
    
  46. 5. RequiredFieldValidator (makes assoctd input ctrl a requd fld; chk if ctrl has data)
    <asp:RequiredFieldValidator id="id_RFV" ControlToValidate="aTextBox" 
    InitialValue="Deflt Value" Text="in" {shown in ctrl}
    Display="Static" ErrorMessage="error" runat="server"/> ... if (Page.IsValid) ... 
    
  47. 6. ValidationSummary (aggregate of all validn ctrls' ErrorMessage props, shown iff Page.IsValid = false)
    <asp:ValidationSummary id="aVS" DisplayMode="BulletList" runat="server" HeaderText="errors: " Font-Name="verdana" Font-Size="12"/>
  48. PlaceHolder (container to store dynamically added server ctrls at runtime)
    <asp:PlaceHolder id="id_PlaceHolder" runat="server"/> ... 
    id_PlaceHolder.Controls.Add(myButton);
    
  49. Literal - (render data in Text property directly to html data stream, easier than DataGrid) ?
  50. ToolboxData : attribute determing init. settgs of a custom ctrl when a tag is created; deflt tag created by vs when custom ctrl dragged from toolbox onto webform.
    namespace aNamespace {
     [ToolboxData("<{0}:MyCustomCtrl Text='txt' BackColor='White'
      ForeColor='Blue' WarnLevel='0' runat='server'>")] 
        public class MyCustomCtrl ... // deflt props of custom ctrl
    
    <@Register TagPrefix="MyTagPrefix" namespace="aNamespace" 
       assembly="MyAssembly" %> {uses MyAssembly.dll ass containg MyCustomCtrl}
    <MyTagPrefix:MyCustomCtrl id="MyCustomCtrl1" Text="txt" BackColor="Color.White"
       ForeColor="Blue" WarnLevel="0" OnMyEvent="f" runat="server" /> {madeby vs}
    
  51. XML (dsply XML doc without formattg or usg XSLT)
    <asp:Xml id="id_Xml" runat="server" /> ... 
    XmlDocument xdoc = new XmlDocument();         xdoc.Load(Server.MapPath("f.xml"));
    XslTransform xtrans = new XslTransform();     xtrans.Load(Server.MapPath("f.xsl"));
      aXml.Document = doc;                        aXml.Transform = trans;
    

c. Custom Controls

    3 Types of Custom Ctrls:
  1. Web user/User ctrls : combine existg server + html ctrls by usg vs.net Designer (not in-code); reside in content files which mustbe included in the project.
      Creatg (subclass of System.Web.UI.UserControl):
    1. Declarn: 2 ways - <%@ Register TagPrefix="MyTagPrefix" Tagname="MyTagName" Src="f.ascx">;
      --> <MyTagPrefix:MyTagName runat="server">
    2. <%@ Register TagPrefix="MyTagPrefix" Namespace="MyNamespace" Assembly="MyAssembly" %> (MyAssemtbly,dll contains class def MyClass)
      --> <MyTagPrefix:MyClass Property="3" id="uniqname" runat="server" /> ; to instantiate ctrl, runat mustbe server
      Creatg User Ctrls
    1. add webuser ctrl page (.ascx)
    2. Designer: draw visual i/f
    3. write code for ctrl props, fu's, evts.
    4. drag ctrl from Solution Explorer to webform.
    5. declare ctrl at module level; vs: Project > Add Web User Ctrl
  2. Composite-Custom / Web Custom Ctrls : new ctrls derivg from/combinatn of existg server + html ctrl; compiled server componts havg UI; created in-code not visually like user ctrls, hence canbe compiled to dlls (which canbe shared between apps + used in vs toolbox); full support for vs design features: Toolbox, Props wdw, visual designer.
  3. Rendered custom ctrls : entirely new ctrls by renderg html directly, compiled and canbe used from toolbox.
    public class RenderedCustomCtrl : WebControl
    {  // 1. render 
       protected override void Render(HtmlTextWriter htw)
       {  htw.Write("<h3> Rendered </h3>"); 
          htw.WriteBeginTag("INPUT"): 
          htw.WriteAttribute("type", "button"); 
          htw.WriteAttribute("onclick","javascript:alert('!')"); 
          htw.WriteEndTag("INPUT"); 
          ... // 2. or create html attribs in any sequence
          htw.RenderBeginTag("INPUT"); // insert <INPUT
          htw.RenderEndTag();          // insert > 
       }
    }
    

III. ADO.NET (System.Data)

a. ado.net layers

RDO (Remote Data Objects): ms api usg ms lower-layer DAO (Data Access Objs) for relational db (not non-relational) access; llimited use as as objs couldnt be marshalled across net. evolved into ADO (ActiveX Data Objects). [searchDatabase.com]

ADO (ActiveX Data Objects): OO ms api for db access to relational and non-relational db. improved support for disconnected db; a disconnected recordset can marshall over n/w. pt of Universal Data Access strategy: provide universal access to various kds of db rather than buildg universal db. (oracle)

ADO.net (not ActiveX Data Objects): "the data access model for .NET-based applications" [mackman 2003]; a disconnected and distributed data access technology based on XML, largely indepdt of data src.

    ADO.net core classes / data access layers [webb.226] & sequence:
  1. Physical Data Store : sql, ole, oracle db or xml file
  2. Data provider/ Managed provider: creates in-memory representatn of data; encapsulates data and provides access to it in a generic, db-independt + distributed manner; = Connection obj + Command objs; represts set of data cmds + a db conn used to fill DataSet + update the data src.
    • Connection: est a conn to a specific data src.
    • Command: exec cmd agst a data src.
  3. DataAdapter: a db-independt obj actg as bridge (readg+writg data) betwn DataSet (ie. populatg DataSets) and data source (resolvg updates with db); Data Adapter Configuration Wizard canbe used; new entity phys combing sql cmd + connectn string
  4. DataSet: an in-memory/mem-resident relational representn of the data (tbls + relatnship) with xml support independt of data src,; filled by oDataAdapter.Fill(oDataSet)
  5. Data View : presentn of tbl in data set to user
  _____               _____________
 /      \---------> ( Data Provider )
|\______/|          (  Connection   )
|        |            --------------
|  Data  |                  |
|  Store |                  |                
|        | da.Update()  ------------ da.Fill(ds)--------                     /
|        |<---------- ( DataAdapter ) -------->|DataSet|--------> Data View -<
|        |             ( _________ )           |       |                      \
 \______/                                      --------
    Other classes
  • Transaction : a grp of cmds that must either succd or fail as a unit,
  • DataReader: Reads a forward-only, read-only stream of data from a data src.
  • data consumer app usg services of a data provider for storg, retrievg, + manipulatg data.

Additional classes:

Object Description
CommandBuilder A helper object that will automatically generate command properties of a DataAdapter or will derive parameter information from a stored procedure and populate the Parameters collection of a Command object.
Parameter Defines input, output, and return value parameters for commands and stored procedures.
Exception Returned when an error is encountered at the data source. For an error encountered at the client, .NET Framework data providers throw a .NET Framework exception.
Error Exposes the information from a warning or error returned by a data source.
ClientPermission Provided for .NET Framework data provider code access security attributes.

b. System.Data

c. T-SQL

d. Transactions

Transactn: grp of cmds treated as a single unit, all-or-nothg fashion: if 1 cmd failed, all fail + data removed.

    ado.net Transaction Types
  1. DataSet Transactions : usg RejectChanges() & Update() & AcceptChanges (reset state of records to Unchanged) [webb.273]
    DataSets have implicit transactn processg as changes not made to db until MyDataAdapter.Update()
    MyDataSet.RejectChanges();  // restore DataSet to original state
    MyDataGrid.DataBind(); ...  // refresh the datagrid
    int i = MyAdapter.Update(MyDataSet); // update db from dataset
    Session["MyDataSet"] = MyDataSet;    // save changes to state var
    MyDataGrid.DataBind();               // refresh data grid
    
  2. Database Transactns: use Transaction obj, System.Data.IDbTransaction (represts transactn ) (implemented by 4 types: OdbcTransaction | OleDbTransaction | OracleTransaction | SqlTransaction)
    SqlTransaction MyTrans = MyConnection.BeginTransaaction();
    SqlCommand MyCommand = new SqlCommand();
    MyCommand.Transaction = MyTrans;      MyCommand.CommandText = "...";
    MyCommand.ExecuteNonQuery();          MyTrans.Commit();
    MyConnection.Close(); 
    
    • providg Rollback(), Commit(), Save() {restore db + cancel pendg cmds, commit changes, create savepts within transactn for rollback of part of transactn}
    • Sql db can have save points (allow db restoratn to specific positn within a transactn), Ole db cannot have save points.
    • Setting Save Points:
      MyTransaction.Save("save point name"); (set save pts);
      MyTransaction.Rollback("save pt name"); (restore to save pt of given name)
    • no Terminate() or Close() in SqlTransaction
    • stop executg cmds when error occurs, rollback transactn and release connectn resrcs quickly:
      try{ MyTransactn.Commit();  }
      catch(Exception e) { MyTransactn.Rollback(); } // cancel pendg cmds
      finally { MyConnection.Close(); }
      
    Sql|OracleTransaction MyTransaction = 
      MyConnection.BeginTransaction(IsolationLevel.ReadCommitted);
    SqlCommand MyCommand = new SqlCommand("DELETE ...", MyConnection, MyTransaction);
    try{ int i_rows = MyCommand.ExecuteNonQuery();
         MyTransaction.Commit();  } // commit the transactn 
    catch{ MyTransaction.Rollback(); }
    
    • IsolationLevel prop: MyConnection.BeginTransaction(ReadUncommitted | ReadCommitted (deflt) | Chaos | RepeatableRead | Serializable); (dont lock records being read, aka "dirty read" as data inconsistent | locks records being read, not affect other records, frees lock as soon as records read | like ReadUncommitted, but more restrictive isolatn levels not overwritten | locks records being read till transactn complete | locks entire dataset being read till transactn complete)
    • MyOleDbCommand.Transaction = MyOleDbTransaction;
    • hint: draw db tbls for q's re. tbls
  3. Enterprise Transactns (System.EnterpriseServices) : System.EnterpriseServices.ContextUtil provides enterprise transactns; use ms sql server 2000's MS DTC (Microsoft Distributed Transaction Coordinator) to track transactns across multiple webforms across multiple COM+ componts.
      MS DTC:
    1. <%@ Page .... TransAction="RequiresNew" >
    2. use ContextUtil.SetAbort() | SetComplete() to change transactn status
    3. use Page.CommitTransaction() | AbortTransaction()

IV. Security

a. Authenticn & Authorizn (System.Web.Security)

  • Authenticatn: process of identifyg users.
  • Authorizatn: process of grantg users access.
  • Impersonatn: prcess of assigng a user a/c to an unknown user.
    Types of security: [webb.419]
  1. Windows Authenticn / Windows integrated security: for Windows network, IIS, verify if users are members of \\adomain\agroup; uses credentils estbd when a user logs on to a win network. FileAuthorizationModule verifies if user has perm to read file. (intranet webapps, private corp webapps); deflt for webapp.
  2. Forms authentication: logon webform (user + passwd prompt) (commercial webapps) [webb.433] ( - less secure)
  3. Passport authenticn: ms user + passwd for multiple sites. (multiple commercial webapps): install passport sdk;
    protected void PassportAuthentication_OnAuthenticate(Object o_sender,
                   PassportAuthenticationEventArgs ea)
    { if (ea.Identity.IsAuthenticated) ... 
          ea.Identity["FirstName" | "LastName" | "City" | "PreferredEmail" ]; 
    }
    
  4. Basic + Digest: prompt user for user+passwd; iis authent methods.
  5. Anonymous: for public web sites; no identity needed. deflt anon user a/c = IUSER_myhost (public internet webapps)
  6. Certificate authent: uses certif (server cert) from 3rd-party src. (cert authority, eg. VeriSign)

b. Session Mgt, State Mgt & Client-Side Scriptg

    Methods for Retaing vars betwn Requests in asp+ [webb.132]:
  1. Context.Handler: if Transfer() or Execute() --> retrieve readonly props of previous webform; Server.Transfer("f.aspx"); ... MyPage aPage = (MyPage) Context.Hanlder; ... aPage.Value;
  2. Query strings: html: <a href="f.aspx?akey=avalue"> c#: set/get query strings: Response.Redirect(Request.FillPath & "?akey=avalue"); ... string s = Request.QueryString["akey"];
  3. Cookies: store info on client machine. [webb.342]
     
    if(Request.Browser.Cookies)  // chk if cookies enabled on clt
     { HttpCookie aHttpCookie = new HttpCookie("cName"); 
          // or = HttpCookie("cName", DateTime.Now.ToString()); 
          // or = Request.Cookies["cName"]; to get cookies
       aHttpCookie["aKey"] = "a key";  // use a key within cookie
       aHttpCookie["bKey"] = "b key";
        aHttpCookie.Value = "English"; 
        aHttpCookie.Expires = DateTime.Now.AddDays(1); // expires tomorrow
       Response.Cookies.Add(aHttpCookie); ...
       Session["Lang"] = Request.Cookies["cName"].Value; 
      }
    
  4. View state: save data in hidden field; hidden data is hashed:
    foreach (StateItem Item in ViewState.Values)
    { ... aTableCell.Text = Item.Value.ToString(); ... }
    
      Features of Hidden Fields
    1. + no server resrc requd.
    2. + increased support as no cookies on browser requd.
    3. - security
  5. Session State: Session = unique instance of webbrowser, canbe multiple instances of browser forsame user; Session["aClass"] = aClass; ... aClass = (aClass)Session["aClass"];
      Session state canbe stored in 3 modes: Web.config: <sessionState mode="Inproc|StateServer|SQLServer|Off or" /> (for whole app) or, Web Form Properties > EnableSessionState = False (for 1 page)
    1. In-process: locally, in-proc with asp.net worker process; each app hosted on single processor, fast.
    2. Out-of-Process State server <sessionState mode="StateServer" />: cannot retain state info durg server restart. out-of-proc: an exec prog running in a separate addr space from that the prog uses; perf. best. as in-memory
    3. SQL Server: if state data tobe secure + capable of being restored after webserver restart; most reliable; speed/perf < stateserver; stateserver | sqlserver useful if multiple processors/data canNOT be lost on server/proc restart.
  6. Application State:
    Application["aName"] = "aString";
    Response.Write(Application["aName"]);
      Types of state vars:
    1. Application state vars: avail. r+w to all users of an app, multi-user global data; app vars mustbe initd in vc# else "value null was found" error Application["MyCount"] = 1;
    2. Session state vars: avail only to a single sessn (user), the current session; = global data in win apps; Session["Clicks"] = 1;

c. Unmanaged Code

using System.Runtime.InteropServices // 1. use namespace [webb.355]
                                     // 2. identify unmanaged proc tocall
[DllImport("KERNEL32.DLL", EntryPoint="GetSystemInfo", SetLastError=true,
 CharSet=CharSet.Unicode, ExactSpelling=true, 
 CallingConvention=CalllingConvention.StdCall)]
public static extern void f(ref XSTRUCT xstruct); 
   // 3. def types for unmgd proc params usg sequential (deflt) layout
[StructLayout(LayoutKind.Sequential)] public struct XSTRUCT
{ ...  public Int32 MyDataType ; ...  }
// [StructLayout(LayoutKind.Explicit)] public struct XSTRUCT 
// { ... [FieldOffset(0)]public Int32 MyDataType ; .. }  explicit struct layout
                                     // 4. call unmgd proc
private void Page_Load(object o_sender, System.EventArgs ea)
{ XSTRUCT MyXStruct; 
  f(ref MyXStruct); ... MyXStruct.MyDaataType; }

d. COM, COM+

e. Client-Side Scripting

    Debugg clt-side scriptg [testking]
  1. enable script debugg: IE > Tools > IN Optns > Adv > Browsg > x Disable Script Debugg
  2. vs: Tools > Debug Processes > attach to IExplore.exe (IE) + brk into script
  3. vs: set brkpt/add "Stop" to vbs/js where interative debugg starts
  4. ie: run vbs/js

V. Testing

Automated tests; reproducible, measurable (success/fail)

a. Types of Test

    Types of Test [webb.527] usu in order:
  1. Unit Test: indept piece/individ componts of code;
  2. Integration Test: all units work together, done after unit testg
  3. Regression Test: newly added features notaffect other parts; testg debugged code
  4. Load/Stress Test: hi usage;
  5. Platform Test: works on all hw+sw platforms

b. Errors & Debugging: Debug & Trace

    Types of Breakpoints (4): vs: Breakpoint Properties > i(conditn)
  1. functn brk pts: brk at functn
  2. file brk pts: brk when spec locatn in specific file reached.
  3. addr. brk pts: brk at memy addr
  4. data brk pts: if var value changes (notexist for vb,c#)

c. Exception Handlg

Exception = unusual occurrence, = error; dealg with exceptns = exceptn handlg; unhandled exceptns = errors not dealt with in code

    Exception Handlg: 3 ways in webapps:
  1. SEH = Structured Exceptn Handlg.
  2. Error Evts
    private void Page_Error(object o_sender, System.EventArgs ea)
    {
      Exception e = Server.GetLastError();  // obtain last exceptn
      Session["Error"] = e.Message;         // store the msg
      Server.ClearError();    // handle exceptn st it doesnt trigger error
                              // evts/appear to user
    }
    
  3. Custom Error Pages
      2 levels
    1. <%@ Page ErrorPage="f.aspx">- spec. webform
    2. Web.config: customErrors - whole app
      <customErrors mode="RemoteOnly (deflt)| On" defaultRedirect="f.aspx">
      {cust errs only to remote clts not on localhost, detailed asp.net
      errors on webserver | show cust err pgs on localhost}
        <error statusCode="401" redirect="f1.aspx">
        <error statusCode="404" redirect="f2.htm">
      </customErrors>
      
    3. Machine.config: <customErrors mode="On"> --> 1 error msg forall webapps on webserver

c. Help

d. Windows Installer


VI. XML & XSLT


VII. Globalization (System.Globalization)

Globalizatn = proc of designg + developg applicn supportg localized UI and regnal data for users in multiple cultures

Localizatn = process of accomodatg cultural differences in an app (currency, calendar, writg dirn, ...)

    Globalization approaches (3)
  1. Detect & Redirect:
    1. CultureInfo ci = new CultureInfo(Request.UserLanguages[0]); (Request.UserLanguages[] = strg arr of user's preferred langs; 0 = user's currt lang)
    2. Web.config: <globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="ar-SA" {Saudi}/>
  2. Run-Time Culture adjustmt: Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
  3. Satellite Assemblies: only culture-depdt pts of webapp compiled into assembly file (.dll) containg localized resrcs for an app for 1 culture
    Thread.CurrentThread.CurrentCulture = 
      CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]);
    Thread.CurrentThread.CurrentUICulture = 
      new CultureInfo(Request.UserLanguages[0]); // which sat.assembly toload
    protected ResourceManager rm =   // create assemblies
      new ResourceManager("rootns.resrcbase",typeof(Satellite).Assembly);
    
    where 2nd arg = currt executable assembly.

VIII. Web Server

a. IIS

    Server Ctrl Events: 3 types [webb.72]:
  1. Postback Evts: web page tobe sent back to server for immed.processg, begins request from browser causg server to process page evts; incr. response time as round-trip to server triggered; caused by Button, LinkButton, ImageButton.
  2. Cached Evts: saved in page's view state tobe processed when postback evt occurs; TextBox, DropDownList, ListBox, RadioButton, CheckBox provide cached evts, canbe overridden by AutoPostBack = true;
  3. Validn Evts: handled by page w/o postback/cachg, usedby validn ctrls; validn ctrls eval'd before page postedback to server
    Order of server ctrl evts: [webb.72,173]
  1. validatn ctrls evald before pg postedback to server
  2. Page_Init, Page_Load after postback
  3. Cached evts
  4. Post-back evt
  5. Page_Unload
  6. Page load, Text changed, Item selected, Button clicked, Page PreRender

b. Performance & Optimization: Caching

c. Building & Deployment: Windows Installer, Xcopy Deployg: installg the app on webserver


IX. XML Web Services (System.Web.Services)

xml web services : - a compont containg business functnality exposed through internet protocols, enablg apps to exchange info usg http and xml through firewall

References