VBA and the Internet - Welcome | AUGI - Autodesk User ... and the... · Application Development...

12
Application Development with VBA and the Interne t Autodesk University 2003— Jerry Winters Pg. 1 CP23-3 Application Development with VBA and the Internet CP23-3 Presented by Jerry Winters About this Class We will discover ways VBA can be used to make the Internet and Internet technologies more useful for AutoCAD users. About the Instructor Jerry Winters has been using AutoCAD since 1988. He has written several books on programming AutoCAD with VBA and will be releasing his AutoCAD 2004 VBA book soon. Jerry provides VBA training as well as customization services for customers all over the United States as well as other countries on Earth. He has yet to teach on other planets in the solar system but is not counting out the possibility in the future. This is his second year teaching at Autodesk University. Had his 5th son, Nathan not been born the night before AU 2001, this would have been his third year. His first daughter, Olivia was born October 28th, 2003, so he is very happy to be here this year. He has been happily married for 12 years. If you are counting, that makes 5 sons, 1 daughter, and 1 wife. Also, 8 chickens, 1 cat, 1 turkey named Thanksgiving (he isn’ t feeling very well) and 1 turkey named Christmas (she is very cold right now). Jerry and his 3 oldest sons hold Tae Kwon Do Black Belts. To contact Jerry, please email him at [email protected] or visit his website: www.vbcad.com

Transcript of VBA and the Internet - Welcome | AUGI - Autodesk User ... and the... · Application Development...

A p p l i c a t i o n D e v e l o p m e n t w i t h V B A a n d t h e I n t e r n e t A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 1 CP23-3

Application Development with VBA and the Internet CP23-3

Presented by Jerry Winters About this Class We will discover ways VBA can be used to make the Internet and Internet technologies more useful for AutoCAD users. About the Instructor Jerry Winters has been using AutoCAD since 1988. He has written several books on programming AutoCAD with VBA and will be releasing his AutoCAD 2004 VBA book soon. Jerry provides VBA training as well as customization services for customers all over the United States as well as other countries on Earth. He has yet to teach on other planets in the solar system but is not counting out the possibility in the future. This is his second year teaching at Autodesk University. Had his 5th son, Nathan not been born the night before AU 2001, this would have been his third year. His first daughter, Olivia was born October 28th, 2003, so he is very happy to be here this year. He has been happily married for 12 years. If you are counting, that makes 5 sons, 1 daughter, and 1 wife. Also, 8 chickens, 1 cat, 1 turkey named Thanksgiving (he isn’t feeling very well) and 1 turkey named Christmas (she is very cold right now). Jerry and his 3 oldest sons hold Tae Kwon Do Black Belts. To contact Jerry, please email him at [email protected] or visit his website: www.vbcad.com

A p p l i c a t i o n D e v e l o p m e n t w i t h V B A a n d t h e I n t e r n e t A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 2 CP23-3

GetRemoteFile GetRemoteFile allows you to get a file on a web server. As with most web browsing, the file is stored in a temporary location on your hard drive. GetRemoteFile tells you the file name (name and location) where the file is placed. You have the option of opening the file from the temporary storage location or copying it to a more permanent location.

Sub TestGetRemoteFile() Dim URLToGet As String Dim FName As String Dim FFile As Long Dim DestFile As String Dim FLine As String DestFile = "c:\test.htm" 'Destination File URLToGet = "http://puny2/index.htm" 'Web file to get 'Get the file. FName will hold the temporary location where the file is stored. ThisDrawing.Utility.GetRemoteFile URLToGet, FName, True 'Copy the file to a permanent location on your hard drive. FileCopy FName, DestFile 'Now, open the file and display the file in the Immediate Window FFile = FreeFile Open DestFile For Input As #FFile Line Input #FFile, fline While EOF(FFile) = False Debug.Print fline Line Input #FFile, fline Wend 'Close the file. Close #FFile End Sub

PutRemoteFile Don’t get me started. Last year I used AutoCAD 2000 because PutRemoteFile worked in A2K. Later versions of AutoCAD had bugs with this call. It looks like the same problem exists in AutoCAD 2004. Here is the sample code from the AutoCAD Help file:

