Wednesday, May 19, 2010

free download visual basic 6 black book including source code


Saturday, May 15, 2010

Blogger SEO Tips


Blogging has become passion and way to earn money for living for many people. To host own blog will take money and efforts to maintain because of the hosting payments, managing stress and downtime of the server that concerns most of the blogger when thinking to host own blogs. For this reason many choose http://www.blogger.com to host personals blogs as it allows you host as many blogs as you wish.

You can host many blogs as you required with free of cost, but also required to be optimized for each search engines when looking for search engines rankings.

Blogger has no provision to add meta tags easily to your blog. Hence it has to be done manually and include the necessary tags to your blog. If you have ever tried to include those tags you might have experienced there is no easy way to do that. For this reason I have decided to discuss few tips and how to optimize blog for search engines.

Title

The title of the blog is most important for search engines and it lets the search engines to know what your blog is about. Include the following code to your blogger blog in head and title tag.

head - b:include data="blog" name="all-head-content" title - data:blog.pageTitle

Description

The description of the blog should be included in Meta tag. The description should give the information to search engines in a meaningful way. It should be framed in complete sentence. Include the following code in between opening and closing of b:if

b:if cond='data:blog.url = ="http://yourblogurl.blogspot.com"' meta content='blog description' name='description'

Keywords

Your Meta tag of the blog also specifies keywords of your blog. The keyword in the Meta tag tells the search engines about what your blog is. Include the following code in between opening and closing of b:if

b:if cond='data:blog.url = ="http://yourblogurl.blogspot.com"' meta content='blog keywords' name='keywords'

After performing on page optimization, it is important to generate back links to your blog. Generating back links will drive much traffic to your blog. Do the following steps to generate back links.

Add your blog to blog directories and RSS directories

Frequently update your blog and use pinging service to ping social networking and social bookmarking sites. Comments should be open but delete unrelated or spam comments. Doing above will generate traffic to your web page.

Wednesday, May 12, 2010

excellent and rare tips on Google Adsesne


Previously I have wrote many articles on Google Adsense. Here I will describe the easiest way to attract advertisers from across the globe to your blog or website. To get approved for Google Adsense see my previous post adsense approval and information. Once you are approved by Google Adsense it will place contextual ads linking to products likely to appeal to the readers. Each time a reader clicks a link, the advertiser pays Google a small fee, and Google splits that with you.

Many webmasters are earning lot of money from it and many are asking - How to Make Money with Google Adsense?. Here I have some more tips and tricks to increase revenue from Google Adsense program.

1. Follow the rules mentioned in Adsense Policies. You will always earn more revenue from Adsense.

2. A common mistake always webmasters do that is asking visitors or relatives to click their Google ads. It will ban you for this program forever. Don’t label Google ads with text other than "sponsored links" or "advertisements".

3. Never modify the Google Adsense HTML code.

4. Google is more than smarter as we think so "don't click on your own ads". Don’t reload your page excessively for testing the layout of website and google ads.

5. Don’t place ads in pop-up windows, error pages or even empty pages.

6. For Long articles, CTR improves if ads are placed somewhere in middle of the content (see how to post ads in middle of the content). Visitors read the long content and then they are looking for more resources.

7. For short article, CTR is best when ads are placed just above the content.

8. For Low CTR pages, try changing titles or adding more content to better focused ads.

9. Use Text Ads instead of image Ads as users get more options. If you still want to display image ads, consider ad formats that support image ads. Choose 300x250 medium rectangle or the 160x600 wide skyscraper.

10. Blend your Google Ad unit well with your site theme because Google Ads without background color and border always perform better. Make the border color and background color same as your page background color.

11. The larger rectangle is the best paying adsense format (336x280). Google Adsense Publisher team also feels that the best formats are the wider ones. The ad formats that contain the widest individual ads. Try to use the 336x280 large rectangle, 300x250 medium rectangle or 160x600 wide skyscraper.

12. Try to put your ads above the main fold. Make sure that the ad unit with the highest CTR (Click Through Rate) is the first instance of the ad code that the appears in the HTML. Since the first ad unit is always filled before the rest, you want to make sure that ad unit is located in the best placement on your page.

13. Placing images next to ads or above ads does help in attracting user attention.

14. Blend Ad Links with other navigation links or place horizontal ad links at the top of your webpage. Adsense publishers are permitted to click on link unit topics on their web pages, provided that they do not click on any Google ads on the resulting page.

15. Try to put your ads on those regions where your website draws more user attention.

16. You can put up to 3 ad units on a page so try to put large skyscraper on the right navigation sidebar of your website because that area is close to the browser scrollbar. You can also add 2 adsense for search boxes, 1 add link unit and 1 referral button per product.

17. The first few lines of your content is most important factor for determining what ads are served on your webpage. That's the right place to put keywords in bold or header tags (eg h1, h2 etc).

18. Select the setting to open Google Adsense search box results in a new browser window, so you won't lose your visitors and it also help to increase the visit length. Click the open search results in a new browser window checkbox and this add target="google_window" to your form tag.

19. Don’t syndicate full content. If people can read everything from the newsreader window itself, why would they visit your website where your ads are is.

20. Block low paying advertisers with filters. Why to lose a visitor for single cents. Use Overtune or Google Adwords Keywords tool to discover keywords that are less popular with advertisers.

21. Use URL Channels to determine performance of individual pages. I recommend to use Google analytics, Statcounter to create a channel for each of the URL. You can even track Adsense Clicks with Analytics.

22. The Adsense for search Top Queries report show you what your users are looking for, by listing the 25 most common searches conducted through your Adsense for Search Boxes. Use this report to identify additional topics to add to your site, or to keep track of your most sought-after information. Focus and improve that content.

23. Use RSS to Email services like FeedBlitz, Rmail or Bloglet to let users subscribe to your blog by email.

Google don’t offer the best advise always so download adsense unload facts .

Monday, May 10, 2010

How to place ads inside posts or under posts title for higher CTR


Ads inside posts have a higher CTR (Click Through Rate), it mean you can increase your earning more. Wrapping code violates the adsense TOS. Here I will describe how to place the ads inside the post without violating the adsense TOS.

1. Login to your blogger account.

2. Go to Layout, Edit HTML and check the "Expand Widget Templates" Check box.

3. Find the following code

<data:post.body/>

(a) If you want to place the ads right under the posts title copy the following code before the above code line.

Do like this:

<b:if cond='data:blog.pageType == "item"'>
<b:if cond='data:post.includeAd'> <data:adEnd/>
<data:adCode/> <data:adStart/> </b:if>
</b:if>

<data:post.body/>

(b) If you want to place the ads at the end of your posts copy the following code after above code line.

Do like this:

<data:post.body/>

<b:if cond='data:blog.pageType == "item"'>
<b:if cond='data:post.includeAd'> <data:adEnd/>
<data:adCode/> <data:adStart/> </b:if>
</b:if>


If you get any problem then post comment

Sunday, May 9, 2010

How to add related post widget in blogger every post


How to add related post widget in blogger every post

This is the simple method to make your visitors stay long in your site. Add "Related Posts" at the end of every post in your blog. This increase the number of page views and who knows, it is also helpful for increasing the page rank of the blog. The "Related Post Widget" can be very handy because this can let your reader to know the similar type of post you have in your blog and it can also allow links to your other posts allowing google bots to read your previous or older posts.

Follow these steps:

1. Login to your "Blogger" with your user id and password.

2. Click on "Layout" of the blog.

3. Click on "Edit HTML"

(Note:- Before editing your HTML download your template for backup.)

4. Tick on "Expand Widget template".

5. Find "CTRL + F" the following code

<data:post.body/>

6. Download this text file. Click Here to Download

7. Copy the text code from the following file and paste it after the above code.

Example:

<data:post.body/>

Your code Here(copied from text file)

8. Save your template. Preview your post and check it if you are getting trouble then leave comment.

Saturday, May 8, 2010

Create read more button on blogger to show the selected content or text


In this article I will describe you about "Read More" option for blogger. Many of blogger still facing such type of problem and finally they decide to change the valuable template of blog only for "Read More" option.

A "Read More" button is very useful if you have blogger having long articles. Here you can select the amount of text from the beginning of the post to display as a teaser. Here I will show you how to design "Read More" button. You can use simple text link but better to try image type of stylish button.

1. First of all you need to create and button (image) to use as background for the button. You can create that image by "Ms. Paint", "Photoshop" or etc.

2. Sign up for the photobucket or google page creator.

3. Place this given code in template code

<b:if cond='data:blog.pageType != &quot;item&quot;'> <div id='read-more-button'><a class='read-more' expr:href='data:post.url'>Read more...</a></div></b:if>

Place the above code after following line:

<data:post.body/>

4. Add CSS code to customize the "Read More" button

#read-more-button {

background-color:white;

background-image:url(http://i998.photobucket.com/albums/af103/sankpur/readmore.png);

height:33px;

width:133px;

padding:2px 0 0 0;

background-repeat:no-repeat;

float:right;

}

a.read-more {

color:white;

font-size:18px;

color:white;

font-weight: normal;

margin:0 0 0 18px;

}

Replace" http://i998.photobucket.com/albums/af103/sankpur/readmore.png" URL with the link you've copied at Step 2(photobucket).

Above first code is to enable "Read More" button and the second code is to customize the text of the button. The height and width tags from the first part of the code are defining the size of the button, use the size of your image. The padding is the distance from the button and the objects around it. The first number is defining the top margin, the second number the right margin, the third is number the button, and the last number the left margin. The padding is defining the space between the text inside the button, the values are the same as the margin. Place this code right before this code:

]]></b:skin>

To show the only a select amount of text as a teaser from your content you will need to select the amount of text to show for each post separately. The content of the post is placed in a div but without the select part of the text. This display of that div is set to hidden so on the main page of the blog is visible just that part of the post what is not in that div. The full post is visible only on the post page. Code is given below

<b:if cond='data:blog.pageType == &quot;item&quot;'>
<style>#full-post{display:inline;}</style>
<b:else/>
<style>#full-post{display:none;}</style></b:if>

Place the above code right after the

<data:post.body/>

5. Save the template and now edit your posts in the following way

This is the first part of the post, the teaser (the part of text showing up on the main page of the blog) <div id="full-post"> This is the rest of the post. This part of the post if visible only on the page of the post. </div>

The red marked code snippets are the starting and the ending tags of the div called full post. Place these tags in each of you posts in the same way as example shown above.

Wednesday, May 5, 2010

tips to increase Your earning per click (EPC), click through rate (CTR) and dealing low, lack or less ad inventory on Bidvertiser


CTR or Click Through Rate is one way of measuring an online campaign's success. CTR is calculated by dividing the number of users who clicked on an advertisement unit on a page over the number of times the ad was delivered (impressions).

Example: If a banner ad had 100 impressions and one person clicked on it then the resulting CTR (Click Through Rate) would be 1 percent. A high CTR means that the advertisement campaign is successful because a lot of clicks with while having less impressions. This shows that your ads are very successful therefore resulting a lot of earning for you.

Bidvertiser is one the many advertising programs that webmasters use to make money online. It’s a CPC (Cost per Click) type of program or also known as PPC (Pay Per Click). Some webmasters are earning big amount from this program and many are still having problems making money from it.

Below is the main reason that most of the webmasters complain about Bidvertiser advertisements on their sites are

1. Low CTR (Click Through Rate)

2. Low EPC (Earning Per Click)

3. Low Advertisement Inventory

Here I will describe about its solutions to your Bidvertiser ads. Here are some cool tips to increase your ads CTR resulting to better earnings for you.

Low CTR (Click Through Rate)

Blend your Bidvertiser Ad unit well with your site's theme

Bidvertiser allows you to fully customize the look of your ad in terms of font, size, color etc so better to take advantage of this.

