Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Articles
Search: 

Office XP smart tags: a VFP look
Alexander Golovlev, September 1, 2002
Hussars Very often VFP applications are associated with Microsoft Office programs. Users want to use the formatting abilities of MS Word to create documents, send letters using Outlook and to carry out statistical analysis of data in Excel. "Smart tags" is a new technology used in O...
Hussars
Very often VFP applications are associated with Microsoft Office programs. Users want to use the formatting abilities of MS Word to create documents, send letters using Outlook and to carry out statistical analysis of data in Excel. "Smart tags" is a new technology used in Office XP, allowing simpler access to VFP applications from Office programs. This new feature is available in Word, Excel, Outlook (when you use Word as an e-mail editor) and Internet Explorer (when one of the above-mentioned applications is installed on your computer).

Smart tag technology enables the real time, dynamic recognition of user input and provides a set of relevant user actions based on the text that was entered and subsequently recognized. For example, it is possible to develop a smart tag for a sales department, which will recognize product codes in the text of a document or from a letter obtained from a client. You can then obtain information about the current price or quantity on hand of a product using this methodology. If you have become interested, let's have a look at how at works.


Figure 1. The SmartTagMOSTLGenerator.xlt spreadsheet template.

Creating smart tags using XML

There are two ways to create smart tags. The simplest is based on XML files and provided by the Microsoft Office Smart Tag List (MOSTL) tool. All that is required is to create an XML list description file (Smart Tag List Definition Files) and place it into one of the following directories:

  • drive:\Program Files\Common Files\Microsoft Shared\Smart Tag\Lists
  • drive:\Documents and Settings\username\Application Data\Microsoft\Smart Tag Lists
  • Smart tag list directory, called "ListDirectory" in the registry
The description of XML syntax can be found in the Smart Tag SDK. The XML file can also be created manually. We will take advantage of the Smart Tag MOSTL Generator, which is part of the Smart Tag Tools. The MOSTL Generator is implemented as an XLT-template and is just a typical application, implemented in the Excel environment (Figure1). The XML description consists of three parts - common properties, description of actions and list of terms.

The Properties Section collects basic information about the smart tag. The Actions Section represents a list of actions for this smart tag. First, a unique ID is needed for each action. This ID can be any string as long as it is unique. A caption is needed for each action to tell users what the specific action will do. These captions are displayed to users when they select a smart tag in a document (see Figure 3). Finally, a URL for the associated action is defined. The Recognizer Terms Section contains a list of terms to be recognized.

After this information is gathered, the user clicks the Export MOSTL XML button. Using a simple Visual Basic for Applications (VBA) routine, the MOSTL XML file is published to the proper Office XP directory.


Figure 2. A list of installed smart tags in Microsoft Word.

When the XML file is created and placed in the appropriate directory of Office XP, the new smart tag should appear in the list of installed smart tags (Figure 2). Check the appropriate checkbox for the new tag, so we can see the tag in operation. For this purpose, we will type in Word any word from the list of terms, for example 'FoxPro', and we will enter a blank space for activation of the process of recognition. After that the word 'FoxPro' will be underlined by purple dots. When the user rests the mouse pointer on the word, the Smart Tag Action button will be displayed. After clicking the Smart Tag Actions button, a menu will appear that allows users to select FoxPro Web sites (Figure 3).


Figure 3. FoxPro Web Sites smart tag in action.

I'd like to mention that URL in XML description file can contain special terms {LCID} and {TEXT}. For example, we can create a Stock Quotes Smart Tag which will recognize stock ticker symbols (MSFT for instance) in text of document and will provide a link to appropriate page on MSN Money web site:

http://moneycentral.msn.com/scripts/webquote.dll?ipage=qd&Symbol={TEXT}

Smart tag DLLs

The example above showed how to create smart tags which allow the user to browse a Web site. But what if we want to create a more complex task like the one suggested at the beginning of the article? For example, suppose we want the smart tag to recognize the identification code of the customer from our database and offer to display his current balance or to insert his address into the document. For this purpose, we should develop a smart tag DLL.

Smart tag DLL is a COM DLL which is comprised of two objects: a recognizer and an action. A Recognizer should determine the portion of the document which is in smart tags. An Action object is responsible for execution of commands which can be executed for recognized text.

For this kind of task, Visual FoxPro seems to be a good choice. We need to make a COM DLL which will work well with strings for recognition of the text and carry out an effective search in the database in order to return the information. However, if you have downloaded and installed Smart Tag SDK, then you know that there are a lot of samples for Visual Basic and Visual C++ but not for Visual FoxPro. Let's try to fill this white space. For example, we shall create a smart tag DLL which will recognize customer IDs from a table (customers.dbf) and will show the information about a customer as well as add the address block in the beginning of the Word document.

It is known from documentation that Recognizer and Action objects must implement ISmartTagRecognizer and ISmartTagAction interfaces respectively. But how can we do this? The answer is simple - with the help of the IMPLEMENTS keyword which appeared in

