Control XML Serialization from DataSet -- Attributes on "TableName element" - xml-serialization

Hope I chose the correct forum.
I have a dataset object with one table that comes to me from a common custom component's GetDS method. I need to pass XML to another process (chunked as byte array). I have it all working but the XML is missing some attributes that the consuming process expects.
I create a dataset object and can control the name of the TableName (root element) and the row like this:
da.Fill(ds, "Foo")
ds.DataSetName = "FooUpload"
I use the GetXML method to serialize to XML that looks like the following:
<?xml version="1.0" standalone="yes" ?>
<FooUpload>
<Foo>
<FooMasterID>483</FooMasterID>
<Country>27</Country>
<PaymentCode>ANN</PaymentCode>
<Amount>132</Amount>
<PaidDate>2012-12-31 00:00:00</PaidDate>
<PaidBy>FooServices</PaidBy>
</Foo>
</FooUpload>
The calling process expects
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<FooUpload **ClientCode="FOOO" RecordCount="1" CreateDate="2008-12-09T15:02:18.920" CreateUser="valli"**>
<Foo>
<FooMasterID>483</FooMasterID>
<Country>27</Country>
<PaymentCode>ANN</PaymentCode>
<Amount>132</Amount>
<PaidDate>2012-12-31 00:00:00</PaidDate>
<PaidBy>FooServices</PaidBy>
</Foo>
</FooUpload>
Note the attributes on the FooUpload element. This node is the name of the DataTable in the DataSet.
I have searched for how to control the XMLSerializer and find lots of examples for custom objects. I even found examples of setting the column mapping to be MappingType.Attribute which is close but I need to do this with the root element which is actually the TableName for the dataset.
I feel that I am close and if I do not find a more elegant solution I will have to create a hack like looping and spitting out changed string plus rest of the XML.

You can feed the output of GetXML into a XmlDocument and add the attributes afterwards. For example:
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(ds.GetXml());
XmlAttribute attr=xdoc.CreateAttribute("ClientCode");
attr.Value = "FOOOO";
xdoc.DocumentElement.Attributes.Append(attr);
Then you can save the xdoc into a file, or put it into a string, for example:
XmlTextWriter xw = new XmlTextWriter(new MemoryStream(),Encoding.UTF8);
xdoc.Save(xw);
xw.BaseStream.Position = 0;
StreamReader sr = new StreamReader(xw.BaseStream);
string result = sr.ReadToEnd();

This looks pretty much as what you are looking for.

Related

How to suppress root element in BeanIO XML generation?

When generating a XML file with BeanIO, the StreamBuilder name is used as root element. How to suppress this root element?
Example:
StreamBuilder builder = new StreamBuilder("builder_name")
.format("xml")
.parser(new XmlParserBuilder()).addRecord(Test.class);
The Test class:
#Record
public class Test {
#Field(at=0)
private String field1 = "ABC";
// Getters and Setters ...
}
The generated XML file:
<builder_name>
<Test>
<field1>ABC</field1>
</Test>
</builder_name>
I don't want builder_name to be showed as root element. I want Test element to be the root. How can I achieve that?
You need to set the xmlType property/attribute to XmlType.NONE on your stream configuration.
The answer is in Appendix A - XML Mapping file reference of the documentation.
xmlType - The XML node type mapped to the stream. If not specified or set to element, the stream is mapped to the root element of the XML document being marshalled or unmarshalled. If set to none, the XML input stream will be fully read and mapped to a child group or record.
The trick is now to translate that piece of information into the StreamBuilder API, which is:
xmlType(XmlType.NONE)
Your example then becomes:
StreamBuilder builder = new StreamBuilder("builder_name")
.format("xml")
.xmlType(XmlType.NONE)
.parser(new XmlParserBuilder())
.addRecord(Test.class);
Which produces this unformatted/unindented output:
<?xml version="1.0" encoding="utf-8"?><test><field1>ABC</field1></test>
To have the xml formatted (pretty print)/indented use:
StreamBuilder builder = new StreamBuilder("builder_name")
.format("xml")
.xmlType(XmlType.NONE)
.parser(new XmlParserBuilder()
.indent()
)
.addRecord(Test.class);
Note the change to the XmlParserBuilder, to produce this output:
<?xml version="1.0" encoding="utf-8"?>
<test>
<field1>ABC</field1>
</test>

itextsharp: unable to cast from FilteredRenderListener to ITextExtractionStrategy

