Visual Language Programming (May-2017) Unit-IV

Question: – 8(a) what are the steps of saving and opening files in rich text box? Explain various file operations supported by VB?

Answer: – I looked at how to load and save plain text between a RichTextBox  and a txt file.   This time I want to look at a different case where text formatting has been applied to the content.   For the purposes of this sample I’m going to take a document that has been created in MS Word.  One of the many formats that both MS Word and WordPad support is RTF.   You can view and edit the RTF document in the RichTextBox.

The WPF Window

Here’s the markup to create the Window I’m using:

<Window x:Class=”RTFContent”

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

Title=”RTF Rich Content” Height=”450″ Width=”378″>

<Grid>

<Grid.RowDefinitions>

<RowDefinition Height=”55″ />

<RowDefinition Height=”224*” />

</Grid.RowDefinitions>

<StackPanel Margin=”12″ Name=”StackPanel1″ VerticalAlignment=”Top”

Orientation=”Horizontal”>

<Button Name=”btnLoad” Margin=”4″ Padding=”2″

Content=”Load RTF” Click=”btnLoad_Click” />

<Button Name=”btnSave” Margin=”24,4″ Padding=”2″

Content=”Save RTF” Click=”btnSave_Click” />

<Button Height=”23″ Name=”btnClear” Click=”btnClear_Click”

Content=”Clear” Width=”75″ />

</StackPanel>

<RichTextBox Grid.Row=”1″ Margin=”7″ Name=”RichTextBox1″ Background=”#FFEDEAEA”>

<FlowDocument>

<Paragraph>RichTextBox</Paragraph>

</FlowDocument>

</RichTextBox>

</Grid>

</Window>

Loading RTF File Content into the RichTextBox

Here is the code needed for loading the content:

1 Imports System.IO

2

3 Partial Public Class RTFContent

4

5     Dim DemoRTFFile As String = “C:\Temp\RTFDocument.rtf”

6     Dim fs As FileStream

7

8     Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

9         ‘  Load RTB with text from RTF file

10         If File.Exists(DemoRTFFile) Then

11             fs = New FileStream(DemoRTFFile, FileMode.Open, FileAccess.Read)

12             Using fs

13                 ‘ Create a TextRange that comprises the start and end points of the RichTextBox text

14                 Dim RTBText As New TextRange(RichTextBox1.Document.ContentStart, RichTextBox1.Document.ContentEnd)

15                 RTBText.Load(fs, DataFormats.Rtf)

16             End Using

17         End If

18     End Sub

You’ll see that I’ve used an Imports statement for the System.IO namespace and that I’ve set up a couple of variables for the file I want to load/edit/save and for a FileStream.  The rest of the code works as follows:

  • In the click event of btnLoad, I first check that the file does exist to save an embarrassing runtime crash.
  • A FileStream is then used to access the file in preparation for reading it.
  • I’ve used the ‘Using’ statement on the next line, as this is a useful feature that saves me having to remember to close and dispose of resources each time.
  • Line 14 might look a bit strange.  Bearing in mind that there is no content yet, it might seem weird to be creating a range that spans the content start to the content end.  However this is just a way of identifying the boundaries of the object that is going to hold the content.
  • Line 15 uses the Load method of the TextRange class.   It takes a FileStream and a Data Format as its parameters.
  • Once this code has completed, all the rich content of the file will be contained in the RichTextBox.

The result, with the particular file I used, looks like this:

Editing the Content

I can make changes to this document.  If you have used the Windows Forms RichTextBox much in the past, you’ll be impressed by the additional features available by default in the WPF version.

WPF includes a feature known as Commands that enable particular tasks to be carried out as a result of various user actions.    In the case of the RichTextBox, several commands are built in to its default feature set.  These include the following common text editing tasks:

  • Copy
  • Cut
  • Paste
  • Bold
  • Italic
  • Underline
  • Undo

There are several more, not listed above.  I will be writing an item that takes this feature further, but for now you know you can use the familiar shortcut key combinations to implement the tasks – Ctrl & C for Copy, and so on.

Saving Content to an RTF File

Once you’ve made any changes you want, you can then save the edited version back to file.    Saving is almost exactly the same procedure that I used in the earlier plain text (.txt) file save :

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSave.Click

If File.Exists(DemoRTFFile) Then

fs = New FileStream(DemoRTFFile, FileMode.Open, FileAccess.Write)

Using fs

Dim RTBText As New TextRange(RichTextBox1.Document.ContentStart, RichTextBox1.Document.ContentEnd)

RTBText.Save(fs, DataFormats.Rtf)

End Using

End If

End Sub

You’ll see that the key is the now familiar TextRange object that represents all the content we are interested in.     The Save method of the TextRange this time uses the Rtf data format.

Summary

