Request Response Ispostback Uiculture Uniqueid: Typical Use

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Stage Description

Page request The page request occurs before the page life cycle begins. When the page is requested by a user, A
needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached versi

Start In the start stage, page properties such as Request and Response are set. At this stage, the page also
postback or a new request and sets the IsPostBack property. The page also sets the UICulture prop

Initialization During page initialization, controls on the page are available and each control's UniqueID property
emes are also applied to the page if applicable. If the current request is a postback, the postback da

Load During load, if the current request is a postback, control properties are loaded with information rec

Postback event If the request is a postback, control event handlers are called. After that, the Validate method of all
handling

Rendering Before rendering, view state is saved for the page and all controls. During the rendering stage, the p
the page's Response property.

Unload The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to

Page Event Typical Use

PreInit Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
Check the IsPostBack property to determine whether this is the first time the page is being processed.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.
Read or set profile property values.
Note
If the request is a postback, the values of the controls have not yet been restored from view state. If

Init Raised after all controls have been initialized and any skin settings have been applied. The Init even
Use this event to read or initialize control properties.

InitComplete Raised at the end of the page's initialization stage. Only one operation takes place
between the Init and InitComplete events: tracking of view state changes is turned on. View state tracki
tracking is turned on, any values added to view state are lost across postbacks. Controls typically tu
Use this event to make changes to view state that you want to make sure are persisted after the nex

PreLoad Raised after the page loads view state for itself and all controls, and after it processes postback data
Load The Page object calls the OnLoad method on the Page object, and then recursively does the same for ea
of the page.
Use the OnLoad event method to set properties in controls and to establish database connections.

Control events Use these events to handle specific control events, such as a Button control's Click event or a TextBox co
Note
In a postback request, if the page contains validator controls, check the IsValid property of the Page an

LoadComplete Raised at the end of the event-handling stage.


Use this event for tasks that require that all other controls on the page be loaded.

PreRender Raised after the Page object has created all controls that are required in order to render the page, inc
page.)
The Page object raises the PreRender event on the Page object, and then recursively does the same for ea
Use the event to make final changes to the contents of the page or its controls before the rendering

PreRenderComplete Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For

SaveStateComplete Raised after view state and control state have been saved for the page and for all controls. Any cha

Render This is not an event; instead, at this stage of processing, the Page object calls this method on each co
browser.
If you create a custom control, you typically override this method to output the control's markup. H
do not need to override the Rendermethod. For more information, see Developing Custom ASP.NET Server Con
A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly

Unload Raised for each control and then for the page.
In controls, use this event to do final cleanup for specific controls, such as closing control-specific
For the page itself, use this event to do final cleanup work, such as closing open files and database
Note
During the unload stage, the page and its controls have been rendered, so you cannot make further
an exception.

1. ASP>NET MVC
2. OPEN SOURCE!
Nu este/nu înlocuiește ASP.NET WebForms!
EXTENSIBIL, TESTABIL, FLEXIBIL
Friendly URLs (Url Routing)
Stadiul curent: ASP.NET MVC 2 RC 2
Suport IDE: Visual Studio 2008 SP 1 / Visual Studio 2010 (inclus)
Dezvoltat peste: .NET Framework 3.5
3. ASP.NET MVC - Execuție
http://domain.ro/sayhello
Domain
Controller (acțiune)
Request
Model
View
Response
Model
4. Ce-i nou în ASP.NET MVC 2?
Html.RenderAction
Areas
Templates
Model Validation
Asynchronous Controllers
5. Html.RenderAction
Îmbunătățește implementareapattern-uluiMVC permițând apelul unei acțiuni dintr-un VIEW, rezultatul fiind afișat
direct în VIEW.
6. Html.RenderAction
Html.RenderPartial

o generează UI direct

Html.RenderAction

o generează UI prin intermediul unui controller

(nou în ASP.NET MVC 2)


7. Areas
Partiționează o aplicație mare în secțiuni (care pot fi dezvoltate independent) reducând complexitatea aplicației.
AreaRegistration.RegisterAllAreas()
8. Templates
Asociază tipurilor de date simple (int, string, ..) sau complexe (clase…) template-uri pentru vizualizarea sau editarea
lor.
9. Templates
Metode pentru vizualizare
Html.Display()
Html.DisplayFor()
Html.DisplayForModel()
Metode pentru editare
Html.Editor()
Html.EditorFor()
Html.EditorForModel()
10. Templates
class ModelMetadata {…}
ConvertEmptyStringToNull, DataTypeName , Description, DisplayFormatString, DisplayName, EditFormatString,
HideSurroundingHtml, IsComplexType, IsNullableValueType, IsReadOnly, IsRequired, NullDisplayText,
ShortDisplayName, ShowForDisplay, ShowForEdit, SimpleDisplayText, TemplateHint, Watermark
11. Templates
Influențează metadata modelului
[HiddenInput](System.Web.Mvc)
[UIHint],[DataType],[ScaffoldColumn], [DisplayFormat] (System.ComponentModel.DataAnnotations)
[ReadOnly],[DisplayName] (System.ComponentModel)
12. Templates
Moduri de specificare / Ordine de selectare
[UIHint(“MyPropertyTemplate”)]
DataTypeName (ModelMetadata)
Numele tip-ului de date (String, DateTime, Person, …)
Dacă obiectul nu e complex -> String
Dacă e complex și e interfață -> Object
Dacă e complex și nu e interfață se caută în ierarhie un tip valid
(direct) Html.DisplayForModel(“MyTemplate.ascx”);
13. Templates
DEMO
14. Validation Security?
15. Model Validation
Oferă suport îmbunătățit și extensibil de validare la nivel de server și client.
Input Validation a devenit Model Validation.
16. Model Validation
Providers

