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. |
|
WinForms | ||
|
|||
|
| .net code |-----> | dll (in MSIL) | -------> | CLR | compiled assembly compile to native code + execs
Machine.config: <processModel enable="true" timeout="Infinite" {restart} shutDownTimeOut="00:00:05" {terminate proc after this time} requestLimit="Infinite" memoryLimit="95" {phys.mem. toconsume before proc restarted} responseRestartDeadlockInterval="00:03:00" {time to wait before restartg deadlocked proc} responseDeadlockInterval="00:03:00" requestQueueLimit="5000" {no. queued requests allowed before 503 (server too busy) returned}; clientConnectedCheck="0:00:05" {chk if clt connected} maxWorkerThreads="25" {max thrds / processor} maxIOThreads="25">
c. Directives
d. Built-in Objects
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
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 |
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 |
b. Server Controls
<%@ 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>
<style> .myStyle{...} </style> ... <script language="C#" runat="server"> myaspid.CssClass = myStyle; </script>
<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;
<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;
Label l = new Label(); l.BorderStyle = BorderStyle.Solid; l.Text = "This is a new Label"; Page.Controls.Add(l);
<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>"));
<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) ...
<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);
<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>
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"/>
<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
<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>
<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();
<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");
<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 }
<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 ... }
<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>
... 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();
<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); }
<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>
<asp:CompareValidator id="myCompareValidator" ControlToValidate="textbox1" ControlToCompare="textbox2" EnableClientScript="False" Type="String|Integer|Double|Date|Currency" runat="server"/> ... myCompareValidator.Validate();
<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) ...
<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) ...
<asp:RegularExpressionValidator id="myREV" ControlToValidate="aTextBox" ValidationExpression="\d{5}" Display="Static" ErrorMessage="mustbe 5 digits" EnableClientScript="False" runat="server"/> ... if (Page.IsValid) ...
<asp:RequiredFieldValidator id="id_RFV" ControlToValidate="aTextBox" InitialValue="Deflt Value" Text="in" {shown in ctrl} Display="Static" ErrorMessage="error" runat="server"/> ... if (Page.IsValid) ...
<asp:PlaceHolder id="id_PlaceHolder" runat="server"/> ... id_PlaceHolder.Controls.Add(myButton);
namespace aNamespace { [ToolboxData("<{0}:MyCustomCtrl Text='txt' BackColor='White' ForeColor='Blue' WarnLevel='0' runat='server'>")] public class MyCustomCtrl ... // deflt props of custom ctrl <@Register TagPrefix="MyTagPrefix" namespace="aNamespace" assembly="MyAssembly" %> {uses MyAssembly.dll ass containg MyCustomCtrl} <MyTagPrefix:MyCustomCtrl id="MyCustomCtrl1" Text="txt" BackColor="Color.White" ForeColor="Blue" WarnLevel="0" OnMyEvent="f" runat="server" /> {madeby vs}
<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
[DefaultEvent("Click")] // deflt evt on dbl-click public class CompositeCustomCtrl : WebControl {... protected override void CreateChildControls() { Controls.Add(new LiteralControl( ">br> hello" )); MyButton.Click += new EventHandler(f_click); } ... EnsureChildControls(); }
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 > } }
<CustCtrl:MyControl ForeColor="Color.Red" runat="server"> public int ForeColor { get { return myTextBox.ForeColor; } set { myTextBox.ForeColor = Value; } }
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. |
_____ _____________ / \---------> ( Data Provider ) |\______/| ( Connection ) | | -------------- | Data | | | Store | | | | da.Update() ------------ da.Fill(ds)-------- / | |<---------- ( DataAdapter ) -------->|DataSet|--------> Data View -< | | ( _________ ) | | \ \______/ --------
|
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. |
xDataSet.Tables["aTable"].Columns["aColumn"}.Caption = "@Home"; // untyped refs xDataSet,aTable.aColumn.Caption = "@Home"; // typed refs(old ado: only untyped refs to data objs)
Web.config: <configuration> <appSettings> <add key=SQLConnection value="conn string"> </appSettings> <configuration>
b. System.Data
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) .. }
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
SqlDataReader myReader = myCommand.ExecuteReader(); if (myReader.HasRows){ while (myReader.Read()) { Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1)); } } myReader.Close();
... 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(); }
// 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();
<asp:DropDownList id="aDropDownList" runat="server" DataSource="<%# aDataSet %>" DataTextField='aName' DataValueField="aValue"></asp:DropDownList> ... aSqlDataAdapter.Fill(aDataSet); aDropDownList.DataBind(); ...
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;
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
object o = {"samar","abbas"}; MyDataView.Find(o); MyDataView.Sort("fname","lname"); MyDataView.Table = ...; MyDataView.Sort(ocol DESC) {reverse sort, descendg}
SqlCommandBuilder cb = new SqlCommandBuilder(oDataAdapter); // create insert, del, update cmds auto oDataAdapter.Update(oDataTable); // [webb.248]
c. T-SQL
d. Transactions
Transactn: grp of cmds treated as a single unit, all-or-nothg fashion: if 1 cmd failed, all fail + data removed.
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
SqlTransaction MyTrans = MyConnection.BeginTransaaction(); SqlCommand MyCommand = new SqlCommand(); MyCommand.Transaction = MyTrans; MyCommand.CommandText = "..."; MyCommand.ExecuteNonQuery(); MyTrans.Commit(); MyConnection.Close();
try{ MyTransactn.Commit(); } catch(Exception e) { MyTransactn.Rollback(); } // cancel pendg cmds finally { MyConnection.Close(); }
Sql|OracleTransaction MyTransaction = MyConnection.BeginTransaction(IsolationLevel.ReadCommitted); SqlCommand MyCommand = new SqlCommand("DELETE ...", MyConnection, MyTransaction); try{ int i_rows = MyCommand.ExecuteNonQuery(); MyTransaction.Commit(); } // commit the transactn catch{ MyTransaction.Rollback(); }
IV. Security
a. Authenticn & Authorizn (System.Web.Security)
|
<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") ... }
subdir/Web.config: <authorization><allow roles="MyRole" /> <deny users="*" /></authorization>
<authorization> <allow users="user1, bhost\user2" /> <deny users="user3, user4" /> </authorization>
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"); }
protected void PassportAuthentication_OnAuthenticate(Object o_sender, PassportAuthenticationEventArgs ea) { if (ea.Identity.IsAuthenticated) ... ea.Identity["FirstName" | "LastName" | "City" | "PreferredEmail" ]; }
Web.config: <configuration> <system.web> <identity impersonate="true"> { or: identity impersonate="true" username="Administrator" password="xyz">} </system.web> </configuration>System.Security.Principal.WindowsIdentity.GetCurrent().Name tosee impersonated winuser id.
b. Session Mgt, State Mgt & Client-Side Scriptg
HttpCookie MyHttpCookie = new HttpCookie("a string", System.Guid.NewGuid().ToString(); // ?error
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; }
foreach (StateItem Item in ViewState.Values) { ... aTableCell.Text = Item.Value.ToString(); ... }
c. Unmanaged Code
Win32 datatype .net sqlserver datatype BSTRS String word Int16 dword Int32 int: 4 bytes (-231)-(231-1)
[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; } }
using System.Runtime.InteropServices // 1. use namespace [webb.355] // 2. identify unmanaged proc tocall [DllImport("KERNEL32.DLL", EntryPoint="GetSystemInfo", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=true, CallingConvention=CalllingConvention.StdCall)] public static extern void f(ref XSTRUCT xstruct); // 3. def types for unmgd proc params usg sequential (deflt) layout [StructLayout(LayoutKind.Sequential)] public struct XSTRUCT { ... public Int32 MyDataType ; ... } // [StructLayout(LayoutKind.Explicit)] public struct XSTRUCT // { ... [FieldOffset(0)]public Int32 MyDataType ; .. } explicit struct layout // 4. call unmgd proc private void Page_Load(object o_sender, System.EventArgs ea) { XSTRUCT MyXStruct; f(ref MyXStruct); ... MyXStruct.MyDaataType; }
d. COM, COM+
[assembly: ComVisible(false)] ...// hide public members from Com by deflt [ComVisible(true)] public class MyClass : AClass { ... }
e. Client-Side Scripting
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");
V. Testing
Automated tests; reproducible, measurable (success/fail)
a. Types of Test
b. Errors & Debugging: Debug & Trace
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out) ); Debug.WriteLine("error");
Debug.Listeners.Add(new TextWriterTraceListener("f.log"); Debug.WriteLine("error"); Debug.Flush(); // wrote o/p to file
EventLog myEventLog = new EventLog(); myEventLog.Source = "mySource"; myEventLog.WriteEntry("a string");
EventLogTraceListener eltl = new EventLogTraceListener("log"); Trace.Listeners.Add(eltl); Trace.WriteLine(aString);
c. Exception Handlg
Exception = unusual occurrence, = error; dealg with exceptns = exceptn handlg; unhandled exceptns = errors not dealt with in code
public class MyException : System.ApplicationException { public MyException() : this("a string", null) { ... } }
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 }
<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>
c. Help
d. Windows Installer
VI. XML & XSLT
MyDataSet.ReadXml( Server.MapPath(".") + "\\f.xml"); MyDataSet.ReadXmlSchema( Server.MapPath(".") + "\\f.xsd"); ... // search for key DataRow MyDataRow = MyDataSet.Tables["aTable"].Rows.Find(aKey); [webb.351]
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, ...) |
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.
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());
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
b. Performance & Optimization: Caching
Cache.Add(oKey, oValue, oCacheDependancy, oDateTime, oTimeSpan, CacheItemPriority.NotRemoveable | High | AboveNormal | Normal | Default | BelowNormal | Low , onRemoveCallback);
public override string GetVaryByCustomString(HttpContext MyHttpContext, string arg) {... "astring" ...MyHttpContext.Request.Browser.Browser; ...}
Response.Cache.SetExpires( System.DateTime.Now.AddSeconds(5) ); Response.Cache.VaryByParams["None"] = true; Response.Cache.SetCacheability(HttpCacheability.Public);
[PartialCaching(60)] public class MyCachedCtrl : System.Web.UI.UserControl
c. Building & Deployment: Windows Installer, Xcopy Deployg: installg the app on webserver
IX. XML Web Services (System.Web.Services)
xml web services : - a compont containg business functnality exposed through internet protocols, enablg apps to exchange info usg http and xml through firewall |