Apart from some subtle differences, the overall approach to using the RTF format is very similar to that for plain text.   The built-in commands I’ve listed above will work with both formats in the RichTextBox.  The difference is that when you save back to a plain text file you will lose any of the bold, italic, underline features.   In the next blog, I’ll pull the two strands together and look at loading a txt file, making some formatting changes and saving as rich text.  At the same time, we’ll look at some further benefits of using commands in the RichTextBox.




Question: – 8(b) Differentiate DAO, RDO and ADO by discussing their important properties.

Answer: – Data Access
Data access is a feature of Visual Basic that allows you to access and manipulate any database from Visual Basic. The database may be either MS-Access database or FoxPro database or it may also be any of the relational databases such as Oracle. You can develop applications in Visual Basic that can access data in a database. The database may be on the same machine as the application or it may be on database server that is far away from Visual Basic application. Whatever may be the case, you can access and manipulate the data using applications written in Visual Basic.

The following are the various ways of access database.

Data Access Objects (DAO)
This is an object model that has a collection of objects using which you can access a database. This model gives complete control on the database. This model uses Jet Engine, which is the native database engine used by Visual Basic and MS-Access. This was the first model to be used in Visual Basic. Though it is possible to access any database using this, it is particularly suitable for MS-Access database and not suitable for ODBC data sources such as Oracle and MS-SQL Server. So, Microsoft later introduced RDO.

Remote Data Objects (RDO)
These objects are only used to access ODBC data sources such as Oracle. These objects access databases that are on remote machine (database server). This object model has less number of objects compared with DAO and more suitable for accessing remote databases. We will discuss more about RDOs in chapter 18.

ActiveX Data Objects (ADO)
Microsoft has introduced a new object model called ActiveX Data Objects (ADO), which is based on ActiveX technology, for the first time in Visual Basic 6.0. This object model has very few objects and it is based on OLE DB interface. OLE DB interface is a new interface (replacing ODBC and others), through which you can access data of all formats in the same manner. ADO uses OLE DB providers to access the data. That means each database is accessed through OLE DB provider. And ADO provides the programming framework to access OLE DB. ADO is also much easier to deal with.

Differentiate DAO, RDO and ADO:-

DAO: Database Access Object came out with Visual Basic 4 today it’s recommended you use ADO instead for, among other things, performance gains in most of your database operations. :-). First to come out, and slowest..correlation? I think so ;-).

RDO: Remote Database Object came out with Visual Basic 5 It was supposed to be designed to allow remote connections to other PC’s database and database servers, which it did, however there was a performance cost involved (in most projects I’ve worked with). However it did do the job. But ADO is faster at it :-).

ADO: ActiveX Database Object. The best available to VB (aside direct ODBC which is faster) but this object hierarchy is the fastest out there and the safest for the data as well. At least it’s what I’ve noticed. Of course other server setups might report differently ;-). but in my experience, ADO is the best of these 3 technologies.




Question: – 9(a) Explain the steps of creating and using ActiveX document with an example.
Answer: – ActiveX Document Overview

ActiveX documents enable you to develop Visual Basic 5 applications that can be used in container applications, such as Microsoft Internet Explorer or Microsoft Outlook. An ActiveX document is not a traditional standard word processing document, such as a Microsoft Word document or a Lotus Word Pro document. Instead, think of an ActiveX document as a Visual Basic Internet application. ActiveX documents are designed and created in the Visual Basic 5 development environment and can use ActiveX controls and forms.

You might be confused by the word document in ActiveX document instead of application. Step back for a moment and think about a Microsoft Excel spreadsheet used to compute a tax return. The spreadsheet contains the formulas and data required to generate a tax return. The spreadsheet offers application-like functionality because it can be used to perform tasks such as computing tax returns. The spreadsheet alone is not an application, however; it requires the application Microsoft Excel to create and use the spreadsheet. You can give your friends a copy of the tax return spreadsheet, and they can do their taxes as long as they have Microsoft Excel. One other point: The Excel spreadsheet also can be viewed in other applications that act as containers–for example, a Visual Basic application using the OLE2 custom control. An ActiveX document created in Visual Basic 5 is similar to the Excel spreadsheet. By itself, the ActiveX document is not an application. With a valid container application and ActiveX component, the ActiveX document performs like an application.

When and Why to Use ActiveX Documents

ActiveX documents are a really cool Visual Basic 5 feature, but those of you who program for a living and want to try out this new technology will ultimately face the manager afraid of technology or the internal software police who must study every technology to death (until it’s old technology) and officially approve it before anyone is allowed to use it. How do you justify using ActiveX documents? I believe that the strength of ActiveX documents will prove to be in an intranet environment as opposed to an Internet environment. In an intranet environment, ActiveX documents enable you to perform these tasks:

  • Viewing and modifying corporate databases using ODBC, DAO, RDO, and data-bound ActiveX controls
  • Providing the user interface tier in a three-tier architecture application