VFP7. The usage of Object Browser greatly simplifies our task.

Let's create a new project and name it customer.pjx and add to it an empty program file named customer.prg. Then we'll launch Object Browser and open Microsoft Smart Tags 1.0 Type Library (C:\program files\common files\microsoft shared\smart tag\mstag.tlb). The appearance of this library in Object Browser is shown in Figure 4.


Figure 4. Smart Tag type library in Object Browser.

In order to create Recognizer and Action classes, drag ISmartTagRecognizer and IsmartTagAction interfaces from the Object Browser and drop them in the editor window. After removing unnecessary lines of code

x=NEWOBJECT("myclass")
we only have to write the implementation of methods for these classes.

Implementing Recognizer

The full source code for this class can be found in the archive file. Here is the main part of Recognizer object implementation. It's a Recognize method. This method splits an input text into separate words, looks for words in Cust_id field and, if found, marks a word within text as a smart tag.

PROCEDURE ISmartTagRecognizer_Recognize(Text AS STRING, DataType AS VARIANT,;
 LocaleID AS Integer, RecognizerSite AS VARIANT) AS VOID
Local lnWords as Integer, lnWordStart as Integer, lnWordLen as Integer
Local stlPropertyBag as SmartTagLib.ISmartTagProperties
* Break the text into words
lcTempText = ' ' + Chrtran(Upper(Text), '!(){}[]:;,./\?' + Chr(9), Space(15)) + ' '

* Loop through words
lnWords = Occurs(' ', lcTempText) - 1
for lnWord = 1 to lnWords
   * Deteremine the word and where it starts and ends
   lnWordStart = At(' ', lcTempText, lnWord) + 1
   lcWord = Substr(lcTempText, lnWordStart, At(' ', lcTempText, lnWord + 1) - lnWordStart)
   lnWordLen = Len(lcWord)
   If !Empty(lcWord) And Seek(lcWord, "Customer", "Cust_id")
      stlPropertyBag = RecognizerSite.GetNewPropertyBag()
      RecognizerSite.CommitSmartTag("hussars-team-com#customers", lnWordStart-1, lnWordLen,;
       stlPropertyBag)
   EndIf
EndFor
ENDPROC

The code in ProgId, Name and Desc properties of recognizer object is intended to provide a unique ID, title and description. Finally, we have to add code to the SmartTagCount, SmartTagName and SmartTagDownload properties in order to provide the number of smart tag types, the list of types and the additional download location.

Implementing Action

The VerbCaptionFromID property of Action object returns the caption for action as it appears in smart tag popup menu. We can use LocaleID parameter for providing localized captions for actions and _ApplicationName for changing the behaviour of object in different Office applications. In code for this property we'll use an _ApplicationName parameter for enabling the "Insert Address Block" item only in Word applications. The item will not be shown when this property returns an empty string.

PROCEDURE ISmartTagAction_get_VerbCaptionFromID(VerbID AS Integer,;
 _ApplicationName AS STRING, LocaleID AS Integer) AS STRING
DO CASE
Case VerbID = 1
   Return "Show Information"
Case VerbID = 2 And Left(_ApplicationName, 4) = "Word"
   Return "Insert Address Block"
Otherwise
   Return ""
ENDCASE
ENDPROC

The InvokeVerb method is called when appropriate action is selected from the menu. For the first item this method generates an HTML page with customer information and list of orders for this customer. This page is shown in the Internet Explorer window. When the second item is selected, the address of customer is inserted into the top of the current document.

Manipulation with Office objects is possible due to Target parameter. This parameter represents a reference to the application-specific object that is responsible for calling the smart tag. In Excel, it is an Excel range object that points to the cell that the smart tag was attached to. In Word, it is a Word range object that wraps around the block of text that the smart tag refers to.

PROCEDURE ISmartTagAction_InvokeVerb(VerbID AS Integer, _ApplicationName AS STRING,;
 Target AS VARIANT, Properties AS VARIANT, Text AS STRING, Xml AS STRING) AS VOID
DO CASE
Case VerbID = 1
   This.ShowInfo(Upper(Text))
Case VerbID = 2 And Left(_ApplicationName, 4) = "Word"
   This.InsertAddress(Upper(Text), Target)
EndCase
ENDPROC

The code in the ProgId, Name and Desc properies provides a unique ID, title and description for our smart tag action. SmartTagCount, SmartTagName and SmartTagCaption properies returns the number, names and captions of the matching tag types. To inform the corresponding smart tag recognizer of the number, names and IDs of the supported actions we have to add code to the VerbCount, VerbID, VerbCaptionFromID and VerbNameFromID properties.

Debugging, registering and testing

Once you have implemented all 18 methods of smart tag objects, you can compile a project as a COM server (DLL), and then register it on your computer. In order for our DLL to be recognized by the Office application, it is necessary to create subkeys with a name matching the unique identifiers of our objects in the following registry subkeys:

  • HKCU\Software\Microsoft\Office\Common\Smart Tag\Recognizers\
  • HKCU\Software\Microsoft\Office\Common\Smart Tag\Actions\
