Skip to content

Creating an ActiveX control in .Net using C#

Create a new Class Library project in Visual Studio 2010

* This post is taken from: Creating an ActiveX control in .Net using C# by Olav Aukan

  1. Start-Run-devenv or Click- Microsoft Visual Studio 2010.
  2. After starting Visual Studio click File – New – Project and select Class Library under C#.
  3. Call the project ‘AxControls’ and click OK.
Class

Class

Create a new class that inherits from UserControl

  1. Rename ‘Class1.cs’ to “HelloWorld.cs”, making sure to rename the class name as well.
  2. Add a project reference to System.Windows.Forms.
Reference

Reference

Create a new interface that exposes the controls methods and properties to COM interop

  1. Right click the project in Visual Studio and click Add –> New Item.
  2. Select ‘Interface’ from the list of components, name it ‘IHelloWorld.cs’ and click Add.
iHelloWorld

iHelloWorld

3.  Edit the ‘IHelloWorld.cs’ file so it looks like this:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace AxControls
{
    [ComVisible(true)]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    [Guid("E66C39CB-BB8B-4738-AA0E-5E0D1F2DB230")]
    public interface IHelloWorld
    {
        string GetText();
    }
}
[ComVisible(true)] makes the interface visible to COM.
[Guid("E66C39CB-BB8B-4738-AA0E-5E0D1F2DB230")] let's us manually assign a GUID to the interface. Use guidgen.exe to generate your own.

Make the control class implement the new interface

Make the HelloWorld class implement the IHelloWorld interface and have the GetText() method return a string of your choice. This is what the file might look like:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace AxControls
{
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    [Guid("D100C392-030A-411C-92B6-4DBE9AC7AA5A")]
    [ProgId("AxControls.HelloWorld")]
    [ComDefaultInterface(typeof(IHelloWorld))]
    public class HelloWorld : UserControl, IHelloWorld
    {
        #region IHelloWorld Members
        public string GetText()
        {
            return "Hello ActiveX World!";
        }
        #endregion
    }
}

Mark the control as safe for scripting and initialization

By default IE will not allow initializing and scripting an ActiveX control unless it is marked as safe. This means that we won’t be able to create instances of our ActiveX class with JavaScript by default. We can get around this by modifying the browser security settings, but a more elegant way would be to mark the control as safe. Before you do this to a “real” control, be sure to understand the consequences. . We will mark the control as safe by implementing the IObjectSafety interface.

  1. Right click the project in Visual Studio and click Add -> New Item.
  2. Select ‘Interface’ from the list of components, name it ‘IObjectSafety.cs’ and click Add.
iObjectSafety

iObjectSafety

3.   Edit the ‘IObjectSafety.cs’ file so it looks like this:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace AxControls
{
    [ComImport()]
    [Guid("51105418-2E5C-4667-BFD6-50C71C5FD15C")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IObjectSafety
    {
        [PreserveSig()]
        int GetInterfaceSafetyOptions(ref Guid riid, out int pdwSupportedOptions, out int pdwEnabledOptions);
        [PreserveSig()]
        int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions);
    }
}
4.  Make the HelloWorld class implement the IObjectSafety interface. The end result should look something like this:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace AxControls
{
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    [Guid("D100C392-030A-411C-92B6-4DBE9AC7AA5A")]
    [ProgId("AxControls.HelloWorld")]
    [ComDefaultInterface(typeof(IHelloWorld))]
    public class HelloWorld : UserControl, IHelloWorld, IObjectSafety
    {
        #region IHelloWorld Members
        public string GetText()
        {
            return "Hello ActiveX World!";
        }
        #endregion
        #region IObjectSafety Members
        public enum ObjectSafetyOptions
        {
            INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x00000001,
            INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x00000002,
            INTERFACE_USES_DISPEX = 0x00000004,
            INTERFACE_USES_SECURITY_MANAGER = 0x00000008
        };

        public int GetInterfaceSafetyOptions(ref Guid riid, out int pdwSupportedOptions, out int pdwEnabledOptions)
        {
            ObjectSafetyOptions m_options = ObjectSafetyOptions.INTERFACESAFE_FOR_UNTRUSTED_CALLER | ObjectSafetyOptions.INTERFACESAFE_FOR_UNTRUSTED_DATA;
            pdwSupportedOptions = (int) m_options;
            pdwEnabledOptions = (int) m_options;
            return 0;
        }
        public int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions)
        {
            return 0;
        }
        #endregion
    }
}