Sub Example_PutRemoteFile() ' This example transfers a local file to a remote URL. Since this example ' relies on both a remote server name and a local file, you will have to ' modify both the DestURL and LocalFile variables below to run this example. Dim DestURL As String, LocalFile As String ' Define source and destination DestURL = "ftp://www.myserver.com/autocadfiles/" LocalFile = "c:\program files\autocad\sample\city map.dwg" ' Transfer local file to remote location ThisDrawing.Utility.PutRemoteFile DestURL, LocalFile MsgBox LocalFile & " was just transfered to: " & DestURL End Sub

A p p l i c a t i o n D e v e l o p m e n t w i t h V B A a n d t h e I n t e r n e t A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 3 CP23-3

Parsing Out a HTML File If we are going to get HTML files, we need an easy way to parse out the data we want. An HTML file contains a great deal of data we may not necessarily want. We will create a Class Module named ‘HTMLParse’. Here is the code in the ‘HTMLParse’ module.

Public HTMLText As String Public ParsedText As String Sub ResetParsed() ParsedText = HTMLText End Sub Sub ParseOut(NextString As String) Dim ParseLoc As Long ParseLoc = InStr(1, ParsedText, NextString) If ParseLoc > 0 Then ParsedText = Mid(ParsedText, ParseLoc + 1) End If End Sub Sub ParseEnd(EndString As String) Dim ParseLoc As Long ParseLoc = InStr(1, ParsedText, EndString) If ParseLoc > 0 Then ParsedText = Left(ParsedText, ParseLoc - 1) End If End Sub

This allows us to take a potentially large HTML file and take chunks of text off the front and end of the file. ResetParsed resets the variable ‘ParsedText’ to be the entire contents of the file. ParseOut changes the variable ‘ParsedText’ by taking the portion of the file out that proceeds the instance of the text string provided in ‘NextString’ parameter. ParseEnd is similar to ParseOut, only ParseEnd takes a chunk off the end of the file. Now that we have a way to parse out a file, let’s write a macro that parses out the file ‘index.htm’ on Puny2. Since the code will not all fit on this page, we will move to the next.

A p p l i c a t i o n D e v e l o p m e n t w i t h V B A a n d t h e I n t e r n e t A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 4 CP23-3

Sub TestGetRemoteFile2() Dim URLToGet As String Dim FName As String Dim FFile As Long Dim DestFile As String Dim MyHTML As New HTMLParse Dim FLine As String DestFile = "c:\test.htm" 'Destination File URLToGet = "http://puny2/index.htm" 'Web file to get 'Get the file. FName will hold the temporary location where the file is stored. ThisDrawing.Utility.GetRemoteFile URLToGet, FName, True 'Copy the file to a permanent location on your hard drive. FileCopy FName, DestFile 'Now, open the file and display the file in the Immediate Window FFile = FreeFile Open DestFile For Input As #FFile Line Input #FFile, FLine While EOF(FFile) = False 'Set up the HTMLText MyHTML.HTMLText = MyHTML.HTMLText & FLine Debug.Print FLine Line Input #FFile, FLine Wend 'Close the file. Close #FFile 'Prepare MyHTML MyHTML.ResetParsed 'Begin parsing out the file MyHTML.ParseOut "<b>" MyHTML.ParseOut "<b" MyHTML.ParseOut ">" 'Take end off of the file MyHTML.ParseEnd "<" 'Display Parsed Text MsgBox MyHTML.ParsedText End Sub

This is the actual HTML file our program sees. I have changed the font height of the items we find using our code. <html> <head> <meta http-equiv="Content-Language" content="en-us"> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <meta name="GENERATOR" content="Microsoft FrontPage 4.0"> <meta name="ProgId" content="FrontPage.Editor.Document"> <title>Welcome to Autodesk University 2003</title> </head> <body> <p>Welcome to Autodesk University 2003.</p> <p>I hope you enjoy this class.</p>

<p>Your friend, <b>Jerry</b></p> </body> </html>

A p p l i c a t i o n D e v e l o p m e n t w i t h V B A a n d t h e I n t e r n e t A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 5 CP23-3

Class Exercise 1: The Formica Website allows users to view sample chips. They constantly add colors and patterns to their product line so keeping up with their designs can be difficult. We want to quickly capture the names of each pattern and download the sample chip image to our local machine. We will also add the image name and ID number to a database. Sample URL: http://www.formica.com/colorchipdetails.jsp?chip_id=1 At this point, 635 different chip_ids exist. How long would it take you to browse to these 635 files, find the data you want, download the sample image, and enter the data into a database?