The ProgIDs can be used as unique identifiers of the classes created by us (i.e. "Customers.SmartTagRecognizer" and "Customers.SmartTagAction"). However, Microsoft recommends (in KB article Q294422) to use the CLSIDs instead. Therefore, we will create the .reg file into which we will insert CLSIDs of our classes, which are copied from .vbr file.

Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Office\Common\Smart Tag\Actions\{8383B4BA-068F-4DDF-B56C-69E25BA53AC3}] @=""
[HKEY_CURRENT_USER\Software\Microsoft\Office\Common\Smart Tag\Recognizers\{B77269E0-455F-4BDD-B4A3-7322CDA7CABF}] @=""

Although usage of .reg file is acceptable during development, in order to install DLL on user's computers consider using a tool such as the Microsoft Visual Studio Installer or InstallShield to create a registration package.

Now we can test to see if our classes work in Office applications. However, it is far from programs being always written without errors. Usually, COM class includes Error method which returns to the calling program the information on an error with the help of the VFP function COMRETURNERROR(). But Word or Excel does not show the error message, originating in smart tag DLLs. Therefore, in the Error method we will write data on originating errors into the error.log file.

Procedure Error(pnErrorNum, pcMethodName, pnLineNum)
LOCAL lcErrorMess
lcErrorMess = ;
 "Date & Time : " + TTOC(Datetime()) + CRLF + ;
 "Error Number: " + TRANSFORM(pnErrorNum) + CRLF + ;
 "Method Name : " + pcMethodName + CRLF + ;
 "Line Number : " + TRANSFORM(pnLineNum) + CRLF + ;
 "Message     : " + Message() + CRLF
* Append to error log text file
STRTOFILE(lcErrorMess + CRLF, JustPath(_VFP.ServerName)+"\error.log", .T.)
EndProc

Now we are ready to test the DLL. Let's start Word XP or Excel XP and type any customer ID from the customers database (ALFKI, for example). If all is done correctly, we will see a word underlined with purple dots in Word or a purple triangle in the right lower corner of Excel's cell (Figures 5, 6).

Figures 5, 6. The Customers smart tag in Word and Excel.

Rest your mouse pointer on these purple dots or the purple triangle and the Smart Tag Actions button will appear. Then click the arrow to activate the actions menu. Click Show Information. Internet Explorer will open the page with customer information and list of orders (Figure 7). Note that in Word there is a second choice: Insert Address Block which is not present in Excel. Click Insert Address Block. The customer name and address will appear at the top of the Word document.


Figure 7. HTML page with customer information.

Conclusion

I have briefly shown two ways of creating smart tags in Office XP. It was shown that Visual FoxPro can be succesfully used in development of smart tag DLLs. This opens the new possibilities of the integration of VFP applications with Office XP programs. The Smart Tags SDK provides additional information about using predefined recognizers (names, addresses, phones, stock ticker symbols, etc.), multi-language support, deployment and updating in a corporate, desktop or Internet scenario.

Links

Download code for this article

Microsoft Office XP Smart Tag SDK 1.1

Advanced Smart Tag Tools

Developing Simple Smart Tags

Alexander Golovlev, Epam Systems
Visual C++, ATL/WTL, C#, ASP.NET, WinForms, MS SQL

Vlad Grynchyshyn, Soft Serve
Vlad Grynchyshyn is senior developer and project manager at the Ukrainian company "Soft Serve Ltd.", that provides custom-developed software solutions in several areas with use of wide range of development tools and languages. Vlad works in the MS Solutions department of the company, and has experience working with many MS development tools, components, utilities and documentation. Most experience is related to Visual FoxPro, MS SQL Server, Visual Studio and Visual Basic. He is active member of Visual FoxPro and SQL Server community, author of several articles for Universal Thread WEB site and other VFP community forums. He was MS MVP 2001-2002. He has a MS MCP certificate in Visual FoxPro area.

Vladimir Zhuravlev, Institute of the Physics of Earth,Russia
Vladimir Zhuravlev graduated from Moscow Physical Technical Institute in 1976 as an engineer - physicist. He obtained a PHD in math and physics in 1981. He has written more than 65 scientific papers. He specializes in electrical deep sounding, seismic catalogues, earthquakes/ blasts detections and long standing temporal serial analysis. He is a head science researcher at Institute of the Earth physics and a head programmer at Metroreclama Company. VNIIA head science researcher. He has been using Visual FoxPro since August 1995. He participated in 25 VFP projects, including VFP-Oracle, VFP-Interbase, VFP-MS SQL server. He has been a member of the Universal Thread VFP World-Wide Tournament winning team. MVP 2005-2011, www.foxclub.ru doamin owner , VFP instructor of Interface and Soft line companies. He can be reached at vztvertsa@mtu-net.ru Life stories on Russian are on http://craneboba.livejournal.com/, http://craneboba.livejournal.com/?skip=10, http://craneboba.livejournal.com/?skip=20