August 14, 2008

AcitveX Controls - how to create one and call with Javascript

One way to get a .NET object to run in a browser is to create a User Control in .NET.
You can then call this User Control from Javascript in your client.

There's nothing magical about this except, it only works on IE and there are a few small bits that you must implement in order for your User Control to be picked up, the errors you get aren't very helpful so I recommend following these steps (Some of these I'm not sure if they're required but they've worked for me).

  1. Create a Class Project in Visual Studio 2005.
  2. Add a User Control to the project.
  3. In the User Control Designer add a TextBox Control
  4. Add a Property to your class to set the Text of the TextBox you've just added.
public void AddText(string time)
{
if (_timerTextBox == null)
{
_timerTextBox = new System.Windows.Forms.TextBox();
_timerTextBox.Text = " Time (msec)";
}
_timerTextBox.Text += ("\r\n" + time);
this.Refresh();
}
  1. Create an Interface in the same namespace as your UserControl and add the signature of the Property you've just added.
public interface IActiveXTimerControl
{
void AddText( string time);
}
  1. Mark the Class with a the GuidAttribute and also inherit it from the interface you've just created.
namespace ActiveXTimerControl
{
[ClassInterface(ClassInterfaceType.AutoDual)]
[GuidAttribute("4F3B57CE-XXXX-XXXX-ACBD-EBB2380990E7")]
public partial class TimerControl : UserControl, IActiveXTimerControl
{
public TimerControl()
{
InitializeComponent();
}
}
}
  1. Mark the Assembly as Com Visible in the Project Properties "Assembly Information".
  2. Compile this and register it by adding a Post-Build Event to your project
  3. regasm $(TargetFileName) /tlb /codebase

You now have an Assembly which has a control usable in a browser.
Now to use this Control
Create a website and add the following aspx page (the content of this could also be in html page) inside the body




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>

<OBJECT id="activeXTimerControl" name="activeXTimerControl" classid="clsid:4F3B57CE-D9CA-41c3-ACBD-EBB2380990E7" style="width: 504px; height: 182px" codebase="Bin/ActiveXTimerControl.dll" class="ActiveXTimerControl.TimerControl">
</OBJECT>

<form name="frm" id="frm">
<input type=button value="Click me" onClick="doScript();">
</form>


</body>

<script language="javascript">
function doScript()
{
activeXTimerControl.Start();
activeXTimerControl.Stop();
activeXTimerControl.AddText("time");

}
</script>

</html>



Note the clsid above this is crucial it must be the same GUID value as you gave the Class.

No comments: