Visual Basic – Anvil of Time https://anvil-of-time.com Nature Forges Everything on the Anvil of Time Thu, 11 Mar 2021 17:24:52 +0000 en-US hourly 1 PowerBuilder – Using C# Visual Objects in PB Classic Applications https://anvil-of-time.com/powerbuilder/powerbuilder-using-c-visual-objects-in-pb-classic-applications/ Mon, 18 Jun 2012 22:16:01 +0000 http://anvil-of-time.com/wordpress/?p=1373 This article will explain how to build a COM visual component in C# using Visual Studio 2010; it is an extension of my earlier example of using the Interop Forms Toolkit to build a Visual Basic COM object.

First you need to install the Microsoft Interop Toolkit (available here).
Then download the C# Interop Form Toolkit by Leon Langleyben from Codeproject. Installation of this is primarily copying files to the appropriate places based on your Visual Studio install (instructions are provided in Leon’s article).

Begin by creating a new project (Visual C#) with the ‘VB6 Interop UserControl’ Template.

Give the project a meaningful name, ‘IOPCsharpexample’ is my choice.

Visual Studio creates the Solution with a variety of files/references. All of the code will be done in the InteropUserControl.cs file.

Opening the InteropUserControl.cs file (right click on the item in the Solution Explorer and choose ‘View Code’) gives this.

Clicking on the plus to the left of ‘Interfaces’ expands that code section.

Note that there are two interface definitions, one for events and another for properties (and methods). This is one place we need to add to in order to expose the control within Powerscript.

To build the actual control, open the Designer window for the InteropUserControl.cs file (right click and choose ‘View Designer’.

This gives you the layout of the user control itself.

Add a trackbar control from the Tools window.

Change some of the trackbar attributes in the Properties display.

The changes from the default are Name – TB1, Backcolor – Yellow, Orientation – Vertical, TickFrequency – 10, TickStyle – Both, Maximum – 100, and Margin – 0,0,0,0. Unlike the VB control I demonstrated before, this is a vertical trackbar without any label to display its current value.

On the properties view for the trackbar TB1, click on the Events button. This shows a list of the defined events for the control. Double click on the ValueChanged event. This will add a stub for the event on the code page.

However, we must also add an initialization for an event handler to the event within the objects declaration so that it will be exposed.

Use the same steps to expose the Scroll event on the trackbar. Once finished you can see the events created in bold on the Properties window.

Now to complete the C# code refer to the following:

using System.ComponentModel;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;
using System.Windows.Forms;
using System.Security.Permissions;
using System.Drawing;

namespace IOPCsharpexample
{

    #region Interfaces

    [ComVisible(true), Guid(InteropUserControl.EventsId), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface __InteropUserControl
    {
        [DispId(1)]
        void Click();
        [DispId(2)]
        void DblClick();
        //add additional events visible in VB6
        // these events exposed and shown in PB event list
        [DispId(3)]
        void tbScroll();
        [DispId(4)]
        void tbValuechanged();
    }

    [Guid(InteropUserControl.InterfaceId), ComVisible(true)]
    public interface _InteropUserControl
    {
        [DispId(1)]
        bool Visible { [DispId(1)] get; [DispId(1)] set; }
        [DispId(2)]
        bool Enabled { [DispId(2)] get; [DispId(2)] set; }
        [DispId(3)]
        int ForegroundColor { [DispId(3)] get; [DispId(3)] set; }
        [DispId(4)]
        int BackgroundColor { [DispId(4)] get; [DispId(4)] set; }
        [DispId(5)]
        Image BackgroundImage { [DispId(5)] get; [DispId(5)] set; }
        [DispId(6)]
        void Refresh();
        //add additional properties visible in VB6
        // PB can call these
        [DispId(7)]
        void tbsetbackcolor(int testval);
        [DispId(8)]
        int tb1backgroundcolor { [DispId(8)] get; [DispId(8)] set; }
        [DispId(9)]
        int tb1value { [DispId(9)] get; [DispId(9)] set; }
    }
    #endregion

    [Guid(InteropUserControl.ClassId), ClassInterface(ClassInterfaceType.None)]
    [ComSourceInterfaces("IOPCsharpexample.__InteropUserControl")]
    [ComClass(InteropUserControl.ClassId, InteropUserControl.InterfaceId, InteropUserControl.EventsId)]
    public partial class InteropUserControl : UserControl, _InteropUserControl
    {
        #region VB6 Interop Code

#if COM_INTEROP_ENABLED

        #region "COM Registration"

        //These  GUIDs provide the COM identity for this class 
        //and its COM interfaces. If you change them, existing 
        //clients will no longer be able to access the class.

        public const string ClassId = "e7c6c97a-af38-4d57-9980-9edd60e1b45c";
        public const string InterfaceId = "2aab63cc-a9df-4197-89f4-44150a746301";
        public const string EventsId = "1eeca2b9-97ac-4c1c-8dc1-770c941c8ebd";

        //These routines perform the additional COM registration needed by ActiveX controls
        [EditorBrowsable(EditorBrowsableState.Never)]
        [ComRegisterFunction]
        private static void Register(System.Type t)
        {
            ComRegistration.RegisterControl(t);
        }

        [EditorBrowsable(EditorBrowsableState.Never)]
        [ComUnregisterFunction]
        private static void Unregister(System.Type t)
        {
            ComRegistration.UnregisterControl(t);
        }


        #endregion

        #region "VB6 Events"

        //This section shows some examples of exposing a UserControl's events to VB6.  Typically, you just
        //1) Declare the event as you want it to be shown in VB6
        //2) Raise the event in the appropriate UserControl event.
        public delegate void ClickEventHandler();
        public delegate void DblClickEventHandler();
        public new event ClickEventHandler Click; //Event must be marked as new since .NET UserControls have the same name.
        public event DblClickEventHandler DblClick;

        private void InteropUserControl_Click(object sender, System.EventArgs e)
        {
            if (null != Click)
                Click();
        }

        private void InteropUserControl_DblClick(object sender, System.EventArgs e)
        {
            if (null != DblClick)
                DblClick();
        }


        #endregion

        #region "VB6 Properties"

        //The following are examples of how to expose typical form properties to VB6.  
        //You can also use these as examples on how to add additional properties.

        //Must Shadow this property as it exists in Windows.Forms and is not overridable
        public new bool Visible
        {
            get { return base.Visible; }
            set { base.Visible = value; }
        }

        public new bool Enabled
        {
            get { return base.Enabled; }
            set { base.Enabled = value; }
        }

        public int ForegroundColor
        {
            get 
            {
                return ActiveXControlHelpers.GetOleColorFromColor(base.ForeColor);
            }
            set
            {
                base.ForeColor = ActiveXControlHelpers.GetColorFromOleColor(value);
            }
        }

        public int BackgroundColor
        {
            get
            {
                return ActiveXControlHelpers.GetOleColorFromColor(base.BackColor);
                }
            set
            {
                base.BackColor = ActiveXControlHelpers.GetColorFromOleColor(value);
            }
        }

        public override System.Drawing.Image BackgroundImage
        {
            get{return null;}
            set
            {
                if(null != value)
                {
                    MessageBox.Show("Setting the background image of an Interop UserControl is not supported, please use a PictureBox instead.", "Information");
                }
                base.BackgroundImage = null;
            }
        }

        #endregion

        #region "VB6 Methods"

            public override void Refresh()
            {
                base.Refresh();
            }

            //Ensures that tabbing across VB6 and .NET controls works as expected
            private void InteropUserControl_LostFocus(object sender, System.EventArgs e)
            {
                ActiveXControlHelpers.HandleFocus(this);
            }

            public InteropUserControl()
            {
                //This call is required by the Windows Form Designer.
                InitializeComponent();

                //' Add any initialization after the InitializeComponent() call.
                this.DoubleClick += new System.EventHandler(this.InteropUserControl_DblClick);
                base.Click += new System.EventHandler(this.InteropUserControl_Click);
                this.LostFocus += new System.EventHandler(InteropUserControl_LostFocus); 
                this.ControlAdded += new ControlEventHandler(InteropUserControl_ControlAdded);
                //////// new events to expose to PB
                this.TB1.ValueChanged += new System.EventHandler(TB1_ValueChanged);
                this.TB1.Scroll += new System.EventHandler(TB1_Scroll);
                //////////
                //'Raise custom Load event
                this.OnCreateControl();
            }

            [SecurityPermission(SecurityAction.LinkDemand, Flags =SecurityPermissionFlag.UnmanagedCode)]
            protected override void WndProc(ref System.Windows.Forms.Message m)
            {

                const int WM_SETFOCUS = 0x7;
                const int WM_PARENTNOTIFY = 0x210;
                const int WM_DESTROY = 0x2;
                const int WM_LBUTTONDOWN = 0x201;
                const int WM_RBUTTONDOWN = 0x204;

                if (m.Msg == WM_SETFOCUS)
                {
                    //Raise Enter event
                    this.OnEnter(System.EventArgs.Empty);
                }
                else if( m.Msg == WM_PARENTNOTIFY && (m.WParam.ToInt32() == WM_LBUTTONDOWN || m.WParam.ToInt32() == WM_RBUTTONDOWN))
                {

                    if (!this.ContainsFocus)
                    {
                        //Raise Enter event
                        this.OnEnter(System.EventArgs.Empty);
                    }
                }
                else if (m.Msg == WM_DESTROY && !this.IsDisposed && !this.Disposing)
                {
                    //Used to ensure that VB6 will cleanup control properly
                    this.Dispose();
                }

                base.WndProc(ref m);
            }

            //This event will hook up the necessary handlers
            private void InteropUserControl_ControlAdded(object sender, ControlEventArgs e)
            {
                ActiveXControlHelpers.WireUpHandlers(e.Control, ValidationHandler);
            }

            //Ensures that the Validating and Validated events fire appropriately
            internal void ValidationHandler(object sender, System.EventArgs e)
            {
                if( this.ContainsFocus) return;

                //Raise Leave event
                this.OnLeave(e);

                if (this.CausesValidation)
                {
                    CancelEventArgs validationArgs = new CancelEventArgs();
                    this.OnValidating(validationArgs);

                    if(validationArgs.Cancel && this.ActiveControl != null)
                        this.ActiveControl.Focus();
                    else
                    {
                        //Raise Validated event
                        this.OnValidated(e);
                    }
                }
            }
        #endregion

#endif
        #endregion

        //Please enter any new code here, below the Interop code
        /////////// events to expose to PB
        public delegate void tbValueChangedEventHandler();
        public event tbValueChangedEventHandler tbValuechanged;
        private void TB1_ValueChanged(object sender, System.EventArgs e)
        {
            if (tbValuechanged != null)
            {
                tbValuechanged();
            }
        }
        public event tbScrollEventHandler tbScroll;
        public delegate void tbScrollEventHandler();
        private void TB1_Scroll(object sender, System.EventArgs e)
        {
            if (tbScroll != null)
            {
                tbScroll();
            }
        }
        ////////////
        //method to call from PB
        public void tbsetbackcolor(int testval)
        {
            Color myColor = ColorTranslator.FromWin32(testval); //translate numeric color
            TB1.BackColor = myColor; //set background of trackbar
            BackColor = myColor; // set background of user control
        }
        ///////////
        // Property get/set to call from PB
        public int tb1backgroundcolor
        {
            get { return ActiveXControlHelpers.GetOleColorFromColor(TB1.BackColor); }
            set { TB1.BackColor = ActiveXControlHelpers.GetColorFromOleColor(value); }
        }
        public int tb1value
        {
            get { return TB1.Value; }
            set { TB1.Value = value; }
        }
        ///////////
    }
}

Note that the two event stubs created by doubleclicking on the event name in the IDE were moved to the end of the class, after the final ‘#endregion’ lable so most of the code outside the interface section is together. In a nutshell to expose the event to PB you have to:
A) add the events after the InitializeComponent call on the class
B) create a public eventhandler delegate
C) create a public event which the delegate references
D) code the event (double clicking on the control – event list gives you the event ‘skeleton’
E) add the event to the event interface

