Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST data to WCF Service from WP7

I am working on a WP7 application. If an error happens, I want to log the error back to my server. To handle this, I have created a WCF service operation. I want this operation to be REST ful so that I can later use it with iPhone and Android apps. Because I'm writing information to the database, I thought the POST method would be best. For this reason, I'm using WebInvoke. To do this, I'm using the following code:

[OperationContract]
[WebInvoke(UriTemplate = "/LogError/{message}/{stackTrace}", ResponseFormat = WebMessageFormat.Json)]
public void LogError(string message, string stackTrace)
{
  // Write info to the database
}

From my WP7 app, I want to call this operaiton via a WebClient. My question is, how do I do that? I don't understand how to call the LogError operation and pass along the required data via the WebClient.

Thank you for your help!

like image 695
user208662 Avatar asked Feb 01 '11 17:02

user208662


2 Answers

If I am getting your Service method correctly, that method is not a POST method. You can just call that with a WebClient

WebClient wc = new WebClient()
Uri uri = new Uri("http://yourUri/LogError/ABC/XYZ"); //ABC is your message and XYZ is your stacktrace string.
wc.DownloadStringAsync(uri);

Or if you are thinking about real HTTP 'POST' then below might help. You can use HttpWebRequest to do a POST on to any service which is accepting POST

This link may be helpful - WCF REST POST XML - The remote server returned an error: (400) Bad Request

like image 136
Jobi Joy Avatar answered Oct 12 '22 23:10

Jobi Joy


Something along the lines:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://serveraddress/LogError/{message}/{stackTrace}");

If you would want to send additional information later on, you can do so with:

request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(ExecuteAction), request);

And have a callback:

void ExecuteAction(IAsyncResult result)
{
    HttpWebRequest request = (HttpWebRequest)result.AsyncState;
    using (Stream s = request.EndGetRequestStream(result))
    {
        s.Write(data, 0, data.Length);
    }
}

If there is a specific string response from the service, you might as well include the data in the WebClient and use DownloadStringAsync to get the response data.

like image 38
Den Delimarsky Avatar answered Oct 12 '22 22:10

Den Delimarsky