VB.NET
Types of Application
Architecture
Applications
are developed to support organizations in their business operations. Application
accepts input, process the data based on business rules and provide data as
output. The function performed by an application can be divided into three
categories:
User
services
Business
services
Data
services.
Each
category is implemented as a layer in an application. The user services layer
constitutes the front end of a solution. It is also called a presentation layer
because it provides an interactive user interface
The business
services layer controls the enforcement of business rules on the data of an
organization. Business rules encompass those practices and activities that
define the behavior of an organization. The business services layer performs
validations pertaining to business rules.
The data
services layer comprises the data and the functions for manipulating the data.
Application
Architecture
1. Single
Tier Architecture -> Based on Single Software
2. Two Tier
Architecture
3. Three
Tier Architecture
4. n-Tier
Architecture (HTML -> VBScript ->
ASP -> Oracle -> XML)
MVC Architecture
Model
View Controller Architecture
Model ->
Business Logic -> EJB -> COM+ (Component Object Model)
View ->
Output -> JSP -> ASP.NET (or) VB.Net
Controller
-> Controlling Pages. -> ASP.Net
.NET Initiative
Microsoft
has introduced the .NET initiative with the intention of bridge the gap in interoperability
between applications. It aims at integrating various programming languages and
services.
It is designed to make significant improvements in code
reuse, code specialization, resource management, multi language development,
security, deployment and administration.
The .NET
Initiative offers a complete suite for developing and deploying applications.
This suite consists of .NET products, .NET services, and the .NET framework.
.NET Products
Microsoft
has already introduced Visual Studio .NET, which is a tool for developing .NET
application by using programming languages such as Visual Basic, C# and Visual C++.
In addition, Microsoft also intends to introduce .NET versions of the Windows
operating system and Office suite. These products aim at allowing developers to
create applications that are capable of interacting seamlessly with each other.
To ensure interaction between different applications, all .NET products use
eXtensible Markup Language (XML) for describing and exchanging data between applications.
.NET services
.NET
delivers software as Web Services. Therefore, users can subscribe to a web
service and use it as long as they need it, regardless of the hardware and
software platform.
Microsoft is coming up with its own set of web services,
known as My Services. These services are based on the Microsoft Passport
authentication service, the same service that we used in Hotmail. They allow
the consumers of the services to access data by linking calendars, phonebooks,
address books, and personal references to the Passport Authentication service.
In addition to the Web services provided by Microsoft, third party products and
services can also be integrated easily with the .NET environment
The .NET Framework
It is the
foundation on which you design, develop and deploy applications. Its consistent
and simplified programming model makes it easier to build robust applications.
.NET Products
Visual
Basic.NET
Visual
C++.NET
C#
ASP.Net
J#
XML
Namespace
Collection
of classes and Interfaces are packed.
Interfaces
Set
of incomplete methods.
MultiThreading ->
I/O Packages
Networking
Assembly -> Deployment purpose
Garbage Collection ->
Security
.Net Framework
Managed Code Execution Process
1. When you compile a program developed in a
language that targets the CLR, instead of compiling the sourcecode into machine
level code, the compiler translates into Microsoft Intermediate Language (MSIL)
or Intermediate Language (IL). No matter which language has been used to
develop the applications, it always gets translated into IL. This ensures
language Interperability.
2. In
addition to translating the code into IL, the compiler also produces metadata
about the program during the process of compilation. Metadata contains the
description of the program, such as the classes and interfaces, the
dependencies and the versions of the components used inthe program.
3. The
IL, and the meta data are linked in assembly
4. The
compiler creates the .EXE or .DLL file
5. When
you execute the .EXE or .DLL file, the code (converted into IL) and all the
other relevant information from the base class library is sent to the class
loader. The class loader loads the code inthe memory.
6. before
the code can be executed, the .NET framework needs to convert the IL into
native or CPU specific code. The Just In Time (JIT) compiler translates the
code from IL into managed process of compilation, the JIT compiler compiles
only the code the code that is required during execution instead of compiling
the complete IL code. When an uncompiled method is invoked during execution,
the JIT compiler converts the IL for that method into native code. This process
saves the time and memory required to convert the complete IL into native code.
7. During
JIT compilation, the code is also checked for type safety. Type safety ensures
that objects are always accessed in a compatible way. Therefore, if you try to
pass an 8 byte value to a method that acceps 4 byte value as its parameter, the
CLR will detect and trap such an attempt. Type safety also ensures that objects
are safely isolated from each other and are therefore same from any inadvertent
or malicious corruption
8. After
translating the IL into native code the converted code is sent to the .NET
runtime manager.
9. The
.NET runtime manager executes the code. while executing the code, a security
check is performed to ensure that the code has the appropriate permissions for
accessing the available resources.
Unicode
characters - 2 Bytes
Features Provided CLR
1.
Automatic memory management
2.
Standard type system
3.
Language Interperability
4.
Platform Independence
5.
Security Management
6. Type
safety
Advantages of .NET Framework
1.
Consistent Programming Model
2. Multi
platform applications
3. Multi
Language Integration
4.
Automatic resource management
5. Ease of
deployment
Visual Basic .NET
* Supports Object
Oriented Programming full fledgely.
* Supports Structured
Exception Handling
* Supports Multithreaded
Programming
Features of .NET
1.
Inheritance
2.
Constructor and Destructor
3.
Overloading
4.
Overriding
5.
Structured Exception Handling
6.
Multithreading
Inheritance
Inheritance is the ability of a
class to derive its characteristics from an existing class
Syntax:
class base
Statements
End class
class DerivedClass Inherits ParentClass
...........
End Class
It is possible to create a base
class in any language and inherits its properties in a derived
class
created using another language. It provides the advantage of code reusability
across languages.
Constructors and Destructors
Constructor -> Used to initialize
the members of the class
Destructor -> Releases the
resources used by an object
Overloading
function nane similar
passing parameters are different
Syntax:
Function Overloads
function_name(parameter list) as return type
Overriding
class base
{
virtual public void
show();
public void fun1();
}
class derived : public base
{
public void show();
public void fun1();
}
derived d;
base b;
base *b1;
b1 = &d;
b1->show();
b1->fun1();
Syntax:
Public Overrides Function func1()
Structured Exception Handling
VB.Net Supports
structured exception handling that consists of protected blocks of code and
filters for the possible exceptions that can be raised by the program.
try
{
Codings
}
catch(Exception)
{
Exception Handling code
}
Multithreading
Multithreading enables an
application contain one or more threads that can share workload in an
application by executing one at a time.
Visual Studio .NET IDE
1. Projects and Solutions
Projects-> Contains Forms and
modules.
Solutions -> Contains one or more
projects.
Project Types
1. Visual Basic Projects
2. Visual C#
3. Visual C++
4. Setup and Deployment Application
Templates
Windows Application -> Stand
alone windows application
Class Library -> Create reusable class library
Windows Control Library -> Custom
Control creation
ASP.NET Web Application -> Create
Web Application
ASP.NET Web Service -> HTTP and
XML to communicate with client applications.
Web Control Library -> Custom
control used in web application
Console application -> create
console application run in command line
Windows Service -> Background
service such as monitoring
Empty Project
Empty Web Project
New Project in Existing Folder ->
Adding Existing files.
User Interface Elements of Visual
Studio .NET IDE
1. Windows Form Designer
2. Solution Explorer Window
3. Properties Window
4. Toolbox
5. Output window
6. The task list window
7. Server Explorer window
8. Dynamic Help window
9. Class view window
10. Code and Text editor window
Object Orientation in
Visual Basic.NET
OOPS -> Object oriented
programming system
1. Classes
and Object
2. Data
Abstraction and Encapsulation
3.
Inheritance
4.
Polymorphism
5.
Overloading
Arrays ->
Collection of like data types.
Structure
Collection
of unlike variables, methods and constructors.
Syntax:
Structure struc_name
access_specifier
var_name as Datatype 'Variables
access_specifier
Sub proc_name(ByVal var as Datatype)
'Sub Procedure
Statement
End Sub
access_specifier
function func_name(ByVal var as Datatype) as DataType
return
var_name
End function
Sub New()
'Constructor
Statements
End sub
.........
End Structure
Eg:
Structure
Emp
Dim
Eno as Integer
Public
Ename as String
Public
Salary as Single
Public
Sub DisplayEmp()
Msgbox
"Empno : " & eno
Msgbox
"Empname : " & ename
Msgbox
"Salary : " & salary
end
sub
End
Structure
Access_Specifier
Public - A
structure declared with the Public keyword is accessible from anywhere within or
outside the application. This is the default access mode.
Protected - A
structure declared with the Protected keyword is accessible only from within its
own class or from a derived class
Friend - A structure declared with the Friend
keyword is accessible from within the program that contains the declaration and
from anywhere else in the same program
Protected Friend -
A structure declared with the Protected Friend keyword is accessible from
within the same assembly and in the derived class.
Private - A
structure declared with the Private Keyword is accessible only from within its declaration
context, including any nested procedures.
(Static)Shared
Variables.
*
Initialized with zero when the first object is created. No other initialization
is permitted.
* Only one
copy of the member is created and shared by all objects.
* Without
creating object the member can be accessed by using structure name.
Shared Methods
* It access
only shared variables.
* Without
creating object the method can be accessed by using structure name.
Eg:
Structure
Student
sno
as Integer
sname
as String
shared
count as integer
End
Structure
Dim s1(10)
as Student
Including Procedure
Structure
order_details
Public
Inv_no as String
Public Ord_dt as Date
Public
CustName as String
Public
Product as String
Public
Cost as Double
Public
Advance_amt as Double
Public
Due_amt as Double
Public
Sub CheckCost (ByVal Cost as Double)
if
Cost < 10 then
Cost
= 10
End
If
End Sub
Shared
count as Integer
End Structure
Storing data within a Structure
Dim
ord1 as order_details
ord1.count
= ord1.count + 1
Dim
ord2 as order_details
ord2.count
= ord2.count + 1
ord1.Inv_no
= "I0001"
ord1.Ord_dt
= #01/31/1980#
ord1.CustName
= "Jack"
ord1.Product
= "ABC"
ord1.Cost
= 450.00
ord1.Advance_amt
= 200.00
ord1.Due_amt
= 250.00
Accessing Data from a structure
if
ord1.Inv_no = "" then
Msgbox("Please
enter the invoice number")
End if
Eg:
Structure Emp
Dim eno As Integer
Dim ename As
String
Dim salary As
Integer
Shared count As
Integer
Sub getEmp()
eno =
Integer.Parse(InputBox("Enter Eno"))
ename =
InputBox("Enter empname")
salary =
Integer.Parse(InputBox("Enter Salary"))
count =
count + 1
End Sub
Sub
displayemp()
MsgBox("Empno : " & eno)
MsgBox("Empname : " & ename)
MsgBox("Salary : " & salary)
End Sub
Shared Sub
displayCount()
MsgBox("No of Objects Created is " & count)
End Sub
Sub New(ByVal
no As Integer, ByVal name As String, ByVal sal As Integer)
eno = no
ename =
name
salary =
sal
count = count + 1
End Sub
End Structure
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim e1(10) As
Emp
Dim e2 As Emp =
New Emp(1000, "Kirthika", 2000)
e2.displayemp()
Dim n, i As
Integer
n =
Integer.Parse(InputBox("Enter how many employees"))
For i = 0 To n
- 1
e1(i).getEmp()
Next
For i = 0 To n
- 1
e1(i).displayemp()
Next
Emp.displayCount()
End Sub
End Class
Classes Vs Structures
Collection
of member variables and methods
Similarities
* Both can
have members, including constructors, properties and constants.
* Both can
implement Interfaces (Set of incomplete methods)
* Both can
have shared constructors with parameters
Shared Keyword
In
a class or a structure, the Shared Keyword indicates that one or more
programming elements are shared. The Shared programming elements are not
associated with a specific instance of a class or structure. To access a shared
element, we need to qulify it with the class or structure name. We can also
access a shared element by qualifying it with the object name of the class or
structure. For example, if we declare a field in our class to count the number
of instances of the class, we can make it a shared field. All the instances of
the class will access the same shared member.
Differences
Class
|
Structure
|
A Class is inheritable from other existing classes
|
A structure is not inheritable
|
A class can have instance constructors with or without
parameters
|
A structure can have instance constructors only if they
have take parameters
|
A class is a referenced type (ByRef)
|
A structure is a value type. (ByVal)
|
The members of a class can be initialized within class
declaration
|
The members of a structure cannot be initialized within
the structure declaration
|
The Variables and constants declared in a class have
Private by default
|
A members of a structure have Public Scope by default
|
Class procedures can handle events
|
Structure procedures cannot handle events.
|
Abstract Class
Set of
complete and Incomplete methods. the
derived class can implement the methods. In VB.Net the abstract class is
created using MustInherit keyword in the class definition.
Eg:
Public class
Form1 Inherits System.Windows.Forms.Form
Dim
emp as New Emp_Details()
Private Sub Button1_Click(ByVal
sender as System.Object, ByVal e as System.EventArgs) Handles Button1.Click
emp.Annual_Salary(TextBox1.Text)
emp.disp()
End Sub
End Class
Public
MustInherit Class EmployeeDetails
Public
MustOverride Sub Annual_Salary(ByVal m As Integer)
Public
Sub disp()
MsgBox("Sample Method")
End
Sub
End Class
Public Class
Emp_Details
Inherits
EmployeeDetails
Dim
salary as Integer = 30000
Dim
months as Integer = 6
Public
Overrides Sub Annual_Salary(ByVal m as Integer)
salary
= salary * m
Msgbox("The
Total salary is : " & salary) salary
= 30000
End
sub
End Class
Eg:
Public MustInherit Class MyAbstractClass
Public MustOverride
Sub display(ByVal a As Integer)
Public Sub
MyAbstractsub()
MsgBox("Abstract Class method")
End Sub
End Class
Public Class DerivedClass
Inherits
MyAbstractClass
Public Overrides
Sub display(ByVal a As Integer)
MsgBox("The value of a = " & a)
End Sub
End Class
Public Class DerivedClass1
Inherits
MyAbstractClass
Public Overrides
Sub display(ByVal a As Integer)
MsgBox("Square Value is " & (a * a))
End Sub
End Class
Private Sub
cmdDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles cmdDisplay.Click
Dim n As
Integer
n =
Integer.Parse(InputBox("Enter a number"))
Dim d1 As New
DerivedClass
d1.display(n)
d1.MyAbstractsub()
End Sub
Private Sub
cmdSquare_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles cmdSquare.Click
Dim n As
Integer
n =
Integer.Parse(InputBox("Enter a number"))
Dim d2 As New DerivedClass1
d2.display(n)
d2.MyAbstractsub()
End Sub
Interface
Set of
incomplete methods. Alternate for Multiple Inheritance
Syntax:
Interface
Iface_name
....
End
Interface
Eg:
Interface
IOrderDetails
Property
CustName() As String
Sub
UpdateCustStatus()
Function
Calculate(ByVal m as integer) as Integer
Event
Update_Complete()
End
Interface
Eg:
Interface
OrderDetails
Sub
Disp()
End
Interface
Public
Class MyOrder
Implements
OrderDetails
Sub
disp() Implements OrderDetails.disp
Msgbox
"MyOrder disp method"
End
Sub
End
Class
Public
Class AnotherOrder
Implements
OrderDetails
Sub
disp() Implements OrderDetails.disp
Msgbox
"Another Order disp method"
End
Sub
Sub
MyMethod()
Msgbox
"Non Interface Method"
End
Sub
End
Class
MyOrder
m1
m1.disp
AnotherOrder
a1
a1.disp
a1.MyMethod
OrderDetails
a2
a2.disp
a2.MyMethod()
'Error
Note
We can
declare only methods, functions, properties and events in an interface. We
cannot declare a variable in an interface.
Interface Inheritance
Interface
Validate_Cust
Sub
Validate_Custname()
End
Interface
Interface
IOrderdetails
Inherits
Validate_Cust
Property
CustName() as String
Sub
UpdateCustStatus()
Event
Update_Complete()
End
Interface
Members of an
Interface
Sub
Validate_Custname()
Property
CustName() as String
Sub
UpdateCustStatus()
Event
Update_Complete()
Note:
Interface
statements are Public by default.
Constructors
Automatic
initialization of object
Two types of
constructors
1.
Shared constructors
2.
Instance Constructors
Shared Variable
* Initialize
with Zero, when the first object is created. No other initialization is permitted.
* Only one
copy of the variable is created and can be accessed by all objects.
Shared Methods
* Access
only Shared Variables
* Without
creating object the method can be accessed using class name.
Shared constructors
Used to
initialize shared variables of type. A shared constructor will not run more
than once during a single execution of program.
Eg:
Public Class
MyClass1
Public Shared x As Integer
Public y As Integer
Shared Sub New()
x = 10
'
y = 20
End Sub
Sub New()
y = 20
End Sub
Sub New(ByVal a As Integer, ByVal b As
Integer)
x = a
y = b
End Sub
Protected Overrides Sub Finalize() 'Destructor
MsgBox("Destructor Called")
x = 0
y = 0
End Sub
End Class
Private Sub
Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim m1 As New MyClass1
MsgBox(m1.x)
MsgBox(m1.y)
Dim m2 As MyClass1
m2 = New MyClass1(60, 70)
MsgBox("x = " & m2.x)
MsgBox("y = " & m2.y)
End Sub
Instance Constructor
Used to
initialize variables that are declared with Dim, Public, Private, Friend,
Protected and Protected Friend. Also access the shared variable within an
instance constructor.
Sub
New(ByVal a as integer)
end Sub
Destructor
Used to
destroy Objects
Methods Used
Finalize()
-> To release the last reference object
Dispose()
-> To release resource, such as Database connection file
closing etc.
Inheritance
*
Resuability of code
*
Extensibility of code
Types
Single
Multiple
Multilevel
Hybrid ->
Combination of multiple and multilevel
Hierarchical
Eg:
1. FirstForm (Base)
Reset
Button cmdReset
Exit Button cmdExit
2. Codings
Public
Overridable Sub cmdReset_Click()
Msgbox
End Sub
Public
Overridable Sub cmdExit_Click()
Msgbox
End Sub
3. Build the
application
4. Solution Explorer
-> Right Click-> Add Inherited Form
5. SecondForm
(Inherit FirstForm)
6. Add Additional
Controls
7. Code Windows
(select Overrides -> cmdReset , cmdExit)
Procedures
Sub
Procedure
Function
Property
Event
Procedure
Sub Procedure
Access_specifier
Sub Proc_name(ByVal arg as Datatype)
Statement
End
Sub
Procedure Overloading
Procedure
name similar, passing argument differs
Sub
proc1()
End
Sub
Sub
proc1(ByVal m as Integer)
End
Sub
Procedure Overriding
Procedure
name and passing arguments are similar
Base
Class
Public
Overridable Sub Procedure_name()
End
Sub
Derived Class
Public
Overrides Sub Procedure_name()
End
Sub
Note: Doesn't return any value
Calling Sub procedure
Procedure_name(arguments)
(or)
Call
Procedure_name(arguments)
Function Procedure
Access_specifier
Function func_name(arguments) as Return_Datatype
func_name
= return value
(or)
return
ret_val
End
Function
Function Overloading
Function Overriding
Property Procedure
BackColor
= red
Public
class Customer
Private
col as System.Drawing.Color
Public
Property BackColor() as System.Drawing.Color
Set(ByVal
col1 as System.Drawing.Color)
col
= col1
End
Set
Get
Return
col
End
Get
End
Property
End Class
Event Procedure
Button_click()
List_SelectedIndexChanged()
Predefined Procedures
(Dialog)
Msgbox ->
Msgbox("Message",Button Style,"Title")
InputBox
-> InputBox("Message","title","default
Value",X pos,Y Pos)
CommonDialog Classes
ColorDialog
FontDialog
FileDialog
OpenFileDialog
SaveFileDialog
PrintDialog
PageSetupDialog
ADO.NET
ActiveX Data Object (ADO)
.NET
Application to communicate with a database for inserting,updating and
retrieving data.
Features
1. Disconnected
Architecture
Applications connect to the database
only while retrieving and updating data. After data is retrieved, the
connection with the database is closed.
2. Data cached in
Datasets
A
dataset is a cached set of database records. We can work with the records stored
in a dataset as we work with real data; the only difference being that the
dataset is independent of data source and we remain disconnected from the data
source. As a result, resources are saved and the database can meet the
increasing demands of users more efficiently.
3. Data Transfer in XML Format
XML
is an industry standard Format for exchaning information between different
applications. Since a Dataset is stored in the XML format, we can transmit it
between different types of application that support XML and any component that
can read the dataset structure can process the data.
4. Interaction with
the database is done through data commands
All
operations on the database are performed by using data commands. A data command
can be a SQL statement or a Stored procedure.
ADO.NET Object Model
Provider -> The Data residing in a
database is retrieved through data provider.
Dataset -> The Data is cached in a
dataset and the application accesses the data from the dataset.
DataReader -> In this method, a
DataReader object, which is component of the data provider, uses the connection
object to connect to the database, uses the command object to retrieves data,
and provides data to the application in a read-only and forward only mode.
Data Providers
Two
types of Data Providers:
OLE DB Data Provider
Works
with all type of OLEDB Providers.
namespace ->
System.Data.OleDb
SQL Server Data Provider
Working
with SQL Server
namespace
-> System.Data.SqlClient
Connection
ConnectionString
() -> Specify the name of the server, username, password etc.
Open()
-> Establish the connection
Close()
-> Close the Connection
State ->
0 value indicates the connection is closed
1 value indicates the connection is opened.
Eg:
Connecting with SQL -
Server
Imports
System.Data.SqlClient
Private Sub
Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
Dim con As
SqlConnection
con = New SqlConnection("server=server;Database=Master;user
id=sa;password=killer")
con.Open()
MsgBox("Connection Opened")
con.Close()
End Sub
Connecting with MS -
Access
Imports
System.Data.OleDb
Dim con As OleDbConnection
con = New
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=d:/demo/vb.net/sampleDB.mdb")
con.Open()
MsgBox("Database Connected")
con.Close()
Data Adapter
Data is
transfered to and from a database through a data adapter.
SqlDataAdapter
-> SQL - Server
OleDbDataAdapter
-> Other Database
Properties and
Methods of Data Adapter
SelectCommand -> Refers to a SQL
Statement or a Stored procedure to retrieve data from the database
InsertCommand -> Refers to a data
command to insert data into a database
UpdateCommand -> Refers to a data
command to update a database
DeleteCommand -> Refers to a data
command to delete from a database
Fill() Method -> Fills the dataset
with the records from a database
Update() Method -> Executes the
correspoding InsertCommand, UpdateCommand or DeleteCommand row to reflect the
changes in the database.
Eg:
Drag a
SqlDataAdapter1
Connect
with Database and Select the Table using Query Builder
Select
SqlDataAdapter1 -> Data Menu -> Generate Dataset -> DSCust
Drag a
Datagrid Control and set the Datasource = DScust1.CustomerTracking
Codings
SqlDataAdapter1.Fill(DsCust1)
DataCommand
A
DataCommand is a SQL Statement or a Stored procedure that is used to retrieve,
Insert, Delete or modify data in a Data source.
SQLCommand
-> SQL - Server
OleDbCommand -> Other Database
Eg:
Dim con As New SqlConnection
Dim command As
New SqlCommand
con = New
SqlConnection("server=system8;database=master;user id=sa;password=killer")
command = New
SqlCommand("Insert into Customertracking
values('C006','Vidhya','Nandhini','23 KK
Nagar',23345,'vidhya@rediff.com')", con)
Dim r As
Integer
command.Connection.Open()
r =
command.ExecuteNonQuery()
command.Connection.Close()
MsgBox("Record Inserted")
DataReader
Data
Reader is used to retrieve data from a data source in a read only and forward
only mode.
Methods Used
Read() ->
Read Current row
Close()
-> Close the DataReader
NextResult()
-> Move to Next Record Pointer
Eg:
Dim custid As String
custid =
InputBox("Enter Customer ID")
Dim con As New
SqlConnection
Dim command As
New SqlCommand
con = New
SqlConnection("server=system8;database=master;user
id=sa;password=killer")
command = New
SqlCommand("Select * from customertracking", con)
Dim dr As
SqlDataReader
command.Connection.Open()
dr =
command.ExecuteReader()
While
(dr.Read())
If (dr(0) =
custid) Then
txtCustid.Text = custid
txtFname.Text = dr(1)
txtLname.Text = dr(2)
txtAddress.Text = dr(3)
txtPhone.Text = dr(4)
txtEmail.Text = dr(5)
End If
End While
command.Connection.Close()
End Sub
DataSet
When
a connection is established with the database, the data adapter creates a
dataset and stores data in it. After the data is retrieved and stored in a
dataset, the connection with the database is closed. Such working architecture
is called disconnected architecture. The dataset acts like a virtual database
containing tables,rows and columns.
Dataset Object Model
The Dataset is present as a Dataset class in the System.Data
namespace. The Components of the dataset object model are
Component
|
Description
|
DataTableCollection
|
It Contains all the tables retrieved from the data source
|
DataRelationCollection
|
It contains relationships and the links between tables in
a dataset
|
ExtendedProperties
|
It contains additional information, such as the SQL statement
for retrieving data and the date time stamp for the retrieved data
|
DataTable
|
It represents a table in the DataTableCollection of a
dataset
|
DataRelation
|
It represents a relationship in the DataRelationCollection
of a dataset
|
DataRowCollection
|
It contains all the rows in a DataTable
|
DataView
|
It represents a fixed customized view of a DataTable
|
PrimaryKey
|
It represents the column that uniquely identifies a row in
a DataTable
|
DataColumnCollection
|
It contains all the columns in a DataTable.
|
Connecting to a
Database
There are
three methods to create a data adapter.
* Manually
* Through a
Wizard
* Using the
Server Explorer Window
Types of Datasets
Datasets
are of two types.
1. Typed
2. Untyped.
Typed Dataset
A typed
dataset is derived from the Dataset class and has an associated XML schema,
which is created at the time of the creation of the dataset. The XML schema
contains information about the dataset structure, such as the tables, columns
and rows. Data is transferred from a database into a dataset and from the
dataset to another component in XML format.
XML Schema
Definition (CSD) language is used to define the elements and attributes of XML
documents. Since a typed dataset structure is stored in an XML format, the
dataset is saved as an XSD file. This structure of a typed dataset is decided
at the time of its creation. When a typed dataset is created, the data commands
are generated automatically by using the column names from the data source.
Tables and their columns can be accessed by their names while programming.
Dim custid
as string
custid =
DSCust.CustomerTracking(0).CustID
Untyped Dataset
An untyped
dataset does not have any associated XML schema. In an untyped dataset, the
tables and columns are represented as collections. Since an XML schema is not
created for an untyped dataset, the structure of an untyped dataset is not
known during compilation.
Dim custid as
String
OleDbDACust.Fill(DSCust)
custid =
CType(DSCust.Tables("CustomerTracking").Rows(0).Item("CustID"),String)
* Using Data
Adapter
* Complex
Data Binding -> Data Grid
Implementing Simple
Data Binding
Navigating Between
Records
For every
data source that is bound to a Windows Form, there exists a CurrencyManager
object. The CurrencyManager object handles the binding to the data source by
keeping a pointer to the current item in the record list. The Currencymanager
class is derived from the BindingManagerBase class. If all the Windows Form
controls are bound to a single Data source, the form will have one
CurrencyManager object associated with it. A BindingContext object, Which is a
Windows Form object, is usd to keep track of the existing CurrencyManager
objects in a form.
Connecting to a
Database through Wizard
1. Drag a
OleDB or SqlDataAdpter control
2. Select
the Servername and Enter user id,password and select the database
3. Query
Builder -> Select the Tablename and add required columns
4. Finish
the wizard
Creating Dataset
1. Select
the OleDB or SqlDataAdapter
2. From
Data Menu -> Choose Generate Dataset
3. Enter
the Dataset name and select the corresponding table and click ok.
Data Binding
1. Simple
Data Binding
2. Complex
Data Binding
Complex Data binding
Binding
with Listbox, Datagrid Control with multiple values or multiple columns
For Datagrid Control
Properties
DataSource -> Dataset name
DataMember -> Table Name
ListBox
Datasource -> Dataset name
DisplayMember -> Column name
Simple Data Binding
Binding
with a single column and single value. Used for Textbox.
TextBox Properties
DataBindings
Text -> Column name
Form_Load
SqlDataAdapter1.Fill(DSCust)
Navigating Between
Records
1. Create
data adapter
2. Create
dataset
3. Binding
with controls.
Codings
General Declaration
Dim bm As
BindingManagerBase
Form1_Load
SqlDACust.Fill(DsCustomer1)
bm = Me.BindingContext(DsCustomer1,
"CustomerTracking")
bm.Position = 0
cmdFirst_Click
bm.Position
= 0
cmdLast_Click
bm.Position = bm.Count - 1
cmdPrevious_Click
bm.Position
-= 1
cmdNext_Click
bm.Position
+= 1
Filtering and Sorting
Data
Two types of Filtering
1.
Parameterized Queries
2.
Filter the Dataset
Parameterized Queries
1. Create a
SqlDataAdapter-> Select Connection -> Query Builder -> Select
CustOrder Table
2. Specify
the condition "where Inv=@param"
3. Click
next and finish the SqlDataAdapter.
4. Generate
the Dataset for SqlDataAdapter
5. Place
the controls and bind the Dataset with the controls.
Codings
Private Sub cmdSearch_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles cmdSearch.Click
SqlDataAdapter1.SelectCommand.Parameters("@param").Value =
TextBox1.Text
DsCust1.Clear()
SqlDataAdapter1.Fill(DsCust1)
End Sub
Filter the Dataset
Using
Select() method
select(condition,sort
order)
Eg:
Private Sub
btnSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnSelect.Click
Dim dt As
DataTable
dt =
DsCust1.Tables("CustOrder")
Dim cond As
String
Dim sort As
String
cond =
"cost >3000"
sort =
"custid asc"
Dim result()
As DataRow
result =
dt.Select(cond, sort)
Dim ctr As
Integer
For ctr = 0 To
result.Length - 1
lstProdid.Items.Add(result(ctr)("custid").ToString)
Next
End Sub
Private Sub
Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
SqlDataAdapter1.Fill(DsCust1)
End Sub
Displaying Data From
multiple tables.
xsd ->
Schema -> Containing conditions for columns
Eg:
Control Properties Settings
sqlDataAdapter1 SelectCommand Select Custid,fname,address from
CustomerTracking
SqlDataAdapter2 SelectCommand Select Inv,InvDate,Custid,prodid
from CustOrder
DataSet DSMasterDetail1 CustomerTracking
CustomerOrder
Double click the DSMasterdetail1.xsd from Solution Explorer
Window
Create Relation from Toolbox. Drag the Relation object and
place it in CustOrder Table.
Label CustomerID
Label Firstname
Label Address
DataGrid DGDetail
-> DataSource ->
DSMasterDetail1
DataMember
-> CustomerTracking -> CustomerTrackingCustOrder
TextBox txtCustid -> DataBindings -> Text ->
CustomerTracking -> CustID
TextBox txtFname -> DataBindings -> Text ->
CustomerTracking -> Fname
TextBox txtAddress -> DataBindings -> Text ->
CustomerTracking ->Address
Codings
Dim bm As BindingManagerBase
Form_Load()
SqlDataAdapter1.Fill(DsMasterDetail1,
"CustomerTracking")
SqlDataAdapter2.Fill(DsMasterDetail1,
"CustOrder")
bm = Me.BindingContext(DsMasterDetail1,
"CustomerTracking")
Next
bm.Position
+= 1
Previous
bm.Position
-= 1
Data Updates
Design Form for the following Table
1. CustomerDetails
Create table CustomerDetails(Custid varchar(10) primary
key,CustName varchar(50),
Address Varchar(100),phoneno numeric(15),Email varchar(50),regdate
datetime)
2. Design
the Form and Bind the Control
3. Codings
General Declaration
Dim bm As
BindingManagerBase
Dim flag As
Integer = 0
Dim dt As DataTable
Dim dr As DataRow
Dim custid As String
Form_Load
SqlDataAdapter1.Fill(DsCustomer1)
bm = Me.BindingContext(DsCustomer1,
"CustomerDetails")
bm.Position = 0
btnFirst_Click
bm.Position
= 0
btnPrev_Click
bm.Position
-= 1
btnNext_Click
bm.Position
+= 1
btnLast_Click
bm.Position
= bm.Count - 1
btnAdd_Click
ClearText()
flag = 1
Dim cid, cidval As String
Dim ctr, len As Integer
dt =
DsCustomer1.Tables("CustomerDetails")
len = dt.Rows.Count - 1
If (len < 0) Then
cid = "C001"
Else
dr = dt.Rows(len)
cidval = dr("Custid")
cidval = Mid(cidval, 2, 3)
ctr = CInt(cidval)
If (ctr > 0 And ctr < 9) Then
ctr = ctr + 1
cid
= "C00" & ctr
ElseIf
(ctr >= 9 And ctr < 99) Then
ctr = ctr + 1
cid = "C0" &
ctr
Else
ctr = ctr + 1
cid = "C" &
ctr
End If
End
If
txtCustid.Text = cid
txtCustname.Focus()
ClearText
Private Sub
ClearText()
txtCustid.Text = ""
txtCustname.Text = ""
txtAddr.Text = ""
txtPhno.Text = ""
txtEmail.Text = ""
txtRdate.Text
= ""
End Sub
btnModify_Click
custid =
txtCustid.Text
flag = 2
btnDelete_Click
custid =
txtCustid.Text
flag = 3
btnSave_Click
If flag = 1
Then
dt =
DsCustomer1.Tables("CustomerDetails")
dr
= dt.NewRow()
dr(0) = txtCustid.Text
dr(1) = txtCustname.Text
dr(2) = txtAddr.Text
dr(3) = txtPhno.Text
dr(4) = txtEmail.Text
dr(5) = txtRdate.Text
dt.Rows.Add(dr)
ElseIf flag =
2 Then
dt =
DsCustomer1.Tables("CustomerDetails")
dr = dt.Rows.Find(custid)
dr.BeginEdit()
dr(1) = txtCustname.Text
dr(2) = txtAddr.Text
dr(3) = txtPhno.Text
dr(4) = txtEmail.Text
dr(5) = txtRdate.Text
dr.EndEdit()
ElseIf flag =
3 Then
dt =
DsCustomer1.Tables("CustomerDetails")
dr = dt.Rows.Find(custid)
dr.Delete()
End If
SqlDataAdapter1.Update(DsCustomer1, "CustomerDetails")
SqlDataAdapter1.Fill(DsCustomer1)
bm.Position =
0
txtRdate_GotFocus
txtRdate.Text
= System.DateTime.Today
Crystal Report
For
Creating Reports and Charts
Three Methods
1. Manually
2. Using
Standard Expert
3. From an
existing Report
Manually
1. Create a
Windows Form
2. From
Project Menu -> Add New Item -> CrystalReport
3. Name
-> RevenueReport.rpt -> Click Open button
4. Crystal
Report Gallery -> Select "As a blank Report" -> Click Ok
5. In the
Field Explorer Window -> Database Fields -> Right Click -> Add/Remove
Database
6. Select
OLEDB (ADO)
-> Microsoft OLEDB for SQL server
7. USer id
= sa;password=killer;server=system8;database=master
8. Select
Table "CustomerTracking" -> Insert Table - Click Finish
9. From
Field Explorer Window -> Drag the Required Fields to Details Section
10. In the
Form Window -> Place one crystalReportViewer Control -> Properties ->
ReportSource -> Browser and Select the -> RevenueReport.rpt
11. Run the
Application
Using Standard Expert
1. Create a
Windows Form
2. Project
Menu -> Add New Item -> CrystalReport
3. Name
-> RevenueReport1.rpt -> Click the Open Button
4. Crystal Report Gallery
-> Select "Using Standard Expert" -> Click Ok
5. Select
OLEDB (ADO)
-> Microsoft OLEDB For SQL Server
6.
server=system8;user id=sa;password=killer;database=master
7. Select
Table "CustOrder" -> Insert Table -> Click Next
8. Select
Display Fields -> Click next
9 Select Group
Field -> Click Next
10. Select
Summarized Field -> Click Next
11. Chart
-> Select chart type -> Text -> Title (Revenue Report) -> Click
Next
12. Click
next
13. Click
Next
14. Click
Finish
15. In the
Form Window -> Place one crystalReportViewer Control -> Properties ->
ReportSource -> Browser and Select the -> RevenueReport.rpt
Filtering Data report
1. Create a
Windows Form
2. Create a
SQLDataAdapter -> Select CustOrder and Set the condition as
"Cost>3000"
3. Generate
a DataSet with the Name of DSReport
4. Project
Menu -> Add New Item -> CrystalReport
5. Name -> RevenueReport2.rpt -> Click
Open
6. Crystal
Gallery Report -> Select "As a blank Report"
7. In the
Field Explorer Window -> Database Fields -> Add /Remove Database
8. Select
"Project Data" -> ADO.NET -> Datastet -> DSReport ->
Custorder
9. From
Field Explorer -> Drag the Required Field
10. Group
Name Fields -> New -> CustOrder.Prodid
11. Running
Total Field -> New -> CustOrder.Cost -> Sum
12. Formula
Field -> New -> Enter "Percentage" -> Formulat Editor ->
CustOrder.Advance / CustOrder.Cost * 100
13. Drag
the Formula Field in the Details Section
14. In the
Form Code Window add the following Code
Global Declaration
Dim cr As
New RevenueReport2
Form_Load
SqlDataAdapter1.Fill(DsReport1,
"Custorder")
cr.SetDataSource(DsReport1)
CrystalReportViewer1.ReportSource = cr
Relating Data Report
1. Create a
Windows Form
2. Project
Menu -> Add New Item -> CrystalReport
3. Name
-> RelatingReport.rpt-> Click Open
4. Crystal
Report Gallery -> Select "Using Standard Expert"
5. Select
OLEDB (ADO) -
> Microsoft OLEDB For SQL - Server
6.
Server=system8;user id=sa;password=killer;database=master;
7. Select
-> CustomerTracking and CustOrder Table
8. Relating
window Displayed -> Click Next
9. Select
Displaying Fields and Click NExt
10. Select
Group Field and Click Next
11. Select
Summarized Field and Click Next
13. Create
Chart if need
14. Click
the Next and Finish the Report
15. In the
Form Window -> Place one crystalReportViewer Control -> Properties ->
ReportSource -> Browser and Select the -> RelatingReport.rpt
Setting Primary key and Foreign Key
in Table
Create
table Custtrack(custid varchar(10) primary key)
(or)
Alter table
custtrack add constraint cpk2 primary key(custid)
Create
table custorder1(custid varchar(10) references custtrack(custid))
(or)
Alter table
custorder1 add constraint cfk2 foreign key(custid) references custtrack(custid)
Menus
MainMenu
-> Normal Menus created in Menubar
ContextMenu
-> For creating shortcut menus
MDI Forms
-> Multiple Document Interface
Eg: MS -
Word
Drag
MainMenu from Toolbar and set the Name and Caption Property
Form1 ->
IsMdiContainer -> Set to True
Context Menu
Drag
Context Menu From toolbar
Create MenuItems
with Itemname
Form1 ->
ContextMenu Property -> ContextMenu1
Toolbar
Drag a
ImageList Control -> Property -> Images -> Add some Images
Drag a
Toolbar Control -
Property
ImageList ImageList1
Button
collection Add Buttons
with Name and ImageIndex
Statubar
Drag a
Statusbar Control
Property
ShowPanels True
Panels Add Panel and Set the
Name Property
Codings
Private Sub mnuNew_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles mnuNew.Click
Dim myform As New Second
myform.MdiParent = Me
myform.Show()
End Sub
Private Sub
mnuSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles mnuSave.Click
MsgBox("Save Clicked")
End Sub
Private Sub
mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles mnuExit.Click
End
End Sub
Private Sub
Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
WindowState =
FormWindowState.Maximized
SBPanel2.Text
= System.DateTime.Now()
End Sub
Private Sub
mnuVertical_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles mnuVertical.Click
Me.LayoutMdi(MdiLayout.TileVertical)
End Sub
Private Sub
mnuHorizontal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles mnuHorizontal.Click
Me.LayoutMdi(MdiLayout.TileHorizontal)
End Sub
Private Sub
mnuCascade_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles mnuCascade.Click
Me.LayoutMdi(MdiLayout.Cascade)
End Sub
Private Sub
mnuArrIcons_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles mnuArrIcons.Click
Me.LayoutMdi(MdiLayout.ArrangeIcons)
End Sub
Private Sub
mnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
mnNew.Click
Dim myform As
New Second
myform.MdiParent = Me
myform.Show()
End Sub
Private Sub mnHori_Click(ByVal
sender As System.Object, ByVal e As System.EventArgs) Handles mnHori.Click
Me.LayoutMdi(MdiLayout.TileHorizontal)
End Sub
Private Sub
mnVert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles mnVert.Click
Me.LayoutMdi(MdiLayout.TileVertical)
End Sub
Private Sub
ToolBar1_ButtonClick(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.ToolBarButtonClickEventArgs) Handles ToolBar1.ButtonClick
Select Case
ToolBar1.Buttons.IndexOf(e.Button)
Case 0
Dim
myform As New Second
myform.MdiParent = Me
myform.Show()
sbPanel1.Text = "New Form"
Case 1
MsgBox("Save Clicked'")
sbPanel1.Text = "Save
Form"
Case 2
sbPanel1.Text = "Exit Form"
End
End Select
End Sub
File Handling
A file is a
collection of bytes that has a persistent storage. The data in a file is stored
as data streams and when we read from or write to a file, we read or write data
as data streams.
A data
stream is a sequence of bytes that can be written to or read from a backup
device, such as hard disk.
File I/O perform in
two different ways.
1. Using
the .NET System.IO model
2. Using
the Visual Basic- runtime functions
Using System.IO Model
This
model are available to all the .NET languages. These classes are contained in
the System.IO namespace and are used for creating copying, moving and deleteing
files. The most frequently used classes in the System.IO namespace are
FileStream, BinaryReader, BinaryWriter, StreamReader, StreamWriter,
TextReader,TextWriter and Directory.
FileStream Class
This
class provides access to files and file related information. The FileSystem
class is used with the File class, which is also contained in the System.IO
namespace, to create, copy, delete, move and open files.
FileStream class opens a file either in synchronous mode or
asynchronous mode.
Synchronous
mode -> The entire file is first read and then displayed to the user.
Method used
-> Read() and Write() method
Asynchronous
mode -> starts reading and displaying files in parts
Method Used
-> BeginRead() and BeginWrite()
FileMode
Append-> File must be exists and open the file and set
the file pointer to end of file
Create -> New Creation. If the file exists, the file is
overwritten
CreateNew -> Create a New file. If the file is exists it
throws an exception
Open -> open an existing file
OpenOrCreate -> Open an existing file, if the file exists
or create a new file
Truncate-> Delete the file and recreate it. File must be
exists.
FileAccess
Read ->
Read Only
ReadWrite
-> Read and Write
Write ->
Write only.
FileShare
Read
ReadWrite
Write
FileCreation
Eg:
Dim fstream As New
FileStream("c:\sample.txt", FileMode.OpenOrCreate,
FileAccess.ReadWrite)
MsgBox("File Created")
BinaryReader and
BinaryWriter
In .NET we
can store data in binary format to keep the size of a file small.
Eg:
Private Sub Form1_Load(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim files As
FileStream = New FileStream("c:\myfile.txt", FileMode.OpenOrCreate)
Dim bw As New BinaryWriter(files)
Dim br As New
BinaryReader(files)
Dim j As
Integer
For j = 1 To
10
bw.Write(CStr(j))
Next
br.BaseStream.Seek(0, SeekOrigin.Begin)
TextBox1.Text
= br.ReadChars(20)
End Sub
Offsets
SeekOrigin.BEGIN -> Beginning of File
SeekOrigin.CURRENT
-> Move to current pointer
SeekOrigin.END
-> End of file
StreamReader and
StreamWriter
These
classes internally use specific encoding to convert characters to and from
bytes.
Create a Form
with a RichTextBox Control
Eg:
Private Sub
Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
Dim fstream As
New FileStream("C:\mydata.txt", FileMode.OpenOrCreate,
FileAccess.ReadWrite)
Dim sw As New
StreamWriter(fstream)
sw.BaseStream.Seek(0, SeekOrigin.End)
writedata("My Employee code is 102", sw)
writedata("My Language is Sanskrit", sw)
Dim sr As New
StreamReader(fstream)
sr.BaseStream.Seek(0, SeekOrigin.Begin)
readdata(sr)
End Sub
Public Sub
writedata(ByVal data As String, ByVal sw As StreamWriter)
sw.Write("Entry : ")
sw.WriteLine(data)
sw.WriteLine("---------------------------------")
sw.Flush()
End Sub
Public Sub
readdata(ByVal r As StreamReader)
RichTextBox1.Text = r.ReadToEnd
r.Close()
End Sub
The Directory Class
CreateDirectory Directory.CreateDirectory("C:\vb_users")
Delete Directory.Delete("c:\vb_users")
Exists Msgbox(Directory.Exists("c:\vb_users"))
GetDirectoryRoot Msgbox(Directory.GetDirectoryRoot("c:\Vb_users"))
GetLogicalDrives
Imports
System.IO
Public
class Form1
Inherits
System.Windows.Forms.Form
Dim
s() as String
dim
i,j as Integer
Private
Sub Form1_Load()
s
= Directory.GetLogicalDrives()
i
= s.length
For
j = 0 to i - 1
RichTextBox1.Text
= RichTextBox1.Text + s(j) + Chr(13)
Next
End
Sub
End
Class
Move Directory.Move("c:\my_Dir","c:\vb_users\MyDir")
Creating Help System
hhp -> Html Help Project
hhc -> Html Help Contents
hhk -> Html Help Index
htm -> Html file
Steps to Create Help
file system
Programs -> HTML Help Workshop
1. File -> New -> Project
2. Click Next -> Browse the location to save the .hhp
file.
3. Click Next -> Click Finish
4. File -> New -> HTML File
Enter the
Title and Contents of the HTML File and Save the file
Title Contents Filename
---------- ------------ -------------
Maintaining
Records Maintain.htm
Add Record Add.htm
Modify
Record Modify.htm
Delete
Record Delete.htm
View Record View.htm
5. Select the Index Tab -> Create a new Index File
6. Select the option -> Insert a Keyword
Enter the Keyword (Maintaining Record) and Add the file
(Maintain.htm) for the keyword and click ok
Similary
add all the keyword with htm file.
7. Select the Contents Tab -> Create a new Contents File
8. Select the option -> Insert a Heading -> Maintaing
Records -> Maintain.htm
9. Select the option -> Insert a Page -> Enter keyword
and Select the correspoding files
10. Select the Projects Tab -> Select "Change
Project options"
Enter the
Title and Select the Default page to display while pressing F1
11. File Menu ->
Compile option -> Select the two checkbox and Click "Compile"
12. View Menu -> Compiled File -> Select the File and
view
Adding File system
with Project Menu
1. Drag a HTMLHelpProvider Control
Properties
-> HTMLNamespace -> Select the Help File
Control Properties
Show Help
on HelpProvider1 -> True
Helpkeyword
on HelpProvider1 -> Enter the Keyword
HelpNavigator
on HelpProvider1 -> Select the Navigation option
Deploying the
Application
1.File -> New -> Project -> Setup and Deployment
Projects -> "CallCenter" -> Click Ok
2. File -> Add Project -> Existing Project ->
"DataUpdates.vbproj"
3. Open the "File System" editor by selecting
"View -> Editor -> File System"
4. Select the "File System On Target Machine" node
5. Select "Action -> Add Special Folder ->Program
Files Folder"
6. Select the "Program Files Folder" node. Select
"Action->Add->Folder". Type the name of the folder as
"CallCenter"
7. To Add the output of the "Data Entry
Application" project to the "CallCenter" folder, select the
"CallCenter" folder. Select "Action-> Add-> Project Output".
This opens the "Add Project Output Group" dialog box.
8. Select "Data Entry Applicaion" from the Project
drop down list, Select "Primary Output" from the Output list.
9. click the ok button
Create a shortcut for
the application
10. In the "File System" editor, Select the
"CallCenter" folder. In the details pane of the "File
System" editor, select "Primary Output from Data Entry Applcation
(Active)".
11. Select "Action -> Create Shortcut to Primary
Output from Data Entry Application (Active)".
12. Change the name of the shortcut to
"CallCenter"
13. Drag the shortcut to the "User's Desktop" mode
in the "File System Editor"
Add a dialog box to
the deployment project
14. Open "Wordpad" and type the text to be
displayed in the license agreement.
15. Save the file with the extension of ".rtf" (Rich text format)
16. In the Visual
Studio .NET deployment project, open the "User Interface" editor by
selecting "view -> editor -> User Interface"
17. In the "Install" section, select
"Start"
18. Select "Action -> Add Dialog"
19. In the "Add Dialog" dialog box, Select
"License Agreement", click the ok button
20. Move the License agreement dialogbox so that it appears
immediately after the Welcome dialog box.
21. Select the "License Agreement" node in the
User Interface editor and press F4 key to switch to properties window.
22. Select the License file property and select the rtf
file.
23. In the "Select Item in Project" dialog box,
Click ok button
24. Build the Application
Execute the Installer
1. Browse the deployment project folder. In the Debug folder
-> it contains the Setup Project and Uninstall Project"
2. Double click and install the project
Component Technology
Component
* A
component is a reusable piece of code in binary form that can be plugged into
components from other vendors, with relatively little effort.
* Component
can be part of an application that implements Business logic.
* We can
reuse code by inheritance.
Component
Architecture of .NET
Components
have to interact with each other. For example, a component that accepts user
information might use another component to validate the information. This is
achieved, in Visual Basic .NET, by putting the components within a self
contained package called assembly. An assembly contains information about the
files on which the component depends and the location of these files. The CLR
can use this information to determine the dependencies of a component. The
assemblies that are required during the execution of an assembly are called
dependencies.
An assembly
usually consists of a manifest and the portable executables (PE)
Manifest
A manifest
consists of information such as the name and version of the assembly. It also
contains information about other files, such as text files, assemblies and
graphics files that assembly uses.
Portable executables
(PE)
A portable
executable consists of the IL code, type information, and meta data. The
manifest might be stored as a part of a portable executable. The metadata
consists of information about every type, such as classes and structures
defined and used in our code.
Characteristics of a
Component
1. The name of the component class should be short and
meaningful. It should be a combination of whole words with a capitalized
initial character for each word.
2. We can control the use of a component by using proper
access level for the constructors.
Classes or components that are used internally by the assembly should
have private access where as a component that is intended for use outside the
containing assembly should have public access.
3. The base class of all component class is the class
Component or IComponent class.
4. The namespace structure in an assembly should be according
to the internal organization of the components. We should group related
components together in separate namespaces. The project name becomes the root
namespace by default.
Life cycle of
component
1. The constructors initialize components. Initialization can
be two types, type initialization and instance initialization. Type
initialization is achieve by shared constructors. Instance initialization is
achieved by constructors.
2. The instance of our component is destroyed when the
garbage collector finds that there are
no references to the components. All clean up code should be put into the
Finalize code.
Eg:
1. File -> New -> Project -> Visual Basic Projects
-> Class Library Project -> "CValidator"
2. Project Menu -> Add Component -> Component Class
3. Change the name of the class in the line of code to
"CardValidator"
4. Change the file name to "CardValidator.vb"
5. Delete the default class library project
"Class1.vb"
6. Save the Project
7. Add Properties and Functions to the component
Public Class CardValidator
Inherits
System.ComponentModel.Component
Private Name As
String
Private CardNo As
String
Public Property
CustomerName() As String
Get
Return Name
End Get
Set(ByVal
CustName As String)
Name =
CustName
End Set
End Property
Public Property CardNumber() As String
Get
Return
CardNo
End Get
Set(ByVal
Number As String)
CardNo =
Number
End Set
End Property
Public Function
Validate() As Integer
Dim cardlength
As Integer = 0
cardlength =
CardNo.Length
Dim valid As
Boolean
If cardlength =
14 Then
Return True
Else
Return
False
End If
End Function
End Class
8. Build Menu -> click Build Solution
(It creates a DLL file -> Dynamic Link Library)
Create a User
interface to display the result
1. Create a windows application project name
"CreditCardDetails".
2. Create Two labels and two textboxes
"TextCustName" and "TextCard"
3. Create a Button Control "Validate"
4. In the solution explorer window right click
"References"-> Choose "Add Reference"
5. Browse and Navigate the "CValidator.dll" and
Click Open
6. Add the Following Code
Imports CValidator
Private Sub btnValidate_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btnValidate.Click
Dim validator
As CardValidator
validator = New
CardValidator
validator.CardNumber = txtCardNo.Text
validator.CustomerName = txtCustName.Text
validator.Validate()
If
validator.Validate = True Then
MsgBox("Valid Card Number")
Else
MsgBox("Invalid Card Number")
End If
End Sub
User Controls
When we
design an application with graphical user interface, we usually use objects
that the user can use to control the flow of the application. These controls
are visual components that can be used across applications.
The UserControl Class
The
UserControl class can contain multiple Child controls. The UserControl class
represents a Single and unified interface. This interface contains inherted
from the Control classes.
Creating Customized
User Controls
Eg:
1. Create a new Windows Control Library and name it CDateLib.
2. In the Solution Explorer Window, change UserControl.vb to
BritishDateTimePicker.vb by right clicking UserControl1.vb and selecting the
Rename option from the short - cut - menu.
3. Right Click BritishDateTimePicker.vb and select view code
from the shortcut menu
4. Change the name of the class to BritishDateTimePicker. In
addition, change the inherits state to Inherits
System.Windows.Forms.DateTimePicker.
5. Double Click the Windows Form Designer generated code,
6. In the New() method, add the following code after the
InitializeComponent method.
Format =
DateTimePickerFormat.Custom
CustomFormat =
"dd/MM/yy"
7. Build -> Build the Solution.
Test Your control
1. Create a new Windows application
2. Right click and customize the toolbox.
3. Select the .NET Framework Components tab -> browse
-> CDatelib.dll
4. Select the Control BritishDateTimePicker and click ok
5. Drag the control and Build and execute.
Eg:
1. File -> New -> Project -> Windows Control Library
-> "NumericTextBox"
2. Change the name of the control to "NumericTextBox"
3. Switch to Code view and add the following code
Public Class NumericTextBox
Inherits
System.Windows.Forms.TextBox
Private maxValue As
Integer
Private minValue As
Integer
Public Property
Max() As Integer
Get
Return
maxValue
End Get
Set(ByVal Value
As Integer)
maxValue =
Value
End Set
End Property
Public Property
Min() As Integer
Get
Return
minValue
End Get
Set(ByVal Value
As Integer)
minValue =
Value
End Set
End Property
Protected Overrides
Sub OnLostFocus(ByVal e As System.EventArgs)
If Val(Text)
< minValue ThVB.NET
Types of Application Architecture
Applications are developed to support organizations in their business operations. Application accepts input, process the data based on business rules and provide data as output. The function performed by an application can be divided into three categories:
User services
Business services
Data services.
Each category is implemented as a layer in an application. The user services layer constitutes the front end of a solution. It is also called a presentation layer because it provides an interactive user interface
The business services layer controls the enforcement of business rules on the data of an organization. Business rules encompass those practices and activities that define the behavior of an organization. The business services layer performs validations pertaining to business rules.
The data services layer comprises the data and the functions for manipulating the data.
Application Architecture
1. Single Tier Architecture -> Based on Single Software
2. Two Tier Architecture
3. Three Tier Architecture
4. n-Tier Architecture (HTML -> VBScript -> ASP -> Oracle -> XML)
MVC Architecture
Model View Controller Architecture
Model -> Business Logic -> EJB -> COM+ (Component Object Model)
View -> Output -> JSP -> ASP.NET (or) VB.Net
Controller -> Controlling Pages. -> ASP.Net
.NET Initiative
Microsoft has introduced the .NET initiative with the intention of bridge the gap in interoperability between applications. It aims at integrating various programming languages and services.
It is designed to make significant improvements in code reuse, code specialization, resource management, multi language development, security, deployment and administration.
The .NET Initiative offers a complete suite for developing and deploying applications. This suite consists of .NET products, .NET services, and the .NET framework.
.NET Products
Microsoft has already introduced Visual Studio .NET, which is a tool for developing .NET application by using programming languages such as Visual Basic, C# and Visual C++. In addition, Microsoft also intends to introduce .NET versions of the Windows operating system and Office suite. These products aim at allowing developers to create applications that are capable of interacting seamlessly with each other. To ensure interaction between different applications, all .NET products use eXtensible Markup Language (XML) for describing and exchanging data between applications.
.NET services
.NET delivers software as Web Services. Therefore, users can subscribe to a web service and use it as long as they need it, regardless of the hardware and software platform.
Microsoft is coming up with its own set of web services, known as My Services. These services are based on the Microsoft Passport authentication service, the same service that we used in Hotmail. They allow the consumers of the services to access data by linking calendars, phonebooks, address books, and personal references to the Passport Authentication service. In addition to the Web services provided by Microsoft, third party products and services can also be integrated easily with the .NET environment
The .NET Framework
It is the foundation on which you design, develop and deploy applications. Its consistent and simplified programming model makes it easier to build robust applications.
.NET Products
Visual Basic.NET
Visual C++.NET
C#
ASP.Net
J#
XML
Namespace
Collection of classes and Interfaces are packed.
Interfaces
Set of incomplete methods.
MultiThreading ->
I/O Packages
Networking
Assembly -> Deployment purpose
Garbage Collection ->
Security
.Net Framework
Managed Code Execution Process
1. When you compile a program developed in a language that targets the CLR, instead of compiling the sourcecode into machine level code, the compiler translates into Microsoft Intermediate Language (MSIL) or Intermediate Language (IL). No matter which language has been used to develop the applications, it always gets translated into IL. This ensures language Interperability.
2. In addition to translating the code into IL, the compiler also produces metadata about the program during the process of compilation. Metadata contains the description of the program, such as the classes and interfaces, the dependencies and the versions of the components used inthe program.
3. The IL, and the meta data are linked in assembly
4. The compiler creates the .EXE or .DLL file
5. When you execute the .EXE or .DLL file, the code (converted into IL) and all the other relevant information from the base class library is sent to the class loader. The class loader loads the code inthe memory.
6. before the code can be executed, the .NET framework needs to convert the IL into native or CPU specific code. The Just In Time (JIT) compiler translates the code from IL into managed process of compilation, the JIT compiler compiles only the code the code that is required during execution instead of compiling the complete IL code. When an uncompiled method is invoked during execution, the JIT compiler converts the IL for that method into native code. This process saves the time and memory required to convert the complete IL into native code.
7. During JIT compilation, the code is also checked for type safety. Type safety ensures that objects are always accessed in a compatible way. Therefore, if you try to pass an 8 byte value to a method that acceps 4 byte value as its parameter, the CLR will detect and trap such an attempt. Type safety also ensures that objects are safely isolated from each other and are therefore same from any inadvertent or malicious corruption
8. After translating the IL into native code the converted code is sent to the .NET runtime manager.
9. The .NET runtime manager executes the code. while executing the code, a security check is performed to ensure that the code has the appropriate permissions for accessing the available resources.
Unicode characters - 2 Bytes
Features Provided CLR
1. Automatic memory management
2. Standard type system
3. Language Interperability
4. Platform Independence
5. Security Management
6. Type safety
Advantages of .NET Framework
1. Consistent Programming Model
2. Multi platform applications
3. Multi Language Integration
4. Automatic resource management
5. Ease of deployment
Visual Basic .NET
* Supports Object Oriented Programming full fledgely.
* Supports Structured Exception Handling
* Supports Multithreaded Programming
Features of .NET
1. Inheritance
2. Constructor and Destructor
3. Overloading
4. Overriding
5. Structured Exception Handling
6. Multithreading
Inheritance
Inheritance is the ability of a class to derive its characteristics from an existing class
Syntax:
class base
Statements
End class
class DerivedClass Inherits ParentClass
...........
End Class
It is possible to create a base class in any language and inherits its properties in a derived
class created using another language. It provides the advantage of code reusability across languages.
Constructors and Destructors
Constructor -> Used to initialize the members of the class
Destructor -> Releases the resources used by an object
Overloading
function nane similar passing parameters are different
Syntax:
Function Overloads function_name(parameter list) as return type
Overriding
class base
{
virtual public void show();
public void fun1();
}
class derived : public base
{
public void show();
public void fun1();
}
derived d;
base b;
base *b1;
b1 = &d;
b1->show();
b1->fun1();
Syntax:
Public Overrides Function func1()
Structured Exception Handling
VB.Net Supports structured exception handling that consists of protected blocks of code and filters for the possible exceptions that can be raised by the program.
try
{
Codings
}
catch(Exception)
{
Exception Handling code
}
Multithreading
Multithreading enables an application contain one or more threads that can share workload in an application by executing one at a time.
Visual Studio .NET IDE
1. Projects and Solutions
Projects-> Contains Forms and modules.
Solutions -> Contains one or more projects.
Project Types
1. Visual Basic Projects
2. Visual C#
3. Visual C++
4. Setup and Deployment Application
Templates
Windows Application -> Stand alone windows application
Class Library -> Create reusable class library
Windows Control Library -> Custom Control creation
ASP.NET Web Application -> Create Web Application
ASP.NET Web Service -> HTTP and XML to communicate with client applications.
Web Control Library -> Custom control used in web application
Console application -> create console application run in command line
Windows Service -> Background service such as monitoring
Empty Project
Empty Web Project
New Project in Existing Folder -> Adding Existing files.
User Interface Elements of Visual Studio .NET IDE
1. Windows Form Designer
2. Solution Explorer Window
3. Properties Window
4. Toolbox
5. Output window
6. The task list window
7. Server Explorer window
8. Dynamic Help window
9. Class view window
10. Code and Text editor window
Object Orientation in Visual Basic.NET
OOPS -> Object oriented programming system
1. Classes and Object
2. Data Abstraction and Encapsulation
3. Inheritance
4. Polymorphism
5. Overloading
Arrays -> Collection of like data types.
Structure
Collection of unlike variables, methods and constructors.
Syntax:
Structure struc_name
access_specifier var_name as Datatype 'Variables
access_specifier Sub proc_name(ByVal var as Datatype) 'Sub Procedure
Statement
End Sub
access_specifier function func_name(ByVal var as Datatype) as DataType
return var_name
End function
Sub New() 'Constructor
Statements
End sub
.........
End Structure
Eg:
Structure Emp
Dim Eno as Integer
Public Ename as String
Public Salary as Single
Public Sub DisplayEmp()
Msgbox "Empno : " & eno
Msgbox "Empname : " & ename
Msgbox "Salary : " & salary
end sub
End Structure
Access_Specifier
Public - A structure declared with the Public keyword is accessible from anywhere within or outside the application. This is the default access mode.
Protected - A structure declared with the Protected keyword is accessible only from within its own class or from a derived class
Friend - A structure declared with the Friend keyword is accessible from within the program that contains the declaration and from anywhere else in the same program
Protected Friend - A structure declared with the Protected Friend keyword is accessible from within the same assembly and in the derived class.
Private - A structure declared with the Private Keyword is accessible only from within its declaration context, including any nested procedures.
(Static)Shared Variables.
* Initialized with zero when the first object is created. No other initialization is permitted.
* Only one copy of the member is created and shared by all objects.
* Without creating object the member can be accessed by using structure name.
Shared Methods
* It access only shared variables.
* Without creating object the method can be accessed by using structure name.
Eg:
Structure Student
sno as Integer
sname as String
shared count as integer
End Structure
Dim s1(10) as Student
Including Procedure
Structure order_details
Public Inv_no as String
Public Ord_dt as Date
Public CustName as String
Public Product as String
Public Cost as Double
Public Advance_amt as Double
Public Due_amt as Double
Public Sub CheckCost (ByVal Cost as Double)
if Cost < 10 then
Cost = 10
End If
End Sub
Shared count as Integer
End Structure
Storing data within a Structure
Dim ord1 as order_details
ord1.count = ord1.count + 1
Dim ord2 as order_details
ord2.count = ord2.count + 1
ord1.Inv_no = "I0001"
ord1.Ord_dt = #01/31/1980#
ord1.CustName = "Jack"
ord1.Product = "ABC"
ord1.Cost = 450.00
ord1.Advance_amt = 200.00
ord1.Due_amt = 250.00
Accessing Data from a structure
if ord1.Inv_no = "" then
Msgbox("Please enter the invoice number")
End if
Eg:
Structure Emp
Dim eno As Integer
Dim ename As String
Dim salary As Integer
Shared count As Integer
Sub getEmp()
eno = Integer.Parse(InputBox("Enter Eno"))
ename = InputBox("Enter empname")
salary = Integer.Parse(InputBox("Enter Salary"))
count = count + 1
End Sub
Sub displayemp()
MsgBox("Empno : " & eno)
MsgBox("Empname : " & ename)
MsgBox("Salary : " & salary)
End Sub
Shared Sub displayCount()
MsgBox("No of Objects Created is " & count)
End Sub
Sub New(ByVal no As Integer, ByVal name As String, ByVal sal As Integer)
eno = no
ename = name
salary = sal
count = count + 1
End Sub
End Structure
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim e1(10) As Emp
Dim e2 As Emp = New Emp(1000, "Kirthika", 2000)
e2.displayemp()
Dim n, i As Integer
n = Integer.Parse(InputBox("Enter how many employees"))
For i = 0 To n - 1
e1(i).getEmp()
Next
For i = 0 To n - 1
e1(i).displayemp()
Next
Emp.displayCount()
End Sub
End Class
Classes Vs Structures
Collection of member variables and methods
Similarities
* Both can have members, including constructors, properties and constants.
* Both can implement Interfaces (Set of incomplete methods)
* Both can have shared constructors with parameters
Shared Keyword
In a class or a structure, the Shared Keyword indicates that one or more programming elements are shared. The Shared programming elements are not associated with a specific instance of a class or structure. To access a shared element, we need to qulify it with the class or structure name. We can also access a shared element by qualifying it with the object name of the class or structure. For example, if we declare a field in our class to count the number of instances of the class, we can make it a shared field. All the instances of the class will access the same shared member.
Differences
Class Structure
A Class is inheritable from other existing classes A structure is not inheritable
A class can have instance constructors with or without parameters A structure can have instance constructors only if they have take parameters
A class is a referenced type (ByRef) A structure is a value type. (ByVal)
The members of a class can be initialized within class declaration The members of a structure cannot be initialized within the structure declaration
The Variables and constants declared in a class have Private by default A members of a structure have Public Scope by default
Class procedures can handle events Structure procedures cannot handle events.
Abstract Class
Set of complete and Incomplete methods. the derived class can implement the methods. In VB.Net the abstract class is created using MustInherit keyword in the class definition.
Eg:
Public class Form1 Inherits System.Windows.Forms.Form
Dim emp as New Emp_Details()
Private Sub Button1_Click(ByVal sender as System.Object, ByVal e as System.EventArgs) Handles Button1.Click
emp.Annual_Salary(TextBox1.Text)
emp.disp()
End Sub
End Class
Public MustInherit Class EmployeeDetails
Public MustOverride Sub Annual_Salary(ByVal m As Integer)
Public Sub disp()
MsgBox("Sample Method")
End Sub
End Class
Public Class Emp_Details
Inherits EmployeeDetails
Dim salary as Integer = 30000
Dim months as Integer = 6
Public Overrides Sub Annual_Salary(ByVal m as Integer)
salary = salary * m
Msgbox("The Total salary is : " & salary) salary = 30000
End sub
End Class
Eg:
Public MustInherit Class MyAbstractClass
Public MustOverride Sub display(ByVal a As Integer)
Public Sub MyAbstractsub()
MsgBox("Abstract Class method")
End Sub
End Class
Public Class DerivedClass
Inherits MyAbstractClass
Public Overrides Sub display(ByVal a As Integer)
MsgBox("The value of a = " & a)
End Sub
End Class
Public Class DerivedClass1
Inherits MyAbstractClass
Public Overrides Sub display(ByVal a As Integer)
MsgBox("Square Value is " & (a * a))
End Sub
End Class
Private Sub cmdDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDisplay.Click
Dim n As Integer
n = Integer.Parse(InputBox("Enter a number"))
Dim d1 As New DerivedClass
d1.display(n)
d1.MyAbstractsub()
End Sub
Private Sub cmdSquare_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSquare.Click
Dim n As Integer
n = Integer.Parse(InputBox("Enter a number"))
Dim d2 As New DerivedClass1
d2.display(n)
d2.MyAbstractsub()
End Sub
Interface
Set of incomplete methods. Alternate for Multiple Inheritance
Syntax:
Interface Iface_name
....
End Interface
Eg:
Interface IOrderDetails
Property CustName() As String
Sub UpdateCustStatus()
Function Calculate(ByVal m as integer) as Integer
Event Update_Complete()
End Interface
Eg:
Interface OrderDetails
Sub Disp()
End Interface
Public Class MyOrder
Implements OrderDetails
Sub disp() Implements OrderDetails.disp
Msgbox "MyOrder disp method"
End Sub
End Class
Public Class AnotherOrder
Implements OrderDetails
Sub disp() Implements OrderDetails.disp
Msgbox "Another Order disp method"
End Sub
Sub MyMethod()
Msgbox "Non Interface Method"
End Sub
End Class
MyOrder m1
m1.disp
AnotherOrder a1
a1.disp
a1.MyMethod
OrderDetails a2
a2.disp
a2.MyMethod() 'Error
Note
We can declare only methods, functions, properties and events in an interface. We cannot declare a variable in an interface.
Interface Inheritance
Interface Validate_Cust
Sub Validate_Custname()
End Interface
Interface IOrderdetails
Inherits Validate_Cust
Property CustName() as String
Sub UpdateCustStatus()
Event Update_Complete()
End Interface
Members of an Interface
Sub Validate_Custname()
Property CustName() as String
Sub UpdateCustStatus()
Event Update_Complete()
Note:
Interface statements are Public by default.
Constructors
Automatic initialization of object
Two types of constructors
1. Shared constructors
2. Instance Constructors
Shared Variable
* Initialize with Zero, when the first object is created. No other initialization is permitted.
* Only one copy of the variable is created and can be accessed by all objects.
Shared Methods
* Access only Shared Variables
* Without creating object the method can be accessed using class name.
Shared constructors
Used to initialize shared variables of type. A shared constructor will not run more than once during a single execution of program.
Eg:
Public Class MyClass1
Public Shared x As Integer
Public y As Integer
Shared Sub New()
x = 10
' y = 20
End Sub
Sub New()
y = 20
End Sub
Sub New(ByVal a As Integer, ByVal b As Integer)
x = a
y = b
End Sub
Protected Overrides Sub Finalize() 'Destructor
MsgBox("Destructor Called")
x = 0
y = 0
End Sub
End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim m1 As New MyClass1
MsgBox(m1.x)
MsgBox(m1.y)
Dim m2 As MyClass1
m2 = New MyClass1(60, 70)
MsgBox("x = " & m2.x)
MsgBox("y = " & m2.y)
End Sub
Instance Constructor
Used to initialize variables that are declared with Dim, Public, Private, Friend, Protected and Protected Friend. Also access the shared variable within an instance constructor.
Sub New(ByVal a as integer)
end Sub
Destructor
Used to destroy Objects
Methods Used
Finalize() -> To release the last reference object
Dispose() -> To release resource, such as Database connection file closing etc.
Inheritance
* Resuability of code
* Extensibility of code
Types
Single
Multiple
Multilevel
Hybrid -> Combination of multiple and multilevel
Hierarchical
Eg:
1. FirstForm (Base)
Reset Button cmdReset
Exit Button cmdExit
2. Codings
Public Overridable Sub cmdReset_Click()
Msgbox
End Sub
Public Overridable Sub cmdExit_Click()
Msgbox
End Sub
3. Build the application
4. Solution Explorer -> Right Click-> Add Inherited Form
5. SecondForm (Inherit FirstForm)
6. Add Additional Controls
7. Code Windows (select Overrides -> cmdReset , cmdExit)
Procedures
Sub Procedure
Function
Property
Event Procedure
Sub Procedure
Access_specifier Sub Proc_name(ByVal arg as Datatype)
Statement
End Sub
Procedure Overloading
Procedure name similar, passing argument differs
Sub proc1()
End Sub
Sub proc1(ByVal m as Integer)
End Sub
Procedure Overriding
Procedure name and passing arguments are similar
Base Class
Public Overridable Sub Procedure_name()
End Sub
Derived Class
Public Overrides Sub Procedure_name()
End Sub
Note: Doesn't return any value
Calling Sub procedure
Procedure_name(arguments)
(or)
Call Procedure_name(arguments)
Function Procedure
Access_specifier Function func_name(arguments) as Return_Datatype
func_name = return value
(or)
return ret_val
End Function
Function Overloading
Function Overriding
Property Procedure
BackColor = red
Public class Customer
Private col as System.Drawing.Color
Public Property BackColor() as System.Drawing.Color
Set(ByVal col1 as System.Drawing.Color)
col = col1
End Set
Get
Return col
End Get
End Property
End Class
Event Procedure
Button_click()
List_SelectedIndexChanged()
Predefined Procedures (Dialog)
Msgbox -> Msgbox("Message",Button Style,"Title")
InputBox -> InputBox("Message","title","default Value",X pos,Y Pos)
CommonDialog Classes
ColorDialog
FontDialog
FileDialog
OpenFileDialog
SaveFileDialog
PrintDialog
PageSetupDialog
ADO.NET
ActiveX Data Object (ADO)
.NET Application to communicate with a database for inserting,updating and retrieving data.
Features
1. Disconnected Architecture
Applications connect to the database only while retrieving and updating data. After data is retrieved, the connection with the database is closed.
2. Data cached in Datasets
A dataset is a cached set of database records. We can work with the records stored in a dataset as we work with real data; the only difference being that the dataset is independent of data source and we remain disconnected from the data source. As a result, resources are saved and the database can meet the increasing demands of users more efficiently.
3. Data Transfer in XML Format
XML is an industry standard Format for exchaning information between different applications. Since a Dataset is stored in the XML format, we can transmit it between different types of application that support XML and any component that can read the dataset structure can process the data.
4. Interaction with the database is done through data commands
All operations on the database are performed by using data commands. A data command can be a SQL statement or a Stored procedure.
ADO.NET Object Model
Provider -> The Data residing in a database is retrieved through data provider.
Dataset -> The Data is cached in a dataset and the application accesses the data from the dataset.
DataReader -> In this method, a DataReader object, which is component of the data provider, uses the connection object to connect to the database, uses the command object to retrieves data, and provides data to the application in a read-only and forward only mode.
Data Providers
Two types of Data Providers:
OLE DB Data Provider
Works with all type of OLEDB Providers.
namespace -> System.Data.OleDb
SQL Server Data Provider
Working with SQL Server
namespace -> System.Data.SqlClient
Connection
ConnectionString () -> Specify the name of the server, username, password etc.
Open() -> Establish the connection
Close() -> Close the Connection
State -> 0 value indicates the connection is closed
1 value indicates the connection is opened.
Eg:
Connecting with SQL - Server
Imports System.Data.SqlClient
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As SqlConnection
con = New SqlConnection("server=server;Database=Master;user id=sa;password=killer")
con.Open()
MsgBox("Connection Opened")
con.Close()
End Sub
Connecting with MS - Access
Imports System.Data.OleDb
Dim con As OleDbConnection
con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:/demo/vb.net/sampleDB.mdb")
con.Open()
MsgBox("Database Connected")
con.Close()
Data Adapter
Data is transfered to and from a database through a data adapter.
SqlDataAdapter -> SQL - Server
OleDbDataAdapter -> Other Database
Properties and Methods of Data Adapter
SelectCommand -> Refers to a SQL Statement or a Stored procedure to retrieve data from the database
InsertCommand -> Refers to a data command to insert data into a database
UpdateCommand -> Refers to a data command to update a database
DeleteCommand -> Refers to a data command to delete from a database
Fill() Method -> Fills the dataset with the records from a database
Update() Method -> Executes the correspoding InsertCommand, UpdateCommand or DeleteCommand row to reflect the changes in the database.
Eg:
Drag a SqlDataAdapter1
Connect with Database and Select the Table using Query Builder
Select SqlDataAdapter1 -> Data Menu -> Generate Dataset -> DSCust
Drag a Datagrid Control and set the Datasource = DScust1.CustomerTracking
Codings
SqlDataAdapter1.Fill(DsCust1)
DataCommand
A DataCommand is a SQL Statement or a Stored procedure that is used to retrieve, Insert, Delete or modify data in a Data source.
SQLCommand -> SQL - Server
OleDbCommand -> Other Database
Eg:
Dim con As New SqlConnection
Dim command As New SqlCommand
con = New SqlConnection("server=system8;database=master;user id=sa;password=killer")
command = New SqlCommand("Insert into Customertracking values('C006','Vidhya','Nandhini','23 KK Nagar',23345,'vidhya@rediff.com')", con)
Dim r As Integer
command.Connection.Open()
r = command.ExecuteNonQuery()
command.Connection.Close()
MsgBox("Record Inserted")
DataReader
Data Reader is used to retrieve data from a data source in a read only and forward only mode.
Methods Used
Read() -> Read Current row
Close() -> Close the DataReader
NextResult() -> Move to Next Record Pointer
Eg:
Dim custid As String
custid = InputBox("Enter Customer ID")
Dim con As New SqlConnection
Dim command As New SqlCommand
con = New SqlConnection("server=system8;database=master;user id=sa;password=killer")
command = New SqlCommand("Select * from customertracking", con)
Dim dr As SqlDataReader
command.Connection.Open()
dr = command.ExecuteReader()
While (dr.Read())
If (dr(0) = custid) Then
txtCustid.Text = custid
txtFname.Text = dr(1)
txtLname.Text = dr(2)
txtAddress.Text = dr(3)
txtPhone.Text = dr(4)
txtEmail.Text = dr(5)
End If
End While
command.Connection.Close()
End Sub
DataSet
When a connection is established with the database, the data adapter creates a dataset and stores data in it. After the data is retrieved and stored in a dataset, the connection with the database is closed. Such working architecture is called disconnected architecture. The dataset acts like a virtual database containing tables,rows and columns.
Dataset Object Model
The Dataset is present as a Dataset class in the System.Data namespace. The Components of the dataset object model are
Component Description
DataTableCollection It Contains all the tables retrieved from the data source
DataRelationCollection It contains relationships and the links between tables in a dataset
ExtendedProperties It contains additional information, such as the SQL statement for retrieving data and the date time stamp for the retrieved data
DataTable It represents a table in the DataTableCollection of a dataset
DataRelation It represents a relationship in the DataRelationCollection of a dataset
DataRowCollection It contains all the rows in a DataTable
DataView It represents a fixed customized view of a DataTable
PrimaryKey It represents the column that uniquely identifies a row in a DataTable
DataColumnCollection It contains all the columns in a DataTable.
Connecting to a Database
There are three methods to create a data adapter.
* Manually
* Through a Wizard
* Using the Server Explorer Window
Types of Datasets
Datasets are of two types.
1. Typed
2. Untyped.
Typed Dataset
A typed dataset is derived from the Dataset class and has an associated XML schema, which is created at the time of the creation of the dataset. The XML schema contains information about the dataset structure, such as the tables, columns and rows. Data is transferred from a database into a dataset and from the dataset to another component in XML format.
XML Schema Definition (CSD) language is used to define the elements and attributes of XML documents. Since a typed dataset structure is stored in an XML format, the dataset is saved as an XSD file. This structure of a typed dataset is decided at the time of its creation. When a typed dataset is created, the data commands are generated automatically by using the column names from the data source. Tables and their columns can be accessed by their names while programming.
Dim custid as string
custid = DSCust.CustomerTracking(0).CustID
Untyped Dataset
An untyped dataset does not have any associated XML schema. In an untyped dataset, the tables and columns are represented as collections. Since an XML schema is not created for an untyped dataset, the structure of an untyped dataset is not known during compilation.
Dim custid as String
OleDbDACust.Fill(DSCust)
custid = CType(DSCust.Tables("CustomerTracking").Rows(0).Item("CustID"),String)
* Using Data Adapter
* Complex Data Binding -> Data Grid
Implementing Simple Data Binding
Navigating Between Records
For every data source that is bound to a Windows Form, there exists a CurrencyManager object. The CurrencyManager object handles the binding to the data source by keeping a pointer to the current item in the record list. The Currencymanager class is derived from the BindingManagerBase class. If all the Windows Form controls are bound to a single Data source, the form will have one CurrencyManager object associated with it. A BindingContext object, Which is a Windows Form object, is usd to keep track of the existing CurrencyManager objects in a form.
Connecting to a Database through Wizard
1. Drag a OleDB or SqlDataAdpter control
2. Select the Servername and Enter user id,password and select the database
3. Query Builder -> Select the Tablename and add required columns
4. Finish the wizard
Creating Dataset
1. Select the OleDB or SqlDataAdapter
2. From Data Menu -> Choose Generate Dataset
3. Enter the Dataset name and select the corresponding table and click ok.
Data Binding
1. Simple Data Binding
2. Complex Data Binding
Complex Data binding
Binding with Listbox, Datagrid Control with multiple values or multiple columns
For Datagrid Control
Properties
DataSource -> Dataset name
DataMember -> Table Name
ListBox
Datasource -> Dataset name
DisplayMember -> Column name
Simple Data Binding
Binding with a single column and single value. Used for Textbox.
TextBox Properties
DataBindings
Text -> Column name
Form_Load
SqlDataAdapter1.Fill(DSCust)
Navigating Between Records
1. Create data adapter
2. Create dataset
3. Binding with controls.
Codings
General Declaration
Dim bm As BindingManagerBase
Form1_Load
SqlDACust.Fill(DsCustomer1)
bm = Me.BindingContext(DsCustomer1, "CustomerTracking")
bm.Position = 0
cmdFirst_Click
bm.Position = 0
cmdLast_Click
bm.Position = bm.Count - 1
cmdPrevious_Click
bm.Position -= 1
cmdNext_Click
bm.Position += 1
Filtering and Sorting Data
Two types of Filtering
1. Parameterized Queries
2. Filter the Dataset
Parameterized Queries
1. Create a SqlDataAdapter-> Select Connection -> Query Builder -> Select CustOrder Table
2. Specify the condition "where Inv=@param"
3. Click next and finish the SqlDataAdapter.
4. Generate the Dataset for SqlDataAdapter
5. Place the controls and bind the Dataset with the controls.
Codings
Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSearch.Click
SqlDataAdapter1.SelectCommand.Parameters("@param").Value = TextBox1.Text
DsCust1.Clear()
SqlDataAdapter1.Fill(DsCust1)
End Sub
Filter the Dataset
Using Select() method
select(condition,sort order)
Eg:
Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelect.Click
Dim dt As DataTable
dt = DsCust1.Tables("CustOrder")
Dim cond As String
Dim sort As String
cond = "cost >3000"
sort = "custid asc"
Dim result() As DataRow
result = dt.Select(cond, sort)
Dim ctr As Integer
For ctr = 0 To result.Length - 1
lstProdid.Items.Add(result(ctr)("custid").ToString)
Next
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SqlDataAdapter1.Fill(DsCust1)
End Sub
Displaying Data From multiple tables.
xsd -> Schema -> Containing conditions for columns
Eg:
Control Properties Settings
sqlDataAdapter1 SelectCommand Select Custid,fname,address from
CustomerTracking
SqlDataAdapter2 SelectCommand Select Inv,InvDate,Custid,prodid from CustOrder
DataSet DSMasterDetail1 CustomerTracking
CustomerOrder
Double click the DSMasterdetail1.xsd from Solution Explorer Window
Create Relation from Toolbox. Drag the Relation object and place it in CustOrder Table.
Label CustomerID
Label Firstname
Label Address
DataGrid DGDetail -> DataSource -> DSMasterDetail1
DataMember -> CustomerTracking -> CustomerTrackingCustOrder
TextBox txtCustid -> DataBindings -> Text -> CustomerTracking -> CustID
TextBox txtFname -> DataBindings -> Text -> CustomerTracking -> Fname
TextBox txtAddress -> DataBindings -> Text -> CustomerTracking ->Address
Codings
Dim bm As BindingManagerBase
Form_Load()
SqlDataAdapter1.Fill(DsMasterDetail1, "CustomerTracking")
SqlDataAdapter2.Fill(DsMasterDetail1, "CustOrder")
bm = Me.BindingContext(DsMasterDetail1, "CustomerTracking")
Next
bm.Position += 1
Previous
bm.Position -= 1
Data Updates
Design Form for the following Table
1. CustomerDetails
Create table CustomerDetails(Custid varchar(10) primary key,CustName varchar(50),
Address Varchar(100),phoneno numeric(15),Email varchar(50),regdate datetime)
2. Design the Form and Bind the Control
3. Codings
General Declaration
Dim bm As BindingManagerBase
Dim flag As Integer = 0
Dim dt As DataTable
Dim dr As DataRow
Dim custid As String
Form_Load
SqlDataAdapter1.Fill(DsCustomer1)
bm = Me.BindingContext(DsCustomer1, "CustomerDetails")
bm.Position = 0
btnFirst_Click
bm.Position = 0
btnPrev_Click
bm.Position -= 1
btnNext_Click
bm.Position += 1
btnLast_Click
bm.Position = bm.Count - 1
btnAdd_Click
ClearText()
flag = 1
Dim cid, cidval As String
Dim ctr, len As Integer
dt = DsCustomer1.Tables("CustomerDetails")
len = dt.Rows.Count - 1
If (len < 0) Then
cid = "C001"
Else
dr = dt.Rows(len)
cidval = dr("Custid")
cidval = Mid(cidval, 2, 3)
ctr = CInt(cidval)
If (ctr > 0 And ctr < 9) Then
ctr = ctr + 1
cid = "C00" & ctr
ElseIf (ctr >= 9 And ctr < 99) Then
ctr = ctr + 1
cid = "C0" & ctr
Else
ctr = ctr + 1
cid = "C" & ctr
End If
End If
txtCustid.Text = cid
txtCustname.Focus()
ClearText
Private Sub ClearText()
txtCustid.Text = ""
txtCustname.Text = ""
txtAddr.Text = ""
txtPhno.Text = ""
txtEmail.Text = ""
txtRdate.Text = ""
End Sub
btnModify_Click
custid = txtCustid.Text
flag = 2
btnDelete_Click
custid = txtCustid.Text
flag = 3
btnSave_Click
If flag = 1 Then
dt = DsCustomer1.Tables("CustomerDetails")
dr = dt.NewRow()
dr(0) = txtCustid.Text
dr(1) = txtCustname.Text
dr(2) = txtAddr.Text
dr(3) = txtPhno.Text
dr(4) = txtEmail.Text
dr(5) = txtRdate.Text
dt.Rows.Add(dr)
ElseIf flag = 2 Then
dt = DsCustomer1.Tables("CustomerDetails")
dr = dt.Rows.Find(custid)
dr.BeginEdit()
dr(1) = txtCustname.Text
dr(2) = txtAddr.Text
dr(3) = txtPhno.Text
dr(4) = txtEmail.Text
dr(5) = txtRdate.Text
dr.EndEdit()
ElseIf flag = 3 Then
dt = DsCustomer1.Tables("CustomerDetails")
dr = dt.Rows.Find(custid)
dr.Delete()
End If
SqlDataAdapter1.Update(DsCustomer1, "CustomerDetails")
SqlDataAdapter1.Fill(DsCustomer1)
bm.Position = 0
txtRdate_GotFocus
txtRdate.Text = System.DateTime.Today
Crystal Report
For Creating Reports and Charts
Three Methods
1. Manually
2. Using Standard Expert
3. From an existing Report
Manually
1. Create a Windows Form
2. From Project Menu -> Add New Item -> CrystalReport
3. Name -> RevenueReport.rpt -> Click Open button
4. Crystal Report Gallery -> Select "As a blank Report" -> Click Ok
5. In the Field Explorer Window -> Database Fields -> Right Click -> Add/Remove Database
6. Select OLEDB (ADO) -> Microsoft OLEDB for SQL server
7. USer id = sa;password=killer;server=system8;database=master
8. Select Table "CustomerTracking" -> Insert Table - Click Finish
9. From Field Explorer Window -> Drag the Required Fields to Details Section
10. In the Form Window -> Place one crystalReportViewer Control -> Properties -> ReportSource -> Browser and Select the -> RevenueReport.rpt
11. Run the Application
Using Standard Expert
1. Create a Windows Form
2. Project Menu -> Add New Item -> CrystalReport
3. Name -> RevenueReport1.rpt -> Click the Open Button
4. Crystal Report Gallery -> Select "Using Standard Expert" -> Click Ok
5. Select OLEDB (ADO) -> Microsoft OLEDB For SQL Server
6. server=system8;user id=sa;password=killer;database=master
7. Select Table "CustOrder" -> Insert Table -> Click Next
8. Select Display Fields -> Click next
9 Select Group Field -> Click Next
10. Select Summarized Field -> Click Next
11. Chart -> Select chart type -> Text -> Title (Revenue Report) -> Click Next
12. Click next
13. Click Next
14. Click Finish
15. In the Form Window -> Place one crystalReportViewer Control -> Properties -> ReportSource -> Browser and Select the -> RevenueReport.rpt
Filtering Data report
1. Create a Windows Form
2. Create a SQLDataAdapter -> Select CustOrder and Set the condition as "Cost>3000"
3. Generate a DataSet with the Name of DSReport
4. Project Menu -> Add New Item -> CrystalReport
5. Name -> RevenueReport2.rpt -> Click Open
6. Crystal Gallery Report -> Select "As a blank Report"
7. In the Field Explorer Window -> Database Fields -> Add /Remove Database
8. Select "Project Data" -> ADO.NET -> Datastet -> DSReport -> Custorder
9. From Field Explorer -> Drag the Required Field
10. Group Name Fields -> New -> CustOrder.Prodid
11. Running Total Field -> New -> CustOrder.Cost -> Sum
12. Formula Field -> New -> Enter "Percentage" -> Formulat Editor -> CustOrder.Advance / CustOrder.Cost * 100
13. Drag the Formula Field in the Details Section
14. In the Form Code Window add the following Code
Global Declaration
Dim cr As New RevenueReport2
Form_Load
SqlDataAdapter1.Fill(DsReport1, "Custorder")
cr.SetDataSource(DsReport1)
CrystalReportViewer1.ReportSource = cr
Relating Data Report
1. Create a Windows Form
2. Project Menu -> Add New Item -> CrystalReport
3. Name -> RelatingReport.rpt-> Click Open
4. Crystal Report Gallery -> Select "Using Standard Expert"
5. Select OLEDB (ADO) - > Microsoft OLEDB For SQL - Server
6. Server=system8;user id=sa;password=killer;database=master;
7. Select -> CustomerTracking and CustOrder Table
8. Relating window Displayed -> Click Next
9. Select Displaying Fields and Click NExt
10. Select Group Field and Click Next
11. Select Summarized Field and Click Next
13. Create Chart if need
14. Click the Next and Finish the Report
15. In the Form Window -> Place one crystalReportViewer Control -> Properties -> ReportSource -> Browser and Select the -> RelatingReport.rpt
Setting Primary key and Foreign Key in Table
Create table Custtrack(custid varchar(10) primary key)
(or)
Alter table custtrack add constraint cpk2 primary key(custid)
Create table custorder1(custid varchar(10) references custtrack(custid))
(or)
Alter table custorder1 add constraint cfk2 foreign key(custid) references custtrack(custid)
Menus
MainMenu -> Normal Menus created in Menubar
ContextMenu -> For creating shortcut menus
MDI Forms -> Multiple Document Interface
Eg: MS - Word
Drag MainMenu from Toolbar and set the Name and Caption Property
Form1 -> IsMdiContainer -> Set to True
Context Menu
Drag Context Menu From toolbar
Create MenuItems with Itemname
Form1 -> ContextMenu Property -> ContextMenu1
Toolbar
Drag a ImageList Control -> Property -> Images -> Add some Images
Drag a Toolbar Control -
Property
ImageList ImageList1
Button collection Add Buttons with Name and ImageIndex
Statubar
Drag a Statusbar Control
Property
ShowPanels True
Panels Add Panel and Set the Name Property
Codings
Private Sub mnuNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuNew.Click
Dim myform As New Second
myform.MdiParent = Me
myform.Show()
End Sub
Private Sub mnuSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuSave.Click
MsgBox("Save Clicked")
End Sub
Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click
End
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WindowState = FormWindowState.Maximized
SBPanel2.Text = System.DateTime.Now()
End Sub
Private Sub mnuVertical_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuVertical.Click
Me.LayoutMdi(MdiLayout.TileVertical)
End Sub
Private Sub mnuHorizontal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuHorizontal.Click
Me.LayoutMdi(MdiLayout.TileHorizontal)
End Sub
Private Sub mnuCascade_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuCascade.Click
Me.LayoutMdi(MdiLayout.Cascade)
End Sub
Private Sub mnuArrIcons_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuArrIcons.Click
Me.LayoutMdi(MdiLayout.ArrangeIcons)
End Sub
Private Sub mnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnNew.Click
Dim myform As New Second
myform.MdiParent = Me
myform.Show()
End Sub
Private Sub mnHori_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnHori.Click
Me.LayoutMdi(MdiLayout.TileHorizontal)
End Sub
Private Sub mnVert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnVert.Click
Me.LayoutMdi(MdiLayout.TileVertical)
End Sub
Private Sub ToolBar1_ButtonClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolBarButtonClickEventArgs) Handles ToolBar1.ButtonClick
Select Case ToolBar1.Buttons.IndexOf(e.Button)
Case 0
Dim myform As New Second
myform.MdiParent = Me
myform.Show()
sbPanel1.Text = "New Form"
Case 1
MsgBox("Save Clicked'")
sbPanel1.Text = "Save Form"
Case 2
sbPanel1.Text = "Exit Form"
End
End Select
End Sub
File Handling
A file is a collection of bytes that has a persistent storage. The data in a file is stored as data streams and when we read from or write to a file, we read or write data as data streams.
A data stream is a sequence of bytes that can be written to or read from a backup device, such as hard disk.
File I/O perform in two different ways.
1. Using the .NET System.IO model
2. Using the Visual Basic- runtime functions
Using System.IO Model
This model are available to all the .NET languages. These classes are contained in the System.IO namespace and are used for creating copying, moving and deleteing files. The most frequently used classes in the System.IO namespace are FileStream, BinaryReader, BinaryWriter, StreamReader, StreamWriter, TextReader,TextWriter and Directory.
FileStream Class
This class provides access to files and file related information. The FileSystem class is used with the File class, which is also contained in the System.IO namespace, to create, copy, delete, move and open files.
FileStream class opens a file either in synchronous mode or asynchronous mode.
Synchronous mode -> The entire file is first read and then displayed to the user.
Method used -> Read() and Write() method
Asynchronous mode -> starts reading and displaying files in parts
Method Used -> BeginRead() and BeginWrite()
FileMode
Append-> File must be exists and open the file and set the file pointer to end of file
Create -> New Creation. If the file exists, the file is overwritten
CreateNew -> Create a New file. If the file is exists it throws an exception
Open -> open an existing file
OpenOrCreate -> Open an existing file, if the file exists or create a new file
Truncate-> Delete the file and recreate it. File must be exists.
FileAccess
Read -> Read Only
ReadWrite -> Read and Write
Write -> Write only.
FileShare
Read
ReadWrite
Write
FileCreation
Eg:
Dim fstream As New FileStream("c:\sample.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
MsgBox("File Created")
BinaryReader and BinaryWriter
In .NET we can store data in binary format to keep the size of a file small.
Eg:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim files As FileStream = New FileStream("c:\myfile.txt", FileMode.OpenOrCreate)
Dim bw As New BinaryWriter(files)
Dim br As New BinaryReader(files)
Dim j As Integer
For j = 1 To 10
bw.Write(CStr(j))
Next
br.BaseStream.Seek(0, SeekOrigin.Begin)
TextBox1.Text = br.ReadChars(20)
End Sub
Offsets
SeekOrigin.BEGIN -> Beginning of File
SeekOrigin.CURRENT -> Move to current pointer
SeekOrigin.END -> End of file
StreamReader and StreamWriter
These classes internally use specific encoding to convert characters to and from bytes.
Create a Form with a RichTextBox Control
Eg:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim fstream As New FileStream("C:\mydata.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim sw As New StreamWriter(fstream)
sw.BaseStream.Seek(0, SeekOrigin.End)
writedata("My Employee code is 102", sw)
writedata("My Language is Sanskrit", sw)
Dim sr As New StreamReader(fstream)
sr.BaseStream.Seek(0, SeekOrigin.Begin)
readdata(sr)
End Sub
Public Sub writedata(ByVal data As String, ByVal sw As StreamWriter)
sw.Write("Entry : ")
sw.WriteLine(data)
sw.WriteLine("---------------------------------")
sw.Flush()
End Sub
Public Sub readdata(ByVal r As StreamReader)
RichTextBox1.Text = r.ReadToEnd
r.Close()
End Sub
The Directory Class
CreateDirectory Directory.CreateDirectory("C:\vb_users")
Delete Directory.Delete("c:\vb_users")
Exists Msgbox(Directory.Exists("c:\vb_users"))
GetDirectoryRoot Msgbox(Directory.GetDirectoryRoot("c:\Vb_users"))
GetLogicalDrives
Imports System.IO
Public class Form1
Inherits System.Windows.Forms.Form
Dim s() as String
dim i,j as Integer
Private Sub Form1_Load()
s = Directory.GetLogicalDrives()
i = s.length
For j = 0 to i - 1
RichTextBox1.Text = RichTextBox1.Text + s(j) + Chr(13)
Next
End Sub
End Class
Move Directory.Move("c:\my_Dir","c:\vb_users\MyDir")
Creating Help System
hhp -> Html Help Project
hhc -> Html Help Contents
hhk -> Html Help Index
htm -> Html file
Steps to Create Help file system
Programs -> HTML Help Workshop
1. File -> New -> Project
2. Click Next -> Browse the location to save the .hhp file.
3. Click Next -> Click Finish
4. File -> New -> HTML File
Enter the Title and Contents of the HTML File and Save the file
Title Contents Filename
---------- ------------ -------------
Maintaining Records Maintain.htm
Add Record Add.htm
Modify Record Modify.htm
Delete Record Delete.htm
View Record View.htm
5. Select the Index Tab -> Create a new Index File
6. Select the option -> Insert a Keyword
Enter the Keyword (Maintaining Record) and Add the file (Maintain.htm) for the keyword and click ok
Similary add all the keyword with htm file.
7. Select the Contents Tab -> Create a new Contents File
8. Select the option -> Insert a Heading -> Maintaing Records -> Maintain.htm
9. Select the option -> Insert a Page -> Enter keyword and Select the correspoding files
10. Select the Projects Tab -> Select "Change Project options"
Enter the Title and Select the Default page to display while pressing F1
11. File Menu -> Compile option -> Select the two checkbox and Click "Compile"
12. View Menu -> Compiled File -> Select the File and view
Adding File system with Project Menu
1. Drag a HTMLHelpProvider Control
Properties -> HTMLNamespace -> Select the Help File
Control Properties
Show Help on HelpProvider1 -> True
Helpkeyword on HelpProvider1 -> Enter the Keyword
HelpNavigator on HelpProvider1 -> Select the Navigation option
Deploying the Application
1.File -> New -> Project -> Setup and Deployment Projects -> "CallCenter" -> Click Ok
2. File -> Add Project -> Existing Project -> "DataUpdates.vbproj"
3. Open the "File System" editor by selecting "View -> Editor -> File System"
4. Select the "File System On Target Machine" node
5. Select "Action -> Add Special Folder ->Program Files Folder"
6. Select the "Program Files Folder" node. Select "Action->Add->Folder". Type the name of the folder as "CallCenter"
7. To Add the output of the "Data Entry Application" project to the "CallCenter" folder, select the "CallCenter" folder. Select "Action-> Add-> Project Output". This opens the "Add Project Output Group" dialog box.
8. Select "Data Entry Applicaion" from the Project drop down list, Select "Primary Output" from the Output list.
9. click the ok button
Create a shortcut for the application
10. In the "File System" editor, Select the "CallCenter" folder. In the details pane of the "File System" editor, select "Primary Output from Data Entry Applcation (Active)".
11. Select "Action -> Create Shortcut to Primary Output from Data Entry Application (Active)".
12. Change the name of the shortcut to "CallCenter"
13. Drag the shortcut to the "User's Desktop" mode in the "File System Editor"
Add a dialog box to the deployment project
14. Open "Wordpad" and type the text to be displayed in the license agreement.
15. Save the file with the extension of ".rtf" (Rich text format)
16. In the Visual Studio .NET deployment project, open the "User Interface" editor by selecting "view -> editor -> User Interface"
17. In the "Install" section, select "Start"
18. Select "Action -> Add Dialog"
19. In the "Add Dialog" dialog box, Select "License Agreement", click the ok button
20. Move the License agreement dialogbox so that it appears immediately after the Welcome dialog box.
21. Select the "License Agreement" node in the User Interface editor and press F4 key to switch to properties window.
22. Select the License file property and select the rtf file.
23. In the "Select Item in Project" dialog box, Click ok button
24. Build the Application
Execute the Installer
1. Browse the deployment project folder. In the Debug folder -> it contains the Setup Project and Uninstall Project"
2. Double click and install the project
Component Technology
Component
* A component is a reusable piece of code in binary form that can be plugged into components from other vendors, with relatively little effort.
* Component can be part of an application that implements Business logic.
* We can reuse code by inheritance.
Component Architecture of .NET
Components have to interact with each other. For example, a component that accepts user information might use another component to validate the information. This is achieved, in Visual Basic .NET, by putting the components within a self contained package called assembly. An assembly contains information about the files on which the component depends and the location of these files. The CLR can use this information to determine the dependencies of a component. The assemblies that are required during the execution of an assembly are called dependencies.
An assembly usually consists of a manifest and the portable executables (PE)
Manifest
A manifest consists of information such as the name and version of the assembly. It also contains information about other files, such as text files, assemblies and graphics files that assembly uses.
Portable executables (PE)
A portable executable consists of the IL code, type information, and meta data. The manifest might be stored as a part of a portable executable. The metadata consists of information about every type, such as classes and structures defined and used in our code.
Characteristics of a Component
1. The name of the component class should be short and meaningful. It should be a combination of whole words with a capitalized initial character for each word.
2. We can control the use of a component by using proper access level for the constructors. Classes or components that are used internally by the assembly should have private access where as a component that is intended for use outside the containing assembly should have public access.
3. The base class of all component class is the class Component or IComponent class.
4. The namespace structure in an assembly should be according to the internal organization of the components. We should group related components together in separate namespaces. The project name becomes the root namespace by default.
Life cycle of component
1. The constructors initialize components. Initialization can be two types, type initialization and instance initialization. Type initialization is achieve by shared constructors. Instance initialization is achieved by constructors.
2. The instance of our component is destroyed when the garbage collector finds that there are no references to the components. All clean up code should be put into the Finalize code.
Eg:
1. File -> New -> Project -> Visual Basic Projects -> Class Library Project -> "CValidator"
2. Project Menu -> Add Component -> Component Class
3. Change the name of the class in the line of code to "CardValidator"
4. Change the file name to "CardValidator.vb"
5. Delete the default class library project "Class1.vb"
6. Save the Project
7. Add Properties and Functions to the component
Public Class CardValidator
Inherits System.ComponentModel.Component
Private Name As String
Private CardNo As String
Public Property CustomerName() As String
Get
Return Name
End Get
Set(ByVal CustName As String)
Name = CustName
End Set
End Property
Public Property CardNumber() As String
Get
Return CardNo
End Get
Set(ByVal Number As String)
CardNo = Number
End Set
End Property
Public Function Validate() As Integer
Dim cardlength As Integer = 0
cardlength = CardNo.Length
Dim valid As Boolean
If cardlength = 14 Then
Return True
Else
Return False
End If
End Function
End Class
8. Build Menu -> click Build Solution
(It creates a DLL file -> Dynamic Link Library)
Create a User interface to display the result
1. Create a windows application project name "CreditCardDetails".
2. Create Two labels and two textboxes "TextCustName" and "TextCard"
3. Create a Button Control "Validate"
4. In the solution explorer window right click "References"-> Choose "Add Reference"
5. Browse and Navigate the "CValidator.dll" and Click Open
6. Add the Following Code
Imports CValidator
Private Sub btnValidate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnValidate.Click
Dim validator As CardValidator
validator = New CardValidator
validator.CardNumber = txtCardNo.Text
validator.CustomerName = txtCustName.Text
validator.Validate()
If validator.Validate = True Then
MsgBox("Valid Card Number")
Else
MsgBox("Invalid Card Number")
End If
End Sub
User Controls
When we design an application with graphical user interface, we usually use objects that the user can use to control the flow of the application. These controls are visual components that can be used across applications.
The UserControl Class
The UserControl class can contain multiple Child controls. The UserControl class represents a Single and unified interface. This interface contains inherted from the Control classes.
Creating Customized User Controls
Eg:
1. Create a new Windows Control Library and name it CDateLib.
2. In the Solution Explorer Window, change UserControl.vb to BritishDateTimePicker.vb by right clicking UserControl1.vb and selecting the Rename option from the short - cut - menu.
3. Right Click BritishDateTimePicker.vb and select view code from the shortcut menu
4. Change the name of the class to BritishDateTimePicker. In addition, change the inherits state to Inherits System.Windows.Forms.DateTimePicker.
5. Double Click the Windows Form Designer generated code,
6. In the New() method, add the following code after the InitializeComponent method.
Format = DateTimePickerFormat.Custom
CustomFormat = "dd/MM/yy"
7. Build -> Build the Solution.
Test Your control
1. Create a new Windows application
2. Right click and customize the toolbox.
3. Select the .NET Framework Components tab -> browse -> CDatelib.dll
4. Select the Control BritishDateTimePicker and click ok
5. Drag the control and Build and execute.
Eg:
1. File -> New -> Project -> Windows Control Library -> "NumericTextBox"
2. Change the name of the control to "NumericTextBox"
3. Switch to Code view and add the following code
Public Class NumericTextBox
Inherits System.Windows.Forms.TextBox
Private maxValue As Integer
Private minValue As Integer
Public Property Max() As Integer
Get
Return maxValue
End Get
Set(ByVal Value As Integer)
maxValue = Value
End Set
End Property
Public Property Min() As Integer
Get
Return minValue
End Get
Set(ByVal Value As Integer)
minValue = Value
End Set
End Property
Protected Overrides Sub OnLostFocus(ByVal e As System.EventArgs)
If Val(Text) < minValue Then
MsgBox("Not in Range")
End If
If Val(Text) > maxValue Then
MsgBox("Not in Range")
End If
End Sub
End class
4. Build the solution
Testing Control
1. Create a New Windows Application
2. Right click in Toolbox -> click the browse button and select the NumericTextBox.dll
3. Drag the Control and Set the Min and Max Property value
4. Execute and Check the Control
en
MsgBox("Not in Range")
End If
If Val(Text)
> maxValue Then
MsgBox("Not in Range")
End If
End Sub
End class
4. Build the solution
Testing Control
1. Create a New Windows Application
2. Right click in Toolbox -> click the browse button and
select the NumericTextBox.dll
3. Drag the Control and Set the Min and Max Property value
4. Execute and Check the Control