o Data Annotation (implicit)

o Enterprise Library Validation Block

o Castle Validator

o XML

o …

17. Model Validation


Data Annotation Validators

o Required

o Range

o RegularExpression
o StringLength

o CustomValidator

18. Altenoutăți în ASP.NET MVC 2


Securitate
HTML Encoding Syntax
<%: Model.NewPostByEvilPerson %>
JsonResult
Performanţă
AsynchronousController Actions
Default Parameters pentru Controller Actions, 
RESTfull support: HttpPost, HttpGet, HttpDelete, HttpPut, 
RequiresHttps, Value Providers, Strongly-Typed Html Helpers
19. Să recapitulăm, noutăți în ASP.NET MVC 2?
Html.RenderAction
Areas
Templates
Model Validation
Asynchronous Controllers

Pe scurt ViewState reprezinta date ce pot fi salvate in pagina web si trimise la client. ViewState este una
din metodele ce permite ca protocolul HTTP sa aiba stari. Celelalte metode sunt hidden fields, cookies si
parametri in adresa. In ViewState se pot salva obiecte serializabile(string, int, double, dataset), dar si
clase realizate de tine. Nu trebuie abuzat de ViewState pentru ca paginile se pot incarca foarte greu.
Cand dai click dreapta in pagina *.aspx si vezi tagul ViewState acolo sunt salvate datele tale. Daca vrei sa
faci o clasa si o sa salvezi in ViewState ii scrii [Serializable] inaintea declararii ei. Mai mult orice obiect din
clasa ta trebuie sa fie serializabil.
Nu poti salva socketi, Obiecte remote in ViewState.

ViewState e un camp hidden de forma:


<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
value="/wEPDwUJMjgzMDgzOTgzZGQJxOsir4ub7qxJucVwfxj5nBYdSg= =" />
care pastreaza toate informatiile din campuri la refresh. Adica daca completezi orice form si dai refresh,
de obicei la PHP pierzi tot ce ai scris, in ASP.NET nu. M-ar fi interesat asta si in PHP.

