System.InvalidOperationException: 'There is an error in XML document (0, 0).' - c#

I am trying to deserialize a file, none of the other solutions are working for me.
This is the code. I get the error on the 'customerList' line
using (StreamReader customerStreamReader =
new StreamReader(#"C:\...\ShoppingApplication\bin\Debug\Customer.xml"))
{
customerList = (List<Customer>)customerSerializer.Deserialize(customerStreamReader);
}

Look into using XDocument instead for it will be more robust in reporting errors, though the 0,0 location is a common one. Avoid using streams because they are so, .Net 2.
Here is an example:
var doc = XDocument.Load(#"C:\...\ShoppingApplication\bin\Debug\Customer.xml");
Console.WriteLine(doc);
Then extract what is needed from the actual nodes.

For anybody coming here from google:
If you do not want to use XDocument, then you must make sure that your .xml is NOT empty. Once I added something, I was able to deserialize it just fine. Hope this helps!

Related

Dynamic JSON schema validation using c#

I am trying to do a JSON schema validation dynamically. We are taking the JSON from an uploaded file and trying to validate this is exact JSON or not. This is an On premise application.I cannot use JSON.net. I cannot install any other third party tools to validate this. I have tried two ways as below.
1.I used System.Web.Helper and Using the below code, i am getting the error
code :
var jsonstring = "{\"user\":{\"name\":\"asdf\",\"age\":\"26\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
var jsonObject = Json.Decode(jsonstring);
Error is "Attempt by method 'System.Web.Helpers.Json.Decode(System.String)' to access field 'System.Web.Helpers.Json._serializer' failed". I searched for solutions and found that we need to uncheck a check box in debug properties of solution.But this only works in Console application for me.But not working in our VS 2012 solution. Is there any way to solve this issue?
Next is, i tried to use JavaScriptSerializer as given below and successfully got the results in my objJson.
JavaScriptSerializer serializer = new JavaScriptSerializer();
string inputContent;
StreamReader inputStreamReader = new StreamReader(FileUploadControl.PostedFile.InputStream);
inputContent = inputStreamReader.ReadToEnd();
inputContent = inputContent.Replace("\r", "").Replace("\n", "").Replace("\t", "");
var objJson= serializer.Deserialize>(inputContent);
But when i am trying to get values of this resulted key values pair, i am getting error as in image. Error is Dynamic operations can only be performed in homogenous AppDomain. for this the solution found was to change the attribute "legacyCasModel=true" to "legacyCasModel=false" in web.config file. But as this is OnPremise application i cannot change this attribute.Please help on this.
Suggest you to have a look at this stackoverflow post
In nutshell what you want to do is :
Perform some basic checks i.e. if JSON string starts with either
'{'
or '['
Try to parse JSON string using JToken.Parse if there
is an exception while parsing simply log or display this to end user and move on ! you are just
trying to validate JSON string not attempting to clean it right ?
PS : Please do refer the linked question for greater details.

C# Error in readering XML from URL

I have an XML reader but I receive an error when I'm trying to read the XML from an URL (external source).
This is the code I have ATM:
XmlReader xmlReader = XmlReader.Create("http://dl.bukkit.org/api/1.0/downloads/projects/craftbukkit/view/build-1330/");
while (xmlReader.Read())
{
}
Very simple code, but it returns an error which says:
Data at the root level is invalid. Line 1, position 1.
Any idea?
I can't edit the XML, because it's not mine.
Thanks in advance!
If you use Fiddler to analyze the response returned by the sever, you'll see, that you get JSON instead of XML. You can add a parameter to the URL to get XML:
http://dl.bukkit.org/api/1.0/downloads/projects/craftbukkit/view/build-1330/?format=xml

How to create a component by providing the XML source file as input

I want to create a component by giving XML source input directly using core service 2011, in SDL Tridion 2011.
I want to write code to create a component by uploading source XML. Using the core service 2011.
Say name of the xml file is helloworld.xml and location is D:\abcd\cdef\all\helloworld.xml.
I have written the code like this, but its not working.
XmlDocument contentxml = new XmlDocument();
contentxml.LoadXml(#"D:\abcd\cdef\all\helloworld.xml");
Response.Write("<BR>" + contentxml.ToString());
component.Content = contentxml.ToString();
ComponentData comp = (ComponentData)client.Create(component, new ReadOptions());
The Response.write is displaying nothing. Correct me if I missed any thing.
It's not creating any component and error is coming.
When i tried this:
XmlDocument contentxml = new XmlDocument();
try
{
contentxml.LoadXml(#"D:\abcd\cdef\all\helloworld.xml");
}
catch (XmlException exp)
{
Console.WriteLine(exp.Message);
}
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
contentxml.WriteTo(xw);
Response.Write("<BR>" + sw.ToString());
component.Content = sw.ToString();
ComponentData comp = (ComponentData)client.Create(component, new ReadOptions());
This time it's showing unable to find UUId: some thing like that.
My helloworld.xml looks like this.
<Content xmlns="uuid:1111eb85-0X11-11f9-1e2X-1X82X78fX920">
<first>Hello World.This is Fisrt field</first>
<second>Hello World.This is second field</second>
</Content>
It would be great if some one share some sample code to do it.
Loading any XML from a a file and trying to create a component won't work unless the XML uses the format the CMS is expecting.
The XML structure of a component in SDL Tridion has some fixed parts (Example Nodes Content, Metadata) plus some flexible parts
(The way you define the fields).
First you need to have the XML with the same structure that the CMS is expecting.
Typically the nodes that should be in your xml are the CONTENT and METADATA, load those in an XML Document and use the Core Service API to
create a component using the content contained in those nodes.
The best way to know how which is the structure of a component based on an schema is to create a sample component using the Tridion UI and
see how the XML is constructed. After that you need to create your XML Sources using that structure.
I posted recently an example of how to create a component using the Core Service, please have a look at that.
Faulted State error while creating component with Core Service
Following this code, you can access the nodes Content and Metadata
componentData.Content = xmlUtil.GetNewXmlNode("Content", schemaData.NamespaceUri);
componentData.Metadata = xmlUtil.GetNewXmlNode("Metadata", schemaData.NamespaceUri);
And replace those with your content
The general outline:
Load the XML from the file into an XDocument / XmlDocument.
Create a new Component by calling GetDefaultData on the client.
Set the Content property of the Component to the XML.
Save the Component by calling Save on the client.
If you haven't already, please have a look at the Core Service API documentation available on SDL Tridion World.
If you have trouble implementing this, please post the code that you have and what you have tried in order to make it work.
Using XmlDocument.LoadXML() expects an XML string as input, as commented by Peter you should use XMLDocument.Load() instead, see here for more details http://msdn.microsoft.com/en-us/library/a8ta6tz4.aspx
When you have passed that hurdle you will need the information Miguel gave in his answer to continue.

Writing to XML resource file through serialization

So I'm writing a C# app that has a couple of XML files added as resources. I read from these XML files to populate objects in the code using XML serialization and it works perfectly. So I can access the files like so (I've left some code out, just have the important bits):
using TestApp.Properties;
XmlSerializer serializer = new XmlSerializer(typeof(MapTiles));
StringReader sr = new StringReader(Resources.Maps);
mapTiles = (MapTiles)serializer.Deserialize(sr);
Now however, I'd like to do the opposite. I'd like to take some data and write it to these XML resource files. However, I seem to be running into trouble with this aspect and was hoping someone could see something I'm messing up or let me know what I need to do? Here's what I'm trying to do:
XmlSerializer serializer = new XmlSerializer(typeof(MapTiles));
TextWriter writer = new StreamWriter(Resources.Maps);
serializer.Serialize(writer, tempGroup);
writer.Close();
When I run this code though, I get an error on the 2nd line that says ArgumentException was unhandled - Empty path name is not legal.
So if anyone has any thoughts I would greatly appreciate some tips. Thanks so much.
The exception is being raised because you are passing Resources.Maps into StreamWriter. StreamWriter is handling this as a string and assuming it is file path for the stream. But the file path is empty so it is throwing an exception.
To fix out the StreamWriter line you could specify a local temporary file instead of Resources.Maps or use StringWriter with the default constructor e.g. new StringWriter().
If you are writing .resx files then ResXResourceWriter is the class you need. It will also handle your stream writing too. See http://msdn.microsoft.com/en-us/library/system.resources.resxresourcewriter.aspx and http://msdn.microsoft.com/en-us/library/ekyft91f.aspx. The second page has examples on how to use the class but breifly you would call something like this:
XmlSerializer serializer = new XmlSerializer(typeof(MapTiles));
using (StringWriter stringWriter = new StringWriter())
{
serializer.Serialize(stringWriter, tempGroup);
using (ResXResourceWriter resourceWriter = new ResXResourceWriter("~/App_GlobalResources/some_file.resx"))
{
resourceWriter.AddResource("Maps", stringWriter.ToString());
}
}
If you want to write out an assembly that has a dynamically created resource in it the you can emit a new assembly. In that case have a look here http://msdn.microsoft.com/en-us/library/8ye65dh0.aspx.
The StreamWriter constructor is throwing the exception because Resources.Maps is an empty string.
Check out the documentation on MSDN:
http://msdn.microsoft.com/en-us/library/fysy0a4b.aspx
Hmm, after trying some other things and doing even more research it appears that the problem is that you cannot write to a resource that is part of the application. Something to do with the resource being written into the assembly and therefore it's not writable. So I'll have to modify my approach and write the output to a different file.
Unless of course anyone does know differently. This is just what I've discovered so far. Thanks to those who had some ideas though, much appreciated.

Exception when trying to deserialize a xml file

Im trying to deserialize an XML file with XmlSerializer, however im getting this exception:
"There is an error in XML document (1,
2)" The innerexception is:
"<Mymessage
xmlns='http://MyMessages/'> was not
expected."
Which is the very first line in the XML file. my guess is that it has something to do with the xmlns.
I tried to ask Google, and then tried to add the following line to my code
[XmlRoot("MyMessage", Namespace="'http://MyMessages/")]
But I still get the same exception.
In the constructor of the XmlSerializer i needed to specify a default namespace, after doing that everything worked just fine
Please provide the full XML file code to help understand the issue better.
Also put this as the first line in the xml file and see if this solves the issue
<?xml version="1.0" encoding="utf-8"?>
Further to CruelIO's response, I resolved the error by adding:
[XmlRoot("RenderResult", Namespace = "http://mynamespace.uri.org")]
to the class that I was trying to deserialize. e.g: the serialization code was:
RenderResult result;
using (var memoryStream = new MemoryStream(data))
{
var xmlSerializer = new XmlSerializer(typeof(RenderResult));
result = (RenderResult)xmlSerializer.Deserialize(memoryStream);
}
and my class looked like this:
[XmlRoot("RenderResult", Namespace = "http://mynamespace.uri.org")]
public class RenderResult
{
}
It sounds like you have a borked xml file. Easy ways to find out:
try loading it into an xml viewer
or just make sure it has a .xml extension and load in VS or IE
or run xsd.exe over it
If they complain, then the xml is certainly corrupt.
If they work fine, and display your data, then you probably have the serialization attributes wrong. Try using xsd.exe with the "/classes" switch to see what it would do with it...

Categories