Thursday 20 June 2013

Advanced VB.net

VB.Net - Regular Expressions


regular expression is a pattern that could be matched against an input text. The .Net framework provides a regular expression engine that allows such matching. A pattern consists of one or more character literals, operators, or constructs.

Constructs for Defining Regular Expressions

There are various categories of characters, operators, and constructs that lets you to define regular expressions. 
  • Character escapes
  • Character classes
  • Anchors
  • Grouping constructs
  • Quantifiers
  • Backreference constructs
  • Alternation constructs
  • Substitutions
  • Miscellaneous constructs

The Regex Class

The Regex class is used for representing a regular expression.
The Regex class has the following commonly used methods:
S.NMethods & Description
1Public Function IsMatch ( input As String ) As Boolean 
Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.
2Public Function IsMatch ( input As String, startat As Integer ) As Boolean 
Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string.
3Public Shared Function IsMatch ( input As String, pattern As String ) As Boolean 
Indicates whether the specified regular expression finds a match in the specified input string.
4Public Function Matches ( input As String ) As MatchCollection 
Searches the specified input string for all occurrences of a regular expression.
5Public Function Replace ( input As String, replacement As String ) As String 
In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.
6Public Function Split ( input As String ) As String() 
Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.
For the complete list of methods and properties, please consult Microsoft documentation.

Example 1

The following example matches words that start with 'S':
Imports System.Text.RegularExpressions
Module regexProg
   Sub showMatch(ByVal text As String, ByVal expr As String)
      Console.WriteLine("The Expression: " + expr)
      Dim mc As MatchCollection = Regex.Matches(text, expr)
      Dim m As Match
      For Each m In mc
          Console.WriteLine(m)
      Next m
   End Sub
   Sub Main()
      Dim str As String = "A Thousand Splendid Suns"
      Console.WriteLine("Matching words that start with 'S': ")
      showMatch(str, "\bS\S*")
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns

Example 2

The following example matches words that start with 'm' and ends with 'e':
Imports System.Text.RegularExpressions
Module regexProg
   Sub showMatch(ByVal text As String, ByVal expr As String)
      Console.WriteLine("The Expression: " + expr)
      Dim mc As MatchCollection = Regex.Matches(text, expr)
      Dim m As Match
      For Each m In mc
          Console.WriteLine(m)
      Next m
   End Sub
   Sub Main()
      Dim str As String = "make a maze and manage to measure it"
      Console.WriteLine("Matching words that start with 'm' and ends with 'e': ")
      showMatch(str, "\bm\S*e\b")
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure

Example 3

This example replaces extra white space:
Imports System.Text.RegularExpressions
Module regexProg
   Sub Main()
      Dim input As String = "Hello    World   "
      Dim pattern As String = "\\s+"
      Dim replacement As String = " "
      Dim rgx As Regex = New Regex(pattern)
      Dim result As String = rgx.Replace(input, replacement)
      Console.WriteLine("Original String: {0}", input)
      Console.WriteLine("Replacement String: {0}", result)
      Console.ReadKey()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Original String: Hello   World   
Replacement String: Hello World   

\

VB.Net - Database Access

Applications communicate with a database, firstly, to retrieve the data stored there and present it in a user-friendly way, and secondly, to update the database by inserting, modifying and deleting data.
Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net framework that is used by the .Net applications for retrieving, accessing and updating data.

ADO.Net Object Model

ADO.Net object model is nothing but the structured process flow through various components. The object model can be pictorially described as:
ADO.Net objects
The data residing in a data store or database is retrieved through the data provider. Various components of the data provider, retrieves data for the application and update data.
An application accesses data either through a dataset or a data reader.
  • Data sets store data in a disconnected cache and the application retrieve data from it.
  • Data readers provide data to the application in a read-only and forward-only mode.

Data Provider

A data provider is used for connecting to a database, executing commands and retrieving data, storing it in a dataset, reading the retrieved data and updating the database.
The data provider in ADO.Net consists of the following four objects:
S.NObjects & Description
1Connection
This component is used to set up a connection with a data source.
2Command
A command is a SQL statement or a stored procedure used to retrieve, insert, delete or modify data in a data source.
3DataReader
Data reader is used to retrieve data from a data source in a read-only and forward-only mode.
4DataAdapter
This is integral to the working of ADO.Net since data is transferred to and from a database through a data adapter. It retrieves data from a database into a dataset and updates the database. When changes are made to the dataset, the changes in the database are actually done by the data adapter.
There are following different types of data providers included in ADO.Net
  • The .Net Framework data provider for SQL Server - provides access to Microsoft SQL Server.
  • The .Net Framework data provider for OLE DB - provides access to data sources exposed by using OLE DB.
  • The .Net Framework data provider for ODBC - provides access to data sources exposed by ODBC.
  • The .Net Framework data provider for Oracle - provides access to Oracle data source.
  • The EntityClient provider - enables accessing data through Entity Data Model (EDM) applications.

DataSet

