Implementing a COM component in... VBScript

Normally, a VBS scripts is used to invoke COM components (written in C++ or even C#). But did you know that it can be the other way around? That is, invoking VBScript code from, say, C#.

Here is a simple exercise:

1) Write a text file with the WSC extension (say, test.wsc) and with the content below. The WSC acronym stands for Windows Scripting Component technology, which is present in Windows XP for example. More details on MSDN here.

<?XML version="1.0"?>
<component id="ScriptletFactorial">
<registration progid="MyComponent.Factorial"/>
<public>
<method name="factorial"/>
</public>

   <script language="VBScript">
<![CDATA[
Function factorial(n)
If isNumeric(n) Then
If n <= 1 Then
factorial = 1
Else
factorial = n * factorial(n-1)
End If
Else
factorial = -2 ' Error code.
End If
End Function
]]>
</script>
</component>

2) Register this component with the following command line:

      regsvr32 /i: Y:\garbage\wsc\test.wsc C:\WINDOWS\system32\scrobj.dll

3) Now, you can simply use your new component, from C# for example.