No matter how you feel about Silverlight 4’s COM interop, it does add an escape hatch out the sandbox when you are running an out-of-browser application. I don’t see many .NET folks getting excited about having to wipe off the dust on their C++ compiler and learn COM all over again for the first time.
Here I want to show a way of making a COM object in pure desktop .NET and using it from Silverlight. This stuff has been around since the dawn of .NET, but it may be a little more obscure to others who have never done it.
Step 1:
Create a new Silverlight 4 application and add a desktop .NET class library (show here as the “COMObject” project)
Step 2:
Setup your Silverlight application to support out-of-browser support AND don’t forget about the elevated trust!
Step 3:
Get your desktop .NET class library ready for COM. In the project settings of the class library set your stuff up like this:
This setting bellow is NOT required, but is there for convenience so you don’t have to manually run “regasm” to register your assembly. YOU MUST RUN VS2010 WITH ADMINISTRATOR RIGHTS IF YOU HAVE THIS OPTION!
Step 4:
In your desktop .NET class library add a class like this:
[ProgId("SilverlightCOM.Example")][ClassInterface(ClassInterfaceType.AutoDual)]
[Guid("5267F53A-0E5F-490A-A891-FFE8B3840D72")]public class ComClass
{ [ComVisible(true)]
public void RunMe()
{ System.Windows.Forms.MessageBox.Show("Hello from .NET via COM!"); }
}
Make sure to give it your own GUID and ProgId!
Step 5
In your Silverlight project add some code like this:
dynamic comClass = ComAutomationFactory.CreateObject("SilverlightCOM.Example");
comClass.RunMe();
Step 6:
Run your Silverlight application and install it out-of-browser and you are done!
Conclusion:
Yeah its that easy. If you need to manually register your assembly manually, use regasm!
The source code