Create a .msi installer for the control

Before an ActiveX control can be used it must be installed and registered on the client. This can be done in a number of ways, from manually editing the registry to using regasm.exe, but we’re going to create a Vistual Studio setup project to handle the installation for us.

  1. Right click the Visual Studio solution, select Add -> New Project and select Setup Project under Other Project Types.
  2. Call the project ‘AxControlsInstaller’ and click OK.
AxControlsInstaller

AxControlsInstaller

3.        Right click the ‘AxControlsInstaller’ project, select Add -> Project Output, select ‘Primary output’ from the ‘AxControls’

Primary Output

Primary Output

project and Click ‘OK’.

  1. Right click ‘Primary output from AxControls (Active)’ and select Properties.
  2. Change the Register property from ‘vsdrpDoNotRegister’ to ‘vsdrpCOM’.
  3. Right click the ‘AxControlsInstaller’ project and select Build.
The installer should now be located in the AxControlsInstaller’s output folder (bin\Debug or bin\Release). In the corporate domain this .msi file can de run manually on the client, or automatically with a Group Policy.

Package the installer in a .cab file for web deployment

For public web sites we obviously can’t deploy our ActiveX control to the client with a Group Policy. In this case we’re gonna have to use Internet Explores built-in ability to download and install controls that are packaged in .cab files.

  1. Download the Microsoft Cabinet Software Development Kit.
  2. Unpack the kit to a local folder and copy Cabarc.exe to the ‘AxControlsInstaller’ folder.
  3. Create a new file named ‘AxControls.inf’ in the ‘AxControlsInstaller’ folder and add the following content:
[version]
signature="$CHICAGO$"
AdvancedINF=2.0

[Add.Code]
AxControlsInstaller.msi=AxControlsInstaller.msi

[AxControlsInstaller.msi]
file-win32-x86=thiscab
clsid={1FC0D50A-4803-4f97-94FB-2F41717F558D}
FileVersion=1,0,0,0

[Setup Hooks]
RunSetup=RunSetup

[RunSetup]
run="""msiexec.exe""" /i """%EXTRACT_DIR%\AxControlsInstaller.msi""" /qn
  • Click the AxControlsInstaller project and then press F4 or (View -> Properties Window if it’s not visible).
  • Click the ‘…’ button next to the PostBuildEvent property and add the following content:
"$(ProjectDir)\CABARC.EXE" N "$(ProjectDir)AxControls.cab" 
"$(ProjectDir)AxControls.inf" "$(ProjectDir)$(Configuration)\AxControlsInstaller.msi"
  • Right click the ‘AxControlsInstaller’ project and select Build.
  • There should now be a ‘AxControls.cab’ file in the ‘AxControlsInstaller’ folder.

Ininitalize and test the control with JavaScript

  1. Right click the AxControls solution, select Add -> New Project and select ‘ASP.Net Web Application’ under ‘Web’.
  2. Call the project ‘WebAppTest’ and click OK.
  3. Right click the ‘WebAppTest’ project, select Add -> New Item and select ‘HTML Page’.
  4. Call it ‘index.html’ and click OK.
  5. Add the following content to index.html:
<html>
    <head>

        <objectname="axHello" style='display:none' id='axHello' classid='CLSID:D100C392-030A-411C-92B6-4DBE9AC7AA5A'
 codebase='AxControls.cab#version=1,0,0,0'></object>
      <script language="javascript">

        <!-- Load the ActiveX object  -->
        var x = new ActiveXObject("AxControls.HelloWorld");

        <!-- Display the String in a messagebox -->
        alert(x.GetText());

      </script>
    </head>
    <body>
    </body>
