Visual Basic – Anvil of Time https://anvil-of-time.com Nature Forges Everything on the Anvil of Time Thu, 11 Mar 2021 17:16:45 +0000 en-US hourly 1 PowerBuilder – Using .Net Visual Controls in PB Classic Applications https://anvil-of-time.com/powerbuilder/powerbuilder-using-net-visual-controls-in-pb-classic-applications/ Tue, 05 Jun 2012 22:27:24 +0000 http://anvil-of-time.com/wordpress/?p=1335 This article describes the techniques and code used during my presentations at the Carolina Code Camp 2012 and at the May 2012 meeting of the North Carolina PowerBuilder User Group.

The techniques described here utilize Visual Basic .Net (coded in Visual Studio 2010) with the Interop Forms Toolkit available from Microsoft. The Interop Forms Toolkit was originally intended as a ‘bridge’ between the VB 6 world and VB .Net. It allows you to host any .Net control in any Win32 application that supports COM. The current version supports Visual Studio 2005, 2008, and 2010.

In this example we are creating a horizontal track bar control to use in a PB application (PB12.5). Why not use the PB control you say? Well, we want one which allows us to control the background color.

First create a project in Visual Studio and under ‘Visual Basic’ – ‘Windows’ choose the VB6 Interop UserControl. Give the control a meaningful name at the bottom, I picked ‘vb_trackbar’.

In the Solution Explorer you should see a number of components which are automatically created. Almost all the work is done in the ‘InterobUserControl.vb’ element

Double click on the ‘InteropUserControl.vb’ element to bring it up in design mode so the actual control can be built.

Choose a Trackbar from the tools window in Visual Studio

and drop it on the usercontrol. Rearrange its size and position as appropriate

Now choose a Label and drop it on the control.

Change the backcolor of the trackbar to yellow; the name to TB; the Margin to 0,0,0,0; the Maximum to 100; the TickFrequency to 10; and the TickStyle to Both.

Modify the background color of the label and the usercontrol itself to yellow. Rename the control to ‘IOP_Trackbar’, the label to ‘LB_Value’, and give the label a border.

Right click on the ‘InteropUserControl.vb’ element from the Project window and choose ‘View Code’

You will see code like this (this is from Visual Studio 2010).

Here is the code to add.

   'Please enter any new code here, below the Interop code

    ' event to show in PB
    Public Event tbScroll()
    Public Event tbValuechanged()

    Private Sub TB_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TB.Scroll
        LB_Value.Text = TB.Value.ToString()
        RaiseEvent tbScroll()
    End Sub
    Private Sub TB_Valuechanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TB.ValueChanged
        RaiseEvent tbValuechanged()
    End Sub

    ' method to call from PB
    Public Sub tbSetBackColor(ByVal testval As Integer)
        Dim myColor As Color = ColorTranslator.FromWin32(testval)

        TB.BackColor = myColor ' set color on trackbar
        LB_Value.BackColor = myColor ' set color on label
        BackColor = myColor ' set color on interop control
    End Sub
    ' Property get/set
    Public Shadows Property TBBackgroundColor() As Integer
        Get
            Return ActiveXControlHelpers.GetOleColorFromColor(TB.BackColor)
        End Get
        Set(ByVal value As Integer)
            TB.BackColor = ActiveXControlHelpers.GetColorFromOleColor(value)
        End Set
    End Property
    ' this is the value of the trackbar
    Public Shadows Property TBValue() As Integer
        Get
            Return TB.Value
        End Get
        Set(ByVal value As Integer)
            TB.Value = value
        End Set
    End Property

In the first portion there are two events we want to expose to PowerBuilder so we can write code in our PB app to respond to the control. These are ‘tbScroll’ and ‘tbValuechanged’. One is triggered in response to the Scroll event on the trackbar (which we named ‘TB’) and the other by the Valuechanged event. In the tbScroll event we are setting the Text in the label (we called it ‘LB_Value’) on the userobject to the Value property of the Trackbar.

We also are creating a method, tbSetBackColor, which can be called from our PB app to set the background colors of the userobject, trackbar, and label.

Finally we are exposing two properties of the Trackbar so we can either set or get them from our PB app. These are called ‘TBBackgroundColor’ and ‘TBValue’.

The last thing we need to do in Visual Studio is to add an Interface to the project so the events we are exposing can be seen from within PowerBuilder. From the Project menu choose ‘Add New Item’.

Then under the ‘Common Items’ choose ‘Interface’

In the code for the interface, replace it with the following.

<guid("ca16a9e8-02c7-43d2-90f6-4ef30885a338"), _="" interfacetype(cominterfacetype.interfaceisidispatch)=""> _
Public Interface iIOP_Trackbar
    <dispid(1)> _
    Sub tbScroll()
    <dispid(2)> _
    Sub tbValuechanged()
End Interface</dispid(2)></dispid(1)></guid("ca16a9e8-02c7-43d2-90f6-4ef30885a338"),>

The first thing to do now is to replace the example GUID with one of your own (Visual Studio can generate one). Also give the Interface a more meaningful name – ‘iIOP_Trackbar’ in this example. Within the interface definition are the two events which will be visible from within PowerBuilder.

With this done you can now build the solution from the ‘Build’ menu

This will create and register the dll on the machine.

Now in PowerBuilder the control will be available when you choose to add an userobject.

The events are visible in Powerscript.

Now in the tbscroll event on our ole control we put the following.

long ll_val
//report on the current value of the control
//this uses the 'getter' method to return the track bar value from the .net control
ll_val = ole_1.object.event tbvalue()
//move the PB control
htb_1.position = ll_val
// show value
st_1.text = string(ll_val)

Code in the tbvaluechanged event on the ole control

sle_2.text = 'tbvaluechanged at ' + string(Now(),'hh:mm:ss')

Code to set the color of the ole control.

long ll_color

// set the desired color on the control
IF sle_1.text = string(RGB(0,174,221)) THEN
	ll_color = 15780518
ELSE
	ll_color = RGB(0,174,221)
END IF
// call method on .Net control to set the background colors
ole_1.object.event tbsetbackcolor(ll_color)
// get the color value using the 'getter' method in .Net class
sle_1.text = string(ole_1.object.tbbackgroundcolor())

Running the application gives the following

See the original control background color. Clicking the Set Color button gives this

Moving the trackbar ole control results in this.

There are a couple of things to look out for when using the techniques described here. The first is that any events exposed via the .Net Interface must have some sort of Powerscript in them within PB. Failure to do this results in an ‘unhandled exception’ application crash. There may be some way to prevent this from within Visual Basic but I am not sure.

The other issue is that if you have to change your VB.Net component you must re add it to your window/form within PowerBuilder. Usually I will add a second ole object to the existing window, transfer all the code from the old ole control, delete the original control, and finally rename the new control to that of the old control. This is the biggest issue I have with working with ‘roll your own’ ole controls. If anyone knows of a work around for this I would like to hear it.

Visual studio and PB files can be downloaded from here.

The video presentation of this is on YouTube.

]]>
VBA – Processing ICS calendar file attachments https://anvil-of-time.com/programming/vba-processing-ics-calendar-file-attachments/ https://anvil-of-time.com/programming/vba-processing-ics-calendar-file-attachments/#respond Thu, 28 Jul 2011 01:20:01 +0000 http://anvil-of-time.com/wordpress/?p=837 This article brings to conclusion the Outlook VBA macro/script I wrote to process event scheduling attachments (.ICS or ICalendar files). The first article shows how to process emails and remove their associated attachments. The second shows how to open the files and both read the file contents into an array as well as write (append) to the file. This code works in Outlook 2007.

The script does the following:

1. Check if the email has an attachment
2. If the attachment is an ICalendar (.ICS) file, remove it to a common folder and update the email with a link to the detached file.
3. Loop through the ICS files in the designated folder and load them into an array.
4. If the last element in the array contains the value “PROCESSED”, skip it
5. Take the UID (Unique IDentifier) array element and turn it into an Outlook Event GUID.
6. Check if there are any events which have the UID Guid. If there are, this indicates the new file is an update to a previously processed event.
7. If there is no previous event with the UID Guid, add the event using the UID Guid as an identifier.
8. If there is a previous event and the new notice is a cancellation, delete the event.
9. If there is a previous event and the new notice is not a cancellation, update the event.
10. Append a line to the ICS file with the value “PROCESSED”.

