Wednesday, November 09, 2005

How to create a VB Script Object and call methods on it

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 call DeleteExtensionRecord Method on it.

private void RemovesWebServiceExtension(string extensionPath)
{
try
{
object ext = 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;
}
}
where Interaction module contains procedures to interact with objects, applications and system. Runtime Helper class contains 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 varient type.

The first argument of LateBinding.LateCall method is the object on which the method should be called, second argument is the type of the object i.e. System.Type object, the third argument is the name of the method, 4th is set of arguments to be passed to that method, 5th argument is the set of names of the parameters to be passed to that method if they have any, and finally 6th argument is the set of booleans indicating whether to copy back any parameters.
Tell me isnt it very simple

No comments: