Error while XML deserialization to class generated by XSD tool - c#

I want to integrate UPS service Locator.
I download from UPS website two XSD templates describing request and response. To generate c# classes I used XSD.exe tool. It generated two files for each template. In both classes are duplicated classes, which make errors, so I remove duplicated classes from one file.
Everything works, I obtain data from UPS API, but when I try to deserialize response to object LocatorResponse (class generated from XSD template) I get errors
Unable to generate a temporary class (result=1). error CS0030: Cannot
convert type 'string[]' to 'string' error CS0029: Cannot implicitly
convert type 'string' to 'string[]'
My code, I attach also generated class
string authBody = GetAuthString();
string accessPoint = GetAccessPointPostBody();
var response = GetResponseString(authBody + accessPoint);
using (TextReader reader = new StringReader(response))
{
// this line below makes problem
var serializer = new XmlSerializer(typeof(LocatorResponse));
// this line above makes problem
var result = (LocatorResponse)serializer.Deserialize(reader);
}
What I do wrong??

Related

map json schema to c# model with NJsonSchema throws System.InvalidCastException

Im trying to convert really simple json schema to my c# model using nuget from this link
Im using example code from the github repo such as:
var schema = """{"$schema":"http://json-schema.org/draft-04/schema#","title":"Person","type":"object","additionalProperties":false,"required":["FirstName","LastName"],"properties":{"FirstName":{"type":"string"},"LastName":{"type":"string"}},"definitions":{}}""";
var generator = new CSharpGenerator(schema);
var file = generator.GenerateFile("mytest"); // on this line I got an exception
Console.WriteLine(file);
Console.ReadLine();
this is my json schema:
Notice: Im using .net 7 , you can notice that Im using tripple string in order to accept json with double quotes.
Exception that I get:
System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'NJsonSchema.JsonSchema'.'
What I did wrong here?

