views:

66

answers:

1

I'm trying to figure out .NET serialization stuff and experiencing a problem. I've made a simple program to test it and got stuck with using attributes. Here's the code:

[Serializable]
public class SampleClass
{
    [SoapIgnore]
    public Guid InstanceId
    {
        get;
        set;
    }
}

class Program
{
    static void Main()
    {

        SampleClass cl = new SampleClass { InstanceId = Guid.NewGuid() };
        SoapFormatter fm = new SoapFormatter();
        using (FileStream stream = new FileStream(string.Format("C:\\Temp\\{0}.inv", Guid.NewGuid().ToString().Replace("-", "")), FileMode.Create))
        {
            fm.Serialize(stream, cl);
        }
    }
}

The problem is that InstanceId is not ignored while serialization is done. What I get in .inv file is something like this:

<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"&gt;
<SOAP-ENV:Body>
<a1:SampleClass id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/TestConsoleApp/TestConsoleApp%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull"&gt;
<_x003C_InstanceId_x003E_k__BackingField>
<_a>769807168</_a>
<_b>27055</_b>
<_c>16408</_c>
<_d>141</_d>
<_e>210</_e>
<_f>171</_f>
<_g>30</_g>
<_h>252</_h>
<_i>196</_i>
<_j>246</_j>
<_k>159</_k>
</_x003C_InstanceId_x003E_k__BackingField>
</a1:SampleClass>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

As I can understand from documentation InstanceId property is not supposed to be serialized since SoapIgnore attribute is applied to it. Am I missing something?

A: 

The attributes are for standard Web Service XML serialization. SoapFormatter is for Remoting serialization not for Web Service serialization.

To make you example work you should provide type mappings for SOAP-encoded message parts.

[Serializable]
public class SampleClass
{

    [SoapIgnore]
    public Guid InstanceId
    {
        get;
        set;
    }
}

class Program
{
    static void Main()
    {

        SampleClass cl = new SampleClass { InstanceId = Guid.NewGuid() };
        XmlTypeMapping xtm = new SoapReflectionImporter().ImportTypeMapping(typeof(SampleClass));
        XmlSerializer xs = new XmlSerializer(xtm);

        using (FileStream stream = new FileStream(string.Format("C:\\Temp\\{0}.inv", Guid.NewGuid().ToString().Replace("-", "")), FileMode.Create))
        {
            xs.Serialize(stream, cl);
        }
    }
}
kyrisu