There was an error reflecting field

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.

  • Remove From My Forums
  • Question

  • I’m getting the below exception while trying to create an instance of  XmlSerializer using the class generated from XsdObjecGen. Any ideas on what may be causing this?

    System.InvalidOperationException: There was an error reflecting field ‘__ApplicationArea’. —> System.InvalidOperationException: There was an error reflecting type ‘ConsoleApplication2.Oagis.ApplicationArea’. —> System.InvalidOperationException:
    There was an error reflecting field ‘__Sender’. —> System.InvalidOperationException: There was an error reflecting type ‘ConsoleApplication2.Oagis.Sender’. —> System.InvalidOperationException: There was an error reflecting field ‘__LogicalID’. —>
    System.InvalidOperationException: There was an error reflecting type ‘ConsoleApplication2.Oagis.LogicalID’. —> System.InvalidOperationException: There was an error reflecting field ‘__Value’. —> System.InvalidOperationException: There was an error
    reflecting type ‘System.String’. —> System.InvalidOperationException: Value ‘String’ cannot be used for the XmlElementAttribute.DataType property. The datatype ‘http://www.w3.org/2001/XMLSchema:String’ is missing.

    The code in question from the exception..

     '*********************** XmlText field ***********************
        <XmlText(DataType:="String"), _
        EditorBrowsable(EditorBrowsableState.Advanced)> _
        Public Shadows __Value As String
    
        <XmlIgnore()> _
        Public Overloads Property Value() As String
          Get
            Value = __Value
          End Get
          Set(ByVal val As String)
            __Value = val
          End Set
        End Property
    

Answers

  • Thanks John. I figured out what the issue was. There are alot of generic object datatypes that need to be changed to the correct type in the auto generated class.

    • Marked as answer by

      Friday, September 17, 2010 8:36 PM

    • Unmarked as answer by
      quadwwchs1
      Friday, September 17, 2010 8:36 PM
    • Marked as answer by
      quadwwchs1
      Friday, September 17, 2010 8:36 PM

