14
SQL .Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location: 1st Széchenyi str. 7666 Pogány, Hungary Tel: +36-309-015-488 E-mail: pauler @ t-online.hu

SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

Embed Size (px)

Citation preview

Page 1: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

SQL .Net ConsultationLesson 2

Dr. Gábor Pauler, Associate Professor, Private Entrepeneur

Tax Reg. No.: 63673852-3-22Bank account: 50400113-11065546

Location: 1st Széchenyi str. 7666 Pogány, HungaryTel: +36-309-015-488

E-mail: [email protected]

Page 2: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

Content of LessonChecking Home Assignment 1-1: Describe your own objectCreating basic webforms in .Net• Objects and sequence of client-server communication• ASPX Form Control Objects• Session object• Transferring data between Pages using Session object• Input individual data, validate on server, send back output• Cross-validation of interlinked inputs on multiple PanelsHome Assignment 2-1: Cross-Page Validation

Page 3: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

Objects and sequence of client-server communicationSystem.Web.UI.Page object: It represents a dynamic webform (Dinamikus weblap) containing

form controls (Űrlap vezérlők) (eg. textbox, check box, listbox, etc.) • It reacts intelligently on user’s action (data entry, using controls, etc.) with the help

ASPX code embedded into an (otherwise static) HTML page code• It does all processing on server’s side, applying thin-client concept (Egyszerű kliens)

(see Session1): clients need only a web browser and no any other software installation• Depending on data collected about user actions on form at client’s side, the dynamic

page on server’s side is translated into a series of static HTML-pages with actualized content, reflecting those actions, and send back to client. This creates the illusion that the thin client intelligently reacts on user response, but it just shows series of static pages generated by server in a rapid sequence

• As users activity on client is not continous, but occours relative scare points of time, server-side page object is destroyed after each communication (however backing up the changed things on the page), releasing occupied resources and enable the server to serve another clients building up their required page

• Properties (only the most important ones are described):• .IsPostBack As Boolean:read only, signals that the pa-

ge was posted back from client, it is not the first load up• Events of Page object reflect the main stages of communica-

tion between server and client:• .PostBack: page was posted back from client with data

changes stored in a collection in .Request object. This event occours only if the page was sent to client earlier!

• .Init: check conditions of (re)building page on server• .Load: reserve resources for (re)building page on server• .PreRender: step before server starts to build up static HTML from current ASPX page• .RenderComplete: Static HTML page assembled with actualized content,

• Changes sent to client in a collection in .Respose object, • Changed parts of form control objects on the page is saved in a collection at

Session object, enabling server remembering changes of the page at next build-up• Then page object is destroyed on server

• .Unload: release resources of the page, enabling server to serve other clients also

Clie

ntSe

rver

IsPost-back?

Init LoadPre-

RenderRender-Comple

UnloadPost-Back

IsPo

stBa

ck?

Upda

te c

han-

ging

con

tent

Get

sto

red

da-

ta fr

om S

essi

on

Load

AS-

PX p

age

Prep

are

HT-

ML

page

Res

pons

e a

rrive

sDe

stro

y AS

PXSa

ve S

essi

on

Send

Req

uest

User

act

ion?

Init

HTM

LPa

ge

Page 4: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

ASPX Form Control Objects 1Embedded objects of Page object: • .Request Object: stores data changes occured at client at .PostBack event• .Response Object: stores data changes of ASPX Form Page Object sent to Client

at .RenderComplete eventUsing these objects, we can save lot of bandwidth in client-server communication, because there is no need to send sizeable page contents (pictures, sounds) at every refresh, just the changed things! Both objects have the following properties:• .Cookies.AllKeys As Dictionary: unique identifier-named collection (see Session2) of

all objects/properties changed in the communication. It is generated automaticallyControl Objects embedded into ASPX Form:• Functional parts of an ASPX Form: Textbox, Label, Checkbox, DropDownList, Button, etc.• Important common properties:

• .AutoPostBack As Boolean: the control contacts back to server with user response automatically. In general, it is not recommended to set it for data controls: eg. several Textbox controls on a Page should just store user input and a submit Button will post-back the whole page – it needs less bandwidth. Some cases autopostback is useful.