Public Sub SaveICSAttachmentsMacro()
    Dim objOL As Outlook.Application
    Dim objitem As Outlook.MailItem 'Object
    Dim objAttachments As Outlook.Attachments
    Dim objSelection As Outlook.Selection
    Dim i As Long
    Dim lngCount As Long
    Dim strFile As String
    Dim strFolderpath As String
    Dim strDeletedFiles As String
    Dim strArray() As String 
    Dim ac As Long
    Dim lSeq As Long
    Dim lPriority As Long
    Dim strLine As String
    Dim strField As String
    Dim strValue As String
    Dim strMethod As String
    Dim strUid As String
    Dim strSummary As String
    Dim strLocation As String
    Dim strDesc As String
    Dim strOrganizer As String
    Dim strDate As String
    Dim dtStart As Date
    Dim dtEnd As Date
    
     Dim hexUID
     
    ' Instantiate an Outlook Application object.
    Set objOL = Application
     
     Dim objNs As Outlook.NameSpace
     Set objNs = objOL.Session
     Dim objFolder As Outlook.MAPIFolder
     
     Set objFolder = objNs.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar)
     Dim objAppts As Outlook.Items
     Set objAppts = objFolder.Items
     Dim objAppt As Outlook.AppointmentItem
     Dim strFilter As String
     
     
     
    ' Get the path to your My Documents folder
    strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
    On Error Resume Next


    ' Get the collection of selected objects.
    Set objSelection = objOL.ActiveExplorer.Selection
''''''''''''''''''''
'[snip] see code from Removing attachments post
'''''''''''''''''''
    ' call function in different module
    ' this populates the string array from the iCalendar file
    icsFileToArray strFile, strArray
    
    ' check last element of array to determine if file previously processed
    If strArray(UBound(strArray)) = "PROCESSED" Then
        'file already processed
        GoTo ExitSub
    Else
        ' loop through array to process event
        For ac = 1 To UBound(strArray)
            ' separate data pairs
            strLine = strArray(ac)
            If InStr(1, strLine, ":") > 0 Then
                strField = Mid(strLine, 1, InStr(1, strLine, ":") - 1)
                strValue = Mid(strLine, InStr(1, strLine, ":") + 1)
            End If
            
            Select Case strField
                Case "METHOD"
                 ' REQUEST or CANCEL
                    strMethod = strValue
                Case "UID"
                 ' Unique identifier for event
                    strUid = strValue
                Case "DTSTART"
                    ' pull out values into 'mm/dd/yyyy hh:mm:ss' format
                    strDate = (Mid(strValue, 5, 2) & "/" & Mid(strValue, 7, 2) & _
                    "/" & Mid(strValue, 1, 4) & " " & Mid(strValue, 10, 2) & ":" & _
                    Mid(strValue, 12, 2))
                    dtStart = CDate(strDate)
                    ' put datetime into Outlook format
                    dtStart = Format(dtStart, "\#m\/d\/yyyy h:mm:ss AM/PM\#")
                Case "DTEND"
                    ' pull out values into 'mm/dd/yyyy hh:mm:ss' format
                    strDate = (Mid(strValue, 5, 2) & "/" & Mid(strValue, 7, 2) & _
                    "/" & Mid(strValue, 1, 4) & " " & Mid(strValue, 10, 2) & ":" & _
                    Mid(strValue, 12, 2))
                    dtEnd = CDate(strDate)
                    dtEnd = Format(dtEnd, "\#m\/d\/yyyy h:mm:ss AM/PM\#")
                Case "SUMMARY"
                    strSummary = strValue
                Case "LOCATION"
                    strLocation = strValue
                Case "ORGANIZER"
                    ' can not set this as of 6-30-2011
                    strOrganizer = strValue
                Case "PRIORITY"
                    lPriority = Val(strValue)
                Case "SEQUENCE"
                 ' if an update must be > 0
                    lSeq = Val(strValue)
                Case "DESCRIPTION"
                    strDesc = strValue
                
                Case Else
                
            End Select
        Next
    End If
    ' check if appointment already exists for given UID
    'convert UID to hex. this should match the GlobalAppointmentID if the item was
    ' imported manually
    'Start with the standard preamble (original example had 26 and not 12 here)=======vv
    hexUID = "040000008200E00074C5B7101A82E0080000000000000000000000000000000000000000120000007643616C2D55696401000000"
    'Now add the provided string
    For i = 1 To Len(strUid)
        hexUID = hexUID & CStr(Hex(Asc(Mid(strUid, i, 1))))
    Next
    'Terminate the UID
    hexUID = hexUID & "00"
    ' this filter used if the new field is set to the GlobalAppointmentID
    strFilter = "[UID] = '" & hexUID & "'"
    Set objAppt = objAppts.Find(strFilter)
    If objAppt Is Nothing Then
        'New event
         Dim myItem As Outlook.AppointmentItem
         Set myItem = objOL.CreateItem(olAppointmentItem)
         myItem.Start = dtStart
         myItem.End = dtEnd
         myItem.Subject = strSummary
         myItem.Location = strLocation
         myItem.Body = strDesc
	 ' this was not working when I did this
         ' myItem.Organizer = strOrganizer
	 ' add a new property "UID" to the event so it can be updated
         myItem.ItemProperties.Add "UID", olText, True
         myItem.Save
         myItem.ItemProperties.Item("UID").Value = hexUID
         myItem.Save
    Else
        If strMethod = "CANCEL" Then
            ' remove item from calendar
            objAppt.Delete
        ElseIf lSeq > 0 Then
            ' update must have sequence > 0
            objAppt.Start = dtStart
            objAppt.End = dtEnd
            objAppt.Subject = strSummary
            objAppt.Location = strLocation
            objAppt.Body = strDesc
            objAppt.Save
        End If
        
    End If
    ' mark file processed
    icsWriteToFile strFile
    