Before placing your Bidvertiser Ad unit to your website content make sure to blend it into your website theme perfectly with the color of your, links and background. The font and font size of your ad must be same as your content. This gives your ad unit a better feel for your readers.

If you are not able to blend it with your content then make sure to blend it with the colors of nearby elements in your webpage where you placed it. It makes the ads as naturally blended with the environment as possible.

We don't have to make the ad units overpower the color and font format of our theme because overpowering ads are less likely to be clicked because it looks annoying.

Place bidvertiser Ad unit on the banner or top fold of your web page.

Banner is the upper part of your web page that is first seen when someone visits your site. More exposure means that your ads are more likely to be clicked so avoid placing your Bidvertiser ad unit after the content or at the bottom of the page.

Mostly website readers don’t scroll down to bottom part of a web page unless what their reading is very interesting. Placing your ad unit on the top fold part of your site gives them enough exposure on the first page load without having to scroll down therefore increase the chances that it will be clicked.

If you are using blog for your site then place an ad unit below of your content's title is one of the best placement.

Allow the Display of Image Ads

Regular visitors of your site know the placements of your ad units on your site since they drop by regularly. Seeing the same text-based ad on same place again lowers it chance to get clicked since they are already know it is an advertisement.

To avoid this you can refresh an ad units look by approving the display of image and eBay ads. This way you can somehow change the feel of your ad unit and make it more interesting to click because it looks fresh and new.

To do this, you need to change your settings of your Bidvertiser "Preferences" and allow to "Display Image Ads" in your Bidvertiser Preferences. Also allow to "Display eBay Ads" as well.

Low EPC (Earning Per Click)

Manually Filter and approver your Advertisers

Automatic approval is not always a good idea because if approves every bidder on your site, a mix of high and low bidders. More often, there are lots of bidders that offer very low earing per click so by manually approving them you are assured that you got the highest bidders appearing on your site frequently.

It is very easy to setup. Go to "Preferences" option and choose "manually approve your ads". Then go to your "Ad Status" tab, there you can approve and filter the highest bidders that you want to appear on your site, also decline advertisers that offer very low bids.

You can also check the site of your advertisers before approving them. Also take in consideration what countries your site's visitor mostly came from. By knowing this, you can select the highest bidders for that countries, this will significantly increase your earnings.

In case of geo-targeted ads, I tend to always approve them to avoid having a low advertisement inventory.

Manual approval only takes less than five minutes to do every day. By doing this, your highest bidders will appear more often in your ad block and protect your readers from unwanted ads.

Avoid placing many Bidvertiser ad units on a single page

Bidvertiser doesn't shows content relevant ads and also doesn't depend on your keywords to generate ads but from the highest bidders. It means that for every ad unit on your page, the same advertisers will show up.

Visitors doesn't want to check out or click the advertisers that they already visited or seen before. To fix this, just place on to tow ad units per page. In case you want to place more than two, make sure to place them away from each other.

Don't forget to place your bidvertiser Ad unit on the banner or top fold of your site's page

More exposure means that your ads are more likely to be clicked. Not all of your site's visitors scroll down your page unless you content is interesting. So avoid placing your bidvertiser ad unit after the content or at the bottom of the page.

Placing your ad unit on the banner or top fold increases its visibility and the chances of getting clicked by your visitors as well as your ad's CTR (Click Through Rate) thus producing you a lot of earnings.

Low Advertisement Inventory

Bidvertiser has less ad inventory compared to other advertising programs so you are more likely to see "Your Ad Here For Free" link when there are no ads available. This link won't let you earn from clicking it, you will earn if an advertiser decides to sign up using this link and spends to advertise on your site as your referred advertiser.

Some advertiser prefer geo-targeting, meaning their ads will only appear in specific countries and other have time duration on their ads. That's why you see this "Your Ad Here For Free" link because there are no available ads targeted for your country.

Select the Best Category that has a many Advertisers

While adding your domain in your Bidvertiser publisher account you need to choose the main and sub category for that. So make sure that categories match your domain's niche or at least have some relevance to it otherwise Bidvertiser admin will reject it.

Computer & Internet as main category works fine and has a good number of advertisers. You can select any of its sub categories that matches to your content. This category is also known as Business category.

If your niche falls between these two categories then you will minimize the lack of Bidvertiser ad inventory. Choosing categories for your domain is very important step because once these are selected, you can't change this anymore even if you delete and re-input it. The only way to change this is to contact Bidvertiser's support team.

Allow to Display eBay and Image ads

Other advertisers prefer to advertise using standard graphical ads so make sure that you allow to "Display Image Ads" in your Bidvertiser "Preferences". Also allow to "Display eBay Ads" as an additional inventory support.

Use only Standard Size Ad Units

Bidvertiser almost got all the standard ad formats for your site. They also allow you to create a customized ad size that prefer through "Free Design". This one is great for text-based ads but in terms of image ads, this is not good.

Advertisers that use graphical ads always use standard size ad units so if you have some custom-sized ad units in your site, you are losing some advertiser inventories. Here is a list of the standard ad units and I advise you to use it.

· Medium Rectangle (300 x 250)

· Vertical Rectangle (240 x 400)

· Large Rectangle (336 x 280)

· Rectangle (180 x 150)

· Full Banner (468 x 60)

· Half Banner (234 x 60)

· Vertical Banner (120 x 240)

· Square Button (125 x 125)

· Leaderboard (728 x 90)

· Wide Skyscraper (160 x 600)

· Skyscraper (120 x 600)

· Half Page Ad (300 x 600)

Avoid Ad units that display more than three Advertisers

There is no problem to use ad units that displays more than three ad units but since Bidvertiser has low ad inventory, we are trying to avoid the "Your Ad here for Free" link that shows up when there are no advertisers available.

The most effective units with three or less advertiser links are

Medium Rectangle (300 X 250)

Full Banner (468 X 60)

Vertical Banner (120 X 240)

Square (25 X 125)

Above four units are also the most likely units to have image ads so better to use these.

These simple tips and tricks can help you effectively monetize your website or blog with Bidvertiser and also help to increase your Bidvertiser ad inventory as well as earnings. It worked for me, hope it works for you too.

Tuesday, May 4, 2010

Meta tags: what is META tags and how it work ?


The purpose of HTML (Hyper Text Markup Language) is to enable web authors to specify structural information about their pages. Example:- images, tables, paragraphs etc. It also provides a way of adding information about the page and its content. Such type of information is known as metadata. It is added through the use of the <META> tag. The tag can also used to create the equivalent of HTTP (Hyper Text Transfer Protocol)headers, which provides instruction to the browser.

Use of Meta tag to provide information.

Meta tags should be placed within the <HEAD> section of your web pages. When we use META tag to provide information about our page, the basic syntax is below given.

<META NAME="dataname" CONTENT="datavalue">

In above syntax, "dataname" is a specific identifier for the information we are providing. The browser looks at this name and then it takes decision that how to treat the data. The information itself represented by "datavalue".

Description of Meta tags.

Here is the simple basically described pages content. Search engines often use it to display a brief page in summary results. Example is given below

<META NAME="description" CONTENT="An article about metadata and the META tag.">

Author

Another self explanatory one, this is usually used to display the name of the person who wrote or designed the page's content.

<META NAME="author" CONTENT="Sanjan Bikram">
Keywords
This is metadata that usually everyone's talk about, although in reality its effectiveness is overhyped. The keywords allows you to identify a number of themed words and phrases which may be associated with tat web page in some particular way. Example:- Most of the keywords are associated with this articles might be: META tags, META data, HTTP, HTML etc.
 
While we search something in search engine, we mostly type few words or phrase whatever we are looking for. Search engine looks for the matches that we have entered within the web pages or stored in its database. That's why people have been going nuts over the META keywords tag, they think that if you don’t have it on each page, and don’t have an extensive list of words, then you won't get very good search engine results.
 
There are only three major search engines who gives the importance to META tags those are as follows.
1.     InfoSeek
2.     AltaVista
3.     HotBot
 
The others base their results upon a page's actual content. However it is still worth adding META keywords to our pages if we want good results in those engines. Words and phrases are treated differently. For example, you would need to include the phrase "web authoring" as well as the two individual words "web" and "authoring" for best results. Here is the example:
 
<META NAME="keywords" CONTENT="metadata, META tag, meta, keywords, search engines">
 
ROBOTS
 
Robot.txt is also related with search engines. Robot is a program which will visit a web page, index it somewhere, and then visit all the hyperlinks in that page, indexing them all. It may continue in this fashion indefinitely or it may stop after it has reached a certain level. Search engines often send a robot round to our website in order to add all its pages to their database.
 
Sometimes we may not want certain pages on our site to appear in search engine. Those may be pages containing sensitive information, or those which should not be viewed outside of frameset. We can use the meta tag to provide instruction to robots visiting a page. We can tell them not to index the page, or not to allow any of the links on it or both.
 
Below are the examples of some of the combinations that we can use:
 
<META NAME="robots" CONTENT="NOINDEX,NOFOLLOW">
<META NAME="robots" CONTENT="NOINDEX,FOLLOW">
<META NAME="robots" CONTENT="INDEX,NOFOLLOW">
<META NAME="robots" CONTENT="INDEX,FOLLOW">
 
Last  line in this list is in fact the default setting. So we wouldn't ever need to use it in practice.
 
Use of META tags for controlling the web browser
 
Above I have described  that META tag can also be used to generate the equivalent of HTTP headers. In practice, this means you can control the behavior of the user's browser.
 
Preventing a page from being cached
 
There may be occasions when we want to prevent a page from being cached locally on the user's computer and thus force the browser to load a fresh copy each time. Example: webcam while is automatically updated every few seconds. If the user visited at a later date the browser might show them the cached (outdated) version.
 
There are in fact three META tag verities which we should use to cause this behavior. This is because they are accepted in different browsers. The first expires is actually supposed to identify an expiry date for the web page. If we leave the value as 0, then it treats it as "now", therefore asks for a new version of the page every time. The other two, Pragma and Cache control, are specifically designed to prevent or control caching, and should take a value of "no-cache". So, to prevent our page being cached in most browsers, we should use the given lines.
 
<META HTTP-EQUIV="Expires" CONTENT="0">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
 
Incidentally, if we wish for our page to expire at later date, we can specify the date in the given format using GMT time:
<META HTTP-EQUIV="Expires" CONTENT="Tue, 05 May 2010 10:05:00 GMT">
 
Redirecting the browser to another URL
 
Currently web hosting services are becoming cheaper and cheaper, many webmasters have decided to change their location of websites from free ISP space to professional server space. This relocation obviously causes confusion because visitors to the site will try to use the old URL. What many people do is keep on page at the old address which, when visited, will automatically send the user on the site's new home. This can be easily achieved using the META tag, which will redirect the user either instantly or after a given time delays.
 
Example is given below, this tag will redirect the visitor to " http://www.sanbik.co.cc" after 15 seconds, giving them enough time to read about what's going on.
 
<META HTTP-EQUIV="Refresh" CONTENT="15;URL=http://www.sanbik.co.cc">
 
Conclusion:
 
META tags can be very useful additions to our web pages, especially if we would like more control over how the search engines treat our site. Although the keywords and description tags are the most well known, the other forms of metadata can also prove to be helpful.
 
 
 
 
 

Sunday, May 2, 2010

Visual Basic Fundamental Notes


Saturday, May 1, 2010

Full notes for Visual Basic Desktop Programming (Part 2)


Chapter 5

Evolution of ActiveX Technology & COM

In mid 1980s, DOS was the most popular operating system. Windows was a very slow Graphical User Interface ( GUI ) which can run on 8086 based machines from floppy disks. DOS was a Single User and Single Tasking Operating System. The tasks can be categorized into two categories : Application – Centric & Data – Centric.

In Application – Centric environment, as long as users work with the data native to the application, everything was fine, but data cannot be converted from one application program to another automatically. It means there was no application which can contain data of different types. One needed to have a separate conversion program to perform the conversion, be it filters or any other program.

