I've got a requirement to pass parameters as Xml to my stored procedures.
I have a WCF service in the middle tier that makes calls to my data layer which in turn forwards the request to the appropriate stored procedure.
The design is that the WCF service is responsible for building the Xml to pass to the Repository.
I'm just wondering whether to keep control of what parameters are contained within the Xml in the middle tier or use a Dictionary built up by the client which I then convert to Xml in the middle tier?
At the moment I've gone for the latter - for example:
public TestQueryResponseMessage TestQuery(TestQueryRequestMessage message)
{
var result = Repository.ExecuteQuery("TestQuery", ParamsToXml(message.Body.Params));
return new TestQueryResponseMessage
{
Body = new TestQueryResponse
{
TopicItems = result;
}
}
}
private string ParamsToXml(Dictionary<string, string> nvc)
{
//TODO: Refactor
StringBuilder sb = new StringBuilder();
sb.Append("<params>");
foreach (KeyValuePair<string, string> param in nvc)
{
sb.Append("<param>");
sb.Append("<" + param.Key + ">");
sb.Append(param.Value);
sb.Append("</" + param.Key + ">");
sb.Append("</param>");
}
sb.Append("</params>");
return sb.ToString();
}
However I might need to do it the first way. E.g.
public TestQueryResponseMessage TestQuery(TestQueryRequestMessage message)
{
string xml = string.Format("<params><TestParameter>{0}</TestParameter></params>",message.Body.TestParameter)
var result = Repository.ExecuteQuery("TestQuery", xml);
return new TestQueryResponseMessage
{
Body = new TestQueryResponse
{
TopicItems = result;
}
}
}
What does the hivemind recommend?
If you must use xml; then rather than passing around a dictionary, I'd use a class that represents that data, and use
XmlSerializer
to fetch it as xml:This makes it much easier to manage which arguments apply to which queries, in an object-oriented way. It also means you don't have to do your own xml escaping...
Once you use Bob The Janitor's solution and you have your XML.
Create your stored procedure with a XML parameter. Then depending on how much XML you have and what your doing with it you can use Xquery or OpenXML to shred the XML document. Extract the data and perform the right action. This example is basic and pseudocode like but you should get the idea.
I would put the xml construction code inside the domain object. That way, you can just call obj.GetXML() from Web Service or data layer.
You could just use an object Serialization class like this
then you don't have to build the XML by hand, plus you can use this with any item to transform it using XSLT