ExitSub:

Set objAttachments = Nothing
Set objitem = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

The biggest issue I came across in dealing with Outlook is the ability to update or delete a previously scheduled event. One would think Microsoft could handle the setting of an ID which could then be used to find it consistently. Outlook does assign an ID to events but these get changed if you move them around. The ‘GlobalAppointmentID’ does get set (as a GUID) and remains constant but you have no way of searching for it (sigh). Anyway I get around this by adding a property to any Event created via this process and assign the UID (which is converted into a GUID) to it. This way I can do a simple ‘Find’ of my apppointments and process appropriately. Here are some links related to GUIDs and Outlook

MSDN Outlook GUID stuff

Changing a string into an Outlook Event GUID See answer by banjaxed.

Note this process does not handle recurring appointments

]]>
https://anvil-of-time.com/programming/vba-processing-ics-calendar-file-attachments/feed/ 0
VBA – Reading a file into an array and Appending to a file https://anvil-of-time.com/programming/vba-reading-a-file-into-an-array-and-appending-to-a-file/ Tue, 12 Jul 2011 01:20:30 +0000 http://anvil-of-time.com/wordpress/?p=833 Both of these routines can be called from Outlook Macros/Scripts to process files. In my case I am using them to open iCalendar (ICS) files and place the contents into a string array. The calling method then processes the information then flags the file as ‘PROCESSED’ by the second routine.

Public Sub icsFileToArray(ByVal FileName As String, ByRef TheArray As Variant)
'
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oFSTR As Scripting.TextStream
Dim lCtr As Long

Set oFSTR = oFSO.OpenTextFile(FileName, 1, 0) ' for reading

Do While Not oFSTR.AtEndOfStream
    ReDim Preserve TheArray(lCtr) As String
    TheArray(lCtr) = oFSTR.ReadLine
    lCtr = lCtr + 1
    DoEvents
Loop
oFSTR.Close
ErrorHandler:
Set oFSTR = Nothing
End Sub


Public Sub icsWriteToFile(ByVal FileName As String)
'
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oFSTR As Scripting.TextStream
'Dim ret As Long
Dim lCtr As Long

Set oFSTR = oFSO.OpenTextFile(FileName, 8, 0) ' for appending
oFSTR.Write "PROCESSED"
oFSTR.Close
ErrorHandler:
Set oFSTR = Nothing
End Sub
]]>
VBA – Removing attachments from Outlook email https://anvil-of-time.com/programming/vba-removing-attachments-from-outlook-email-2/ Sat, 02 Jul 2011 01:20:57 +0000 http://anvil-of-time.com/wordpress/?p=806 One very powerful aspect of the Microsoft Office Suite of applications is the ability to create Macros and Scripts to perform various processes. This gives those of us who worked in Visual Basic 6 a chance to dust off our skills since the ‘flavor’ of Visual Basic used in the Microsoft Office applications (aptly called Visual Basic for Applications) is essentially the same.

