0

I used to work with browser-based applications. for example Angular simple repository.

function getSomeData(params) {
        ...
        return $http({
            url: conf.urlDev + 'some/rest-url',
            method: "GET",
            params: params,
            cache: true
        }).then(getDataComplete);

        function getDataComplete(response) {

            return response.data;
        }
    }

How it will look the same in c# (XAMARIN for example)? i try :

 public class BaseClient 
{
    protected Http _client = null;
    protected string _urlObj;
    protected string _basePath;

    public BaseClient ()
    {
        _client = new Http(new HttpClientHandler());
    }

    public string Path
    {
        set
        {
            _urlObj = value;
        }
    }

    public async Task<Result<IList<T>>>getList<T>(Dictionary<string,object> parametrs = null)
    {
        if (parametrs != null)
        {
            foreach(KeyValuePair<string, object> keyValue in parametrs)
            {
                _urlObj = _urlObj.SetQueryParam(keyValue.Key, keyValue.Value);
            }
        }

        var response = await _client.GetAsync(_urlObj.ToString());

        if (response.IsSuccessStatusCode)
        {
            return new Result<IList<T>>()
            {
                Success = true,
                Value = JsonConvert.DeserializeObject<IList<T>>(await response.Content.ReadAsStringAsync())
            };
        }
        else
        {
            var error = new Result<IList<T>>()
            {
                Error = response.StatusCode.ToString(),
                Message = response.ReasonPhrase,
                Success = false
            };

            return error;
        }
    }

in my service:

public async Task<IList<News>> GetAllNewsByParams(DateTime from,
                            string orderBy = "-published",
                            DateTime to = new DateTime(),
                            int page = 1, int category = 0)
    {
        _client.Path = _config.NewsPath;

        var  dict = new Dictionary<string, object> {
            {"from", from.ToString("s")},
            {"order_by", orderBy.ToString()},
            {"to", to.ToString("s")},
            {"page", page.ToString()}
        };

        if (category != 0)
        {
            dict.Add("category", category.ToString());
        }

        var res = await _client.getList<News>(dict);

        return res.Value;
    }

and im ny viewmodel

foreach (var item in await _newsService.GetAllNewsByParams(
                                         _To,
                                         _OrderBy,
                                         _From, _Page,
            selectedTag == null ? _SeletedNewsTagId : selectedTag.Id))
        {
            NewsList.Add(item);
        }

Is his query executed synchronously ? How do I make it an asynchronous?

3
  • 1
    If by asynchronous you mean do not occupy a thread while waiting for a response, then yes, your operation is purely asynchronous. Commented May 25, 2016 at 13:22
  • that is, there should not be .then({})? Commented May 25, 2016 at 13:35
  • 1
    async/await are an abstraction over call-back based asynchronous operations : you may see your then call-back as simply everything under the await line. Commented May 25, 2016 at 13:37

1 Answer 1

1

First of all I would really encourage you to use RestSharp, it really simplifies making HTTP requests and deserialise them. Add a RestSharp nuget package to your project. Here is how your code will look like using RestSharp.

public class BaseClient
{
    protected IRestClient _client = null;
    protected string _urlObj;
    protected string _basePath;

    public BaseClient()
    {
        _client = new RestClient();
    }

    public async Task<Result<IList<T>>> GetList<T>(string path, Dictionary<string, object> parametrs = null)
    {
        var request = new RestRequest(path, Method.GET);
        if (parametrs != null)
        {
            foreach (var keyValue in parametrs)
            {
                request.AddQueryParameter(keyValue.Key, keyValue.Value);
            }
        }

        var response = await _client.Execute<List<T>>(request);

        if (response.IsSuccess)
        {
            return new Result<IList<T>>()
            {
                Success = true,
                Value = response.Data
            };
        }
        else
        {
            var error = new Result<IList<T>>()
            {
                Error = response.StatusCode.ToString(),
                Message = response.StatusDescription,
                Success = false
            };

            return error;
        }
    }
}

In your service

public async Task<IList<News>> GetAllNewsByParams(DateTime from,
                        string orderBy = "-published",
                        DateTime to = new DateTime(),
                        int page = 1, int category = 0)
    {

        var dict = new Dictionary<string, object> {
                        {"from", from.ToString("s")},
                        {"order_by", orderBy.ToString()},
                        {"to", to.ToString("s")},
                        {"page", page.ToString()}
                    };

        if (category != 0)
        {
            dict.Add("category", category.ToString());
        }

        var res = await _client.GetList<News>(_config.NewsPath, dict);

        return res.Value;
    }

And in your viewmodel

var news = await _newsService.GetAllNewsByParams(
                                     _To,
                                     _OrderBy,
                                     _From, _Page,
            selectedTag == null ? _SeletedNewsTagId : selectedTag.Id);
foreach (var item in news)
{
    NewsList.Add(item);
}

This will be 100% asynchronous.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.