DataSet is an in-memory representation of data. It is a disconnected, cached set of records that are retrieved from a database. 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. This is called the 'disconnected architecture'. The dataset works as a virtual database, containing tables, rows, and columns.
The following diagram shows the dataset object model:
VB.Net Data Classes
The DataSet class is present in the System.Data namespace. The following table describes all the components of DataSet:
S.NComponents & Description
1DataTableCollection
It contains all the tables retrieved from the data source.
2DataRelationCollection
It contains relationships and the links between tables in a data set.
3ExtendedProperties
It contains additional information, like the SQL statement for retrieving data, time of retrieval etc.
4DataTable
It represents a table in the DataTableCollection of a dataset. It consists of the dataRow and DataColumn objects. The DataTable objects are case-sensitive.
5DataRelation
It represents a relationship in the DataRelationshipCollection of the dataset. It is used to relate two DataTable objects to each other through the DataColumn objects.
6DataRowCollection
It contains all the rows in a DataTable.
7DataView
It represents a fixed customized view of a DataTable for sorting, filtering, searching, editing and navigation.
8PrimaryKey
It represents the column that uniquely identifies a row in a DataTable.
9DataRow
It represents a row in the DataTable. The DataRow object and its properties and methods are used to retrieve, evaluate, insert, delete, and update values in the DataTable. The NewRow method is used to create a new row and the Add method adds a row to the table.
10DataColumnCollection
It represents all the columns in a DataTable.
11DataColumn
It consists of the number columns that comprise a DataTable.

Connecting to a Database

The .Net Framework provides two types of Connection classes:
  • SqlConnection - designed for connecting to Microsoft SQL Server.
  • OleDbConnection - designed for connecting to a wide range of databases, like Microsoft Access and Oracle.

Example 1

We have a table stored in Microsoft SQL Server, named Customers, in a database named testDB. Please consult 'SQL Server' tutorial for creating databases and database tables in SQL Server.
Let us connect to this database. Take the following steps:
  1. Select TOOLS -> Connect to Database
    VB.Net Database connection Example
  2. Select a server name and the database name in the Add Connection dialog box.
    VB.Net Database Connection
  3. Click on the Test Connection button to check if the connection succeeded.
    Connection Success
  4. Add a DataGridView on the form.
    VB.Net DataGridView
  5. Click on the Choose Data Source combo box.
  6. Click on the Add Project Data Source link.
    Add Project Data Source Link
  7. This opens the Data Source Configuration Wizard.
  8. Select Database as the data source type
    Data Source
  9. Choose Dataset as the database model.
    Database Model
  10. Choose the connection already set up
    VB.Net Database Connection
  11. Save the connection string.
    Saving the connection string
  12. Choose the database object, Customers table in our example, and click the Finish button.
    VB.Net database connection
  13. Select the Preview Data link to see the data in the Results grid:
    Data Preview
When the application is run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
VB.net data in data grid view

Example 2

In this example, let us access data in a DataGridView control using code. Take the following steps:
  1. Add a DataGridView control and a button in the form.
  2. Change the text of the button control to 'Fill'
  3. Double click the button control to add the required code for the Click event of the button, as shown below:
Imports System.Data.SqlClient
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) _
   Handles MyBase.Load
        'TODO: This line of code loads data into the 'TestDBDataSet.CUSTOMERS' table.   You can move, or remove it, as needed.
      Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
      ' Set the caption bar text of the form.   
      Me.Text = "only4programmers.blogspot.com"
   End Sub
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      Dim connection As SqlConnection = New sqlconnection()
      connection.ConnectionString = "Data Source=KABIR-DESKTOP; _
          Initial Catalog=testDB;Integrated Security=True"
      connection.Open()
      Dim adp As SqlDataAdapter = New SqlDataAdapter _
      ("select * from Customers", connection)
      Dim ds As DataSet = New DataSet()
      adp.Fill(ds)
      DataGridView1.DataSource = ds.Tables(0)
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
Database Connectivity
Clicking the Fill button, displays the table on the data grid view control:
Database connectivity

Creating Table, Columns and Rows

We have discussed that the DataSet components like DataTable, DataColumn and DataRow allows us to create tables, columns and rows respectively.
The following example demonstrates the concept:

Example 3

So far, we have used tables and databases already existing in our computer. In this example, we will create a table, add column, rows and data into it and display the table using a DataGridView object.
Take the following steps:
  • Add a DataGridView control and a button in the form.
  • Change the text of the button control to 'Fill'
  • Add the following code in the code editor
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      ' Set the caption bar text of the form.   
      Me.Text = "tutorialspont.com"
   End Sub
   Private Function CreateDataSet() As DataSet
      'creating a DataSet object for tables
      Dim dataset As DataSet = New DataSet()
      ' creating the student table
      Dim Students As DataTable = CreateStudentTable()
      dataset.Tables.Add(Students)
      Return dataset
   End Function
   Private Function CreateStudentTable() As DataTable
      Dim Students As DataTable
      Students = New DataTable("Student")
      ' adding columns
      AddNewColumn(Students, "System.Int32", "StudentID")
      AddNewColumn(Students, "System.String", "StudentName")
      AddNewColumn(Students, "System.String", "StudentCity")
      ' adding rows
      AddNewRow(Students, 1, "Zara Ali", "Kolkata")
      AddNewRow(Students, 2, "Shreya Sharma", "Delhi")
      AddNewRow(Students, 3, "Rini Mukherjee", "Hyderabad")
      AddNewRow(Students, 4, "Sunil Dubey", "Bikaner")
      AddNewRow(Students, 5, "Rajat Mishra", "Patna")
      Return Students
   End Function
   Private Sub AddNewColumn(ByRef table As DataTable, _ 
   ByVal columnType As String, ByVal columnName As String)
      Dim column As DataColumn = _ 
       table.Columns.Add(columnName, Type.GetType(columnType))
   End Sub

   'adding data into the table
   Private Sub AddNewRow(ByRef table As DataTable, ByRef id As Integer,_
   ByRef name As String, ByRef city As String)
      Dim newrow As DataRow = table.NewRow()
      newrow("StudentID") = id
      newrow("StudentName") = name
      newrow("StudentCity") = city
      table.Rows.Add(newrow)
   End Sub
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      Dim ds As New DataSet
      ds = CreateDataSet()
      DataGridView1.DataSource = ds.Tables("Student")
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
Example
Clicking the Fill button, displays the table on the data grid view control:
Example