I want to extract text from a specified pdf area with itextsharp. I know there is an example http://sourceforge.net/p/itextsharp/code/HEAD/tree/book/iTextExamplesWeb/iTextExamplesWeb/iTextInAction2Ed/Chapter15/ExtractPageContentArea.cs#l35. The core code is like this:
RenderFilter[] filter = {new RegionTextRenderFilter(rect)};
ITextExtractionStrategy strategy = new FilteredRenderListener(new LocationTextExtractionStrategy(), filter);
string text = PdfTextExtractor.GetTextFromPage(reader, i, strategy);
However, vs2012 shows me that "cannot convert implicitly from FilteredRenderListener to ITextExtractionStrategy ". I tried to do explicit conversion. But failed. Could anyone help me? Do I use a wrong itextsharp version? Thanks so much!
Your line looks like this:
ITextExtractionStrategy strategy = new FilteredRenderListener(new LocationTextExtractionStrategy(), filter);
but the corresponding lines from the sample you reference look like this:
ITextExtractionStrategy strategy;
...
strategy = new FilteredTextRenderListener(
new LocationTextExtractionStrategy(), filter
);
I.e. the sample uses a FilteredTextRenderListener while you only use a FilteredRenderListener. The former actually extends the latter to also implement ITextExtractionStrategy.
Thus, simply use FilteredTextRenderListener instead of FilteredRenderListener.

Xtext and EMF modeling - Opposite relations parsing

I'm currently playing around with XText and EMF and I've come to a dead end.
I have an ecore model that I created using the diagram editor. I don't provide the XML representation; it should be clear from the example. Some of the relations are opposite to each other (like the parent-children relation).
This binding works perfectly fine when I create the instances programatically. Below, I show a test case that is successfully passed.
However, when I parse the model using XText, these opposite relations are not set. I can't find a way to fix this. The relations are strictly one-directional as they appear in the input file. Is there any way to force Xtext to set these? or am I supposed to resolve these manually?
Passing test
WordsFactory factory = WordsFactory.eINSTANCE;
// Prepare a simple dictionary hierarchy
Dictionary d = factory.createDictionary();
Synset s = factory.createAdjectiveSynset();
s.setDescription("A brief statement");
s.setExample("He didn't say a word.");
WordSense ws = factory.createAdjectiveWordSense();
Word w = factory.createWord();
w.setName("word");
ws.setWord(w);
s.getWordSenses().add(ws);
d.getWords().add(w);
d.getSynsets().add(s);
// Now check the bidirectional links
Assert.assertTrue(ws.getSynset() == s);
Assert.assertTrue(w.getSenses().get(0) == ws);
XMI representation of this example
<?xml version="1.0" encoding="ASCII"?>
<words:Dictionary xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:words="http://www.example.com/dstahr">
<words senses="//#synsets.0/#wordSenses.0" name="word"/>
<synsets xsi:type="words:AdjectiveSynset" description="A brief statement" example="He didn't say a word.">
<wordSenses xsi:type="words:AdjectiveWordSense" word="//#words.0"/>
</synsets>
</words:Dictionary>
Grammar definition (some unimportant rules removed)
grammar ocs_assignment.dsl.DSL with org.eclipse.xtext.common.Terminals
import "platform:/resource/ocs_assignment.model/model/words.ecore"
import "http://www.eclipse.org/emf/2002/Ecore" as ecore
Dictionary returns Dictionary:
{Dictionary}
'dict' name=EString
('add words' '[' words+=Word* ( "," words+=Word)* ']')?
synsets+=Synset*
;
Synset returns Synset:
AdjectiveSynset | NounSynset | VerbSynset;
WordSense returns WordSense:
AdjectiveWordSense | NounWordSense | VerbWordSense;
Word returns Word:
name=EString;
EString returns ecore::EString:
STRING | ID;
NounWordSense returns NounWordSense:
word=[Word|EString];
NounSynset returns NounSynset:
{NounSynset}
'(N)' name=EString
'{'
'content' '[' (wordSenses+=NounWordSense ( "," wordSenses+=NounWordSense)*)? ']'
'description' description=EString
'example' example=EString
('hyponym' hyponym=[Synset|EString])?
('hypernym' hypernym=[Synset|EString])?
('similarTo' '(' similarTo+=[Synset|EString] ( "," similarTo+=[Synset|EString])* ')' )?
'}';
Parsed file
dict dict
add words test1 test2 test3
(N) test1
{
content [ test1 test2 ]
description "test1"
example "test1"
}
(N) test2
{
content [ test3 ]
description "test2"
example "test2"
hypernym test1
}
XMI representation of the parsed file (missing references for Words)
<?xml version="1.0" encoding="ASCII"?>
<words:Dictionary xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:words="http://www.example.com/dstahr">
<words name="test1"/>
<words name="test2"/>
<words name="test3"/>
<synsets xsi:type="words:NounSynset" description="test1" example="test1" name="test1">
<wordSenses xsi:type="words:NounWordSense">
<word href="importedFile1.wdsl#xtextLink_::0.1.0.2.0::1::/0"/>
</wordSenses>
</synsets>
<synsets xsi:type="words:NounSynset" description="test2" example="test2" name="test2">
<hypernym xsi:type="words:AdjectiveSynset" href="importedFile1.wdsl#xtextLink_::0.1.1::1::/21"/>
<wordSenses xsi:type="words:NounWordSense">
<word href="importedFile1.wdsl#xtextLink_::0.1.1.2.0::1::/0"/>
</wordSenses>
</synsets>
</words:Dictionary>
Xtext does not support inverse relations built-in. If you generate the metamodel from your grammar, you would see that the inverse is not set for the corresponding relations. However, if your Ecore model has the inverse relation property is set, Xtext will maintain that.
There are two ways to use such a metamodel:
Create your own Ecore model and reference it.
You could define an IXtext2EcorePostProcessor instance that can update your generated metamodel before it is serialized. For details, see the corresponding blog post of Christian Dietrich.
The first solution is quite easy, but you would lose the auto-generated EMF models. In the second case, you have to write code that updates the Ecore (meta)model before it is serialized that can be really tricky to achieve. We have done the second approach for EMF-IncQuery (for another kind of customization), as at that point the autogeneration was really important, however the customizer became really hard to understand since.

Linq to XML returns no items when there are items in the XML

I am trying to query some XML data using Linq because it's easier than using XPath and as a good "proof of concept" for my co-workers as to how we can use Linq. Here is my XML:
<Booking>
<ServiceCollection>
<Service>
<BookingID>10508507</BookingID>
<AdditionalChargeID>1</AdditionalChargeID>
<ServiceName>Fuel Surcharge</ServiceName>
<ServiceCost>56.87</ServiceCost>
<ServiceCharge>103.41</ServiceCharge>
<showInNotes>0</showInNotes>
<showInHeader>0</showInHeader>
<BOLHeaderText />
</Service>
<Service>
<BookingID>10508507</BookingID>
<AdditionalChargeID>2</AdditionalChargeID>
<ServiceName>Lift Gate at Pickup Point</ServiceName>
<ServiceCost>25.00</ServiceCost>
<ServiceCharge>42.00</ServiceCharge>
<showInNotes>1</showInNotes>
<showInHeader>1</showInHeader>
<BOLHeaderText>Lift Gate at Pickup Point</BOLHeaderText>
</Service>
</ServiceCollection>
</Booking>
Now, here is my C# code (ignore the Conversions class; they simply make sure a default value is returned if the item is null):
var accessorials = from accessorial in accessorialsXml.Elements("ServiceCollection").Elements("Service")
select new Accessorial
{
BookingID = Conversions.GetInt(accessorial.Element("BookingID").Value),
Name = accessorial.Element("ServiceName").Value,
Cost = Conversions.GetDecimal(accessorial.Element("ServiceCost").Value),
Charge = Conversions.GetDecimal(accessorial.Element("ServiceCharge").Value),
ShowInNotes = Conversions.GetBool(accessorial.Element("showInNotes").Value),
ShowInHeader = Conversions.GetBool(accessorial.Element("showInheader").Value),
BillOfLadingText = accessorial.Element("BOLHeaderText").Value
};
return accessorials.ToList();
I have a Unit test which is failing because the count of accessorials (the "Service" node in the XML) is 0 when it should be 2. I tested out this same code in LinqPad (returning an anonymous class instead of an actual entity) and it is returning the proper number of values, yet the code here returns no objects.
Any ideas?
The bug may lie in how you're getting accessorialsXml in the first place. Try outputting the contents of this object before doing the query, to make sure it's exactly the same as the string you're using in LINQPad.

ADO.NET Mapping From SQLDataReader to Domain Object?

