.NET Notes
ASP.net
Version 0.14 by Samar 23/10/2003
- asp+ (asp+ vs. asp;directives, objects)
- Web Forms (Types, Server Ctrls: System.Web.UI.HtmlControls,
System.Web.UI.WebControls, User Ctrls, Custom Ctrls)
- ADO.net (ado.net Layers + Items,
System.Data, T-SQL, Transactions)
- Security (State Mgt: App, Sessn; Authenticn &
Authorizn: anon, etc, User Info, Cookies, Clt-Side Scriptg,
Passport; Unmanaged Code; COM, COM+)
- Testing (Types of Test, Debugging & Errors:
Debug & Trace, Exception Handlg, Help)
- Xml & Xslt
- Globalization
- Web Server (IIS,
Performance & Optimization: Cache + Caching,
Buildg & Deploymt: Windows Installer, Xcopy)
- 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
|
WinForms
|
Framework Classes
|
Common Language Runtime
|
Old ASP props:
- Changg deflt scriptg lang vbs (old asp)
Registry key: DefaultScriptLanguge
HKEY_LOCAL_MACHINE\SYSTEM\CurrentConsoleSet\Services\W3Svc\ASP\Parameters
- Old ASP obj model: 6 built-in objs: Session, Application, Request (5
collectns, 1 prop, 1 f: Form, QueryString, Cookies, ServerVariables,
ClientCertificate; TotalBytes; BinaryRead() ), Response (1 collectn, 9
props, 8 fus: Cookies; ...), Server (1 prop, 4 fus), ObjectContext.
-
Start > Progs > Win NT 4.0 Optn Pack > MS IIS > Internet
Service Mgr
- asp_wp.exe: worker proc
- vs.net can use old asp pgs as is.
Componts of .net framework:
- 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.
- managed code: targets runtime, run under CLR, eg. asp.net;
unmanaged code: not target runtime, eg. IE, COM
- .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
Componts of asp.net
- System.Web
- server + html ctrls: ui componts
- vs.net web dev tools
Types of Applications:
- 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
- Web services (System.Web.Services): provide server
processg services to other apps; XML Web Services
- Internet-enabled apps (System.Net): standalone apps
incorporatg web info to provide user services (help, updates, etc.);
Winforms
- 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 :
- 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]
- xspisapi.dll filter intercepts request, passes it to
xspwp.exe XSP worker process.
- xspwp hands request to correct HTTPModule
(isapi filter replacemts, classes takg pt
in every request)
& HTTPHandler (end pt of web request processg, = isapi extensns)
- aspx pg read from hd/cache & exec
- JavaScript required by asp.net to call serverside code;
JavaScript disabled -->
asp.net cannot call serverside code
- Document.EnableSessionState = true | false | ReadOnly
- (pg maintns session state | not | pg cannot create/modify sessn vars)
c.
Directives
- @Page: page-specific props; attribs:
<%@ Page Language="VB (deflt)|C#"
- Codebehind="f.aspx.cs" Inherits="oNamespace.oPgClass"
{code-behd file}
- SmartNavigation = true {IE5+: keep elemt focus betwn
navigns + kp scroll posns +
reduces flicker + kp only last pg state in history st. only 1x BACK}
- ClassName ="f" {auto-compiled when pg requested}
- AutoEventWireup = true | false {auto assoc web pg evts with
serverside methods (vs.net creates code binding web pg evts to server methods, but
same code canbe exec 2x) | manually assoc evt handler fu's with evt (safer when usg
vs) ; event wirg: consumg evt: evt handler responds to evt + registers evt
handler with evt src.}
- ASPCompat {old asp compatibility mode: force pg
execn in single-threaded apartmt STA mode --> canuse COM componts, but
perf penalty}
- EnableViewState = true (deflt) | False {enable state mgt (server ctrl persists its +
child ctrls state to clt after
endofrequest) --> extra t requd to send state info round-trip betwn
browser + webserver | disable: no state kept across requests : perf
improvemt; has no effect on TextBox as Value property used to persist}
-
EnableViewStateMac = "true | false" > {chk clt not hacked
data usg encrypted/hashed
view state (containd in hidden vars on pg}
- Data Bindg:
linkg app data (eg. datasets) to
ctrl properties;
Page.DataBind(); bind data to page ctrls;
vs: ctrl > Properties > DataBindings : DataSource ;
usefor DataGrid, DataList & Repeater (all 3 use templates also)
- Page.IsPostBack = false | true
(is page being loaded 1st x? | page loaded dueto client postback)
- Trace property
- @Import: import namespaces
- <%@Import Namepsace="System.Web" %>
- @Assembly: call assemblies from GAC (hence not necessary to cp
to \Bin dir) w/o affectg other pages in app
- GAC = special subfolder in Windows folder storg shared .net
componts; assemblies mustbe cfg'd touse strong names before
installatn in GAC;
ShFusion.dll started when folder opened.
- or in Web.config: <assemblies> <add> ...
easier than addg @Assembly at the top of each page.
- @Control: used in user ctrl file to set
ctrl-specific attribs, eg. Debug, Language
-
Machine.config <location allowOverride="false">
--> prevent changes to cfg settgs of app
-
Web.config: <location: ... allowOverride="false">
--> subdirs cfg not overridable but Web.config canbe changed!
d.
Built-in Objects
System.Web
- Application: top-level obj for web apps;
subclass of HttpApplication
[webb.125]
- Context
- Modules
- Request;
eg. if(Request.Browser.MajorVersion < 4)
- Response: write to response
- Server
- Session
- Modules: access http modules
- User: authenticn info
- Page
- Application
- Cache
- Controls
- Request
- Response
- Server
- Session
- Trace: turn tracg on/off, write to trace log
- Request
{mem: "BCC-FI: bld carbon cp for india"}
- Browser
- ClientCertificates: authenticate clt
- Cookies :
Session["User"] = Request.Cookies["aname"].Value;
- Files: get files uploaded by clt
- InputStream: r | w raw data to request
- Response
- Cache:
Response.Cookies.Add(aHttpCookie);
- Cookies
- Output
- HttpResponse.BufferOutput = true | false (buffer o/p or
not)
- HttpResonse.SuppressContent = true | false
(send http to clt or not)
- HttpResponse.Clear() | ClearContent()
(clear all contt o/p from buffer stream)
- Response.Flush() (send all buffered o/p to clt)
Navign Methods
- Response.Redirect {=hyperlink}
Response.Redirect("f.aspx");
- hyperlink: use NavigateURL, no serverside
evts, if evts requd then use LinkButton/ImageButton
[webb.195]
- 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.
- disable deflt ViewState hashing: <%@ Page ...
EnableViewStateMac="false" ... > Server.Transfer("f.aspx",
true); ... Request.Form["xTextBox"]; (get info)
- onlyfor webforms, runtime error if goto html
- Server.Execute {goto new webform, still displayg currt
webform iff aspx};
-
Server.Execute("f.aspx"); - results written to currt p;
toshow results in other p:
Server.Execute("f.aspx", new StringWriter());
- both p shown, can respond to usr evts
- postback evts occurrg on webform2 will clear webform1
--> mainly usedfor non-postback
- Window.Open {new browser wdw in clt-side code, but
appearnace canbe ctrlld from server};
- <input ... onclick="window.open('f.aspx' |
'<%# datatag %>' )" ...
- c# target url vars mustbe public
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:
- 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">)
- 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)
- user ctrls/pagelets: a webforms pg used as a server ctrl;
custom, reusable ctrls created similar to web forms, cannot be requested
independantly.
- db query in web user ctrl + cached using @ OutputCache
--> speed incr. as web pg displays while db query performed
- data ctrls (db) System.Data
- 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]
- AssemblyInfo.cs: all attribs written to compiled assembly,
incl. versn, co, guid.
- Global.asax:
global evts occurg in web app, (eg. ...OnStart),
only 1 Global.asax/oroject, residg in project root folder.
- Global.asax.cs: ocde used in Global.asax
- Web.config:
webserver proj settgs
- Styles.css: style defs for generatd html
(iff vb, not vc#)
- WebForm1.aspx: visual descriptn of webform
- WebForm1.aspx.cs: code-behind pg, evt handlers
- WebForm1.aspx.resx: xml resrcs used by the webform
- Myproject.vsdisco: descriptn of webservices provided
by this proj;
for dyn.discovery of webservices (.asmx)
- Myproject.csproj: project file listg diles + settgs used at tesign
time
- 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]
- Page_Init - first step in webform's lifecycle
- Page_Load - server ctrls loaded onto pg; viewstate info
avail
- Page_PreRender - pg abt tobe rendered, before viewstate
saved
- pg life:
- Page_Error - unhandled exceptn
- Page_AbortTransaction
- Page_CommitTransaction - transactn accepted
- Page_DataBinding - server ctrl binds to data src
- Page_Unload - unloaded from mem
- Page_Disposed - last evt. in life of pg; pg released from
mem
Other evts:
- Application_Start -
when 1st user starts app; Session, Response not usable as notyet
created
- Application_BeginRequest - 1st evt in http pipeline chian
when asp.net responds to requests
- Session_Start or OnStart?
- Session_End
- Application_EndRequest
- Application_End - cannot be known when it occurs
as garbage collectn
- Global.asax: HttpApplication.Application_Error()
or Application_EventName()
2 Layout Options for webforms:
- Grid layout (deflt): absolute positn;
- Flow layout: relative toother elemts;
Design Wdw > webform > Properties > Document Obj >
pageLayout
b.
Server Controls
- Server ctrls declard usg custom tags of
intrinsic HTML tags
(System.Web.UI.HtmlControls)
containg runat="server" attribute.
- evt handlers assigned when ctrl is inserted into webform.
- asp.net has 45 in-built server contrls
- Any tag not matchg one
asp.net html server ctrl is assignd type
System.Web.UI.HtmlControls.HtmlGenericControl
- asp.net uses hyphenated syntax, eg.
Property-Subproperty to access
subprops: <asp:... Messages-Error404Message ... / >
NOT Messages.Error404Message,
<asp: ... Font-Size .../> ... Font.Size.
- more than 1 <form> ctrl on a webforms page
not allowed; deflt. method=POST & action= src pg url
- if id attrib of server ctrl not set,
it cannot be programmed
- <forms loginUrl="/default.aspx"> (deflt)
System.Web.UI.HtmlControls
HTML-specific controls;
add id + runat="server" attribs to html ctrls -->
vs.net handles html elemts as html ctrls
- HtmlAnchor : <a>
<a ID="AnchorButton" OnServerClick="f" runat="server">
- HtmlButton : renders as an html 4.0
<button>:
<button OnServerClick="f" runat=server>
<I> a button </I></b></button>
- <input
type="button" runat="server" value="b" onclick="f_client();"
onserverclick="f_server" />: exec clt-side routine
f_client before executg server-side method f_server.
- html ctrls must place semicolon at end of clt-side method name;
serverside code > clt code if conflict.
- impossible for server to make popup window appear to client
- HtmlForm : to process
postback requests
- 1 web forms page can only have one server side <form> tag
- HtmlGenericControl :
all unknown html server ctrls not directly represented
by this html server ctrl (eg. <span>,
<div> <body> <p> etc.)
- InnerHtml prop usedto write txt
- HtmlImage
- HtmlInputButton
<input type= button|reset|submit>
- HtmlInputCheckBox
- HtmlInputFile
- HtmlInputHidden
- HtmlInputImage
- HtmlInputRadioButton
- HtmlInputText (passwd)
- HtmlInputText (txt)
- HtmlSelect
- 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>
- HtmlTableCell
- HtmlTableRow
- HtmlTextArea
System.Web.UI.WebControls
(ASP.NET Web sever ctrls)
- { WebControl }
(asp: prefix + runat="server") [prosise.238]
- all web ctrls subclasses of abstract
System.Web.UI.WebControls.WebControl
- AutoPostBack = false (deflt) | true --> do not
post to webserver auto when ctrl altered + fire Changed (eg.
SelectedIndexChanged) evt iff another ctrl forces
postback (ie. cache Changed evt in pg's viewstate until another
ctrl fires postback evt) | fire Changed evt (eg.
TextChanged occurrg if TextBox txt changed, when focus lost, not
after every char change) which is handled by clt browser ( -->
JavaScript requd!) + force postback to server
- System.Web.UI.Control: base class forall asp.net server
ctrls.
-
BorderStyle=NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|Inset|Outset
- BackColor|ForeColor|BorderColor = Color.Empty|Color
- Width|BorderWidth = i|i px|Unit.Empty(unset);
BorderWidth only works for table ctrls
- ControlStyle: encapsulates all appearance properties
(eg. Font etc.)
- CssClass = String.Empty|"myClass" get/set css of webctrl;
rendered to clt
as class:
<style> .myStyle{...} </style> ...
<script language="C#" runat="server"> myaspid.CssClass = myStyle; </script>
- Enabled|Visible = true|false
- Font
<form><asp:Label id="xLabel" Font-Name="Verdana" Font-Names="Verdana, Courier"
Font-Size="10pt" Font-Bold="true" Font-Italic="true" Font-Underline="true"
Font-Strikeout="false" Text="myText" runat="server/> </form> ...
myLabel.Font.Underline = false;
myLabel.Font.Bold= false;
- Parent:
Control c = myControl.Parent;
- MergeStyle(): cp's nonblank elemts of spec style to
webctrl,
but not overwrite existg style elemts of the ctrl.
- ApplyStyle(): cp's nonblank style elemts, overwritg
existg style elemts
- more abstract than html server ctrls
I. Simple Ctrls
- 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>
- 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 :
- bg : Webform: Background whole p;
or Panel: BackImageUrl for regnal imgs
xImage.ImageUrl = "f.jpg";
- fg: Image
- button: use ImageButton for clickable img
- AdRotator
- 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);
- Literal + PlaceHolder controls also display web txt
but dont render any additnal tags.
- 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>"));
- direct drawg to webform Panel notpossible --> draw on webform
first,
then drag to panel
- webforms panel uses flowlayout --> no exact positng
- 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) ...
- GroupName mustbe same for set of rb
- 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);
- MyTableCell.Attributes.Add ("Name", "Value");
-
TableCell tc = (TableCell) MyDGItemEvent.Item.Controls[0]; // 1st
col
tc.Attributes.Add("style","background-color:red");
- 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>
- TextChanged fired only iff (another ctrl causes
postback or AutoPostBack = true)
- html produced: <asp:TextBox TextMode="SingleLine | Password |
MultiLine" runat="..." ... /> --> <input type="text |
password" id="..." /> & <textarea id="id_textbox"
name="id_textbox" rows="10">
- html produced for autopostback textbox: <asp:TextBox
ID="id_TextBox" AutoPostBack="true" runat="server" />
-->
<input name="id_TextBox" type="text" id="id_TextBox"
onchange="__doPostBack('UserName','')" language="javascript" />
[prosise.236]
II. Button Ctrls
- 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"/>
- all 3 buttons fire
Click + Command evts
- enablg clt-side evts:
f.aspx: Page_Load: id_Button.Attribute.Add("onClick","f_clt()");
- if usg Command evts --> +
pass more info via CommandName & CommandArgument
- 2. LinkButton - (hyperlink style button)
<asp:LinkButton id="id_lb" Text="Click" Font-Name="Verdana"
Font-Size="14pt" OnClick="f" runat="server"/>
- LinkButton ctrl has same appearance as HyperLink ctrl,
but same functionality as Button ctrl.
- 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
- Click & Command evts both fired when clicked
--> OnClick, OnCommand event handlers used.
- OnMouseOver: clnt side event, notexist in ImageButton
III. List Ctrls
- ListControl : abstract baseclass forall
data-bound list-type ctrls = (CheckBoxList | DataList | DropDownList |
ListBox | RadioButtonList) cancontain ListItem | ComboBox
[aspalliance.com]
- SelectedIndexChanged - user changes list selectn,
1st selected item = SelectedItem
- DataBinding - when ctrl binds to data src.
- no Clicked evt defd forany list ctrl
- AccessKey: finds navign access key.
- oListControl.RepeatDirection =
RepeatDirection.Vertical | Horizontal; :
- oListControl.RepeatLayout = RepeatLayout.Flow |
Table; (forall list ctrls)
- show db:
oListControl.DataSource = oDataSet;
- CheckBoxList, RadioButtonList donot contain CheckBox or
RadioButtons but ListControls
- 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>
- use Collectn Editor (vs) toadd items to
CheckBoxList | RadioButtonList.
- 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();
- uses 3 categories of templates:
Header & Footer templates, Items templates (row contents),
Separator templates (rule lines, etc.).
- displys template-defd data bound list,
allows selectg + editg.
- templates supported:
AlternatingItemTemplate | EditItemTemplate | FooterTemplate |
HeaderTemplate | ItemTemplate | SelectedItemTemplate | SeparatorTemplate
- minimum ItemTemplate to be defined
- when DataList ctrl with data bindg created --> vs makes
DataBinder.Eval(Container, "DataItem.FirstName");
- 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");
- DropDownList + ListBox auto store items added at runtime Not for
Table, which auto stores data only for design-time rows + cells; one must
rebuild table stored from state var. [webb.163]
- 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 }
- 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 ... }
- - ListItem : (option item in selectable list
ctrl
- ListItem's canbe added i) between <asp:ListBox>
& </asp:ListBox> tags (iff html code),
ii) Items.Add() (iff .net code)
- - 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?}
- CheckedChanged evt, not Clicked
IV. Data-bound Ctrls
- 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>
- you must explicitly declare all HTML layout, formattg, and style tags
within the control's templates.
- the only control allowg HTML tags tobe split across templates.
- has no built-in selectn or editg support.
- min: every Repeater must define an ItemTemplate
- templates: ItemTemplate | AlternatingItemTemplate |
SeparatorTemplate | HeaderTemplate | FooterTemplate
- 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();
- ItemCreated - fired if any item created
- ItemDataBound evt fired after item
bound to data src + before rendered to pg --> last t to access data
before shown
- ItemCommand evt raised when
any button in DataGrid clkd.
- SelectedIndexChanged evt raised
when difft row sel'd.
- PreRender evt raised just before the grid renders itself
to the page.
- DataGrid has no Click, no ButtonClicked, nor
OnClick event, but fires
EditCommand event when Edit button clicked.
- data tobe rendered to cells canbe accessed usg
DataGridItemEventArgs.Item.Controls
- template: set of html elemets/server ctrls/both
repeated foreach
data item
- EditItemIndex - get/set which item being
edited as zero-based idx; no deflt | -1 if no item; user-set idx:
oDataGrid.EditItemIndex =
oDataGridCommandEventArgs.Item.ItemIndex
- SelectedIndex - get/set idx of user-sel'd item
- CurrentPageIndex - get/set which pg shown
- Auto-generatd columns not added to Columns collectn.
- Sort property notexist for DataGrid;
but DataViews canbe sorted usg DataView.Sort = aColumn;
DataSets canonly be sorted by changg data src.
- oDataGrid.AllowSorting
- myDataGrid.DataBind(); datagrid bind + display data
of dataset; DataGrid already in Control collectn.
V. Calendar Ctrls
- 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); }
- 4 date selectn modes: SelectionMode = Day |
DayWeek | DayWeekMonth | None (any single d | d/w | d/w/m |
seln disabled)
- JavaScript required
- SelectedDate or SelectedDates: use with
SelectionChanged
- 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>
- Impressions: `weight': higher the no., more often
displayed.
- vs: Properties > TargetSchema > AdRotator schedule file:
<Advertisements xmlns =
"http://schemas.microsoft.com/AspNet/Adortator-Schedule-File"> ;
AdRotator > AdvertisementsFile = f.xml [webb.177]
VI. Validatn Ctrls
- 6 validatn ctrls [webb.187]
- clt-side validatn: Jscript lib: WebUIValidation.js
but iff IE 4+
- validatn occurs clt-side, after postback
- Validate(): devr can manually cause validatn to occur
- validn occurs auto when page submitted, not when loaded
- ControlToValidate forall ctrls except CompareValidator;
false if type conversn failed
ControlToCompare() if CompareValidator;
true if type conversn failed [webb.190].
- set Text if msg other than ErrorMessage
requd.
- ctrl canhave multiple validators
- all validatn ctrls except RequiredFieldValidator valid if blank
- cancellg validatn:
<input ... onclick="Page_ValidationActive=false;"
which sets Page.IsValid = false;
- 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();
- if inputs empty, validation still succeeds -->
use RequiredFieldValidator to force data entry
- 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) ...
- 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) ...
- validn succeeds if input ctrl is empty -->
RequiredFieldValidator to make it a mandatory field.
- 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) ...
- server-side + clt-side validn performed unless client-side validn
unsupported or client-side validn disabled (EnableClientScript = false)
- System.Text.RegularExpressions.Regex syntax used on server,
JScript regex syntax (a subset of Regex) used on clt, -->
reco: JScript regex syntax used so same results on both sides
- 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) ...
- 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"/>
- PlaceHolder
(container to store dynamically added server ctrls
at runtime)
<asp:PlaceHolder id="id_PlaceHolder" runat="server"/> ...
id_PlaceHolder.Controls.Add(myButton);
- Literal - (render data in Text property
directly to html data stream, easier than DataGrid) ?
- 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'>{0}:MyCustomCtrl>")]
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}
- 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:
- 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):
- Declarn: 2 ways -
<%@ Register TagPrefix="MyTagPrefix"
Tagname="MyTagName" Src="f.ascx">;
--> <MyTagPrefix:MyTagName runat="server">
-
<%@ 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
Props:
- .ascx extensn (conventn) --> cannot be requested as standalone
web pg.
- cannot be shared; web user ctrls|web forms cannot be installed
into GAC. --> a cp of web use ctrl mustbe in each webapp proj [boris]
- cannot be loaded into vs.net Toolbox as compiled dyn at
runtime; mustbe dragged from
Solutn Explorer to webform; vs cannot show user ctrls in Design Mode
(just generic ctrls)
- constituent ctrls: ctrls makg up a user ctrl, usu. private.
- has UI pg + code-behd file, = webform
- initd after webform loads, ie. properties
not updated till after webform's Load evt.;
user ctrl's Load evt after webform's Load evt proc.-->
code mustbe in Page_PreRender evt.
- in progs: Control c = LoadControl("f.ascx");
- deflt flowlayout, no built-in support for absolute positng;
use style prop toset to
gridlayout: aPanel.Attributes["style"] = value;
[webb.584]
Creatg User Ctrls
- add webuser ctrl page (.ascx)
- Designer: draw visual i/f
- write code for ctrl props, fu's, evts.
- drag ctrl from Solution Explorer to webform.
- declare ctrl at module level;
vs: Project > Add Web User Ctrl
- 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.
- 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 >
}
}
- Control.RenderChildren(): show ctrl's children
- as no contained ctrls --> use ViewState
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:
- Physical Data Store : sql, ole, oracle db or xml file
- 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.
- 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
- 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)
- 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. |
Features & Props of ADO.net
- Typed Refs to Data objs enabled
when connectn, adapter + dataset objs
created in vs Design mode --> type checkg, hence fewer errors.
xDataSet.Tables["aTable"].Columns["aColumn"}.Caption = "@Home"; // untyped refs
xDataSet,aTable.aColumn.Caption = "@Home"; // typed refs
(old ado: only untyped refs to data objs)
- Stored Procedure: frequtly used tasks stored on sql server
(♁ clts neednot send stmts ♁ compiled --> speed); exec in
db manager context + hence canbe idealized for performance.
- ADO RecordSet replaced by several components
- ado.net access usg Web.config:
Web.config:
<configuration>
<appSettings> <add key=SQLConnection value="conn string">
</appSettings> <configuration>
- dont call Close or Dispose on Connection/DataReader/managed obj in Finalize() In a
finalizer, only release unmanaged resources that your class owns directly.
- default max pool size = 100;
connection poolg iff 1 sql server a/c (same user + passwd) &
must use identical strings
- SqlException; OleDbException; OracleException; ODBCException
- CommandBuilder: "based on a single tbl SELECT, autom. generates the INSERT, UPDATE,
and DELETE cmds used for queries by the DataAdapter" [rothaus 2003]
- Variant (old ADO): In ADO, all results are returned in a standard OLE Automation
Variant type
- msado15.dll: provides old ADO Recordset,
its assembly mustbe created for .net apps [boris]
- 1 a/c toaccess sql server db --> conn poolg optimized
-
.NET Data Providers
- bridge providers: for older data access techs (OLE DB, ODBC)
- System.Data.OleDb: Oracle OLE DB via COM
- System.Data.ODBC: odbc
- native providers: use one less layer of abstraction (Oracle, SQL
Server)
- System.Data.SqlClient: Only MS Sql Server 7.0+
- System.Data.OracleClient: Oracle .Net Data Provider
- indexes on tables --> access speed ↑
-
>csc.exe sample.cs /r:System.dll /r:System.Data.dll /r:System.Data.OracleClient.dll /r:System.Xml.dll
b.
System.Data
Core Classes
- System.Data.IDbConnection (abstract interface
forall Connection classes) {= OdbcConnection |
OleDbConnection (ms access, mysql, < ms sql server 6.5)
| OracleConnection (oracle) | SqlConnection
(sql db, ms sql server 7.0, 2000+)}
- min connectn string = "user id=sa;
password=mypass; initial catalog | database=MyDB; data
source=server_addr_or_name_havg_db | myserver\sql2kinstance"
(sa = sys.admin)
- connectn string = "user id=sa; password=xyz; initial
catalog=MyDB; data source = myServer; connection timeout = 30;
max pool size=20; min pool size=1; connection lifetime=50"
--> server must respond in 30 secs before cancellg attempt+ may have no
more than 20 connectns in connectn pool. Connection Lifetime: howmany secs
elapse before destroyg a connectn that has been returned to connectn pool.
- ASPNET user a/c ∈ User Group:
asp.net + webapps run under this a/c,
sql server musthave this a/c + permissns;
for ms access/file-based db: File Security Settings > ASPNET user
a/c; else
i) grant aspnet user access to files usg ntfs ii) change
aspnet group iii) use impersonatn
- if managed provider for ms sql server db used -->
dont specify provider in connectn string.
- only connectns with identical connectn strings are pooled;
no. unique connectn strings = no. connectn pools
- System.Data.IDbCommand (interface representg
sql stmt) (implemented by = OdbcCommand | OleDbCommand |
OracleCommand | SqlCommand ) [webb.263]
Sql | OracleConnection MyConnection = new
SqlConnection("server=(local);"+"database=tbl; Trusted_Connection=yes");
SqlCommand MyCommand = new SqlCommand("SELECT col1, col2 FROM aTable",MyConnection);
MyConnection.Open();
Sql | OracleDataReader MyDataReader = MyCommand.ExecuteReader();
while(MyDataReader.Read())
{ foreach(object item in items)...
myReader.GetInt32(0); myReader.GetString(1) .. }
- ExecuteNonQuery(): for cmds not returng values
yet changg db, returns no. rows affected:
if(MyCommand.ExecuteNonQuery() > 0) { RefreshList(); .. }
- ExecuteScalar(): for queries returng single
value [rothaus 2003], returns value of 1st row and 1st col. --> good
for stored procedure + queries int i = (int)
MyCommand.ExecuteScalar();
- ExecuteReader(): sequentially read records from
db; sends CommandText to connectn + builds reader:
Sql|OracleDataReader MyDataReader = MyCommand.ExecuteReader();
- MyCommand.CommandText = "SELECT * from
OTABLE": contains sql stmt/stored proc; =
MyDataAdapter.SelectCommand = "SELECT * from OTABLE"
- MyCommand.CommandType = StoredProcedure |
Text (deflt) | TableDirect {exec as proc stored in db / sql stmt
/ ret entire tbl only for oledb} where SqlCommand MyCommand
= new MyCommand("storedprocname",MyConnection); [webb.270]
- MyCommand.Parameters("@param").Value.ToString() =
oLabel.Text; or MyCommand.Parameters.Add("@param",
OleDbType.VarChar, 40, "string");
- System.Data.IDbDataAdapter (combines sql cmd
+ connectn string; bridge fillg DataSet + updatg data src; interface
implemented byall: OdbcDataAdapter | OleDbDataAdapter |
OracleDataAdapter | SqlDataAdapter );
Sql | OracleConnection MyConnection = new // 1. create conn obj
SqlConnection("server=(local);"+"database=tbl; Trusted_Connection=yes");
SqlDataAdapter MyDataAdapter = // 2. create data adapter
new SqlDataAdaper("select * from oTable", MyConnection);
// or new SqlDataAdapter("SELECT * FROM aTable",
// "server=(local); database=aTable; Trusted_Connection=yes");
DataSet oDataSet = new DataSet(); // 3. create data set
MyDataAdapter.Fill(oDataSet)
| (ds,"tbl"); // 4. fill/update data set
oDataGrid.DataSource = oDataSet.Tables["tbl"].DefaultView;
oDataGrid.DataBind(); // 5. show data from dataset usg say data bindg
- MyDataAdapter.Fill() - populate DataSet;
exec MyCommand.CommandText
- MyDataAdapter.Update() - update db/data src +
ado.net does: i) oDataRow.RowState chkd tofd changes to db, ii)
oDataAdapter.Insert|Update|DeleteCommand() to change db for
rows inserted|del'd|modifd, iii) oDataRow.RowState = unchanged
set forall updtd DataRows [webb.242]
- before callg Update():
MyDataAdapter.SelectCommand.CommandText = "SELECT * from
oTable"; or setby constructor; ado.net creates
Insert|Delete|UpdateCommand's from this auto.
or
MyDataAdapter.SelectCommand = MyCommand; ;
- ContinueUpdateOnError = true | false -->
no exceptn thrown | throw exceptn/row if error durg row update;
error stored in Row.RowError
- Row.RowError
-
SqlDataAdapter.SelectCommand = SELECT * FROM TABLE1 ORDER BY
VALUE can sort, but only iff no stored procedure
- System.Data.IDataReader (fast, fwd-only,
read-only stream of data from a data src; not IDbDataReader) [rothaus
2003] (implemented by OdbcDataReader | OleDbDataReader |
OracleDataReader | SqlDataReader)
SqlDataReader myReader = myCommand.ExecuteReader();
if (myReader.HasRows){ while (myReader.Read()) {
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1)); } }
myReader.Close();
- Read(): moves reader to next record.
- values of o/p params of a DataReader arenot populated until
DataReader obj is closed.
- NextResult()
- Close(): close DataReader + supply values to o/p params
int i = MyDataReader.Parameters["@MyOutputParam"].Value;;
Close() mustbe called touse SqlConnection for other purposes
-
int i = MyReader.GetInt32(0); ←
select col1, col2 from tbl where .... (col1 = 0)
-
System.Data.IDbTransaction (cf. later)
System.Data
- System.Data.DataSet :
core db-indepedt compont of disconnected arch of ado.net;
DataSet ds = new DataSet("aTable");
- aDataSet.Tables.Rows | Columns;
- search by primary key: DataRow oDataRow =
MyDataSet.Tables["oTable"].Rows.Find(oKey); [webb.351]
- xml files r static reps of data sets.
- addg row:
aDataSet.aTable.Rows.Add(aDataSet.aTable.NewRow());
[webb.240 error]
- findg row:
aDataSet.aTableRow atr = aDataSet.aTable.FindByMyPrimaryKey(i);
- deletg row:
aDataSet.aTableRow atr = aDataSet.aTable.FindByMyPrimaryKey(i);
aTableRow.Delete();
- updatg db from DataSet:
... this.PreRender += new EventHandler(f_PreRender); ... // after all ctrl
// evts processed
public void f_PreRender(object o_sender, EventArgs e)
{ MySqlAdapter.Update(MyDataSet); aDataGrid.DataBind(); }
- DataSet has no DataBind() functn
- multiple tables: [webb.250]
// Data adapter, combines sql cmd + connectn string
oDataAdapter.Fill(oDataTable);
oDataAdapter.SelectCommand.CommandText =
"SELECT * FROM bTable"; // change adapter's SELECT cmd
DataSet aDataSet = new DataSet("xxx");
aDataSet.Tables.Add(aDataTable);
aDataSet.Tables.Add(bDataTable); // add both tbls to dataset
aDropDownList.DataBind():
aDataSet.Tables[".."].DefaultView.RowFilter = "conctactId=" +
aDropDownList.SelectedItem.Value.ToString();
- canshow data in other ctrls:
ListBox, DropDownList, CheckBoxList, RadioButtonList.
<asp:DropDownList id="aDropDownList" runat="server"
DataSource="<%# aDataSet %>" DataTextField='aName'
DataValueField="aValue"></asp:DropDownList>
... aSqlDataAdapter.Fill(aDataSet); aDropDownList.DataBind(); ...
- ReadXML(), WriteXML(): get/write static rep of data from xml
files: DataSet ds = new DataSet();
ds.ReadXml("input.xml", XmlReadMode.ReadSchema);
writing DataSet to XML: file | stream | XmlWriter | string:
ds.WriteXml("Customers.xml", XmlWriteMode.WriteSchema);
- if record modifd or not: RowState = UnChanged | Modified |
Deleted | Inserted
- uniform speed for DB/xml/app data
as db-indepdt & may contn tbls populated
from difft dbs & other non-db srcs
- serializable into XML data stream; ado.net uses xml forall
data trsfr across www
- Clear() removes data from dataset but leaves
data structures intact.
- ds2.Merge(ds1) combines data of 2 DataSets
into ds2, rows containg
same primary key combined --> no duplicate rows; DataSets shouldhave
similar schemas, else use MissingSchemaAction param to see how
differences are handled.
- merging ds1 into ds2
ds2.Merge(ds1, false, MissingSchemaAction.Ignore |
AddWithKey); - {dataset/datatable; | preserveChanges = false
--> changes in target db to be preserved or not, else old val
overwritten; | howto handle incomplete schema: Ignore = ignore extra
cols/schema elemts in ds1: | AddWithKey: add cols + key}
- AcceptChanges(): resets DataRowState to Unchanged,
removes deleted rows; inverse of RejectChanges;
MyDataSet.AcceptChanges();
- RejectChanges(): restores dataset, undoes changes.
MyDataSet.RejectChanges();
- Update()
- bDataSet = aDataSet.GetChanges();: return cp of aDataSet
with all changes made to it since last loaded/ since AcceptChanges()
called; populate bDataSet with modifd rows from another aDataSet
- aDataSet.HasChanges(): if ds contains changes
- aDataSet.Clone(): return a copy of the ds with no rows
- DataRelation (constrain parent + child tbls, st.
deletn of row in parent tbl forces deletn of related rows in child tbls.)
- DataRelation dr = new DataRelation("xtable", aDataColumn,
bDataColumn);
- ForeignKeyConstraint (
define actns occurg when rows are delted/updated in a parent tbl)
DataColumn dc1 = myDataSet.Tables["aTable"].Columns["SameCol"];
DataColumn dc2 = myDataSet.Tables["cTable"].Columns["SameCol"];
ForeignKeyConstraint fkc = new ForeignKeyConstraint["oTable",dc1,dc2];
fkc.UpdateRule = Rule.Cascade;
fkc.DeleteRule = Rule.Cascade;
fkc.AcceptRejectRule = AcceptRejectRule.Cascade;
myDataSet.Tables["Chemicals"].Constraints.Add[fkc];
myDataSet.EnforceConstraints = true;
- enable datagrid to show from multiple tbls
- when row deleted in a parent tbl, all rows in the child tbl (with
same primary key value) del | DBNull by fkc obj (dependg on
UpdateRule property)
- auto-created when DataRelation obj created in a DataSet.
- System.Data.DataTable = "collection of rows from a
single tbl" (= ADO RecordSet)
- oDataTable.Select() = array of DataRows matchg filter in
order of pirmary key else order of addn
-
oDataTable.AcceptChanges(): commits changes, use after ds
updated.
- DataTable.DisplayExpression
- oDataTable.KeyDeleteRule = Rule.Cascade | SetNull | SetDefault
| None - actn when ForeignKeyConstraint enforced: {all rows
containg val deleted | all child col vals = null | all child cols to deflt
vals | no actn but exceptns}
- System.Data.ForeignKeyConstraint:
an actn restrictn enforced on a set of cols -->
parent tbl affects child tbl
- oDataTable.Constraints: contains fkc's
- DataTableMapping : map difft names to columns
DataTableMapping dtm = myDataAdapter.TableMappings.Add("MyMap","aTable");
// create dtm from the data adapter, & add col mappgs to dtm usg Add
dtm.ColumnMappings.Add("newcol","oldcol");
DataSet ds = new DataSet();
myDataAdapter.Fill(ds, "MyMap"); // use dtm instead of DataTable
foreach (DataRow myRow in ds.Tables["aTable"].Rows)
{ string s = myRow["newcol"].ToString(); } // use idx or col name
- DataSet
- DataTable
- DataRow dr = myDataSet.Tables["aTable"].GetErrors; -
returns array of DataRows containg errors
- boolean b = myDataSet.Tables["aTable"].HasErrors();
- DataRow : does not contain a Columns collectn
- RowState = Added | Deleted | Modified | Unchanged | Detached
[webb.242]
- DataView : canbe sorted & filtered
efficiently
object o = {"samar","abbas"}; MyDataView.Find(o);
MyDataView.Sort("fname","lname"); MyDataView.Table = ...;
MyDataView.Sort(ocol DESC) {reverse sort, descendg}
- DataGrid.DataSource : est data src the data grid is bound
to.
- myDataView.RowFilter = "RegionCode ='" + myListItem.Text +"'";
(filter contents of data grid)
- FindRow() returns a set of rows that meets a specific
criteria, but it cannot filter the data grids row
- DataGrid.SelectCommandName = ro property
- { CommandBuilder } - (nonexistt superclass for
Sql | Oracle | OleDb)CommandBuilder - provides auto creatn ofall
sql stmts ie. InsertCommand, DeleteCommand & UpdateCommand, based on
DataAdapter info, for updatg db at runtime)
SqlCommandBuilder cb = new SqlCommandBuilder(oDataAdapter);
// create insert, del, update cmds auto
oDataAdapter.Update(oDataTable); // [webb.248]
System.Data.SqlClient : ms sql server db
access
- SqlCommand; SqlConnection;
SqlDataAdapter :cannot be used with old ADO Recordset
obj; SqlDataReader ; SqlException ;
SqlTransaction
-
SqlParameter: if param i/p only | o/p only | bidirectnal | stored proc
return param
- Direction = ParameterDirection.Output | Returnvalue
- SqlParameter.SourceColumn = src col. for loadg a val. o
System.Data.OracleClient - Oracle db access
- OracleCommand ; OracleConnection ;
OracleDataAdapter ; OracleDataReader ;
OracleException ; OracleTransaction
System.Data.OleDb : other db access
- OleDbCommand ; OleDbConnection ;
OleDbDataAdapter ; OleDbDataReader ;
OleDbException
System.Data.Odbc
- OdbcCommand ; OdbcConnection ;
OdbcDataAdapter ; OdbcDataReader ;
OdbcException ; OdbcTransaction
c.
T-SQL
- @@IDENTITY: identity value of last row inserted into tbl
- SCOPE_IDENTITY fu: returns val of the Identity column of the row
most recently added
- Autonumber field may produce duplicate values in separate
datasets if multiple users insertg rows.
- SCOPE_IDENTITY, IDENT_CURRENT, @@IDENTITY: retrieve identity values
for db supportg stored procedures (eg. ms sql)
- Identity columns: cols containg unique number; used to uniquely id
each row.
- IDENT_SEED: seed value used when an Identity column created.
- DATALENGTH fu: length of column/expressn
- IDENT_INCR fu: returns incremental value specifd when an Identity
column created.
- user INNER JOIN to combine data of 2 tables.
SELECT acol1, acol2
FROM atable
INNER JOIN btable
ON atable.acol1 = btable.acol1 =
cols to return, parent tbl, child tbl after INNER JOIN,
common col comparison
d.
Transactions
Transactn: grp of cmds treated as a single unit,
all-or-nothg fashion: if 1 cmd failed, all fail + data removed.
ACID test: which cmds belong to transactn; must satisfy certain conditns:
- Atomic: if cmds comprise a single unit of work,
eg. st, city, state r pt of address.
- Consistent: data relatnships maintained correctly.
- Isolated : changes by other clients dont affect currt changes,
no indeterminate states.
- Durable : changes r permanent
Problems for webapps + distributed db
- Contentn for Resrcs: eg. changg same record at same time.
- Unexpected failures: disconnectns, power failures, modems
- Webapp lifecycle: webforms livefor only an instant,
clt canleave anytime.
ado.net Transaction Types
- 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
- 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();
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
- 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:
-
<%@ Page .... TransAction="RequiresNew" >
- use ContextUtil.SetAbort() | SetComplete()
to change transactn status
- 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]
- 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.
Enablg Windows Authenticn:
- Web.config :
<authorization> <deny users="?" /> :
deny access to anon. users.
<table> ... <span id="MySpan1" runat="server"> ....
private void Page_Load(object o_sender, System.EventArgs ea)
{ MySpan1.InnerText = User.Identity.IsAuthenticated.ToString();
MySpan2.InnerText = User.Identity.Name;
MySpan3.InnerText = User.Identity.AuthenticationType;
if(User.IsInRole("Administrators") ... }
- ? = anon.users | * = all users
- first matchg authorizn rule used, eg <deny
users="*" />
<allow roles="MyRole" />
all users denied first, roles never evel'd.
- role = group of users, allow a role, restrict subdir:
subdir/Web.config:
<authorization><allow roles="MyRole" />
<deny users="*" /></authorization>
- users attrib = single string containg 1/+ comma-septd
user names. [webb.426, boris]
<authorization>
<allow users="user1, bhost\user2" />
<deny users="user3, user4" />
</authorization>
- Global module: AuthorizeRequest: customizn, eg
chk usernames usg ext file not Web.config.
- iis settg eval first, Web.config later.
iis > rclick(webapp folder) > Properties > Dir Security
> Anon Access Ctrl Area > Edit
- Machine.config: deflt authorizes all users to access all
resrcs on
server
Advantages of Windows Authenticn
- same nw user/passwds canbe used from home/trip/co.
- loggedin win users neednot use user/pass for webapp access
- Forms authentication: logon webform (user + passwd prompt)
(commercial webapps) [webb.433] ( - less secure)
1. usg Web.config
- <forms
name=".authaspx" {cookiename; 1cookie/app}
loginUrl="Default.aspx" {login webform}
protection=" All | Encryption | Validation | None " {cookie
protection: All = encryptn + data validn}
timeout="30" {nu.min.cookie persists}
path="\"> {path tostore cookie}
-
Web.config: {set auth mode}
<authentication mode="Forms | Windows | Passport">
<forms loginUrl="f.aspx"> {if no valid cookies found}
<credentials passwordFormat="SHA1 | MD5 | Clear">
{user list}
<user name="auser" password="xyz">
<user name="buser" password="xyz">
</credentials>
</forms>
</authentication>
using System.Web.Security; ...
// chk against <credentials>
f_login(object o_sender, EventArgs ea)
{ if (FormsAuthentication.Authenticate(user_TextBox.Text, passwd_TextBox.Text))
{ FormsAuthentication.RedirectFromLoginPage(user_TextBox.Text, true); }
else{ Resonse.Redirect("denied.htm"); ...} ... }
f_logout(object o_sender, EventArgs ea)
{ FormsAuthentication.SignOut();
Response.Redirect("login.aspx"); }
2. usg db [webb.442]
- encrypt db
Password = FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "SHA1");
-
OleDbCommand odc = new OleDbCommand("SELECT * FROM aTable WHERE
User='" + aTextBox.Text + "'", MyOleDb);
- 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" ];
}
- passport info stored on five cookies, mustbe removed on signout:
Response.Cookies["MSPProf | MSPProfC | MSPAuth | MSPSecAuth |
MSPConsent"]
- Basic + Digest: prompt user for user+passwd;
iis authent methods.
- Anonymous: for public web sites; no identity needed.
deflt anon user a/c = IUSER_myhost
(public internet webapps)
- Certificate authent: uses certif (server cert) from 3rd-party
src. (cert authority, eg. VeriSign)
- SSL (Secure Sockets Layer): https;
encryptn
- cert. request: iis : deflt website > actn: properties > deflt
website props
> dir security > Server Certificate > Web Server Certif Wizard
--> .cer file (send to cert authority)
- installg cert: iis : deflt website > actn: props > deflt
website props > dir security : server certif > Web Server Certif
Wizard
Security Tools:
- sn.exe
(strong name tool for signg assemblies)
- -R (resign prev. signed/delayed assembly)
| -Vr (temp. disable strong name verificatn durg testg)
- > sn -R MyAssembly.dll MyKeys.snk
(resign prev. signed/delayed assembly)
- Authenticode dig sig signg willnot prevent
assemblies from failg strong name verificn process.
- Signcode.exe: sign assemblies with
verifiable Authenticode digital signature.
- Regasm.exe
(register assembly modules)
; register assemblies sothat they canbe used as COM componts
- Secutil.exe
(signature extractn util)
: extract dig signatures, not install, manage strong name public key info
or Authenticode signatures.
- Ngen.exe ('Native generator'):
compile native images of .net apps and
assemblies
- Al.exe ('Assembly linker')
- > Al f._ - embed f resrcs in o/p assembly.
- > Al /delay+ f._ - delay signg: sig not computed but
sig space reserved for later
- Cert2spc.exe (sw publisher certif. test tool)
make spc from 1/+ X.509 certs for testg only.
- Resgen.exe (resrc file generator): .txt +
.resx (xml resrc fmt) --> clr binary .resources file
--> canbe
embedded in run-time bin exec or compiled to satellite assemblies.
Assemblies
- public key:
<assembly:AssemblyKeyFileAttribute("PublicKey.snk")>
- delay assembly signg:
< assembly:AssemblyDelaySignAttribute(true)>
- assemblies installed into GAC mustbe signed with a strong name.
- GAC:
Installatn .net assemblies into GAC
- MS Windows Installer 2.0
- Gacutil.exe (Gac Utility)
- InstallUtil.exe
(installer tool): install + uninstall server resrcs.
b.
Session Mgt, State Mgt & Client-Side Scriptg
Methods for Retaing vars betwn Requests in asp+ [webb.132]:
- Context.Handler:
if Transfer() or Execute() --> retrieve readonly
props of previous webform; Server.Transfer("f.aspx"); ... MyPage
aPage = (MyPage) Context.Hanlder; ... aPage.Value;
- 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"];
- 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;
}
- View state: save data in hidden field; hidden data is hashed:
- Page.EnableViewState
= <%@ Page ... EnableViewState=true ...>
- get/set if pg maintains its
and its server ctrls view state when pg request ends,
stored in hidden form field. (hence nw load increased)
- view state = data asp.net preserves between requests; deflt
avail. only within that webform
- oControl.ViewState inherited by ctrl.
- changes to Web.config auto restart the web app,
Application state vars & Session state vars lost to current users if
Web.config changed for deployed app [webb.77]
foreach (StateItem Item in ViewState.Values)
{ ... aTableCell.Text = Item.Value.ToString(); ... }
Features of Hidden Fields
- + no server resrc requd.
- + increased support as no cookies on browser requd.
- - security
- 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)
- In-process: locally,
in-proc with asp.net worker process;
each app hosted on single processor, fast.
- 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
- 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.
- auto. get username w/o prompt:
Session.Item("User") = User.Identity.Name;
- - stored in memy till removed/replaced.
- on | off:
i) vs: Web Form Properties > EnableSessionState = false (for 1 webform);
ii) Web.config: <sessionstate mode="off"> (whole webapp)
- Application State:
Application["aName"] = "aString";
Response.Write(Application["aName"]);
- Applicatn State: shared by all sessions of an app
- System.Web.SessionState.HttpSessionState: class
- Old asp
Session["val"]=9; | Session.Add["val"]=9; |
Session.Contents["val"] = 9;
- query strings: store state in plain txt
- deflt session time-out for webapp = 20 min.; specfd in Web.config
[webb.66, 76];
<sessionState
mode="InProc" sqlConnectionString="userid=sa; password=xyz; data
source=127.0.0.1" timeout="20"
>
- Enablg sessn state for xml webservice method:
Global.asax: Session_Start: <WebMethod ... EnableSession=true
> = StateServer.
- Application State:
Application["aName"] = "aString";
Response.Write(Application["aName"]);
Types of state vars:
- 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;
- Session state vars: avail only to a single sessn (user), the
current
session; = global data in win apps;
Session["Clicks"] = 1;
c.
Unmanaged Code
- unmanaged code: clr not ctrl memory mgt nor how app executes,
- pinvoke (platform invoke) = the process of executg native code
from within .net assembly.
- marshaling:
clr collects params + converts their types
when unmgd proc called.
-
DllImport: CharSet = CharSet.Ansi -->
strings auto converted betwn Unicode & ANSI formats.
Win32 datatype .net sqlserver datatype
BSTRS String
word Int16
dword Int32 int: 4 bytes (-231)-(231-1)
- ret val: 0 | nonzero ( error | success )
- Exceptn Handlg for Unmgd Code: [webb.360]
[DllImport("KERNEL32.DLL", EntryPoint="MoveFile", SetLastError=true,
CharSet=CharSet.Unicode, ExactSpellling=false,
CallingConvention=CallingConvention.StdCall)]
if (MoveFile(...)) { ... } // nonzero if success
else
{ switch( Marshal.GetLastWin32Error() )
{ case 2: s = "file not found"; break;
case 5: s = "access denied"; break; }
}
- Limitatns of Unmanaged Code:
- Performance: canperform some operatns quicker than
clr mgd code, but data marshalg betwn unmgd proc and .net assembly
slow.
- Type safety: might notbe type safe
- Code security: doesnt use .net code security model
- Versng: .net versng not supported
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; }
System.Runtime.InteropServices
d.
COM, COM+
COM Interop Tools: [webb.372]
- TlbImp.exe (Type Library Importer: gen .net assembly
from COM obj; type library importer: creates .NET-compatible assembly
from COM compont), "wraps"
- TlbExp.exe (Type Library Exporter: gen COM lib from
.net assembly; export type lib info from .net assemblies + COM componts)
- Ildasm.exe (Intermediate Language Disassembler:
view interop assembly)
- Regasm.exe (Assembly Registratn Tool: add/remove sys.
registratn db entries for a .net assembly)
RegAsm.exe MyAssembly.dll
- Regedit.exe (Registry Editor: view sys. registry db
entries for COM objs installed on sys, incl. .net objs registered for COM
interop)
Limitatns of COM Interop:
- Shared/static members not supported by COM as objs mustbe
created before use.
- Shadow/new members not callable as COM flattens inheritance
tree.
- Constructors with params COM cannot pass params to
constructors.
- COM objs memory-leak prone
- Type libs mightbe inaccurate
- COM is unmanaged code
- Shared solutns mightnot allow COM objs
e.
Client-Side Scripting
Purposes of Clt-side scriptg:
- Ctrl Browser Wdw
- Mouse-Over Evts immediately responded to.
- Mail Sys. of clt started:
- clt-side:
<asp:HyperLink NavigateUrl="mailto:a@y.com?SUBJECT=hello
world&BODY=hello world." runat="server"> ...
- serverside:
SmtpMail.Send("from@a.com", "to@z.com", "sub line", "msg txt");
(deflt SmtpServer is localhost, canchange). For complex msgs:
System.Web.Mail.MailMessage MyMailMessage = new MailMessage();
MyMailMessage.From = "from@a.com";
MyMailMessage.To = "to@z.com";
MyMailMessage.Subject = "sub line";
MyMailMessage.Body = "msg body";
MailAttachment MyMailAttachment
= new MailAttachment(Server.MapPath(".") + "\\f.jpg");
Debugg clt-side scriptg [testking]
- enable script debugg: IE > Tools > IN Optns > Adv > Browsg
> x Disable Script Debugg
- vs: Tools > Debug Processes > attach to IExplore.exe (IE) + brk into
script
- vs: set brkpt/add "Stop" to vbs/js where interative debugg starts
- ie: run vbs/js
V.
Testing
Automated tests;
reproducible, measurable (success/fail)
a.
Types of Test
Types of Test [webb.527] usu in order:
- Unit Test: indept piece/individ componts of code;
- unit = smallest piece of code that canbe independantly tested, eg.
classes, props, fu's, events.
- usu by developer in same lang.
- use MinValue, MaxValue, etc.
- Integration Test: all units work together, done after unit
testg
- stub = nonfunctnal componts providg class/rop/fu defitn used by
other componts; outline of future code; prevents errors when other classes
call fu's.
- driver = test componts ensurg 2/+ componts work together.
- testg interface = set of pub props and fu's used to ctrl a compont
from an ext.testg prog;
#if DEBUG ...
- Regression Test: newly added features notaffect other parts;
testg debugged code
- Load/Stress Test: hi usage;
ACT (App.Center Test) [webb.541]
- ACT: stress-testing by vs
- act records tests usg VBS only, but tests canbe in Jscript/vbs.
- c:/Perflogs - act log file per test (deflt)
- Test.TraceLevel = -1 | 0 | 1 | 2
( all info | no info | requests+responses | Trace fu msgs (deflt) )
- Test.Trace("msg to log");
- deflt: 1 connectn tosend requests to the webapp.
- Test.GetNextUser(): - manually change users.
- Test.GetCurrentUser.Name - get name.
- act can mimick difft browsers
- Platform Test: works on all hw+sw platforms
- Unattended vs build: run vs from cmd line usg solutn file (.sln):
> DevEnv f.sln /build Debug > Logs\f.log
-
Start > All Progs > Accessories > Sys.Tools > Scheduled Tasks
b.
Errors & Debugging: Debug & Trace
System.Diagnostics
- Trace :
fu's + props retained in release code by deflt.
Enablg Tracg:
- for entire webapp:
Web.config:
<system.web>
<trace enabled="true" pageOutput="true"
localOnly="false"/> </system.web>
--> tracing on for whole app +
send o/p to both Trace.axd and bottom of each web page +
browsers outside webserver can view Trace.axd file:
http://server/myApp/trace.axd;
(shows 6 sectns: 1. Cookies colln 2. Trace info 3. Ctrl tree 4. Headers
collectn, 5. Server vars 6. request details)
dir: //localhost/myApp
- pageOutput = false (deflt) | true -->
o/p to Trace.axd file only | to both Trace.axd and bottom of each web
page. [webb.328] [tk]
- localOnly = false | true (deflt) -->
browsers on remote machines can |
(trace.axdd only viewable on webserver/locahost)
cannot access Trace.axd [webb.328]
- <Trace ... RequestLimit=20
enabled="true"...>
enable tracg for first 20 requested pgs only
- Clear Current Trace (rhc Trace.axd) -->
reshow Trace.axd & passes querystring clear=1
(<a href="Trace.axd?clear=1">
- Trace.WriteIf(bool_DataChanged, s_ChangeDescriptn) :
track changes made to associated profiles, write 2nd string param to
trace listeners if bool_... = true.
- Trace.Write(): Context property: ensure trace info from user ctrl
appears with trace info from f.aspx
- trace info is stored in a TraceContext class provided by
Page.Trace & Control.Context props.
Control.Context allows custom server ctrls' trace info tobe included
with
host page's trace info.
- for single page:
<@ Page ... Trace=true
.. TraceMode="SortByCategory|..." ... >
--> enable tracg on per page basis;
for tracg on entire app use approot/Web.config.
vs: Properties > Document > Trace = true
- trace o/p shown at bottom of each webpage deflt.
- Write to Trace log: Write(), Warn();
Trace.Warn("error","", Server.GetLastError();
- if(Trace.IsEnabled) - chk if tracg enabled.
- cannot write to an event log directly;
use EventLogTraceListener to direct tracg o/p to event log.
- Context.Trace.Write("My Context", xstring); :
trace o/p of user ctrl appear with trace info of webform,
in web form itself.
- WriteIf() : send info to trace listeners if statemt is
true.
- WriteLineIf() : not stop exec, write info
- Assert(): stop exec, show msg if conditn exists
- trace info contns: t of each request, file name requested,
a status code, http verb, etc.
- Debug :
fu's + props auto-stripped out of code compiled for release.
- Debug.WriteLine() - write errors to testg log file.
- Debug.Assert() - raise alerts if value tested is false;
Debug.Assert( i == j+k , "error");;
shown on server only.
- methods+props of Debug obj not compiled when app compiled in
release mode, only in debug mode.
- Web.config: <compilation Debug="true"> -->
enable calls to Debug
- Write(), WriteLine(): write messages w/o haltg app,
shown in vs Output wdw durg debugging
- direct debug msgs to server's console:
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out) );
Debug.WriteLine("error");
- write msgs to file:
Debug.Listeners.Add(new TextWriterTraceListener("f.log");
Debug.WriteLine("error");
Debug.Flush(); // wrote o/p to file
- Trace = Debug but still processed after compiln in release mode.
- Debug.Assert(!bool_DataChange, s_ChangeDescriptn): send msgs to
trace listeners if bool_.. is false (opposite of Trace.WriteIf())
- calls to Debug functns arenot compiled into release versns of the
app.
- Remote Debugg: vs clt debugs webserver webapp:
vs ctl: Tools > Debug Procs > attach aspnet_wp.exe ;
server: Web.config: Debug mode;
install vs.net remote debugg componts on the webapp
server.; cfg server perms to allow remote debugg.
- Interactive Debugg: Cfg Mgr > Debug Cfg > rebuild compont/app
- JIT Debugg: debug prog started outside vs.
- Debugger: user group @ webserver enablg interactive
debugger.
- EventLog : (r+w info to local/remote event log,
creatg new log if notexist)
EventLog myEventLog = new EventLog();
myEventLog.Source = "mySource";
myEventLog.WriteEntry("a string");
- canwrite entries to evt log through WriteEntry(), but cannot write
trace info
- EventLogTraceListener :
canbe added to Trace.Listeners or Debug.Listeners collectns to direct
tracg/debugg info to evt log
EventLogTraceListener eltl = new EventLogTraceListener("log");
Trace.Listeners.Add(eltl);
Trace.WriteLine(aString);
- Web.config <customErrors mode="RemoteOnly|Off">
(causes deflt .net error msg tobe shown| prevent custom error processg
from occurrg, more detailed deflt error msgs displayed to users)
Types of Breakpoints (4):
vs: Breakpoint Properties > i(conditn)
- functn brk pts: brk at functn
- file brk pts: brk when spec locatn in specific file reached.
- addr. brk pts: brk at memy addr
- data brk pts: if var value changes (notexist for vb,c#)
Props of breakpoints:
- if breakpoints not invoked:
vs: asp.net pg > Property > tick Enable ASP Debugg
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:
- SEH = Structured Exceptn Handlg.
- Error Evts
- webform.aspx: Page_Error: p error
- Global.asax: Global_Error: app error
- Global.asax: Application_Error
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
}
- Custom Error Pages
2 levels
- <%@ Page ErrorPage="f.aspx">- spec. webform
- 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>
- Machine.config: <customErrors mode="On">
--> 1 error msg forall webapps on webserver
c.
Help
Help:
- ToolTip:
<asp:... ToolTip="click here" ... ></asp:...>
- html: <a
href="#" onclick="window.open('f.aspx','newwinname').focus()">
- use HTML Help Workshop to create/compile help
- pluggable proto:
<a href="ms-its:http...f.chm::/f.htm" target="..">
- showHelp(): <a
href="#" onclick="window.showHelp('f.aspx|c:\\help\\f.chm')">
usg compiled help files (.chm)
- compiled help (.chm: toc, idx, search features) mustbe cp'd to
local HD
d.
Windows Installer
- Deploymt condn: condn mustbe met before installn can proceed
- Merge module (myproject.msm): setup file only callable from other
setup files,
used to pkg assemblies + other reusable componts.
[webb.497]
- FS Editor: create folders + shortcuts, etc. on file sys
durg setup event.
- Custom actn: exec f's, dlls, scripts/assemblies
containg instructns invoked at end of installn.;
used to incl db setup scripts
- winXP has Windows Installer 1.5 -->
any projects tobe installed neednot incl. Win Installer bootstrapper files
--> Bootstrapper = None
- web app --> Web Installation project not stdd installn project
- pkg assembly as merge modules
- Launch Conditions Editor: ensure target comp meets min requiremts for
app.
VI.
XML & XSLT
CSS [webb.ch13]
- cascadg precedence: Inline > Page > Global level (webfrom:
<head>... <link rel="stylesheet" type="text/css"
href="f.css">
- style class: .myclass { font-style: italic; } ...
<span class="myclass"> ...
<asp:TextBox ... CssClass="myclass">
- nested styles: ul li li li ...
- runtime style-sheets:
<link ... media="screen | print" >
or document.all["ScreenStyle"].get/setAttribute("HREF");
- behaviour: dyn.fmt'g: import behavior files:
.time {behavior: url(#default#time); }
--> usg Movable.htc to drag-drop paras on webform.
XSLT: intelligt fmtg layer complementg css
- <xsl:stylesheet
version="1.0" xmlns:xsl="...www"> : versn of xsl used
- <xsl:template match="/xtemplate">: def template for
xml node
- <xsl:apply-templates select="xnode"> - apply template
to selected node
- <xsl:value-of select="nodevalue"> - select xml node
value;
... select="generate-id(xmlnode)" use XPath
fu to gen uniq id for xml node
- <xsl:text> - literal txt
- <xsl:for-each select="repeatednode" /> - repeat
instructns
- <xsl:element name="a" /> - compose html elemts
- <xsl:sort select="title" order="ascending" />
- <xsl: if | choose | when | otherwise />
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)
- Detect & Redirect:
-
CultureInfo ci = new
CultureInfo(Request.UserLanguages[0]);
(Request.UserLanguages[] = strg arr of user's preferred
langs; 0 = user's currt lang)
- Web.config: <globalization requestEncoding="utf-8"
responseEncoding="utf-8" culture="ar-SA" {Saudi}/>
- - seprt webapp forall cults
- + large content
- Run-Time Culture adjustmt:
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
- + no redirn, same code
- + if content amt ↓
- Thread.CurrentThread.CurrentCulture ≠ neutral culture
as it uses regn info to fmt currencies, etc. [webb.762]
--> use CultureInfo.CreateSpecificCulture("fr-FR");
- 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.
- + app gens content at run-time.
- + for translated contt
- ResourceManager: access to cult resrcs at run-time.
- addg resrc file to vs: Project > Add New Item >
Templates: Assembly Resrc file
-
id_paragraph.InnerHtml =
oResourceManager.GetString("satellite.id_button");
- CultureInfo.Name = Request.UserLanguages[];
- <body dir="rtl"> --> right-to-left
≡ oPanel.Attributes.Add("dir","rtl");
- CurrentCulture: used to fd fmts for dates, currency, nus.
- CurrentUICulture: used to find which satellite assembly tobe
used when loadg translated strings from oResourceManager
- <globalization ... UICulture="...">
--> for locale-depdt searches.
- <globalization ... fileEncoding="utf-8" />;
clr uses utf-16 char encodg, but asp.net uses utf-8.
- saveas utf-8 with signature --> asp.net auto-detects encodg
- set encodg for response (not auto done by asp,net!):
Response.ContentEncoding = System.Text.Encoding("shift_JIS");
System.Globalization
- CultureInfo (info abt a specific culture,
ie. a cult assoc with a lang and a cntry/regn.)
CultureInfo myCI = new CultureInfo( "es-ES" | 0x040A, false );
Console.Write(" : " + myCI.CompareInfo + myCI.DisplayName +
myCI.EnglishName + myCI.IsNeutralCulture + myCI.IsReadOnly +
myCI.LCID + myCI.Name + myCI.NativeName + myCI.Parent + myCI.TextInfo
myCI.ThreeLetterISOLanguageName + myCI.ThreeLetterWindowsLanguageName +
myCI.TwoLetterISOLanguageName;
foreach ( CultureInfo ci in
CultureInfo.GetCultures( CultureTypes.SpecificCultures ) ) {
if ( ci.TwoLetterISOLanguageName == "zh" ) ...
Console.Write( "0x{0} {1} {2,-37}", ci.LCID.ToString("X4"),
ci.Name, ci.EnglishName );
CultureInfo ci = new CultureInfo("th-TH");
if (ci.Calendar is GregorianCalendar) ... else
Console.WriteLine ("{0} deflt cal:", ci.DisplayName.ToString(),
ci.Calendar.ToString()
for(int i = ci.OptionalCalendars.GetLowerBound(0);
i <=ci.OptionalCalendars.GetUpperBound(0); i++)
Console.WriteLine (ci.OptionalCalendars[i].ToString());
- Neutral Culture = general lang,
eg. "fr" = neutral culture & "fr-FR" = specific culture (+ regn).
- "zh-CHS" (Chin.Simplifd) and "zh-CHT" (Chin.Trad.) are
neutral cult.s
- resrc(specific cult.) > resrc(neutral cult.) >
resrc(embedded in main assembly)
- CultureInfo.Calendar (culture's deflt. calendar);
CultureInfo.OptionalCalendars (some cultures support >1 calendar)
- most effict way to localize web app for multiple cultures:
make sep satellite assemblies for each culture in own subdirs under
\Bin
- RegionInfo
nothave user pref's + not depend on user's lang/cult.
- System.Globalization.Calendar: abstract superclass
ofall calendars, ( = System.Globalization.GregorianCalendar |
HebrewCalendar | HijriCalendar | JapaneseCalendar | JulianCalendar |
KoreanCalendar | TaiwanCalendar | ThaiBuddhistCalendar)
CultureInfo ci = new CultureInfo("ja-JP");
ci.DateTimeFormat.Calendar = new JapaneseCalendar();
DateTime dt = DateTime.Now; Console.WriteLine(""
+ ci.DateTimeFormat.Calendar.GetDayOfMonth(dt) | GetMonth(dt) | GetYear(dt);
+ ci.DisplayName.ToString() + ci.DateTimeFormat.Calendar.ToString() );
VIII.
Web Server
a.
IIS
IIS 6.0:
- IIS Mgt Console:
Start > All Progs > Admin Tools > Internet Info Services
- Virtual Folder Creatn Wizard:
Rclick(deflt website) > New > Virtual Dir.
alias: name of virtual folder; = phys. locatn.
http://localhost/vfolderalias
- creatn of virtual folder:
1. create virtual folder
(Virtual Folder Creatn Wizard)
2. Add FrontPage Server Extensions to the virtual folder to create a
subweb: IIS Mgt Console > Rclick (deflt website) > New > Server
Extensions --> New Subweb Wizard
- map .htm/.html files to the asp.net executable usg iis snap-in: else
htm, html files deflt handled by iis not asp.net
- subweb = virtual folder containg a website
- bootdrive:\Inetpub\wwwroot : IIS root folder
- c:\Inetpub\wwwroot\localhost : web root folder
..\bin : compiled exec assembly (dll)
- C:\Inetpub\wwwroot\MyApp\f.aspx
= http://www.x.org/MyApp/f.aspx
- create virtual dir on web server:
webapp folder > VirtualDirectory = vd
- Global.asax: contains app-level and session level event
handlers; Global.asa for old asp
- AssemblyInfo.cs : hold app's global attributes.
- Global.asax: Application_OnStart evt handler called each time
the app is
started, when 1st user accesses a page of a web app.
- Global.asax: Application_OnEnd evt handler called when app
exited. if Globalasax saved --> webserver completes all outstandg
requests, raises Application_OnEnd evnt + restarts the app, raisg
Application_OnStart evt with less impact on users
- "error: sectn registered as allow
Definition=MachineToApplication beyond app level" -->
cfg iis settgs = dev env + create virtual dir for app on webserver |
wdws installer routine.
- use web installn pkg, eg. Windows Installer, to install the web app
and supportg assemblies st. the app + assemblies canbe uninstalled usg the
Add/Remove Programs as uninstalln info aded to Registry (not added by GAC
util or Xcopy deploymt).
- WinNT does not support . NET as asp.net web services requires IIS5+ which not
supported on WinNT. [faq ]
- boundaries of webapp = determined by folder struct;
start: root app folder (app startpage, Web.config, /bin:assembly);
ends: at last subordinate folder or when another root app folder met
- start page = first page to display by vs,
first webform in a project (ie. a dir):
Webform1.aspx; change:
Solution Explorer > rclick(webform | html) > Set as Start
Page
- IIS default document: page displayed if user omits doc name;
deflt doc file names:
Default.htm, Default.asp, Index.htm, Iisstart.asp
IIS Mgt Console > MyWebApp > Action > Properties > Documents
> Add > Add Default Doc
- application domain = one process space allocated by asp+ workeer
process / app
- w3wp.exe: multiple app pools [webb.76]
Server Ctrl Events: 3 types [webb.72]:
- 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.
- 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;
- 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]
- validatn ctrls evald before pg postedback to server
- Page_Init, Page_Load after postback
- Cached evts
- Post-back evt
- Page_Unload
- Page load, Text changed, Item selected, Button clicked,
Page PreRender
b.
Performance & Optimization: Caching
System.Web.Caching
- Cache ; results reside in memory on webserver;
store frequtly used items in mem for faster access
Addg data to Cache (3 ways):
- Key/Value pair:
Cache["MyKey"] = aString;
- Add(): requires all params;
Cache.Add("MyKey",aString);: fails if item exists; returns
Cache obj; Cache.Add("aKey", "aString", null,
Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(1),
CacheItemPriority.Default, null);
Cache.Add(oKey, oValue, oCacheDependancy, oDateTime, oTimeSpan,
CacheItemPriority.NotRemoveable | High | AboveNormal | Normal | Default | BelowNormal | Low ,
onRemoveCallback);
- oCacheDependancy = new CacheDependancy(astring,
System.DateTime.Now);
- Insert(): Cache.Insert("MyKey",aString) ;
overwrites existg items; doesnt return objs
- Remove() :
Cache.Remove("aKey");
-
Cache.Add("aDataSet", aDataSet, null, DateTime.MaxValue,
System.TimeSpan.FromMinutes(20),
System.Web.Caching.CacheItemPriority.Default, null);
(keep dataset in memory for 20 mins after last access)
[webb.250]
- onRemoveCallback - only evt provided by Cache; delegate
tocall wen data removed from cache, eg. CacheItemRemovedCallback
delegate.
- scavenging: process of removg items when resrcs scarce.
- DataSet obj in Cache obj + data in Sesion obj --> effict.
- Cache objs stores data as long as app is active, instances private
to each app, available to each app instance; lifetime(cache
obj) = lifetime(app); are static objs
- Session obj maintains session state between round trips, cannot be
shared with anyone (nor can Hidden fields), suited for maintaing
contents/values of ctrls after postback, dynamic
- <@OutputCache ... %> : directive controls how a
web page or web user ctrl is cached.
[boris li]
- Response.Cache [webb.640]
- Fragment Caching: process of breakg a web page into cached
web user ctrls. [boris] --> pts of web page appear before other parts
requirg more server resrcs;
cachg pts of a webform response [webb642]
c.
Building & Deployment: Windows Installer, Xcopy
Deployg: installg the app on webserver
- vs Upload :
Online resrcs > web hostg > Upload directly to Acct
- Own Server Hostg :
(musthave asp.net, iis 5.0+, .net fw of same versn)
iis > virtual folder > cp webapp to virtual
dir, add shared .net componts to server's GAC; set security
[app: starts at root folder, extends to all of its subordinate folders]
- 2 kinds of .net componts : 1. weak: not guaranteed tobe
unique, mustbe cp'd to /bin dirs; 2. strong: digitally signed, has public
key, canbe cp'd to GAC or installed as GacUtil -i MyControl.dll
- register COM compont to server: RegSvr32 MyComp.dll
- Installatn Program: use
Setup and Deploymt Projects Setup Wizard.
- Windows Installer bootstrap executable: Setup.exe - chcks if target
machine has Windows Installer, starts Installer/prompts for download.
- MMC: maintenance of deployed webapps.
- Multiple processors:
- Scalability: ability to add capacity to an app
- Web Garden: webapp runng on 1 server havg multiple CPUs
- Machine.config <processModel
... webGarden="true" cpuMask="0xffffffff"... />
- cpuMask - bit mask:
eg. 1101 = 0x0000000d --> cpus 0, 2, 3 on
- NLB: nw load balancg (incl. ms win2k adv server/ win2k
datacenter)
- Web Farm: webapp runng on multiple servers.
- Windows Installer :
- custom actions: run code at end of installn to perform actns
that cannot be handled durg installn
- Installer.Context
- launch conditns
- MsiConfigureProduct()
Optimizatn
- turnoff debugg for deployed apps
- avoid server-clts round-trips
- turnoff Session state
- turnoff ViewState
- db: use stored procedures
- use SqlDataReader rather than DataSets as faster + uses less mom.
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
|
for app to comm with xml web service:
- Vbc.exe or csc.exe to compile web service proxy into
assembly
- asp.net assemblies should reside in
\Bin dir of app.
- web references: used to link an app to a web service, not to
assemblies;
addg web ref to proj:
vs: Solution Explorer > Project > Add Web Ref. > URL
- Disco.exe: discover urls of web services runng on a server.
- Wsdl.exe (Web Services Descriptn Lang. tool)
gens proxy classes defing methods exposed by web
service which canbe used by other co's.
- addg webref to proj's usg xml web services:
Soln Explorer > Project > Add Web.Ref > xml web service url.
System.Xml
- XmlDocument
XmlDocument xd = new XmlDocument();
References