Entry # ParseOUT Value ParseEND Value

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Pattern Name Parsing

Entry # ParseOUT Value ParseEND Value

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Image Location Parsing

A p p l i c a t i o n D e v e l o p m e n t w i t h V B A a n d t h e I n t e r n e t A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 6 CP23-3

GPS Coordinates Parsed from Web Sample Data: "NV","102 Ranch","locale","Washoe",32,031,"393401N","1193008W",39.56694,-119.50222,"","",,,4275,,"","Patrick" "NV","171 Ac Pond-McGill Dam","dam","White Pine",32,033,"392554N","1144918W",39.43167,-114.82167,"","",,,,,"","McGill" "NV","1862 Overland","trail","Lander",32,015,"393029N","1170723W",39.50806,-117.12306,"","",,,5800,,"","Yankee Blade" "NV","23 Mile Reservoir","reservoir","Elko",32,007,"413148N","1142148W",41.53,-114.36333,"","",,,,,"","Delano Peak" Website URL to view pages with GPS Data: http://geonames.usgs.gov/stategaz/index.html Sample Code:

Sub GetGPSCoords() Dim MyFile As String MyFile = "c:\au2003\inet\NV_deci.csv" Dim FFile As Long FFile = FreeFile Open MyFile For Input As #FFile Dim LInput As String Dim SPT As Variant Line Input #FFile, LInput On Error Resume Next Dim LineNum As Long LineNum = 1 While EOF(FFile) = False 'And LineNum < 2500 SPT = Split(Trim(LInput), ",") Dim Lat As Double Dim Lon As Double Dim PName As String Dim PType As String Lat = SPT(8) Lon = SPT(9) PName = Replace(SPT(1), """", "") PType = Replace(SPT(2), """", "") PointData Lat, Lon, PName, PType, 1 / 256 Line Input #FFile, LInput LineNum = LineNum + 1 Wend Close #FFile MsgBox LineNum - 1 & " lines entered." End Sub Function PointData(Lat As Double, Lon As Double, Name As String, _ PType As String, BScale As Double) Dim InsPt(0 To 2) As Double InsPt(0) = Lon InsPt(1) = Lat Dim InsBlk As AcadBlockReference Set InsBlk = ThisDrawing.ModelSpace.InsertBlock(InsPt, "GPSPoint", _ BScale, BScale, BScale, 0) atts = InsBlk.GetAttributes atts(0).TextString = Name End Function

We already know how to download a file and save it to a dedicated location on our hard drives. In this example, we have saved a file to "c:\au2003\inet\NV_deci.csv" We open the file, parse out each line using the ‘Split’ command and insert a block at the specified location. AutoCAD MAP allows us to specify the units of the drawing to be in Lat/Lon Coordinates. MAP is not necessary, however.

A p p l i c a t i o n D e v e l o p m e n t w i t h V B A a n d t h e I n t e r n e t A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 7 CP23-3

Real-Time Data Acquisition We have seen how we can use data that has been posted to the Internet. These files may have been posted 10 minutes ago or 10 years ago. Wait. When was it that Al Gore invented the Internet? Was it more than 10 years ago? How about providing a mechanism where data can be posted to the Internet and that same data can be pulled into AutoCAD? Let’s do it! We need a database. We will name it ‘c:\au2003\inet\RealTimePoints.mdb’.

A table named ‘Points’ is added with fields: UniqueID AutoNumber PointName Text (255 chars) Lat Number(Double) Lon Number(Double) Next, we will create a file named ‘c:\udls\AU2003Points.udl’. Do this by creating a new TextDocument and changing the name to AU2003Points.udl You will be asked if you are sure you want to change the file name. Say ‘Yes’.

Now we have a database and a UDL file. The hardest part is over now. All we need to do is allow someone to enter data over the Internet and copy and paste existing code so AutoCAD will draw new data.

A p p l i c a t i o n D e v e l o p m e n t w i t h V B A a n d t h e I n t e r n e t A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 8 CP23-3

Now, double-click on the UDL file you just created. Change the driver (provider) as shown here: After selecting the correct provider and browse to the database we just created, click the ‘Test Connection’ button. If all is well, you should see the message box below:

