Save datatable as user setting - c#

I currently try to save a datatable as a user setting using die old "properties.settings.default.save()" method.
It does not work. My Settings don't get saved. however it does work when I try to save a string as setting.
So I am really wondering why it doesn't work with the datatable. Saving the datatale would make a lot of things easier for me, so any help on that or any alternative solutions would be greatly appreciated!

You can save the DataTable as an XML string to an ordinary String setting, like this:
StringWriter writer = new StringWriter();
table.WriteXml(writer);
Settings.Default.TableXml = writer.ToString();
You can then load it from the setting like this:
StringReader reader = new StringReader(Settings.Default.TableXml);
table.ReadXml(reader);

I believe I encountered this same problem while performing a LINQ query on a DataTable from an ERP database. After using the CopyToDataTable() method on the query result and assigning it to the settingTable setting, I verified that neither the resultTable nor the settingTable were null and I ran the Settings.Default.Save() method. However, I received a null error when I subsequently attempted to assign the settingTable to a dataTable variable.
I resolved this problem by assigning the settingTable.TableName property to something other than its default value (the null string) before running the Settings.Default.Save() method.
Note: The ERP system is really slow, I would just query the data directly using the ERP's business objects.

sadly the solution above doesn't work for me (got an exceptation that the root element is missing).
I had to make this adjustments.
Create XML String:
StringWriter writer = new StringWriter();
table.WriteXml(writer, XmlWriteMode.WriteSchema); //WriteSchema
Settings.Default.TableXml = writer.ToString();
Create DataTable from Xml String
StringReader reader = new StringReader(Settings.Default.TableXml);
table.ReadXml(reader);
Hope this helps al further users having the same problem ;)

Related

DataSet.ReadXml not getting all data

I have a relatively simple xml file that I would like to use to fill a DataSet. I am trying the following code
using (DataSet ds = new DataSet())
{
ds.ReadXml(Server.MapPath("xmlFileName.xml"));
}
But my dataset ends up with only one row containing the first node of the file.
I have tried other methods such as
XmlReader xmlFile = XmlReader.Create("xmlFileName.xml", new XmlReaderSettings());
DataSet ds = new DataSet();
ds.ReadXml(xmlFile);
And
FileStream fsReadXml = new FileStream("xmlFileName.xml", FileMode.Open);
XmlTextReader xmlReader = new System.Xml.XmlTextReader(fsReadXml);
newDataSet.ReadXml(xmlReader, XmlReadMode.ReadSchema);
Both of which result in empty datasets.
I can't post the entire xml file, but its format is essentially
<service_orders count="70">
<service_order order_number="1111" id="111111">
<customer>
<customer_id>55555</customer_id>
<first_name>John</first_name>
<last_name>Doe</last_name>
<email>JohnDoe#gmail.com</email>
<phone1>55555555</phone1>
The first method I mentioned only generates two columns from this
"service_order_id" and "count"
with values 0 and 70 respectively.
It seems like it's only hitting the first node?
So I'm not sure what I'm doing wrong with these methods. Is the xml file not formatted properly? Do I somehow need to make it go deeper into the nodes? Is there any way I can specify which nodes to hit?
Any help would be appreciated,
Thank you
I realized I had forgotten that DataSets hold multiple tables, and that I was only looking at the first one which contained the root. Though this did help me understand how the parser navigates the xml tree. Only leaf elements (with no children) get added to the tables, all other elements get tables of their own in the dataset.

What would be a good simple solution for data storage in a Silverlight application?

I have a silverlight application running on an IIS which currently has some data lists hard coded into the c#, not a good idea I know but this was for a proof of concept demo and now I need to move on to getting the data from another source which can be modified.
I've looked at xml files as well as an sql database. The problem is that the client is reluctant to allow anything extra to be installed on the machine (long security process) and so sql express may not be practical. I've also tried to look into sql compact edition but I cannot seem to be able to find any decent tutorials about it.
The data is made up of three, fairly short, lists of small objects which contain strings and integers. I'm looking for a, preferably, simple and quick to implement solution which ideally does not need anything extra installing on the server.
Does anyone have any suggestions or links which may be handy?
Thanks in advance
Cap
If you are comfortable using LINQ to query your data instead of SQL, Sterling DB sounds perfect for you. It's extremely lightweight, and requires nothing extra on the server or the client (other than including it in your code obviously). It uses isolated storage to store data. All of the serialization/deserialization is taken care of for you by the library.
Edit:
Based on your comment that the data is "static" (meaning all clients consume the same data), it's probably best not to use a client-side database like Sterling or even (as you mentioned) SQL CE. You are right to have reservations about hard-coding this type of "catalog" data, as changes in that data would require a new release of software.
A simple way to make the abstraction is to simply host an XML file alongside your XAP that contains all your data. You can author the XML in any way you want. In the software, it should be fairly straightforward to download the XML file, parse it, and populate your catalog each time the app runs. When changes to the catalog are necessary, it's just a matter of modifying the XML file.
I know this is not an ideal solution but you could try using tab separated text files. They are the easiest to create.
I use XML (web.config) to store data use by all clients such as pre-configure or default user setting value and use Isolated Storage for client-independent data, such as, user UI-layout setting.
I would serialize the objects to XML and store them on the server, it's relatively easy to do
You can pull the values into and XDocument
XDocument ConnectionStrings = XDocument.Load(System.AppDomain.CurrentDomain.BaseDirectory + "ConnectionStrings.xml");
Here are the serialization function i'm using
private static XDocument Serialize<T>(object obj)
{
XDocument ReturnValue = new XDocument();
//Create our Serializer with the type that was passed in
XmlSerializer Serializer = new XmlSerializer(typeof(T));
//Serialize our object to a string writer
System.IO.StringWriter sw = new System.IO.StringWriter();
Serializer.Serialize(sw, obj);
//We use a string reader to read the string from our Writer (created when serialized)
System.IO.StringReader sr;
sr = new System.IO.StringReader(sw.ToString());
//Then we can load the string reader giving us an XDocument
ReturnValue = XDocument.Load(sr);
return ReturnValue;
}
private static T Deserialize<T>(XDocument Xdoc)
{
T ReturnValue;
//Create our Serializer with the type that was passed in
XmlSerializer Serializer = new XmlSerializer(typeof(T));
//Create a string reader to access the XML data in our XDocument
System.IO.StringReader sr = new System.IO.StringReader(Xdoc.ToString());
//Deserialize the XML into our object
ReturnValue = (T)Serializer.Deserialize(sr);
return ReturnValue;
}

