12
VBA and the Internet Presented by Jerry Winters Of VB CAD On November 29, 2001 Autodesk University 2001 Las Vegas, NV

VBA and the Internet - AUGI · them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier. • For the time being, I suggest

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: VBA and the Internet - AUGI · them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier. • For the time being, I suggest

VBA and the Internet

1

Presented by

Jerry Winters Of

V B C A D On November 29, 2001

Autodesk University 2001 Las Vegas, NV

Page 2: VBA and the Internet - AUGI · them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier. • For the time being, I suggest

VBA and the Internet

2

• The Internet—What is it? Not technically, but functionally. What do you use it for? Communication? Research? • This class will cover internet-related technologies available to the VBA developer.

• AutoCAD-embedded GetRemoteFile Function • AutoCAD-embedded PutRemoteFile Function • AutoCAD entity’s URL hyperlink • CDO (Collaboration Data Objects) • WinSock Control • ASP (Active Server Pages) • ADO (ActiveX Data Objects) • FSO (File System Objects)

• Protocols

• HTTP (Hyper Text Transmission Protocol) • FTP (File Transfer Protocol) • SMTP (Simple Mail Transfer Protocol) • POP (Post Office Protocol)

GetRemoteFile AutoCAD-specific VBA function to get a file located on a remote but accessible machine. Sub TestGetRemoteFile() Dim RF As String Dim WebFileName As String Dim WebLocation As String WebFileName = "test1.dwg" WebLocation = "http://www.vbcad.com/au" ThisDrawing.Utility.GetRemoteFile WebLocation & "/" & WebFileName, RF, True FileCopy RF, "c:\auinternet\" & WebFileName End Sub • File is copied to your local machine. The variable ‘RF’ above stores the location of the file on your local system. It is

normally placed in an Internet Temporary directory. It is a good idea to copy it to a different location so it can be easily found.

PutRemoteFile AutoCAD-Specific VBA function to put a file located on your local machine to a remote machine. Sub TestPutRemoteFile() Dim RF As String Dim WebFileName As String Dim WebLocation As String WebFileName = "test2.dwg" WebLocation = "ftp://dev/upload" ThisDrawing.Utility.PutRemoteFile WebLocation & "/" & WebFileName, _ "c:\auinternet\test1.dwg" End Sub • PutRemoteFile sounds like a companion function to GetRemoteFile. Autodesk even suggests this in AutoCAD’s

help file. Although the functionally, it could be considered a companion, a little work needs to be done to truly make it so. GetRemoteFile simply gets a file from a remote location. Generally, this is done without any other work because most directories on remote machines provide read writes to anonymous users. Putting files (not golfing the act of putt, but doing the act of put) is quite another issue.

Page 3: VBA and the Internet - AUGI · them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier. • For the time being, I suggest

VBA and the Internet

3

• The dialog shown here will meet your user if an attempt is made to put a file to a remote machine and the remote machine requires a username and password. In most FTP type operations, you can include the username and password as part of the URL and the software recognizes it.

• For example, I can use the URL ‘ftp://jerrywintersismyname:[email protected]’ and Internet

Explorer will recognize the username of ‘jerrywintersismyname’ and a password of ‘doingvbaismygame’ and log me right in. However, this does not work when using PutRemoteFile. So, if anyone knows anyone at Autodesk, ask them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier.

• For the time being, I suggest the creation of a write-only directory with anonymous access on your FTP site so PutRemoteFile will work without asking the user to type in a username and password.

• To make matters worse, look at the code below. Sub TestPutRemoteFile2() Dim RF As String Dim WebFileName As String Dim WebLocation As String WebFileName = "test2.dwg" WebLocation = "ftp://www.vbcad.com/www/au" ThisDrawing.Utility.PutRemoteFile WebLocation & "/" & WebFileName, _ "c:\auinternet\test1.dwg" ThisDrawing.Utility.PutRemoteFile WebLocation & "/" & WebFileName, _ "c:\auinternet\test1.dwg" End Sub

Notice how we are using PutRemoteFile twice? Guess how many times you get to enter a username and password? Uuuuuuuuuuuuuuuuuuuuuuuuugh! AutoCAD Entity URL Hyperlinks You can add a hyperlink to AutoCAD entities by using the Hyperlink command or by clicking on the ‘Insert Hyperlink’ icon. As your cursor passes over the entity, a little tool tip pops up. How is this done, you ask? You will have to turn the page to find out.

