sql.net consultation session 5 dr. gábor pauler, associate professor, private entrepeneur tax reg....

14
SQL .Net Consultation Session 5 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: [email protected]

Upload: oswin-owen-poole

Post on 11-Jan-2016

225 views

Category:

Documents


0 download

TRANSCRIPT

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

SQL .Net ConsultationSession 5

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 Session 5 Dr. Gábor Pauler, Associate Professor, Private Entrepeneur Tax Reg. No.: 63673852-3-22 Bank account: 50400113-11065546

Content of PresentationCreating web-applications with relational database system 5• Creating main form: panels and link buttons• Creating forms for code tables: form with single table data

source• Configuring SqlDataSource object• Usage of DataGridView and DetailsView objects

• Creating forms for master tables: form with single table data source and foreign keys• Download, install and import Obout .Net component• Obout Grid, ComboBox• Manage and edit Obout Grid templates to create dropdown

lists for foreign keys• Setting auto-query generation in .Net SqlDataSource• Manual query generation in query editor

References

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

Creating main formIts time to build up web-based GUI in Aspx .Net for our

sample database Invoicing created at Session4:• First we planned it in MS Visio as ERD Invoicing.vsd • Then we generated as SQL script Invoicing.DDL• Then we run the script in MS SQL to create

database, imported data of code and master tables, and backed it up as Invoicing.bak

• Then we created logical design of GUI in Lesson4• In the followings we assume that MS SQL server

process + Invoicing database is runningIn the first step we create a main/master page/form

(Főűrlap) which usually contains: • Logo and graphics of designer• Username+Password entry• Linkbuttons to other thematic forms of GUI• Exit/logoff buttonCreate Invoicing.aspx form:• Title = „Invoicing”• Add necessary comment text• Within Invoicing, create PanelCodeTables

– BorderStyle = Solid– BorderWidth = 1px– Add necessary comment text– Within it, create LinkButtonStreetType

• Text = „Street type”• PostBackURL = ~/StreetType.aspx

– You may notice that naming of linkbuttons and referenced thematic forms strictly follows name of their base entity to keep form naming consis-tent. Never use „Page1, Page2”-style form names, because you will mess them up when you will have 80-100 forms!

Practice 5-1: Create another 4 linkbuttons referencing to proposed forms of code tables (0.5pts)

StreetType

PK StreetTypeID int identity

StreetTypeDescr varchar(16)

LegalFormat

PK LegalFormatID int identity

LegalFormatDescr varchar(16)

VAT

PK VATID int identity

VATPercent float

MeasUnit

PK MeasUnitID int identity

MeasUnitDescr varchar(16)

Country

PK CountryID int identity

CountryDescr varchar(16)

Zip

PK ZipID int

City varchar(32)FK1 CountryID int

u:Rd:R

ITJ

PK ITJID int identity

ITJDescr varchar(32)FK1 VATID int

u:Rd:R

Address

PK AddressID int identity

Door varchar(8) Floor varchar(16) Building varchar(16) HouseNum varchar(8) Street varchar(32)FK2 StreetTypeID int LinePhone varchar(16) Fax varchar(16)FK1 ZipID int Modifier varchar(16) Modified datetime Status smallint

u:Rd:R

u:Rd:R

Buyer

PK BuyerID int identity

FirstName varchar(16) LastName varchar(16) CellPhone varchar(16) E-mail varchar(32)FK1 AddressID int

u:Rd:R

SalesPers

PK SalesPersID int identity

FirstName varchar(16) LastName varchar(16) CellPhone varchar(16) E-mail varchar(32)FK1 AddressID int

u:Rd:R

Seller

PK SellerID int identity

SellerName varchar(16) SellerTaxReg varchar(16)FK2 LegalFormatID int CellPhone varchar(16) E-mail varchar(32) URL varchar(128)FK1 AddressID int

u:Rd:R

u:Rd:R

Product

PK ProductID int identity

ProductDescr varchar(32) UnitPrice floatFK1 MeasUnitID intFK2 ITJID intFK3 VATID int

u:Rd:R

u:Rd:R

u:Rd:R

PersProdSale

PK PersProdSaleID int identity

SumOfSales floatFK2 ProductID intFK1 SalesPersID int

u:Rd:R

u:Rd:R

Invoice

PK InvoiceID int identity

InvoiceNum varchar(16) ItemCount int NetTotalVal float GrossTotal float Paid bit IssueDate datetimeFK3 BuyerID intFK2 SalesPersID intFK1 SellerID int Modifier varchar(16) Modified datetime Status smallint

u:Rd:R

u:Rd:R

u:Rd:R

Item

PK ItemID int identity

Quantity float NetVal float GrossVal floatFK2 InvoiceID intFK1 ProductID int Modifier varchar(16) Modified datetime Status smallint

u:Rd:R