How to serialize/de-serialize a custom DataSet

I have a winforms app that uses a strongly typed custom DataSet for holding data for processing. It gets populated with data from a database.
I have a user control that takes any custom dataset and displays the contents in a data grid. This is used for testing and debugging. To make the control reusable, I treat the custom dataset as a normal System.Data.DataSet.
I have extended the control to allow the dataset to be saved to an XML file and also load previously saved XML files.
What I'm now trying to do is take the loaded data file, which is treated as a standard DataSet, and cast it back to the Custom Dataset. This shouldn't be difficult but I am getting the following System.InvalidCastException message:
Unable to cast object of type 'System.Data.DataSet' to type
'CostingDataSet'.
Here is an example of the problem code (It's the last line of the 3 that generates the exception):
DataSet selected = debugDisplay.SelectedDataSet;
CostingDataSet tempDS = new CostingDataSet();
tempDS = (CostingDataSet)selected.Copy();
Can anyone give me a steer on how to fix this?
Edit:
Following the comments from nEM I implemented this and all was good.
foreach (System.Data.DataTable basicDT in selected.Tables)
{
DataTable dt = tempDS.Tables[basicDT.TableName];
dt = basicDT.Copy();
}
In addition, the code suggested by SSarma also works.
From what I have gathered from this website, you can't cast a regular dataset into a typed one which makes sense as its strongly typed and has certain specifications. If you have saved it as a regular dataset, when you deserialise it, the XML has no recollection of it ever being created as a typed dataset. For the xml file, you only ever saved a regular dataset so it is equivalent to trying to convert a standard dataset into a typed one by explicit casting which isn't allowed.
You could create a populate method that takes in a regular dataset as an argument which copies all the data into your typed dataset.
This is assuming that you are serialising it as a standard dataset.
How about using Streams (sorry following code is not tested) but you get the idea
DataSet selected = debugDisplay.SelectedDataSet;
string ds1 = selected.GetXml();
CostingDataSet tempDS = new CostingDataSet();
System.IO.MemoryStream ms = new System.IO.MemoryStream(ds1.Length);
selected.WriteXml(ms);
ms.Position = 0;
tempDS.ReadXml(ms);

C# XmlTextReader and DataSet causing Duplicate Name Exception

I'm trying to read a standard CNN news feed to put into a table, and it's telling me "duplicate 'link' column exception." on the line:
cnnds.ReadXml(CNNfeed);
Here's the whole code, and it stops the code and throws errors, when it should simply just ignore duplicate columns or use the last column.
XmlTextReader CNNfeed = new XmlTextReader("http://rss.cnn.com/rss/cnn_topstories.rss");
DataSet cnnds = new DataSet("CNN");
cnnds.ReadXml(CNNfeed, XmlReadMode.Auto); // read the XML feed
DataTable CNNNewsFeedTable = new DataTable("CNNNewsFeed");
How do I resolve this issue? I've tried everything, and the only way to get this to work is to properly not use the CNN feed.
I just changed XmlReadMode.ReadSchema and it got through this part but then it says cnnds.Tables[1] is an index out of range. Like as if it's an empty XML.
Is there any easier way to read RSS feeds from other websites without all these exceptions and problems?
Edit: It seems adding a try { } catch() around it, however redundant, seems to bypass this problem.
If you want to read the xml in a dataset, then you need the xml-schema (else ReadXml() can't distinguish between the different namespaces).
Use:
var CNNfeed = new XmlTextReader("http://rss.cnn.com/rss/cnn_topstories.rss");
var cnnds = new DataSet("CNN");
cnnds.ReadXmlSchema("http://www.thearchitect.co.uk/schemas/rss-2_0.xsd"); // read the rss schema
cnnds.ReadXml(CNNfeed); // read the XML feed
But I think you'd better use xpath to find the information you need:
var doc = XDocument.Load("http://rss.cnn.com/rss/cnn_topstories.rss");
foreach (XElement node in (IEnumerable) doc.XPathEvaluate("//item"))
{
Console.WriteLine(node.XPathSelectElement("title").Value);
}

Howto parse csv and returns a dataSet as a result

I need a CSVParser class file
A Class File which parses csv and returns a dataSet as a result ASP.Net
I'm pretty sure that CSVReader (CodeProject) can read to DataTable.
DataTable table = new DataTable();
// set up schema... (Columns.Add)
using(TextReader text = File.OpenText(path))
using(CsvReader csv = new CsvReader(text, hasHeaders)) {
table.Load(csv);
}
Note that manually setting up the schema is optional; if you don't, I believe it assumes that everything is string.
Simple google gives plenty of results.
I've had luck with this parser. It will return results to a DataSet.
Another tool you might want to check out is FileHelpers. I see there's a tag for this resource here on SO.

Categories

Resources