To code a property or method which can be called from PB you have to:
A) create a public method with parameters and return values (if needed) OR a public property with both a get and set section.
B) add the method/property to the property interface

Important Note: Unlike the default for Visual Basic (or PowerBuilder for that matter), C# is strongly typed. This means that a method with the name ‘MyEvent’ is not the same as ‘myevent’, ‘Myevent’ or ‘myEvent’. Quite often your code will compile file, but when you try to use your component in PB you will crash and burn.

When this is built in Visual Studio a dll is created and registered on the machine. If you want to take the dll to a different machine you will have to manually register the dll in order to use it in PowerBuilder.

Using the control in PowerBuilder

So now to add the control in Powerbuilder you click on the Insert OLE control icon,

choose the Insert Control tab and then the control from the control list.

The example app created to demonstrate the VB .Net component is expanded to include the C# component as well. A few more PB controls are added to the form which results in this.

The code in the clicked event of the Set Color button follows:

long ll_vb_color, ll_cs_color
// set the desired color on the controls
IF sle_1.text = string(RGB(0,174,221)) THEN
	ll_vb_color = 15780518
	ll_cs_color = RGB(168,255,168)
ELSE
	ll_vb_color = RGB(0,174,221)
	ll_cs_color = RGB(196,240,16)
END IF
// call method on VB .Net control
ole_3.object.event tbSetBackColor(ll_vb_color)
// call method on C# .Net control
ole_2.object.tbSetBackColor(ll_cs_color)
// get the color value using the 'getter' method in VB .Net control
sle_1.text = string(ole_3.object.tb1backgroundcolor())
// get the color value using the 'getter' method in C# .Net control
sle_2.Text = string(ole_2.object.tb1backgroundcolor())

