Issue with Xml and dataset - c#

This problem is most likely pretty simple, but I am making a dataset and trying to save it to a file using XMLTextWriter
Now when i save my dataset and then attempt to read it will read the table names but shows the rows as 0? So it seems my writer is not writing the rows of the table?
Anyone know how I can fix this?
public static DataSet liveData = new DataSet();
public static DataTable players = new DataTable("Players");
public static void WriteSchemaWithXmlTextWriter()
{
// Set the file path and name. Modify this for your purposes.
string filename = "Schema.xml";
// Create a FileStream object with the file path and name.
System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Create);
// Create a new XmlTextWriter object with the FileStream.
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.Unicode);
// Write the schema into the DataSet and close the reader.
liveData.WriteXmlSchema(writer);
writer.Close();
}
public static void ReadSchemaFromXmlTextReader()
{
// Set the file path and name. Modify this for your purposes.
string filename = "Schema.xml";
// Create a FileStream object with the file path and name.
System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Open);
// Create a new XmlTextReader object with the FileStream.
System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(stream);
// Read the schema into the DataSet and close the reader.
liveData.ReadXmlSchema(xmlReader);
Console.WriteLine("y: {0}", liveData.Tables["Players"].Rows.Count);
xmlReader.Close();
}
Thank you for your help in advance :)

You are writing the schema, which is the layout/structure of the Xml, rather than the actual content.
You need to use DataSet.WriteXml ...
https://msdn.microsoft.com/en-us/library/ms135426%28v=vs.110%29.aspx
... instead!

Related

How can I save the attribute named "x:SynchronousMode" to a xaml file?

In our software, we can draw or edit shapes and save it as a xaml.
Then, we want to load it(this xaml file) asynchronously, we used LoadAsync() method to do this, now the question is we can write x:SynchronousMode='Async' to the file manually, but how can we save this attribute to a xaml file directly(when we serialize it)?
The instruction from MSDN:
In order for LoadAsync to load XAML input asynchronously, the root
element in the XAML input must contain the attribute and value
x:SynchronousMode="Async".
Finally,I didn't find the way to add the attribute to the object, then I used a tack-handed way to solve this problem by the following code:
StringBuilder sb = new StringBuilder();
var xmlWriter = XmlWriter.Create(sb, settings);
XamlWriter.Save(Window, xmlWriter);
var str = sb.ToString().Insert(11, "assembly:SynchronousMode=\"Async\" ");
if (!File.Exists(path))
{
FileStream tmp = File.Create(path);
tmp.Close();
}
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(str);
sw.Flush();
sw.Close();
fs.Close();
Insert it to the string that we convert object into with XamlWriter directly, and then save the string as a xaml file.

How to edit a file in IsolatedStorage C#

I have been fiddling with this problem for the past hour so I thought you guys may be able to help on a Friday afternoon!
Problem
I am trying to edit an XML file in localstorage but can't figure out how to edit the existing file and re-save the file. The edit I have made it to remove a certain node from the XML.
Code
Here is the method that does all the work.
This first code snippet was already in the code and basically creates the XML file and saves it to localstorage.:
protected byte[] CreateFileData(PortableBusinessObjects.Location location, string geoObjectFilename)
{
byte[] fileData = null;
var xmlFile = System.IO.Path.GetFileNameWithoutExtension(geoObjectFilename) + ".xml";
var zipFile = System.IO.Path.GetFileNameWithoutExtension(geoObjectFilename) + ".zip";
using (IsolatedStorageFileStream fileStream = localStorage.CreateFile(xmlFile))
{
XmlWriter writer = XmlWriter.Create(fileStream);
if (location.GetType() == typeof(PortableBusinessObjects.Shape))
_xmlShapeSerializer.Serialize(writer, location);
else if (location.GetType() == typeof(PortableBusinessObjects.Point))
_xmlPointSerializer.Serialize(writer, location);
fileStream.Flush();
fileStream.Close();
}
}
This is my attempt at overwriting the saved file (Doesn't work):
using (IsolatedStorageFileStream doc = localStorage.OpenFile(xmlFile, FileMode.Open))
{
System.Xml.Linq.XDocument test = System.Xml.Linq.XDocument.Load(doc);
test.Descendants("Time").Remove();
XmlWriter writer = XmlWriter.Create(doc);
doc.Flush();
doc.Close();
}
Question
Where do I place my code that removes the "Time" nodes and saves the file?
Your saving code doesn't do any saving - you just create an XmlWriter and do nothing with it.
There are various methods built into XDocument than can help you here. While you could pass your XmlWriter to it, you can actually save directly to the stream:
test.Save(doc);
Note you will need to move to the beginning of the stream before writing to it - loading your XML will have read to the end:
doc.Position = 0;
You should use the IsolatedStorageFileStream together with the StreamWriter.
See How to: Read and Write to Files in Isolated Storage
With XDocument you then have to Save() the new contents to the stream.

Simple client server to send XML information to CRUD database

I need to develop a resident app to get info from Win32_BaseBoard class when is required by another app by XML without create any file and then this app must insert or update that information on database.
I saw a few apps but always have to create a file and i don't know if already exists something like that.
The code below will create memory stream with the data instead of writing to a file.
///old code
//XmlSerializer serializer = new XmlSerializer(typeof(AppConfig));
//StreamWriter writer = new StreamWriter(FILENAME);
//serializer.Serialize(writer, config);
//new code
string input = "Your XML here";
string output = "";
XmlSerializer serializer = new XmlSerializer(typeof(AppConfig));
MemoryStream mstream = new MemoryStream(Encoding.UTF8.GetBytes(input));
StreamWriter writer = new StreamWriter(mstream);
serializer.Serialize(writer, config);
​

Generate XML and HTML from MemoryStream

Need to generate an html report from XML and corresponding XSL butI have to use memorystream instead of IO File write on server directories. For the most part I managed to create an xml
MemoryStream ms = new MemoryStream();
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.Indent = true;
using(XmlWriter writer = XmlWriter.Create(ms,wSettings))
{
/**
creating xml here
**/
writer.Flush();
writer.Close();
}
return ms; // returning the memory stream to another function
// to create html
// This Function creates
protected string ConvertToHtml(MemoryStream xmlOutput)
{
XPathDocument document = new XPathDocument(xmlOutput);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(xmlOutput);
StringWriter writer = new StringWriter();
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(reportDir + "MyXslFile.xsl");
transform.Transform(xDoc, null, writer);
xmlOutput.Position = 1;
StreamReader sr = new StreamReader(xmlOutput);
return sr.RearToEnd();
}
Somewhere along the line I am messing up with creating the HTML Report and cant figure out how to send that file to client end. I dont have much experience working with memorystream. So, any help would be greatly appreciated. Thank you.
You're completely bypassing your transform here:
// This Function creates
protected string ConvertToHtml(MemoryStream xmlOutput)
{
XPathDocument document = new XPathDocument(xmlOutput);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(xmlOutput);
StringWriter writer = new StringWriter();
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(reportDir + "MyXslFile.xsl");
transform.Transform(xDoc, null, writer);
// These lines are the problem
//xmlOutput.Position = 1;
//StreamReader sr = new StreamReader(xmlOutput);
//return sr.RearToEnd();
return writer.ToString()
}
Also, calling Flush right before you call Close on a writer is redundant as Close implies a flush operation.
It is not clear to me what you want to achieve but using both XmlDocument and XPathDocument to load from the same memory stream does not make sense I think. And I would set the MemoryStream to Position 0 before loading from it so either have the function creating and writing to the memory stream ensure that it sets the Position to zero or do that before you call Load on the XmlDocument or before you create an XPathDocument, depending on what input tree model you want to use.

serialize to XML path issue

I am trying to serialize my Report class info to an XML. At this point I think all of the serialize and deserialize code works, but for the initial write, I'm having trouble performing the serialize, because the XML file doesn't exist yet.
for an empty text file, i can use:
StreamWriter sw = File.CreateText(#"path");
sw.Close();
this is my code block for the serializing. the exception (Directory not found) is getting thrown on the StreamWriter line. I'd like to simply add an if(!File.Exists(xmlPath))...create empty XML. Or maybe there is a more correct way to do this.
public void SerializeToXML(Report newReport)
{
XmlSerializer serializer = new XmlSerializer(typeof(Report));
TextWriter textWriter = new StreamWriter(xmlPath);
serializer.Serialize(textWriter, newReport);
textWriter.Close();
}
The StreamWriter(String) constructor will create the file if it does not already exist:
If the file exists, it is overwritten; otherwise, a new file is created.
However, it will not create any inexistent directories in your path.
DirectoryNotFoundException: The specified path is invalid, such as being on an unmapped drive.
To create any required directories, you can include the following code (at the beginning of your SerializeToXML method):
var dir = Path.GetDirectoryName(xmlPath);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
First to make sure the directory exist you can use:
Directory.CreateDirectory(#"c:\directory\subdirectory");
You don't have to check if directory already exist.
A easy way to convert public classes to XML is to use the following snippet:
public static string ToXml<T>(T obj)
{
using (var ms = new MemoryStream())
using (var sr = new StreamReader(ms))
{
var xmlSer = new XmlSerializer(typeof(T));
xmlSer.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
return sr.ReadToEnd();
}
}
Then you could just use the following code to write it to a file:
var xmlString = Util.ToXml(report);
File.WriteAllText(#"path", xmlString);
(this example is without error handling)
Also, in your code you forgot to close/dispose the TextWriter. I would recommend using the using-statement to handle it for you.
CreateText, and the StreamWriter, will create files if they don't exist, but they won't create directories that don't already exist for you. Is your path correct?
Try Checking with a Directory.Exists(Path.GetDirectoryName(xmlPath)).

Categories