Wednesday, September 29, 2021

Transform COM+ serviced component to WCF Service

With the advent of WCF, there is a paradigm shift in developing applications interacting across network. However porting existing COM based applications to WCF architecture can be daunting task. A balance can be achieved by deploying existing COM based applications as a WCF service so that it can be accessed by WCF clients.

Any COM component can be simply made as a WCF service using he LBGenrator.Following defines the process.
1.      Select COM components as described in DCOM Client
2.      Navigate to WCF Server tab, enter a namespace for the generated wrapper class
3.      The Generate Code option does following
a.       Scan through the selected COM objects and generate an Interface for each
b.      A project is created containing a COM object COM_LB_<prog id> that implements ServicedComponent and the interface
c.       This project is compiled and wcfserver.dll is generated and copied to wcfserver.dll

Example
As described in the previous post, use sillycalc.wsc. Copy the code and save it to sillycalc.wsc and register it.
Load the WCF component in a COM+ Application as discussed in the previous post.


 
Load  the wsc file as shown below and generate wcfserver.dll from WCF Server tab. This contains a COM class implementing wcf service. wcfserver.COM_LB_SillyCalc_WSC_1. 
Copy wcfserver.dll from the output folder and Execute following command to deploy  WCF service.

ComAppHelper -ins -app:wcfcalc  -gac -runforever -svc  D:\Github\TechBlog\COM+\WSC\wcf_client\wcfserver.dll


WCF Client

Create a console project and add a service reference for address net.pipe://localhost/wcfcalc/wcfserver.COM_LB_SillyCalc_WSC_1/mex



The app.config needs be edited to comment as below:
       
	   
<!--
<identity>
<userPrincipalName value="VEDAVYASARAO\rvvya" />
</identity>
-->

 
 

Consume the service as below
       
	   
static void Main(string[] args)
{
    var x = new ServiceReference1.SillyCalc_WSC_1Client();
    Console.WriteLine("calling x.add(10, 2) Result:{0}", x.add(10, 2));
    Console.ReadKey();
}

 
 

Result



Adding a  different service endpoints to WCF service
Currently the installer deploys a named pipes endpoint. Additional endpoint such as net.tcp can be easily added using “SCConfiguration Editor”(svcConfigEditor.exe ) as shown below.

  1.         Open the COM+ application from File->Open->COM+ Application.
  2.         Select WCFCalc Application

.     



   3      3. Add a new service point as shown below.


Similarly Managed COM component CalcServer.Calucalator, hosted in a COM+ application can be utilized as  a WCF service.


Source and Binaries can be found here.





Monday, September 13, 2021

Working with Managed COM Component

COM components can also be generated under .net environment using Visual studio and languages such as C#.

A COM component is essentially class library having an interface declared as below.

    [ComVisible(true)]
    [Guid("E3D02A14-ED36-471E-BE32-2D65F1BC97DA")]
    public interface ICalucalator
    {
        int add(int op1, int op2);
    }
and class implementation as below. TheComvisible attribute makes the class visible to COM based clients and the guid serves as clsid. The class name serves as the second parts of the program id. for example, servercalc.calucalator.
    [ComVisible(true)]
    [Guid("0AD70785-5539-4EE0-83D5-37A62CF5318F")]
    public class Calucalator :  ICalucalator
    {

        public int add(int op1, int op2)
        {
            return op1 + op2;
        }
      
    } 
AssemblyInfo.cs should look as below. The Comvisible attribute makes the class visible to COM based clients and the guid identifies the  typelib.  A typelib contains metadata about the classes, interfaces, methods within the assembly. It will be used com based clients to make calls.
// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8CF1D751-666D-40C6-A741-0C14B4727A9E")]
the project file .csproj should look as below. The assembly name serves as the first part of the program id. for example, servercalc.calucalator. The registerforInterop executes RegAsm for the assembly making it visible for  COM clients.
<AssemblyName>CalcServer</AssemblyName>
<RegisterForComInterop>true</RegisterForComInterop>

Note:- All the guids must be unique. if the same project is  cloned they must be replaced apart from the code 

Registration
The assembly must be registered. it's done Regasm tool as below. Note that a typelibrary is also generated.

regasm D:\Github\TechBlog\COM+\Managed\server\bin\CalcServer.dll /tlb:D:\Github\TechBlog\COM+\Managed\server\bin\CalcServer.tlb

Com callable wrappers are used to consume managed com components from native clients. The process involves creating the type library from the managed dll by using tlbexp.exe and import it. Later native clients query type library for published interfaces to make calls. 

