locked
Getting error while using POST method of Webclient RRS feed

  • Question

  • Hi

    I am developing a app for windows phone, using visual studio2012,

    Its a simple question, but i need a help,

    I really confused with the POST method of Webclient class,

    I need to post or upload a large string(app crash report) through a service call to my server.

    i tried various examples, nothing is clear, can anybody give me a clear view to post my string in my service call.

    here my code which i have tried finally

     public void sendCrashReport()
            {
                WebClient webClient = new WebClient();
                webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                var uri = new Uri("http://192.168.1.131:8090/wannado/mwebservice/crashreport", UriKind.Absolute);
                StringBuilder postData = new StringBuilder();
                postData.AppendFormat("{0}={1}", "email", HttpUtility.UrlEncode("your email id"));
                //postData.AppendFormat("&{0}={1}", "password", HttpUtility.UrlEncode("secret"));
                //postData.AppendFormat("&{0}={1}", "type", HttpUtility.UrlEncode("regular"));
                //postData.AppendFormat("&{0}={1}", "title", HttpUtility.UrlEncode("hello this is regular text from phone 7 app"));
    
                webClient.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
                webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
                webClient.UploadProgressChanged += webClient_UploadProgressChanged;
                webClient.UploadStringAsync(uri, "POST", postData.ToString());
            }
    
            void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
            {
                MessageBox.Show(e.Result);
            }
    
            void webClient_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
            {
                MessageBox.Show(e.ProgressPercentage.ToString());
            } 
    

    and its giving the error

    An exception of type 'System.Reflection.TargetInvocationException' occurred in System.ni.dll but was not handled in user code.

    what would be wrong in my code.

    Thank you.


    noorul


    Wednesday, April 3, 2013 6:55 AM

All replies

  • Your problem is that you are making an UI change in a thread different than the ui thread.

    In this case your method webClient_UploadStringCompleted is running on a worket thread instead of the ui thread.

    For this to work you should do the following:

           void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
            {
                Deployment.Current.Dispatcher.BeginInvoke(()=>MessageBox.Show(e.Result));
            }

    I recommend you to study a little about the runtime of windows phone

    Wednesday, April 3, 2013 9:04 AM