u:Rd:R

Click Click

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

Creating forms for code tables 1• Code tables (Kódtáblák) are small-sized tables

containing a numeric artificial primary key and its text description and does not contain any foreign keys. As their content cahnges in time very seldom, they do not contain logging fields (Modifier, Modified, Status) They are usually filled by developer before publishing the appli-cation,and usually cannot be Updated/Deleted by normal users (but often Insert is allowed)

• So their GUI is less important, but very simple (has single table data source, and form will contain only textbox controls) so we start here

• Creation of simple code table maintenance (In-sert/Update/Delete) forms is very well suppor-ted in .Net, no need of manual coding here:

Create StreetType.aspx form:• Title = „StreetType”• Add necessary comment text• Within it, create LinkButtonBckInvoicing

• Text = „Back to main page”• PostBackURL = ~/Invoicing.aspx

• Within it, create SQLDataSourceStreetType. It connects MS SQL database with data controls. Click on its intelligent label|Configure wizard:• Press New Connection button, on its panel• Select MS SQL,give Sever name, DBname• Press Test Connection to log into server• Save connection into system config• Select table StreetTypes and all of its fields

Data Source=PG-LAPTOP;Initial Catalog=Invoicing;Integrated Security=True

SELECT [StreetTypeID], [StreetTypeDescr] FROM [StreetTypes]

Imports System.Data.OleDbDim SqDSrc1 As SqlDataSource = New SqlDataSource()SqDSrc1.ID="SqlDataSourceStreetType"SqDSrc1.SelectCommand="SELECT [StreetTypeID],[StreetTypeDescr] FROM [StreetTypes]"SqDSrc1.ConnectionString="DataSource=pg-laptop;Initial Catalog=Invoicing;Integrated Security=True"SqDSrc1.ProviderName="System.Data.OleDb"

• Press Advanced and check generate Insert/Update/Delete statements

Of course the SqlDataSource can be con-figured from VB code also. Please note that configuring MS Access, XML, ODBC and other data sources usually have more difficult syntax

ClickClick

ClickClick

Click Click

ClickClick

ClickClick

ClickClick

ClickClick

ClickClickClickClick

ClickClickClickClick

ClickClick

Click Click

Click

Click

ClickClick

ClickClick

Click Click

ClickClick

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

ClickClick

ClickClick

ClickClick

ClickClick

ClickClick

Creating forms for code tables 2After completing data source wizard, we create a

GridView control, which shows content of data source in tabular format, and configure it from its intelligent label menu:

• Choose data source = SqlDataSourceStreetType• Enable Paging, Sorting, Editing, Selection

(we usually do not allow Deleting from code tables, because referential integrity closes it out)

• At Edit columns:– Select all of BoundFields,click Add button– Select the extra CommandField added to

existing fields. It will contain links for auto-generated java scripts manipulating the given record:

• Show Insert/Edit/Delete/Select button• InsertVisible: inserted record is visible

– At artificial primary keys(eg.StreetTypeID):• ReadOnly = True: cannot write

because of identity setting of field• InsertVisible = False: field cannot be

inserted being auto-generated number– At normal data fields(eg.StreetTypeDescr):

• ReadOnly = False: if user can write• InsertVisible = True

After setting these, GridView should work fine:

ClickClick

Click Click

ClickClick

Click

Click

ClickClickClickClickClickClick

ClickClick

ClickClick

Shift

ClickShi

ftClic

k

ClickClickClickClick

ClickClick

ClickClickClickClick

ClickClick

•With Auto-generate, you can do it 1 step•Refr.schema passes changes of database

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

Creating forms for code tables 3• Please note that GridView control does not

query the database itself. Instead of that, it calls SQL queries (SQL nyelvű lekérdezés) or stored procedures (Tárolt eljárás) – a set of SQL or procedural commands copiled together into one executable – of the SqlDataSource defined at its .Insert, .Update, .Delete, .Select properties in property editor.

• The data source wizard auto-configures these queries if generate Insert/Update/Delete statements is checked, but they can be modified manually

• While GridView could show many records (25-40) in one page, it can show only limited number of fields (5-10) without forcing the user to scroll screen constantly

• Therefore we can use DetailsView control also, which shows only one record on one page but with many (70-80) fields without the need of scrolling. We show an example for its use creating Country.aspx:– We add necessary comment text– We create LinkButtonBckInvoice pointing

back to main form– We create SqldataSourceCountry using

the same connection we already defined previously (pg-laptop.invoicing.dbo) and representing Countries table of Invoicing

– Then we create DetailsView1 using Sql-DataSourceCountry and enabling Paging, Inserting, Editing (but not Deleting)

– Edit fields works pretty much the same as above, but DetailsView has more reliable inserting than GridView, which often stucks

ClickClick

ClickClick

ClickClickClickClick

