LateBinding

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm trying to use late binding for Outlook automation. I am trying 2
methods. One using VB.NET's Option Strict Off and the other using
System.Runtime.InteropServices and System.Reflection

Option Strict Off
....
Dim outlook as Object = CreateObject("Outlook.Application")
Dim message As Object = outlook.CreateItem(0)
message.To = "(e-mail address removed)"
message.Subject = "Hi"
message.HtmlBody = "<html>Test</html>"
message.Send

When I try
Option Strict On
Imports System.Runtime.InteropServices
Imports System.Reflection

....
Dim outlook as Object = CreateObject("Outlook.Application")
Dim message as Object = outlook.GetType.InvokeMember("CreateItem",
BindingFlags.InvokeMethod, Nothing, message, New Object() {0})
message.GetType.InvokeMember("Subject", BindingFlags.SetProperty, Nothing,
message, New Object() {"Hi"})
message.GetType.InvokeMember("To", BindingFlags.SetProperty, Nothing,
message, New Object() {"(e-mail address removed)"})
message.GetType.InvokeMember("HTMLBody", BindingFlags.SetProperty, Nothing,
message, New Object() {"<html>Test</html>"})
message.GetType.InvokeMember("Send", BindingFlags.InvokeMethod, Nothing,
message, Nothing)

The "CreateItem" causes a runtime error.

Method System.__ComObject.CreateItem not found.
at System.RuntimeType.InvokeMember(String name, BindingFlags invokeAttr,
Binder binder, Object target, Object[] args, ParameterModifier[] modifiers,
CultureInfo culture, String[] namedParameters)

Only CreateItem causes this problem. If I turn Option Strict Off and write
this

Dim outlook as Object = CreateObject("Outlook.Application")
Dim message As Object = outlook.CreateItem(0)
message.GetType.InvokeMember("Subject", BindingFlags.SetProperty, Nothing,
message, New Object() {"Hi"})
message.GetType.InvokeMember("To", BindingFlags.SetProperty, Nothing,
message, New Object() {"(e-mail address removed)"})
message.GetType.InvokeMember("HTMLBody", BindingFlags.SetProperty, Nothing,
message, New Object() {"<html>Test</html>"})
message.GetType.InvokeMember("Send", BindingFlags.InvokeMethod, Nothing,
message, Nothing)

It works just as expected.

Why is "CreateItem" not working properly?
 
Well if it says that CreateItem is not found then one would probably
think that either you were
a) invoking the wrong class
b) specifying the wrong properties to look for
If i were you I would google for some sample vb.net reflection code
which reflects over all properties/methods/fields of a object and then
have this information printed out somewhere so you can look at it. This
may be helpful in pinpointing out why it cannot find a method that you
expect to be there.
 
I'm calling a COM object, not a .NET class. As far as I know, you cannot
iterate through the exposed properties of a com object using Reflection.
 
Back
Top