There is an error in XML document when deserializing(C#)

I have the following xml:
XML
I have the following C# class
C# GlobalClass
I am trying to convert the xml content into C# custom object like that:
string xmlFilePath = Android.OS.Environment.ExternalStorageDirectory.ToString() + "/Settings4/settings.xml";
XmlSerializer deserializer = new XmlSerializer(typeof(GlobalClass));
TextReader textReader = new StreamReader(xmlFilePath);
GlobalClass globalVariables;
globalVariables = (GlobalClass)deserializer.Deserialize(textReader);
textReader.Close();
But I get
There is an error in XML document
on the line of code
globalVariables = (GlobalClass)deserializer.Deserialize(textReader);
I make GlobalClass inherit from Application because I want GlobalClass to be global that is to say I want to use its properties throughout all activities. What I'm doing wrong to recieve that error?
In your class put something like this [Serializable, XmlRoot("YourRoot")]
When you work with deserialization it might not found.
From MSDN
The name of the XML root element that is generated and recognized in
an XML-document instance. The default is the name of the serialized
class.

Deserialization not working across projects

I am encountering a problem with Json.NET (version 6.0.5) that leaves me a bit puzzled.
One of my classes that gets to be serialized looks something like this:
[JsonConstructor]
public MyContainerClass(IEnumerable<AbstractBaseClass> myDerivedUnitClasses)
{
if (myDerivedUnitClasses == null)
{
Units = ImmutableHashSet.Create<object>();
}
else
{
Units = myDerivedUnitClasses.ToImmutableHashSet();
}
}
public IEnumerable<AbstractBaseClass> Units { get; private set; }
Using Json.Convert with TypeNameHandling set to TypeNameHandling.Auto serializes this without problems. The serialized JSON includes the expected $type-qualifier for the property: "System.Collections.Immutable.ImmutableHashSet`1[[AbstractBaseClass, MyLibrary]], System.Collections.Immutable"
I got one project in my Solution where I serialize the data structure and another one where I deserialize it using Json.Convert (deserialization also using automatic type name handling). Deserialization fails with this error: Error resolving type specified in JSON System.Collections.Immutable.ImmutableHashSet`1[[AbstractBaseClass, MyLibrary]], System.Collections.Immutable
Using the source of Json.NET I traced the error back to the DefaultSerializationBinder calling assembly.GetType(string name) and getting null as result.
So far so bad. Here comes the part that leaves me especially puzzled right now: When I deserialize the JSON in the same code block where I serialize my data structure everything works perfectly fine (using the same code that I use in the other project).
Thank you for your help.
Turns out there was an assembly binding problem regarding the assembly containing AbstractBaseClass in the one project. I used fuslogvw.exe of the Visual Studio Tools while debugging to check for errors and noted that the directories that were searched were not the ones I was expecting and did not contain the assembly file.
My solution was to subscribe to the AppDomain.CurrentDomain.AssemblyResolve-event prior to deserialization and then manually load the assembly from the correct path via Assembly.LoadFrom in the event handler.

Fedex Service Integration Error (unable to generate a temporary class)

I am trying to integrate Fedex Service in my asp.net website. I have downloaded the code from the Fedex website, but when I run this simple program I get an error,
Check the following Code:
static void Main(string[] args)
{
TrackRequest request = CreateTrackRequest();
TrackService service = new TrackService();//I get Error Here
if (usePropertyFile())
{
service.Url = getProperty("endpoint");
}
try
{
// Call the Track web service passing in a TrackRequest and returning a TrackReply
TrackReply reply = service.track(request);
if (reply.HighestSeverity == NotificationSeverityType.SUCCESS || reply.HighestSeverity == NotificationSeverityType.NOTE || reply.HighestSeverity == NotificationSeverityType.WARNING)
{
ShowTrackReply(reply);
}
ShowNotifications(reply);
}
catch (SoapException e)
{
Console.WriteLine(e.Detail.InnerText);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("Press any key to quit!");
Console.ReadKey();
}
The Following error on debugging occurred on TrackService service = new TrackService(); (line #5):
Unable to generate a temporary class (result=1).
error CS0029: Cannot implicitly convert type
'TrackWebServiceClient.TrackServiceWebReference.EMailNotificationEventType' to
'TrackWebServiceClient.TrackServiceWebReference.EMailNotificationEventType[]'
This might be an issue with the way that WSDL.exe generates the client code.
You will have to manually edit Reference.cs file to replace double brackets [][] to single [] in EmailNotificationEventType definition.
From Microsoft:
There is no resolution available at this point. However, three workarounds are available:
You can generate the proxy class manually by using WSDL.exe and then change the proxy class in which the data type was inappropriately created as a two-dimensional array (for example, "CustomType[][]") so that it is a single-dimensional array (for example, "CustomType[]").
You can change the data type in the desired Web Services Description Language (WSDL) so that a second, optional element is included in the definition. You can do this by adding an element such as the following:
<xs:element minOccurs="0" name="dummyElement" nillable="true" type="xs:string"/>
You can change the complex type in the desired WSDL so that the boundary attributes are part of the complex type instead of being part of the element. (That is, you can move the minOccurs and maxOccurs attributes to the complex type and then remove them from the element.)
Check also this link for further explanation.
I tried the third option "You can change the complex type in the desired WSDL so that the boundary attributes are part of the complex type instead of being part of the element. (That is, you can move the minOccurs and maxOccurs attributes to the complex type and then remove them from the element.)" and it worked. The solution below:
Removed from the WSDL the minOccurs and maxOccurs for the NotificationEventsAvailable element [see the image below]

how to ask XSD.exe to generate proper class for me, so that i can create a fine XML

I have created an XSD file from Visual Studio 2010,
Then I use xsd /c mydemo.xsd to generate class for me, so that I can create a XML file at runtime.
However, when I use that class, fill in some values, and serialize the object, the XML file does not look nice to me.
Here is my XSD file Click here to see
What I expected the XML file to be is Click here to see
(Generated from Visual Studio "Sample XML")
But when I try to serialize it, the XML file is like this CLick here to see
The format is totally different
e.g
Expecting:
<ColumnInfo>
<Column Type="Type1" DisplayValue="DisplayValue1" Key="Key1"/>
<Column Type="Type2" DisplayValue="DisplayValue2" Key="Key2"/>
<Column Type="Type3" DisplayValue="DisplayValue3" Key="Key3"/>
</ColumnInfo>
but the generate result is like this:
<columnInfoField>
<ColumnType>
<displayValueField>Display value for key 1</displayValueField>
<keyField>key1</keyField>
<typeField>string</typeField>
</ColumnType>
<ColumnType>
<displayValueField>Display value for key 2</displayValueField>
<keyField>key2</keyField>
<typeField>int</typeField>
</ColumnType>
<ColumnType>
<displayValueField>Display value for key 3</displayValueField>
<keyField>key3</keyField>
<typeField>long</typeField>
</ColumnType>
</columnInfoField>
And the code I implement to serialize the report is :
http://msdn.microsoft.com/en-us/library/ms731073.aspx
DataContractSerializer dcs = new DataContractSerializer(typeof(Report));
using (XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(File.Create(#"C:\demo\schema\output.xml"), Encoding.UTF8))
{
dcs.WriteObject(xdw, report);
}
Not sure why I cannot use "XmlSerializer", when I use it, it will complain about cannot cast array type something...
Unable to generate a temporary class (result=1).
error CS0030: Cannot convert type 'ColumnValueType[]' to
'ColumnValueType'
error CS0029: Cannot implicitly convert type 'ColumnValueType' to
'ColumnValueType[]'
So, does anyone can give me some suggestion, how can i fix my XML format???
There is a bug on xsd.exe - look at this blog-post:
http://satov.blogspot.com/2006/12/xsdexe-generated-classes-causing.html
The data contract serializer has different rules that the XmlSerializer. Why don't you try the XmlSerializer first and then see if the output is "correct".

Categories

Resources