Jaycee Evangelista
Jaycee Evangelista

Reputation: 1127

Xamarin.Forms Connecting to Web Services

Good Day Everyone. I'm creating a simple Xamarin.Forms Portable Application in my Visual Studio 2015.

I want my Mobile Application to connect to the SQL Database I have in my VS2015 and return a LIST OF CUSTOMERS which should be display to my mobile phone.

I have created a Xamarin Portable project and a WebForms project that will handle my Web Services and Database.

In my WebForms project, I created a Controller that should return the List of Customers. This has a web service URL api/Customer that I used to connect to the RestClient in my Xamarin Portable. I also have CustomerViewModel that should represent the data in my application.

In my Xamarin Portable project, I have a ClientList.xaml that should display the List that comes from my database. I also have a CustomerVM that is connected to Services and my RestClient. My RestClient used the WEB SERVICE URL to get the List of Customer from my WebForms project.

Based on the given steps above, I still wasn't able to display the Data in my mobile phone. What do you think is the reason behind this? Thanks for your help.

Here are some of my codes:

RestClient.cs

  public class RestClient_Customer<T>
{


    private const string WebServiceUrl = "http://localhost:50857/api/Customer/";

    public async Task<List<T>> GetCustomerAsync()
    {

        var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var json = await httpClient.GetStringAsync(WebServiceUrl);

        var taskModels = JsonConvert.DeserializeObject<List<T>>(json);

        return taskModels;
   }
 }

CustomerServices.cs

using Plugin.RestClient;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using XamarinFormsDemo.Models;

namespace XamarinFormsDemo.Services
{
    public class CustomerServices
    {

    public async Task<List<Customer>> GetCustomerAsync()
    {
        RestClient_Customer<Customer> restClient = new RestClient_Customer<Customer>();

        var customerList = await restClient.GetCustomerAsync(); //yung getasync ay pantawag as restclient

        return customerList;
        }
    }
}

CustomerVM.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using XamarinFormsDemo.Models;
using XamarinFormsDemo.Services;
using XamarinFormsDemo.Views;

namespace XamarinFormsDemo.ViewModels
{
    public class CustomerVM : INotifyPropertyChanged
    {


        private List<Customer> _customerList; // keep all customers
        private List<Customer> _searchedCustomerList; // keep a copy for searching
        private Customer _selectedCustomer = new Customer();

        private string _keyword = "";
        public string Keyword
        {
            get
            {
                return _keyword;
            }
            set
            {
                this._keyword = value;

                // while keyword changed we filter Employees
                //Filter();
            }
        }



        private void Filter()
        {
            if (string.IsNullOrWhiteSpace(_keyword))
            {
                CustomerList = _searchedCustomerList;

            }
            else
            {
                // var lowerKeyword = _keyword.ToLower();
                CustomerList = _searchedCustomerList.Where(r => r.CUSTOMER_NAME.ToLower().Contains(_keyword.ToLower())).ToList();
                //  EmployeesList = _searchedEmployeesList.Where(r => r.EMPLOYEE_NAME.Contains(_keyword)).ToList();


            }
        }


        public List<Customer> CustomerList
        {
            get
            {
                return _customerList;
            }
            set
            {
                _customerList = value;
                OnPropertyChanged();
            }
        }



        public CustomerVM()
        {
            InitializeDataAsync();

        }

        private async Task InitializeDataAsync()
        {
            var customerServices = new CustomerServices();
            _searchedCustomerList = await customerServices.GetCustomerAsync();
            CustomerList = await customerServices.GetCustomerAsync();

        }




        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}

Upvotes: 0

Views: 2007

Answers (2)

Ahmed Sayed
Ahmed Sayed

Reputation: 465

Try running it in UWP. If it works in UWP then you have to take a look at Xamarin HttpClient.GetStringAsync not working on Xamarin.Droid

I had the same issue but when I tried it in UWP it worked fine. I am still seeking for the solution to run xamarin.android using device.

Upvotes: 0

jake talledo
jake talledo

Reputation: 610

I think the problem is in your services hope this will help you,

      public interface ICustomer
      {
           Task<string> GetCustomers();
      }

      public class CustomerService : ICustomer
      {

        public async Task<string> GetCustomers()
        {
          var client = new HttpClient();
          var response = await client.GetAsync(string.Format("http://mysite/api/Customer"));
          var responseString = await response.Content.ReadAsStringAsync();
          return responseString; 
        }

       }

Call it anywhere you like

       var _custList = new GetCustomers();

       var returnJson = await _custList.GetCustomers(); 

Note the return is json string format or xml format depending on your REST API so you need to parse this first before you can get the value and display it to ListView

Upvotes: 1

Related Questions