Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8890863
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T22:35:57+00:00 2026-06-14T22:35:57+00:00

We return instances of the class AuthenticateUserOutput from a WCF web service. So we

  • 0

We return instances of the class AuthenticateUserOutput from a WCF web service.

So we have this method:

public override AuthenticateUserOutput AuthenticateUser(AuthenticateUserInput AuthenticateUserInput)

AuthenicateUserOutput is auto generated:

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.5420")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="xxxx")]
public partial class AuthenticateUserOutput : WS2MethodOutput
{

    private bool authenticationResultField;

    private UserContext userContextField;

    /// <remarks/>
    public bool AuthenticationResult
    {
        get
        {
            return this.authenticationResultField;
        }
        set
        {
            this.authenticationResultField = value;
        }
    }

    /// <remarks/>
    public UserContext UserContext
    {
        get
        {
            return this.userContextField;
        }
        set
        {
            this.userContextField = value;
        }
    }
}

We need to be able to de serialize as AuthenticateUserOutput, but it’s not working.

As a test, I instantiated an AuthenticateUserOutput, serialized it and tried to de-serialize it.

It fails with InvalidOperationException.

Here’s the serialized Xml:

<?xml version="1.0" encoding="utf-16"?>
<AuthenticateUserOutput xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="xxxx">
  <Response xmlns="xxxx">
    <IsValid>true</IsValid>
    <Success>true</Success>
  </Response>
  <AuthenticationResult xmlns="xxxx">true</AuthenticationResult>
  <UserContext xmlns="xxxx">
  </UserContext>
</AuthenticateUserOutput>

Here’s the serialization and de-serialization code:

    public static string ToXml(this object input)
    {
        string output;
        XmlSerializer serializer = new XmlSerializer(input.GetType());
        StringBuilder sb = new StringBuilder();
        using (TextWriter textWriter = new StringWriter(sb))
        {
            serializer.Serialize(textWriter, input);
        }
        output = sb.ToString();
        return output;
    }

And:

    public static T FromXml<T>(this string input)
    {
        T output;

        XmlSerializer serializer = new XmlSerializer(typeof(T));

        output = (T)serializer.Deserialize(new StringReader(input));

        return output;
    }

The exact details of the exception:

System.InvalidOperationException occurred
  Message="<AuthenticateUserOutput xmlns='xxxx'> was not expected."
  Source="qkxd8dd-"
  StackTrace:
       at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderAuthenticateUserOutput.Read31_AuthenticateUserOutput()
  InnerException: 

So it can’t de-serialize it’s own serialized Xml.

Can anybody see why?

Thanks,

J1M.

UPDATE: Here is the test code:

        AuthenticateUserOutput test = new AuthenticateUserOutput();

        test.AuthenticationResult = true;
        test.Response = new ResponseType();
        test.Response.Exception = null;
        test.Response.IsValid = true;
        test.Response.Success = true;
        test.Response.ValidationErrors = null;
        test.UserContext = new UserContext();

        string serializedXml = test.ToXml();

        AuthenticateUserOutput deserializedString = serializedXml.FromXml<AuthenticateUserOutput>();

UPDATE2: Deserializer works thanks to Mark Gravell

OK, I forgot I’d added this to get the namespaces to come out correctly when de-serializing:

public partial class WS2MethodInput
{
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces _xmlns;

    /// <summary>
    /// Constructor for WS2MethodInput that sets up default namespaces
    /// </summary>
    public WS2MethodInput()
    {
        _xmlns = new XmlSerializerNamespaces();
        _xmlns.Add("", "xxxx");
    }
}

With this, the serialized Xml is as it was at the top of this message.
Without it, the de-serializer works but AuthenticateUserOutput is missing a namespace:

<?xml version="1.0" encoding="utf-16"?>
<AuthenticateUserOutput xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="xxxx">
  <Response xmlns="xxxx">
    <IsValid>true</IsValid>
    <Success>true</Success>
  </Response>
  <AuthenticationResult xmlns="xxxx">true</AuthenticationResult>
  <UserContext xmlns="xxxx">
  </UserContext>
</AuthenticateUserOutput>

Note the xmlns="xxxx" at the end of AuthenticateUserOutput

Problem is, now I can’t use that Xml with our other code without either:

1) Loading it into an XDocument and adding the namespace and removing it when I need to de-serialize it
2) Doing the same with string replace of regex or something