I have a very simple mapping function called "BuildEntity" that does the usual boring "left/right" coding required to dump my reader data into my domain object. (shown below) My question is this - If I don't bring back every column in this mapping as is, I get the "System.IndexOutOfRangeException" exception and wanted to know if ado.net had anything to correct this so I don't need to bring back every column with each call into SQL ...
What I'm really looking for is something like "IsValidColumn" so I can keep this 1 mapping function throughout my DataAccess class with all the left/right mappings defined - and have it work even when a sproc doesn't return every column listed ...
Using reader As SqlDataReader = cmd.ExecuteReader()
Dim product As Product
While reader.Read()
product = New Product()
product.ID = Convert.ToInt32(reader("ProductID"))
product.SupplierID = Convert.ToInt32(reader("SupplierID"))
product.CategoryID = Convert.ToInt32(reader("CategoryID"))
product.ProductName = Convert.ToString(reader("ProductName"))
product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit"))
product.UnitPrice = Convert.ToDouble(reader("UnitPrice"))
product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock"))
product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder"))
product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel"))
productList.Add(product)
End While
Also check out this extension method I wrote for use on data commands:
public static void Fill<T>(this IDbCommand cmd,
IList<T> list, Func<IDataReader, T> rowConverter)
{
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
list.Add(rowConverter(rdr));
}
}
}
You can use it like this:
cmd.Fill(products, r => r.GetProduct());
Where "products" is the IList<Product> you want to populate, and "GetProduct" contains the logic to create a Product instance from a data reader. It won't help with this specific problem of not having all the fields present, but if you're doing a lot of old-fashioned ADO.NET like this it can be quite handy.
Although connection.GetSchema("Tables") does return meta data about the tables in your database, it won't return everything in your sproc if you define any custom columns.
For example, if you throw in some random ad-hoc column like *SELECT ProductName,'Testing' As ProductTestName FROM dbo.Products" you won't see 'ProductTestName' as a column because it's not in the Schema of the Products table. To solve this, and ask for every column available in the returned data, leverage a method on the SqlDataReader object "GetSchemaTable()"
If I add this to the existing code sample you listed in your original question, you will notice just after the reader is declared I add a data table to capture the meta data from the reader itself. Next I loop through this meta data and add each column to another table that I use in the left-right code to check if each column exists.
Updated Source Code
Using reader As SqlDataReader = cmd.ExecuteReader()
Dim table As DataTable = reader.GetSchemaTable()
Dim colNames As New DataTable()
For Each row As DataRow In table.Rows
colNames.Columns.Add(row.ItemArray(0))
Next
Dim product As Product While reader.Read()
product = New Product()
If Not colNames.Columns("ProductID") Is Nothing Then
product.ID = Convert.ToInt32(reader("ProductID"))
End If
product.SupplierID = Convert.ToInt32(reader("SupplierID"))
product.CategoryID = Convert.ToInt32(reader("CategoryID"))
product.ProductName = Convert.ToString(reader("ProductName"))
product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit"))
product.UnitPrice = Convert.ToDouble(reader("UnitPrice"))
product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock"))
product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder"))
product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel"))
productList.Add(product)
End While
This is a hack to be honest, as you should return every column to hydrate your object correctly. But I thought to include this reader method as it would actually grab all the columns, even if they are not defined in your table schema.
This approach to mapping your relational data into your domain model might cause some issues when you get into a lazy loading scenario.
Why not just have each sproc return complete column set, using null, -1, or acceptable values where you don't have the data. Avoids having to catch IndexOutOfRangeException or re-writing everything in LinqToSql.
Use the GetSchemaTable() method to retrieve the metadata of the DataReader. The DataTable that is returned can be used to check if a specific column is present or not.
Why don't you use LinqToSql - everything you need is done automatically. For the sake of being general you can use any other ORM tool for .NET
If you don't want to use an ORM you can also use reflection for things like this (though in this case because ProductID is not named the same on both sides, you couldn't do it in the simplistic fashion demonstrated here):
List Provider in C#
I would call reader.GetOrdinal for each field name before starting the while loop. Unfortunately GetOrdinal throws an IndexOutOfRangeException if the field doesn't exist, so it won't be very performant.
You could probably store the results in a Dictionary<string, int> and use its ContainsKey method to determine if the field was supplied.
I ended up writing my own, but this mapper is pretty good (and simple): https://code.google.com/p/dapper-dot-net/