• .EnableViewState As Boolean: automatically save control data into Session object in compressed form

• Important common events are nearly the same as Page object’s:• .Init: check conditions of launching• .Load: reserve resorces• .PostBack: contact back to server with user response• .Unload: release resources

• Controls can be created pulling them with mouse from control toolbox (see Lesson1) at ASPX form editor (see their symblols), or from code with .Add method of corresponding control collection of Page object. The most important controls are:Button Object: button generating automatic .PostBack event. Most important properties:• .Text As String: button caption text• .Tooltip As String: short pop-up help text moving mouse over

Label Object: text label box. Its most important properties:• .Text As String: text to show

TextBox Object: text input box. Its most important properties:• .Text As String: input text• .Tooltip As String: short pop-up help text moving mouse over

pullpull

pullpull

Page 5: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

ASPX Form Control Objects 2Required Field Validator Object:

• Checks whether an input control object is filled by user, • Shows error message if user tries to submit page with unfilled control, • Usually placed after or below the checked control on page. Its most important properties:

• .ControlToValidate As Object: which input control is checked• .EnableClientScript As Boolean: validation code should run on client not server, it

requires less bandwith but more client capacity, and gives faster error signal• .ErrorMessage As String: error message text• .Tooltip As String: short pop-up help text moving mouse over

Range Validator Object:• Checks whether a text/numeric entry in an input control falls in a specific range• Shows error message if user tries to submit page with unfilled control, • Usually placed after or below the checked control on page. Its most important properties:

• .ControlToValidate As Object: which input control is checked• .EnableClientScript As Boolean: validation code should run on client not server• .ErrorMessage As String: error message text• .Tooltip As String: Short pop-up help text moving mouse over• .Type As Enum: primitive type of control value to evaluate (Integer, Double, String)• .Maximum/MinimumValue As String: we can define static range bounds, always as

string, regardless the checked control value type! (Don’t forget to use .ToString method of other primitive types to convert them into string). Dynamic bound (Dinamikus értékhatár) definition (when input in one control may change range bound of other control - eg. If Gender = Men, NumberOfPregnancy should be = 0) can be resolved only from manual coding attached to Load event handler of Range Validator (use top listboxes at VB coding window to select the object and its event to create the nasty-looking event handler sub header automatically – see Lesson1):Protected Sub RangeValidatorNameLoad( _ByVal Sender As Object, _ByVal e As System.EventArgs) _

Handles RangeValidatorName.LoadIf Page.IsPostBack Then ’If not first load of page RangeValidatorName.MaximumValue=OtherControl.Value.ToStringEnd If ’If not first load of page

End Sub ’RangeValidatornameLoad

Page 6: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

ASPX Form Control Objects 3Panel Object: container for grouping several controls making them .Visible or not and .Enabled or not in the same time. It is pretty useful if we have a large webform with many controls (eg. an electronic Market Research Survey questionnaire), and values of controls heavily affect each others range or fillout validation:

• We should group controls on the form into consecutive Panels according to which is precondition of which (eg. Gender should go in Panel1 and NumberOfPregnancies should go on Panel2)

• The next panel should be invisible or disabled (printed in grey) until the current panel is not finished and submitted

• When user submits the current one and goes to next panel valid according to his previous answers, last panel should be shown disabled

• This way, we can avoid that if a „blondie woman” user tries to fill up controls of a complex webform in random sequence then she will enter into endless cycles of range- and incomplete fill errors. With breaking into panels alongside validation, the form will be very foolproof

• The same effect can be achieved if we break up the content into several independent Pages and submit buttons navigate between them, or placing more Frame objects on a page (technically, they are Page objects also nested in the main page). However, these solutions require much more machine resources and bandwith than using panels. Moreover, panels can be more flexibly sized, allowing only 1 or 2 controls / panel, if the logic structure of the questionnaire requires it. Panels most important properties:• .Visible As Boolean: it can be seen or not. Embedded controls inherit this setting: they

shift visibility with panel• .Enabled As Boolean: ebedded controls are enabled or not