ClickClick

Click

Click

Click

Click

Click Click

ClickClick

Practice 5-2:Create code table forms for: • Legal formats (in tabular format),• Measure units (in tabular format), • VATs (in details format),• Connected to corresponding code

tables of Invoicing database • Referenced by LinkButtons on

PanelCodeTables of Invoicing main form (1.5pts)

•After field definition, we can run the form and it should work fine both in update an insert mode:

Click Click

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

Content of PresentationCreating web-applications with relational database system 5• Creating main form: panels and link buttons• Creating forms for code tables: form with single table data

source• Configuring SqlDataSource object• Usage of DataGridView and DetailsView objects

• Creating forms for master tables: form with single table data source and foreign keys• Download, install and import Obout .Net component• Obout Grid, ComboBox• Manage and edit Obout Grid templates to create dropdown

lists for foreign keys• Setting auto-query generation in .Net SqlDataSource• Manual query generation in query editor

References

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

About Obout: download, install and import its .Net components• Obout Inc. is a manufacturer of highly sophis-ticated .Net components downloadable from http://www.obout.com/ in the install package oboutSuite20081003.exereducing manual co-ding need compared to MS .Net components

• Install package in a given directory (eg. C:\ Obout) and run Default.aspx to see working examples of Obout.Net controls grouped into programming tasks both in Asp,C#, and VB

• To use examples, import controls into Visual Studio by Toolbox|Data tab|Rightclick| Choose item opening .Net components list

• There click Browse and select component *.dll file from C:\Obout\bin directory,click OK

• Imported controls can be seen in Toolbox, from where you have to Drag them once into any of the forms of your website and Save all

• This will import control *.dll files into \bin di-rectory the site, check it in Solution explorer

• Now you can add example form of Obout to your site with SiteName|Rightclick|Add ex-isting item| C:\Obout\Controlname\Exaple name.aspx As Obout controls have many properties with sometimes misleading names, copy examples carefully to get them working

ClickClick

ClickClick

Click

Click

ClickClick

DragDragClickClick

ClickClick

Click Click Click Click

right

Clickright

Click

Click

Click

right

Clickright

Click

Add existing item…Add existing item…

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

Creating forms for master tables 1• Master tables (Törzstáblák) can be big sized, but they change slowly in time, so they do not

contain logging fields (Modifier, Modified, Status). • However they contain foreign keys referencing to code/lookup (Kinézegető) tables: as

referential integrity of these relations are usually checked, they wont accept values not represented in the referenced primary key of the one side table (eg. you cannot write a non-existing CountryID in Zips table)

• Therefore foreign keys should not be simple TextBox controls, but they should be DropDownLists or ComboBoxes, where items of the list are automatically merged from one side table (eg. Countries), this way user cannot mistype the code

• As primary keys are usually identity-generated numbers, it is hard to remember their meaning for the user. Therefore the list should show some text description for the items, not the code itself it writes back in foreign key field

• Built-in MS .Net GridView and DetailsView controls do not support showing DropDownLists in record editing mode, therefore they require lot of additional manual coding

So we will build the first master table form of our Invoicing web application using the imported Grid control of Obout:

• First create PanelMasterTables on Invoicing.aspx form– BorderStyle = Solid– BorderWidth = 1px– Add necessary comment text– Within it, create LinkButtonITJ

• Text = „ITJ”• PostBackURL = ~/ITJ.aspx

• Create ITJ.aspx form. It is a master form which has a foreign key referencing to VATs table– Title = „ITJ” and add comment text– Add LinkButtonBckInvoice .Text=„Back to main” .PostBackURL = ~/Invoicing.aspx– Within it, create SQLDataSourceITJ. This will be the data source of the master form

• Connection=InvoicingConnectionString• Select all fields of ITJs table• Press Advanced and check generate Insert/Update/Delete statements

– Within it, create SQLDataSourceVAT. This will be the data source of lookup table• Connection=InvoicingConnectionString (we reuse the same connection!)• Select all fields of VATs table• Do NOT check generate Insert/Update/Delete here!

Click Click

ClickClick

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

Creating forms for master tables 2• Add new Obout Grid to ITJ.aspx• In its intelligent label:set its da-

ta source to SqlDataSourceITJ• Click Edit Columns panel:

• Add all columns of ITJs• Fill their DataField

• Allow Select,Add,Sort,Page• At Manage template panel:

• Add new template• Set ID=EditVAT (it

will be a template for editing VATID)

• Set Control=ddlVAT (it will use a control with this name)

• Set Property=Value (it will be the input)

• At Edit templates panel:• Add a DropDownList

• In intelligent label:• Edit databind:

Select.value, Custom=No

• Data source:=SqlDataSour- ceVAT Display= VATPercent Value=VATID

• In Properties set its ID=ddlVAT

• At Edit columns panel: • VATID|Col.template:

• Edit mode=EditVATRun and enjoy VATID lookup table!

Edit Templates

ClickClick

ClickClickClickClick

ClickClick

ClickClick

ClickClick

ClickClickClickClick

Dra

gD

rag

ClickClick

Click

Click

ClickClick

Click

Click

Click

Click

ClickClick

Click

Click

Click

Click

ClickClick

Clic

kC

lick

Clic

kC

lick

ClickClick Click

Click

ClickClick

ClickClick

ClickClick

ClickClickClick Click

ClickClick

Template controls cannot have fix data binding!

Field to put in foreign key

Field to show in droplist

Match up with name given in EditVAT. ControlID

sometimes it cannot be renamed,do not force it, use original!you have to find out name in advance

memori-ze field names!

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

Creating forms for master tables 3

One can see that lookup table for VATID works fine, but it is somewhat confusing that the field in view mode (when not edited) will contain numeric codes undezipherable for the user:

• We could solve this problem assigning EditVAT template as View template of VATID field in its Column template property. However it will case type mismatch runtime error in Grid

• An alternative solution is that description of VATID should be added to the Grid as a new column. However VATPercent descriptor field (Leíró mező) can be found in different table (VATs) than data source table of the master table form (ITJs).

Therefore we have to learn about how to use multiple tables as data source of a form queried together in a viewtable (Nézet tábla). We will see it creating form Zip.aspx for master table ZIPs, which has a lookup table Countries:

• On PanelMasterTables of Invoicing.aspx form– Create LinkButtonZIP

• Text = „ZIPs”• PostBackURL = ~/ZIP.aspx

• Create Zip.aspx form:– Title = „ZIP” and add comment text– Add LinkButtonBckInvoice

• Text=„Back to main”• PostBackURL = ~/Invoicing.aspx

ClickClick

Clic

kC

lick

Clic

kC

lick

Country

PK CountryID int identity

CountryDescr varchar(16)

Zip

PK ZipID int

City varchar(32)FK1 CountryID int

Click Click

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

Creating forms for master tables 4• Create SQLDataSourceZIP. This will be the data source of

the master form– Connection=InvoicingConnectionString– Select Specify SQL to give query of viewtable:

• Click Select/Update/Insert/Delete to specify queries of datasource called at different data control operations:

• Click Query Builder to open graphic query designer of MS SQL server:

• Add tables with Rightclick|Add table• Tables will inherit joins from defined

relations, but extra joins can be defined Drag&Drop join fields

• Fields of tables can be Pulled into query assembly grid’s Column part

• Set Alias for rename fields, check Output

• Prepared query can be seen and edited in SQL panel

• Press Execute query to check resulting viewtable

– Important: defining manual queries one should not use autogenerate Insert/ Update/ Delete statements and Optimistic concurrency from Advanced panel of SqlDataSource wizard!!!

• Within Zip.aspx form, create SQLDataSourceCountries. This will be the data source of lookup table– Connection=InvoicingConnectionString

(we reuse the same connection!)– Select all fields of Countries table– Do NOT check generate Insert/Update/Delete here!

UPDATE [Zips] SET [City]=@City, [CountryID]=@CountryID WHERE [ZipID]=@ZipID

INSERT INTO [Zips] ([ZipID],[City],[CountryID]) VALUES(@ZipID,@City,@CountryID)

DELETE FROM [Zips] WHERE [ZipID]=@ZipID

ClickClickClickClick

ClickClick

Clic

kC

lick

DragDrag

DragDrag

ClickClick

ClickClick

right

Clic

k

right

Clic

k

Add table…Add table…

Clic

kC

lick

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

Creating forms for master tables 5

• Then we apply Obout Grid control and its edit template in the same way as before• Running the form one can see that if value of the foreign key (CountryID) is

updated with the lookup table, the Grid requeries its content from view table and foreign key description field (CountryDescr) will be refreshed

• Changing the Select query of basis data source including some computed fields there, we can perform computations with Grid reacting on user input instantly

• Even better solution is to define the view table in MS SQL already and assign it to the data source SqlDataSourceZip. This way, computed fields can be reached from database also

• The disadvantage of this solution is that in this case Update/ Insert/ Delete queries cannot be generated automatically, their definition will be totally manual

• Moreover, if we would like to modify more source tables of the view table, we have to write separate Update/ Insert/ Delete queries for each of them.

• But coding in SQL is still 20 times faster than manual coding in VB. Therefore we will broaden our SQL knowledge in the next part.

Practice 5-3: Create master table form for Products table in Invoicing database with all its necessary lookup tables, and descriptor fields! (2pts)

Click

Click

Click

Click

ClickClick

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

.Net Visual Basic reference: http://msdn.microsoft.com/en-us/library/sh9ywfdk.aspx References