PostBack e de fapt o proprietate AutoPostBack care daca e pusa enabled pe orice camp care o suporta,
imediat ce un text dintr-un input sau un checkbox, sau un radiobutton care s-a schimbat, pagina isi face
refresh automat si se pot face diverse operatii in acel moment.
Exemplu:
Daca am un TextBox (<input name="TextBox1" type="text" value="blabla"
onchange="javascript:setTimeout('__doPostBack(\'Te xtBox1\',\'\')', 0)" onkeypress="if
(WebForm_TextBoxKeyHandler(event) == false) return false;" id="TextBox1" />)
si daca schimb textul din acel camp si ies cu focusul din el (de ex cu un tab), pagina ia acea valoare noua
pe care am scris-o, isi face refresh prin postback, executa anumite functii date de tine la eventul
onchange, apoi cand revine pune si textul inapoi in acel camp. Fara niciun pic de JavaScript scris, doar
cateva optiuni bifate (unele pornite by default), si fara niciun buton pe form.

ASP-urile se utilizeaza pentru:


· Editarea dinamica, schimbarea sau
adaugarea de continut la o pagina Web;
· Generarea de raspunsuri cererilor utilizatorilor
sau informatiilor trimise prin
formularele HTML;
· Accesarea oricarei date sau baze de
date si returnarea de rezultate catre navigator;
· Personalizarea paginilor Web, facândule
mai utile pentru utilizatori particulari;
· Simplitatea si viteza de executie a ASP
fata de CGI si Perl;
· Asigurarea securitatii, deoarece codul
ASP nu este vizibil prin navigator;
· Posibilitatea de a fi afisate de orice
navigator, fisierele ASP sunt returnate în
format HTML;
· Minimizarea traficului prin retea.

Obiecte ASP predefinite


Pentru a utiliza marea majoritate a obiectelor
existente, un program trebuie mai
întâi sa creeze o instanta a acelui obiect.
ASP furnizeaza cinci obiecte care nu necesita
instantierea. Aceste obiecte sunt:
· Request furnizeaza informatia venita de
la clientul HTTP care a initiat cererea;
· Response trimite informatie catre client;
· Server controleaza mediul de executie
ASP;
· Session contine informatii legate de sesiunea
de lucru cu server-ul Web, deschisa
de un client;
· Application contine informatii globale despre
aplicatia care poate fi accesate de catre
mai multi clienti.

Obiectul Page
Reprezinta pagina web pe durata unei executii pe server. La fiecare request al unei pagini aspx, asp.net
compileaza fisierul si creaza un obiect Page care va fi container pentru toate controalele.
O pagina trece printr-o serie de evenimente intr-un ciclu de viata:
? Init
? Load
? Render
Proprietati ale paginii:
? Controls – o colectie de controale care reprezinta toate controalele de pe pagina
? IsPostBack – false daca este primul request, true altfel
? User – informatii despre vizitatorul curent
? ViewState – un dictionar care contine informatii despre starea controalelor si care este
actualizat intre request-uri
Page.Request contine informatii despre cererea HTTP. Cateva proprietati utile ale acestui obiect sunt:
? QueryString – colectie care contine parametrii trimisi prin url
? UserAgent – browserul folosit
? UserHostAddress – ip-ul vizitatorului
Obiectul Page.Request este de tipul HttpRequest.

Page.Response ofera acces la anumiti parametri ai raspunsului HTTP care va fi furnizat browserului. Spre
exemplu: MIME-Type, Cookies. Alte metode utile sunt:
Response.Write() si Response.Redirect() .
Web Forms, Web Controls
Este un model imbunatatit al formularelor HTML. Fiecare pagina aspx trebuie sa contina un
, in care vor sta toate controalele.
Controalele asp.net se scriu asemanator controalelor HTML. Ele au atributul runat=”server”. Acest
atribut va spune serverului ca acela este un control
asp.net si va ajuta la interpretarea lui. Tagurile au nume care incep cu “asp:”.
Exemplu:
Acest tag va determina crearea unui membru de tipul System.Web.UI.WebControls.TextBox, numit
TextBox1, in clasa care sta in spatele paginii aspx si care deriva din System.Web.UI.Page.
In momentul in care se va randa continutul HTML ce va fi servit clientului, pentru acest control va fi creat
un .
Continutul HTML care va fi randat nu este controlat de programator. Acest lucru constituie un avantaj
major( din cauza diferentelor dintre browsere).

ASP.NET este o tehnologie Microsoft pentru crearea de aplica?ii web ?i servicii web.
ASP.NET este succesorul lui ASP (Active Server Pages) ?i beneficiaza de puterea platformei de
dezvoltare .NET,
?i de setul de instrumente oferite de mediul de dezvoltarea al aplica?iei „Visual Studio .NET”.
Cateva dintre avantajele ASP .NET sunt:
-ASP .NET are un set larg de componente, bazate pe XML, oferind astfel un model de programare
orientat obiect (OOP).
-ASP .NET ruleaza cod compilat, ceea ce cre?te performan?ele aplictiei web. Codul sursa poate fi separat
în doua fi?iere,
unul pentru codul executabil, iar un altul pentru continutul paginii (codul HTML ?i textul din pagina) .
-.NET este compatibil cu peste 20 de limbaje diferite, cele mai utilizate fiind C# si Visual Basic.

Benefits Of Design Patterns


- Capture expertise and make it accessible to non-experts in a
standard form
- Facilitate communication among developers by providing a
common language
- Make it easier to reuse successful designs and avoid alternatives
that diminish reusability
- Facilitate design modifications
- Improve design documentation
- Improve design understandability

Creational Patterns
• Abstract Factory:- Creates an instance of several families of classes
• Builder: - Separates object construction from its representation
• Factory Method:- Creates an instance of several derived classes
• Prototype:- A fully initialized instance to be copied or cloned
• Singleton:- A class in which only a single instance can exist
Note: - The best way to remember Creational pattern is by remembering ABFPS (Abraham Became First
President of States).

Structural Patterns
• Adapter:-Match interfaces of different classes .
• Bridge:-Separates an object’s abstraction from its implementation.
• Composite:-A tree structure of simple and composite objects.
• Decorator:-Add responsibilities to objects dynamically.
• Façade:-A single class that represents an entire subsystem.
• Flyweight:-A fine-grained instance used for efficient sharing.
• Proxy:-An object representing another object.
Note : To remember structural pattern best is (ABCDFFP)

Behavioral Patterns
• Mediator:-Defines simplified communication between classes.
• Memento:-Capture and restore an object's internal state.
• Interpreter:- A way to include language elements in a program.
• Iterator:-Sequentially access the elements of a collection.
• Chain of Resp: - A way of passing a request between a chain of objects.
• Command:-Encapsulate a command request as an object.
• State:-Alter an object's behavior when its state changes.
• Strategy:-Encapsulates an algorithm inside a class.
• Observer: - A way of notifying change to a number of classes.
• Template Method:-Defer the exact steps of an algorithm to a subclass.
• Visitor:-Defines a new operation to a class without change.

You might also like