There was an error reflecting type

Using C# .NET 2.0, I have a composite data class that does have the [Serializable] attribute on it. I am creating an XMLSerializer class and passing that into the constructor: XmlSerializer seria...

If you need to handle specific attributes (i.e. Dictionary, or any class), you can implement the IXmlSerialiable interface, which will allow you more freedom at the cost of more verbose coding.

public class NetService : IXmlSerializable
{
    #region Data

        public string Identifier = String.Empty;

        public string Name = String.Empty;

        public IPAddress Address = IPAddress.None;
        public int Port = 7777;

    #endregion

    #region IXmlSerializable Implementation

        public XmlSchema GetSchema() { return (null); }

        public void ReadXml(XmlReader reader)
        {
            // Attributes
            Identifier = reader[XML_IDENTIFIER];
            if (Int32.TryParse(reader[XML_NETWORK_PORT], out Port) == false)
            throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_PORT);
            if (IPAddress.TryParse(reader[XML_NETWORK_ADDR], out Address) == false)
            throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_ADDR);
        }

        public void WriteXml(XmlWriter writer)
        {
            // Attributes
            writer.WriteAttributeString(XML_IDENTIFIER, Identifier);
            writer.WriteAttributeString(XML_NETWORK_ADDR, Address.ToString());
            writer.WriteAttributeString(XML_NETWORK_PORT, Port.ToString());
        }

        private const string XML_IDENTIFIER = "Id";

        private const string XML_NETWORK_ADDR = "Address";

        private const string XML_NETWORK_PORT = "Port";

    #endregion
}

There is an interesting article, which show an elegant way to implements a sophisticated way to «extend» the XmlSerializer.


The article say:

IXmlSerializable is covered in the official documentation, but the documentation states it’s not intended for public use and provides no information beyond that. This indicates that the development team wanted to reserve the right to modify, disable, or even completely remove this extensibility hook down the road. However, as long as you’re willing to accept this uncertainty and deal with possible changes in the future, there’s no reason whatsoever you can’t take advantage of it.

Because this, I suggest to implement you’re own IXmlSerializable classes, in order to avoid too much complicated implementations.

…it could be straightforward to implements our custom XmlSerializer class using reflection.

If you need to handle specific attributes (i.e. Dictionary, or any class), you can implement the IXmlSerialiable interface, which will allow you more freedom at the cost of more verbose coding.

public class NetService : IXmlSerializable
{
    #region Data

        public string Identifier = String.Empty;

        public string Name = String.Empty;

        public IPAddress Address = IPAddress.None;
        public int Port = 7777;

    #endregion

    #region IXmlSerializable Implementation

        public XmlSchema GetSchema() { return (null); }

        public void ReadXml(XmlReader reader)
        {
            // Attributes
            Identifier = reader[XML_IDENTIFIER];
            if (Int32.TryParse(reader[XML_NETWORK_PORT], out Port) == false)
            throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_PORT);
            if (IPAddress.TryParse(reader[XML_NETWORK_ADDR], out Address) == false)
            throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_ADDR);
        }

        public void WriteXml(XmlWriter writer)
        {
            // Attributes
            writer.WriteAttributeString(XML_IDENTIFIER, Identifier);
            writer.WriteAttributeString(XML_NETWORK_ADDR, Address.ToString());
            writer.WriteAttributeString(XML_NETWORK_PORT, Port.ToString());
        }

        private const string XML_IDENTIFIER = "Id";

        private const string XML_NETWORK_ADDR = "Address";

        private const string XML_NETWORK_PORT = "Port";

    #endregion
}

There is an interesting article, which show an elegant way to implements a sophisticated way to «extend» the XmlSerializer.


The article say:

IXmlSerializable is covered in the official documentation, but the documentation states it’s not intended for public use and provides no information beyond that. This indicates that the development team wanted to reserve the right to modify, disable, or even completely remove this extensibility hook down the road. However, as long as you’re willing to accept this uncertainty and deal with possible changes in the future, there’s no reason whatsoever you can’t take advantage of it.

Because this, I suggest to implement you’re own IXmlSerializable classes, in order to avoid too much complicated implementations.

…it could be straightforward to implements our custom XmlSerializer class using reflection.

i’m working .NetFramework4 Client Profile / Visual Studio 2010 Ultimate / Windows7.