If you are thinking that these tasks are identical to the tasks you currently use Visual Basic and other development tools to perform, you are correct. But the advantage that ActiveX documents offer over current development tools is the buzzword of the late 1990s: lower-cost ownership. ActiveX documents are easier to install and maintain than existing client/server applications, which results in a lower cost of ownership. ActiveX documents install themselves from a central code base, for example. No information system personnel must go from PC to PC (or use software such as Microsoft SMS) to perform software installations. When a new employee starts work, instead of ensuring that he has all the proper applications, you can have them access a URL, and the application installs itself. When the ActiveX document requires a revision, you just have to change the software in one location. No need to worry about upgrading a user to a newer version or that a user is working with an older version. When a user accesses the revision via a Web browser, the ActiveX document automatically upgrades itself.

The ease of software distribution via ActiveX documents makes ActiveX documents very attractive in an intranet environment. If your company executes all your applications from a central directory on a LAN instead of installing them on users’ PCs, you probably are thinking that ActiveX documents will not cut your cost of ownership because your applications are installed in only one location anyway. In this type of environment, ActiveX documents offer better performance because running applications from a LAN is always slower than executing them from a client PC. Also, you have the added benefit of no software distribution requirements. And even though you might have all your applications installed on a LAN, IS personnel are often required to run minimum setup and installation procedures on client machines when giving them access to new applications.

ActiveX documents are not restricted to the intranet and can be used as well on the Internet. You might want to use an ActiveX document when you find HTML and VBScript lacking in functionality for a complex client form. You might prefer to use ActiveX documents instead of a standard HTML page because of the powerful features of Visual Basic 5’s design environment and integrated debugger compared to the current HTML and scripting environment.

NOTE: You cannot use ActiveX documents over the Internet to interact with corporate databases using standard Visual Basic 5 controls and ODBC (which can be performed in an intranet). Microsoft has introduced a technology called Advanced Data Connector (ADC), which enables you to use bound data connections to a corporate database via the Internet (HTTP). ADC is covered in Chapter 23, “MS SQL Server Internet Capabilities.”

Creating an ActiveX Document

ActiveX documents are easy to build and test. This section will give you a detailed walkthrough of the steps required to create an ActiveX document. You will learn about the primary object that makes up an ActiveX document: the UserDocument object.

TIP: You will get the most out of the next section if you follow along and perform each step in Visual Basic 5. The database application created in this section is not included on the CD-ROM that accompanies this book.

The UserDocument

Before going over the steps required to create an ActiveX document, you should understand the primary object used to create ActiveX documents: the UserDocument. The UserDocument is the equivalent of a Visual Basic form in a standard client/server project. Like a standard Visual Basic form, the UserDocument object has events, properties, methods, and ActiveX controls (except the OLE2 control) that can be placed on the UserDocument object.

Steps to Create an ActiveX Document

To create an ActiveX document, follow these steps:

  1. Create a new Visual Basic project by selecting File|New Project from the Visual Basic menu. The Visual Basic New Project dialog box, shown in Figure 15.2, appears. Double-click the ActiveX Document DLL icon in the New Project dialog box.

NOTE:An ActiveX document’s associated ActiveX components can be created as DLLs or EXEs. You will learn more about the differences between an ActiveX DLL and EXE in Chapter 22, “Writing Server-Side Applications with VB 5 ActiveX Components.” When developing ActiveX documents, it is important for you to know that the ActiveX DLL will provide you with the best performance. One drawback of an ActiveX DLL is that when you use Internet Explorer as the ActiveX document container, the ActiveX document using an ActiveX DLL cannot display any modeless forms (all forms must be modal). An ActiveX document using an EXE component can display modeless forms in Internet Explorer.

The new project contains a single UserDocument object called UserDocument1.

  1. Double-click UserDocument1in the Visual Basic Project box. UserDocument1 appears, as shown in Figure 15.3. Notice that the UserDocument object resembles a standard Visual Basic form. Like a standard Visual Basic form, you can set UserDocument properties by using the standard Properties dialog box.
  2. Add the following ActiveX controls to UserDocument1: a data control and three textboxes. UserDocument1should look similar to Figure 15.4.4. Set the data control’s DatabaseName property to the Microsoft Access database that comes with Visual Basic 5, Biblio.mdb. Biblio.mdb is located in the directory in which Visual Basic 5 is installed.
  3. Set the data control’s RecordSourceproperty to Authors (the Authors table in the Biblio.mdb database).6. Set the DataSource property on all three textbox controls to Data1.7. Set the textbox control’s DataField property to Au_Id for text1, Author for text2, and Year Born for text3.

