Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ILMerge with log4net is causing "inaccessible due to protection level" error

I created a wrapper class for the initialization of my log4net logging objects in order to make it easier to establish custom properties in the ThreadContext. This occurs within a class library that I have established along with many other useful functions. To join all of the various libraries I have also added an AfterBuild target to ILMerge using the '/internalize' switch.

All references to this initializer method within the library targeted by ILMerge seem to work just fine. However, when I reference this merged library in other places. My implementation throws protection level errors. I have tried adding various things to the optional exclude (/internalize:excludes.txt) file but this doesn't seem to work.

Example excludes.txt:

log4net.Config
log4net.ThreadContext
log4net.LogManager

Has anyone else had this issue?

[EDIT]:

Here is the code:

 [assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace Logging
{
    public static class Log4NetThreadContext
    {
        public static ILog Initialize(Type declaringType)
        {
            // Read from configuration
            XmlConfigurator.Configure();

            // Set Properties
            ThreadContext.Properties["ID"] = ...
                ...
                ...
                ...

            if(System.Diagnostics.Debugger.IsAttached)
            {
                // Special debugging logger
                return LogManager.GetLogger("DEBUG_MODE");
            }
            else
            {
                // Root logger
                return LogManager.GetLogger(declaringType);
            }
        }
    }
}

I'm utilizing this code like so..

private static readonly Type declaringType = 
    MethodBase.GetCurrentMethod().DeclaringType;
private static readonly ILog log =
    Log4NetThreadContext.Initialize(declaringType);
...
log.Info("Something useful");

[EDIT]:

This is my AfterBuild target

<Target Name="AfterBuild">
<CreateItem Include="@(ReferenceCopyLocalPaths)" Condition="'%(Extension)'=='.dll'">
  <Output ItemName="AssembliesToMerge" TaskParameter="Include" />
</CreateItem>
<Message Text="MERGING: @(AssembliesToMerge->'%(Filename)')" Importance="High" />
<Exec Command="&quot;$(ProgramFiles)\Microsoft\Ilmerge\Ilmerge.exe&quot; /targetplatform:v2 /log /internalize:&quot;ilmerge.excludes.txt&quot; /keyfile:$(AssemblyOriginatorKeyFile) /out:@(MainAssembly) &quot;@(IntermediateAssembly)&quot; @(AssembliesToMerge->'&quot;%(FullPath)&quot;', ' ')" />
<Delete Files="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')" />

Is there just a better way in general to debug protection level issues?

Log4NetThreadContext.Initialize(System.Type)' is inaccessible due to its protection level
like image 899
NickSuperb Avatar asked Jan 18 '13 22:01

NickSuperb


2 Answers

Ultimately the easiest thing to do is to exclude log4net completely from the ilmerge process and maintain it as a dependent assembly.

So after much torture here's the "not-so-obvious" solution..

The excludes were not required after all, the real answer is to use the /lib:[path] switch in ilmerge.

I updated the AfterBuild target to remove the excludes from the /internalize switch. Next I added the /lib switch to pass in the location of the log4net dll as a dependent reference. It looks like this:

<Target Name="AfterBuild">
  <CreateItem Include="@(ReferenceCopyLocalPaths)" Condition="'%(Extension)'=='.dll'">
    <Output ItemName="AssembliesToMerge" TaskParameter="Include" />
  </CreateItem>
  <Message Text="MERGING: @(AssembliesToMerge->'%(Filename)')" Importance="High" />
  <Exec Command="&quot;$(ProgramFiles)\Microsoft\Ilmerge\Ilmerge.exe&quot; /lib:..\packages\log4net.2.0.0\lib\net35-full\ /targetplatform:v2 /log /internalize /keyfile:$(AssemblyOriginatorKeyFile) /out:@(MainAssembly) &quot;@(IntermediateAssembly)&quot; @(AssembliesToMerge->'&quot;%(FullPath)&quot;', ' ')" />
  <Delete Files="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')" />
</Target>

In addition, I've added another target to restrict the list of assemblies included in the merge by adding a unique <ILMerge /> element to the references located in my .csproj file

<Target Name="AfterResolveReferences">
  <Message Text="Filtering out ILMerge assemblies from ReferenceCopyLocalPaths..." Importance="High" />
  <ItemGroup>
    <ReferenceCopyLocalPaths Remove="@(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.ILMerge)'=='false'" />
  </ItemGroup>
</Target>

Thus the reference elements were listed like so to accommodate:

...
<Reference Include="Ionic.Zip">
  <HintPath>..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll</HintPath>
  <ILMerge>True</ILMerge>
</Reference>
<Reference Include="log4net">
  <HintPath>..\packages\log4net.2.0.0\lib\net35-full\log4net.dll</HintPath>
  <ILMerge>False</ILMerge>
...

There's probably a better (programmatic) alternative for explicitly adding ILMerge=False values to the /lib switch but, in my case it is sufficient due to there being only one excluded item. Otherwise you may need to add additional paths manually.

Credit for the 'AfterResolveReferences' technique I've listed goes to http://www.hanselman.com/blog/MixingLanguagesInASingleAssemblyInVisualStudioSeamlesslyWithILMergeAndMSBuild.aspx

Hopefully this helps someone!

like image 184
NickSuperb Avatar answered Sep 28 '22 00:09

NickSuperb


This usually happens to me when I am running the code from a remote location. .NET has permission issues when accessing the config file from a remote location. For example, a code repository setup on a network share.

I've only every been able to overcome it by moving my code to a local harddrive (as I don't have admin rights to elevate the security of the network share to "Trusted", etc).

(Note that this is primarily an issue with versions of Visual Studio prior to 2005. I think this was fixed in 2008 onwards, so it may not affect you. You don't say what version you are using, though.)

like image 37
JDB Avatar answered Sep 27 '22 23:09

JDB