using System;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace WebApplication1
{
    [ServiceContract(Namespace = "")]
    [SilverlightFaultBehavior]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1
    {
        [OperationContract]
        public IEnumerable<Dictionary<string, object>> GetData(string query)
        {
            var table = GetDataTable(query);

            return table
                .AsEnumerable()
                .Select(r => table.Columns.OfType<DataColumn>()
                    .Select(c => new { Column = c.ColumnName, Value = r[c] })
                    .ToDictionary(i => i.Column, i => i.Value != DBNull.Value ? i.Value : null));
        }

        private DataTable GetDataTable(string query)
        {
            var connString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
            var conn = new SqlConnection(connString);
            var adapter = new SqlDataAdapter();
            adapter.SelectCommand = new SqlCommand(query, conn);

            var table = new DataTable();

            conn.Open();
            try
            {
                adapter.Fill(table);
            }
            finally
            {
                conn.Close();
            }

            return table;
        }
    }
}