Page 4: VBA and the Internet - AUGI · them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier. • For the time being, I suggest

VBA and the Internet

4

• ‘Insert Hyperlink’ works through XData. The application name is ‘PE_URL’. As you can see in this image (the result of using the xdlist command), the URL is stored as well as the Tool Tip.

• The Insert Hyperlink command only allows for one hyperlink attachment to any single entity. Programmatically, we can put on much more than that.

Sub TestHyperlink() Dim SelEnt As AcadEntity Dim SelPt As Variant ThisDrawing.Utility.GetEntity SelEnt, SelPt, vbCrLf & "Select an entity: " Dim MyLink As AcadHyperlink Set MyLink = SelEnt.Hyperlinks.Add("") MyLink.URL = "http://www.microsoft.com" MyLink.URLDescription = "Check this out!" End Sub • This code works well. If you run it

twice on the same object, you get another hyperlink added to the entity, but AutoCAD commands will still only reveal one hyperlink. Goofy? Maybe not. It does allow developers to do some pretty cool stuff.

• Structuring multiple hyperlinks can provide extended functionality.

• Hyperlink 1: General Information.

• Hyperlink 2: Specification • Hyperlink 3: Picture • Hyperlink 4: Materials

Sub TestHyperlink3() Dim SelEnt As AcadEntity Dim SelPt As Variant ThisDrawing.Utility.GetEntity SelEnt, SelPt, vbCrLf & "Select an entity: " Dim MyLink As AcadHyperlink Set MyLink = SelEnt.Hyperlinks.Add("") MyLink.URL = "http://www.collegedale.com/concept_2.htm" MyLink.URLDescription = "General Information" Set MyLink = Nothing Set MyLink = SelEnt.Hyperlinks.Add("") MyLink.URL = "http://www.collegedale.com/zip/concept_2.zip" MyLink.URLDescription = "Specifications" Set MyLink = Nothing Set MyLink = SelEnt.Hyperlinks.Add("") MyLink.URL = "http://www.collegedale.com/images/Concept2.jpg" MyLink.URLDescription = "Picture" Set MyLink = Nothing Set MyLink = SelEnt.Hyperlinks.Add("") MyLink.URL = "http://www.collegedale.com/material_finish.htm" MyLink.URLDescription = "Materials" Set MyLink = Nothing End Sub

Page 5: VBA and the Internet - AUGI · them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier. • For the time being, I suggest

VBA and the Internet

5

• The image to the right shows the XDList result of the previous macro. Now, let’s write a macro that shows the appropriate file.

• ShellExecute is a Windows API function that allows you to specify the file you want to see, and it launches the appropriate application with the file in it. The function needs to be declared in your General Declarations area of a Code Module so you can use it.

Public Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, _ ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long Sub ShowGeneral() Dim SelEnt As AcadEntity Dim SelPt As Variant ThisDrawing.Utility.GetEntity SelEnt, SelPt, vbCrLf & "Select an entity: " Dim MyLink As AcadHyperlink Set MyLink = SelEnt.Hyperlinks(0) ShellExecute 0, "OPEN", MyLink.URL, "", "", 1 End Sub • The above macro gets the first hyperlink of an entity (SelEnt.Hyperlinks(0)) and uses it’s URL property in the

ShellExecute Function call. • How do we get the Specifications? Retrieve the second hyperlink (SelEnt.Hyperlinks(1)) Sub ShowSpecs() Dim SelEnt As AcadEntity Dim SelPt As Variant ThisDrawing.Utility.GetEntity SelEnt, SelPt, vbCrLf & "Select an entity: " Dim MyLink As AcadHyperlink Set MyLink = SelEnt.Hyperlinks(1) Dim WindHnd As Long ShellExecute WindHnd, "OPEN", MyLink.URL, "", "", 1 End Sub Sub ShowPicture() Dim SelEnt As AcadEntity Dim SelPt As Variant ThisDrawing.Utility.GetEntity SelEnt, SelPt, vbCrLf & "Select an entity: " Dim MyLink As AcadHyperlink Set MyLink = SelEnt.Hyperlinks(2) Dim WindHnd As Long ShellExecute WindHnd, "OPEN", MyLink.URL, "", "", 1 End Sub Sub ShowMaterials() Dim SelEnt As AcadEntity Dim SelPt As Variant ThisDrawing.Utility.GetEntity SelEnt, SelPt, vbCrLf & "Select an entity: " Dim MyLink As AcadHyperlink Set MyLink = SelEnt.Hyperlinks(3) Dim WindHnd As Long ShellExecute WindHnd, "OPEN", MyLink.URL, "", "", 1 End Sub

Page 6: VBA and the Internet - AUGI · them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier. • For the time being, I suggest

VBA and the Internet

6

E-Mailing with VBA • To many people, “Internet” means one thing: E-Mail. We can e-mail using VBA by using CDO (Collaboration Data

Objects). • First thing to do? Add a reference in your VBA project to the

‘Microsoft CDO for Windows 2000 Library’. • Next thing we will do is create a Procedure that sends mail so

we can call if from anywhere in our code. Sub SendMail(MailTo As String, MailFrom As String, _ MailBody As String, MailSubject As String) Dim MyMsg As CDO.Message Dim MyConf As CDO.Configuration Dim Flds As Variant Const cdoSendUsingPort = 2 Set MyMsg = CreateObject("CDO.Message") Set MyConf = CreateObject("CDO.Configuration") Set Flds = MyConf.Fields With Flds .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPort .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "pop.slkc.qwest.net" .Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 10 .Update End With With MyMsg Set .Configuration = MyConf .To = MailTo .From = MailFrom .Subject = MailSubject .HTMLBody = MailBody .Send End With Set MyMsg = Nothing Set MyConf = Nothing Set Flds = Nothing End Function • What if we want to send file attachments? Create another procedure to handle that. Copy and Paste the existing

code and name the new procedure “SendMail2”. Function SendMail2(MailTo As String, MailFrom As String, MailBody As String, _ MailSubject As String, AttachFile As String) Dim MyMsg As CDO.Message Dim MyConf As CDO.Configuration Dim Flds As Variant Const cdoSendUsingPort = 2 Set MyMsg = CreateObject("CDO.Message") Set MyConf = CreateObject("CDO.Configuration") Set Flds = MyConf.Fields With Flds .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = cdoSendUsingPort .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "pop.slkc.qwest.net" .Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 10 .Update End With With MyMsg Set .Configuration = MyConf .To = MailTo

Page 7: VBA and the Internet - AUGI · them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier. • For the time being, I suggest

VBA and the Internet

7

.From = MailFrom .Subject = MailSubject .HTMLBody = MailBody End With If AttachFile <> "" Then If Dir(AttachFile) <> "" Then MyMsg.AddAttachment AttachFile End If End If MyMsg.Send Set MyMsg = Nothing Set MyConf = Nothing Set Flds = Nothing End Function • Now that we have a procedure to send someone a file attachment, it seems a shame not to have something really

cool to use it with. Sub EmailSelection() Dim MySS As AcadSelectionSet Set MySS = ThisDrawing.SelectionSets.Add("SSMail") ThisDrawing.Utility.Prompt vbCrLf & "Select entities to e-mail: " MySS.SelectOnScreen Dim FName As String Dim MailFrom As String Dim MailTo As String FName = ThisDrawing.Utility.GetString(False, vbCrLf & "File name: ") MailTo = ThisDrawing.Utility.GetString(False, vbCrLf & "Email to address: ") MailFrom = "[email protected]" ThisDrawing.Wblock "c:\" & FName, MySS SendMail2 MailTo, MailFrom, "", "Here is the selection you requested", "c:\" & FName & ".dwg" Kill "c:\" & FName & ".dwg" MySS.Delete ThisDrawing.Utility.Prompt vbCrLf & "The file was sent." End Sub

The WinSock Control • The WinSock control allows you to communicate with remote servers using Protocols. • This form has a WinSock control named “WS1” as well as two

TextBoxes and a Command Button. TextBox2 is for a Website address. TextBox1 shows the results of asking the web server for the content of a file ‘index.htm’ at the address specified in TextBox2.

Page 8: VBA and the Internet - AUGI · them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier. • For the time being, I suggest

