0

How to ensure UploadStringCompletedEventHandler event has been executed successfully ? in following code you can see i am calling function UploadMyPOST with my lastreads parameter having some data. Now you can see i am saving a variable named response into the MyClassXYZ varialbe. in the extreme last you can see there is a event which invoked by the method UploadMyPost() is filling the server response into the response variable. Now here issue is UploadMyPost(lastreads) executes successfully but its invoked event does not executes. Even cursor do not go on that event by which i am not able to fill server response into the response variable. So Anyone know any approach by which i can wait until that event successfully execute and i could able to save server response ?

private async void MyMethod(MyClassXYZ lastreads)
{
     await UploadMyPOST(lastreads);
     MyClassXYZ serverResponse = response;
     if (serverResponse.Book == null)
     {
           //Do Something.
     }
}

private void UploadMyPOST(MyClassXYZ lastreads)
{
    apiData = new MyClassXYZApi()
    {
       AccessToken = thisApp.currentUser.AccessToken,
       Book = lastreads.Book,
       Page = lastreads.Page,
       Device = lastreads.Device
    };
    //jsondata is my global variable of MyClassXYZ class.
    jsondata = Newtonsoft.Json.JsonConvert.SerializeObject(apiData);
    MyClassXYZ responsedData = new MyClassXYZ();
    Uri lastread_url = new Uri(string.Format("{0}lastread", url_rootPath));
    WebClient wc = new WebClient();
    wc.Headers["Content-Type"] = "application/json;charset=utf-8";
    wc.UploadStringCompleted += new UploadStringCompletedEventHandler(MyUploadStringCompleted);
    wc.UploadStringAsync(lastread_url, "POST", jsondata);
}

private void MyUploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
    try
    {
        if (e.Error == null)
        {
            string resutls = e.Result;
            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(MyClassXYZ));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resutls));
            response = (MyClassXYZ)json.ReadObject(ms);
        }
        else
        {
            string sx = e.Error.ToString();
        }
   }
   catch(Exception exe)
   {
   }
 }

//After Stephen suggession i used the HttpClient so i have written new code with the help of HttpClient. Code is building successfully but at run time cursor goes out from this method to the parent method where from its calling.

   private async Task<string> UploadMyPOST(MyClassXYZ lastreads)
   {
        string value = "";
        try
        {
            apiData = new LastReadAPI()
            {
                AccessToken = thisApp.currentUser.AccessToken,
                Book = lastreads.Book,
                Page = lastreads.Page,
                Device = lastreads.Device
            };
            jsondata = Newtonsoft.Json.JsonConvert.SerializeObject(apiData);
            LastRead responsedData = new LastRead();
            Uri lastread_url = new Uri(string.Format("{0}lastread", url_rootPath));
            HttpClient hc = new HttpClient();

            //After following line cursor go back to main Method.
            var res = await hc.PostAsync(lastread_url, new StringContent(jsondata));
            res.EnsureSuccessStatusCode();
            Stream content = await res.Content.ReadAsStreamAsync();
            return await Task.Run(() => Newtonsoft.Json.JsonConvert.SerializeObject(content));
            value = "kd";
        }
        catch
        { }
        return value;
   }
Ashish-BeJovial
  • 1,829
  • 3
  • 38
  • 62

2 Answers2

2

I recommend that you use HttpClient or wrap the UploadStringAsync/UploadStringCompleted pair into a Task-based method. Then you can use await like you want to in MyMethod.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • Hi @Stephen Clery, Now i am using the HttpClient inplace of WebClient. By using it code is building successfully but on a particular line cursor return to my parent method while i am using try catch block. I am posting code which now i am updating my code which i am using. – Ashish-BeJovial Feb 11 '14 at 06:20
  • yes now cursor is executing successfully. It was my mistake i was calling function without await keyword now this function executing. on res.EnsureSuccessStatusCode() i am getting exception 401. Please have a look where i am wrong ? – Ashish-BeJovial Feb 11 '14 at 06:47
  • HTTP 401 is "Unauthorized" – Stephen Cleary Feb 11 '14 at 12:59
  • I have updated code also. Is there any issue in my function ? – Ashish-BeJovial Feb 11 '14 at 13:02
  • 1
    The serialization of the stream inside the `Task.Run` doesn't make any sense to me, but the code isn't even getting there yet. You'll need to look at the docs for the API you're using, make sure your auth token is correct, etc. – Stephen Cleary Feb 11 '14 at 13:06
  • Stephen, i tried following after above failure but that also not working. HttpClient hc=new HttpClient(); hc.BaseAddress=new Uri(annotation_url.ToString()); HttpRequestMessage req=new HttpRequestMessage(HttpMethod.Post, annotation_url); req.Content=new StringContent(myJsonData, Encoding.UTF8, "application/json"); hc.SendAsync(req).ContinueWith(respTask => { var resp=respTask.Result; DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Annotation)); MemoryStream ms=new MemoryStream(Encoding.UTF8.GetBytes(resp.ToString())); AnnotateResponse=(Annotation)json.ReadObject(ms); }); – Ashish-BeJovial Feb 12 '14 at 13:12
0

Thank you Stephen Clear you leaded me in a right direction and i did POST my request successfully using HttpClient.

HttpClient hc = new HttpClient();
hc.BaseAddress = new Uri(annotation_url.ToString());
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, myUrl);
HttpContent myContent = req.Content = new StringContent(myJsonData, Encoding.UTF8, "application/json");
var response = await hc.PostAsync(myUrl, myContent);

//Following line for pull out the value of content key value which has the actual resposne.
string resutlContetnt = response.Content.ReadAsStringAsync().Result;
DataContractJsonSerializer deserializer_Json = new DataContractJsonSerializer(typeof(MyWrapperClass));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resutlContetnt.ToString()));
AnnotateResponse = deserializer_Json.ReadObject(ms) as Annotation;
Ashish-BeJovial
  • 1,829
  • 3
  • 38
  • 62