There was no link between the source application ( application where the document actually resides ) and the target application ( application where the document is being inserted after conversion ). It makes the document to convert again and again whenever there is a change in the source document. It is quite tiring and time – wasting experience. Then there was the scaling problem. The documents could not be scaled properly in the target application. Moreover, data was lost every time the conversion takes place.

In Data – Centric Environment, there is no need of any separate conversion program to move documents between different applications. Microsoft developed Data – Centric Environment ( also called Docu – Centric Environment ) with a vision of the future. The idea was to have a single document capable of containing any type of data and, users do not have to worry about the type of data or the conversion process. Here, the applications are made to embed different types of data into itself. The data – centric environment was not developed in a day or in one step, rather it was a gradual process.

The first step was the Dynamic Data Exchange ( DDE ), which allows applications to communicate with each other. This communication took two forms : data and commands. Data was identified by the application names within that application. Application could also execute some commands like macro in another application. But, DDE actually was very difficult to implement correctly and it was very slow too.

Next step was OLE (Object Linking & Embedding). It came with the document ( Object ) which could contain any type of data. The Linking & Embedding part of the term suggest the possible locations for objects that are part of the document. Any application can display a document consisting of many different types of objects and an object can be edited simply by double – clicking on it, which results in the application associated with it. There was no need of any separate conversion program and moreover the applications are linked to each other by means of objects. But, OLE 1.0 could not be implemented properly as the hardware technology was not that much advanced that time.

Then OLE 2.0 came, which was an improved version of OLE 1.0. OLE 2.0 is a group of technologies which are independent of each other, but they all are based on one common thing : COM. COM is Component Object Model and is a standard to develop application. The Standard Defines :

  • A common way for applications to access and perform operations on objects.
  • A mechanism for keeping track of the objects and deleting it whenever it is no longer needed.
  • A set of error codes and values.
  • A mechanism for applications to exchange objects.
  • A way to identify objects and to associate objects with application that understand how these objects are implemented.

In 1991, Microsoft developed Visual Basic to develop Windows Applications. Visual Basic was grafted from a number of existing technologies. It used the old BASIC language engine written in 16 – bit assembly language. This language engine was then grafted onto a forms package architecture called RUBY, originally developed by Alan Cooper. Alan Cooper is considered as the Father of Visual Basic.

From version 1 to version 3.0, Visual Basic used to perform the same functions for 16 – bit operating systems. After that Microsoft started working on a different language engine called Object Basic for 32 – bit Operating Systems ( then under development ). Later this Object Basic was known as Visual Basic for Applications ( VBA ). VBA was based on COM ( Component Object Model ) and it used OLE Automation to program other Objects and applications. It also uses OLE internally to execute commands on its own objects.

From Visual Basic version 4, Microsoft had made possible for developers to develop their own controls that work very similar to the intrinsic controls. These controls are called custom controls ( VBX). Microsoft had also developed Visual Basic for Applications ( VBA ), but by the time of development of VBA, the VBX technology became obsolete. OLE already was there but it had a problem, it can not raise events that time. A new type of object was defined called OLE Control ( OCX ), which can raise events as well. Microsoft became world leaders in windows programming with VBA and OCX, since windows programming was the most happening thing of that time.

Enter World Wide Web ( www ) and it changed the vision of the people. The windows hype was all gone and Internet was the next most happening thing. www became the next buzzword and suddenly companies like Netscape and Sun Microsystems emerged from no where and suddenly became the front – runners of this very new technology. Microsoft which took quite a while to realize the changed vision of the people had to change its strategy. The new strategy that seemed to be "Whatever we do must have and Internet Component". Then came HTML ( Hyper Text Mark – up Language ), a true docu – centric environment which can contain virtually any type of data and it is very easy to implement. Microsoft’s new strategy was to adopt internet and they changed a whole lot of things in the existing OLE to add some internet technologies and functions. A compound document created that way was fully compatible with HTML. Microsoft wanted to make people feel that it was very serious about the www and is working on the new technology, but at the same time it can not afford to be left behind. And since any new technology would take time to develop, Microsoft simply renamed its OLE to AciveX. So, OLE is ActiveX. OLE automation is ActiveX automation and OLE Object is ActiveX Object.

Component Object Model ( COM ) :

COM components are self-contained units of code that provide specific functionality. Using COM, several different components that work together as a single application, can be developed. Separating users code into components gives the ability to develop and test small, encapsulated pieces of the application independently. It also enables multiple developers to work on a project together by allowing tasks to be distributed among the members of the development team. Designing an applications using COM components also enables the Programmer to use multiple instances of an Object within one application.

COM components can be either internal components, which are compiled into a project and are available only to that project, or external components, which are compiled into executable files or dynamic-link libraries. External components can be used by any client application that supports COM. A COM component is used in exactly the same way, regardless of whether they are internal or external components.

With COM, reusable software components can be created. A reusable software Component is a piece of reusable software in binary form. Such Component s can be developed by an application Programmer or can be reused from another project. Software built with this object – oriented approach is often called ComponentWare.

A COM object has the following characteristics :

· A COM Object may contain data.

· A COM Object is primarily composed of interfaces.

· These interfaces can be called to operate on data or perform other operations.

· COM Object s can be identified by a GUID, an identifier used to identify a particular type of Objects.

· The GUID can be used by the system to associate a particular instance of an Object with the application or with the .DLL that contains the functions for that Object.

· The functions for the Object are contained in an application or Dynamic Link Library ( .DLL ).