VBA and the Internet

8

Private Sub CommandButton1_Click() If WS1.State <> 0 Then WS1.Close End If TextBox1.Text = "" WS1.Protocol = sckTCPProtocol WS1.RemotePort = 80 WS1.RemoteHost = TextBox2.Text WS1.Connect While WS1.State <> 7 DoEvents Wend WS1.SendData "GET /index.htm" & vbCrLf & vbCrLf End Sub Private Sub WS1_DataArrival(ByVal bytesTotal As Long) Dim strData As String WS1.GetData strData, vbString TextBox1.Text = TextBox1.Text & strData End Sub • The above code gets the file ‘index.htm’ off of the server specified in the TextBox2.Text property. • How often do you need to get the HTML code of a file named ‘index.htm’ from any server? Not often? I didn’t think

so.

Active Server Pages • Why Active Server Pages in a VBA and the Internet class? ASP files are actually little programs that utilize VB

Script to do their work. Whenever you see a file in your web browser with a file extension of .asp, a little program was run on the web server to display what you actually see in your web browser.

• Goal: Allow user to select from a list of available blocks on a web server. When a block is selected, download the file to the user’s local machine and insert the block.

• Create a database named ‘inetblocks’ with a table in it called ‘blocks’. The Blocks table will have a field named ‘UniqueID’ which is an AutoNumber and a field named ‘BlockName’, a 50 Character Text field.

• Create a UDL file in “c:\udls” named ‘blocks.udl’ <% Dim MyDB Dim MyRS Set MyDB = Server.CreateObject("ADODB.Connection") Set MyRS = Server.CreateObject("ADODB.Recordset") MyDB.Open "File Name=c:\udls\blocks.udl" myrs.open "blocks", MyDB, 1, 2 response.write "BEGIN BLOCKS" & vbcr while myrs.eof = false response.write myrs("BlockName") & vbcr myrs.movenext Wend myrs.close mydb.close set myrs = nothing set mydb = nothing %> • This file is named ‘showblocks.asp’. It will talk to the database and retrieve all block names and write them to the

web page.

Page 9: VBA and the Internet - AUGI · them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier. • For the time being, I suggest

VBA and the Internet

9

• I have added a ComboBox to the form now. A little extra code to the existing code and we are in business. Notice that we are using a variable to place the HTML results in. We then parse the variable to extract the block names and put them in the ComboBox.

Public HTMLStr As String Private Sub CommandButton1_Click() If WS1.State <> 0 Then WS1.Close End If TextBox1.Text = "" ComboBox1.Clear WS1.Protocol = sckTCPProtocol WS1.RemotePort = 80 WS1.RemoteHost = TextBox2.Text WS1.Connect While WS1.State <> 7 DoEvents Wend WS1.SendData "GET /showblocks.asp" & vbCrLf & vbCrLf While WS1.State <> 8 DoEvents Wend HTMLStr = Mid(HTMLStr, InStr(1, HTMLStr, "BEGIN BLOCKS") + 13) While InStr(1, HTMLStr, vbCr) > 0 ComboBox1.AddItem Left(HTMLStr, InStr(1, HTMLStr, vbCr) - 1) HTMLStr = Mid(HTMLStr, InStr(1, HTMLStr, vbCr) + 1) Wend End Sub Private Sub WS1_DataArrival(ByVal bytesTotal As Long) Dim strData As String WS1.GetData strData, vbString HTMLStr = HTMLStr & strData TextBox1.Text = TextBox1.Text & strData End Sub • The block names are now being placed in the ComboBox. All we need to do now is download the selected file from

the ComboBox and allow the user to insert it. Private Sub CommandButton2_Click() If ComboBox1.Text = "" Then Exit Sub End If Dim FileLoc As String ThisDrawing.Utility.GetRemoteFile "http://" & TextBox2.Text & "/" & ComboBox1.Text & ".dwg", FileLoc, True FileCopy FileLoc, "c:\" & ComboBox1.Text & ".dwg" UserForm6.Hide Dim InsPt As Variant Dim InBlock As AcadBlockReference InsPt = ThisDrawing.Utility.GetPoint(, vbCrLf & "Select Insertion Point: ") Set InBlock = ThisDrawing.ModelSpace.InsertBlock(InsPt, "c:\" & ComboBox1.Text & ".dwg", 1, 1, 1, 0) InBlock.Update UserForm6.Show End Sub

Page 10: VBA and the Internet - AUGI · them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier. • For the time being, I suggest

VBA and the Internet

10

• OK. We now have the ability to have clients automatically download blocks and have them inserted. The database tells the program the names of the blocks. Wouldn’t it be cool if we could post new blocks to our web server when they become available? Let’s do it!

• We already have much of the code we need to get things moving along. We will first do some copying and pasting of existing code, change it around a little, and then we will create an Active Server Page file so we can move the file from an upload directory to the directory where our program is currently looking for drawings. We will also add the block to the database.

• Here is the form for the ‘Select and Post’ function. Notice that we are using a Winsock Control, named ‘WS1’. We also have one Command Button.

Private Sub CommandButton1_Click() If WS1.State <> 0 Then WS1.Close End If WS1.Protocol = sckTCPProtocol WS1.RemotePort = 80 WS1.RemoteHost = "dev" WS1.Connect While WS1.State <> 7 DoEvents Wend Dim FName As String UserForm7.hide FName = ThisDrawing.Utility.GetString(False, vbCrLf & "File name: ") PostBlock FName WS1.SendData "GET /postblocks.asp?blockname=" & FName & vbCrLf & vbCrLf While WS1.State <> 8 DoEvents Wend UserForm7.Show End Sub Sub PostBlock(BlockName As String) Dim RF As String Dim WebFileName As String Dim WebLocation As String Dim MySS As AcadSelectionSet Set MySS = ThisDrawing.SelectionSets.Add("SSMail") ThisDrawing.Utility.Prompt vbCrLf & "Select entities to e-mail: " MySS.SelectOnScreen Dim FName As String ThisDrawing.Wblock "c:\" & BlockName, MySS WebFileName = BlockName & ".dwg" WebLocation = "ftp://dev/upload" ThisDrawing.Utility.PutRemoteFile WebLocation & "/" & WebFileName, _ "c:\" & WebFileName Kill "c:\" & BlockName & ".dwg" MySS.Delete ThisDrawing.Utility.Prompt vbCrLf & "The file was has been posted." End Sub • Much of what you see above is taken from other places. We are simply W-blocking a selection, using

PutRemoteFile to put the file to a directory on a server, then we use the WinSock control to ‘Get’ the postblocks.asp file with a parameter name of ‘blockname’ and a value of whatever the user entered at the command line.

Page 11: VBA and the Internet - AUGI · them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier. • For the time being, I suggest

VBA and the Internet

11

• Now, for the ASP file. <% Dim MyDB Dim MyRS Set MyDB = Server.CreateObject("ADODB.Connection") Set MyRS = Server.CreateObject("ADODB.Recordset") MyDB.Open "File Name=c:\udls\blocks.udl" myrs.open "blocks", MyDB, 1, 2 myrs.AddNew myrs("BlockName") = request("BlockName") myrs.update myrs.close mydb.close set myrs = nothing set mydb = nothing Dim MyFSO Set MyFSO = CreateObject("Scripting.FileSystemObject") Dim FileFrom Dim FileTo FileFrom = "c:\inetpub\ftproot\upload\" & request("BlockName") & ".dwg" FileTo = "c:\inetpub\wwwroot\" & request("BlockName") & ".dwg" MyFSO.MoveFile FileFrom, FileTo Set MyFSO = Nothing %> • We are introducing something called “File System Objects” in this ASP code. FSO is used to work with files. The

code shown here moves the file from where it is located in the ‘upload’ directory to the ‘wwwroot’ directory where our Block Insertion from the Web program is looking.

The Internet means a great deal to a great many people. What it means varies greatly from person to person. I hope the examples of how to use VBA to work with the Internet has been helpful. Should there be anything specific you would like to know about or see, please ask during the Question and Answer section at the end of the class. Thank you for coming to this class. I look forward to meeting you and answering your questions. Jerry Winters VB CAD Inc. [email protected] www.vbcad.com

Page 12: VBA and the Internet - AUGI · them to allow the inclusion of username and password in PutRemoteFile and life as a VBA developer will be much easier. • For the time being, I suggest

VBA and the Internet

12