Next, the web-based data entry screen: The code on the far left results in the web page shown here. We are keeping it very simple and very small so data can be entered using a PDA, laptop, or desktop.

We have three table fields we want to use: PTName, PTLat, and PTLon. We will now create a page that will accept this data and put it into a database.

Here is our ASP code. It opens the ‘Points’ table and adds a new record. It then populates the database with the entered data, updates the record, closes the table and the database. We redirect the user back to the data entry screen so the next point can be entered.

A p p l i c a t i o n D e v e l o p m e n t w i t h V B A a n d t h e I n t e r n e t A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 9 CP23-3

Getting AutoCAD to draw the entered points We are adding points to a database. This differs slightly from the GPS example we looked at previously. We can’t just enter a static web page URL and get the new points. We need one more ASP file and some VBA code. If we are not careful, we will draw the same points over and over. We need a mechanism to allow us to only get the new points. We will store the latest UniqueID retrieved in our AutoCAD drawing and only display points with a UniqueID larger than the one we have stored in our AutoCAD drawing.

Here is the ASP code. We supply a parameter named ‘HighID’ and we get back all entered points greater than the HighID we supply.

This is what the ‘retrievepoints.asp’ file looks like in a web browser with a couple of sample points entered. It doesn’t look very good because we want the data formatted for our code, not for our eyes. When you view the source of this page, you will see that we get one line per point entry and each value is delimited with the pipe symbol. I prefer using the pipe symbol to the comma because the comma is a common punctuation symbol and could appear in the point name.

Next, we need to write the VBA code to retrieve this page and save the HighID so the next time we attempt to retrieve this page, we only get the newly added points.

A p p l i c a t i o n D e v e l o p m e n t w i t h V B A a n d t h e I n t e r n e t A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 10 CP23-3

Function GetHighID() As Long Dim AppName As String Dim xdt As Variant Dim xdv As Variant AppName = "VBA-Inet" ThisDrawing.Layers("0").GetXData AppName, xdt, xdv Select Case VarType(xdt) Case 8194 GetHighID = CLng(xdv(1)) Case 0 GetHighID = 0 End Select End Function Sub SetHighID(HighID As Long) Dim xdt(0 To 1) As Integer Dim xdv(0 To 1) As Variant xdt(0) = 1001: xdv(0) = "VBA-Inet" xdt(1) = 1000: xdv(1) = CStr(HighID) ThisDrawing.Layers("0").SetXData xdt, xdv End Sub

The above procedure and function get and set the HighID in the drawing. We store it as Xdata on Layer “0” since it’s in all AutoCAD drawings. Next, we need to retrieve the file, insert the blocks, and set the HighID in the drawing.

Sub GetLIVECoords() Dim MyFile As String Dim PType As String ThisDrawing.Utility.GetRemoteFile "http://puny2/retrievepoints.asp?highid=" _ & GetHighID, MyFile, True Dim FFile As Long FFile = FreeFile Open MyFile For Input As #FFile Dim LInput As String Dim SPT As Variant On Error Resume Next Dim LineNum As Long LineNum = 1 While EOF(FFile) = False 'And LineNum < 2500 Line Input #FFile, LInput SPT = Split(Trim(LInput), "|") Dim Lat As Double Dim Lon As Double Dim PName As String Lat = SPT(2) Lon = SPT(3) PName = Replace(SPT(1), """", "") SetHighID CLng(SPT(0)) PType = "" PointData Lat, Lon, PName, PType, 1 LineNum = LineNum + 1 Wend Close #FFile MsgBox LineNum - 1 & " lines entered." End Sub

A p p l i c a t i o n D e v e l o p m e n t w i t h V B A a n d t h e I n t e r n e t A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 11 CP23-3

This concludes the exercises planned for this class. I hope you enjoyed the presentation. If you are reading this but did not attend the class, you missed out because we had a blast!!!!!! Attend Autodesk University next year and you will see what you have been missing. If you have problems with the code, feel free to email me and I will attempt to respond. Thank you for coming! Jerry Winters VB CAD [email protected] www.vbcad.com

A p p l i c a t i o n D e v e l o p m e n t w i t h V B A a n d t h e I n t e r n e t A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 12 CP23-3

This page left blank so you can get my autograph. If you think I am serious, you obviously were not in the class. See ya at AU in 2004 (I hope).