65.9K
CodeProject is changing. Read more.
Home

How to Create a VB Script Object and Call Methods On It

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.07/5 (9 votes)

Oct 25, 2005

CPOL

1 min read

viewsIcon

53301

It explains how you can call methods on a VB Script object using C#

Introduction

Well, you will be surprised to know that it is very easy to create a VB Script object in C# and call methods on it. Consider the following VB Script Code:

Dim IIsWebServiceObj 
Set IIsWebServiceObj = GetObject("IIS://localhost/W3SVC") 
IIsWebServiceObj.DeleteExtensionFileRecord 
    "E:\RMS\Code\BusinessServices\KalSPS\Debug\KalSPS.dll"

To write this code in C#, you just need to add a reference to Microsoft.VisualBasic.CompilerServices and System.Runtime.CompilerServices. The following code snippet creates an IIS object and calls the DeleteExtensionRecord method on it.

private void RemovesWebServiceExtension(string extensionPath)
{
    try
    {
        object ext = RuntimeHelpers.GetObjectValue(this.GetIISObject("IIS://" + 
        Environment.MachineName+"/W3SVC"));
        object[] args=new object[1]{extensionPath};
        LateBinding.LateCall(ext, null, "DeleteExtensionFileRecord", args, null, null); 
    }
    catch
    {
        throw;
    }
}

private object GetIISObject(string fullObjectPath)
{
    try
    {
        return RuntimeHelpers.GetObjectValue
            (Interaction.GetObject(fullObjectPath, null));
    }
    catch
    {
        throw;
    }
}

Here, the Interaction module contains procedures to interact with objects, applications and system. The Runtime Helper class contains a method for compiler construction. It is a service class and hence contains only static methods. Its GetObjectValue method boxes the object passed as the parameter. Boxing a value type creates an object and performs a shallow copy of the fields of the specified value type into the new object. Finally LateBinding is used as an object of type Object can be bound to object of any type i.e. it behaves as a variant type.

  • The first argument of LateBinding.LateCall method is the object on which the method should be called
  • The second argument is the type of the object i.e. System.Type object
  • The third argument is the name of the method
  • The fourth argument is a set of arguments to be passed to that method
  • The fifth argument is the set of names of the parameters to be passed to that method if they have any
  • The sixth argument is the set of booleans indicating whether to copy back any parameters

Tell me, isn't it very simple?

History

  • 25th October, 2005: Initial post