The only difference in the method calls to the controls (tbSetBackColor method) is in VB you qualify it as an event.

The code in the tbvaluechanged event on the C# control is

st_4.text = string(ole_2.object.tb1value())

Which is calling the C# get method of the tb1value property.

In the tbscroll event on the control is the following:

long ll_val, ll_color
//report on the current value of the control
ll_val = ole_2.object.tb1value()
//move the PB control
vtb_1.position = ll_val

As is the case for the VB control, you must have some code in the events you expose or you will get an unhandled exception error.

Running the sample application.

Clicking the Set Color button changes the .Net controls

Moving the VB control

Moving the C# control

The PowerBuilder code was written in version 12.5.1. Within the csharpinteroppb are export files if you are working with an earlier version.

]]>
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 – 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?

]]>
VB.Net – “…any public member or cannot be found…” message https://anvil-of-time.com/net/vb-net-any-public-member-or-cannot-be-found-message/ Thu, 31 Mar 2011 01:20:03 +0000 http://anvil-of-time.com/wordpress/?p=734 So I’m playing around with Visual Basic in VisualStudio 2010 Express and I’m planning on importing some code from an old VB file I squirrelled away a while ago. I create my project and define a new class and then copy/paste out of the old code. Intellisence immediately squawks and I get the message “The Namespace or type specified in the Imports ‘System.Drawing’ doesn’t contain any public member or cannot be found.” Great.

A search in MSDN is fruitless but eventually I stumble upon a posting with exactily what I needed to know.

I need to add a reference to the class library. Go to Project > Add Reference and choose the .NET tab. Scroll down to the System.Drawing entry (or whatever you are using) and then add it.

]]>