</html>
Note that 'classid' matches the GUID of the HelloWorld control.
  • Right click ‘index.html’ and select ‘Set as start page’.
  • Right click the ‘WebAppTest’ project and select ‘Set as startup project’.
  • Copy ‘AxControls.cab’ from the ‘AxControlsInstaller’ folder to the same folder as index.html.
  • Uninstall the control from the client by going to Control Panel -> Add or Remove.., selecting ‘AxControlsInstaller’ on the list and clicking Uninstall. This forces Internet Explorer to download and install the .cab file and is an important step in case you’ve already installed the control.
  • Run the application (F5). This will open ‘index.html’ in Internet Explorer.
  • Internet Explorer will display a security warning, asking if you want to install ‘AxControls.cab’. Click Install.
install

Install ActiveX

When the page loads it should display a message box with the string you defined in HelloWorld’s GetText() method.
Hello ActiveX World!

“ACCESSORS AND MUTATORS in Asp.Net”

Accessors:-

1.	Read or obtain the value of private member variables.
	This must be done in a manner that maintains the integrity of the private member data.

2.	Display the value of private member variables.
	The displayed information should be user friendly, i.e., formatted in a fashion easily readable and understandably by the user.

3.	Print the value of private member variables.
	When an inappropriate attempt is made to change the value of a private data member, a properly written get function with good 		
        characteristics will be programmed to notify the user. User management should receive written notification of all inappropriate 		
        activity as soon as it occurs.



Mutators:-

1.	Modify the value of private data members.
	Public set functions set the value of private data members. However, set functions should not just change data. Set functions must be 
	programmed to make sure what they are being called to do is correct before they do it. Properly written set functions are the first 	
	line of	defense against, “garbage in, garbage out.”

2.	Validate the value of private data members.
	When an inappropriate attempt is made to change the value of a private data member, a properly written set function will be 	
        programmed to prevent the modification.

Example:-

using system;
public class Department
{
private string departname;
.......
// Accessor.
public string GetDepartname()
{
  return departname;
}
// Mutator.
public void SetDepartname( string a)
  {
    departname=a;
  }
}

How do we prevent the backspace key being used by the browser to move back to previous page in history

How do we prevent the backspace key being used by the browser to move back to previous page in history

How do we prevent the backspace key being used by the browser to move back to previous page in history

Most Wicket Holders at ICC Cricket World Cup 2011

Most Wicket Holders at ICC Cricket World Cup 2011

Most Wicket Holders at ICC Cricket World Cup 2011

Want more traffic? Publicize now makes it easy (via WordPress.com News)

Want more traffic? Publicize now makes it easy We've made some big user experience improvements to how the traffic building feature called Publicize works.  This feature allows you to connect your WordPress.com blog to your account on social networking services like Twitter and Facebook, broadcasting your posts to your friends automatically for you. In the past it took a few steps to figure out how to get going. Now it's just a click away. Starting today, when you publish a post, you'll see a … Read More

via WordPress.com News

Mark the method obsolete in c# (via Navneet Nagpal’s Blog)

Mark the method obsolete in c# We usually create libraries and define some reusable methods that are used across applications. The new enhancements can be due to change in name or method with different signature. But it becomes a cumbersome task to replace the older method with new enhanced one. So here is the simpler way to introduce new method and simultaneously maintains backward compatibility for applications that are using the older method. Here is the solution, create ne … Read More

via Navneet Nagpal's Blog

Handling null values in DataTable’s DateTime columns using “SqlDateTime” Type (via Ilyas Ahmad’s blog)

One the most important aspects of writing this article to share knowledge and making open and easily available so that other can be utilized. Problem While working in one of our project we came across a problem. Database tables contains null data in date and time columns In a C# code a “DataTable” is prepared to retrieve data from Database using ADO.net If In database query Date type column is null then c# “DataTable’s” DateTime” type column hold … Read More

via Ilyas Ahmad's blog

%d bloggers like this: