.net using xml for mapping csv to class - c#

I have a Task where I have to read an csv file and write the content into a c# List.
Since the csv file can change its layout (caption/order) in the future I want to use a configuration file for mapping the attributes.
Now I am wondering if there is an example out there so I don't have to reinvent the weel :D
My datasource looks like this (tab stop seperated)
Customer No. Customer Name Created Discount
10215 John Doe 2010-08-25 5050.23
And my class like this:
Class Customer
{
string CustomerNo {get;set;}
string CustomerName {get;set;}
DateTime CreatedOn {get;set;}
decimal Discount {get;set;}
}
Now I want to have an external xml file with the definition so I can modify it at runtime without recompiling the code.
<customermapping mapstoclass="my.namespace.Customer">
<attribute csvcaption="Customer No." mapstoproperty="CustomerNo"
typeof="System.String" required="true">
<attribute csvcaption="Customer Name" mapstoproperty="CustomerName"
typeof="System.String" required="true">
<attribute csvcaption="Created" mapstoproperty="CreatedOn"
typeof="System.DateTime" required="false">
<attribute csvcaption="Discount" mapstoproperty="Discount"
typeof="System.Decimal" required="false">
</customermapping>
At the end of the Day I want to do the following:
(I already can read all the values from the csv file (the first line is the caption and is in a seperate array)
List<Customer> customers =
CreateCustomerList(string[] csvCaptions, string[] csvLines,
"c:\customermapping.xml");
Shouldn't be to complicated but as I said, if someone already did something similar, any examples are welcome.

It looks like you want to reinvent the xsd schema. If you can change the format use the xml and define that rules in the xml.
If you can't change the format or your data is too large to fit nicely in to xml I guess you are on your own. CSV isn't rather an adhoc format I don't think any body cared enough to create a schema validation for it.

You might want to look into using LINQ for this. There is an articles on LINQ to TEXT here:
Tutorial Reading A Text File Using LINQ
LINQ to TEXT and LINQ to CSV
Update: I've re-read your question and I'm no longer sure that using LINQ will really help solve your problem, however I'm leaving the answer here just in case it helps.
If you can at all help it I would put the logic about what columns map onto what properties in code rather than in xml files.

Related

Reading a string formatted like XML

I have a string that is written out like an XML file. An example would look like this:
string = <Employees><EmployeeId>1</EmployeeId>< ... ></Employees>
I am saving this in a table because I wanted to audit changes, but I didn't want to have multiple tables for different audits. This is because it would record changes to things other than employees. So using an XML style string in the database seemed like a good suggestion.
Now to the real business. I want to check to make sure that there were actually changes to the employee because one could go into the edit page, change nothing, and click save. As of right now, the data would write to the DB and just clutter it up with non-changed data.
I'd like to be able to check if the XML styled string that is going to be saved is on the database, so if <employees><employeeid>###</employeeid> == "changes" and then see if the whole string equals the other. Basically, check the employeeId first because that won't change, and then check the string as a whole to see if there is any difference. I would have just checked the first n numbers, but the id number could have a length of 1 to 3.
Also, because it is styled as XML, is there an easy way to convert it to read it like an XML file and check that way?
Storing arbitrary data in a column is a form of denormalization. You can't really do much with it at a database level. However, SQL Server does have an XML column type. Entity Framework doesn't support mapping to/from an XML column, so it will simply treat your XML as a standard string. With this column type, though, you can write actual SQL queries against your XML using XPath expressions.
Your best bet, then, is to type your column as XML, and then write a stored procedure that performs the query you need. You can then utilize this stored procedure with Entity Framework.
For more information on the XML column type see: https://msdn.microsoft.com/en-us/library/ms190798(SQL.90).aspx

How to read an xaml file and get the data I want in C#

I want to read through a xaml file, and find all the lines with 'Annotation.AnnotationText' and get specific data from that line.For example, this line:
<prwab:Branch Condition="{x:Null}" sap2010:Annotation.AnnotationText="testing information " ContinuouslyExecute="False" CreatedBy="System Administrator" CreatedOn="2013-02-23T14:51:28.1555955-05:00" DisplayName="Failure" EnableValidationRule="False" sap:VirtualizedContainerService.HintSize="160,234" ID="ab91dec8-1976-491e-91eb-58e073a69d16" IsReportable="False" LastModifiedBy="System Administrator" LastModifiedOn="2013-02-23T14:51:28.1555955-05:00" MediaRecord="[MediaRecord]" SystemName="CollectDigitsActivity1 Failure6" Timeout="10000" Type="Voice">
I want find all the lines with 'AnnotationText' in my xaml file, and get information like text = 'testing information', id = 'ab91dec8-1976-491e-91eb-58e073a69d16' , created date and lastmodified date.
I have 0 knowledge in this area and I don't know where to start and which method should I use. Thanks for helping!
XAML is just a specific flavour of XML. You will need to use XML parsing to read the file into an object that you can process in this manner. I recommend Linq to XML for this (look at XDocument class to get started), specifically as finding values by XName using a specific namespace as you will need to for the "sap2010" namespace is very easy.
You can then easily parse and extract the information you are looking for using those classes.

How to Custom Format Custom Data WPF 4.5?

I am developing some software that generates reports from event data collected from some devices. The data is stored in a database. I want the user to be able to template the output filename of the report generated by the software. So when the user decides to generate a report, the output filename template they have configured is applied to the data retrieved from the database.
For example, lets say that each report has the following data template elements associated with it:
<Name>
<Timestamp>
<Location>
<EventType>
So the user could select any of these template items in any order to determine the format of the output filename. If they chose something like this:
<Name> <EventType> <Location> <Timestamp>.pdf
And lets say this is the data for the current report in the database:
Name = "MyReport"
EventType = "Error"
Location = "Park Ave"
Timestamp = 1-30-2013 11.00.00 AM
The report filename would look like this when the actual report is generated:
"MyReport Error Park Ave 1-30-2013 11.00.00 AM.pdf"
I'm struggling to come up with an elegant way of providing custom format elements like <Name>, <Location> etc... and building a string from data in a database or possibly an entity object. I have looked at ICustomFormatter and IFormatProvider, but I'm not sure if these are completely appropriate for what I'm doing.
I am using WPF 4.5 and my data will be driven by the Entity Framework.
Any ideas would be appreciated!
I saw this in my questions and that no one ever answered. Just for posterity I wanted to record what I did. I ended up using Regex.Replace. I used an enumeration to list the different format fields like this:
String pattern = String.Format("<{0}>", Template.Timestamp);
String result = Regex.Replace(pattern, data.Timestamp.ToString());
Where "Template" is an enumeration and "Timestamp" is the element I wanted to replace. It seemed to work for my needs.

C# program to read, write, query xml

I would like to create a C# program to write, read, query xml file. I am very new to xml using C#. Can anyone please help me..
specifically i want to do this:
<streets>
<street1>
<house1 no=1 color=red/>
</street1>
<street2>
<house2 no=2 color=blue/>
</street2>
</streets>
I want to read this xml file and print all the houses and their properties.
I want to append to this xml file any new houses
I want to query where any specific house is located.
Can anyone please help me in this?
You can use LINQ. Please have a look at this article: http://www.codeproject.com/Articles/24376/LINQ-to-XML. Hope this help!
If you are interested in creating an application to create some data on 'House' and want to have the capabilities of editing/updating, adding and removing such data, and also want to store it in XML, then it is simple. Here I am considering that you are not very interested to know the exact metadata of the XML and the XML need not be following some predefined schema.
For such a requirement I worked sometime back and you may look at this for the same:
http://www.geekays.net/post/2011/03/24/XML-Data-Storage-and-XmlSerializer-The-easy-data-store.aspx

Class Design related clarification c#

I have a design related question. So please guide me on how to do this?
Right now, I have a xml structure which will be in this format.
<Sheet id="abc"/>
<Elements>
<Element id="xyz">
<value>23</value>
</Element>
<Element id="sdz">
<value>46</value>
</Element>
...
</Elements>
</Sheet>
So, we have a class like this to store each & every element of the sheet.
Sheet
{
Public string SheetId
{
get; set;
}
//all Elements will be stored in the below collection
Public IList<IDictionary<string, string>> Elements
{
get; set;
}
}
But now for few sheets the format has been changed to the below structure.
<abc> //SheetId
<Elements>
<Record>
<Element1/>
<Element2/>
<Element3/>
<Element4/>
</Record>
<Record>
<Element1/>
<Element2/>
<Element3/>
<Element4/>
</Record>
...
</abc>
So, we need to create a Generic class to hold the above xml formats and we don't want to have different object to store these.
I mean in future if we have some other xml format also we need to accommodate the same without any change in the Sheet class.
So, can you please advise me on how to design the Sheet Class.?
Ok. let me explain how my app works.
Actually we have around 200 sheets(in other words measures).
1) User will upload the sheet data in xml format (all sheets in xml file) & edit the same if they want Or Enter the data in the screen (dynamic screen generated using the xml template) if they dont want to upload.
2) Then the data will be stored in the Sheet object and it will go through lot of Validation process and finally the data will be converted to xml again and stored in the db.
You can ask why you want to store this as XML? The reason is we dont want to create 200 aspx pages for this same kind of data and thats why we are generating the sheet pages dynamically using the xml templates. Also, we will be adding, updating or deleting sheets frequently.
Ok. I think now you will have some idea about this issue.
To be more clear, all the elements in my XML file will be displayed as a field in the aspx page. It maybe a Textbox, dropdown & etc....
I would recommend designing your class based on what the information actually represents and how your software plans to utilize the data, not the XML format being used.
You should always be able to do the transposition from the data format into the structure which best represents how your program will use this data.

Categories

Resources