开发者

Return a jagged array with dynamic number of dimensions from C# WCF Service

I'm currently trying create a service that will return results of a OLAP cube query in a C#/ WCF data service. I am doing this to gain complete programmatic control over how the OLAP results are serialized, how clients are authenticated/authorized and to be able to query cubes from javascript in a website directly.

The results from the OLAP queries may have any number of dimensions (realistically 开发者_如何学运维somewhere between 1 and 5 max). The problem I'm having is that I cannot figure out how to first create a jagged array of a dynamic number of dimensions without hard codding the handling of every number of dimensions I'll possibly use. So the first quest is: is there an elegant way to create a jagged array of a dynamic number of dimensions in C#?

Once I have this array of dynamic number of dimensions, is it possible to then serialize this into json using DataContractJsonSerializer (or any other json serializer freely available). The goal is to serialize this into an object that looks something like this for 2-dimensional results:

{
  "DimensionMemberCaptions" = [["Dim1 member1", "Dim2 member2"], ["Dim2 member1"], ["Dim2 member2"]],
  "Data" = [[1, 2],
            [3, 4]],
  "FormatedData = [["1$", "2$"],
                   ["3$", "4$"]]
}

Where DimensionMemberCaptions contain the headers for each dimension (OLAP member names) and data/formateddata is a table of the results.

I would like to avoid writing my own serialization functions but its seeming more appealing as time goes on -- using an Array (multi-dimensional array instead of jagged) and writing my own json serializer specifically for the purpose of serializing OLAP output to a Stream returned by a WCF REST method.


I found a way to solve my problem thats more specific to Adomd than my question specified, but I think the same technique could be applied to solve this without a dependency on Adomd. I choose to use Newtonsoft's Json serialization library (http://james.newtonking.com/projects/json-net.aspx). With this I could create my own 'JsonConverter' to serialize a Adomd CellSet (basically the results from a mulitdimensional OLAP query). This will work regardless of the number of dimensions.

public class CellSetConverter : JsonConverter
{

    public override bool CanRead
    {
        get
        {
            return false;
        }
    }

    public override bool CanConvert(Type objectType)
    {
        if (objectType == typeof(CellSet))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        CellSet cellSet = (CellSet)value;
        int cellCount = cellSet.Cells.Count;
        int[] axisCounts = new int[cellSet.Axes.Count];
        int[] currentIndex = new int[cellSet.Axes.Count];
        for (int i = 0; i < axisCounts.Length; i++)
        {
            axisCounts[i] = cellSet.Axes[i].Positions.Count;
        }

        for (int i = 0; i < cellSet.Axes.Count; i++)
        {
            writer.WriteStartArray();
        }

        for (int i = 0; i < cellCount; i++)
        {
            serializer.Serialize(writer, cellSet[currentIndex].Value);
            currentIndex = IncrementIndex(writer, currentIndex, axisCounts);
        }
    }

    string[] GetCaptions(CellSet cellSet, int[] index)
    {
        string[] captions = new string[index.Length];
        for (int i = 0; i < index.Length; i++)
        {
            Axis axis = cellSet.Axes[i];
            captions[i] = axis.Positions[index[i]].Members[0].Caption;
        }

        return captions;
    }

    int[] IncrementIndex(JsonWriter writer, int[] index, int[] maxSizes)
    {
        bool incremented = false;
        int currentAxis = 0;
        while (!incremented)
        {
            if (index[currentAxis] + 1 == maxSizes[currentAxis])
            {
                writer.WriteEndArray();
                index[currentAxis] = 0;
                currentAxis++;
            }
            else
            {
                for (int i = 0; i < currentAxis; i++)
                {
                    writer.WriteStartArray();
                }

                index[currentAxis]++;
                incremented = true;
            }

            if (currentAxis == index.Length)
            {
                return null;
            }
        }

        return index;
    }
}

And the WCF Rest service to go with it:

[ServiceContract]
public class MdxService
{
    const string JsonMimeType = "application/json";
    const string connectionString = "[Data Source String]";
    const string mdx = "[MDX query]";

    [OperationContract]
    [WebGet(UriTemplate = "OlapResults?session={session}&sequence={sequence}")]
    public Stream GetResults(string session, string sequence)
    {
        CellSet cellSet;
        using (AdomdConnection connection = new AdomdConnection(connectionString))
        {
            connection.Open();
            AdomdCommand command = connection.CreateCommand();
            command.CommandText = mdx;
            cellSet = command.ExecuteCellSet();
        }

        string result = JsonConvert.SerializeObject(cellSet, new CellSetConverter());
        WebOperationContext.Current.OutgoingResponse.ContentType = JsonMimeType;
        Encoding encoding = Encoding.UTF8;
        byte[] bytes = encoding.GetBytes(result);
        return new MemoryStream(bytes);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