VB.Net - Excel Sheet

VB.Net provides support for interoperability between the COM object model of Microsoft Excel 2010 and your application.
To avail this interoperability in your application, you need to import the namespaceMicrosoft.Office.Interop.Excel in your Windows Form Application.

Creating an Excel Application from VB.Net

Let's start with creating a Window Forms Application by following the following steps in Microsoft Visual Studio: File -> New Project -> Windows Forms Applications
Finally select OK, Microsoft Visual Studio your project and displays following window with a default Form with a name Form1.
Insert a Button control Button1, in the form.
Add a reference to Microsoft Excel Object Library to your project. To do this:
  1. Select Add Reference from the Project Menu.
    Add Reference
  2. On the COM tab, locate Microsoft Excel Object Library, and then click Select.
    COM tab
  3. Click OK.
Double click the code window, and populate the Click event of Button1, as shown below.
'  Add the following code snippet on top of Form1.vb
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      Dim appXL As Excel.Application
      Dim wbXl As Excel.Workbook
      Dim shXL As Excel.Worksheet
      Dim raXL As Excel.Range
      ' Start Excel and get Application object.
      appXL = CreateObject("Excel.Application")
      appXL.Visible = True
      ' Add a new workbook.
      wbXl = appXL.Workbooks.Add
      shXL = wbXl.ActiveSheet
      ' Add table headers going cell by cell.
      shXL.Cells(1, 1).Value = "First Name"
      shXL.Cells(1, 2).Value = "Last Name"
      shXL.Cells(1, 3).Value = "Full Name"
      shXL.Cells(1, 4).Value = "Specialization"
      ' Format A1:D1 as bold, vertical alignment = center.
      With shXL.Range("A1", "D1")
          .Font.Bold = True
          .VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
      End With
      ' Create an array to set multiple values at once.
      Dim students(5, 2) As String
      students(0, 0) = "Zara"
      students(0, 1) = "Ali"
      students(1, 0) = "Nuha"
      students(1, 1) = "Ali"
      students(2, 0) = "Arilia"
      students(2, 1) = "RamKumar"
      students(3, 0) = "Rita"
      students(3, 1) = "Jones"
      students(4, 0) = "Umme"
      students(4, 1) = "Ayman"
      ' Fill A2:B6 with an array of values (First and Last Names).
      shXL.Range("A2", "B6").Value = students
       ' Fill C2:C6 with a relative formula (=A2 & " " & B2).
      raXL = shXL.Range("C2", "C6")
      raXL.Formula = "=A2 & "" "" & B2"
       ' Fill D2:D6 values.
      With shXL
          .Cells(2, 4).Value = "Biology"
          .Cells(3, 4).Value = "Mathmematics"
          .Cells(4, 4).Value = "Physics"
          .Cells(5, 4).Value = "Mathmematics"
          .Cells(6, 4).Value = "Arabic"
      End With
      ' AutoFit columns A:D.
      raXL = shXL.Range("A1", "D1")
      raXL.EntireColumn.AutoFit()
       ' Make sure Excel is visible and give the user control
      ' of Excel's lifetime.
      appXL.Visible = True
      appXL.UserControl = True
       ' Release object references.
      raXL = Nothing
      shXL = Nothing
      wbXl = Nothing
      appXL.Quit()
      appXL = Nothing
      Exit Sub
Err_Handler:
      MsgBox(Err.Description, vbCritical, "Error: " & Err.Number)
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
VB.Net Excel Example
Clicking on the Button, would display the following excel sheet. You will be asked to save the workbook.
VB.Net Excel Result Form

VB.Net - Send Email

Advertisements


VB.Net allows sending E-mails from your application. The System.Net.Mail namespace contains classes used for sending emails to a Simple Mail Transfer Protocol (SMTP) server for delivery.
The following table lists some of these commonly used classes:
S.NClassDescription
1AttachmentRepresents an attachment to an e-mail.
2AttachmentCollectionStores attachments to be sent as part of an e-mail message.
3MailAddressRepresents the address of an electronic mail sender or recipient.
4MailAddressCollectionStore e-mail addresses that are associated with an e-mail message.
5MailMessageRepresents an e-mail message that can be sent using the SmtpClient class.
6SmtpClientAllows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
7SmtpExceptionRepresents the exception that is thrown when the SmtpClient is not able to complete a Send or SendAsync operation.

The SmtpClient Class

