/// <summary>
 /// Retrieve registration wrappers for all (public, static) methods marked with [ExcelCommand] attributes,
 /// in all exported assemblies.
 /// </summary>
 /// <returns>All public static methods in registered assemblies that are decorated with an [ExcelCommand] attribute
 /// (or a derived attribute)
 /// </returns>
 public static IEnumerable <ExcelCommandRegistration> GetExcelCommands()
 {
     return(from ass in ExcelIntegration.GetExportedAssemblies()
            from typ in ass.GetTypes()
            from mi in typ.GetMethods(BindingFlags.Public | BindingFlags.Static)
            where mi.GetCustomAttribute <ExcelCommandAttribute>() != null
            select new ExcelCommandRegistration(mi));
 }
示例#2
0
 public void OnError(Exception exception)
 {
     // TODO: Is the sequence here important?
     Value = ExcelIntegration.HandleUnhandledException(exception);
     // Set the topic value to #VALUE (not used!?) - converted to COM code in Topic
     _topic.UpdateValue(ExcelError.ExcelErrorValue);
     IsCompleted = true;
 }
示例#3
0
 public void AutoOpen()
 {
     ExcelIntegration.RegisterUnhandledExceptionHandler(globalErrorHandler);
     AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
     ExcelDna.ComInterop.ComServer.DllRegisterServer();
     ExcelApp.AttachApplicationEvents();
     this.InjectWvvwDelegate();
 }
示例#4
0
 private void SetupExcel()
 {
     ExcelIntegration.RegisterUnhandledExceptionHandler(
         delegate(object ex) {
         return(string.Format("Error: {0}", ex.ToString()));
     }
         );
 }
示例#5
0
        public void AutoOpen()
        {
            var listener = new LogDisplayTraceListener();

            Trace.Listeners.Add(listener);
            ExcelIntegration.RegisterUnhandledExceptionHandler(
                ex => "Unhandled EXCEPTION: " + ex.ToString());
            IntelliSenseServer.Install();
        }
示例#6
0
 private static void InitializeIntegration()
 {
     if (!_initialized)
     {
         ExcelIntegration.Initialize(pathXll);
         TraceLogger.IntegrationTraceSource = ExcelIntegration.GetIntegrationTraceSource();
         _initialized = true;
     }
 }
示例#7
0
        public void AutoOpen()
        {
            new AutoXllRegister().RegisterXll();

            ExcelAsyncUtil.Initialize();
            ExcelIntegration.RegisterUnhandledExceptionHandler(ex => $"EXCEPTION: {ex.ToString()}");

            CtpManager.Initialize();
        }
示例#8
0
        /// <summary>
        /// Register all eligible functions in <paramref name="assembly"/>.
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="addInName">This will be used to ensure that all functions start with the
        /// '[<paramref name="addInName"/>].' That means the QuantSA functions need to start with
        /// 'QSA' and plugin function need to start with <see cref="IQuantSAPlugin.GetShortName"/>.</param>
        /// <param name="funcsInUserFile"></param>
        public static void RegisterFrom(Assembly assembly, string addInName, Dictionary <string, bool> funcsInUserFile)
        {
            Log.Info($"Registering Excel functions from {assembly.FullName}");
            var delegates                  = new List <Delegate>();
            var functionAttributes         = new List <object>();
            var functionArgumentAttributes = new List <List <object> >();

            GetDelegatesAndAttributes(assembly, addInName, funcsInUserFile, ref delegates, ref functionAttributes, ref functionArgumentAttributes);
            ExcelIntegration.RegisterDelegates(delegates, functionAttributes, functionArgumentAttributes);
        }
示例#9
0
        internal static HRESULT DllGetClassObject(CLSID clsid, IID iid, out IntPtr ppunk)
        {
            Debug.Print("DllGetClassObject entered - calling InitializeIntegration.");
            HRESULT result;

            InitializeIntegration();
            Logger.Initialization.Verbose("In DllGetClassObject");
            result = ExcelIntegration.DllGetClassObject(clsid, iid, out ppunk);
            return(result);
        }