Serviced Component
COM+ offers services such as object pooling. A Serviced component can take advantage of this by deriving from System.EnterpriseServices.ServicedComponent class.
    public class Calucalator : System.EnterpriseServices.ServicedComponent, ICalucalator
This enable overriding the default methods such as object pooling with custom code.


Scripting host Client
The component can be consumed by a scripting host client such as cscript or wscript as below. Save the 
Save the following to calcserver_client.vbs.
       
 set calc = createobject("CalcServer.Calucalator")
 msgbox calc.add(40,6)
 
 
Execute it in a WOW64 command window. The message box should popup as shown below


C# client
Unlike unmanaged com component, managed com component cannot be consumed by importing typelibrary in a managed client. It needs to be hard coded as below. 

       
static void Main(string[] args)
{
    dynamic remoteobj = Activator.CreateInstance(Type.GetTypeFromProgID("CalcServer.Calucalator"));
    Console.WriteLine("40+6={0}", remoteobj.add(40, 6));
}
 
 
The output looks as below:

Debugging scripting component
It's possible to debug Managed Com Component at run time using Visual Studio as below.
1. Start the client
2. Load the symbols for the managed com component

3.step into the managed component  implementation



Source and Binaries can be found here.


Thursday, September 2, 2021

Working with WSC (Windows scripting component)

Often times an application require a certain functionality to be extended by users .For example a workflow engine can let users customize start or end steps. The .NET framework provides perfect mechanism to implement this but it comes with a steep leaning curve.

Windows scripting component or WSC provide an easier javascript or vscript based solution for creating COM components  using command line tools. WSC are essentially XML based  that can be used to generate COM based object that can even support events.
What's more interesting is it's possible to host these in COM+ applications for remote access and integrated as a WCF service.

Below is a simple example. This hosts a single component that has a single method Add.
<?xml version="1.0"?>
<component>

<?component error="true" debug="true"?>

<registration
 description="silly calculator"
 progid="SillyCalc.WSC"
 version="1"
 classid="{502B2117-D5AC-41B2-9441-B466932F613F}"
>
</registration>

<public>
 <method name="add" >
 <PARAMETER  name="op1" />
 <PARAMETER  name="op2" />
 </method >
</public>

<script language="VBScript">
<![CDATA[


Function add(op1, op2)
add=op1 + op2
End Function 


]]>
</script>

</component>

The window scripting component wizard can also be used for creating wscs. It can be installed by running wz10en.exe.

Registration
  1. Save the above text to file sillycalc.wsc
  2. open a WOW64 command window and run following command.
regsvr32 sillycalc.wsc

Scripting host Client
The component can be consumed by a scripting host client such as cscript or script as below. Save the following to sillycalc_client.vbs and execute it in a WOW64 command window. The message box should popup as shown below. 
       
        set calc = createobject("sillycalc.wsc")
	msgbox calc.add(40,6)
       
 


C# client with WSC unregistered
The wsc can be consumed directly by a c# client without even registering as below:
   dynamic remoteobj;
   remoteobj = (dynamic)Marshal.BindToMoniker(@"script:D:\Github\TechBlog\COM+\WSC\server\SillyCalc2.wsc");
   Console.WriteLine("40+6={0}", remoteobj.add(40,6));
       
 
However this requires hardcoding the method names and its parameters which can be problematic to maintain.

C# client with WSC registered
CLR uses Runtime callable wrapper to consume unmanaged COM components. 
The process involves generating an interop dll from the type library of  the unmanaged COM dll usng tlbimp.exe and adding it as a reference to the project. Alternatively this can be done by adding tlb as a reference.
However this method does not work for wsc tlb files as Visual studio does not interpret wsc tlb files.
The when wsc is registered, it can be consumed by a c# client  by hard coding method name as below. also this needs to be executed in WOW64 command window.
       
 dynamic remoteobj;
 remoteobj=(dynamic)Activator.CreateInstance(Type.GetTypeFromProgID("SillyCalc.WSC.1"));
 Console.WriteLine("40+6={0}", remoteobj.add(40, 6));
 
 

The output should like below:

Debugging scripting component
It's possible to debug WSCs at run time using Visual Studio as below.

CSCRIPT //X  calc_client.vbs

This will  launch JIT debugger and source code is loaded into it.
stepping into the wsc method will load the source code of the wsc as below

Note:- The wsc file should explicitly allow debugging as below.

<?component error="true" debug="true"?> 

Source and Binaries can be found here.