Friday, May 17, 2013

WSDL service returning DataSet? Seriously?

Just got a 'last-minute' TODO - have to establish another interface for state agency. Like any good developer - I grab the WSDL and 'prop-up' a test service. Imagine my surprise when I see the defined method results as DataSet. Yup. Can be anything - based on nature of the "select" - egads. 

The ONLY reasonable  - and its by NO MEANS reasonable - "theory" that *might* explain this 'design' decision is that auto-generated proxies won't 'break'. (Yea. It's a lame excuse and kinda defeats the purpose of contract-first development) Besides, auto-generated proxies are for the faint-hearted (HTTP/XML for me).

How to generically 'mock' a dataset? Grab NBuilder from NuGet and add to your project. Then add a POCO representation of the fields you wish to return. Then call this:
private static DataSet CreateDataSet<T>(int numberOfRows = 1)
        {
            var datatable = new DataTable(typeof (T).Name);
            typeof (T).GetProperties().ToList().ForEach(
                x => datatable.Columns.Add(x.Name));
            Builder<T>.CreateListOfSize(numberOfRows).Build()
                                    .ToList().ForEach(
                                        x => datatable.LoadDataRow(x.GetType().GetProperties().Select(
                                            y => y.GetValue(x, null)).ToArray(), true));
            var dataset = new DataSet();
            dataset.Tables.Add(datatable);
            return dataset;
        }

soapUI tests against WSDL methods work - now 'back-to-work'!

No comments: