• Reading BAML at runtime is faster than reading XAML.
• Deployment is easier. Because BAML is embedded in your assembly as one or more resources,
there’s no way to lose it.
• XAML files can be edited in other programs, such as design tools. This opens up the possibility
for better collaboration between programmers and designers.
Note that Visual Studio uses a two-stage compilation process when you’re compiling a WPF applica-
tion. The first step is to compile the XAML files into BAML.
• Fields for all the controls in your window.
• Code that loads the BAML from the assembly, thereby creating the tree of objects.
• Code that assigns the appropriate control object to each field and connects all the event han-
dlers.
The partial class does not include code to instantiate and initialize your controls because that task is
performed by the WPF engine. In summary of the XAML compilation process, the XAML compiler
needs to create a partial class. This is possible only if the language you’re using supports the .NET
Code DOM model. C# and VB support Code DOM, but if we’re using a third-party language, we’ll
need to make sure this support exists before we can create compiled XAML applications.
When the XAML-to-BAML compilation stage is finished, Visual Studio uses the appropriate language
compiler to compile your code and the generated partial class files. In the case of a VB application,
it’s the vbc.exe compiler that handles this task. The compiled code becomes a single assembly, and
the BAML for each window is embedded as a separate resource.
7.3.8 Performance of XAML: Usefulness of BAML
All Microsoft technologies use XAML in combination with another .NET programming language, e.g.
as C# or VB.NET, to create desktop, tablet, and mobile applications with stunning and unique user
interfaces as well as elegant and intuitive user experience designs, which were nearly impossible to
achieve prior to the introduction of XAML and WPF in .NET 3.0.
XAML is an XML-based declarative markup language, it adds a completely new paradigm to Windows-
based user interface (UI) development. XAML is verbose and thus easily read by humans. This is
helpful when you need to edit XAML by hand. Moreover, the XML basis of XAML makes it an easy
language for which WYSIWYG editors can be created. XML may be easy to read, but what about the
performance of my application? XML is too verbose!” This is true.
XML can cause performance problems when parsing; however, the XAML parser will compile your
XAML into a binary format called Binary Application Markup Language (BAML) that is used during the
execution of your application. BAML drastically reduces the size of your XAML code, and this helps to
eliminate the performance problems associated with traditional XML parsing. BAML is tokenized as
well so that duplicate references throughout the BAML code can be replaced by much smaller tokens.
This in turn makes BAML code even smaller and thus faster during application execution.
151
7.3.9 Separation of User Interface Concerns
Microsoft adopts the Model-View-ViewModel (MVVM) design pattern, as used in the Visual Studio
2019. MVVM helps to cleanly separate the business and presentation logic of an application from
its user interface (UI). Maintaining a clean separation between application logic and the UI helps to
address numerous development issues and can make an application easier to test, maintain, and
evolve. Explore on the MVVM in the following URLs.
• What is MVVM Pattern? 17
• The Evolution of MVVM 18
• Benefits of MVVM 19
7.3.10 Declarative vs. Imperative Programming
In declarative programming, the source code is written in a way that expresses the desired outcome
of the code with little or no emphasis on the actual implementation. This leaves the framework to deal
with parsing the declarative source code and handling the ”heavy lifting” required to instantiate objects
and set properties on the these objects, which are defined in the XAML elements.
Imperative programming is the opposite of declarative programming. Suppose that declarative pro-
gramming can be thought of as declaring what the desired outcome is, imperative programming can
be viewed as writing lines of code that represent the instructions of how to achieve the desired out-
come.
As the both programming models combined with the shared-state concurrent computing model 20, we
can summarise the existing GUI programming into three types, as follows.
1. Purely procedural: The user interface is constructed by a sequence of graphics commands. These
commands can be purely imperative, as in tcl/tk; object-oriented, as in Java AWT (Abstract Window
Toolkit) package or its extension, the Java Swing components; or even functional, as Haskell fudgets
21. The type of object-oriented or functional style is preferable to an imperative style because it is
easier to structure the graphics commands. The following code depicts the sample of Java AWT.
1 import java.awt.BorderLayout;
2 import java.awt.Button;
3 import java.awt.Color;
4 import java.awt.Frame;
5 import java.awt.GridLayout;
6 import java.awt.Label;
17https://docs.microsoft.com/en-us/xamarin/xamarin-forms/enterprise-application-patterns/
mvvm
18https://docs.microsoft.com/en-us/archive/msdn-magazine/2009/february/
patterns-wpf-apps-with-the-model-view-viewmodel-design-pattern
19https://docs.microsoft.com/en-us/windows/uwp/data-binding/data-binding-and-mvvm
20https://en.wikipedia.org/wiki/Concurrent_computing
21https://en.wikipedia.org/wiki/Fudgets
152
7 import java.awt.Panel;
8 import java.awt.TextField;
9 import java.awt.event.ActionEvent;
10 import java . awt . event . ActionListener ;
11 import java . awt . event . WindowAdapter ;
12 import java . awt . event . WindowEvent ;
13
14 public class JavaForm
15 {
16 public static void main ( String [] args )
17 {
18 Frame frm = new Frame ( " Java frame " ) ;
19 frm . setSize (450 , 150) ;
20 frm . setVisible ( true ) ;
21 frm . a ddWind owList ener ( new WindowAdapter ()
22 {
23 public void windowClosing ( WindowEvent e )
24 {
25 System . exit (0) ;
26 }
27 }) ;
28
29 Label jFirstName = new Label ( " First Name " ) ;
30 TextField lFirstName = new TextField (20) ;
31 Label jLastName = new Label ( " Last Name " ) ;
32 TextField lLastName = new TextField (20) ;
33 Panel p = new Panel () ;
34 p . setLayout ( new GridLayout (3 , 2) ) ;
35 p . add ( jFirstName ) ;
36 p . add ( lFirstName ) ;
37 p . add ( jLastName ) ;
38 p . add ( lLastName ) ;
39 Label lbl = new Label ( " Please fill with your
information:");
40 Button Submit = new Button ( " Submit " ) ;
41 Submit . setBackground ( Color . yellow ) ;
42 Submit . ad dActio nListe ner ( new ActionListener ()
43 {
44 public void actionPerformed ( ActionEvent e )
45 {
46 lbl . setText ( " Your name : "
47 + lFirstName . getText () + " "
48 + lLastName . getText () ) ;
49 Submit . setBackground ( Color . green ) ;
50 }
51 }) ;
52 p . add ( Submit ) ;
53 p . add ( lbl ) ;
54 Panel p1 = new Panel () ;
55 p1 . add ( p ) ;
56 frm . add ( p1 , BorderLayout . NORTH ) ;
153
57 }
58 }
2. Purely declarative: The user interface is constructed by choosing from a set of predefined possibili-
ties. This is an example of descriptive declarativeness 22. A well-known example is HTML, the format-
ting language used for web pages. The following code depicts the sample of HTML self-submission
form.
1 <html >
2 <head >
3 <script type="text/JavaScript" language="JavaScript">
4 function check()
5{
6 document.getElementById(’f1 ’).innerHTML =
7 document.writeln("Your name: "
8 + document.bizLoginForm.firstName.value + " "
9 + document.bizLoginForm.lastName.value);
10 }
11 </ script >
12 </ head >
13 < body >
14
15 < form name = " bizLoginForm " method = " post " action " " >
16 < table >
17 <tr > < td > First Name : </ td > < td > < input type = " text " id = " firstName "
value="" /></td ></tr >
18 <tr > < td > Last Name : </ td > < td > < input type = " text " id = " lastName " value = " "
/></td ></tr >
19 </ table >
20 < input type = " Submit " name = " submitButton " value = " Submit "
onclick="check(); return false" />
21 </ form >
22
23 <p id = " f1 " > </p >
24 </ body >
25 </ html >
22Declarativeness here is defined in a particular way that reasoning about programs is simplified. however, this is not
the only way to make precise what declarative programming is. Intuitively, it is programming by defining the what (the
results we want to achieve) without explaining the how (the algorithms and etc, needed to achieve the results). Read more
on declarative programming at URL https://en.wikipedia.org/wiki/Declarative_programming
154
3. Using an interface builder: The user interface is constructed manually by the developer, using a
direct manipulation interface. The Microsoft Visual Studio is a good example for it.
The procedural type is expressive, i.e. anything at all can be done at runtime, but it is complex to use.
The declarative type is easy to use, i.e. a few simple declarative suffice to create an interface, but
lacks of expressiveness. The interface builder type is easy to use and gives immediate feedback on the
interface. However, it lacks of expressiveness, and the interface is hard to change at runtime.
7.3.11 WPF as A Higher-Level Application Programming Interface (API)
Suppose that the only thing WPF offered was hardware acceleration through DirectX, it would be a
compelling improvement but not a revolutionary one. However, WPF actually includes a basket of
high-level services designed for application programmers. The following are the changes that WPF
ushers into the Windows programming world:
i. WPF with a web-like layout model:
Rather than fix controls in place with specific coordinates, WPF emphasizes flexible flow layout
that arranges controls based on their content. The result is a user interface that can adapt to
show highly dynamic content or different languages.
ii. WPF with a rich drawing model:
Rather than painting pixels, in WPF, software developers deal with primitives-basic shapes,
blocks of text, and other graphical ingredients. Software developer have new features, e.g. true
transparent controls, the ability to stack multiple layers with different opacities, and native 3D
support.
iii. WPF with a rich text model:
155
WPF gives Windows applications the ability to display rich, styled text anywhere in a user in-
terface. Software developer allows to combine text with lists, floating figures, and other user
interface elements. Suppose that software developers need to display large amounts of text,
they can use advanced document display features, e.g. wrapping, columns, and justification, to
improve readability.
iv. Animation as a first-class programming concept in WPF application:
In WPF, there’s no need to use a timer to force a form to repaint itself. Instead, animation is
an intrinsic part of the framework. Software developer defines animations with declarative tags,
and WPF puts them into action automatically.
v. Support for audio and video media in WPF application:
Previous user interface Toolkits, e.g. Windows Forms, were surprisingly limited when dealing
with multimedia. However, WPF includes support for playing any audio or video file supported
by Windows Media Player, and it allows software developer to play more than one media file at
once. Even more impressively, it gives software developer the tools to integrate video content
into the rest of designed user interface, allowing software developer to pull off exotic tricks, e.g.
placing a video window on a spinning 3D cube.
vi. WPF with styles and templates:
Styles allow software developer to standardize formatting and reuse it throughout their designed
application. Templates allow software developer to change the way any element is rendered,
even a core control,e.g. the button. It’s never been easier to build modern skinned interfaces.
vii. WPF with commands:
Most users realize that it doesn’t matter whether they trigger the Open command through a
menu or through a Toolbar; the end result is the same. Now that abstraction is available to our
code, we can define an application command in one place and link it to multiple controls.
viii. Declarative user interface in WPF application:
Although we can construct a WPF window with code, Visual Studio takes a different approach.
It serializes each window’s content to a set of XML tags in a XAML document. The advantage
is that our user interface is completely separated from our code, and graphic designers can use
professional tools to edit our XAML files and refine our application’s front end.
ix. WPF with page-based applications:
Using WPF, we can build a browser-like application that lets us move through a collection of
pages, complete with forward and back navigation buttons. WPF handles the messy details,
e.g. the page history. We can even deploy your project as a browser-based application that
runs right inside Internet Explorer.
156
7.4 Graphical User Interface with WPF
To create a WPF application, open the New Project dialog in VS and select WPF Application. Lets
name the project ”MyWPFApplication”
There is a list of files created for the WPF application in VS.
i. Application.xaml: defines the overall application object and its settings
ii. Application.xaml.vb: code behind file which holds all the programming logic
iii. MainWindow1.xaml: defines the settings for the default object MainWindow1
iv. MainWindow1.xaml.vb: code behind file which holds all the programming logic
The Application.xaml file holds a setting Startupuri which defines which XAML document loads at
application startup.
Let’s examine the prepared VB code to manipulate the following controls, as available at GitHub.
i. Drawing lines, rectangles and ellipses
WPF has several built in shapes which designers can use directly. You may observe the follow-
ing example to create lines, rectangles and ellipses using WPF.
157
ii. Drawing polygons
Polygons are multi-sided shapes. A polygon is any shape with three or more sides. There are
two shape controls for drawing multisided shapes. These controls are:
• Polyline: Draws a series of connected lines defined by a set of points.
• Polygon: Draws a series of connected lines defined by a set of points and joins the starting
and ending points to make a closed figure.
iii. Brushes - Embedding image and video
Brushes can change the graphic properties of elements such as the Fill, Stroke or Background.
There are three main kinds of brushes which are:
• SolidColourBrush: fills an element with a specified colour. The following piece of code
fills the text in a TextBlock
• ImageBrush: paints an image into the property it is assigned to. The following piece of
code draws an image into a TextBlock
• VisualBrush: can be used to display a video in an element. The following piece of code
displays a video in a TextBlock
Note that MediaElement can play all the file formats supported by Windows Media Player. In
order to play media using MediaElement you need to install the latest Windows Media Player.
158
iv. Image transforms
A transform can be applied to any UI element to reposition, resize or reorient the graphic. There
are four types of transforms which are:
• TranslateTransform: moves an object to a new location
• RotateTransform: rotates an object around a point and by a specified rotation angle
• SkewTransform: shears or skews the object
• ScaleTransform: scales the object’s x, y coordinate points by a specified amount
v. Drawing shape with image
A star image is transformed into a polygon using random colors.
vi. 3D object and image
A 3D rotatable-object using WOU image is formed on X, Y and Z-axis.
159
Animation in the WPF can be defined as the transition of a property from one value to another within
a specified timeline. WPF uses a Storyboard element, which defines the parameters for the anima-
tion. There are several animation classes available in the WPF. However, the most commonly used
animation classes are as follows.
• DoubleAnimations: It animates the size property of objects
• PointAnimations: It animates the location of an object
• ColorAnimations: It animates the colour of an object
7.5 Database and LINQ to SQL
Note that you need to fulfil the following prerequisite in order to follow this section.
i. Computer is installed with both Microsoft Visual Studio (VS) Community edition and Microsoft
SQL Server, e.g.
• VS 2019 with SQL Server 2017 (require SQL Server Management Studio)
• VS 2017 with SQL Server 2016
• VS 2015 with SQL Server 2014
ii. Database file Books.mdf and its ldf file (transaction log file are compatible with installed version
of Microsoft SQL Server.
VB program is used to communicate with a relational database, and to manipulate the data inside
through LINQ to SQL. IDE’s visual programming tools and wizards are used to connect and manipulate
a database.
160
7.5.1 Relational database
A relational database organizes data in tables that are appropriately structured. The fundamental
elements of a relation are the tuples or records in a table. For example, a table stores the attributes
of employees. Tables are composed of rows (records) and columns. The EmployeeID is the primary
key in table. Note that a primary key is a unique key to identify a record.
The properties of a relational table
i. The table name must be distinct from all other tables in the database, i.e., no two tables can
have the same name in the database.
ii. Tables do not contain repeating groups of data, e.g., it is not permitted to store several telephone
numbers for a single branch in a single cell.
iii. Each column has a distinct name, i.e., no two columns have the same name in a table.
iv. Each record is distinct, i.e., there are no duplicate records.
SQL Server database file, i.e. Books.mdf, ends with ‘.mdf’ file name extension is used. It stores
information on some publications using three tables
i. Authors table: it consists of three columns that maintain each author’s particular information
(AuthorID, FirstName and LastName). AuthorID is a primary key.
ii. Titles table: it consists of four columns that maintain information about each book in the database
(ISBN, Title, EditionNumber, Copyright). ISBN is a primary key.
iii. AuthorISBN table: it consists of two columns that maintain ISBNs for each book and their
corresponding authors’ ID numbers. (AuthorID, ISBN). AuthorID is a foreign key that matches
the primary key column (AuthorID) in the Authors table. ISBN is also a foreign key that matches
the primary key column (ISBN) in the Titles table. Both the AuthorID and ISBN columns form a
composite key. A composite key is a primary key that is composed of two or more columns.
7.5.2 Step-by-step guide: Define a Data Source
In this section, an example with query on the Books database is presented.
i. We retrieve the entire Authors table and displays the data in a DataGridView. It is done by
connecting the Books database and creating the LINQ to SQL classes using the following steps.
• Create a new database, named as Books, with the given SQL script script create db Books.sql
using the SQL Server xxxx Management Console. Note that pre-loaded data will be
stored in the database table objects of database Books
161
• After the successful creation, replace your local copies of files Books.mdf and Books log.ldf
(given in this course) with those from the location (example path from the Windows 10
with instance named SQLEXPRESS) C: \Program Files \Microsoft SQL Server
\MSSQL13.SQLEXPRESS \MSSQL \DATA
ii. In VS, create a new WPF application, and name it as DisplayTable
iii. Open the Data Sources window in VS.
iv. Add a data source, by clicking the link of Add New Data Source..., into the new created project.
Choose Database as its type of data source, and click Next.
v. Choose Database as its type of database model, and click Next.
162
vi. Click New Connection. . . to open the Add Connection dialog. Ensure that the value of Data
Source is not set to Microsoft SQL Server Database File (SqlClient). Otherwise click on
Change. . . button to change to required value, and click OK. In the Add Connection dialog,
click Browse. . . , locate the Books.mdf database file on your computer. Click OK to create the
connection.
vii. Confirm the correct target data connection, which is based on database file, for this project.
Click Next to proceed for next step.
163
viii. Click Yes to allow VS copying the database file into created project and modifying the connec-
tion.
ix. Check on Yes, and allow VS to save the modified connection string to the application configu-
ration file, i.e. file App.config of your project. Click Next to proceed for next step.
Select one or more Database Objects, e.g. pre-loaded database tables as in database file
164
Books.mdf, to be included in the DataSet. A default DataSet name is given, i.e. BooksDataSet
or [database file name]DataSet. Click Finish to end the Data Source creation process.
x. As above steps are performed correctly, the selected Database Object/s will appear in Data
Source window under the name of BooksDataSet. Well done, A Data Source is defined!
7.5.3 Step-by-step guide: Manipulate records
i. Use Server Explorer window to manipulate data in database objects, i.e. View → Server
Explorer. Establish the Data Connection by right-click on the database file → Refresh.
165
ii. Create a database table, i.e. right-click Tables → Add New Table.
iii. Name the new table as Viewer, and create each of these columns with properties. Note that
column Id has the Auto-increment ID, and it is set as Primary Key.
iv. Preview the records in database table by right-click Viewer (the created table name) → Show
Table Data. Note that edit the definition of created database table (Open Table Definition) will
either delete or modify the existing records. Well done, records are manipulated!
166
v. Enter new records into the created table, i.e. Viewer, as follows.
7.5.4 Changing the database’s copy to Output Directory property
Each time you run the application, a new copy of the database file is used by default. Therefore,
any records that was saved to the database when testing your application will be lost. Remedy for
this problem: Select ‘Books.mdf’ in the Solution Explorer, and then change its Copy to Output
Directory property to Copy if Newer in the Properties window.
167
7.5.5 Step-by-step guide: Visualize Database Design
i. In the prepared VB code DisplayTable project, as available at GitHub, generate the LINQ to
SQL Classes by right-click DisplayTable → Add → New Item...
ii. Name the file as Books.dbml, and click Add.
168
iii. A blank Object Relational Designer will be showed upon the success of creation file Books.dbml.
iv. Establish the data connection by refreshing the database file Books.mdf in the Server Explorer,
i.e. View → Server Explorer.
v. Drag and drop the required table/s to the Object Relational Designer. Save (File → Save All)
and build (Build → Build DisplayTable) the solution before proceed to run the program.
169
Well done, a database design is visualised!
7.5.6 Step-by-step guide: Establish the connection to WPF
LINQ to SQL object model provides an Application Program Interface (API) for accessing database
systems. LINQ to SQL replaces the previous Microsoft created API, i.e. ADO.NET, in many cases.
In this section, we use the created data source to display records in database table via the LINQ to
SQL.
i. Open the Data Source window as follows.
ii. Note that the created data source is editable, i.e. right-click BooksDataSet → Configure Data
Source with Wizard.... Adding and removing database objects, for instance.
iii. Note that the records in data source is view-able, i.e. right-click table’s name → Preview
Data.... Records are not editable in this previewing.
170
iv. Compile the project (Build → Rebuild Solution). In Data Source window, drag and drop the
required data (for each individual table). Author table is dropped, for instance, as follows.
Upon running the VB program, you should notice records from the database table are displayed
now. Congratulation and you did it!
7.5.7 Reading
To get more overviews, examples, and background information on the VB and LINQ, please read the
following topics at https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/
language-features/linq/:
i. Introduction to LINQ in Visual Basic
ii. How to: Query a Database by Using LINQ
iii. How to: Call a Stored Procedure by Using LINQ
iv. How to: Modify Data in a Database by Using LINQ
v. How to: Combine Data with LINQ by Using Joins
vi. How to: Sort Query Results by Using LINQ
vii. How to: Filter Query Results by Using LINQ
viii. How to: Count, Sum, or Average Data by Using LINQ
ix. How to: Find the Minimum or Maximum Value in a Query Result by Using LINQ
171
x. How to: Return a LINQ Query Result as a Specific Type
VB also provides support for LINQ to XML through XML literals and XML axis properties. This en-
ables you to use a familiar, convenient syntax for working with XML in your Visual Basic code. XML
literals enable you to include XML directly in your code. XML axis properties enable you to access
child nodes, descendant nodes, and attributes of an XML literal. LINQ to XML is an in-memory XML
programming API designed specifically to take advantage of LINQ. Although you can call the LINQ
APIs directly, only VB enables you to declare XML literals and directly access XML axis properties. Ex-
plore further the uniqueness of LINQ to XML on following topics at https://docs.microsoft.com/
en-us/dotnet/visual-basic/programming-guide/language-features/xml/overview-of-linq-to-xm
i. Creating XML
ii. Manipulating XML
iii. Accessing XML
7.6 Useful codes
Samples of SQL for the required table objects in this topic.
1: CREATE TABLE [dbo].[AuthorISBN](
2: [AuthorID] [int] NOT NULL,
3: [ISBN] [varchar](20) NOT NULL,
4: CONSTRAINT [PK AuthorISBN] PRIMARY KEY CLUSTERED
5: ([AuthorID] ASC, [ISBN] ASC) WITH
6: (PAD INDEX = OFF,
7: STATISTICS NORECOMPUTE = OFF,
8: IGNORE DUP KEY = OFF,
9: ALLOW ROW LOCKS = ON,
10: ALLOW PAGE LOCKS = ON) ON [PRIMARY]
11: ) ON [PRIMARY]
1: CREATE TABLE [dbo].[Authors](
2: [AuthorID] [int] IDENTITY(1,1) NOT NULL,
3: [FirstName] [varchar](30) NOT NULL,
4: [LastName] [varchar](30) NOT NULL,
5: PRIMARY KEY CLUSTERED
6: ([AuthorID] ASC) WITH
7: (PAD INDEX = OFF,
8: STATISTICS NORECOMPUTE = OFF,
9: IGNORE DUP KEY = OFF,
10: ALLOW ROW LOCKS = ON,
11: ALLOW PAGE LOCKS = ON) ON [PRIMARY]
172
12: ) ON [PRIMARY]
1: CREATE TABLE [dbo].[Titles](
2: [ISBN] [varchar](20) NOT NULL,
3: [Title] [varchar](100) NOT NULL,
4: [EditionNumber] [int] NOT NULL,
5: [Copyright] [varchar](4) NOT NULL,
6: PRIMARY KEY CLUSTERED
7: ([ISBN] ASC) WITH
8: (PAD INDEX = OFF,
9: STATISTICS NORECOMPUTE = OFF,
10: IGNORE DUP KEY = OFF,
11: ALLOW ROW LOCKS = ON,
12: ALLOW PAGE LOCKS = ON) ON [PRIMARY]
13: ) ON [PRIMARY]
A sample SQL, i.e. script create db Books.sql, for this topic.
1 DROP DATABASE Books
2 GO
3
4 CREATE DATABASE Books
5 GO
6
7 USE Books
8 GO
9
10 SET ANSI_NULLS ON
11 GO
12 SET Q UOTED_ IDENTI FIER ON
13 GO
14 SET ANSI_PADDING ON
15 GO
16 CREATE TABLE [ dbo ].[ AuthorISBN ](
17 [ AuthorID ] [ int ] NOT NULL ,
18 [ ISBN ] [ varchar ](20) NOT NULL ,
19 CONSTRAINT [ PK_AuthorISBN ] PRIMARY KEY CLUSTERED
20 (
21 [ AuthorID ] ASC ,
22 [ ISBN ] ASC
23 ) WITH ( PAD_INDEX = OFF , S T A T I S T I C S _ N O R E C O M P U T E = OFF , IGNORE_DUP_KEY =
OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
24 ) ON [ PRIMARY ]
25
26 GO
27 SET ANSI_PADDING OFF
28 GO
173
29
30 SET ANSI_NULLS ON
31 GO
32 SET Q UOTED_ IDENTI FIER ON
33 GO
34 SET ANSI_PADDING ON
35 GO
36 CREATE TABLE [ dbo ].[ Authors ](
37 [ AuthorID ] [ int ] IDENTITY (1 ,1) NOT NULL ,
38 [ FirstName ] [ varchar ](30) NOT NULL ,
39 [ LastName ] [ varchar ](30) NOT NULL ,
40 PRIMARY KEY CLUSTERED
41 (
42 [ AuthorID ] ASC
43 ) WITH ( PAD_INDEX = OFF , S T A T I S T I C S _ N O R E C O M P U T E = OFF , IGNORE_DUP_KEY =
OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
44 ) ON [ PRIMARY ]
45
46 GO
47 SET ANSI_PADDING OFF
48 GO
49
50 SET ANSI_NULLS ON
51 GO
52 SET Q UOTED_ IDENTI FIER ON
53 GO
54 SET ANSI_PADDING ON
55 GO
56 CREATE TABLE [ dbo ].[ Titles ](
57 [ ISBN ] [ varchar ](20) NOT NULL ,
58 [ Title ] [ varchar ](100) NOT NULL ,
59 [ EditionNumber ] [ int ] NOT NULL ,
60 [ Copyright ] [ varchar ](4) NOT NULL ,
61 PRIMARY KEY CLUSTERED
62 (
63 [ ISBN ] ASC
64 ) WITH ( PAD_INDEX = OFF , S T A T I S T I C S _ N O R E C O M P U T E = OFF , IGNORE_DUP_KEY =
OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
65 ) ON [ PRIMARY ]
66
67 GO
68 SET ANSI_PADDING OFF
69 GO
70 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (1 , N ’0131752421 ’)
71 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (1 , N ’0132222205 ’)
72 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (1 , N ’0132404168 ’)
73 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (1 , N ’0136053033 ’)
74 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (1 , N ’013605305 X ’)
75 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (1 , N ’013605322 X ’)
76 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (1 , N ’0136151574 ’)
77 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (1 , N ’0136152503 ’)
174
78 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (2 , N ’0131752421 ’)
79 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (2 , N ’0132222205 ’)
80 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (2 , N ’0132404168 ’)
81 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (2 , N ’0136053033 ’)
82 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (2 , N ’013605305 X ’)
83 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (2 , N ’013605322 X ’)
84 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (2 , N ’0136151574 ’)
85 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (2 , N ’0136152503 ’)
86 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (3 , N ’0136053033 ’)
87 INSERT [ dbo ].[ AuthorISBN ] ([ AuthorID ] , [ ISBN ]) VALUES (4 , N ’0136151574 ’)
88 SET IDENTITY_INSERT [ dbo ].[ Authors ] ON
89
90 INSERT [ dbo ].[ Authors ] ([ AuthorID ] , [ FirstName ] , [ LastName ]) VALUES (1 ,
N’Choo Jun ’, N’Tan ’)
91 INSERT [ dbo ].[ Authors ] ([ AuthorID ] , [ FirstName ] , [ LastName ]) VALUES (2 ,
N’Paul ’, N’Sierra ’)
92 INSERT [ dbo ].[ Authors ] ([ AuthorID ] , [ FirstName ] , [ LastName ]) VALUES (3 ,
N’Herbert ’, N’Ayer ’)
93 INSERT [ dbo ].[ Authors ] ([ AuthorID ] , [ FirstName ] , [ LastName ]) VALUES (4 ,
N’Dan ’, N’Joel ’)
94 SET IDENTITY_INSERT [ dbo ].[ Authors ] OFF
95 INSERT [ dbo ].[ Titles ] ([ ISBN ] , [ Title ] , [ EditionNumber ] , [ Copyright ])
VALUES (N’0131752421 ’ , N’Effective Java ’, 4, N’2018’)
96 INSERT [ dbo ].[ Titles ] ([ ISBN ] , [ Title ] , [ EditionNumber ] , [ Copyright ])
VALUES (N’0132222205 ’ , N’Java How to Program ’, 7, N’2017’)
97 INSERT [ dbo ].[ Titles ] ([ ISBN ] , [ Title ] , [ EditionNumber ] , [ Copyright ])
VALUES (N’0132404168 ’ , N’C How to Program ’, 5, N’2017’)
98 INSERT [ dbo ].[ Titles ] ([ ISBN ] , [ Title ] , [ EditionNumber ] , [ Copyright ])
VALUES (N’0136053033’, N’Simply Visual Basic ’, 3, N’2019’)
99 INSERT [ dbo ].[ Titles ] ([ ISBN ] , [ Title ] , [ EditionNumber ] , [ Copyright ])
VALUES (N’013605305X’, N’Visual Basic How to Program ’, 4, N’2019’)
100 INSERT [ dbo ].[ Titles ] ([ ISBN ] , [ Title ] , [ EditionNumber ] , [ Copyright ])
VALUES (N’013605322X’, N’Visual C# How to Program ’, 3, N’2019’)
101 INSERT [ dbo ].[ Titles ] ([ ISBN ] , [ Title ] , [ EditionNumber ] , [ Copyright ])
VALUES (N’0136151574 ’ , N’Visual C++ How to Program ’, 2, N’2018’)
102 INSERT [ dbo ].[ Titles ] ([ ISBN ] , [ Title ] , [ EditionNumber ] , [ Copyright ])
VALUES (N’0136152503 ’ , N’C++ How to Program ’, 6, N’2018’)
103 ALTER TABLE [ dbo ].[ AuthorISBN ] WITH CHECK ADD FOREIGN KEY ([ AuthorID ])
104 REFERENCES [ dbo ].[ Authors ] ([ AuthorID ])
105 GO
106 ALTER TABLE [ dbo ].[ AuthorISBN ] WITH CHECK ADD FOREIGN KEY ([ ISBN ])
107 REFERENCES [ dbo ].[ Titles ] ([ ISBN ])
108 GO
109
110
111 ALTER DATABASE Guestbook SET READ_WRITE
112 GO
175
7.7 Summary
We learnt on how to use the application program to connect to a database, and to access and manip-
ulate the data. These are done using the data source as well as the IDE’s drag-and-drop functions in
helping us to display database tables in our VB application.
176
8 Topic 8: Wed-based Application Development
8.1 Objectives
By the end of this section, you should be able to:
i. Develop a Web application using ASP.NET
ii. Create Web Forms
iii. Implement data validation controls
iv. Use cookies to obtain information about users
8.2 Introduction
Internet with Web application plays a major role in the global economy and it has become part of our
business and lives, e.g. online banking, shopping or investing. We will learn how to develop Web
applications using ASP.NET. technology.
ASP.NET stands for Active Server Page.NET. It is a technology (not a programming language) that
allows you to build applications. The applications are then run on the browser, and they are referred
as dynamic Web applications. It is part of the .NET framework and ASP.NET applications can be
written in VB, C++ or C#.
Basic structure of a multitier Web-based application for design and development use:
i. Data store: A relational database to store the data.
ii. Data tier: Retrieve and manipulate the data in the database.
iii. Middle tier: A web server to implement business logic to process client requests and retrieves
data from the database.
iv. Client tier: An application’s user interface that defines what a user should see on the screen.
Developer may use different kinds of data stores in the application. However, SQL Server as a data
store in this course. Data Access Layer (DAL) is the code that executes the database queries such
as retrieve, insert, update, and delete data. Business logic has a role to ensure that data are reliable
before the server application program updates the database. User interface gather input and display
output in the Windows Forms.
177
8.3 Building an ASP.NET Web Application
A Web Form is a page displayed in a client, e.g. Microsoft Internet Explorer. In other words, it
represents the Web page that is sent to a Web browser. Web Form is created with a file extention
.aspx, also known as ASPX file, using VS. Web controls, e.g. labels, button, textbox, can be added in
a Web Form.
Advantages of creating Web Form:
i. Distribution: If there are any changes made to the Web Forms that are installed on the web
server, they are automatically published on the Web server so users who visit the site are
viewing the latest updated application.
ii. Version control: You do not need to worry about the software version used by the user. This
is because all users will access the same application.
iii. Platform independent: As long as you have a browser and are connected to the Web server,
you will be able to access the application regardless of the types of operating system.
Code-behind file is written using VB, which contains classes with event handlers, initialization code,
utility methods and other supporting code. Note that code-behind file is associated with the ASPX file
to provide the actual implementation for the ASPX file. Let’s walkthrough the following steps to create
the Web application in VS.
8.4 Practice: Dynamic web time
This VB program demonstrate the display of Web server’s time in a Web browser.
i. In VS, click File → New Web Site... to display the New Web Site dialog box.
178
ii. Select ASP.NET Empty Web Site, which is belong to Visual Basic, in the Templates pane.
Select File System from the drop-down list, which is next to Web Location to create the Web
application in a directory on your computer. You may change the drive location based on your
computer’s storage, and name the Web application, e.g. WebSite1, before click on OK.
iii. In the Solution Explorer, right-click WebSite1 → Add → Web Form to create a new item, i.e.
a Web Form, as WebTime.
179
iv. A Web Form, i.e. ASPX file named as WebTime.aspx, with the following code is showed upon
the success of above steps. Another code-behind file, i.e. WebTime.aspx.vb, is also created
at the background. Note that do not use blank spaces in the Web application file’s name as
Web browsers do not support a blank space in its Web.
v. Once you have changed the class name in the code-behind file, you will also need to change
the Inherits attribute in the ASPX file. In other words, the value of Inherits attributes (WebTime)
and the class name (WebTime) in code-behind file must be identical.
180
item Note that WebTime inherits from class Page in namespace System.Web.UI. The names-
pace contains classes and controls that help in building Web-based applications.
vi. The <asp:... tag prefix indicates that the label is an ASP.NET Web control, not an XHTML
element. For example, the Web control contains runat=“server”, which shows that the control
will be processed on the server. It is a process of translating the control into XHTML, which that
can be rendered in the client, i.e. Web browser.
vii. Two important tabs are located at the bottom of the WebTime.aspx page, i.e. Source (as
shown as below) and Design. Drag and drop controls from the Toolbox is only allowed in the
Design mode.
viii. Right-click WebTime.aspx → View Designer is another alternative to switch to the Design
mode. Note that Web application filename with blank space is prohibited because browsers do
not support a blank space in its web page address.
181
ix. In Design mode, edit the WebTime.aspx with a Label from Toolbox and its details.
x. (ID) property is set to timeLabel. Delete the value of the Text property. As a result, timeLa-
bel name is displayed in square brackets. Set BackColor, ForeColor and Font properties to
Black, Yellow and 14pt, respectively. Set the EnableViewState property to False.
xi. Select DOCUMENT from the drop-down list in the Properties window and set the Web Form’s
EnableSessionState property to False.
xii. Switch to code-behind file, i.e. WebTime.aspx.vb, by right-click WebTime.aspx → View
182
Code.
xiii. Add a Page Init event handler, which contains code to initialise the page and it sets timeLabel’s
text to the server’s current time.
xiv. Click Internet Explorer/Edge to run the Web application, and output is shown as follows.
8.5 Interface of Web application
In this section, we use Web controls in the Toolbox to create and design a Web Form, i.e. Web
interface.
i. Use an XHTML table element to organise the Images (FirstName, LastName, Email and Phone)
and Textbox controls.
183
ii. Use an Image control to insert an image into a Web page. ImageUrl property specifies the
location of the image to display in the Image control.
iii. Use a DropDownList to include a list of items for selection. After dragging a DropDownList
control onto a Web Form, developer can add items to it using the ListItem Collection Editor.
iv. Use Button control for triggering an action when clicked, e.g. Register button. By default,
controls does not include any functionality, i.e. nothing happens when we click the Register
button.
v. Use HyperLink control to add a hyperlink to a Web page. The NavigateUrl property specifies
the resource (e.g. http://wou.edu.my) that is requested when a user clicks the hyperlink.
vi. Setting of the Target property to blank indicates that the requested Web page is opened in a
new browser window.
8.6 Validation controls
Validation controls are used to ensure that the value in a required field is within reasonable range.
ASP.NET provides built-in validation control object that required developer to write little or without
coding at all. For example:
i. A Postcode field must contain exactly five digits
ii. Last-name field cannot contain numerical digits
Note that when the XHTML page is created, the validation control is converted into JavaScript that
performs the validation. JavaScript is a scripting language that enhances the functionality and ap-
pearance of Web pages. ASP.NET built-in validation control objects are as follows:
i. RequiredFieldValidator verifies that a required field contains data.
184
ii. RegularExpressionValidator verifies that an entry data matches the standard formats.
iii. RangeValidator verifies the value of an input control is within a specified range of values.
iv. CompareValidator verifies that the value entered by the user in an input control with the value
entered in another input control, or with a constant value.
v. CustomValidator verifies the user-defined validation on an input control.
There are three RequiredFieldValidator and two RegularExpressionValidator controls in this pro-
gram. The warning messages are displayed in red colour.
Examples of RequiredFieldValidator and RegularExpressionValidator for emailTextBox are shown
as follows.
Examples of RequiredFieldValidator and RegularExpressionValidator for phoneTextBox are shown
as follows.
185
8.7 Postback
The Web pages is designed such that the current page will reload when the user submits the form. It
enables the program to receive input, process it and display the results in the same page when it is
loaded the second time. This event is known as a postback.
The IsPostBack property to check whether the page is being loaded due to a postback. IsPostBack
is False when the Web page is requested for the first time. IsPostBack becomes True when the
postback occurs (i.e., the user clicks Submit button).
186
8.8 Session tracking
What is session tracking? It is a mechanisms to identify individual clients via a Web’s session. The
client is recognised as the same user if client leaves the Web site and returns later. Tracking a
individual client is known as session tracking.
Usefulness of session tracking:
i. to provide tracking services to each customer’s activities through the Internet.
ii. to combine the collected information provided by the customer, for instance as billing informa-
tion, personal preferences, interests and hobbies.
iii. personalisation of e-businesses: to communicate effectively with their customers, and to im-
prove the customer’s ability to locate desired products and services.
8.9 Cookies
It is a technique of tracking individual Web client. It is also known as a tool for personalising Web
page for Web developer. It is a piece of data stored in a text file on the user’s computer, which is
created upon the first time Web site visiting. Cookie is reactivated each time the user revisiting the
Web site.
Example: an online store’s server will receive a cookie consisting of user unique identifier once client
add items to an online shopping cart. The server will make use of the unique identifier to locate the
shopping cart and perform any necessary processing.
187
The program demonstrate how user choose a favourite programming language and then recommends
a programming book for user based on the language chosen. Details of the program are as fol-
lows.
i. User choose a favourite programming language from a group of radio buttons and then click the
Submit button to send the form to the Web server for processing
ii. The Web server responds by creating a cookie that will store a record of your chosen language
and ISBN number for the particular programming language book
iii. The server then returns an XHTML document to the browser to let user choose another favourite
programming language or view a list of recommended books that you have selected previously
iv. When user click the hyperlink, the cookies previously stored on the client, i.e. a remote com-
puter, will be read and used to form the list of book recommendations
8.10 Summary
In this section, we learnt how to develop ASP.NET Web applications using Web Forms for multiple
pages. Cookies are adopted to maintain user information. We also know the way to use validation
control functions to ensure validity of the user inputs for our web application.
188
9 Topic 9: Advanced Wed-based Application Development
9.1 Objectives
By the end of this section, you should be able to:
i. Connect to a database in ASP.NET based Web application.
9.2 Introduction
In this topic, we are going to learn a development of guestbook application. Suppose that when you
click on the guestbook page, the guestbook page contains fields such as user’s name, email address,
feedback and so on. Once you click on the Submit button, the data you submitted are then stored in
a database located in the Web server’s machine.
The Web application program we are going to create in this topic is more complex, and we are going
to introduce a GridView data control. We present the guestbook application GUI in design mode for
your reference. You can see all the entries in the design form are in tabular format. We will guide you
through the steps to create and configure this GridView control. This form consists of three fields i.e.,
name, email address and a message. The Submit button is used to send the data to the server and
a Clear button is used to reset each of the fields. The guestbook information will be stored in a SQL
Server database called ’Guestbook.mdf’. You can find the ’Guestbook.mdf’ database in the GitHub
repository. You can also see that the GridView displays the data (guestbook entries) in the Messages
table.
9.3 Display data from a database using the Web Form
A guestbook program’s page contains fields, i.e. user’s name, email address, feedback. By clicking
189
Submit button, the data will be stored in a relational database. Note that the guestbook information
will be stored in a Microsoft SQL Server database, which is named as ’Guestbook.mdf’. A GridView
data control is used to populate all records in a database using Guestbook.aspx.
i. Open the Web project as follows.
ii. Create a new database, named as Guestbook, with the given SQL script script create db Guestbook.sql
using the SQL Server xxxx Management Console. Note that pre-loaded data will be stored
in a database table object of database Books. After the successful creation, replace your lo-
cal copies of files Guestbook.mdf and Guestbook log.ldf (given in this course) with those
from the location (example path from the Windows 10 with instance named SQLEXPRESS) C:
\Program Files \Microsoft SQL Server \MSSQL12.SQLEXPRESS \MSSQL.
iii. Re-establishing the database connection by right-click on file Guestbook.mdf. An error mes-
sage will be shown for those using the updated version of SQL Server database, such as SQL
Server 2014 and later version.
iv. Perform the following steps to upgrade the given file Guestbook.mdf
190
v. Enter the appropriate information, including the exact path of file Guestbook.mdf, and proceed
for the upgrading of file Guestbook.mdf
vi. Try this step if you failed with step in previous slide (in upgrading the database file). In Server
Explorer of VS, right-click the Data Connection and choose Add Connection. Enter the ap-
propriate information, including local server name (pre-built in VS) as (localdb)\MSSQLLocalDB,
exact path of file Guestbook.mdf, logical name as GuestbookConnectionString, and pro-
ceed for the upgrading of file Guestbook.mdf
191
vii. The following screenshot shows the established database connection. It contains a database
object, named as Messages. Note that a database used by an ASP.NET web site should be
located in the project’s App Data.
192
9.4 Create the Web Form with database connection
i. Add the LINQ to SQL by right-click App Code in the Solution Explorer. Name the target file
as GuestbookDataClasses.dbml. Then, open the file GuestbookDataClasses.dbml in
the Solution Explorer by double-clicks. Drag the Guestbook database’s Message table from
the Database Explorer onto the Object Relational Designer, and save the project. Binding
the messagesGridView to the Message table of the Guestbook database by using the the
GridView Tasks smart tag menu (via New data sourceaˆ C¦ from the Choose Data Source
drop-down list). Define the data source as messagesLinqDataSource, and choose the option
’*’ during its configuration before save the project.
ii. messagesLinqDataSource control appears on the Web Form directly below the GridView. Check
all the check boxes to enable LINQ to perform INSERT, UPDATE and DELETE.
iii. The event handler for clearButton clears each TextBox. Text property is set to an empty string.
This resets the form for a new guestbook submission. The user’s information is added to the
Messages table using submitButton. Recall that we configured messagesLinqDataSource’s
INSERT command to use the values of the TextBoxes on the Web Form.
iv. A String representation of the current date (e.g., “3/15/88”) to a new object of type Parameter
is created. This Parameter object is identified as “Date” and is given the current date as a
default value. Note that the SqlDataSource’s InsertParameters collection contains an item
named Date, which represents the CurrentDate parameter. Invoking LinqDataSource method,
it executes the INSERT command against the database, thus adding a row to the Messages
table.
v. Launch the Guestbook Web application for previewing the final output as follows.
193
vi. As the data is inserted into the database, the TextBoxes is cleared. The messagesGridView’s
DataBind method is invoked to refresh the data that the GridView displays. This causes mes-
sagesLinqDataSource (the data source of the GridView) to execute its SELECT command to
obtain the Messages table’s newly updated data. Note that this project can be created using
ASP .NET Web Form Site in the New Web Site of VS.
To learn more about connecting to a database using ASP.NET, please read following material:
i. Deitel, P J and Deitel, H M (2009) Visual Basic 2008: How to Program, Upper Saddle River,
New Jersey: Pearson Education, Prentice Hall, pp. 1122 - 1131.
9.5 Useful codes
A sample VB script for the Submit button.
194
1: Protected Sub btnSubmit Click(ByVal sender As Object,
2: ByVal e As System.EventArgs) Handles btnSubmit.Click
3:
4: ’ create dictionary of parameters for inserting
5: Dim insertParameters As New ListDictionary()
6: insertParameters.Add(”Date”, Date.Now.ToShortDateString())
7: insertParameters.Add(”Name”, txtBoxName.Text)
8: insertParameters.Add(”Email”, txtBoxEmail.Text)
9: insertParameters.Add(”Message”, txtBoxMessage.Text)
10: ’ execute an INSERT LINQ statement to add a new entry
11: messagesLinqDataSource.Insert(insertParameters)
12:
13: ’ clear the TextBoxes
14: txtBoxName.Text = String.Empty
15: txtBoxEmail.Text = String.Empty
16: txtBoxMessage.Text = String.Empty
17:
18: ’ update the GridView with the new database table contents
19: messagesGridView.DataBind()
20: End Sub ’ btnSubmit Click
A sample VB script for the Clear button.
1: ’ Clear Button clears the Web Form’s TextBoxes
2: Protected Sub btnClear Click(ByVal sender As Object,
3: ByVal e As System.EventArgs) Handles btnClear.Click
4:
5: txtBoxName.Text = String.Empty
6: txtBoxEmail.Text = String.Empty
7: txtBoxMessage.Text = String.Empty
8: End Sub ’ btnClear Click
A sample SQL, i.e. script create db Guestbook.sql, for this topic.
1 DROP DATABASE Guestbook
2 GO
3
4 CREATE DATABASE Guestbook
5 GO
6
7 USE Guestbook
8 GO
9
10 SET ANSI_NULLS ON
11 GO
12 SET Q UOTED_ IDENTI FIER ON
13 GO
195
14 SET ANSI_PADDING ON
15 GO
16 CREATE TABLE [ dbo ].[ Messages ](
17 [ MessageID ] [ int ] IDENTITY (1 ,1) NOT NULL ,
18 [ Date ] [ varchar ](20) NOT NULL ,
19 [ Name ] [ varchar ](50) NOT NULL ,
20 [ Email ] [ varchar ](50) NOT NULL ,
21 [ Message ] [ text ] NOT NULL ,
22 CONSTRAINT [ P K _ _ M e s s a g e s _ _ 7 C 8 4 8 0 A E ] PRIMARY KEY CLUSTERED
23 (
24 [ MessageID ] ASC
25 ) WITH ( PAD_INDEX = OFF , S T A T I S T I C S _ N O R E C O M P U T E = OFF , IGNORE_DUP_KEY =
OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
26 ) ON [ PRIMARY ] TEXTIMAGE_ON [ PRIMARY ]
27
28
29 GO
30 SET ANSI_PADDING OFF
31 GO
32 SET IDENTITY_INSERT [ dbo ].[ Messages ] ON
33
34 INSERT [ dbo ].[ Messages ] ([ MessageID ] , [ Date ] , [ Name ] , [ Email ] , [ Message ])
VALUES (3, N ’6/27/2016 ’ , N’Bob Green ’, N’[email protected] ’, N’Great
site ! ’)
35 INSERT [ dbo ].[ Messages ] ([ MessageID ] , [ Date ] , [ Name ] , [ Email ] , [ Message ])
VALUES (4, N ’6/28/2016 ’ , N’Sue Black ’, N’[email protected] ’, N’I love
the site! Keep up the good work!’)
36 INSERT [ dbo ].[ Messages ] ([ MessageID ] , [ Date ] , [ Name ] , [ Email ] , [ Message ])
VALUES (10, N ’6/29/2016 ’ , N’Liz White ’, N’[email protected] ’, N’Very
useful information. Will visit again soon.’)
37 SET IDENTITY_INSERT [ dbo ].[ Messages ] OFF
38 USE [ master ]
39 GO
40 ALTER DATABASE Guestbook SET READ_WRITE
41 GO
9.6 Summary
In this section, We learnt the way to use the GridView control to display data from a SQL Server on
the Web Form.
196
10 Topic 10: Object-Oriented Programming (OOP)
10.1 Objectives
By the end of this section, you should be able to:
i. How to declare a class with a method and instantiate an object of a class
ii. How to declare a method with a parameter
iii. How to initialise objects with constructors
iv. How to implement an inheritance class
v. How to implement the method overloading and method overriding
vi. How to design the interface class
vii. How to implement the concept of encapsulation and polymorphism
10.2 Introduction
Object-oriented (OO) programs are based on objects that are created from classes. Each object is an
instance (member) of a class. As a result, classes are the building blocks of an OO program. A list of
VB program is prepared to demonstrate how OO concepts using VB code. Examine the VB code as
available at GitHub repository.
10.3 Classes, objects, methods and instance variables
An object is an instance (member) of a class, and it is known that a class consists of a set of related
objects. In VB, a class can store and retrieve values of the properties and carry out the methods. For
example, the textbox control is a class with a Text property. String class has a ToLower() method for
converting the string to lower case characters.
In another example, a class that represents a bank saving account might contain many methods. A
first method could be to deposit money in the savings account; a second method could be to withdraw
money from the savings account; and a third method is to enquire about the savings balance. Credit
197
card receipt and student are other examples of classes that can relate to your real life. Note that an
object of a class is required for a program to perform tasks
A scenario of listen to the radio: increasing the sound volume requires a message to the radio to
perform a task, i.e. to make the radio volume louder or to instruct the amplifier to increase the output
volume technically. In OOP, developer send messages to an object, and each message is known
as a method call. Message tells one of an object’s methods to perform its task. e.g. a radio is an
object, the amplifier is also another object. Note that an object may be made up with a group of other
objects.
A class specify the attributes and behaviours of the objects. For example, a car has attributes such
as colour, number of doors and wheels. In another example, a savings account is an object, which
has a balance attribute. Note that each savings account knows the balance in its own account but
not the balances of other accounts in the bank. This is the concept of encapsulation or information
hiding.
1 Module GradeBookTest
2 Sub Main()
3 ’ initialize gradeBook to refer to a new GradeBook object
4 Dim gradeBook As New GradeBook()
5
6 ’ call gradeBook ’s DisplayMessage method
7 gradeBook.DisplayMessage()
8 End Sub
9 End Module
A constructor is used when an object is created to initialise the object’s data. VB allows developer to
create objects (e.g. gradeBook) with the same name as their class (e.g. GradeBook). DisplayMes-
sage() method displays a message on the console screen. Note that an object of class GradeBook is
creasted, and it calls DisplayMessage() method.
198
1 Public Class GradeBook
2 ’ display a welcome message to the GradeBook user
3 Public Sub DisplayMessage()
4 Console.WriteLine("Welcome to the Grade Book!")
5 End Sub
6 End Class
Keyword Public is an access modifier. Every class declaration consists of the keyword Class followed
by the name of the class (GradeBook) and ends with the keyword End Class
Class GradeBook consists of one method i.e. DisplayMessage(). Public indicates that the method
is “available to the public”, that means methods from other objects can call it. Sub indicates that
the DisplayMessage() method will perform a task, but it will not return any information to its calling
method when it completes its task. An empty set of parentheses DisplayMessage() indicates that
this method does not need any parameters. Note that Main method is called automatically when
developer execute an VB application, e.g. the Main method in GradeBookTest.
Attributes are represented as variables in a class declaration. Note that these variables are called
instance variables. Instance variables are declared inside a class declaration, e.g. courseNameValue
in GradeBook program. vbCrLf constant identifier represents a combination of the carriage return
and line feed characters. It makes the subsequent text to be displayed at the beginning of the next
line.
10.4 Variable types
A variable of a value type (such as integer, string) simply contains a value of that type.
A variable of a reference type (also known as reference) contains the memory address of the location
where the data is referred to that variable. This means variable refers to an object in the program.
Reference type instance variables are initialised to the value Nothing by default. Note that there is an
empty box representing the String variable courseNameValue in the memory.
199
10.5 Constructor
A constructor call is required for every object that is created. In fact, we have already used this
concept. The New keyword calls the class’s constructor to perform the initialisation.
Example: Dim gradeBook As New GradeBook
Note that the New keyword calls the class’s constructor to perform the initialisation. In the given
example, there is no parenthesis after New GradeBook, indicating that a call to the class’s constructor
takes no arguments. Constructor declarations cannot return values but it returns a reference to an
object of its class type. Constructors are usually declared as Public.
In another example, input student name in text box. When you click on the button, it displays first
name. Create a class Room with instance variables for the data item student. The Room class should
have instance variable, property procedure and a single constructor with optional parameter.
A pseudocode of Room class is as follows:
1: Public Class Room
2: ’ instance variables
3: Private student As String
4: ’ constructor
5: Public Sub New(Optional ByVal theStudent As String = ””)
6: student = theStudent
7: End Sub
8: ’ Property procedures
9: Public Property Student() As String
10: Get
11: Return student
12: End Get
200