示例#10
0
 public static void RegisterSlave()
 {
     Console.Beep();
     Console.Beep();
     Console.Beep();
     Console.Beep();
     Excel(xlcMessage, true, $"Loading {path}");
     Thread.Sleep(1000);
     ExcelIntegration.RegisterXLL(path);
 }
示例#11
0
        public void AutoOpen()
        {
            ExcelIntegration.RegisterUnhandledExceptionHandler(ErrorHandler);

            // Register Ctrl+Shift+H to show log window
            XlCall.Excel(XlCall.xlcOnKey, "^H", "ShowLogWindow");

            // Register Ctrl+Shift+A to show introspection window
            XlCall.Excel(XlCall.xlcOnKey, "^A", "ShowIntrospectionWindow");
        }
示例#12
0
        public void AutoOpen()
        {
            ExcelIntegration.RegisterUnhandledExceptionHandler(ErrorHandler);

            try {
                com_addin = new MyCom();
                ExcelComAddInHelper.LoadComAddIn(com_addin);
            } catch (Exception e) {
                MessageBox.Show("Error loading COM AddIn: " + e.ToString());
            }
        }
示例#13
0
 void LoadXLL(string path)
 {
     try {
         logger.Debug($"RegisterXLL '{path}'");
         Directory.SetCurrentDirectory(Path.GetDirectoryName(path));
         var ans = ExcelIntegration.RegisterXLL(path);
     }
     catch (Exception ex) {
         logger.Error(ex, $"Cannot load XLL");
     }
 }