You now have constructed an ActiveX document.




Question: – 9(b) Explain steps of database connectivity with DAO. How a record in record set is updated and deleted.

Answer: – Data Access Object (DAO):

The Microsoft Data Access Object (DAO) is an approach of database programming which is similar to ODBC. In this approach instead of using CRecordset and CDatabase, we use CDaoRecordset and CDaoDatabase.

Features of DAO are –

  1. DAO is a set of COM interface. These interfaces are set of pure virtual functions.
  2. The required COM model is located in DAO350.DLL.
  3. It has support for Jet Database engine.
  4. The Visual Basic Application (VBA) Automation controller can use DAO object and can make use of the DAO Library.
  5. The MFC classes are used to implement the concept of DAO. The MFC database classes for DAO are –
  •  CDaoDatabase: An interface for using database.
  •  CDaoWorkspace: An interface for managing the single user connectivity with the database.
  • CDaoRecordset: An interface for accessing records.
  • CDaoTableDef: An interface for manipulating the base table.
  • CDaoQueryDef: An interface used to execute queries on database.

Types of Database that can be opened with DAO-

  1. Access Database
  2. ODBC Database Source
  3. ISAM-Type Database Source
  4. External Tables

Recordset Object

·         The Recordset object is an important concept.  When we set the RecordSource property (either select a table from the database or form a virtual table via a query), the data control (using the Jet engine) retrieves the needed records and places them in the Recordset object for our use.  We will see that this object has its own properties and methods for our use.

 

·         There are three types of recordsets, established via the RecordsetType property:

Table                         Representation of a native database table (not formed via a query).  You can add, change, or delete records.

Dynaset                    The default type, a Dynaset is formed as the result of a database query.  You can add, change, or delete records from the underlying table(s).  This is the most flexible Recordset type.

Snapshot                  A static copy of records that cannot be updated.  Used if you are just viewing or searching a database table.

Add new record to DAO Recordset

To add a new record a recordset has to be be available. The adding of a record requires:

  1. AddNew: Start inserting a record
  2. Set the values of the fields of the record being created
  3. Update: Finalize the adding

Dim rstCategories As RecordsetSet

rstCategories = CurrentDb.OpenRecordset(Name:=”Categories”, Type:=RecordsetTypeEnum.dbOpenDynaset)

With rstCategories

.AddNew

![Category Name] = “Better software”

!Description = “5 star rated”

.Update

End With

Notes

  1. If a fieldname contains a space you must put it between square brackets.
  2. If you add a record to a recordset of type dynaset, the new record will appears at the end of the Recordset, regardless how the Recordset is sorted. To force the new record to appear in its properly sorted position, you can use the Requery method.
Read values from record

To read the field values from a record you first have to make it the current. Subsequently the value of a field can either be obtained using the .Fieldsmethod or shorter equivalents

With rstCategories

lng = !CategoryID

str1 = ![Category Name]

str2 = .Fields(“Description”)

End With

Edit a record in a DAO Recordset

To edit a record in a recordset it first has to be made the current record. After that, changing the values of fields of a record requires:

  1. Edit: Indicate the current record is to be edited
  2. Set the values of the fields of the record being created
  3. Update: Finalize the adding

With rstCategories

.Edit    ![Category Name] = “Best software”

.Update

End With

Move through a DAO Recordset – make record current

Moving through a recordset changes what is the ‘current’ record.

Find a record

The most direct way to move to a specific record is using the FindFirst method.

With rstCategories

.FindFirst “CategoryName = ” & “‘better software'”

If .NoMatch Then

End If

End With

For best performance, the criteria should be in either the form “field = value” where field is an indexed field in the underlying base table, or “field LIKEprefix” where field is an indexed field in the underlying base table and prefix is a prefix search string (for example, “ART*” ).

After having found the record you can read or change the record’s field values as explained under Edit a record in a DAO Recordset.

Processing all records

Use the Move methods to move from record to record without applying a condition. When you open a Recordset, the first record is current. Using any of the Move methods (MoveFirst, MoveLast, MoveNext, or MovePrevious) causes an error if the recordset has no records, so you should test this condition before using a Move method. If, as usually is the case, you use the MoveNext in a loop as below this test is done with .EOF.

Do While Not rst.EOF

rst.Move

NextLoop

Delete a record
If you want to delete a record you first have to move to it (see above) making it the current. After that simply
rstCategories.Delete
When you use the Delete method, the Microsoft Access database engine immediately deletes the current record without any warning or prompting. Deleting a record does not automatically cause the next record to become the current record; to move to the next record you must use the MoveNext method.



This article is contributed by Tarun Jangra. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Author: Susheel kumar

Leave a Reply

Your email address will not be published. Required fields are marked *