Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Parameters as Xml to a Stored Procedure

Tags:

c#

tsql

xml

soa

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?

like image 284
Rob Stevenson-Leggett Avatar asked Apr 14 '09 15:04

Rob Stevenson-Leggett


1 Answers

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:

[Serializable, XmlRoot("args")]
public class SomeArgs {
    [XmlElement("foo")] public string Foo { get; set; } 
    [XmlAttribute("bar")] public int Bar { get; set; }
}
...
SomeArgs args = new SomeArgs { Foo = "abc", Bar = 123 };
XmlSerializer ser = new XmlSerializer(typeof(SomeArgs));
StringWriter sw = new StringWriter();
ser.Serialize(sw, args);
string xml = sw.ToString();

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...

like image 61
Marc Gravell Avatar answered Oct 29 '22 12:10

Marc Gravell