Neither of which I really like. In fact that’s horrible! 8X

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T22:35:58+00:00Added an answer on June 14, 2026 at 10:35 pm

    The problem was setting the XmlSerializerNamespaces to force xmlns on the root element.

    Take that away and it works.

    However, now I can’t use the serialized Xml anywhere else because it’s missing a namespace.

    I will start a new question that is focused on that.

    Thanks,

    J1M.

    UPDATE:

    OK, I figured it out so I’m not going to write a new question.

    Given the following XSD:

    <xs:schema xmlns="urn:www-test-com:testservice" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:www-test-com:testservice" elementFormDefault="qualified" attributeFormDefault="unqualified">
        <xs:element name="AuthenticateUserInput">
            <xs:annotation>
                <xs:documentation>Used to provide user credentials to the AuthenticateUser method</xs:documentation>
            </xs:annotation>
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="Username" type="xs:string"/>
                    <xs:element name="Password" type="xs:string"/>
                    <xs:element name="Method" type="xs:string"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    </xs:schema>
    

    svcutil generates something like this, although I imagine there are lots of tools that spit out something similar for that XSD:

    [Serializable()]
    [XmlType(AnonymousType = true, Namespace = "urn:www-test-com:testservice")]
    public class AuthenticateUserInput
    {
        public string Username { get; set; }
        public string Password { get; set; }
        public string Method { get; set; }
    }
    

    Now, using the “default” XmlSerializer code:

        static string ToXml(object input)
        {
            string output;
    
            XmlSerializer serializer = new XmlSerializer(input.GetType());
            StringBuilder sb = new StringBuilder();
    
            using (XmlWriter xw = XmlWriter.Create(sb))
            {
                serializer.Serialize(xw, input);
            }
            output = sb.ToString();
            return output;
        }
    

    You get the following Xml:

    <AuthenticateUserInput xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <Username xmlns="urn:www-test-com:testservice">sa</Username>
        <Password xmlns="urn:www-test-com:testservice">Password1</Password>
        <Method xmlns="urn:www-test-com:testservice">Plain</Method>
    </AuthenticateUserInput>
    

    Which does NOT conform to the schema (validation fails, which is what is killing us at the moment)

    OK, so, I found a reference to changing [XmlType] to [XmlRoot] and a cursory test worked, if I change the generated class I now get the following conformant Xml:

    <AuthenticateUserInput xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:www-test-com:testservice">
        <Username>sa</Username>
        <Password>Password1</Password>
        <Method>Plain</Method>
    </AuthenticateUserInput>
    

    But I don’t want to hand change all the auto generated classes. So after some time I found the following solution:

        static string ToXml(object input)
        {
            string output;
    
            XmlSerializer serializer = CreateSerializer(input.GetType());
            StringBuilder sb = new StringBuilder();
    
            var settings = new XmlWriterSettings() { OmitXmlDeclaration = true, Encoding =  Encoding.UTF8, Indent = true };
    
            using (XmlWriter xw = XmlWriter.Create(sb, settings))
            {
                serializer.Serialize(xw, input);
            }
            output = sb.ToString();
            return output;
        }
    
        static T FromXml<T>(string input)
        {
            T output;
    
            XmlSerializer serializer = CreateSerializer(typeof(T));
    
            output = (T)serializer.Deserialize(new StringReader(input));
    
            return output;
        }
    
        private static XmlSerializer CreateSerializer(Type incomingType)
        {
            XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
            XmlAttributes newAttributes = new XmlAttributes();
    
            newAttributes.XmlRoot = new XmlRootAttribute();
            newAttributes.XmlRoot.Namespace = ((XmlTypeAttribute)incomingType.GetCustomAttributes(typeof(XmlTypeAttribute), true)[0]).Namespace;
            attrOverrides.Add(incomingType, newAttributes);
    
            XmlSerializer serializer = new XmlSerializer(incomingType, attrOverrides);
            return serializer;
        }
    

    As you can see, rather than just using the default constructor for XmlSerializer, you can create an XmlAttributeOverrides and add to it one XmlAttributes on which you instantiate the XmlRoot attribute.
    In order to make this nice and generic, it hoovers the Namespace out of the incoming type with ((XmlTypeAttribute)incomingType.GetCustomAttributes(typeof(XmlTypeAttribute), true)[0]).Namespace, which fails if the type doesn’t have that attribute so this solution needs more work but you get the general idea.

    Regards,

    J1M

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In my query I need to return instances of a class that doesn't have
I have a generic abstract class Factory<T> with a method createBoxedInstance() which returns instances
This a data binding question in C#. I have a simple Person class: public
I want to have a large number of class instances return the same similar
I'm writing a factory class that should be able to return singleton instances of
I have a method where I would like to return an object instance of
I have stored instances of class A in a std:vector , vec_A as vec_A.push_back(A(i))
I have a class, which holds a static dictionary of all existing instances, which
I'm writing my first desktop app and I'm struggling with class instances. This app
From Essential C++: 4.10 Providing Class Instances of the iostream Operators Often, we wish

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.