[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


Содержание

  1. There was an error reflecting field
  2. Answered by:
  3. Question
  4. Answers
  5. All replies
  6. There was an error reflecting field
  7. Answered by:
  8. Question
  9. Answers
  10. All replies
  11. Announcement
  12. Looking for a User App or Add-On built by the NinjaTrader community?
  13. Partner 728×90
  14. Error on executing DB command
  15. Error on executing DB command

There was an error reflecting field

Answered by:

Question

I’m writing a web service client dll in Managed C++ 2003 for a Java WebService. I added the web service as webreference and its compiling well.

when i try to run the application its giving a runtime error «Method can not be reflected» when i try to create the object for the Web Service class.

The webservice is working fine when i run it through the browser or from another C# 2005 client.

I tried to add that service as a reference to a managed C++ 2005, but the generated files are giving some compiler errors.

Can anyone help me on how to resolve this error.

Below is the complete error list

ERROR Exception handled : Method can not be reflected.
at System.Web.Services.Protocols.SoapReflector.ReflectMethod(LogicalMethodInf
o methodInfo, Boolean client, XmlReflectionImporter xmlImporter, SoapReflectionI
mporter soapImporter, String defaultNs)
at System.Web.Services.Protocols.SoapClientType.GenerateXmlMappings(Type type
, ArrayList soapMethodList, String serviceNamespace, Boolean serviceDefaultIsEnc
oded, ArrayList mappings)
at System.Web.Services.Protocols.SoapClientType..ctor(Type type)
at System.Web.Services.Protocols.SoapHttpClientProtocol..ctor()

Answers

Please allow me to translate this, from «.NET» into «English»:

  1. System.InvalidOperationException: Method can not be reflected, because of
  2. System.InvalidOperationException: There was an error reflecting ‘inData’., because of
  3. System.InvalidOperationException: There was an error reflecting type ‘ ‘. , because of
  4. System.InvalidOperationException: There was an error reflecting field ‘osaRequestHeader’. , because of
  5. System.InvalidOperationException: There was an error reflecting type ‘., because of
  6. System.InvalidOperationException: There was an error reflecting field ‘entitlements’., because of
  7. System.InvalidOperationException: There was an error reflecting type ‘ANIMatchService.Entitlements’., because of
  8. System.InvalidOperationException: There was an error reflecting field ‘entitlement’., because of
  9. System.InvalidOperationException: The Form property may not be ‘Unqualified’ when an explicit Namespace property is present.

The original problem is at number 9. It appears that the «entitlement» field is specified to use Form=»Unqualified» at the same type that it sets a specific namespace. You will need either to not use the Form property, or not use the Namespace property.

John Saunders | Use File->New Project to create Web Service Projects

  • Marked as answer by Nathan Anderson — MSFT Microsoft employee, Moderator Thursday, September 4, 2008 8:20 PM

Please post the complete exception. In order to do this, catch the exception (let’s call it «ex»), then post here the output of ex.ToString().

These exceptions have much more detail, which will tell you exactly where the problem is. John Saunders | Use File->New Project to create Web Service Projects

Thanks for the reply.Below is the entire exception

Its giving the error for all the classes and functions saying that they can not be reflected. This Web Service is written in Java. I’m not familiar on what is this Reflection means and why it is used. I added this web service as a Web Reference to this project which is in Managed C++ 2003

Источник

There was an error reflecting field

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 .

Источник

Announcement

Looking for a User App or Add-On built by the NinjaTrader community?

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!

Partner 728×90

Error on executing DB command

Error on executing DB command

I receive the following error message with automation:

Error on executing DB command: System.InvalidOperationException: There was an error reflecting type ‘NinjaTrader.NinjaScript.Strategies.Testsystem’. —> System.InvalidOperationException: There was an error reflecting field ‘entryOrder’. —> System.InvalidOperationException: There was an error reflecting type ‘NinjaTrader.Cbi.Order’. —> System.InvalidOperationException: There was an error reflecting property ‘UserData’. —> System.InvalidOperationException: There was an error reflecting type ‘System.Xml.Linq.XDocument’. —> System.InvalidOperationException: Cannot serialize member ‘System.Xml.Linq.XDocument.Declaration’ of type ‘System.Xml.Linq.XDeclaration’, see inner exception for more details. —> System.InvalidOperationException: System.Xml.Linq.XDeclaration cannot be serialized because it does not have a parameterless constructor. — End of inner exception stack trace — at System.Xml.Serialization.StructModel.CheckSupporte dMember(TypeDesc typeDesc, MemberInfo member, Type type) at System.Xml.Serialization.StructModel.GetPropertyMo del(PropertyInfo propertyInfo) at System.Xml.Serialization.StructModel.GetFieldModel (MemberInfo memberInfo) at System.Xml.Serialization.XmlReflectionImporter.Ini tializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Imp ortStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter) — End of inner exception stack trace — at System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Imp ortAccessorMapping(MemberMapping accessor, FieldModel model, XmlAttributes a, String ns, Type choiceIdentifierType, Boolean rpc, Boolean openModel, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Imp ortFieldMapping(StructModel parent, FieldModel model, XmlAttributes a, String ns, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Ini tializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter) — End of inner exception stack trace — at System.Xml.Serialization.XmlReflectionImporter.Ini tializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Imp ortStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter) — End of inner exception stack trace — at System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Imp ortAccessorMapping(MemberMapping accessor, FieldModel model, XmlAttributes a, String ns, Type choiceIdentifierType, Boolean rpc, Boolean openModel, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Imp ortFieldMapping(StructModel parent, FieldModel model, XmlAttributes a, String ns, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Ini tializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter) — End of inner exception stack trace — at System.Xml.Serialization.XmlReflectionImporter.Ini tializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Imp ortStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter) — End of inner exception stack trace — at System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Imp ortElement(TypeModel model, XmlRootAttribute root, String defaultNamespace, RecursionLimiter limiter) at System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace) at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace) at NinjaTrader.NinjaScript.StrategyBase.ToXml() at NinjaTrader.NinjaScript.StrategyBase.DbAdd() at NinjaTrader.NinjaScript.StrategyBase.DbUpdate() at NinjaTrader.Cbi.DB.DBThread().

Any idea why I get this error message? Unfortunately NinjaTrader does not indicate the line in the code where the error has occured.