I want to read some xx.trx files. TRX file is Test Result File of Microsoft Unit Test Framework.

Generated runtime classes from an XSD schema file using by ‘XML Schema Definition Tool(Xsd.exe)’ for Microsoft Unit Test Result File( XX.TRX) and Schema File(vstst.xsd).

And programmmed this code.

        public void ReadTrxFileContents(string filePath)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(TestRunType));    // But exception occured ‘There was an error reflecting type..’
            TestRunType xmlTestRunType = serializer.Deserialize(new StreamReader(filePath)) as TestRunType;

            // add custom code
            Debug.WriteLine(«id : » + xmlTestRunType.id + «n»);
            Debug.WriteLine(«name : » + xmlTestRunType.name + «n»);
            Debug.WriteLine(«runuser : » + xmlTestRunType.runUser + «n»);
        }

Why occured exception ?

XmlSerializer serializer = new XmlSerializer(typeof(TestRunType));    // But exception occured ‘There was an error reflecting type..’

I added also a parameterless constructor.
TestRunType Definition is …

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute(«xsd», «4.0.30319.1»)]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute(«code»)]
[System.Xml.Serialization.XmlTypeAttribute(Namespace=»http://microsoft.com/schemas/VisualStudio/TeamTest/2010″)]
[System.Xml.Serialization.XmlRootAttribute(«TestRun», Namespace=»http://microsoft.com/schemas/VisualStudio/TeamTest/2010″, IsNullable=false)]
public partial class TestRunType {
    // add a parameterless constructor
    public TestRunType() { }

    private object[] itemsField;

   
    private string idField;

   
    private string nameField;

   
    private string runUserField;

   
    private int tcmPassIdField;

   
    private bool tcmPassIdFieldSpecified;

   
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(«Build», typeof(TestRunTypeBuild))]
    [System.Xml.Serialization.XmlElementAttribute(«ResultSummary», typeof(TestRunTypeResultSummary))]
    [System.Xml.Serialization.XmlElementAttribute(«Results», typeof(ResultsType))]
    [System.Xml.Serialization.XmlElementAttribute(«TestDefinitions», typeof(TestRunTypeTestDefinitions))]
    [System.Xml.Serialization.XmlElementAttribute(«TestEntries», typeof(TestEntriesType1))]
    [System.Xml.Serialization.XmlElementAttribute(«TestLists», typeof(TestRunTypeTestLists))]
    [System.Xml.Serialization.XmlElementAttribute(«TestRunConfiguration», typeof(TestRunConfiguration))]
    [System.Xml.Serialization.XmlElementAttribute(«TestSettings», typeof(TestSettingsType))]
    [System.Xml.Serialization.XmlElementAttribute(«Times», typeof(TestRunTypeTimes))]
    [System.Xml.Serialization.XmlElementAttribute(«UserData», typeof(System.Xml.XmlElement))]
    public object[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }

   
    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string id {
        get {
            return this.idField;
        }
        set {
            this.idField = value;
        }
    }

   
    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }

   
    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string runUser {
        get {
            return this.runUserField;
        }
        set {
            this.runUserField = value;
        }
    }

   
    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public int tcmPassId {
        get {
            return this.tcmPassIdField;
        }
        set {
            this.tcmPassIdField = value;
        }
    }

   
    /// <remarks/>
    [System.Xml.Serialization.XmlIgnoreAttribute()]
    public bool tcmPassIdSpecified {
        get {
            return this.tcmPassIdFieldSpecified;
        }
        set {
            this.tcmPassIdFieldSpecified = value;
        }
    }
}

[Solved-3 Solutions] XmlSerializer — There was an error reflecting type


Error Description:

  • Using C# .NET 2.0, we have a composite data class that does have the [Serializable] attribute on it. When we create an XMLSerializer class and pass that into the constructor:
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
click below button to copy the code. By — C# tutorial — team
  • We get this exemption saying:

There was an error reflecting type.

Solution 1:

  • Look at the inner exception that you are getting. It will tell which field/property it is having trouble serializing.
  • We can exclude fields/properties from xml serialization by decorating them with the [XmlIgnore]attribute.

Solution 2:

  • Serialized classes must have default (i.e. parameter less) constructors. If we have no constructor at all, that’s fine; but if we have a constructor with a parameter, we’ll need to add the default one too.

Solution 3:

  • All the objects in the serialization graph have to be serializable.
  • Since XMLSerializer is a black box, check these links if you want to debug further into the serialization process.

Changing where XmlSerializer Outputs Temporary Assemblies
HOW TO: Debug into a .NET XmlSerializer Generated Assembly


Let’s say you have a C# (or VB.NET) project with namespace “MyProject” and you are trying to serialize a class named “MyClass” and you get the error message: There was an error reflecting type ‘MyProject.MyClass’.

The first thing to check, is that the class which you want to serialize (that save it to disk), contains the [Serializable] attribute.

First Thing to Check: The [Serializable] attribute

Example of proper usage of the [Serializable] attribute:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyProject
{
    [Serializable]
    public class MyClass
    {
        public string something;
        
        //NOTE: Something else is still missing, see next example.

    }
}

Even though however you include the [Serializable] attribute in your class as above, there is still something missing.

If you try to serialize the above class, you will still get the error message  “There was an error reflecting type…

Second Thing to Check: Is there a Default Constructor for your Class?

So what’s wrong and you still cannot serialize the class?

Well, the answer is quite simple: You need to include in in your class a default constructor, that is a constructor with no parameters.


Get Started with .NET Programming Fast and Easy!

Check our online course titled “.NET Programming for Beginners – Windows Forms with C#
(special limited-time discount included in link).

Learn how to implement Windows Forms projects in .NET using Visual Studio and C#, how to implement multithreading, how to create deployment packages and installers for your .NET Windows Forms apps using ClickOnce in Visual Studio, and more! 

Many live demonstrations and downloadable resources included!

.NET Programming for Beginners - Windows Forms with C# - Online Course

(Lifetime Access, Certificate of Completion, Downloadable Resources and more!)

Enroll from $14.99


Code Example that Works

So, if we take the above code example and further modify it, our class will be successfully serialized to disk:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyProject
{
    [Serializable]
    public class MyClass
    {
        public string something;
        
       //Default Constructor
        public MyClass(){
      
    }
   }
}

Featured Online Courses:

  • Boost SQL Server Database Performance with In-Memory OLTP 
  • Data Management for Beginners – Main Principles
  • Essential SQL Server Administration Tips
  • SQL Server Fundamentals – SQL Database for Beginners
  • Essential SQL Server Development Tips for SQL Developers
  • The Philosophy and Fundamentals of Computer Programming
  • .NET Programming for Beginners – Windows Forms with C#
  • Introduction to SQL Server Machine Learning Services
  • Introduction to Azure SQL Database for Beginners
  • SQL Server 2019: What’s New – New and Enhanced Features
  • Entity Framework: Getting Started – Complete Beginners Guide
  • How to Import and Export Data in SQL Server Databases
  • Learn How to Install and Start Using SQL Server in 30 Mins
  • A Guide on How to Start and Monetize a Successful Blog

Read Also:

  • .NET Programming for Beginners – Windows Forms (C#)
  • Using ClickOnce for Deploying your .NET Windows Forms Apps
  • The Net.Tcp Port Sharing Service service on Local Computer started and then stopped
  • Using the C# SqlParameter Object for Writing More Secure Code
  • Cannot declare instance members in a static class
  • Cannot implicitly convert type ‘string’ to ‘System.Windows.Forms.DataGridViewTextBoxColumn
  • The timeout period elapsed prior to obtaining a connection from the pool
  • The type or namespace name ‘Office’ does not exist in the namespace ‘Microsoft’ – How to Resolve
  • …more

Subscribe to our newsletter and stay up to date!

Check out our latest software releases!

Check out Artemakis’s eBooks!

Rate this article: 1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading…

Reference: SQLNetHub.com (https://www.sqlnethub.com)

© 2018 SQLNetHub

Artemakis Artemiou

Artemakis Artemiou is a Senior SQL Server Architect, Author, a 9 Times Microsoft Data Platform MVP (2009-2018). He has over 20 years of experience in the IT industry in various roles. Artemakis is the founder of SQLNetHub and {essentialDevTips.com}. Artemakis is the creator of the well-known software tools Snippets Generator and DBA Security Advisor. Also, he is the author of many eBooks on SQL Server. Artemakis currently serves as the President of the Cyprus .NET User Group (CDNUG) and the International .NET Association Country Leader for Cyprus (INETA). Moreover, Artemakis teaches on Udemy, you can check his courses here.

Views: 4,855

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit «Cookie Settings» to provide a controlled consent. Read More

Содержание

  1. There was an error getting the type
  2. Answered by:
  3. Question
  4. Answers
  5. All replies
  6. There was an error reflecting type… (.NET/C#)
  7. First Thing to Check: The [Serializable] attribute
  8. Second Thing to Check: Is there a Default Constructor for your Class?
  9. Code Example that Works
  10. Featured Online Courses:
  11. Read Also:
  12. Stay Informed
  13. Thank you!
  14. Recommended Online Courses
  15. There was an error getting the type
  16. Answered by:
  17. Question
  18. Answers
  19. All replies

There was an error getting the type

Answered by:

Question

i’m working .NetFramework4 Client Profile / Visual Studio 2010 Ultimate / Windows7.

I want to read some xx.trx files. TRX file is Test Result File of Microsoft Unit Test Framework.

Generated runtime classes from an XSD schema file using by ‘XML Schema Definition Tool(Xsd.exe)’ for Microsoft Unit Test Result File( XX.TRX) and Schema File(vstst.xsd).

And programmmed this code.

public void ReadTrxFileContents(string filePath)
<
XmlSerializer serializer = new XmlSerializer(typeof(TestRunType)); // But exception occured ‘There was an error reflecting type..’
TestRunType xmlTestRunType = serializer.Deserialize(new StreamReader(filePath)) as TestRunType;

// add custom code
Debug.WriteLine(«id : » + xmlTestRunType.id + «n»);
Debug.WriteLine(«name : » + xmlTestRunType.name + «n»);
Debug.WriteLine(«runuser : » + xmlTestRunType.runUser + «n»);
>

Why occured exception ?

XmlSerializer serializer = new XmlSerializer(typeof(TestRunType)); // But exception occured ‘There was an error reflecting type..’

I added also a parameterless constructor.
TestRunType Definition is .

///
[System.CodeDom.Compiler.GeneratedCodeAttribute(«xsd», «4.0.30319.1»)]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute(«code»)]
[System.Xml.Serialization.XmlTypeAttribute(Namespace=»http://microsoft.com/schemas/VisualStudio/TeamTest/2010″)]
[System.Xml.Serialization.XmlRootAttribute(«TestRun», Namespace=»http://microsoft.com/schemas/VisualStudio/TeamTest/2010″, IsNullable=false)]
public partial class TestRunType <
// add a parameterless constructor
public TestRunType()

private object[] itemsField;

private string idField;

private string nameField;

private string runUserField;

private int tcmPassIdField;

private bool tcmPassIdFieldSpecified;

///
[System.Xml.Serialization.XmlElementAttribute(«Build», typeof(TestRunTypeBuild))]
[System.Xml.Serialization.XmlElementAttribute(«ResultSummary», typeof(TestRunTypeResultSummary))]
[System.Xml.Serialization.XmlElementAttribute(«Results», typeof(ResultsType))]
[System.Xml.Serialization.XmlElementAttribute(«TestDefinitions», typeof(TestRunTypeTestDefinitions))]
[System.Xml.Serialization.XmlElementAttribute(«TestEntries», typeof(TestEntriesType1))]
[System.Xml.Serialization.XmlElementAttribute(«TestLists», typeof(TestRunTypeTestLists))]
[System.Xml.Serialization.XmlElementAttribute(«TestRunConfiguration», typeof(TestRunConfiguration))]
[System.Xml.Serialization.XmlElementAttribute(«TestSettings», typeof(TestSettingsType))]
[System.Xml.Serialization.XmlElementAttribute(«Times», typeof(TestRunTypeTimes))]
[System.Xml.Serialization.XmlElementAttribute(«UserData», typeof(System.Xml.XmlElement))]
public object[] Items <
get <
return this.itemsField;
>
set <
this.itemsField = value;
>
>

///
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id <
get <
return this.idField;
>
set <
this.idField = value;
>
>

///
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name <
get <
return this.nameField;
>
set <
this.nameField = value;
>
>

///
[System.Xml.Serialization.XmlAttributeAttribute()]
public string runUser <
get <
return this.runUserField;
>
set <
this.runUserField = value;
>
>

///
[System.Xml.Serialization.XmlAttributeAttribute()]
public int tcmPassId <
get <
return this.tcmPassIdField;
>
set <
this.tcmPassIdField = value;
>
>

///
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool tcmPassIdSpecified <
get <
return this.tcmPassIdFieldSpecified;
>
set <
this.tcmPassIdFieldSpecified = value;
>
>
>

Answers

I catch some bugs.

I checked the inner exception for more details. And Last Bug message is.

‘There was an error reflecting type ‘CodedWebTestElementType’ , Member ‘CodedWebTestElementType.Items’ hides inherited member ‘BaseTestType.Items’, but has different custom attributes.

So i kill some code.

1) ‘Items’ of CodedWebTestElementType class

2) ‘Items’ of GenericTestType class

And then program is good runnned !! I can read ‘trx’. Thanks.

XmlSerializer serializer = new XmlSerializer(typeof(TestRunType)); // exception occured ‘There was an error reflecting type TestRunType’

Other Type is no problem.

i’m working .NetFramework4 Client Profile / Visual Studio 2010 Ultimate / Windows7.

I want to read some xx.trx files. TRX file is Test Result File of Microsoft Unit Test Framework.

Generated runtime classes from an XSD schema file using by ‘XML Schema Definition Tool(Xsd.exe)’ for Microsoft Unit Test Result File( XX.TRX) and Schema File(vstst.xsd).

And programmming code is..

public void ReadTrxFileContents(string filePath)
<
XmlSerializer serializer = new XmlSerializer(typeof(TestRunType)); // But exception occured ‘There was an error reflecting type..’
TestRunType xmlTestRunType = serializer.Deserialize(new StreamReader(filePath)) as TestRunType;

// add custom code
Debug.WriteLine(«id : » + xmlTestRunType.id + «n»);
Debug.WriteLine(«name : » + xmlTestRunType.name + «n»);
Debug.WriteLine(«runuser : » + xmlTestRunType.runUser + «n»);
>

Why occured exception ?

XmlSerializer serializer = new XmlSerializer(typeof(TestRunType)); // But exception occured ‘There was an error reflecting type TestRunType’

I added also a parameterless constructor.
TestRunType Definition is .

Источник

There was an error reflecting type… (.NET/C#)

Let’s say you have a C# (or VB.NET) project with namespace “MyProject” and you are trying to serialize a class named “MyClass” and you get the error message: There was an error reflecting type ‘MyProject.MyClass’.

The first thing to check, is that the class which you want to serialize (that save it to disk), contains the [Serializable] attribute.

First Thing to Check: The [Serializable] attribute

Example of proper usage of the [Serializable] attribute:

Even though however you include the [Serializable] attribute in your class as above, there is still something missing.

If you try to serialize the above class, you will still get the error message “ There was an error reflecting type… ”

Second Thing to Check: Is there a Default Constructor for your Class?

So what’s wrong and you still cannot serialize the class?

Well, the answer is quite simple: You need to include in in your class a default constructor, that is a constructor with no parameters.

Get Started with .NET Programming Fast and Easy!

Check our online course titled “ .NET Programming for Beginners – Windows Forms with C#
(special limited-time discount included in link).

Learn how to implement Windows Forms projects in .NET using Visual Studio and C#, how to implement multithreading, how to create deployment packages and installers for your .NET Windows Forms apps using ClickOnce in Visual Studio, and more!

Many live demonstrations and downloadable resources included!

( Lifetime Access , Certificate of Completion, Downloadable Resources and more!)

Code Example that Works

So, if we take the above code example and further modify it, our class will be successfully serialized to disk:

Featured Online Courses:

  • Boost SQL Server Database Performance with In-Memory OLTP
  • Data Management for Beginners – Main Principles
  • Essential SQL Server Administration Tips
  • SQL Server Fundamentals – SQL Database for Beginners
  • Essential SQL Server Development Tips for SQL Developers
  • The Philosophy and Fundamentals of Computer Programming
  • .NET Programming for Beginners – Windows Forms with C#
  • Introduction to SQL Server Machine Learning Services
  • Introduction to Azure SQL Database for Beginners
  • SQL Server 2019: What’s New – New and Enhanced Features
  • Entity Framework: Getting Started – Complete Beginners Guide
  • How to Import and Export Data in SQL Server Databases
  • Learn How to Install and Start Using SQL Server in 30 Mins
  • A Guide on How to Start and Monetize a Successful Blog

Read Also:

Subscribe to our newsletter and stay up to date!

Rate this article: (1 votes, average: 5.00 out of 5)

Artemakis Artemiou is a Senior SQL Server Architect, Author, a 9 Times Microsoft Data Platform MVP (2009-2018). He has over 20 years of experience in the IT industry in various roles. Artemakis is the founder of SQLNetHub and . Artemakis is the creator of the well-known software tools Snippets Generator and DBA Security Advisor. Also, he is the author of many eBooks on SQL Server. Artemakis currently serves as the President of the Cyprus .NET User Group (CDNUG) and the International .NET Association Country Leader for Cyprus (INETA). Moreover, Artemakis teaches on Udemy, you can check his courses here.

Stay Informed

Thank you!

You have successfully joined our newsletter.

Recommended Online Courses

Learn what’s new and enhanced in SQL Server 2022 such as bidirectional HA/DR to Azure SQL Managed Instance and more.

Learn how you can start using Azure SQL Database and Azure SQL Server Virtual Machines, fast and easy!

Learn how to access and work with SQL Server databases, directly from your Python programs, by implementing Python data access programming.

Via this course, we share our tips for efficient SQL Server Database Administration.

Learn about the new and enhanced features in SQL Server 2019.

Источник

There was an error getting the type

Answered by:

Question

i’m working .NetFramework4 Client Profile / Visual Studio 2010 Ultimate / Windows7.

I want to read some xx.trx files. TRX file is Test Result File of Microsoft Unit Test Framework.

Generated runtime classes from an XSD schema file using by ‘XML Schema Definition Tool(Xsd.exe)’ for Microsoft Unit Test Result File( XX.TRX) and Schema File(vstst.xsd).

And programmmed this code.

public void ReadTrxFileContents(string filePath)
<
XmlSerializer serializer = new XmlSerializer(typeof(TestRunType)); // But exception occured ‘There was an error reflecting type..’
TestRunType xmlTestRunType = serializer.Deserialize(new StreamReader(filePath)) as TestRunType;

// add custom code
Debug.WriteLine(«id : » + xmlTestRunType.id + «n»);
Debug.WriteLine(«name : » + xmlTestRunType.name + «n»);
Debug.WriteLine(«runuser : » + xmlTestRunType.runUser + «n»);
>

Why occured exception ?

XmlSerializer serializer = new XmlSerializer(typeof(TestRunType)); // But exception occured ‘There was an error reflecting type..’

I added also a parameterless constructor.
TestRunType Definition is .

///
[System.CodeDom.Compiler.GeneratedCodeAttribute(«xsd», «4.0.30319.1»)]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute(«code»)]
[System.Xml.Serialization.XmlTypeAttribute(Namespace=»http://microsoft.com/schemas/VisualStudio/TeamTest/2010″)]
[System.Xml.Serialization.XmlRootAttribute(«TestRun», Namespace=»http://microsoft.com/schemas/VisualStudio/TeamTest/2010″, IsNullable=false)]
public partial class TestRunType <
// add a parameterless constructor
public TestRunType()

private object[] itemsField;

private string idField;

private string nameField;

private string runUserField;

private int tcmPassIdField;

private bool tcmPassIdFieldSpecified;

///
[System.Xml.Serialization.XmlElementAttribute(«Build», typeof(TestRunTypeBuild))]
[System.Xml.Serialization.XmlElementAttribute(«ResultSummary», typeof(TestRunTypeResultSummary))]
[System.Xml.Serialization.XmlElementAttribute(«Results», typeof(ResultsType))]
[System.Xml.Serialization.XmlElementAttribute(«TestDefinitions», typeof(TestRunTypeTestDefinitions))]
[System.Xml.Serialization.XmlElementAttribute(«TestEntries», typeof(TestEntriesType1))]
[System.Xml.Serialization.XmlElementAttribute(«TestLists», typeof(TestRunTypeTestLists))]
[System.Xml.Serialization.XmlElementAttribute(«TestRunConfiguration», typeof(TestRunConfiguration))]
[System.Xml.Serialization.XmlElementAttribute(«TestSettings», typeof(TestSettingsType))]
[System.Xml.Serialization.XmlElementAttribute(«Times», typeof(TestRunTypeTimes))]
[System.Xml.Serialization.XmlElementAttribute(«UserData», typeof(System.Xml.XmlElement))]
public object[] Items <
get <
return this.itemsField;
>
set <
this.itemsField = value;
>
>

///
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id <
get <
return this.idField;
>
set <
this.idField = value;
>
>

///
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name <
get <
return this.nameField;
>
set <
this.nameField = value;
>
>

///
[System.Xml.Serialization.XmlAttributeAttribute()]
public string runUser <
get <
return this.runUserField;
>
set <
this.runUserField = value;
>
>

///
[System.Xml.Serialization.XmlAttributeAttribute()]
public int tcmPassId <
get <
return this.tcmPassIdField;
>
set <
this.tcmPassIdField = value;
>
>

///
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool tcmPassIdSpecified <
get <
return this.tcmPassIdFieldSpecified;
>
set <
this.tcmPassIdFieldSpecified = value;
>
>
>

Answers

I catch some bugs.

I checked the inner exception for more details. And Last Bug message is.

‘There was an error reflecting type ‘CodedWebTestElementType’ , Member ‘CodedWebTestElementType.Items’ hides inherited member ‘BaseTestType.Items’, but has different custom attributes.

So i kill some code.

1) ‘Items’ of CodedWebTestElementType class

2) ‘Items’ of GenericTestType class

And then program is good runnned !! I can read ‘trx’. Thanks.

XmlSerializer serializer = new XmlSerializer(typeof(TestRunType)); // exception occured ‘There was an error reflecting type TestRunType’

Other Type is no problem.

i’m working .NetFramework4 Client Profile / Visual Studio 2010 Ultimate / Windows7.

I want to read some xx.trx files. TRX file is Test Result File of Microsoft Unit Test Framework.

Generated runtime classes from an XSD schema file using by ‘XML Schema Definition Tool(Xsd.exe)’ for Microsoft Unit Test Result File( XX.TRX) and Schema File(vstst.xsd).

And programmming code is..

public void ReadTrxFileContents(string filePath)
<
XmlSerializer serializer = new XmlSerializer(typeof(TestRunType)); // But exception occured ‘There was an error reflecting type..’
TestRunType xmlTestRunType = serializer.Deserialize(new StreamReader(filePath)) as TestRunType;

// add custom code
Debug.WriteLine(«id : » + xmlTestRunType.id + «n»);
Debug.WriteLine(«name : » + xmlTestRunType.name + «n»);
Debug.WriteLine(«runuser : » + xmlTestRunType.runUser + «n»);
>

Why occured exception ?

XmlSerializer serializer = new XmlSerializer(typeof(TestRunType)); // But exception occured ‘There was an error reflecting type TestRunType’

I added also a parameterless constructor.
TestRunType Definition is .

Источник

Hi. Im running into the same problem as #2150 .

System.InvalidOperationException: There was an error reflecting type ‘ZregService.ManifestType’. —> System.InvalidOperationException: There was an error reflecting property ‘Reference’. —> System.InvalidOperationException: There was an error reflecting type ‘ZregService.ReferenceType’. —> System.InvalidOperationException: There was an error reflecting property ‘DigestMethod’. —> System.InvalidOperationException: There was an error reflecting type ‘ZregService.DigestMethodType’. —> System.InvalidOperationException: There was an error reflecting property ‘Any’. —> System.InvalidOperationException: There was an error reflecting type ‘System.Xml.Linq.XElement’. —> System.InvalidOperationException: System.Xml.Linq.XElement cannot be used as: ‘xml text’.
at System.Xml.Serialization.XmlReflectionImporter.CheckContext(TypeDesc typeDesc, ImportContext context)
at System.Xml.Serialization.XmlReflectionImporter.ImportSpecialMapping(Type type, TypeDesc typeDesc, String ns, ImportContext context, RecursionLimiter limiter)
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
— End of inner exception stack trace —

Here is the wsdl
wsdl.zip

And here is the generated reference
Reference.zip

Seems like it does not like the System.Xml.Linq.XElement Any properties like in:


    [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil","0.5.0.0")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.w3.org/2000/09/xmldsig#")]
    public partial class DigestMethodType
    {
        
        private System.Xml.Linq.XElement[] anyField;
        
        private string algorithmField;
        
        /// <remarks/>
        [System.Xml.Serialization.XmlTextAttribute()]
        [System.Xml.Serialization.XmlAnyElementAttribute(Order=0)]
        public System.Xml.Linq.XElement[] Any
        {
            get
            {
                return this.anyField;
            }
            set
            {
                this.anyField = value;
            }
        }
        
        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute(DataType="anyURI")]
        public string Algorithm
        {
            get
            {
                return this.algorithmField;
            }
            set
            {
                this.algorithmField = value;
            }
        }
    }

C#
1
2
3
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll
 
Additional information: There was an error reflecting type 'System.Collections.Generic.List`1[cursova6.Client]'.

Вот ошибка.
а вот тут тот класс который хочу сериализовать.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace cursova6
{
    [Serializable]
   public class Client
    {
 
        public string Name{get;set;}
        public string Surname { get; set; }
        public int Npassport { get; set; }
        public string Adres { get; set; }
        public int Telefon { get; set; }
        public int Nombank { get; set; }
        public string Tipneruh { get; set; }
        public int Vcena { get; set; }
        public List<Realty> Neruh { get; set; }
        public Client(string name, string surname, int npassport, string adres, int telefon, int nombank, string tipneruh, int vcena)
        {
            Name = name;
            Surname = surname;
            Npassport = npassport;
            Adres = adres;
            Telefon = telefon;
            Nombank = nombank;
            Tipneruh = tipneruh;
            Vcena = vcena;
            Neruh = new List<Realty>();
        }
        public Client()
        {
 
        }
        public string Description()
        {
            var sb = new StringBuilder();
            PropertyInfo[] properties = this.GetType().GetProperties();
            foreach (PropertyInfo propertyInfo in properties)
            {
                sb.Append(propertyInfo.GetValue(this));
                sb.Append(" ");
            }
 
            return sb.ToString();
        }
    }
}

и содержимое обьекта что есть в етом классе

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace cursova6
{
 
    public class Realty
    {
        public string Name { get; set; }
        public double Vartist { get; set; }
        public string Mrozt { get; set; }
        public Firstvlas Popvlas{get; set;}
 
        public Realty(string name, double vartist, string mrozt,ref Firstvlas popvlas)
        {
            Name = name;
            Vartist = vartist;
            Mrozt = mrozt;
            Popvlas = popvlas;
        }
 
        public string Description()
        {
            var sb = new StringBuilder();
            PropertyInfo[] properties = this.GetType().GetProperties();
            foreach (PropertyInfo propertyInfo in properties)
            {
                sb.Append(propertyInfo.GetValue(this));
                sb.Append(" ");
            }
 
            return sb.ToString();
        }
    }
}

Ну и тд)
Мне надо что бы полностю всю инфу сериализовало))
Ну + вот такая ошибка непонятная вылетает

Вот как я сериализую

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
        public static void serilaze<T>(T vector, string filename)
        {
            XmlSerializer writer = new XmlSerializer(vector.GetType());
            var path = filename;
            FileStream file = new FileStream(path, FileMode.Truncate);
            writer.Serialize(file, vector);
            file.Close();
        }
 
        public static T desirelize<T>(string filename)
        {
            System.Xml.Serialization.XmlSerializer reader =
                new System.Xml.Serialization.XmlSerializer(typeof(T));
            System.IO.StreamReader file = new System.IO.StreamReader(
                filename);
            T overview;
            overview = (T)reader.Deserialize(file);
            file.Close();
            return overview;
        }

и десериализация на всякий)
Подскажет кто в чем причина ошибки? и как ее решить?
Вот в етой строчке выбивает ексепшен рание описан

C#
1
XmlSerializer writer = new XmlSerializer(vector.GetType());

Добавлено через 33 минуты
Проблема решена добавлением дефаулт конструкторов в те вложеные обьекты. Сонливость дает знать о себе. Пора походу спааать

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

Понравилась статья? Поделить с друзьями:
  • There was an error reflecting property
  • There was an error reflecting field
  • There was an error reading this rom file see the message log for details
  • There was an error reading the world file tedit
  • There was an error processing your request please try again later перевод