Monday, May 14, 2007

How to access a .NET assembly method from JavaScript

There are many ways to implement solutions for this kind of situations. There are also different languages to use. In this particular case, I implemented a JavaScript activeX instantiation of a .NET C# assembly. It is required that the assembly has a public COM visible interface, meaning, public methods that can be accessed from not .NET objects. To access assembly functionality you have to instantiate the .NET assembly as an activeX object in the web page. This can be really easy using JavaScript. Let’s take a look at the code:

// Variable to keep your Program Id. Has to be exactly the same than

// the Program Id registered on the windows registry.
var yourProgId = "YourProgramId";

// Variable to instantiate your assembly as an activeX object.

var yourObj = new ActiveXObject(yourProgId);

// Once the assembly is instantiated as an activeX object in the page,
// you can easily access it’s public methods and properties.
try{
if (yourObj.propertyName == false) {
yourObj.methodName(param);
}
}
catch(e){
alert(e.message);
}

Remember, your assembly has to be already registered on the client PC, or you will get an exception when you try to access it’s methods or properties. Using try{} and catch{} blocks is recommended to capture exceptions.I’ll keep adding more information about how to make an assembly COM visible, and how to easily and automatically register it on the client PC.


Happy Coding
-ArbBot

No comments:

Post a Comment