views:

748

answers:

1

Hi,

I'm trying to do something a bit unusual...

I have this class Foo :

public class Foo
{
    public Foo(string name)
    {
        this.Name = name;
    }

    internal Foo()
    {
    }

    public string Name { get; internal set; }
    public int Age { get; set; }
}

Notice the internal setter for Name, and the internal default constructor. This would normally prevent the XML serialization, but I also marked the XML serialization assembly as "friend" with InternalsVisibleTo :

[assembly: InternalsVisibleTo("TestXML2008.XmlSerializers")]

And I added a MSBuild task to pre-generate the serialization assembly :

<Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
  <SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutputPath)" References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)">
    <Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" />
  </SGen>
</Target>

This works fine : the Name property is correctly serialized and deserialized.

Now, I want to sign my assembly... So I define a key file for my assembly, and I modify the InternalsVisibleTo declaration to match the key :

[assembly: InternalsVisibleTo("TestXML2008.XmlSerializers, PublicKey=c5cd51bf2cc4ed49")]

But now SGEN fails :

Unable to generate a temporary class (result=1).
Property or indexer 'TestXML2008.Foo.Name' cannot be assigned to -- it is read only

The SGEN task should pick the key file through the macros, but apparently that's not enough... I also tried to specify the key file explicitly in the SGEN task, without success. I have the same result when I use sgen.exe on the command line...

Am I missing something ? I can't understand why it doesn't work when I sign the assembly...

+2  A: 

In the InternalsVisibleTo attribute, you need to specify the full public key, not just the public key token.

See this answer to a similar question and this MSDN article for info on how to get the public key.

Joe
It works, thanks ! I was misled by the example in the MSDN documentation of InternalsVisibleToAttribute : the key shown in the example was very short, so I thought it was the public key token...
Thomas Levesque