26

I was tasked with writing a real-time Excel automation add-in in C# using RtdServer for work. I relied heavily on the knowledge that I came across in Stack Overflow. I have decide to express my thanks by writing up a how to document that ties together all that I have learned. Kenny Kerr's Excel RTD Servers: Minimal C# Implementation article helped me get started. I found comments by Mike Rosenblum and Govert especially helpful.

Community
  • 1
  • 1
Frank
  • 2,759
  • 4
  • 31
  • 43
  • Good effort, I remember the first time I tried to get one of those working the just weren't any examples around. I'm sure this will help someone out :) I'll two things. 1) you can create an xla which wraps up the call to RTD in a function which will give you a cleaner, clearer syntax and error handling on the Excel end. Second, if you do any VSTO stuff, and to a lesser extend stuff with IRTDServers coded in .net, use the options dialog in Excel to simulate Excel being blocked. Your code has to deal with it. – Ian Mar 22 '11 at 20:53
  • Very true. The pull request from Excel (RefreshData) may come almost immediately after you call UpdateNotify but there are many things that could delay it indefinitely (dialog boxes, entering a formula, etc). You can't queue updates forever. – Frank Mar 23 '11 at 02:16
  • I also agree that in general you do not want to force a human being to call the RTD function directly. It is easy to create a wrapper function in VBA. I am not sure how to create a wrapper function in C# and have posted a question related to that [here](http://stackoverflow.com/questions/5398152/how-do-i-create-an-excel-automation-add-in-in-c-that-wraps-an-rtd-function) – Frank Mar 23 '11 at 02:18
  • @Frank - I am not sure how to write a wrapper in c#, but if you were to write a UDF wrapper in c++ - you can use xlfRtd (part of the excel 2007+ c api) to wrap the call to your rtd server. – quixver Feb 05 '13 at 18:18

3 Answers3

34

(As an alternative to the approach described below you should consider using Excel-DNA. Excel-DNA allows you to build a registration-free RTD server. COM registration requires administrative privileges which may lead to installation headaches. That being said, the code below works fine.)

To create a real-time Excel automation add-in in C# using RtdServer:

1) Create a C# class library project in Visual Studio and enter the following:

using System;
using System.Threading;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

namespace StackOverflow
{
    public class Countdown
    {
        public int CurrentValue { get; set; }
    }

    [Guid("EBD9B4A9-3E17-45F0-A1C9-E134043923D3")]
    [ProgId("StackOverflow.RtdServer.ProgId")]
    public class RtdServer : IRtdServer
    {
        private readonly Dictionary<int, Countdown> _topics = new Dictionary<int, Countdown>();
        private Timer _timer;

        public int ServerStart(IRTDUpdateEvent rtdUpdateEvent)
        {
            _timer = new Timer(delegate { rtdUpdateEvent.UpdateNotify(); }, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
            return 1;
        }

        public object ConnectData(int topicId, ref Array strings, ref bool getNewValues)
        {
            var start = Convert.ToInt32(strings.GetValue(0).ToString());
            getNewValues = true;

            _topics[topicId] = new Countdown { CurrentValue = start };

            return start;
        }

        public Array RefreshData(ref int topicCount)
        {
            var data = new object[2, _topics.Count];
            var index = 0;

            foreach (var entry in _topics)
            {
                --entry.Value.CurrentValue;
                data[0, index] = entry.Key;
                data[1, index] = entry.Value.CurrentValue;
                ++index;
            }

            topicCount = _topics.Count;

            return data;
        }

        public void DisconnectData(int topicId)
        {
            _topics.Remove(topicId);
        }

        public int Heartbeat() { return 1; }

        public void ServerTerminate() { _timer.Dispose(); }

        [ComRegisterFunctionAttribute]
        public static void RegisterFunction(Type t)
        {
            Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(@"CLSID\{" + t.GUID.ToString().ToUpper() + @"}\Programmable");
            var key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"CLSID\{" + t.GUID.ToString().ToUpper() + @"}\InprocServer32", true);
            if (key != null)
                key.SetValue("", System.Environment.SystemDirectory + @"\mscoree.dll", Microsoft.Win32.RegistryValueKind.String);
        }

        [ComUnregisterFunctionAttribute]
        public static void UnregisterFunction(Type t)
        {
            Microsoft.Win32.Registry.ClassesRoot.DeleteSubKey(@"CLSID\{" + t.GUID.ToString().ToUpper() + @"}\Programmable");
        }
    }
}

2) Right click on the project and Add > New Item... > Installer Class. Switch to code view and enter the following:

using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace StackOverflow
{
    [RunInstaller(true)]
    public partial class RtdServerInstaller : System.Configuration.Install.Installer
    {
        public RtdServerInstaller()
        {
            InitializeComponent();
        }

        [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
        public override void Commit(IDictionary savedState)
        {
            base.Commit(savedState);

            var registrationServices = new RegistrationServices();
            if (registrationServices.RegisterAssembly(GetType().Assembly, AssemblyRegistrationFlags.SetCodeBase))
                Trace.TraceInformation("Types registered successfully");
            else
                Trace.TraceError("Unable to register types");
        }

        [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            var registrationServices = new RegistrationServices();
            if (registrationServices.RegisterAssembly(GetType().Assembly, AssemblyRegistrationFlags.SetCodeBase))
                Trace.TraceInformation("Types registered successfully");
            else
                Trace.TraceError("Unable to register types");
        }

        public override void Uninstall(IDictionary savedState)
        {
            var registrationServices = new RegistrationServices();
            if (registrationServices.UnregisterAssembly(GetType().Assembly))
                Trace.TraceInformation("Types unregistered successfully");
            else
                Trace.TraceError("Unable to unregister types");

            base.Uninstall(savedState);
        }
    }
}

3) Right click on the project Properties and check off the following: Application > Assembly Information... > Make assembly COM-Visible and Build > Register for COM Interop

3.1) Right click on the project Add Reference... > .NET tab > Microsoft.Office.Interop.Excel

4) Build Solution (F6)

5) Run Excel. Go to Excel Options > Add-Ins > Manage Excel Add-Ins > Automation and select "StackOverflow.RtdServer"

6) Enter "=RTD("StackOverflow.RtdServer.ProgId",,200)" into a cell.

7) Cross your fingers and hope that it works!

Frank
  • 2,759
  • 4
  • 31
  • 43
  • How does Excel find where the file with the ProgId is located? I am trying to move my Excel Addin to a different machine, but I can't set up it on Excel – Alexey Jul 22 '13 at 14:56
  • To what path does `Trace` write in this example? I can't find it. – Grant Birchmeier Oct 25 '13 at 18:32
  • [Sysytem.Diagnostics.Trace](http://msdn.microsoft.com/en-us/library/system.diagnostics.trace.aspx) is similar to System.Console but is more flexible. It allows you to do things such adding trace levels and adding multiple listeners. – Frank Oct 28 '13 at 02:38
  • What is the significance of the GUID attribute of RtdServer? Do I need to specify it? Where do I get it from? – Grant Birchmeier Jan 28 '14 at 23:41
  • The GUID is required for COM registration. You can generate a GUID using Tools > Create GUID in Visual Studio. – Frank Jan 28 '14 at 23:52
  • It appears to work even if I don't specify a GUID. (And thanks for the Excel-DNA tip; it's great! But still need this RTD stuff for updating cells.) – Grant Birchmeier Jan 29 '14 at 20:45
  • Excel-DNA supports RTD...check out the samples that come with the download. – Frank Jan 29 '14 at 20:51
  • @Frank this is really interesting. Is there an Excel RTD equivalent of TopShelf? TopShelf uses the System.Configuration.Install assembly behind-the-scenes to bootstrap installing a Windows Service. You can see the source code here: https://github.com/Topshelf/Topshelf/search?q=System.Configuration.Install.Installer&unscoped_q=System.Configuration.Install.Installer – John Zabroski Jun 25 '19 at 19:47
8

Calling UpdateNotify from the timer thread will eventually cause strange errors or disconnections from Excel.

The UpdateNotify() method must only be called from the same thread that calls ServerStart(). It's not documented in RTDServer help, but it is restriction of COM.

The fix is simple. Use DispatcherSynchronizationContext to capture the thread that calls ServerStart and use that to dispatch calls to UpdateNotify:

public class RtdServer : IRtdServer
{
    private IRTDUpdateEvent _rtdUpdateEvent;
    private SynchronizationContext synchronizationContext;

    public int ServerStart( IRTDUpdateEvent rtdUpdateEvent )
    {
        this._rtdUpdateEvent = rtdUpdateEvent;
        synchronizationContext = new DispatcherSynchronizationContext();
        _timer = new Timer(delegate { PostUpdateNotify(); }, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
        return 1;
    }


    // Notify Excel of updated results
    private void PostUpdateNotify()
    {
        // Must only call rtdUpdateEvent.UpdateNotify() from the thread that calls ServerStart.
        // Use synchronizationContext which captures the thread dispatcher.
        synchronizationContext.Post( delegate(object state) { _rtdUpdateEvent.UpdateNotify(); }, null);
    }

    // etc
} // end of class
John Zabroski
  • 1,878
  • 2
  • 22
  • 46
dlaudams
  • 151
  • 1
  • 2
  • Very good point (another option is to have a thread-safe collection to read/write from). However, from a pure C# class library, which additional reference is needed to locate DispatcherSynchronizationContext? I can't find it (and I suspect it's a WPF-specific thing). – Carl Cook Jul 30 '17 at 17:45
2

Following the previous two answers for the RTD server worked for me. However I ran into an issue when on an x64 machine running Excel x64. In my case, until I switched the "target platform" of the project to x64, Excel always showed #N/A.