Upload
hoang-nguyen
View
55
Download
1
Embed Size (px)
DESCRIPTION
Quản lý trạng thái và ứng dụng trong ASP.NET; Chi tết các đối tượng trong quản lý trạng thái.
Citation preview
Cng ngh .NET.NET Technology
Lng Trn Hy HinB mn Cng ngh Phn mm
Khoa Cng Ngh Thng Tin
Trng HSP TP. H Ch Minh
Chng 3:
ASP.NET Application & State Management
Cng ngh NET 3 HIENLTH
Ni dung
Request
Response
Server
Qun l trng thi
o View state
o Session state
o Cookie
Cross-page Postback
Application
Cng ngh NET 4 HIENLTH
Tng quan
Cng ngh NET 5 HIENLTH
Request Object
Request l mt th hin ca lp HttpRequest, Browserdng Request object gi thng tin cn thit tiServer
Dng c thng tin t client gi ln (header, querystring, cookies, )
Data
Cng ngh NET 6 HIENLTH
Request Object (tt)
Cc thuc tnh
RequestType: tr v phng thc truyn d liu tclient n server gm 2 phng thc POST v GET
C php
valMethod=Request.RequestType
Cng ngh NET 7 HIENLTH
Ly d liu gi i
Request.Form("Phn_t_cn_c"): c gi tr ca mt phn t c gi theo phng thc POST.
Request.QueryString("Phn_t_cn_c"): c gi tr ca mt phn t c gi theo phng thc GET.
Cng ngh NET 8 HIENLTH
Request Object - POST
V d: thit k giao din nh hnh
Cng ngh NET 9 HIENLTH
M giao din
trang 1
username
password
Cng ngh NET 10 HIENLTH
Request Object - POST
V d (tt):Ly gi tr ca UserName v Password trn form
string sUser, sPass;sUser = Request.Form["txtUser"];sPass = Request.Form["txtPass"];//Xut ra mn hnh
Cng ngh NET 11 HIENLTH
Request Object - GET
Ly d liu t cc phn t ca form:
C php:
Nu tham s khng c gi tr th gi tr tr v ca tham s khi s dng Request.QueryString l null.
Request.QueryString[varName]
Cng ngh NET 12 HIENLTH
Request Object - GET
UserName:
Cng ngh NET 13 HIENLTH
Request Object - GET
Ti Server (file CheckUser.aspx), ly gi tr ca UserName v Password
string strUser, strPws;
strUser = Request.QueryString["txtUser"];
strPws = Request.QueryString["txtPass"];
Cng ngh NET 14 HIENLTH
Request Object - GET
Hoc
Tin Gio dc
Var1=Request.QueryString[CatID];//Var1=eduVar2=Request.QueryString[NewsID];//Var2=98708
Ti ReadNews.aspx mun ly gi catID and NewsID, s dng c php:
Cng ngh NET 15 HIENLTH
Demo Query String
To mt ng dng truy cp CSDL GameList gm:
oGameList.aspx: hin th tn tt c cc game c trong database, vi mi game to url dng querystring vi id ca game , user kch vo s m ra trang GameDetail.aspx cho php xem chi tit thng tin ca game
oGameDetail.aspx: ly id t querystring, c CSDL GameList v tr v chi tit tt c thng tin ca game.
Cng ngh NET 16 HIENLTH
Query String
Cng ngh NET 17 HIENLTH
Query String
To trang GameList.aspx
o Trang ny c control l label s hin th danh sch cc tn game.
Label: c id l lblGameList
Cng ngh NET 18 HIENLTH
Query String
Trang GameList.aspx khi thc thi
Danh sch cc tn game ly trong database
Hyperlink xem chi tit ca Thun Thin Kim
Cng ngh NET 19 HIENLTH
Query String
To trang GameDetail.aspx
o Trang ny c 4 label cha cc thng tin chi tit ca game:
Tn game: lblTenGame, nh sn xut: lblNSX, nh pht hnh: lblNPH, th loi: lblTheLoai
Cng ngh NET 20 HIENLTH
Query String
Phn x l ca GameDetail.aspxprotected void Page_Load(object sender, EventArgs e)
{// ly query stringstring sid = Request.QueryString["id"]; // tham s idif (sid != null) // kim tra xem tham s ny c tn ti hay khng{
// truy cap database de lay du lieustring sConn = @"server=.; database=gamelist; trusted_connection=true";SqlConnection conn = new SqlConnection(sConn); // to i tng kt nitry{
conn.Open(); // m kt nistring query = string.Format("select * from DanhMuc where ID={0}",sid);SqlCommand cmd = new SqlCommand(query, conn);SqlDataReader reader;reader = cmd.ExecuteReader(); // thc thi cu truy vn
// phn tip theo trong slide k
Cng ngh NET 21 HIENLTH
Query String
// tip theo ca silde trcif (reader.HasRows) // nu c d liu
{reader.Read(); // c 1 dng d liulblTenGame.Text = reader["TenGame"].ToString();lblNSX.Text = reader["NhaSanXuat"].ToString();lblNPH.Text = reader["NhaPhatHanh"].ToString();lblTheLoai.Text = reader["TheLoai"].ToString();
}reader.Close(); conn.Close(); // ng kt ni
}catch (Exception ex){
Response.Write(ex.Message); // hin th thng bo li}
} // end if (sid !=null)} // end method Page_Load
Cng ngh NET 22 HIENLTH
Query String
Chy demo
id = 5 l m game C Long
Cng ngh NET 23 HIENLTH
Response Object
Response: i tng ny c dng gi ni dung (mt xu) bt k v cho trnh duyt
Phng thc:o Response.Write() dng gi gi tr biu
thc truyn vo cho pha trnh duyt.
o Response.Redirect(a ch URL): Chuyn ti mt trang khc.
Data
Cng ngh NET 24 HIENLTH
Response Object (tt)
Cc phng thc
Response.Clear(): Xa vng tm
C php:
Response.Flush() dng a d liu cn trong b m pha server v cho pha trnh duyt.
Response.End(): Kt thc tin trnh x l trn Server v y d liu ti Client
Response.Clear()
Cng ngh NET 25 HIENLTH
Response Object
Cc thuc tnh
Buffer: c 2 gi tr true v false quy nh cch
truyn ti d liu:
o True: Hon tt cng vic v gi mt ln
o False: Thc hin xong n u th gi n
Cng ngh NET 26 HIENLTH
Server Object
i tng Server cung cp thng tin ca Web server chong dng, bao gm cc phng thc gip chuyn iu khingia cc trang vi nhau, ly thng tin v m li, encode,
Cc thuc tnh
o MachineName: tn server
o ScriptTimeout: thit lp thi gian x l ti a 1 file
V d:
Server.ScriptTimeout = 100s //thit lp thi gian mc nh
Cng ngh NET 27 HIENLTH
Server Object
Cc phng thc
MapPath(URL): nh x ng dn o thnh ng
dn vt l cho mt tp tin trn Server
o C php:
o Path l chui thc hin ng dn tng i ca tp tintrn ng dng Web
o Phng thc s tr v chui hin thc ng dn vt lca tp tin .
Server.MapPath(path)
Cng ngh NET 28 HIENLTH
Server Object
Transfer: gi tt c thng tin m n x l t trang
ASPX hin hnh sang trang ASPX khc. C php:
Trong , tham s path l ng dn ca tp tin ASPX
cn chuyn iu khin.
Lu :
o s dng k hiu ~ ch n ng dn tng i
o s dng k hiu .. ch n ng dn tuyt i
Server.Transfer(path)
Phn bit Server.Tranfer vs Reponse.Redirect
Cng ngh NET 29 HIENLTH
Server Object
HtmlEncode(str): dng m ho HTML thnhchui
C php:
Server.HTMLEncode(str)
Cng ngh NET 30 HIENLTH
Server Object
Khi m ho chui HTML sang chui bnh
thng nu gp cc k t nh sau s chuyn
sang k t tng ng:
o K t chuyn thnh >
o K t & chuyn thnh &
o Du i chuyn thnh "
Cng ngh NET 31 HIENLTH
Server Object
HtmlDecode(strcontent):gii m cc th HTML
V d:
Str = n>5
Str = Server.HtmlDecode(str); // kt qu n>5
Cng ngh NET 32 HIENLTH
Server Object
Phng thc URLEncode: Tng t nhphng thc HTMLEncode, phng thcURLEcode dng m ho URL thnh chui
C php:
Quy tc chuyn:
o K t khong trng chuyn thnh du +
o K t khng thuc k t ch v s s chuyn thnh s hexadecimal
Server.URLEncode(str)
Cng ngh NET 33 HIENLTH
Qun l trng thi
Cng ngh NET 34 HIENLTH
Qun l trng thi
Mi ng dng cn chia s thng tin gia cc request
ASP.NET cung cp cc c ch cho php chia s thng tin gia cc Request:
o Cc i tng qun l trng thi (State) pha client v server.
o C ch Cache
Cng ngh NET 35 HIENLTH
Cc i tng qun l trng thi
Client-based State
o c lu tr my Client
o Gm: ViewStates, Hidden Fields, QueryStrings, Cookies
Server-based State
o c lu tr my Server
o Gm: Session, Application
Cng ngh NET 36 HIENLTH
View state
Cho php lu cc kiu d liu ca .NET
Lu tr client side, trong hidden field ca trang web
Lu tr trong cc ln post back ca trang. Mt d liu khi user nhp vo URL mi
Phm vi gii hn trong mt trang web
Bo mt: mc nh trng thi insecure. Tuy nhin ta c th thit lp page directive m ha
Hn ch: lu tr s lng ln thng tin trong viewstate s lm chm thi gian response v request
Thng dng ci t thng tin c bit no ca page
Cng ngh NET 37 HIENLTH
View state
View state l u tin chn la u tin khi cn lu tr thng tin trong phm vi ca mt trang web
View state cng c s dng bi ASP.NET Web control, cho php cc control ny duy tr nhng thuc tnh gia cc ln postback
C th add d liu vo
view state collection
thng qua thuc tnh
Page.ViewState
int count;if (ViewState["Count"] == null)
count = 0;else
count = (int) ViewState["Count"];count += 1;
ViewState["Count"] = count;
Label1.Text = string.Format("S ln postback {0}", count);
Cng ngh NET 38 HIENLTH
View state
Thun li:
View state khng s dng memory trn server
View state cng khng b rng buc no (nh time out)
Tnh hung hn ch khi s dng view state
Cn thit lu tr d liu c mc nhy cm cao. View state cng c th m ha, nhng session la chn tt hn
Cn thit lu tr thng tin c s dng trong nhiu trang. Trong tnh hung ny ta s dng session, cookie hoc query string.
Cn thit lu tr thng tin ln v khng mun lm chm thi gian truyn ti, nn s dng database, cache hoc session.
Cng ngh NET 39 HIENLTH
Session l g?
User 1
User 2
User 3
Session: user 1Session: user 2Session: user 3
Cng ngh NET 40 HIENLTH
Session l g?
Khi nim phin lm vic Mi khi user request mt trang web ln u tin th
phin lm vic c to ra. Mt nhn dng phin lm vic c cp bi server Phin lm vic kt thc khi
Ngi lp trnh hy Kt thc cycle life (quy nh bi Timeout) User ng trnh duyt
Phin lm vic l cch thc trao i/chia s d liu gia cc trang web trong Web app.
Cng ngh NET 41 HIENLTH
Session
Cho php lu tr d liu kiu .NET
Lu tr trn b nh ca server
Thi gian sng kt thc sau mt khong thi gian nh ngha trc (thng l 20 pht, c th thay i, hoc lp trnh hy)
Phm vi ton b ng dng .NET
Tnh bo mt cao, do d liu lu tr trn server, khng bao gi chuyn cho client v mi client c client session id ring
Lu tr session vi d liu ln cng c th lm chm server, c bit nu nhiu ngi truy cp ng thi, do mi user s c bn copy session ring!
Cng ngh NET 42 HIENLTH
Session
Mi user s c gn mt gi tr gi l Session id, gi tr ny l duy nht
c lu tr trong non-persistent cookie cho n khi trnh duyt ng.
Session state s dng c php collection nh l view state
int count;if (Session["Count"] == null)
count = 0;else
count = (int)Session["Count"];count++;Session["Count"] = count;
int count;if (Session["Count"] == null)
count = 0;else
count = (int)Session["Count"];count++;Session["Count"] = count;
Cng ngh NET 43 HIENLTH
Session cu hnh
Thi gian sng ca session c th thit lp thng qua web.config (n v l pht)
Session c th lm vic m khng cn cookie
Trong trng ny Session ID lu tr trong URL
http://server/(h44a1e55c0breu552yrecobl)/page.aspxhttp://server/(h44a1e55c0breu552yrecobl)/page.aspx
Cng ngh NET 44 HIENLTH
Session
Phng thc
Abandon(): gii phng vng nh c dng duy tri tng Session trn Web Server ngay khi c githc hin. Nhng yu cu sau c Web server coinh l mt ngi dng mi.
Remove(SessionName): xo d liu trn bin VarSession
RemoveAll(): Xo d liu, nhng sessionID vn tn ti
Cng ngh NET 45 HIENLTH
Session
V d: To trang (Page) hoc User Control l Login.aspx
Thit k giao din nh sau:
Cng ngh NET 46 HIENLTH
Session
Khi to v Hu thng tin ng nhp ca ngi dng trong Session
void Session_Start(object sender, EventArgs e)
{
// Tng s khch ving khi c 1 phin lm vic ca user
Application["SoKhachVieng"] = (int)Application["SoKhachVieng"] + 1;
// Thit lp thi gian TimeOut cho mi phin l 30 pht
Session.Timeout = 30;
// t trng thi ban u ca user l cha ng nhp
Session["LOGIN_OK"] = false;
}
Cng ngh NET 47 HIENLTH
protected void btnLogin_Click(object sender, EventArgs e) {
if (Authority(txtUserName.Text, txtPassword.Text)) {
// Lu thng tin ng nhp thnh cng vo SessionSession["LOGIN_OK"] = true; // n chc nng LoginpanelLogin.Visible = false; // Hin th chc nng logout v li cho mng LblGreeting.Text = "Cho mng bn " +
txtUserName.Text + " ng nhp website!"; } else
{ // Lu thng tin ng nhp tht bi vo Session Session["LOGIN_OK"] = false;
} }
Cng ngh NET 48 HIENLTH
Session
protected bool Authority(string user, string pwd)
{
if (user == "admin" && pwd == "12345")
{
return true;
}
return false;
}
Cng ngh NET 49 HIENLTH
Cookie
L mu tin nh (dng chui) dng lu tr thng tin ngi dng trn my ca client (trong b nh hoc file text nh).
Lifetime c thit lp bi ngi lp trnh, c s dng trong nhiu trang v trong cc ln visit site
Phm vi ton b ng dng .NET
Khng bo mt, do ton b d liu c gi cho client. Cookie c th modify d dng.
Tng t nh view state, hn ch ch s dng d liu nh
Thng lu tr thng tin c nhn custom cho website.
Cng ngh NET 50 HIENLTH
Cookie
thit lp mt cookie: To i tng System.Net.HttpCookie To d liu dng chui Add i tng cookie vo i tng Response ca
trang web hin ti
HttpCookie cookie = new HttpCookie(Account");cookie[Username"] = Nguyen Mai Chi";Response.Cookies.Add(cookie);
HttpCookie cookie = new HttpCookie(Account");cookie[Username"] = Nguyen Mai Chi";Response.Cookies.Add(cookie);
Cng ngh NET 51 HIENLTH
Cookie
truy cp cookie S dng i tng Request ly cookie Kim tra xem cookie khc null? Truy cp gi tr cookie qua thuc tnh key
string str = "";HttpCookie cookie = Request.Cookies["Account"];if (cookie != null)
str = cookie["Username"];
string str = "";HttpCookie cookie = Request.Cookies["Account"];if (cookie != null)
str = cookie["Username"];
Cng ngh NET 52 HIENLTH
Cookie
Cookie c phn lm 2 loi Persistent cookies/permanent cookie
Lu tr trong a cng ca client cho n khi ht hn, dng cookie ny c thit lp ngy ht hn (expiration date)
Non persistent cookie/temporary cookie Khng nh ngha thi gian ht hn, cookie c lu tr
trong browser memory, kt thc khi ng trnh duyt!
Khng c s khc nhau khi s dng persistent v non persistent cookie
Cng ngh NET 53 HIENLTH
Cookie
Khai bo Persistent cookie
HttpCookie cookie = new HttpCookie("Account");cookie["Username"] = "Nguyen Mai Chi";cookie["email"] = [email protected]";// khai bo thi gian ht hn cho cookiecookie.Expires = DateTime.Now.AddDays(5);// add cookie vo response ca trang webResponse.Cookies.Add(cookie);
HttpCookie cookie = new HttpCookie("Account");cookie["Username"] = "Nguyen Mai Chi";cookie["email"] = [email protected]";// khai bo thi gian ht hn cho cookiecookie.Expires = DateTime.Now.AddDays(5);// add cookie vo response ca trang webResponse.Cookies.Add(cookie);
Cng ngh NET 54 HIENLTH
Cross-page Postback
Cross page postback l dng postback gi ti trang khc
Cc button control nh Button, ImageButton v LinkButton u c thuc tnh PostBackUrl
s dng Cross-page postback Thit lp PostBackUrl cho web form cn chuyn
n Khi user click vo button Page s c gi ti URL mi vi tt c cc gi tr
ca cc control trong trang hin thi.
Cng ngh NET 55 HIENLTH
Cross-page Postback
Trang cross page c th truy cp trang trc thng qua thuc tnh PreviousPage
protected void Page_Load(object sender, EventArgs e){
if (PreviousPage != null){
lblInfo.Text = "You came from " +PreviousPage.Header.Title;
}}
protected void Page_Load(object sender, EventArgs e){
if (PreviousPage != null){
lblInfo.Text = "You came from " +PreviousPage.Header.Title;
}}
Cng ngh NET 56 HIENLTH
Cross-page Postback
truy cp chi tit hn, cc gi tr ca control trn form, th cn phi gn tham chiu PreviousPage cho lp page tng ng
Ta c th add thuc tnh vo trang ngun v c chng trang ch.
if (PreviousPage != null) {SourcePage prevPage = PreviousPage as
SourcePage;if (prevPage != null){
lblInfo.Text = "Welcome" + prevPage.NameEntry;}
}
if (PreviousPage != null) {SourcePage prevPage = PreviousPage as
SourcePage;if (prevPage != null){
lblInfo.Text = "Welcome" + prevPage.NameEntry;}
} Tn lp ca trang source
Thuc tnh ca lp SourcePage
Cng ngh NET 57 HIENLTH
Cross-page Postback
Minh ha cross-page Postback
To 2 trang SendInfo.aspx: cha form nhp thng tin user TargetPage.aspx: ly thng tin t user t
SendInfo.aspx v hin th ln trnh duyt.
Cng ngh NET 58 HIENLTH
Cross-page Postback
M t control ca trang SendInfo.aspx
Id control Kiu control Thuc tnh Din gii
txtUsername TextBox Nhp tn user
txtEmail TextBox Nhp a ch email
txtCompany TextBox Nhp tn cng ty
btnPostInfo Button PostBackUrl = ~/TargetPage.aspx
Button thc thi thao tc Cross Page Postback
Cng ngh NET 59 HIENLTH
Cross-page Postback
Khai bo thuc tnh PostBackUrl cho button btnPostInfo
Khai bo URL cho PostBackUrl
Cng ngh NET 60 HIENLTH
Cross-page Postback
M t trang TargetPage.aspx Ly thng tin t SendInfo.aspx v hin th ra
trnh duyt
Id control Kiu control Thuc tnh Din gii
lblUsername Label - Hin th tn user
lblEmail Label - Hin th email
lblCompany Label - Hin th cng ty
Cng ngh NET 61 HIENLTH
Cross-page Postback
Phn x l ca TargetPage ly thng tin t SourcPage.aspx
protected void Page_Load(object sender, EventArgs e) {// ly thng tin t previous pageif (PreviousPage != null) {
// bin i tng source tham chiu n previous pageSendInfo source = PreviousPage as SendInfo;
// ly cc control ca previous page (SourcePage.aspx)TextBox username = (TextBox) source.FindControl("txtUsername");TextBox email = (TextBox) source.FindControl("txtEmail");TextBox company = (TextBox)source.FindControl("txtCompany");
// gn thng tin cho cc labellblUsername.Text = username.Text;lblEmail.Text = email.Text;lblCompany.Text = company.Text;
} // end if} // end method Page_Load
ID ca control trong SendInfo.aspx
SendInfo l class page ca SendInfo.aspx
Cng ngh NET 62 HIENLTH
Application
i tng Application c s dng qun l
tt c cc thng tin ca mt ng dng web, bao
gm cc file, trang web, s kin, module v code
trong th mc web o(virtual directory) v cc th
mc con ca n.
Application chia s thng, ngha l mt Application
sau khi khi to th mi ngi s dng c th truy
cp i tng ny.
Cng ngh NET 63 HIENLTH
Application vs Session
Application:
o Chia s d liu cho tt c ngi dng ca mt ng dng (d liu ton cc, a ngi dng)
Session:
o Chia s d liu cho nhiu Web Form trong cng mt Session
o Ch c Session hin hnh mi c kh nng truy cp thng tin Session ca chnh n.
Cng ngh NET 64 HIENLTH
S kin Application v Session
Application_Start: Ngi dng u tin ving thm 1 trang web trong ng dng web c gi.
Application_End: Khi ng dng web kt thc (khng c ngi dng no m trang web ca ng dng)
Application_Error: Xy ra khi c li trong ng dng
Session_Start: Mt ngi dng mi, gh thm 1 trang web ca ng dng
Session_End: Ngi dng ng trnh duyt hoc sau mt khong thi gian timeout khng request ln ng dng
Cng ngh NET 65 HIENLTH
Application
Khi to:
i tng Application c to khi client yu cu bt k trang no trong ng dng
Application.Lock();
Application[TenBien] = Value ;
Application.UnLock();
Cng ngh NET 66 HIENLTH
Application
Ly gi tr:
= Application[tn bin];string s = (string) Application[chuoi] ;
int count = (int) Application[count] ;
Cng ngh NET 67 HIENLTH
V d dng Application
c s lt truy cp, s ngi online
Cng ngh NET 68 HIENLTH
THE END