The SmtpClient class allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
Following are some commonly used properties of the SmtpClient class:
S.NPropertyDescription
1ClientCertificatesSpecify which certificates should be used to establish the Secure Sockets Layer (SSL) connection.
2CredentialsGets or sets the credentials used to authenticate the sender.
3EnableSslSpecify whether the SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection.
4HostGets or sets the name or IP address of the host used for SMTP transactions..
5PortGets or sets the port used for SMTP transactions.
6TimeoutGets or sets a value that specifies the amount of time after which a synchronous Send call times out.
7UseDefaultCredentialsGets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.
Following are some commonly used methods of the SmtpClient class:
S.NMethod & Description
1Dispose
Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, and releases all resources used by the current instance of the SmtpClient class.
2Dispose(Boolean)
Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, releases all resources used by the current instance of the SmtpClient class, and optionally disposes of the managed resources.
3OnSendCompleted
Raises the SendCompleted event.
4Send(MailMessage)
Sends the specified message to an SMTP server for delivery.
5Send(String, String, String, String)
Sends the specified e-mail message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using String objects.
6SendAsync(MailMessage, Object)
Sends the specified e-mail message to an SMTP server for delivery. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.
7SendAsync(String, String, String, String, Object)
Sends an e-mail message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using String objects. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.
8SendAsyncCancel
Cancels an asynchronous operation to send an e-mail message.
9SendMailAsync(MailMessage)
Sends the specified message to an SMTP server for delivery as an asynchronous operation.
10SendMailAsync(String, String, String, String)
Sends the specified message to an SMTP server for delivery as an asynchronous operation. . The message sender, recipients, subject, and message body are specified using String objects.
11ToString
Returns a string that represents the current object.
The following example demonstrates how to send mail using the SmtpClient class. Following points are to be noted in this respect:
  • You must specify the SMTP host server that you use to send e-mail. The Host and Portproperties will be different for different host server. We will be using gmail server.
  • You need to give the Credentials for authentication, if required by the SMTP server.
  • You should also provide the email address of the sender and the e-mail address or addresses of the recipients using the MailMessage.From and MailMessage.To properties respectively.
  • You should also specify the message content using the MailMessage.Body property.

Example

In this example, let us create a simple application that would send an email. Take the following steps:
  1. Add three labels, three text boxes and a button control in the form.
  2. Change the text properties of the labels to - 'From', 'To:' and 'Message:' respectively.
  3. Change the name properties of the texts to txtFrom, txtTo and txtMessage respectively.
  4. Change the text property of the button control to 'Send'
  5. Add the following code in the code editor.
Imports System.Net.Mail
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      ' Set the caption bar text of the form.   
      Me.Text = "only4programmers.blogspot.com"
   End Sub

   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      Try
          Dim Smtp_Server As New SmtpClient
          Dim e_mail As New MailMessage()
          Smtp_Server.UseDefaultCredentials = False
          Smtp_Server.Credentials = New Net.NetworkCredential("username@gmail.com", "password")
          Smtp_Server.Port = 587
          Smtp_Server.EnableSsl = True
          Smtp_Server.Host = "smtp.gmail.com"

          e_mail = New MailMessage()
          e_mail.From = New MailAddress(txtFrom.Text)
          e_mail.To.Add(txtTo.Text)
          e_mail.Subject = "Email Sending"
          e_mail.IsBodyHtml = False
          e_mail.Body = txtMessage.Text
          Smtp_Server.Send(e_mail)
          MsgBox("Mail Sent")

      Catch error_t As Exception
          MsgBox(error_t.ToString)
      End Try

   End Sub
You must provide your gmail address and real password for credentials.
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window which you will use to send your emails, try it yourself.
Sending Email from VB.Net

VB.Net - XML Processing

Advertisements


The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard.
The System.Xml namespace in the .Net Framework contains classes for processing XML documents. Following are some of the commonly used classes in the System.Xml namespace.
S.NClassDescription
1XmlAttributeRepresents an attribute. Valid and default values for the attribute are defined in a document type definition (DTD) or schema.
2XmlCDataSectionRepresents a CDATA section.
3XmlCharacterDataProvides text manipulation methods that are used by several classes.
4XmlCommentRepresents the content of an XML comment.
5XmlConvertEncodes and decodes XML names and provides methods for converting between common language runtime types and XML Schema definition language (XSD) types. When converting data types the values returned are locale independent.
6XmlDeclarationRepresents the XML declaration node <?xml version='1.0'...?>.
7XmlDictionaryImplements a dictionary used to optimize Windows Communication Foundation (WCF)'s XML reader/writer implementations.
8XmlDictionaryReaderAn abstract class that the Windows Communication Foundation (WCF) derives from XmlReader to do serialization and deserialization.
9XmlDictionaryWriterRepresents an abstract class that Windows Communication Foundation (WCF) derives from XmlWriter to do serialization and deserialization.
10XmlDocumentRepresents an XML document.
11XmlDocumentFragmentRepresents a lightweight object that is useful for tree insert operations.
12XmlDocumentTypeRepresents the document type declaration.
13XmlElementRepresents an element.
14XmlEntityRepresents an entity declaration, such as <!ENTITY... >.
15XmlEntityReferenceRepresents an entity reference node.
16XmlExceptionReturns detailed information about the last exception.
17XmlImplementationDefines the context for a set of XmlDocument objects.
18XmlLinkedNodeGets the node immediately preceding or following this node.
19XmlNodeRepresents a single node in the XML document.
20XmlNodeListRepresents an ordered collection of nodes.
21XmlNodeReaderRepresents a reader that provides fast, non-cached forward only access to XML data in an XmlNode.
22XmlNotationRepresents a notation declaration, such as <!NOTATION... >.
23XmlParserContextProvides all the context information required by the XmlReader to parse an XML fragment.
24XmlProcessingInstructionRepresents a processing instruction, which XML defines to keep processor-specific information in the text of the document.
25XmlQualifiedNameRepresents an XML qualified name.
26XmlReaderRepresents a reader that provides fast, noncached, forward-only access to XML data.
27XmlReaderSettingsSpecifies a set of features to support on the XmlReader object created by the Create method.
28XmlResolverResolves external XML resources named by a Uniform Resource Identifier (URI).
29XmlSecureResolverHelps to secure another implementation of XmlResolver by wrapping the XmlResolver object and restricting the resources that the underlying XmlResolver has access to.
30XmlSignificantWhitespaceRepresents white space between markup in a mixed content node or white space within an xml:space= 'preserve' scope. This is also referred to as significant white space.
31XmlTextRepresents the text content of an element or attribute.
32XmlTextReaderRepresents a reader that provides fast, non-cached, forward-only access to XML data.
33XmlTextWriterRepresents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations.
34XmlUrlResolverResolves external XML resources named by a Uniform Resource Identifier (URI).
35XmlWhitespaceRepresents white space in element content.
36XmlWriterRepresents a writer that provides a fast, non-cached, forward-only means of generating streams or files containing XML data.
37XmlWriterSettingsSpecifies a set of features to support on the XmlWriter object created by the XmlWriter.Create method.