Session Object: it stores data of ASPX Form Control objects during communication cycles of server with client. This is necessary, because Page on server is destroyed after sending changes to client in .Response object. Its most important methods are:

• .Add(Key As String, StoreSomething As Object): we can manually add a .Key to Session to store some change in any object/property, partial result of computation, which should be preserved during server-client communication, even if Page object is destroyed. This is automatically done for data of all control objects where .ViewState=True

• .Item(Key)=Value: changes value of a stored key. If there is no such a key, it creates thatEvents:• .SessionStart: a client with a static or dynamic IP address contacts server first time• .SessionEnd: a client ceases to communicate, so server drops session after a timeout

„I don’t have time to read through all this shit…”

Page 7: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

Content of LessonChecking Home Assignment 1-1: Describe your own objectCreating basic webforms in .Net• Objects and sequence of client-server communication• ASPX Form Control Objects• Session object• Transferring data between Pages using Session object• Input individual data, validate on server, send back output• Cross-validation of interlinked inputs on multiple PanelsHome Assignment 2-1: Cross-Page Validation

Page 8: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

PRACTICE 2-3: Transferring data between Pages using Session object (0.5pts)TASK: Transfer ( ) a text given in a textbox at

PageMain to a textbox at PageSub clicking a hyperlink, then return to PageMain clicking another hyperlink, but do not transfer back modifications from PageSub

SOLUTION:(See PageMain.aspx,PageSub.aspx To see and edit these samples in Visual Studio, you should copy both linked *.aspx files as well as their corresponding *.aspx.vb code files into the root directory of an existng web application, Right-click on Web application in Solution explorer and select Add existing element from popup menu. Alternatively, you can copy them to a web directory of a web-server, just to check out their working)

Create PageMain, PageSub, on PageMain:• Create TextBoxName

• .Text=”Write here something” – this is the initial text in the TextBox

• .AutoPostBack=True ( ) – we need this because we have only 1 TextBox on page: TextBox records text input only if: user presses Enter, or shifts to another control, or it is AutoPostBack

• Create HyperLinkPageSub.Text=”PageSub”,.NavigateUrl=”~/PageSub.aspx”

• On PageSub:• Create TextBoxNameSub.Text=””• Create HyperLinkPageMain

.Text=”PageMain”,

.NavigateUrl=”~/PageMain.aspx”

Unload

Load

Session:TextBoxName .Text=„Write..”

ClickClick

Session:TransferName=„Write..”

ClickClick

Unload

Load

Write here something

Coding in PageMain.aspx.vb code editor:• Create PageMain.Unload event handler:

Session.Item(„TransferName”)= _TextBoxName.Text ‘Save into Session

Coding in PageSub.aspx.vb code editor:• Create PageSub.Load event handler:

TextBoxNameSub.Text= _Session.Item(„TransferName”) ‘Retrieve saved data from Session by name

Page 9: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

PRACTICE 2-4: Input individual data, validate on server, send back output (0.5pts)TASK: Input year of birth on input panel,

output current age on output panelSOLUTION: (see PageInpOut.aspx)Create PageInpOut, on PageInpOut:Create PanelInput.Visible=True, ( )

PanelOutPut.Visible=False ( )On PanelInput:• Write text „What is your year of birth?”• Create TextBoxBirthYear• Create ButtonSubmit.Text=”Submit”

(Button control always posts back! )• Create RequiredFieldValidatorBirthYear

• .ControlToValidate= TextBoxBirthYear, • .ErrorMessage=”Required!”,

• Create RangeValidatorBirthYear• .ControlToValidate= TextBoxBirthYear, • .ErrorMessage=”Integer,1900..current year”, • .MinValue=”1900”, • .Type=Integer,

On PanelOutput:• Write text „Your age:”• Create LabelAge• Create ButtonNewQuery.Text=”NewQuery >”Coding in PageInpOut.aspx.vb code editor:• Create RangeValidatorBirthYear.Load event

handler:If Not Page.IsPostBack Then

RangeValidatorBirthYear.MaximumValue= _Year(Now()).Tostring ’MUST convert it!

End If• As maximum value of range validator – the current

