Excel DNA: Strange Exception of cast while using ConfigurationManager.GetSection

224 views
Skip to first unread message

APaul94

unread,
Sep 15, 2015, 1:28:50 PM9/15/15
to Excel-DNA
Hi, I try to read my app.config and I receive a strange exception.
My config file is renamed has MyAddin-Addin64.xll.config

Config :
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="FactoryUnityConfig" type="Configuration.FactoryUnitySection,
MyAddin" />
    </configSections>


    <FactoryUnityConfig>
        <!-- application part -->
        <AdminBusinessCore  Implementation="AdminBusinessCore.AdminBusinessCoreImpl" Assembly="AdminBusinessCore" IsSingleton="true" />
[...]

In My c# the Configuration Section/element are defined with :

    public class FactoryUnitySection : ConfigurationSection
    {
        #region ---- application components ---
        [ConfigurationProperty("AdminBusinessCore")]
        public FactoryUnityElement FeederBusinessCore { get { return (FactoryUnityElement)this["AdminBusinessCore"]; } }
[...]

and

    public class FactoryUnityElement : ConfigurationElement
    {
        [ConfigurationProperty("Implementation", IsRequired = true)]
        public string Implementation { get { return (string)this["Implementation"]; } }

        [ConfigurationProperty("Assembly", IsRequired = true)]
        public string Assembly { get { return (string)this["Assembly"]; } }

        [ConfigurationProperty("IsSingleton", DefaultValue=false, IsRequired = true)]
        public bool IsSingleton { get { return (bool)this["IsSingleton"]; } }
    }

I try to read in AutoOpen function :

        private void initAddin()
        {
            try
            {
                FactoryUnitySection factoryUnitSection = (FactoryUnitySection)ConfigurationManager.GetSection("FactoryUnityConfig");
[...]
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("Unable to get config of the RibbonAdmin");
                System.Diagnostics.Trace.WriteLine(ex);

                throw;
            }
        }

The exception is:

[A]Configuration.FactoryUnitySection ne peut pas être converti en [B]Configuration.FactoryUnitySection.
Le type A provient de 'MyAddin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' dans le contexte 'Default' à l'emplacement 'D:\Sources\Branches\POC-Excel-UDF\_bin\Debug\POC\MyAddin.dll'.
Le type B provient de 'MyAddin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' dans le contexte 'LoadNeither' d'un tableau d'octets.

[A]Configuration.FactoryUnitySection can not be converted in [B]Configuration.FactoryUnitySection.The type A is into 'MyAddin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in context 'Default' at path 'D:\Sources\Branches\POC-Excel-UDF\_bin\Debug\POC\MyAddin.dll'.The type B is into 'MyAddin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in context 'LoadNeither' from bytes array.
I have trying with "var test = ConfigurationManager.GetSection("FactoryUnityConfig");" to display test variable with debugger, but debugger can not display it.

Have you some idea or work arround ?

The error happen even if I try the packaged version of xll.

Thanks

Govert van Drimmelen

unread,
Sep 15, 2015, 1:39:01 PM9/15/15
to exce...@googlegroups.com
I think the ConfigurationManager is doing its own load of the "MyAddin" assembly, leading to two copies being loaded - first the onw that is LoadFromBytes="true" loaded by Excel-DNA, and then the version that is loaded by the ConfigurationManager.

The problem should go away if you do either of the following:
* Mark the <ExternalLibrary ... LoadFromBytes="false" />
* Use the packed add-in in a separate directory (where the MyAddIn.dll is not present).

-Govert


From: exce...@googlegroups.com [exce...@googlegroups.com] on behalf of APaul94 [ap...@free.fr]
Sent: 15 September 2015 07:21 PM
To: Excel-DNA
Subject: [ExcelDna] Excel DNA: Strange Exception of cast while using ConfigurationManager.GetSection

--
You received this message because you are subscribed to the Google Groups "Excel-DNA" group.
To unsubscribe from this group and stop receiving emails from it, send an email to exceldna+u...@googlegroups.com.
To post to this group, send email to exce...@googlegroups.com.
Visit this group at http://groups.google.com/group/exceldna.
For more options, visit https://groups.google.com/d/optout.
Message has been deleted

APaul94

unread,
Sep 16, 2015, 4:43:44 AM9/16/15
to Excel-DNA
Hi Govert, problem is solved.
Thanks for your reply and for this great dev.

Just a last question, there is no recommandation to use NettOffice with ExcelDna or ExcelDna has already the same functionalities as NetOffice (Binding ListObject, validation List, etc) ?

Arnaud

Govert van Drimmelen

unread,
Sep 16, 2015, 5:01:00 AM9/16/15
to exce...@googlegroups.com

Hi Arnaud,

 

You can use the NetOffice interop libraries with Excel-DNA, but you need not. You can reference the Excel interop assemblies directly, and use the ‘Embed Interop Types’ option so that you don’t have to distribute extra assemblies.

 

There is a NuGet package called ExcelDna.Interop that install the Excel 2010 interop assemlbies. With this you can target any version of Excel, but only use the parts of the COM object model that are available in Excel 2010.

 

In my understanding, NetOffice gives you the union of COM features (all the types and members from all versions) although on a particular Excel version of course only the available features will work.

Also NetOffice has IntelliSense help that indicates which Excel versions support a particular member. That helps a lot if you want to target different versions, and has some features light up on a newer version.

 

I don’t know that NetOffice provides any extra support for binding ListObjects beyond the COM support.

The VSTO libraries (called Microsoft.Office.Tools.XXX) provide a wonderful extensions on top of the COM object model to bind to ListObjects, to receive events etc.

 

However, you can’t use the VSTO library together with Excel-DNA, so you would have to re-implement the binding and event features yourself. This would be a nice open-source project or extension to Excel-DNA!

 

My suggestion is to reference the standard interop assemblies (either directly by Add Reference…, or by installing the ExcelDna.Interop package) and build on top of that.

 

Remember that to get hold of the root Application COM object in your Excel-DNA add-in, you should call ExcelDnaUtil.Application. And never under any circumstances to do any COM work from another thread or Task running on the ThreadPool.

 

-Govert

--

APaul94

unread,
Sep 16, 2015, 11:12:48 AM9/16/15
to Excel-DNA
Many thanks for your complete and quick reply.

In fact, I convert an addin from VSTO with many ListObject already bind and in a short time I will have the same work to do on PivotTable/Graph. All will be based on your ExcelDNA. I thought to use NetOffice that implement the "management/ cleanup" of COM objects.

I will try to use directly Excel-DNA as you suggest.
If I create a acceptable solution to wrapp excel like VSTO, I send it to you.

Arnaud

Ken

unread,
Aug 3, 2017, 9:01:53 PM8/3/17
to Excel-DNA
Govert - 

Can you be more clear your second point about loading the packed add-in from separate directory.  

I created a custom configuration section in my MyAddIn-Addin-64.xll.config file.  

<configuration>
<configSections>
<section name="MyCustomConfig" type="MyAddIn.MyCustomConfigSection, MyAddIn" />
</configSections> 
<MyCustomConfig>

</MyCustomConfig>
</configuration>

I started Excel and loaded the packed XLL file for my solution -> MyAddIn-AddIn64-packed.xll.

I attached my solution to this running instance of Excel and stepped into debug mode.

In debug mode, I was getting a "System.IO.FileNotFoundException" and message "Cannot load assembly: C:\repos\....\MyAddIn.dll" when I attempted to create an instance of my custom configuration section.

instance = (MyCustomConfigSection) config.Sections["MyCustomConfig"]  

Magically, when I reverted to loading the unpacked XLL and set LoadFromBytes="false" as you suggested, I was able to successfully create an instance of my custom section.

How, can I still use the packed XLL with my custom configuration section with ConfigurationManager?  How do I set this up between my the configuration file and the packed assembly?  How do I get the best of both worlds?
 

 
 
 
 
To post to this group, send email to exc...@googlegroups.com.

Govert van Drimmelen

unread,
Aug 4, 2017, 6:18:31 AM8/4/17
to exce...@googlegroups.com

Hi Ken,

 

I would expect an exception because the .NET configuration manager attempts to load the assembly (MyAddIn.dll) and when that fails with the exception you see in the debugger, we expect .NET to call the add-in’s AssemblyResolve event which will get the packed assembly. So we expect a first-time exception even in the case where it should work.

It’s not clear from your message whether you’ve tried without the debugger.

 

The issue about putting the packed file in a separate directory, is that otherwise the MyAddIn.dll will be loaded twice into the AppDomain – once from the packed binary data and once by the ConfigurationManager from the actual file. You’ll then end up with unexpected errors due to there being distinct copies of the ‘same’ type.

 

I’m not sure whether the packing works with custom configSections, but the earlier messages in this thread, and an example using NLog, indicate that it should.

 

If you still have trouble you might make a small example with all the right bits and post to GitHub – that would give an easy start to having a closer look.

 

-Govert

 

 

From: exce...@googlegroups.com [mailto:exce...@googlegroups.com] On Behalf Of Ken


Sent: 4 August 2017 03:02
To: Excel-DNA <exce...@googlegroups.com>

To post to this group, send email to exce...@googlegroups.com.

Reply all
Reply to author
Forward
0 new messages