XML Parser APIs

The two most basic and broadly used APIs to XML data are the SAX and DOM interfaces.
  • Simple API for XML (SAX) : Here you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from disk, and the entire file is never stored in memory.
  • Document Object Model (DOM) API : This is World Wide Web Consortium recommendation wherein the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document.
SAX obviously can't process information as fast as DOM can when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on a lot of small files.
SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other there is no reason why you can't use them both for large projects.
For all our XML code examples, let's use a simple XML file movies.xml as an input:
<?xml version="1.0"?>

<collection shelf="New Arrivals">
<movie title="Enemy Behind">
   <type>War, Thriller</type>
   <format>DVD</format>
   <year>2003</year>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Talk about a US-Japan war</description>
</movie>
<movie title="Transformers">
   <type>Anime, Science Fiction</type>
   <format>DVD</format>
   <year>1989</year>
   <rating>R</rating>
   <stars>8</stars>
   <description>A schientific fiction</description>
</movie>
   <movie title="Trigun">
   <type>Anime, Action</type>
   <format>DVD</format>
   <episodes>4</episodes>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Vash the Stampede!</description>
</movie>
<movie title="Ishtar">
   <type>Comedy</type>
   <format>VHS</format>
   <rating>PG</rating>
   <stars>2</stars>
   <description>Viewable boredom</description>
</movie>
</collection>

Parsing XML with SAX API

In SAX model, you use the XmlReader and XmlWriter classes to work with the XML data.
The XmlReader class is used to read XML data in a fast, forward-only and non-cached manner. It reads an XML document or a stream.

Example 1

This example demonstrates reading XML data from the file movies.xml.
Take the following steps:
  1. Add the movies.xml file in the bin\Debug folder of your application.
  2. Import the System.Xml namespace in Form1.vb file.
  3. Add a label in the form and change its text to 'Movies Galore'.
  4. Add three list boxes and three buttons to show the title, type and description of a movie from the xml file.
  5. Add the following code using the code editor window.
Imports System.Xml
Public Class Form1

   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      ' Set the caption bar text of the form.   
      Me.Text = "only4programmers.blogspot.com"
   End Sub
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      ListBox1().Items.Clear()
      Dim xr As XmlReader = XmlReader.Create("movies.xml")
      Do While xr.Read()
          If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "movie" Then
              ListBox1.Items.Add(xr.GetAttribute(0))
          End If
      Loop
   End Sub
   Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
      ListBox2().Items.Clear()
      Dim xr As XmlReader = XmlReader.Create("movies.xml")
      Do While xr.Read()
          If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "type" Then
              ListBox2.Items.Add(xr.ReadElementString)
          Else
              xr.Read()
          End If
      Loop
   End Sub
   Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
      ListBox3().Items.Clear()
      Dim xr As XmlReader = XmlReader.Create("movies.xml")
      Do While xr.Read()
          If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "description" Then
              ListBox3.Items.Add(xr.ReadElementString)
          Else
              xr.Read()
          End If
      Loop
   End Sub
End Class
Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the buttons would display, title, type and description of the movies from the file.
VB.Net XML Processing Example 1
The XmlWriter class is used to write XML data into a stream, a file or a TextWriter object. It also works in a forward-only, non-cached manner.

Example 2

Let us create an XML file by adding some data at runtime. Take the following steps:
  1. Add a WebBrowser control and a button control in the form.
  2. Change the Text property of the button to Show Authors File.
  3. Add the following code in the code editor.
Imports System.Xml
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      ' Set the caption bar text of the form.   
      Me.Text = "only4programmers.blogspot.com"   End Sub
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      Dim xws As XmlWriterSettings = New XmlWriterSettings()
      xws.Indent = True
      xws.NewLineOnAttributes = True
      Dim xw As XmlWriter = XmlWriter.Create("authors.xml", xws)
      xw.WriteStartDocument()
      xw.WriteStartElement("Authors")
      xw.WriteStartElement("author")
      xw.WriteAttributeString("code", "1")
      xw.WriteElementString("fname", "Zara")
      xw.WriteElementString("lname", "Ali")
      xw.WriteEndElement()
      xw.WriteStartElement("author")
      xw.WriteAttributeString("code", "2")
      xw.WriteElementString("fname", "Priya")
      xw.WriteElementString("lname", "Sharma")
      xw.WriteEndElement()
      xw.WriteStartElement("author")
      xw.WriteAttributeString("code", "3")
      xw.WriteElementString("fname", "Anshuman")
      xw.WriteElementString("lname", "Mohan")
      xw.WriteEndElement()
      xw.WriteStartElement("author")
      xw.WriteAttributeString("code", "4")
      xw.WriteElementString("fname", "Bibhuti")
      xw.WriteElementString("lname", "Banerjee")
      xw.WriteEndElement()
      xw.WriteStartElement("author")
      xw.WriteAttributeString("code", "5")
      xw.WriteElementString("fname", "Riyan")
      xw.WriteElementString("lname", "Sengupta")
      xw.WriteEndElement()
      xw.WriteEndElement()
      xw.WriteEndDocument()
      xw.Flush()
      xw.Close()
      WebBrowser1.Url = New Uri(AppDomain.CurrentDomain.BaseDirectory + "authors.xml")
   End Sub
End Class
Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the Show Author File would display the newly created authors.xml file on the web browser.
VB.Net XML Processing Example 2

Parsing XML with DOM API

According to the Document Object Model (DOM), an XML document consists of nodes and attributes of the nodes. The XmlDocument class is used to implement the XML DOM parser of the .Net Framework. It also allows you to modify an existing XML document by inserting, deleting or updating data in the document.
Following are some of the commonly used methods of the XmlDocument class:
S.NMethod Name & Description
1AppendChild
Adds the specified node to the end of the list of child nodes, of this node.
2CreateAttribute(String)
Creates an XmlAttribute with the specified Name.
3CreateComment
Creates an XmlComment containing the specified data.
4CreateDefaultAttribute
Creates a default attribute with the specified prefix, local name and namespace URI.
5CreateElement(String)
Creates an element with the specified name.
6CreateNode(String, String, String)
Creates an XmlNode with the specified node type, Name, and NamespaceURI.
7CreateNode(XmlNodeType, String, String)
Creates an XmlNode with the specified XmlNodeType, Name, and NamespaceURI.
8CreateNode(XmlNodeType, String, String, String)
Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI.
9CreateProcessingInstruction
Creates an XmlProcessingInstruction with the specified name and data.
10CreateSignificantWhitespace
Creates an XmlSignificantWhitespace node.
11CreateTextNode
Creates an XmlText with the specified text.
12CreateWhitespace
Creates an XmlWhitespace node.
13CreateXmlDeclaration
Creates an XmlDeclaration node with the specified values.
14GetElementById
Gets the XmlElement with the specified ID.
15GetElementsByTagName(String)
Returns an XmlNodeList containing a list of all descendant elements that match the specified Name.
16GetElementsByTagName(String, String)
Returns an XmlNodeList containing a list of all descendant elements that match the specified LocalName and NamespaceURI.
17InsertAfter
Inserts the specified node immediately after the specified reference node.
18InsertBefore
Inserts the specified node immediately before the specified reference node.
19Load(Stream)
Loads the XML document from the specified stream.
20Load(String)
Loads the XML document from the specified URL.
21Load(TextReader)
Loads the XML document from the specified TextReader.
22Load(XmlReader)
Loads the XML document from the specified XmlReader.
23LoadXml
Loads the XML document from the specified string.
24PrependChild
Adds the specified node to the beginning of the list of child nodes for this node.
25ReadNode
Creates an XmlNode object based on the information in the XmlReader. The reader must be positioned on a node or attribute.
26RemoveAll
Removes all the child nodes and/or attributes of the current node.
27RemoveChild
Removes specified child node.
28ReplaceChild
Replaces the child node oldChild with newChild node.
29Save(Stream)
Saves the XML document to the specified stream.
30Save(String)
Saves the XML document to the specified file.
31Save(TextWriter)
Saves the XML document to the specified TextWriter.
32Save(XmlWriter)
Saves the XML document to the specified XmlWriter.

Example 3

In this example, let us insert some new nodes in the xml document authors.xml and then show all the authors' first names in a list box.
Take the following steps:
  • Add the authors.xml file in the bin/Debug folder of your application( it should be there if you have tried the last example)
  • Import the System.Xml namespace
  • Add a list box and a button control in the form and set the text property of the button control to Show Authors.
  • Add the following code using the code editor.
Imports System.Xml
Public Class Form1
   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      ' Set the caption bar text of the form.   
      Me.Text = "only4programmers.blogspot.com"   End Sub
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      ListBox1.Items.Clear()
      Dim xd As XmlDocument = New XmlDocument()
      xd.Load("authors.xml")
      Dim newAuthor As XmlElement = xd.CreateElement("author")
      newAuthor.SetAttribute("code", "6")
      Dim fn As XmlElement = xd.CreateElement("fname")
      fn.InnerText = "Bikram"
      newAuthor.AppendChild(fn)
      Dim ln As XmlElement = xd.CreateElement("lname")
      ln.InnerText = "Seth"
      newAuthor.AppendChild(ln)
      xd.DocumentElement.AppendChild(newAuthor)
      Dim tr As XmlTextWriter = New XmlTextWriter("movies.xml", Nothing)
      tr.Formatting = Formatting.Indented
      xd.WriteContentTo(tr)
      tr.Close()
      Dim nl As XmlNodeList = xd.GetElementsByTagName("fname")
      For Each node As XmlNode In nl
          ListBox1.Items.Add(node.InnerText)
      Next node
   End Sub
End Class
Execute and run the above code using Start button available at the Microsoft Visual Studio tool bar. Clicking on the Show Author button would display the first names of all the authors including the one we have added at runtime.
VB.Net XML Processing Example 3

VB.Net - Web Programming

A dynamic web application consists of either or both of the following two types of programs:
  • Server-side scripting - these are programs executed on a web server, written using server-side scripting languages like ASP (Active Server Pages) or JSP (Java Server Pages).
  • Client-side scripting - these are programs executed on the browser, written using scripting languages like JavaScript, VBScript etc.
ASP.Net is the .Net version of ASP, introduced by Microsoft, for creating dynamic web pages by using server-side scripts. ASP.Net applications are compiled codes, written using the extensible and reusable components or objects present in .Net framework. These codes can use the entire hierarchy of classes in .Net framework.
The ASP.Net application codes could be written in either of the following languages:
  • Visual Basic .Net
  • C#
  • Jscript
  • J#
In this chapter, we will give a very brief introduction to writing ASP.Net applications using VB.Net. For detailed discussion, please consult the ASP.Net Tutorial.

ASP.Net Built-in Objects

ASP.Net has some built-in objects that run on a web server. These objects have methods, properties and collections that are used in application development.
The following table lists the ASP.Net built-in objects with a brief description:
ObjectDescription
ApplicationDescribes the methods, properties, and collections of the object that stores information related to the entire Web application, including variables and objects that exist for the lifetime of the application.
You use this object to store and retrieve information to be shared among all user of an application. For example, you can use an Application object to create an e-commerce page.
RequestDescribes the methods, properties, and collections of the object that stores information related to the HTTP request. This includes forms, cookies, server variables, and certificate data.
You use this object to access the information sent in a request from a browser to the server. For example, you can use a Request object to access information entered by a user in an HTML form.
ResponseDescribes the methods, properties, and collections of the object that stores information related to the server's response. This includes displaying content, manipulating headers, setting locales, and redirecting requests.
You use this object to send information to the browser. For example, you use a Response object to send output from your scripts to a browser.
ServerDescribes the methods and properties of the object that provides methods for various server tasks. With these methods you can execute code, get error conditions, encode text strings, create objects for use by the Web page, and map physical paths.
You use this object to access various utility functions on the server. For example, you may use the Server object to set a time out for a script.
SessionDescribes the methods, properties, and collections of the object that stores information related to the user's session, including variables and objects that exist for the lifetime of the session.
You use this object to store and retrieve information about particular user sessions. For example, you can use Session object to keep information about the user and his preference and keep track of pending operations.

ASP.Net Programming Model

ASP.Net provides two types of programming models:
  • Web Forms - this enables you to create the user interface and the application logic that would be applied to various components of the user interface.
  • WCF Services - this enables you to remote access some server-side functionalities.
For this chapter, you need to use Visual Studio Web Developer, which is free. The IDE is almost same as you have already used for creating the Windows Applications.
VS Web Developer IDE

Web Forms

Web forms consists of:
  • User interface
  • Application logic
User interface consists of static HTML, or XML elements and ASP.Net server controls. When you create a web application, HTML or XML elements and server controls are stored in a file with .aspx extension. This file is also called the page file.
The application logic consists of code applied to the user interface elements in the page. You write this code in any of .Net language like, VB.Net, or C#.
The following figure shows a Web Form in Design view:
Web Form

Example

Let us create a new web site with a web form, which will show the current date and time, when a user clicks a button. Take the following steps:
  1. Select File -> New -> Web Site. The New Web Site Dialog Box appears.
    Web Form Example
  2. Select the ASP.Net Empty Web Site templates. Type a name for the web site and select a location for saving the files.
  3. You need to add a Default page to the site. Right click the web site name in the Solution Explorer and select Add New Item option from the context menu. The Add New Item dialog box is displayed:
    Web Form Example
  4. Select Web Form option and provide a name for the default page. We have kept it as Default.aspx. Click the Add button.
  5. The Default page is shown in Source view
    Web Form Example
  6. Set the title for the Default web page by adding a value to the
  7. To add controls on the web page, go to the design view. Add three labels, a text box and a button on the form.
    Web Form Example
  8. Double-click the button and add the following code to the Click event of the button:
Protected Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
   Label2.Visible = True
   Label2.Text = "Welcome to Tutorials Point: " + TextBox1.Text
   Label3.Text = "You visited us at: " + DateTime.Now.ToString()
End Sub
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, the following page opens in the browser:
Web Form Example
Enter your name and click on the Submit button:
Web Form Example

Web Services

A web service is a web application which is basically a class consisting of methods that could be used by other applications. It also follows a code-behind architecture like the ASP.Net web pages, although it does not have an user interface.
The previous versions of .Net Framework used this concept of ASP.Net Web Service, which had .asmx file extension. However, from .Net Framework 4.0 onwards, the Windows Communication Foundation (WCF) technology has evolved as the new successor of Web Services, .Net Remoting and some other related technologies. It has rather clubbed all these technologies together. In the next section, we will provide a brief introduction to Windows Communication Foundation(WCF).
If you are using previous versions of .Net Framework, you can still create traditional web services. Please consult ASP.Net - Web Services tutorial for detailed description.