A common request in Outlook is to process mail messages with attachments by removing the attachments and saving them to some specified folder. This can be accomplished with either a macro or a script. The script has an advantage of being something you can put into a rule so any incoming emails are processed automatically. Macros allow you to process only specific emails should you so desire.

My examples below are set to remove external calendar request files (.ICS or ICalendar format) and place them into the folder ‘ICSFiles’ set up in the standard ‘My Documents’ folder.

Public Sub SaveICSAttachments()
' to set this as a script the declaration would be
' Public Sub SaveICSAttachments(objitem As MailItem)
Dim objOL As Outlook.Application
''''''''''''''''''''''''''''''''''''
' the next line removed if set up as a script
Dim objitem As Outlook.MailItem 'Object
'''''''''''''''''''''''''''''''''''
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lCount As Long
Dim sFile As String
Dim sFolderpath As String
Dim sDeletedFiles As String

' Instantiate an Outlook Application object.
Set objOL = Application

Dim objNs As Outlook.NameSpace
Set objNs = objOL.Session
Dim objFolder As Outlook.MAPIFolder

' Get the path to your My Documents folder
sFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next

' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection

' Set the Attachment folder.
' You could check for the existance of the folder and 
' prompt the user if you want
sFolderpath = sFolderpath & "\ICSFiles\"

' Check each selected item for attachments.
'''''''''''''''''''''''''''''''
' Remove loop if used in script (you call script with the item)
For Each objitem In objSelection
'''''''''''''''''''''''''''''''''''''
	' Remove this check if running as a script
	' This code only strips attachments from mail items.
	If objitem.Class = olMail Then
	'''''''''''''''''''''''''''''''''''
		' Get the Attachments collection of the item.

		Set objAttachments = objitem.Attachments
		lCount = objAttachments.Count

		If lCount > 0 Then
			' Since we are removing things from an array, remove
			' from the end going to the beginning
			For i = lCount To 1 Step -1

				' Save attachment before deleting from item.
				sFile = objAttachments.Item(i).FileName
				' only looking for ICS file attachments
				If Right(sFile, 3) = "ics" Then
					' Combine with the path to the Temp folder.
					sFile = sFolderpath & sFile

					' Save the attachment as a file.
					objAttachments.Item(i).SaveAsFile sFile
                                        ' remove attachment
					objAttachments.Item(i).Delete

					'write the save as path to a string to add to the message
					If objitem.BodyFormat <> olFormatHTML Then
						sDeletedFiles = sDeletedFiles & vbCrLf & "<file://" & sFile & ">"
					Else
						sDeletedFiles = sDeletedFiles & "<br>" & "<a href='file://" & sFile & "'>" & sFile & "</a>"
				End If
			Next i
		End If

		' Adds the filename string to the message body and save it
		If objitem.BodyFormat <> olFormatHTML Then
			 objitem.Body = objitem.Body & vbCrLf & "The file(s) were saved to " & sDeletedFiles
		 Else
			 objitem.HTMLBody = objitem.HTMLBody & "<p>" & "The file(s) were saved to " & sDeletedFiles & "</p>"
		 End If
		 ' save the modified email with link to the detached file
		 objitem.Save
	''''''''''''''''''''
	' remove if running as a script
   End If
   '''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''
' remove loop if running as a script
Next
''''''''''''''''''''''''''''''''
ExitSub:

Set objAttachments = Nothing
Set objitem = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

(Sorry for the screwed up code listing but the file link tags are being improperly interpreted by the plugin I use).

This macro was designed to run on Outlook 2007. You will most likely have to change the security settings in Outlook to have it run (and sign the macro or whatever). There is minimal (none) error checking in this code but then I’m not going to do it all for you.

]]>
Look what I found – Part 3 https://anvil-of-time.com/programming/look-what-i-found-part-3/ Fri, 01 Jul 2011 01:20:44 +0000 http://anvil-of-time.com/wordpress/?p=800 Found on a Microsoft Answers forum:

Hello? Microsoft? your help files are of no help.

Does anyone really bother to participate in any of those obnoxious ‘Help us improve’ programs?

]]>