Источник

  • Home
  • VBForums
  • Visual Basic
  • Visual Basic .NET
  • VS 2012 [RESOLVED] Export Object to XML with Reflection

  1. Jul 26th, 2013, 01:59 AM


    #1

    Simon Canning is offline

    Thread Starter


    Frenzied Member


    Resolved [RESOLVED] Export Object to XML with Reflection

    I have had a look on the WWW for some code but could not find any so I thought that I would ask here.

    Does anyone have a class, or some code that I can pass an object to (of any type) and an XML file is created that has all the values of the objects fields and the name of each field? I am sure this is a combination of reflection and XML.

    Rather than writing this myself, I thought I would ask first.


  2. Jul 26th, 2013, 03:21 AM


    #2

    Re: Export Object to XML with Reflection

    Are you not using XML serialisation for a reason or do you just not know it exists?

    http://msdn.microsoft.com/en-us/libr…erializer.aspx


  3. Jul 26th, 2013, 03:26 AM


    #3

    Simon Canning is offline

    Thread Starter


    Frenzied Member


    Re: Export Object to XML with Reflection

    I did not know that it existed.

    Thanks for the link.


  4. Aug 5th, 2013, 02:02 AM


    #4

    Simon Canning is offline

    Thread Starter


    Frenzied Member


    Re: Export Object to XML with Reflection

    When trying to serialize a class of mine, I am getting the following error:

    there was an error reflecting type

    This class has a List(Of String) as a field as well as some User Created Classes.

    Are the User Created Classes the issue here? To serialize this object, do I need to add a specific attribute to ignore these classes, or is there another way?

    Last edited by Simon Canning; Aug 5th, 2013 at 02:23 AM.


  5. Aug 5th, 2013, 02:27 AM


    #5

    Simon Canning is offline

    Thread Starter


    Frenzied Member


    Re: Export Object to XML with Reflection

    Here is my code:

    Code:

    <Serializable> Public Class ClassTest
        Public string1 As String
        Public string2 As String
        Public ListOfString As List(Of String)
        Public dreamscript As New DreamScript
    End Class

    Code:

        Public Sub SerializeObjectToXML(FileName As String, ObjectToSerialize As Object, ObjectType As Type)
            Dim Serializer As New XmlSerializer(ObjectType)
            Dim Writer As New StreamWriter(FileName)
            Serializer.Serialize(Writer, ObjectToSerialize)
            writer.Close()
        End Sub

    Here is the error:

    There was an error reflecting type ‘CanLucidDream.ClassTest’.

    At line:

    Code:

    Dim Serializer As New XmlSerializer(ObjectType)


  6. Aug 5th, 2013, 06:49 AM


    #6

    Simon Canning is offline

    Thread Starter


    Frenzied Member


    Re: Export Object to XML with Reflection

    Can I please have some help to serialize an object of this class?


  7. Aug 5th, 2013, 07:11 AM


    #7

    Re: Export Object to XML with Reflection

    Have you looked deeper into the exception? Is there an inner exception?

    By the way, you know by now that bumping your threads is against forum rules so maybe don’t do it.


  8. Aug 5th, 2013, 07:26 AM


    #8

    Simon Canning is offline

    Thread Starter


    Frenzied Member


    Re: Export Object to XML with Reflection

    Here is the full stack trace:

    Code:

    System.InvalidOperationException was unhandled
      HResult=-2146233079
      Message=There was an error reflecting type 'CanLucidDream.ClassTest'.
      Source=System.Xml
      StackTrace:
           at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
           at System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModel model, XmlRootAttribute root, String defaultNamespace, RecursionLimiter limiter)
           at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
           at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
           at System.Xml.Serialization.XmlSerializer..ctor(Type type)
           at CanLucidDream.CommonActions.SerializeObjectToXML(String FileName, Object ObjectToSerialize, Type ObjectType) in C:UsersSimonDocumentsVisual Studio 11ProjectsCanLucidDreamCanLucidDreamCommonActions.vb:line 103
           at CanLucidDream.FormListOfDreamScripts.Button1_Click(Object sender, EventArgs e) in C:UsersSimonDocumentsVisual Studio 11ProjectsCanLucidDreamCanLucidDreamFormListOfDreamScripts.vb:line 318
           at System.Windows.Forms.Control.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
           at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ButtonBase.WndProc(Message& m)
           at System.Windows.Forms.Button.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.Run(ApplicationContext context)
           at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
           at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
           at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
           at CanLucidDream.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
           at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
           at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
           at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
           at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
           at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
           at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
           at System.Activator.CreateInstance(ActivationContext activationContext)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException: System.InvalidOperationException
           HResult=-2146233079
           Message=There was an error reflecting field 'dreamscript'.
           Source=System.Xml
           StackTrace:
                at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
                at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter)
                at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
           InnerException: System.InvalidOperationException
                HResult=-2146233079
                Message=There was an error reflecting type 'CanLucidDream.DreamScript'.
                Source=System.Xml
                StackTrace:
                     at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
                     at System.Xml.Serialization.XmlReflectionImporter.ImportAccessorMapping(MemberMapping accessor, FieldModel model, XmlAttributes a, String ns, Type choiceIdentifierType, Boolean rpc, Boolean openModel, RecursionLimiter limiter)
                     at System.Xml.Serialization.XmlReflectionImporter.ImportFieldMapping(StructModel parent, FieldModel model, XmlAttributes a, String ns, RecursionLimiter limiter)
                     at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
                InnerException: System.InvalidOperationException
                     HResult=-2146233079
                     Message=There was an error reflecting property 'DreamScriptBackgroundSound'.
                     Source=System.Xml
                     StackTrace:
                          at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
                          at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter)
                          at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
                     InnerException: System.InvalidOperationException
                          HResult=-2146233079
                          Message=There was an error reflecting type 'CanLucidDream.Sound'.
                          Source=System.Xml
                          StackTrace:
                               at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
                               at System.Xml.Serialization.XmlReflectionImporter.ImportAccessorMapping(MemberMapping accessor, FieldModel model, XmlAttributes a, String ns, Type choiceIdentifierType, Boolean rpc, Boolean openModel, RecursionLimiter limiter)
                               at System.Xml.Serialization.XmlReflectionImporter.ImportFieldMapping(StructModel parent, FieldModel model, XmlAttributes a, String ns, RecursionLimiter limiter)
                               at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
                          InnerException: System.InvalidOperationException
                               HResult=-2146233079
                               Message=Cannot serialize member 'CanLucidDream.Sound.SoundFileInfoObject' of type 'System.IO.FileInfo', see inner exception for more details.
                               Source=System.Xml
                               StackTrace:
                                    at System.Xml.Serialization.StructModel.CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type type)
                                    at System.Xml.Serialization.StructModel.GetPropertyModel(PropertyInfo propertyInfo)
                                    at System.Xml.Serialization.StructModel.GetFieldModel(MemberInfo memberInfo)
                                    at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
                                    at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter)
                                    at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
                               InnerException: System.InvalidOperationException
                                    HResult=-2146233079
                                    Message=System.IO.FileInfo cannot be serialized because it does not have a parameterless constructor.
                                    InnerException:


  9. Aug 5th, 2013, 07:38 AM


    #9

    Re: Export Object to XML with Reflection

    Have you even read that stack trace? It would appear not. What exactly do you find confusing about this:

    Message=System.IO.FileInfo cannot be serialized because it does not have a parameterless constructor.

    Sorry but you’re wasting my time when you have all the diagnostic information you need right in front of you and just ignore it. I won’t be posting here again.


  10. Aug 5th, 2013, 12:28 PM


    #10

    Re: Export Object to XML with Reflection

    What jmc is saying is that the object you’re serializing has to have a constructor that looks like this:-

    vbnet Code:

    1. '

    2. Public Sub New()

    3.     ''' Constructor code here

    4. End Sub

    Notice no parameters in the constructor.


  11. Aug 6th, 2013, 02:51 AM


    #11

    Simon Canning is offline

    Thread Starter


    Frenzied Member


    Re: Export Object to XML with Reflection


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic .NET
  • VS 2012 [RESOLVED] Export Object to XML with Reflection


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

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

Понравилась статья? Поделить с друзьями:
  • 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 перевод
  • There was an error processing your request please try again later ubisoft
  • There was an error processing your request please try again at a later time