Windows Communication Foundation

Windows Communication Foundation or WCF provides an API for creating distributed service oriented applications, known as WCF Services.
Like Web services, WCF services also enable communication between applications. However, unlike web services, the communication here is not limited to HTTP only. WCF can be configured to be used over HTTP, TCP, IPC, and Message Queues. Another strong point in favour of WCF is, it provides support for duplex communication, whereas with web services we could achieve simplex communication only.
From beginners' point of view, writing a WCF service is not altogether so different from writing a Web Service. To keep the things simple, we will see how to:
  • Create a WCF Service
  • Create a Service Contract and define the operations
  • Implement the contract
  • Test the Service
  • Utilize the Service

Example

To understand the concept let us create a simplistic service that will provide stock price information. The clients can query about the name and price of a stock based on the stock symbol. To keep this example simple, the values are hardcoded in a two-dimensional array. This service will have two methods:
  • GetPrice Method - it will return the price of a stock, based on the symbol provided.
  • GetName Method - it will return the name of the stock, based on the symbol provided.
Creating a WCF Service
Take the following steps:
  1. Open VS Express for Web 2012
  2. Select New Web Site to open the New Web Site dialog box.
  3. Select WCF Service template from list of templates:
    Creating a WCF Service
  4. Select File System from the Web location drop-down list.
  5. Provide a name and location for the WCF Service and click OK.
A new WCF Service is created.
Creating a Service Contract and Defining the Operations
A service contract defines the operation that a service performs. In the WCF Service application, you will find two files automatically created in the App_Code folder in the Solution Explorer
  • IService.vb - this will have the service contract; in simpler words, it will have the interface for the service, with the definitions of methods the service will provide, which you will implement in your service.
  • Service.vb - this will implement the service contract.
    WCF Service Example
Replace the code of the IService.vb file with the given code:
Public Interface IService
    <OperationContract()>
    Function GetPrice(ByVal symbol As String) As Double

    <OperationContract()>
    Function GetName(ByVal symbol As String) As String
End Interface
Implementing the Contract
In the Service.vb file, you will find a class named Service which will implement the Service Contract defined in the IService interface.
Replace the code of IService.vb with the following code:
' NOTE: You can use the "Rename" command on the context menu to change the class name "Service" in code, svc and config file together.
Public Class Service
   Implements IService
   Public Sub New()
   End Sub
   Dim stocks As String(,) =
   {
   {"RELIND", "Reliance Industries", "1060.15"},
   {"ICICI", "ICICI Bank", "911.55"},
   {"JSW", "JSW Steel", "1201.25"},
   {"WIPRO", "Wipro Limited", "1194.65"},
   {"SATYAM", "Satyam Computers", "91.10"}
   }

   Public Function GetPrice(ByVal symbol As String) As Double _
   Implements IService.GetPrice

      Dim i As Integer
      'it takes the symbol as parameter and returns price
      For i = 0 To i = stocks.GetLength(0) - 1

          If (String.Compare(symbol, stocks(i, 0)) = 0) Then
              Return Convert.ToDouble(stocks(i, 2))
          End If
      Next i
      Return 0
   End Function

   Public Function GetName(ByVal symbol As String) As String _
   Implements IService.GetName

      ' It takes the symbol as parameter and 
      ' returns name of the stock
      Dim i As Integer
      For i = 0 To i = stocks.GetLength(0) - 1

          If (String.Compare(symbol, stocks(i, 0)) = 0) Then
              Return stocks(i, 1)
          End If
      Next i
      Return "Stock Not Found"
   End Function
End Class
Testing the Service
To run the WCF Service, so created, select the Debug->Start Debugging option from the menu bar. The output would be:
WCF Service Testing
For testing the service operations, double click the name of the operation from the tree on the left pane. A new tab will appear on the right pane.
Enter the value of parameters in the Request area of the right pane and click the 'Invoke' button.
The following diagram displays the result of testing the GetPrice operation:
WCF Service Testing
The following diagram displays the result of testing the GetName operation:
WCF Service Testing
Utilizing the Service
Let us add a default page, a ASP.NET web form in the same solution from which we will be using the WCF Service we have just created.
Take the following steps:
  1. Right click on the solution name in the Solution Explorer and add a new web form to the solution. It will be named Default.aspx.
  2. Add two labels, a text box and a button on the form.
    WCF Service Utilization
  3. We need to add a service reference to the WCF service we just created. Right click the website in the Solution Explorer and select Add Service Reference option. This opens the Add Service Reference Dialog box.
  4. Enter the URL(location) of the Service in the Address text box and click the Go button. It creates a service reference with the default name ServiceReference1. Click the OK button.
    Add Service Reference
    Adding the reference does two jobs for your project:
    • Creates the Address and Binding for the service in the web.config file.
    • Creates a proxy class to access the service.
  5. Double click the Get Price button in the form, to enter the following code snippet on its Click event:
Partial Class _Default
   Inherits System.Web.UI.Page

   Protected Sub Button1_Click(sender As Object, e As EventArgs) _
   Handles Button1.Click
      Dim ser As ServiceReference1.ServiceClient = _ 
      New ServiceReference1.ServiceClient
      Label2.Text = ser.GetPrice(TextBox1.Text).ToString()
   End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, the following page opens in the browser:
WCF Service Utilization
Enter a symbol and click the Get Price button to get the hard-coded price:
WCF Service Utilization