· Not every COM has a visual interface.`

Advantage Of Using COM Components :

There are many reasons to use COM components in an application:

Reusability :

Once you create a COM component, other developers can use it. This enables easy access to your component's features in other applications without requiring developers to write extensive code. A developer can use the Object Browser to get information about the properties, methods, and events exposed by your COM component. For more information, see Using the Object Browser in this chapter.

Reduced Complexity :

You can create a COM component to hide programming complexity from other programmers. Other programmers need only know what information to provide to your component, and what information to retrieve.

Easier Updating :

Components make it easier for you to revise and update your applications. For example, you can create a COM component that encapsulates business rules. If the business rules change, you update just the component, and not all the applications that use the component.

Interface :

An interface is a list of semantically related properties and methods. An interface has no implementation, and the Class provides the implementation. So, the interface can not be used directly from code. A Class is implementation of one or more interfaces. A Class provides code and data to implement interfaces.

Every Component Object must implement at least one interface. COM insists that software components have pointers to at minimum three important functions. These pointers to functions can be obtained in a consistent way, regardless of what the component does. The first function, when called, reveals what the component does. The second function tells the component which is being referenced by the Program and the third function tells the component the program which is using the reference of the Component, is finished the execution.

Every COM Object must implement a special interface known as IUnknown. This special interface consists of three functions :

· AddRef

· Release

· QueryInterface.

Note : These functions are not called explicitly. These functions will always take the same parameter and will always return the same values regardless of whether the Object is a Picture or an Animation, or a Sound Object. Moreover, these functions will always appear in the same order in the interface declaration and always perform exactly the same operations.

Every COM Object has an internal reference counter that keeps track of how many times it is being referenced. The AddRef function in the IUnknown interface increments the reference counter. The Release Function decrements it. If an Object is released and the counter becomes zero, the system knows that it can delete the Object. The QueryInterface allows to ask an Object if it supports a particular interface and if it does, to get a pointer to the code containing the function for that interface. As long as the object exposes interfaces in a standard way and the functions for those interfaces can read the parameters and return values as specified by the COM standard, the Object will work. That is how, objects created with Visual Basic can be accessed by C++ programmer or Access Programmer. The language and implementation do not matter; only the interface and the COM standard matter.

An Object does not need to support every possible interface. IUnknown interface is the minimum interface that a COM Object must support. Apart from IUknown interface, there are several other interfaces supported by COM. One such interface is the IDispatch interface. This interface is used by a COM program to invoke a COM Object’s properties, methods, and events. A IDispatch interface has functions that allow the objects to define other Objects. Moreover, it provides a way for each Object to expose as many different functions and properties as it wants. A Dispatch interface is also called an Automation Interface. ActiveX automation is used to implement all of the functions and properties that the VB Classes and ActiveX Objects define.

COM Objects often rely on other COM Objects to get work done. All COM objects must have an accompanying COM Object, known as its Class Factory. The Class Factory is used to create the COM Object. Since COM Objects effectively create themselves, creating a COM Object on behalf of a Client can be problematic. COM solves this problem using Class Factory. When a COM server starts execution, it creates a COM Object that implements the IClassFactory interface. This interface contains a method called CreateInstance, which is used to create new instances of the COM Object. COM uses the Class Factory to create the Object for the Client.

Globally Unique Identifier ( GUID ) :

All the Objects including COM Objects must be defined in some unique way in order to avoid confusion amongst the different Objects. Clearly, an Object Name is not unique enough. COM Objects are identified not by name but by an ID. COM assigns every type of Object a 16 – Byte value called GUID ( Globally Unique Identifier ). GUID is assigned to an Object, and it is effectively guaranteed to be unique through out the entire universe, forever. Two factors ensure that the number is unique : Part of each GUID is generated based on the Network Card Address ( Which is unique for every Network Card ) and then, this ID is partly randomly generated, using the current Date & Time of the system.

GUIDs are used to identify COM Objects, interfaces, Type Libraries, and other items that need to be uniquely identified. Same GUID can be used for two different kinds of things. As for example, a class may have the same GUID as a type Library. Since they are two different things, there is no confusion for the reuse of the GUID.

When a GUID is used to identify a COM Object, it is known as Class Id (CLSID). When a GUID is used to identify an interface, it is referred to as Interface ID ( IID ), and when a GUID identifies a Type Library, it is known as a Library ID ( LibID ). A COM Object may consume several GUIDs. It needs one for itself ( CLSID ), one for its Type Library ( LIBID ) and one each for each of the interfaces it may have. To be able to use an Object’s interface, the using Object must know the CLSID and the IID.

Note : Visual Basic automatically generates the CLSIDs and the IIDs.

Type Library :

A Type Library describes the classes and interfaces provided by a COM Server. Type Libraries are usually complied into a .TLB file. However, the COM developer can choose to compile Type Library information into the Exe or the DLL. Thus, a Type Library can be contained in a .TLB, EXE, or a DLL file. Visual Basic automatically compiles Type Library information into the EXE or DLL. A VB Developer can request the creation of a .TLB file by selecting the Remote Server Files option from the Components tab of the Project Properties Dialog.

Type Libraries are described using the Interface Definition Language ( IDL ). In a Type Library, an interface defines a set of methods and property Let/Get Procedures.

Visual Basic lets developers create three types of COM components : ActiveX controls, ActiveX documents, and COM executable Programs and DLLs.

ActiveX Controls :

ActiveX controls (formerly known as OLE controls) are standard user-interface elements that allow users to rapidly assemble reusable forms and dialog boxes.

Active Documents :

Active documents are COM components that must be hosted and activated within a document container. Active document technology is an extension to OLE documents. It enables generic shell applications, such as Microsoft Internet Explorer, to host different types of documents.

COM Executable Programs and DLLs :

COM executable programs and DLLs are libraries of classes. Client applications use COM objects by creating instances of classes provided by the COM .exe or .DLL file. Clients call the properties, methods, and events provided by each COM object.

In Visual Basic, the project templates you use to create a COM executable program or COM DLL are referred to as ActiveX EXE and ActiveX DLL, respectively.

Visual Basic handles much of the complexity of creating COM .exe and .dll files, such as creating a Type Library and registering the component, automatically.

Creating COM Components :

A COM component is a library of code that is compiled into either an executable program or a dynamic-link library (DLL). In Visual Basic, COM components are composed of one or more class modules in a VB Project

In Process VS. Out-Of- Process Components :

Components can be designed and built to provide services from different locations, depending on the intended use of the component. For example, a user interface component would probably be best located as close to an individual client as possible, while a component that supplies statistical calculations of remote data would probably be best located on a separate computer.

In-Process Vs Out-of-Process Components :

Components can be run in any one of three places: in the same address space as the client (in-process), on the same computer (out-of-process), or on a remote computer. The following table defines the differences between these types of locations for components.

Type of Component Location

In - Process An in-process component is implemented as a dynamic-link library (DLL). It runs in the same process space as its client application. This enables the most efficient communication between client and component, because you need only call the function to obtain the required functionality. Each client application that uses the component starts a new instance of the component.

Out-of-process An out-of-process component is implemented as an executable file, and runs in its own process space. Communication between the client and component is slower because parameters and return values must be marshaled across process boundaries from the client to the component, and back again. However, a single instance of an out-of-process component can service many clients, share global data, and insulate other client applications from problems that one client might encounter.

Remote Remote components are also out-of-process components, but they are located on a separate computer. While communication time between a client and a remote component is much slower than with a local component, remote components allow processing to be done on a separate and possibly more powerful computer. The component can also be located closer to the work it is doing. For example, a component can be located closer to a remote database with which it interacts.

Component Project Templates :

In Visual Basic, you can build code components to run in-process (COM DLL) or out-of-process (COM executable program).

When you create a new project in Visual Basic, you can choose among a number of project templates on which to base the new project. In the New Project dialog box, choose ActiveX EXE to create an out-of-process component, or ActiveX DLL to create an in-process component. Selecting either type sets a number of default values that are important to creating components.

Declaring Friend Properties and Methods :

You can create components that contain more than one class module. If you want instances of these classes to communicate with each other, but you do not want to make them available to other client applications that use these components, you can use the Friend keyword. This declares the properties and methods of the Friend class as available only to the other classes within the component.

The Public properties and methods in a class can be called by other objects, and they can also be called by client applications. The Private properties and methods cannot be called from outside a component, and they are also not visible to other objects within the component.

Properties and methods declared with the Friend keyword are visible to other classes in the application, but are not visible outside your application because Friend procedures are not added to the type library or to the public interface.

In the following example code, the FormatSalaryInfo method in CEmployee is a friend method to other classes in the same application:

' Code in CEmployee can be called from other class modules but not

' from outside the project.

Friend Sub FormatSalaryInfo()

' code to process salary info

End Sub

Instancing Property :

Every Class Module has this Instancing Property which is set to specify whether or not the object will be available for use by client applications, and whether or not multiple instances of the object can be created. You need to set the Instancing property for each class module in the component.

Although a client does not have any control over the instancing of the component, the Instancing property can significantly influence the performance of the client. For example, if the client must share an instance of a component, its performance may be slower.

The Instancing property also determines if applications outside a project can create new instances of a class, and if so, how those instances are created.

The available instancing options are different in COM executable and COM DLL components.

The following table defines each of the Instancing property settings.

Setting Description

Private Other applications are not allowed access to type library information about the class, and cannot create instances of it. Private objects are used only within a component. It is supported by both ActiveX DLL and ActiveX EXE.

PublicNotCreatable Other applications can use objects of this class only if a component creates the objects first. Other applications cannot use the CreateObject function or the New operator to create objects of this class. You set the Instancing property to this value when you want to create Dependent Objects.

SingleUse There are two ways for an EXE Server to support Objects. There can be a Single Server Support Multiple Objects in which, all the Objects run in the same process or, each Object can have its own instance of the Server in which case, each Object runs in its Process. SingleUse allows other applications to create objects from the class. Every object of this class that is created by a client will start a new instance of the component.

GlobalSingleUse Similar to the SingleUse setting, except that properties and methods of the class can be invoked as though they were global functions.

MultiUse Allows other applications to create objects from the class. One instance of a component can provide any number of objects created in this way, regardless of how many applications request them. It allows a Single Server to support any number of Objects of a given Class.

GlobalMultiUse Similar to the MultiUse setting, except that properties and methods of the class can be invoked as though they were global functions. Explicitly creating an instance of the class first is not necessary because one will automatically be created.

Friend Properties & Methods :

You can create components that contain more than one class module. If you want instances of these classes to communicate with each other, but you do not want to make them available to other client applications that use these components, you can use the Friend keyword. This declares the properties and methods of the Friend class as available only to the other classes within the component.

The Public properties and methods in a class can be called by other objects, and they can also be called by client applications. The Private properties and methods cannot be called from outside a component, and they are also not visible to other objects within the component.

Properties and methods declared with the Friend keyword are visible to other classes in the application, but are not visible outside your application because Friend procedures are not added to the type library or to the public interface.

In the following example code, the FormatSalaryInfo method in CEmployee is a friend method to other classes in the same application:

' Code in CEmployee can be called from other class modules but not

' from outside the project.

Friend Sub FormatSalaryInfo()

' code to process salary info

End Sub

Compiling A Component :

Once you have built the class modules for a COM component, you are ready to compile it. Your component is compiled as either an .exe or .dll file, depending on the settings in the Project Properties dialog box.

The Project Compatibility field in the Project Properties dialog box is selected by default. In this setting, Visual Basic reuses the same type-library ID each time you compile a code component.

If you make a change that is incompatible with the version of your server specified in the Project Compatibility field (for example, if you delete a property), Visual Basic displays a warning and generates a new type-library ID to indicate that your component has changed.

Version Compatibility :

At some point, it becomes necessary for the programmers to modify or upgrade the components. But when the COM server is changed the installed client is affected, so a programmer ought to be very careful while making any sort of modification in the Server. COM standards require that once you create a version of a COM component that is used by others, you don't change the characteristics of that component. To facilitate making improvements to COM components, Visual Basic provides version compatibility that enables you to enhance components while maintaining compatibility with programs compiled with earlier versions of a component.

Changes to the server fall into two broad categories : Compatible & Incompatible Changes. A Compatible Change to the server allows existing clients to use the new Server without having to change or reinstall the client. For example, if there is a logical error in one of the methods of the Server, then the logic can be changed and the compatibility with the client can be maintained, provided no changes are made to the parameters.

An Incompatible Change to the server prohibits existing clients from using the newer COM server. In this case, the client needs to be reinstalled.

In Visual Basic, you select version compatibility options by clicking Project Properties on the Project menu, and then clicking the Component tab of the Project Options dialog box.

Under Version Compatibility, you can select one of three options, as shown in the following table.

Option Result

No Compatibility Each time you compile a component, new type library information is generated. There is no relationship between versions of a component. Applications that currently use one version cannot use subsequent versions. Use this compatibility option when you start a new project, or when you do not want to enforce compatibility with an earlier version of the component.

Project Compatibility Each time you compile a component, new type library information is generated, but the type-library ID remains the same so that your test projects can maintain their references to the component project.Use this compatibility option when you start a new project, or if you are working on components without changing their methods or properties.

Binary Compatibility When you compile a component using Binary Compatibility, Visual Basic preserves the type library information from the previous version. Components that currently use an earlier version will continue to work. Use this compatibility option when you want to ensure that an upgrade to a component will work with clients currently using an earlier version of the component. Visual Basic warns you when changes to your component would make the new version incompatible with previously compiled versions.

Registering A Component :

A COM component must be registered before its use. The process to register a component differs for out-of-process and in-process components. When a COM component is registered, some information gets added to the Windows registry to identify itself as an available COM component to clients on that system.

There are several ways to register an out-of-process component (.exe file):

Compile the component.

Visual Basic registers the component as it compiles the component.

Run the component.

It automatically registers itself each time it runs.

Run the component with the /Regserver command-line argument.

The component ends immediately after registering itself.

Create a Setup program.

When you run the Setup program, the component is registered.

There are several ways to register an in-process component (.DLL file):

Compile the component

Visual Basic registers the component as it compiles the component.

Run Regsvr32.exe.

Regsvr32 is a utility that will register a .dll. Pass the .dll file name as an argument to the Regsvr32 utility as shown in this example code:

Regsvr32.exe C:\StateUBookstore\payroll.dll

Regsvr32.exe is located on the Visual Basic CD-ROM in the \Tools folder.

Create a Setup program.

When you run the Setup program, the component is registered.

Unregistering A Component :

When a component is no longer needed, it can be removed from the registry.

To remove an .exe entry from the registry, run the component with the /UnRegserver command line argument, like :

StateUEmployee.exe /UnRegserver

To remove a .DLL entry from the registry, run Regsvr32.exe, including the /u option and the name of the .DLL file, like :

Regsvr32.exe /u C:\StateUBookstore\payroll.dll

Note : You can also uninstall a component using its Setup program.

Testing Component :

Microsoft Visual Basic offers different scenarios for testing and debugging in-process and out-of-process components. For in-process components, you test and debug a component within a single instance of Visual Basic. For out-of-process components, you run two copies of the development environment.

Testing :

To test a COM component, you create a test project that will use the component. Depending on whether your component is a DLL or an executable program, you create the test project within the current instance of Visual Basic, or in a separate instance.

Testing a COM DLL :

To test a COM DLL, you can add a Standard EXE project to the project group, and test the in-process component within a single instance of Visual Basic. You can then step directly from the test project's code into the in-process component's code.

Testing a COM Executable Program :

To test a COM executable program, you must run the component within one instance of Visual Basic, and run the test application in a second instance of Visual Basic. In this case, you cannot step directly from one component into the other, but you can still use all of the other Visual Basic debugging tools.

Debugging :

Once you have set up a test project and established a reference to the component, you can debug the component just as you would any Visual Basic application. You can step between the client application and component, and use the standard debugging tools to set break points, step through code, use watch expressions, and so on.

Errors Handling in COM :

There are two ways of handling errors : Providing Error Information to a client application & Raising an Error that the application must handle, and returning an Error Code to the Application.

Handling errors requires close communication between client applications and components. If possible, a component and its clients should handle errors, rather than displaying a message to the user.

When a client application calls a method of an object provided by a component, the method can provide error information in the following ways:

Raise an error that the client application must handle. In this case, the client uses conventional error-handling statements to handle errors that are raised.

Return an error code that the client application must test for and handle.

Using a Raised Error :

In a code component, a method calls the Raise method of the Err object to raise an error to the client application. The client implements an error handler to trap the error.

Using a Return Value :

In a code component, a method can return a value to the client application. The client examines the return value to determine if an error occurred, and if so, which one.

With this type of error handling, developers of client applications must always test the return value after calling a method of an object in a component.

Raising Run-Time Errors :

When you create a component, you can provide error messages to the client application. To pass an error back to a client application, you use the Raise method in a component. For the error to be raised in the client, you must call Raise from your method's error-handling routine or with error handling disabled.

The Raise method has the following syntax:

Err.Raise (Number, Source, Description, HelpFile, HelpContext)

To generate an error number, add the constant vbObjectError to the error number. The resulting number is returned to the client application. This ensures that your error numbers do not conflict with the built-in Visual Basic error numbers.

Component Code

Private mvarSalary As Double

Public Property Let Salary(ByVal dNewSalary As Double)

If dNewSalary < 0 Then

Err.Raise 12345 + vbObjectError, "CEmployee", "Salary must be +ve"

Else

mvarSalary = dNewSalary

End If

End Property

Public Property Get Salary() As Double

Salary = mvarSalary

End Property

Client Code

Private Sub SetSalary_Click()

' declare an employee object

Dim empCurrent As CompanyComponent.CEmployee

On Error GoTo HandleError

' create the employee and set the salary property

Set empCurrent = New CompanyComponent.CEmployee

' an error could occur here

empCurrent.Salary = CDbl(txtSalary.Text)

Exit Sub

HandleError:

If Err.Number = 12345 + vbObjectError Then

MsgBox "Salary must be positive.", ,Err.Source

End If

End Sub

Breaking on Errors

You can change the way Visual Basic enters Break mode when an error occurs in your code component. To do this, you set Error Trapping options on the General tab of the Options dialog box.

Visual Basic provides three options for setting breakpoints, as shown in the following table.

Option Description

Break on All Errors Any error causes the project to enter break mode, whether or not an error handler is active, and whether or not the code is in a class module.

Break in Class Module Any unhandled error that has been produced in a class module will cause the project to enter Break mode at the line of code in the class module that produced the error. When you debug a COM component project by running a client application from another project, set this option in the COM component project to break on errors in its class modules, instead of returning the error to the client application.

Break on Unhandled Errors If an error handler is active, the error is trapped without entering Break mode. If there is not any active error handler, the error causes the project to enter Break mode. An unhandled error in a class module will cause the project to enter Break mode on the line of code that invoked the offending procedure of the class.

Using Visual Component Manager:

Visual Component Manager allows you to easily publish, find, and catalog components, including ActiveX controls, COM Components, HTML and ASP pages, and Visual Basic source code. With Visual Component Manager you publish components to a repository database, where they can easily be located, inspected, retrieved, and reused. The Enterprise version of Visual Component Manager makes it easy for teams of developers to share components, enabling effective component and code reuse both within a development team, and across an entire organization.

To add Visual Component Manager to the Visual Basic toolbar

1. On the Add-ins menu, click Add-in Manager.

2. In the list of available add-ins, select Visual Component Manager.

3. Under Load Behavior, select the Load on Startup check box, and then click OK.


Publishing a Component:

Publishing a component means storing it in a Visual Component Manager repository database along with attributes and search keywords that make it easy for others to find and reuse it.

When you publish a component, you add it to a Microsoft Repository database. This can be a local database on your own workstation, or it can be a shared database on a network server. A shared database gives everyone who has access to that server the ability to find and reuse your component.

Note : Microsoft Repository creates a default repository database for you when it is installed. This database is managed by Microsoft Jet. Its location is determined by the default value of the Current Location registry key.

To Publish A Component :

On the Tools menu, point to Publish, and then click Source Files or Build Outputs.

When you click Source Files, you publish the project’s source code files; when you click Build Outputs, you compile and publish the files that are generated at compile time.

The Visual Component Manager Publish Wizard appears, and walks you through a series of steps that allow you to publish a project for reuse.

Chapter 6

Building ActiveX Control

Controls are reusable objects that include visual elements and code. With Visual Basic, controls can be used to quickly create forms and dialog boxes. Visual Basic ships with built-in controls that are visible on the Control Toolbox whenever Visual Basic is loaded, and ActiveX controls that can be added to the Toolbox. Beginning with Visual Basic version 5.0, users have been able to create their own ActiveX Controls. Controls must be placed in some type of container, such as a form or an application.

ActiveX controls created in Visual Basic can be used in many different container applications, such as other Visual Basic applications, Microsoft Office documents, and Web pages viewed with Microsoft Internet Explorer.

Creating the user interface for an ActiveX control is similar to creating a standard Visual Basic form. Controls can be drawn first, and then provided the code that defines the behavior of those controls.

A control can take advantage of the functionality of existing controls while adding some new custom functionality. The control developer has the ability to choose which pieces of functionality from the existing controls to expose to the user of that custom control.

Control Classes :

A control that is created in Visual Basic is known as a control class, which acts as a template for that control. The control class is compiled into an .ocx file. To use the control in an application, the control is placed on a form, which creates a design-time instance of that control. When a user runs the application containing the control, the user gets a run-time instance of the control.

Project Files :

The source code and property values for a control class are stored in a text file with a .ctl extension. A .ctl file is equivalent to the Visual Basic .frm file that is used to store this information for a form.

Graphical elements, which cannot be stored as text, are stored in a file with a .ctx extension. A .ctx file is equivalent to a Visual Basic .frx file that is used to store graphical elements in forms.

A Visual Basic ActiveX control project can contain one or more .ctl files, each of which defines a separate control class. When a control projectis compiled, one .ocx file is created that contains all of the controls in the project.

Steps For Creating An Active Control :

To build an ActiveX control, you perform the following steps:

1. Create an ActiveX Control project.

2. Create the user interface for the control.

ActiveX controls are typically made up of constituent controls. A constituent control is any existing control, such as a control that ships with Visual Basic (for example, a text box or command button), or a control that you've purchased.

3. Create the properties and methods of the control.

4. Create event procedures for the constituent controls on your control.

5. Expose events from the control.

6. Create property pages for the control.

7. Debug and test the control.

Adding Constituent Controls :

An ActiveX control includes a UserControl object and constituent controls.

The UserControl Object :

The UserControl object is the foundation for building controls. Every ActiveX control that is created with Visual Basic contains a UserControl object.

UserControl objects contain code modules and visual designers. When you open a UserControl in design mode, the object is displayed in a visual designer window. You can use the visual designer to place constituent controls on the UserControl object just as you would on a Visual Basic form.

Constituent Controls :

A constituent control is an instance of a control that you place on a UserControl object. When you place an ActiveX control on a form, an instance of the UserControl object is created, along with instances of any constituent controls you placed on the UserControl object.

Any standard Visual Basic control can be used on the UserControl object except the OLE Container control. The Constituent Controls can be added to a UserControl object in the same way as a standard Visual Basic form.

User Control Events :

An ActiveX control is a client that runs in a form or in some other type of container. Therefore, its events behave somewhat differently than control events on a standard .exe project form.

When a control is created, the UserControl object acts as the blueprint to place the control on a form or in another container. This blueprint now, can be used to create an instance of the control. When a control is created, a series of control events occurs.

The specific events and the order in which they occur depend on the particular user or system actions that take place during the lifetime of the control instance.

The following table summarizes how controls are created in response to a user's actions, and which events occur when the control is created.

User action

Type of control instance

Events

Places the control on a form.

Design-time instance is created.

Initialize, InitProperties,

Resize, Paint

Runs an application containing the control at design time.

Design - time instance is destroyed, & run-time instance is created

WriteProperties (if needed),

Terminate, Initialize,

Resize, ReadProperties, Paint

Exits an application containing the control; returns to design mode.

Run-time instance is destroyed, and design-time instance is created.

Terminate, Initialize,

Resize, ReadProperties,

Paint

Closes the form containing the control.

Design-time instance is destroyed.

WriteProperties
(if needed)Terminate

Runs the compiled application

Run-time instance is created.

Initialize, ReadProperties,

Resize, Paint

Interacting With A Container Application :

The author of the control, cannot always predict which container will be used for the control or what size this control will be in its container. Therefore, the control should be designed such that it can function appropriately in a variety of containers and is sized appropriately. To ensure consistency between the control and its container, the container's ambient properties can be used. Resize event can be used to size the control properly in the container.

Ambient Properties :

Containers provide ambient properties to suggest behavior to controls that is appropriate for the container. Ambient properties ensure that the user of a control is provided with the expected visual appearance and behavior, regardless of the container.

For example, BackColor is one of the standard ambient properties of a Visual Basic form. The container suggests the background color for the control so that it matches the color of the container.

The AmbientChanged Event :

The AmbientChanged event occurs when an ambient property changes. To enable a control to respond to any changes made to the ambient properties of the container at design time, you place code in the AmbientChanged event. This event has one argument, PropertyName, that identifies which property has changed.

The Ambient Object :

The Ambient object lets you read the values of the various ambient properties.

For example, the following example code shows how to use the Ambient object in the AmbientChanged event:

Private Sub UserControl_AmbientChanged(PropertyName As String)

If PropertyName = "BackColor" Then

UserControl.BackColor = Ambient.BackColor

End If

End Sub

If the developer who uses the control, changes the BackColor property of the container, the background color of the control instance will match that of the container.

Supporting the Enabled Property :

The Enabled property is another ambient property you should consider when designing your control. To correctly support the Enabled property of your control, you must write Get and Let procedures for the Enabled property that delegate the enabling of your control to the UserControl object, as shown in the following example code:

Public Property Get Enabled() As Boolean

Enabled = UserControl.Enabled

End Property

Public Property Let Enabled(ByVal NewValue As Boolean)

UserControl.Enabled = NewValue

PropertyChanged "Enabled"

End Property

Because the container is responsible for enabling and disabling controls, you must also assign the Enabled property to the Enabled procedure ID.

To assign the Enabled property to the Enabled procedure ID

1. On the Tools menu, click Procedure Attributes.

2. In the Name box, select your Enabled procedure.

3. Click Advanced to expand the Procedure Attributes dialog box.

4. In the Procedure ID box, select Enabled to give the property the correct identifier.

Making The Control Transparent :

If you want to allow whatever is behind your control to show through, in between the constituent controls on your control’s surface, you can set the BackStyle property of the UserControl object to Transparent.

However, setting BackStyle to Transparent may affect the performance of your control. Visual Basic must do a great deal of clipping to make the background show through correctly if your control uses:

A large number of constituent controls.

A complex bitmap.

A Label control with a transparent background, a TrueType font, and a large amount of text.

Invisible Controls :

Most of the controls you create will have a visible user interface. However, you can create a control that is invisible at run time, such as the Timer control. To create an invisible control, set the InvisibleAtRuntime property of the UserControl object.

Sizing a Control :

The factors that determine how a control is displayed include the amount of available screen space, user preference, and the container used to display the control.

At design time, a developer adds your control to a container application and sizes it to fit in the container. At run time, a user can resize the entire application, which in turn might resize your control to better fit the new container size. In both these scenarios, the control needs to respond to the Resize event in order to work with the container application.

For example, assume your control consists of a command button, several text boxes, and a list box. When your control is resized to be smaller, unless you have added the appropriate code to the Resize event, the text boxes and list box may not be completely visible.

Note : Container controls cannot handle errors when the Resize event occurs, and will cause the application using the control to fail. Therefore, you should provide error handling in Resize event procedures.

Using the Resize Event :

You can use the Resize event to handle the resizing of controls and adjust the appearance of controls. The sizing of constituent controls is adjusted according to the current property settings for the UserControl object.

The following example code adjusts the width of a text box when the UserControl object is resized:

Private Sub UserControl_Resize()

Const MinWide = 2000

If UserControl.ScaleWidth < MinWide Then

Text1.Width = 1000

Else

'Scale textbox to size of the UserControl.

Text1.Width = UserControl.ScaleWidth - Text1.Left

End If

End Sub

Exposing Properties, Methods, And Events :

As with any standard control in a Visual Basic application, an ActiveX control provides functionality by exposing its properties, methods, and events.

The ActiveX Control Interface Wizard can be used to create properties, methods, and events.

ActiveX control interface wizard :

Visual Basic includes the ActiveX Control Interface Wizard, which simplifies the task of creating a control. This wizard lets you determine which properties, methods, and events will constitute the interface definition of your control.

The ActiveX Control Interface Wizard maps functionality from your control to the functionality of the UserControl object or constituent controls. You can change the default mappings later in the process.

In addition, this wizard generates the underlying interface code, including:

Property procedure code to implement procedures.

Sub and Function procedures to implement methods.

Code to raise the events you have selected.

The wizard generates the correct arguments and data types for standard events and event forwarding code for all your event mappings.

Adding Properties :

The container for an ActiveX control supplies a number of default properties, so you should decide which additional properties you need for the control.

Creating a Property :

To create a property for a control, you need to define storage for the property and then create property procedures to set and retrieve the property value. You must also let Visual Basic know when a property value changes. To indicate that a property value has changed, you use the PropertyChanged method of the UserControl object within a property procedure.

Calling the PropertyChanged method notifies Visual Basic that a property of your control changed. This is important so that Visual Basic can mark your control as needing to be saved in the project where it is being used. Also, calling PropertyChanged notifies Visual Basic to update the property value in the Properties window and in any property pages for your control.

Using Property Procedures :

You create property procedures for a read-write property in pairs. You can create a Set or Let procedure to assign a value to the property, and then create a Get procedure to return the value. You give the two procedures the same name, which is also the name of the property.

When a user reads the property, the Property Get procedure runs. When a user sets the property, the Property Let or Property Set procedure runs.

The following example code shows property procedures that define the UpperCase property of a control:

Private m_UpperCase as Boolean

Public Property Get UpperCase()As Boolean

UpperCase = m_UpperCase

End Property

Public Property Let UpperCase(ByVal New_UpperCase As Boolean)

m_UpperCase = New_UpperCase

PropertyChanged "UpperCase"

End Property

To create a read-write property that returns a standard data type, define a Property Get procedure and a Property Let procedure. To create a read-write property that is an Object data type, define a Property Get procedure and a Property Set procedure.

Note : To create a read-only property, define a Property Get procedure without a matching Property Let or Property Set procedure.

Exposing Constituent Control Properties :

In addition to creating custom properties for an ActiveX control, you can expose properties of the constituent controls in your ActiveX control.

Exposing the Property of a Constituent Control :

When a user works with your control, the properties of the UserControl object and of any constituent controls are not available by default. You can, however, make the properties available through existing properties of the UserControl object or of any constituent controls you have placed on the object.

For example, if you create a control that contains a Label control and a TextBox control, you can expose the properties of either the UserControl object or the constituent controls by using property procedures.

Public Property Get Caption()As String

Caption = lblName.Caption

End Property

Public Property Let Caption(ByVal NewCaption As String)

lblName.Caption = NewCaption

PropertyChanged "Caption"

End Property

When an instance of the UserControl object is placed on the form, the Caption property becomes available in the Properties window for that instance. A developer who uses your control can then set the value of the text that will appear in the label.

Mapping a Property to Multiple Controls :

You can map more than one constituent control property to a property of your control through delegation.

Public Property Get ForeColor() As OLE_COLOR

ForeColor = UserControl.ForeColor

End Property

Public Property Let ForeColor(ByVal New_ForeColor As OLE_COLOR)

Dim ctl As Object

UserControl.ForeColor = New_ForeColor

For Each ctl In Controls

If(TypeOf ctl Is Label) _

Or (TypeOf ctl Is CheckBox) Then

ctl.ForeColor = New_ForeColor

End If

Next

PropertyChanged "ForeColor"

End Property

When a user changes the ForeColor property of your control, the ForeColor properties of the constituent controls are also changed.

Adding Methods :

A method is a Sub or Function procedure exposed by an object. You can implement custom methods or delegate to existing methods of constituent controls, just as you can with properties.

Creating a Method :

The following example code creates a method that displays the date:

Public Sub ShowDate()

MsgBox "Date is: " & Now()

End Sub

Exposing Methods of Constituent Controls :

You can also expose methods of any constituent controls that are part of your control.

The following example code creates the method IDFocus, which in turn calls the SetFocus method of the constituent text box control:

Public Sub IDFocus()

txtEmpID.SetFocus

End Sub

In the example code, the TextBox control txtEmpID is a constituent control of the UserControl object. When the method is called from a form, focus is set to the txtEmpID control on the UserControl object.

In this way, you can expose methods of your constituent controls and enhance them with your own code as well.

Storing And Retrieving Property Values :

Instances of controls are continually created and destroyed, so you must ensure that the property values are preserved. When you create a control, you must include code that saves and retrieves property values of the control.

To store and retrieve information each time an object is created or destroyed, you use the ReadProperty and WriteProperty methods of the PropertyBag object.

Saving Property Values :

You save property values in the WriteProperties event of the UserControl object. This event is called when the design-time control is destroyed.

The WriteProperty method takes three arguments: a string indicating the property to save, a value for the property, and a default value if the developer did not set an initial property.

The following example code shows how to save current property values with the WriteProperty method of the PropertyBag object:

Private Sub UserControl_WriteProperties(PropBag As PropertyBag)

PropBag.WriteProperty "UpperCase", mvarUpperCase, vbUpperCase

PropBag.WriteProperty "Caption", Label1.Caption, "Username"

End Sub

Reading Property Values :

You retrieve property values in the ReadProperties event of the UserControl object. This event is called when either the design-time or run-time control is created.

The ReadProperty method takes two arguments: a string designating the property name and a default value. If a property value has been saved, the ReadProperty method returns the value. If a property value has not been saved, the method returns the default value.

The following example code shows how to use the ReadProperty method to return the saved value of the Caption property:

Private Sub UserControl_ReadProperties(PropBag As PropertyBag)

'Trap for invalid property values

On Error Resume Next

Label1.Caption = PropBag.ReadProperty("Caption", "Username")

End Sub

Initializing Property Values in the InitProperties Event :

The first time an instance of a control is placed on a container, it receives the InitProperties event. Thereafter, only the ReadProperties event occurs.

In the InitProperties event, you set the initial value for a property using the same default value that you provide with the WriteProperty and ReadProperty methods to save and retrieve the property value.

Since mapped properties are already initialized by the constituent control, you only need to initialize properties that don't map to properties of constituent controls. The following example code shows how to initialize the UpperCase property of an ActiveX control:

'set up storage for the property

Dim mvarUpperCase as Boolean

..

'Use that default value in the InitProperties event

Private Sub UserControl_InitProperties()

mvarUpperCase = vbUpperCase

End Sub

Raising Control Events :

An event is the way a control communicates with a container application. When a user interacts with the constituent controls on your control, your control receives those events and can react to them. However, the container of your control will not receive these same events unless your control specifically raises them to the container.

You use the following steps to raise an event from an ActiveX control:

1. Declare the event. 2. Raise the event.

Declaring an Event :

You declare an event in the General Declarations section of a UserControl by using the Event keyword. This makes the event visible to client applications that use your control. The following example code declares an event named StatusChanged:

Public Event StatusChanged(status as Integer)

Raising an Event :

When you want an event to be raised to the client application, you call the RaiseEvent statement, and pass the event name and any arguments that the event takes. You can raise an event at any time from your control: from an event procedure of one of your constituent controls, or from a method of your control.

The following example code raises the StatusChanged event when the user clicks the cmdPlaceOrder constituent control:

Private Sub cmdPlaceOrder_Click()

Dim iStatus as Integer

'set iStatus and raise the event

iStatus = 3

RaiseEvent StatusChanged(iStatus)

End Sub

Receiving an Event :

There is an important distinction between the events received by your control, or by its constituent controls, and the events your control raises. The control developer uses the events a control receives to add functionality to that control. A developer who uses the control uses the events the control raises to add functionality to the application containing the control.

When developers use your control, they will trap the events raised by your control just like handling any other event from any other control. In the following example code, a form uses your control and handles the StatusChanged event:

Private Sub ctlOrder_StatusChanged(iStatus as Integer)

Msgbox "Status of the order is now: " & iStatus

End Sub

Events raised by an ActiveX Control are handled in the container application using the control. For more information on how to handle events from a control, see Testing the Control Programmatically, in this chapter.

Exposing Constituent Control Events :

Unlike exposing properties and methods by delegation, you expose an event of a constituent control by raising your own event.

To expose the events of a constituent control

1. Declare a new event in the UserControl object.

2. In the constituent control's event, raise your own event.

In the following example code, the KeyPress event from a TextBox control is exposed through an event of the control named UserNameKeyPress:

Public Event UserNameKeyPress(KeyAscii As Integer)

Private Sub txtUserName_KeyPress(KeyAscii As Integer)

RaiseEvent UserNameKeyPress(KeyAscii)

End Sub

Testing A Control :

When you test your ActiveX control, you must test the control's design-time as well as run-time functionality.

An ActiveX control will behave differently, depending on how the control is instantiated. Understanding this behavior will help you test your controls properly. Because an ActiveX control cannot run by itself, you test the control by running it inside a container.

Testing the Control in Internet Explorer :

If you open an ActiveX Control project and select Run from the Visual Basic menu, Visual Basic will run the control in Internet Explorer. This allows you to test the user interface of the control from a Web page.

Testing the Control on a Form :

Visual Basic allows you to load two or more projects into a project group, which is saved with the extension .vbg. While you have your control project open, add a standard EXE project to your project group and place an instance of your control on a form in this new test project. Use this technique when you want to run and test the control on a form. You can test the design-time and run-time behavior of the control.

  • To add a test project to a project group

1. On the File menu, click Add Project.

2. In the Add Project dialog box, double-click the Standard EXE icon to add an .exe project to your project group.

You can now see both projects in the Project window. The title of the Project window indicates the project group name, as shown in the following illustration.

To test the design-time features of your control, you must close the control's visual designer. This causes Visual Basic to display the icon for the control in the Control Toolbox, so you can place instances of the control on a container form.

Debugging :

Once you have created a test project for your ActiveX control, you can test and debug the control by placing breakpoints in the control's procedures and stepping through the code. However, a unique trait of debugging ActiveX controls is that the control can run when the client is in Design mode as well as when the client is running.

There are several situations in which the control runs in Design mode:

When a developer sets the properties of your control.

When property values are read and saved.

When the control is initially displayed.

In these cases, your breakpoints can be reached before the client is run.

Testing The Control Programmatically :

Using controls is an integral part of building a standard application. In general, using a custom ActiveX control is no different than using a control that ships with Visual Basic. However there are a few things to keep in mind about ActiveX controls at design time.

Using Properties

You can set and retrieve properties of the ActiveX control at either design time or run time. Be aware that property procedures run in both cases.

Design time

When you use the Properties window at design time to set property values of your control, Visual Basic invokes your control's Property Let or Property Set procedures. This means that your control is running even though the application using the control is not. Therefore you must close any design windows of the control before you can test it in a container application.

Run time

There are no special considerations to keep in mind about getting and setting properties of an ActiveX control at run time. Behavior is the same as for any other control.

Handling Events :

When you place a custom ActiveX control on a form, it gets added to the list of objects in the Code window and any events you've exposed for the control are listed in the Procedure list for the control. This makes it easy for you to add event procedures for the control in the same way you add event procedures for standard controls.

For example, this is the event procedure for the control's UserNameKeyPress event:

Private Sub ctlNewEmployee_UserNameKeyPress(KeyAscii As Integer)

'Convert the character to uppercase.

'Since KeyAscii is passed ByRef it can be changed

'in the client.

KeyAscii = Asc(UCase(Chr(KeyAscii)))

End Sub


Chapter 7

Packaging & Deploying an Application

There are two ways to develop an application : - Off Sore & On Site. Site refers to the place where an application is to run. If the software is being developed at the computer where it has to run then it is known as On Site Development. If Software Development takes place at a different location and computer than where it is to run then it is known as Off Sore development. Most of the software are off – sore developments.

The developer has to copy all the programs associated with the application to the target computer in order to run the application. This includes main executable file and all the Components plus the data file & dependency file. Moreover, the files should be in the format which can not be used directly to prevent the Piracy. When an Application is to be distributed, users should be provided with a Setup program to perform some or all of the following tasks:

Copy the necessary files to the user’s computer.

Place the files in the appropriate folders.

Register files.

Create a Start menu item or group.

Create an icon on the users desktop.

Using the Package and Deployment Wizard

When an application is finished with writing, debugging, and testing, it is ready to distribute it to the Client users. The Visual Basic Package and Deployment Wizard steps through the process of determining which files need to be distributed, compressing them into a Cabinet file (.cab file), and creating a Setup program.

The Package and Deployment Wizard stores the information it gathers about the application every time the wizard runs, and saves it in a script file that can be named. The next time when the wizard runs, one can choose to use the settings in an existing script file so that there is no need to step through each screen of the wizard again.

To start the Package and Deployment Wizard, click the Start menu, point to Programs, and then point to Microsoft Visual Basic 6.0. Point to Microsoft Visual Basic 6.0 Tools, and then click Package & Deployment Wizard.

You can also add the wizard to the Add-Ins menu. If you start the Package and Deployment Wizard from the Add-Ins menu, it uses the current active project.

To add the Package and Deployment Wizard to the Add-Ins menu

1. On the Add-Ins menu, click Add-In Manager.

2. In the list of available add-ins, select Package and Deployment Wizard.

3. Under Load Behavior, select the Loaded/Unloaded check box, and then click OK.

Note : If you select the Load on Startup check box, the Package and Deployment Wizard will automatically be available on the Add-Ins menu every time you start a new project or open an existing project.

If you need to customize your Setup program to include functionality that is not supported by the Package and Deployment Wizard, you can use the Setup Toolkit that comes with Visual Basic.

Packaging an Application :

The first step in preparing your application for distribution is to package it for convenient handling. The Package and Deployment Wizard gathers information about all the files used by your application, and compresses them into a Cabinet file (.cab file).

The Package and Deployment Wizard offers the following options for packaging an application:

Standard Setup Package :

You can choose to package your application into a single .cab file for distribution on a network folder or CD-ROM, or you can package your application into multiple .cab files of a specific size to fit on a number of floppy disks.

Internet Package :

Your application is compressed into a single .cab file that is posted to a Web site. You can choose to have some components downloaded from an alternate Web site if you always want your users to download the most current version of the component.

Dependency File :

You can also use the Package and Deployment Wizard to create a dependency file that lists the run-time components required by your application.

To determine which file to include in the Setup program, the Package and Deployment Wizard checks the references and custom controls that has been loaded in the project. It then reads the VB6Dep.ini file in the <install folder>\Visual Studio\VB98\Wizards\PDWizard folder to determine which files are required for each reference or custom control.

For example, if you have set a reference to the Microsoft Common Dialog control, the Package and Deployment Wizard includes the appropriate .ocx file in your Setup program.

Note : The Package and Deployment Wizard recognizes controls and references, whether you use them in your application or not. If controls or type libraries that you have not used in your application appear in the Install Locations step of the wizard, and you know you did not use any of these, you should delete the unused files. Either remove the tools and references from your source files manually and then run the wizard again, or clear the check boxes in the list box in the wizard.

The Package and Deployment Wizard also enables you to manually add or remove files from the list of files that need to be distributed.

Distributing an Application :

Once your application has been packaged, you are ready to distribute it to your users. The Package and Deployment Wizard provides support for distributing your application on a network folder, CD-ROM, floppy disks, or an Internet server.

Your application must be packaged into one or more Cabinet files (.cab files) before you can deploy your application. For information about packaging your application, see Packaging an Application in this chapter.

The Package and Deployment Wizard offers the following options for deploying your application:

Folder :

The .cab file and supporting setup files are copied to a local or network folder for distribution.

Web Publishing :

The .cab file is copied to a Web site, and your application is distributed across the Internet by using automatic code download from Microsoft Internet Explorer version 3.0 or later.

Setup Files

The Package and Deployment Wizard creates all of the files necessary to install your application on a user’s computer.

The following list describes some of the necessary files:

Cabinet file (.cab file) :

The Package and Deployment Wizard compresses your application files into one or more .cab files for distribution. The Setup program then extracts application files from this .cab file and copies them to the appropriate locations on a user's computer.

Setup.exe :

The Package and Deployment Wizard copies Setup.exe from a Visual Basic folder to your application's distribution site. The user runs Setup.exe to install your application.

Setup.exe copies the bootstrap files, and then executes the main Setup program (usually named Setup1.exe) listed in Setup.lst.

Setup.lst :

The Package and Deployment Wizard creates the Setup.lst file. This file contains the list of files required by your application, and contains general information such as default folders and the required disk space.

The following example code illustrates what a sample Setup.lst file might contain:

[Bootstrap]

File1=1,,setup1.ex_,setup1.exe,$(WinPath),...

..

[Files]

File1=1,,GRID32.OC_,GRID32.OCX,$(WinSysPath),,$(Shared)..

..

[Setup]

Title=LoanSheet

DefaultDir=$(ProgramFiles)\Loan

Setup1.exe :

The Package and Deployment Wizard includes Setup1.exe, the main Setup program, in the .cab file that contains your application files. Setup1.exe copies and registers application files, and creates startup icons. Setup1.exe also increments the reference count for shared files in the registry.

St6Unst.Log :

The Setup program creates an application log file (St6Unst.log) that is copied to the application folder, and includes the following information:

Folders that were created.

Files that were installed. The log indicates if a file was not copied because a newer version of the file was already found on the disk.

Registry entries that were created.

Start menu entries that were created.

DLLs, .exe files, or .ocx files that were self-registered.

St6Unst.exe :

The Setup program also copies an application removal utility (St6Unst.exe) to the Windows folder. The application removal utility removes the application files and icons or groups, and it decrements the reference count for shared components. If a reference count is zero, the utility prompts the user to remove the shared component.

Note : The application removal utility depends on an accurate log file and an accurate registry entry to perform its function.

If your application uses a shared component that you know is already on the user’s system, you should still include the component with your Setup program. This ensures that the reference count for the component is incremented when the user installs your application.

To remove an application with either Microsoft Windows NT or Windows 98, click the Add/Remove Programs icon in the Control Panel.

Deploying An ActiveX control

If the ActiveX control will be used on an HTML page, there are a number of issues that should be taken into account, such as the security of the control and proper use of the control by other developers.

Option for Distributing Control :

The way you distribute a control depends on how the control will be used. An ActiveX control can be used in many different types of applications, such as Microsoft Office or Visual Basic applications, or as part of a Web site. You can either distribute it as a compiled component, or include the source code of the control as part of your application.

Distributing Controls as Compiled Components :

To distribute a compiled control (.ocx file) with an application, you must create ActiveX controls as public classes. Users of your control can then include the compiled control in the Setup program of their application.

The advantages of distributing a compiled control are:

You keep the implementation of the control confidential.

Users of your control cannot change the implementation of the control.

You can make bug fixes and feature upgrades to the control and then ship the newly compiled control to all users of the control.

Distributing Controls as Source Code :

You can also include a .ctl file in any Visual Basic project. When the application is compiled, the source code of the control is compiled as part of the application's executable file.

The advantages of distributing controls as source code are:

There is no .ocx file to distribute.

Debugging is easier because you only need to debug features of the specific application.

You don't have to worry about whether your application will work with future versions of the control, because the version your application uses is compiled as part of the application.

The disadvantages of distributing controls as source code are:

Fixing bugs in the control’s source code requires recompiling the entire application.

Multiple applications require additional disk space because each application includes all of the source code for a control.

Each time you use the source code in an application, there will be an opportunity to fix bugs or enhance the code. It may become difficult to keep track of which version of a control was used in which version of which application.

Adding a control to an HTML Pages :

If you want to distribute an ActiveX control over the Internet, you can use the Package and Deployment Wizard to create an Internet download for the control When you create an Internet download for a control, an HTML template is created. You can then modify the template to include download information for your users, and post the template as a Web site on the Internet. This template enables you to specify your control by using the <OBJECT> tag.

The <OBJECT> tag is an element of HTML that provides a standardized way to add objects to an HTML page. The HTML template created by the Package and Deployment Wizard contains the appropriate <OBJECT> tag for your ActiveX control.

Parameters of the <OBJECT> Tag

The <OBJECT> tag contains a number of parameters that define an object, its location, and how it appears on an HTML page.

This following example code shows how to use the parameters of the <OBJECT> tag:

<OBJECT

CLASSID="clsid:6A7A58F2-3DFC-11D0-A520-0080C776418A"

WIDTH=200

HEIGHT=200

ID=MyControl

CODEBASE="MySetup.cab#version=1,0,0,0">

</OBJECT>

The following table lists some of the standard parameters used with the<OBJECT> tag.

Parameter Definition

CLASSID A unique class identifier used to identify the control. The ClassID is stored in the system registry.

ID A string that specifies the object name so you can refer to the object in code.

CODEBASE A Uniform Resource Locator (URL) that points to a file containing the implementation of an object. For Visual Basic controls, you specify a URL that points to your .cab file, relative to the location of your HTML page. If the HTML page and .cab file are in the same folder on your Web server, the CODEBASE parameter refers to the name of the .cab file.

Licensing an ActiveX Control :

To protect your ActiveX controls, Visual Basic provides licensing capabilities. Licensing your controls prevents other developers from using an instance of your control to create their own control. You can include licensing protection for any controls you want to distribute on the Internet, as well as providing licensing for ActiveX controls distributed as stand-alone components.

Licensing Controls for Standard Distribution :

You can use Visual Basic to create licensed ActiveX controls. A licensed control contains a key that prevents it from being used at design time. This prevents other developers from including your control as part of their application without obtaining its license.

Adding Licensing to a Control

To add licensing to a control, select the Require License Key option in the Project Properties dialog box, as shown in the following illustration.

When you compile the .ocx file, Visual Basic creates a .vbl file that contains the licensing key for your control.

The Package and Deployment Wizard creates a Setup program that automatically registers any .vbl files in the system registry. When a user runs the Setup program, the default option for a .vbl file is Do not install this file. This is because you usually want the end-user to have the license file registered but not installed on their computer. This option ensures that you can include your controls in applications you distribute, but users of the application will only be able to access the run-time version of the control.

Using Licensed Constituent Controls :

If you use a licensed constituent control as a part of a control that you build, you must require developers using your control to have the constituent control installed, or ask that the constituent control vendor include the licensing key with their control's Setup program.

Licensing Controls for the Internet :

Licensing a control for distribution on the Internet is different from licensing a control as part of a stand-alone application. Internet licensing involves the following two steps:

1. Create a license package (.lpk) file.

When you license a control for use on a Web page, you create a licensing package file. This file stores the run-time licensing information for all components on the page.

2. Create a reference to the licensing package file on your HTML page.

When a user attempts to use a licensed control on a Web page, the Internet Explorer License Manager checks the information in the .lpk file to ensure that the proper license is being used. If someone tries to use your control on a Web page that does not include the .lpk file, the control will not appear on the page.

Creating an .LPK File :

You create a licensing package file by using the utility program Lpk_Tool.exe. This program is available as part of the Microsoft Internet Client SDK. The licensing information for all controls on a page must be in a single .lpk file.

Creating a Reference to an .lpk File :

You provide the name of the .lpk file in the HTML code of your Web page by using the License Manager object. The <OBJECT> tag is included in the sample HTML page created by the Package and Deployment Wizard. The following example code shows how to use an <OBJECT> tag for licensing:

<OBJECT CLASSID="clsid:5220cb21-c88d-11cf-b347-00aa00a28331">

<PARAM NAME="LPKPath" VALUE="MyLicenseFile.LPK">

</OBJECT>

Testing an .lpk File :

When you compile a licensed ActiveX control on your computer, the license information is written to your computer's registry. The control will load properly on your computer without using the .lpk file.

To make sure your control's licensing functionality works correctly, you should test it on a local computer before distributing it over the Internet. To test the licensing functionality, test it on a separate computer or remove the license information from your computer's system registry.

Signing an ActiveX control :

Because ActiveX controls can pose a security risk, a user can set browser options to only download controls that have been digitally signed by certain authors. If a control is not signed, or is signed by an author the user does not trust, the browser will not download and run the control.

To identify your control and assure users that the code has not been modified since it was signed, you can add a digital signature to your code. You add a digital signature by using the Authenticode technology, which is derived from public-key signature algorithms.

To sign your code, you work with a certificate authority (CA) to obtain a digital certificate, which provides users with information about the author of a control. The CA provides and renews your certificate, authenticates identity, and handles legal and liability issues when security is broken.

Signing Code :

To sign code by adding a digital signature, you follow these steps:

1. Apply for a digital certificate over the Internet from a certificate authority.

2. Install the ActiveX Software Development Kit (SDK).

The ActiveX SDK provides the tools and documentation necessary for code signing.

3. Sign the files.

Use the Signcode.exe application included in the ActiveX SDK to apply your digital certificate to your code. Although you can sign most types of executable files, you will probably want to sign .cab files in particular because this applies the signature to the complete collection of compressed files.

Packaging for a control for the Internet :

When you use an ActiveX control in a standard Visual Basic application, the control is installed on the user's computer when the user runs the Setup program for your application. When you use an ActiveX control on an HTML page, the control is downloaded from the Internet and registered on the user's computer when the user requests the Web page. Once the control is downloaded and registered, it remains on the user's computer and does not need to be downloaded again on subsequent requests for that page.

To make sure that your control can be downloaded from the Internet, you must package the control so it can be used in the HTML environment.

Using the Package and Deployment Wizard :

The Package and Deployment Wizard handles most of the work involved with placing a control on a Web page, including the following tasks:

Creating a .cab file.

Marking your control as safe for scripting and initialization.

Building an HTML template for using your control.

Creating a .cab File :

When you use an ActiveX control on a Web page, the control must reside on an Internet server along with any dependent files or help information.

To simplify the distribution and installation of these files over the Internet, ActiveX controls can be compressed into a single .cab file. The Package and Deployment Wizard in Visual Basic can create this .cab file for you.

Marking a Control as Safe :

A control is considered safe when it handles script and data passed to it during initialization in such a way that a malicious script or data cannot damage a user's computer.

When you are confident that your control's properties and methods cannot be used maliciously, you can use the Package and Deployment Wizard to mark your control as safe. In marking a control as safe for scripting, you are asserting that the control cannot do any damage, such as reformatting a hard drive, with an HTML script. Marking an ActiveX control as safe for initialization indicates that it cannot do any damage during initialization. In addition, you are guaranteeing that downloading your control will never corrupt a user’s computer or obtain unauthorized information from the computer.

Building an HTML Template for Using The Control :

When you create an Internet download for a control, the Package and Deployment Wizard creates an HTML template for you. You can modify the template to include download information for your users, and then post the template as a Web site on the Internet. This template includes a reference to your control by using the <OBJECT> tag.

Chapter 8

Optimizing the Applications

An Application is fine – tuned or Optimized before it can be distributed. Fine – Tuning of an application is done to improve the speed of the application, or to make it easier to internationalize, or to include online documentation to describe the functionality the application provides. If an ActiveX control is developed, then the author may want to license the control to regulate its use by other developers. If a control is to be distributed over the Internet, security issues need to be tracked down

Optimizing an application means, improving its run-time speed and memory usage. The Author may also want to fine-tune the application's usability. For example, code can be added, so that the developers can save their current preferences and working environment settings. In subsequent sessions, users will not have to reconfigure their application at startup.

PROJECT PROPERTIES :

Project Settings are accessed through the VB Properties Menu Option Under the Project Menu or from the Popup Menu comes after Right Clicking the Project Name in the Project Explorer Window.

Project Type :

Reflects the type of Project Template chosen. It could by Standard Exe, AciveX DLL, ActiveX Exe, or ActiveX Control.

Startup Object :

Determines when the application runs which Object is to execute first. Standard Exe Projects require a Startup Object. It can be any Form in the Project or a Sub Main. I f any Form is Chosen as the startup Object then that form initialized & gets loaded, when the application starts running.

If Sub Main is selected as the startup Object then the Main Sub – Routine in the Standard Module ( Which is included ) runs first.

ActiveX Servers do not require a Startup Object. In that case None Option can be specified or Sub Main can also be specified. However, Sub Main will not be executed until the first Object is created y the Server. Once the Server is loaded, the Sub Main will not run again until the Server is Reloaded again. If an ActiveX Server is to display a form when the application runs, then Sub Main may be selected as the Startup Object and inside it there should be a statement to Show the Form.

Project Name :

This Project Name is given to the Project by which it can be referenced inside Visual Basic Codes.

Project Description :

This is used by the Object Browser to describe the Component.

Help File Name :

The Help File Name is the name of the Help File for the Project. The Help File can be a Windows Help File ( *.HLP) or a HTML Help File ( *.CHM).

Help Context ID :

It represents the help context that is called when a help is requested by the users on the Component from the Object Browser.

Upgrade ActiveX Controls :

This Option tells Visual Basic to Upgrade old ActiveX Controls with the newer versions available.

Require License Key :

This Option forces a License key to have if one wants to distribute the ActiveX control.

Unattended Execution :

This option indicates that there is no need to be interactive while the application is running. The application will run in the Background.

Threading Model :

This option indicates the Threading Model for the ActiveX Components.

Retain In Memory :

Generally, when a Component is no longer in use, it is released from the memory and when ever it is required again it is loaded into memory. This option enables the component to remain in the memory even if there is no use of it currently.

Tuning Application Performance :

Optimizing your application means making sure it is as efficient as possible. You optimize your application throughout the development process, starting with the design phase. A poorly designed application may run slowly, no matter what you do to try to improve performance.

Optimization is a tradeoff. If you improve one area of performance, you can cause poorer performance in another area. For example, if you keep forms loaded but hidden, they will be displayed quickly, but they will consume memory while they are loaded.

If your user's computer does not have enough memory, your application may run more slowly. Determine the factors that are most important to your user, and develop your application accordingly.

Optimizing Speed :

To improve the speed of your application, consider the following techniques.

Optimizing Actual Speed

The following suggestions describe how to optimize the speed of your application:

Some data types are faster at calculation speed than others. Use the simplest data type possible.

Accessing a variable is faster than accessing a property. If you are accessing a property in a loop, set the property to a variable first, and then use the variable in the loop.

Optimizing Apparent Speed

The following techniques will make your application appear faster to the user:

Use progress indicators to inform the user of the status of a task.

Use a mouse cursor, such as the hourglass cursor, to indicate that processing is occurring.

Optimizing Display Speed

To make display operations faster, use the following techniques:

Use the form’s AutoRedraw property appropriately.

If your application generates complex graphics that change frequently, you will get better performance if you set AutoRedraw to False, and handle repainting graphics manually.

Use an Image control instead of a PictureBox control.

An Image control requires less overhead than a PictureBox. If you only need to display a picture and respond to a Click event, use an Image control.

If a form is used frequently, keep the form hidden rather than unloaded. A hidden form displays more quickly than an unloaded form.

Reducing Memory Size :

To reclaim memory from an application, consider the following suggestions:

Reclaim data from strings

When you no longer need the data in a long string, set the string to " " to reclaim the memory used by the string. When you no longer need the data in a dynamic array, use Erase or ReDim Preserve to discard unneeded data, and reclaim the memory used by the array. Erase eliminates an array; ReDim Preserve shrinks the size of the array without losing the data in the array.

Reclaim data from pictures

When you no longer need the picture displayed in a PictureBox object, use the LoadPicture function with an empty string parameter to clear the object.

Compiling to Native Code :

You can compile your code either to standard Visual Basic Pseudocode ( p-code ) format or to native code format.

P-code is an intermediate step between the high-level instructions of a Visual Basic application and the low-level native code that your computer's processor executes. At run time, Visual Basic translates each p-code statement to native code. By compiling directly to native code format, you eliminate the intermediate p-code step. However, you will still need to distribute the Visual Basic run-time DLL with your application.

Native code compilation provides several options for optimizing and debugging that are not available with p-code. The performance of your application will benefit from native code compilation if your code includes complex mathematical calculations and looping.

To compile a project to native code

1. In the Project window, select the project you want to compile.

2. On the Project menu, click Project Properties.

3. In the Project Properties dialog box, click the Compile tab.

4. Select the compile options you want to use, and then click OK.

For additional native code options, click the Advanced Optimizations button.

Native Code Optimizations

There are several native code optimizations you can choose from.

Fast Code

Maximizes the speed of the compiled executable by instructing the compiler to favor speed over size.

Small Code

Minimizes the size of the compiled executable by instructing the compiler to favor size over speed.

Favor Pentium Pro

Optimizes executable for Pentium Pro (P6) processor. The executable will still run on earlier processors, but not as efficiently.

Create Symbolic Debug Info

Generates debugging information in the compiled executable. The executable can then be debugged with the Visual C++ or compatible debugger.

Optimizing an Executable :

You can further optimize a native code executable by clicking the Advanced Optimizations button on the Compile tab of the Project Properties dialog box, and selecting further optimization options.

The following advanced optimization options are available:

Assume No Aliasing

An alias is a name that refers to a memory location that is already referred to by a different name. This occurs when using ByRef arguments that refer to the same variable in two ways.

If you do not use aliasing you can turn on this optimization and the compiler will create faster code.

Remove Array Bounds Checks

Turns off checking for valid array indexes and the correct number of array dimensions.

This will create code that does faster array manipulations. However, if your program accesses an array with an index that is out of bounds, unexpected behavior or program crashes may occur.

Remove Integer Overflow Checks

Turns off checking to insure that numeric values assigned to integer variables (Byte, Integer, Long, and Currency) are within the correct range for the data type.

This will speed up integer calculations. However, if data type capacities are overflowed, no error will be returned, and incorrect results may occur.

Remove Floating Point Error Checks

Turns off checking to insure that numeric values assigned to floating-point variables (Single and Double) are within the correct range for the data type, and that division by zero or other invalid operations do not occur.

This will speed up floating-point calculations. However, if data type capacities are overflowed, no error will be returned, and incorrect results may occur.

Allow Unrounded Floating Point Operations

Allows the computer to compare the results of floating-point expressions without first rounding those results to the correct precision.

Comparisons are more efficient without rounding, so this option will speed up some floating-point operations. However, this might introduce errors because floating-point numbers are stored at a higher precision than expected.

Do not use this option if you perform comparisons of the results of floating-point expressions.

Remove Safe Pentium FDIV Checks

Turns off generation of special code to check for the floating-point division bug in some Pentium processors.

Saving Application Setting :

You can make your applications easier to use by saving information about user activity or preferences each time a user runs your application. You can then use this information in subsequent sessions. For example, you can save the name of the last database the user opened, and then use that name as the default database the next time your user opens a database.

In Windows 3.1 and earlier, program settings were commonly stored in .ini files. In Windows NT and Windows 95, program settings are stored in the registry.

To save and retrieve application settings, you can use the Visual Basic statements SaveSetting and GetSetting.

Using SaveSetting :

To write an entry to the registry, use the SaveSetting function with the following syntax:

SaveSetting (appname, section, key, setting)

The following example code saves customer ID information to the appropriate key in the Windows 98 registry:

Dim iCustID As Integer

Private Sub Form_Unload()

iCustID = CInt(txtCustID.Text)

SaveSetting _

"OrderApp", "CustSection", "CustID", iCustID

End Sub

Using GetSetting :

To read a setting from the registry, use the GetSetting function with the following syntax:

GetSetting (appname, section, key, [default])

The following example code obtains customer ID information from the appropriate key in the Windows 95 registry. If there is no value for CustID in the registry, the value 0 is returned.

Dim iCustID As Integer

Private Sub Form_Load()

iCustID = GetSetting _

("OrderApp", "CustSection", "CustID", "0")

End Sub

Both GetSetting and SaveSetting use the following default location on Windows 95:

HKEY_CURRENT_USER\Software\VB and VBA Program Settings\<appname>\<section>

Both GetSetting and SaveSetting use the following default location on Windows NT:

HKEY_USERS\<user section>\Software\VB and VBA Program Settings\<appname>\<section>

To add your own hierarchy of data in the registry, add directory structure to the Section argument of GetSetting and SaveSetting. You can also remove a setting in the registry by using DeleteSetting, or retrieve a whole section of the registry by using GetAllSettings. For more information about managing application settings in the registry, read the article "Managing Application Settings" in Visual Basic Help.

 

Popular Posts

Man Behind This Blog