Hamid Fathi
Hamid Fathi

Reputation: 310

Xamarin WCF call

Im trying to call a WCF service in my xamarin android app but when it calls the method suddenly application exit whiteout any exception. I used this tutorial from Xamarin we site

and here is my MainAxtivity.cs file content:

using Android.App;
using Android.Widget;
using Android.OS;
using System.Net;
using System.ServiceModel;
using System;

namespace TaskTracking.Droid
{
    [Activity(Label = "TaskTracking.Droid", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        Button button1 = null;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            button1 = FindViewById<ButtonšŸ˜ Resource.Id.button1);
            button1.Click += Button1_Click;
        }

        private void Button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                EndpointAddress EndPoint = new EndpointAddress("http://10.10.2.162/TaskTracking.Service/TaskService.svc");
                BasicHttpBinding binding = new BasicHttpBinding
                {
                    Name = "basicHttpBinding",
                    MaxBufferSize = 2147483647,
                    MaxReceivedMessageSize = 2147483647
                };
                System.TimeSpan timeout = new System.TimeSpan(0, 0, 30);
                binding.SendTimeout = timeout;
                binding.OpenTimeout = timeout;
                binding.ReceiveTimeout = timeout;

                var client = new TaskServiceClient(binding, EndPoint);
                client.GetDataAsync(2);  /// Problem is here
                client.GetDataCompleted += Client_GetDataCompleted;
            }
            catch (Exception ex) // Never catch anything
            {
                var message = ex.ToString();
            }
        }

        private void Client_GetDataCompleted(object sender, GetDataCompletedEventArgs e)
        {
            var res = e.Result;
            Toast.MakeText(this, res, ToastLength.Long);
        }
    }
}

Upvotes: 1

Views: 137

Answers (1)

George Chondrompilas
George Chondrompilas

Reputation: 3237

Assuming you already set up your WCF correctly, try to subscribe to the client.GetDataCompleted event before the client.GetDataAsync(2); call.

var client = new TaskServiceClient(binding, EndPoint);
client.GetDataCompleted += Client_GetDataCompleted;
client.GetDataAsync(2);

Also, you are trying to make a Toast in a background thread instead of the UIThread. So change the Client_GetDataCompleted code as follows:

private void Client_GetDataCompleted(object sender, GetDataCompletedEventArgs e)
{
    var res = e.Result;
    RunOnUiThread(() => Toast.MakeText(Application.Context, res, ToastLength.Long).Show());
}

More about the UIThread here

Upvotes: 1

Related Questions