Search code examples
jsonsilverlightwcf-ria-services

Transfer JSON from Server to Client via WCF RIA Service


I am complete newbie to Silverlight and the WCF platform. I want to get some data from a server using a Silverlight client. The solution has a WCF RIA service class library for reading the data and serializing it into a JSON string, but I can't figure out how to create the request for the data, run the server method and return the JSON string for Deserialization at the client side.

I have spent hours searching and no reasonable solution. Till now I have done this:

[WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "data/{id}")]
public string getLogs(string server)
{
    EventLog[] remoteEventLogs = EventLog.GetEventLogs(System.Environment.MachineName);

    ObservableCollection<string> logs = new ObservableCollection<string>();

    for (int i = 0; i < remoteEventLogs.Length; i++)
    {
        logs.Add(remoteEventLogs[i].Log);
    }

     return serializer(logs); //helper function using DataContractJsonSerializer

}

But I can't wrap my head around what is going on. Any help please!


Solution

  • If you are using RIA Services, you just need to do this:

    [Invoke]
    public string getLogs(string server)
    {
        ...
        return serializer(logs);
    }
    

    And now you can call the getLogs from the Silverlight. But you can too use:

    [Invoke]
    public IEnumerable<string> getLogs(string server)
    {
        ...
        return logs;
    }
    

    this way, you return the list without having to serialize it to json.