year - is not influenced by user responses, to save processor time, we set it ONLY at the first load of the page, when it is not posted back from client yet

• Validators normally run only at posting back the page. If you want to force immediate validation, you should set TextBox.CausesVali-dation for just validate this one or .AutPostBack for validate all stuff

• Create ButtonSubmit.Click event handler:

LabelAge.Text=Year(Now())- _Cint(TextBoxBirthYear.Text)PanelInput.Visible=FalsePanelOutput.Visible=True

We can make here necessary computations and shifting visibility between I/O panels: it is much more convenient than setting visibility of many controls 1 by 1

• Create ButtonNewQuery.Click event handler:

TextBoxBirthYear.Text=””PanelInput.Visible=TruePanelOutput.Visible=False

It clears input textbox and shifts visibility back

ClickClick

1971

37ClickClick

Page 10: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

PRACTICE 2-5: Cross-validation of interlinked inputs on multiple Panels 1 (1pts)TASK: Ask for Gender first, then for Actual penis

size (inches) If Male, it can be 0..15, otherwise 0. Then ask for Required penis size (inches). It can be Actual..15. Depending on Difference = Required-Actual, recommend penis enlarge-ment devices:0-No,1-Diet,2..4-Pill,>4-Prothesis

SOLUTION: (see CrossValidInp.aspx)Break up plan of a difficult form into sections (Szekció): group of controls placed on one Pa-nel, which have no validation interdependencies inside section, and values of last section’s con-trols (eg. Gender) determine validation of next section’s controls (eg. Actual penis size), in the fillup logical sequence (Kitöltési Logikai Sor): most independent section comes first, most de-pendent section comes last

Create Page CrossValidInp. On this Page:• Create PanelInput1.Enabled=True ( )• Create PanelInput2.Enabled=False ( )• Create PanelInput3.Enabled=False• Create PanelResult.Enabled=FalseControls and validators on separate input panels

are set in separate .ValidationGroups (Validá-ciós csoport): they are validated together if any member initiates validation, even if there is no postback. Their names: ValGrInp1..ValGrInp3

On all input panels, data controls are created:• On PanelInput1, create DropDownListGender

• .Item={„Undetermined”,”Male”,”Female”} always the first item is the default!

• On PanelInput2, create TextBoxActSize• On PanelInput3, create TextBoxReqSize• Set .CausesValidation ( ) for all of them• Set their .ValidationGroups respectively!

Page 11: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

PRACTICE 2-5: Cross-validation of interlinked inputs on multiple Panels 2For all data controls, validators ar created:• For DropDownList, CompareValidatorGender

• .ControlToValidate=DropDownListGendr• .Operator=NotEqual• .ValueToCompare=Undetermined

• For TextBoxActSize, RequiredValidatrActSize• .ControlToValidate=TextBoxActSize,• .ErrorMessage=”Required!”,

• For TextBoxActSize, RangeValidatorActSize• .ControlToValidate=TextBoxActSize,• .ErrorMessage=”0..15”,• .Type=Integer,• .MinimumValue=0 (Max is set in code)

• For TextBoxReqSize, RequiredValidatrRqSize• .ControlToValidate=TextBoxReqSize,• .ErrorMessage=”Required!”,

• For TextBoxReqSize, RangeValidatorReqSize• .ControlToValidate=TextBoxReqSize,• .ErrorMessage=”Actual..15”,• .Type=Integer,• .MaximumValue=15(Min is set in code)

Set .ValidationGroup of validators respectively!On all input panels, submit buttons are created:• For PanelInput1, create ButtonInp1Next In

its .Click event handler we update range validators of the next panel and flip enabled/ disabled status between last/next panel:

• For PanelInput2,create ButtonInp2Next Its .Cli-ck event handler does similar things as the last:

With Me.RangeValidatorReqSize .MinimumValue=Me.TextBoxActSize.Text .ErrorMessage=.MinimumValue + "..15"End WithMe.PanelInput2.Enabled = FalseMe.PanelInput3.Enabled = True

ClickClick

10

12

MaleClickClick

ClickClick

With Me.RangeValidatorActSize If Me.DropDownListGender. _ SelectedItem.Text = "Male" Then .MaximumValue = "15" .ErrorMessage = "0..15" Else .MaximumValue = "0" .ErrorMessage = "0..0" End IfEnd WithMe.PanelInput1.Enabled = FalseMe.PanelInput2.Enabled = True

Page 12: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

PRACTICE 2-5: Cross-validation of interlinked inputs on multiple Panels 3• For PanelInput3, create ButtonInp3Next

Its .Click event handler computes the output and flips enabled status to PanelResult:

Dim SizeDiff As IntegerSizeDiff=CInt(Me.TextBoxReqSize.Text)_ -CInt(Me.TextBoxActSize.Text)With Me.LabelResult Select Case SizeDiff Case 0 .Text = "Nothing" Case 1 .Text = "Low-fat diet" Case 2 To 4 .Text = "Penis pills" Case Else .Text = "Penis prothesis" End SelectEnd WithMe.PanelInput3.Enabled = FalseMe.PanelResult.Enabled = True• For PanelResult, create ButtonResultAgain

Its .Click event handler resets the whole page in default status, forcing server into repeated first reload of page:

Server.Transfer("CrossValidInp.aspx")• For PanelInput2 and PanelInput3, create

ButtonInp2Last and ButtonInp3Last with a very simple .Click event handler flipping enabled/disabled status backward:

Me.PanelInput2.Enabled = FalseMe.PanelInput1.Enabled = True

ClickClick

ClickClick

10

12

Penis pills

MaleClickClick

ClickClick

ClickClick

Page 13: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

Content of LessonChecking Home Assignment 1-1: Describe your own objectCreating basic webforms in .Net• Objects and sequence of client-server communication• ASPX Form Control Objects• Session object• Transferring data between Pages using Session object• Input individual data, validate on server, send back output• Cross-validation of interlinked inputs on multiple PanelsHome Assignment 2-1: Cross-Page Validation

Page 14: SQL.Net Consultation Lesson 2 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546 Location:

Home Assignment 2-1: Cross-Page ValidationTASK: Create ASPX .Net Web Application containing 2 Pages: (3pts)• Values of TextBoxes/DropDownLists placed on first Page and set by user will modify

required- and range validation of TextBoxes/DropDownLists placed on the second Page.• The user should be able to navigate between the 2 Pages forth and back using Hyperlink

or LinkButton controls• When navigating backward, Pages should be set in their default statusContent of the two pages should model the following:STUDENT1: If a persons gender is male, you should ask beginning/end dates of military

service. In case of female, ask number of pregnaciesSTUDENT2: If type of an engine is diesel the type of fuel can be only diesel (Gázolaj). If it is a

gasoline/petrol (Benzin US/UK) engine, type of fuel can be gasoline/petrol, propane, ethanolSTUDENT3: Utility bill (Közüzemi számla) transfers has an upper limit of $300, while other

transfers $1000STUDENT4: At 2-stroke (Kétütemű) engines, number of valves can only be 0, while at 4-stroke

engines it can be 2, 4 or 5 times number of cylinders (Henger)STUDENT5: Premium customers can choose from lemonade machine sizes 500, 1000,

1500quarts/hr, while normal customers can have only 1000quarts/hrSTUDENT6: if Sperr differential (Sperr-diffi) is locked status, there can be only max. 10%

difference between the rotation/min of left and right stub axles (Féltengely). If it is not locked, there is no limitation of difference

STUDENT7: Number of divorces of a person can be equal or 1 less than number of marriagesSTUDENT8: If number of valves per cylinder is 2 it can be controlled by 1 cranckaxle

(Vezérműtengely) / cylinder row, otherwise, 2/ cylinder row are neededSTUDENT9: At 1600ccm engine or smaller, front tyre gauge pressure (Mellső gumiabroncs

légnyomás) should not exceed 2.0bar, above that, the max. is 2.2barSTUDENT10: Until the coolant (Hűtőfolyadék) temp is under 85C°, engine rotation should be

kept between 2000..3500rot/minSOLUTION: use practices 2-3..2-5 as sample solutions