示例#14
0
 /// <summary>Initialize the <see cref="IExcelAddIn"/>.
 /// </summary>
 public void AutoOpen()
 {
     try
     {
         IntelliSenseServer.Install();
         ExcelIntegration.RegisterUnhandledExceptionHandler(UnhandledExceptionHandler);  // add a 'standard-output' if a try-catch block is missing
     }
     catch (Exception e)
     {
         MessageBox.Show(String.Format("{0} Stack trace: {1}", e.Message, e.StackTrace), "Dodoni.net (XL-BasicComponents): Fatal error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
示例#15
0
 /// <summary>
 /// This function is called when the XLL is installed into an Excel spreadsheet
 /// </summary>
 public void AutoOpen()
 {
     try
     {
         ExcelIntegration.RegisterUnhandledExceptionHandler(
             ex => "!!! EXCEPTION: " + ex.ToString());
     }
     catch (Exception ex)
     {
         log.Fatal(ex.ToString());
     }
 }
示例#16
0
        public static void LoadIntegration()
        {
            ExcelIntegration.ConfigureHost(new IntegrationHost());

            // Check the version declared in the ExcelIntegration class
            int integrationVersion = ExcelIntegration.GetExcelIntegrationVersion();

            if (integrationVersion != ExcelIntegrationVersion)
            {
                // This is not the version we are expecting!
                throw new InvalidOperationException("Invalid ExcelIntegration version detected.");
            }
        }
示例#17
0
 public void AutoOpen()
 {
     ExcelIntegration.RegisterUnhandledExceptionHandler(ex => "!!! EXCEPTION: " + ex.ToString());
     ComServer.DllRegisterServer();
     try
     {
         _comAddin = new qXLComAddIn();
         ExcelComAddInHelper.LoadComAddIn(_comAddin);
     }
     catch (Exception ex)
     {
         MessageBox.Show(@"Error loading COM AddIn: " + ex);
     }
 }
        public void Initialize()
        {
            IntelliSenseServer.Register();
            ExcelIntegration.RegisterUnhandledExceptionHandler(ex =>
            {
                var message = (ex as Exception)?.Message;
                if (ex is AggregateException)
                {
                    message = ((AggregateException)ex).GetBaseException().Message;
                }

                return($"#ERROR: {message}");
            });
        }
示例#19
0
        public static RegistrationResults RegisterApi(OpenApiDocument apiDefinition, bool reregister = false)
        {
            List <Delegate>       delegates      = new List <Delegate>();
            List <object>         funcAttribs    = new List <object>();
            List <List <object> > argAttribsList = new List <List <object> >();

            var functionsAdded = new List <string>();

            foreach (var path in apiDefinition.Paths)
            {
                foreach (var operation in path.Value.Operations)
                {
                    delegates.Add(CreateDelegateForOperation(path.Key, path.Value, operation.Key, operation.Value));

                    ExcelFunctionAttribute att = new ExcelFunctionAttribute();

                    att.Name = operation.Value.OperationId;

                    att.Description            = operation.Value.Description;
                    att.HelpTopic              = apiDefinition.ExternalDocs?.Url?.ToString();
                    att.SuppressOverwriteError = reregister;

                    funcAttribs.Add(att);
                    List <object> argAttribs = new List <object>();

                    foreach (var parameter in operation.Value.Parameters)
                    {
                        ExcelArgumentAttribute atta1 = new ExcelArgumentAttribute();
                        atta1.Name        = parameter.Name;
                        atta1.Description = parameter.Description;

                        argAttribs.Add(atta1);
                    }

                    argAttribsList.Add(argAttribs);

                    functionsAdded.Add(att.Name);
                }
            }

            ExcelIntegration.RegisterDelegates(delegates, funcAttribs, argAttribsList);

            var registrationResults = new RegistrationResults
            {
                FunctionsAdded = functionsAdded
            };

            return(registrationResults);
        }
示例#20
0
 private static void DeInitializeIntegration()
 {
     if (_initialized)
     {
         if (_opened)
         {
             ExcelIntegration.DnaLibraryAutoClose();
             XlRegistration.UnregisterMethods();
         }
         TraceLogger.IntegrationTraceSource = null;
         ExcelIntegration.DeInitialize();
         _initialized = false;
         _opened      = false;
     }
 }
        // Called on the VsLinkServer thread - should not block
        public static void VsLinkMessageHandler(VsLinkMessage message)
        {
            var registerXllMessage = message as RegisterAddInMessage;

            if (registerXllMessage != null)
            {
                if (registerXllMessage.AddInPath.EndsWith(".xll"))
                {
                    ExcelAsyncUtil.QueueAsMacro(() => ExcelIntegration.RegisterXLL(registerXllMessage.AddInPath));
                }
                else if (registerXllMessage.AddInPath.EndsWith(".dll"))
                {
                    ExcelAsyncUtil.QueueAsMacro(() => AddInLoader.RegisterDll(registerXllMessage.AddInPath));
                }
            }
        }
示例#22
0
        internal static short XlAutoOpen()
        {
            Debug.Print("XlAddIn.XlAutoOpen - AppDomain Id: " + AppDomain.CurrentDomain.Id + " (Default: " + AppDomain.CurrentDomain.IsDefaultAppDomain() + ")");
            short result = 0;

            try
            {
                if (_opened)
                {
                    DeInitializeIntegration();
                }
                object xlCallResult;
                XlCallImpl.TryExcelImpl(XlCallImpl.xlcMessage, out xlCallResult /*Ignore*/, true, "Registering library " + pathXll);
                InitializeIntegration();
                Logger.Initialization.Verbose("In XlAddIn.XlAutoOpen");

                // v. 30 - moved the setting of _opened before calling AutoOpen,
                // so that checking in DeInitializeIntegration does not prevent AutoOpen - unloading via xlAutoRemove from working.
                _opened = true;

                // InitializeIntegration has loaded the DnaLibrary
                ExcelIntegration.DnaLibraryAutoOpen();

                result = 1; // All is OK
            }
            catch (Exception e)
            {
                // Can't use logging here
                string alertMessage = string.Format("A problem occurred while an add-in was being initialized (InitializeIntegration failed - {1}).\r\nThe add-in is built with ExcelDna and is being loaded from {0}", pathXll, e.Message);
                object xlCallResult;
                XlCallImpl.TryExcelImpl(XlCallImpl.xlcAlert, out xlCallResult /*Ignored*/, alertMessage, 3 /* Only OK Button, Warning Icon*/);
                result = 0;
            }
            finally
            {
                // Clear the status bar message
                object xlCallResult;
                XlCallImpl.TryExcelImpl(XlCallImpl.xlcMessage, out xlCallResult /*Ignored*/, false);
                // Debug.Print("Clear status bar message result: " + xlCallResult);
            }
            return(result);
        }
        //#region AppDomain helper
        //static AppDomain GetAppDomain(string friendlyName)
        //{
        //    IntPtr enumHandle = IntPtr.Zero;
        //    mscoree.ICorRuntimeHost host = new mscoree.CorRuntimeHost();

        //    try
        //    {
        //        host.EnumDomains(out enumHandle);

        //        while (true)
        //        {
        //            object domain;
        //            host.NextDomain(enumHandle, out domain);

        //            if (domain == null)
        //                break;

        //            AppDomain appDomain = (AppDomain)domain;
        //            if (appDomain.FriendlyName.Equals(friendlyName))
        //                return appDomain;
        //        }
        //    }
        //    finally
        //    {
        //        host.CloseEnum(enumHandle);
        //        System.Runtime.InteropServices.Marshal.ReleaseComObject(host); // Why??? Pure cargo-culting here...
        //    }

        //    return null;
        //}
        //#endregion

        #region IntelliSense control function registered with Excel

        static void RegisterControlFunction()
        {
            var method = typeof(IntelliSenseServer).GetMethod("IntelliSenseServerControl", BindingFlags.Static | BindingFlags.Public);
            var name   = "IntelliSenseServerControl_" + _serverId.ToString("N");

            ExcelIntegration.RegisterMethods(new List <MethodInfo> {
                method
            },
                                             new List <object> {
                new ExcelCommandAttribute {
                    Name = name
                }
            },
                                             new List <List <object> > {
                new List <object> {
                    null
                }
            });
            // No Unregistration - that will happen automatically (and is only needed) when we are unloaded.
        }
示例#24
0
        static void RegisterControlMacro()
        {
            var method = typeof(IntelliSenseServer).GetMethod(nameof(IntelliSenseServerControl), BindingFlags.Static | BindingFlags.NonPublic);
            var name   = RegistrationInfo.GetControlMacroName(_serverId);

            ExcelIntegration.RegisterMethods(new List <MethodInfo> {
                method
            },
                                             new List <object> {
                new ExcelCommandAttribute {
                    Name = name
                }
            },                                                                                               // Macros in .xlls are always hidden
                                             new List <List <object> > {
                new List <object> {
                    null
                }
            });
            // No Unregistration - that will happen automatically (and is only needed) when we are unloaded.
        }
        static void RegisterControlMacro()
        {
            Func <object, object> delControl = control => IntelliSenseServerControl(control);
            var name = RegistrationInfo.GetControlMacroName(_serverId);

            ExcelIntegration.RegisterDelegates(new List <Delegate> {
                delControl
            },
                                               new List <object> {
                new ExcelCommandAttribute {
                    Name = name
                }
            },                                                                                               // Macros in .xlls are always hidden
                                               new List <List <object> > {
                new List <object> {
                    null
                }
            });
            // No Unregistration - that will happen automatically (and is only needed) when we are unloaded.
        }
示例#26
0
        public void AutoOpen()
        {
            RegisterFunctions();

            // setup error handler
            ExcelIntegration.RegisterUnhandledExceptionHandler(ex => ex.ToString());

            var app = ExcelDnaUtil.Application as Microsoft.Office.Interop.Excel.Application;

            app.RTD.ThrottleInterval = 100;

            //Open the client connection
            ConnectionMonitor = new ConnectionMonitor();
            ConnectionMonitor.RegisterClient(Client);
            ExcelComAddInHelper.LoadComAddIn(new ComAddIn(Client, ConnectionMonitor));

            //Start the monitor
            ConnectionMonitor.FindAvailableServicesAsync().ContinueWith(result =>
            {
                ConnectionMonitor.Start();
            });
        }
示例#27
0
        public virtual void AutoOpen()
        {
            ExcelIntegration.RegisterUnhandledExceptionHandler(OnError);

            // Set the Parameter Conversions before they are applied by the ProcessParameterConversions call below.
            // CONSIDER: We might change the registration to be an object...?
            var conversionConfig = GetParameterConversionConfig();

            // Get all the ExcelFunction functions, process and register
            // Since the .dna file has ExplicitExports="true", these explicit registrations are the only ones - there is no default processing
            ExcelRegistration.GetExcelFunctions()
            .ProcessParameterConversions(conversionConfig)
            .ProcessParamsRegistrations()
            .RegisterFunctions();

            var registration = new Registration(Container);

            foreach (var methodInfo in Methods)
            {
                registration.AddMethod(methodInfo);
            }

            foreach (var propertyInfo in Properties)
            {
                registration.AddProperty(propertyInfo);
            }

            var bindingService = Container.GetInstance <IBindingService>();
            var application    = (Application)ExcelDnaUtil.Application;

            application.SheetChange += bindingService.OnSheetChange;

            registration.GetAllRegistrations()
            .ProcessParameterConversions(conversionConfig)
            .ProcessParamsRegistrations()
            .ProcessAsyncRegistrations()
            .RegisterFunctions();
        }
示例#28
0
    // Called when addin opens
    public void AutoOpen()
    {
        try
        {
            string pathString = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "QuantSA");
            if (!Directory.Exists(pathString))
            {
                Directory.CreateDirectory(pathString);
            }
            //TODO: Check if newer version of addin exists.

            //Check if functions_all.csv is newer than functions_user.csv.  If it is then
            //merge the new functions in and use that to hide or show inividual functions.
            UpdateUserFunctionFile();

            //Expose only those functions that appear in FunctionsFilenameUser with a true.  The
            //rest will still be there but as hidden.  So that users can share sheets.
            ExposeUserSelectedFunctions();

            //Check in the installation folder for any dlls that include a class of type IQuantSAPlugin
            plugins = new List <IQuantSAPlugin>();
            assemblyImageResources = new Dictionary <string, Bitmap>();
            ExposePlugins();
            foreach (IQuantSAPlugin plugin in plugins)
            {
                plugin.SetObjectMap(ObjectMap.Instance);
                plugin.SetInstance(plugin);
            }
            ExcelIntegration.RegisterDelegates(delegates, functionAttributes, functionArgumentAttributes);
        }
        catch (Exception e)
        {
            string pathString = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "QuantSA");
            string fileName   = Path.Combine(pathString, "QuantSAError.txt");
            File.WriteAllText(fileName, e.ToString());
            throw new Exception("An error occured while opening the QuantSA addin.  Check the error log file for details.");
        }
    }
        /// <summary>
        /// Registers the given macros with Excel-DNA.
        /// </summary>
        /// <param name="registrationEntries"></param>
        public static void RegisterCommands(this IEnumerable <ExcelCommandRegistration> registrationEntries)
        {
            var delList = new List <Delegate>();
            var attList = new List <object>();

            foreach (var entry in registrationEntries)
            {
                try
                {
                    var del = entry.CommandLambda.Compile();
                    var att = entry.CommandAttribute;

                    delList.Add(del);
                    attList.Add(att);
                }
                catch (Exception ex)
                {
                    Logging.LogDisplay.WriteLine("Exception while registering method {0} - {1}", entry.CommandAttribute.Name, ex.ToString());
                }
            }

            ExcelIntegration.RegisterDelegates(delList, attList, null);
        }
示例#30
0
        public void AutoOpen()
        {
            ExcelIntegration.RegisterUnhandledExceptionHandler(ex => "!!! ERROR: " + ex.ToString());

            // Set the Parameter Conversions before they are applied by the ProcessParameterConversions call below.
            // CONSIDER: We might change the registration to be an object...?
            var conversionConfig      = GetParameterConversionConfig();
            var postAsyncReturnConfig = GetPostAsyncReturnConversionConfig();

            var functionHandlerConfig = GetFunctionExecutionHandlerConfig();

            // Get all the ExcelFunction functions, process and register
            // Since the .dna file has ExplicitExports="true", these explicit registrations are the only ones - there is no default processing
            ExcelRegistration.GetExcelFunctions()
            .ProcessParameterConversions(conversionConfig)
            .ProcessAsyncRegistrations(nativeAsyncIfAvailable: false)
            .ProcessParameterConversions(postAsyncReturnConfig)
            .ProcessParamsRegistrations()
            .ProcessFunctionExecutionHandlers(functionHandlerConfig)
            .RegisterFunctions();

            // First example if Instance -> Static conversion
            InstanceMemberRegistration.TestInstanceRegistration();
        }