Microsoft Visual Studio Example

Microsoft Visual Studio offers many different modules and tools to build mobile front-end applications.  Any of these modules can incorporate REST API calls and use the API Server as an endpoint to store and retrieve data.  Live API Creator provides security, authentication, and business logic services (Declarative Reactive Programming) to handle server side validations, calculations, and event processing.  

Step-by-Step Guide

  1. Connect to Azure SQL Server (or any other SQL database).
  2. Test new REST API in the REST Lab and create new Resource endpoints (Documents with sub-documents).
  3. Use REST Generator to create POCO (classes):[http://jsonclassgenerator.codeplex.com/releases/view/102614]
There are many tools that can generate POCO from Swagger or JSON. This is an example of one tool that takes JSON output and creates all POCO classes:
Sample POCO (Plain Old CLR Object)
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Example.CustomerJsonTypes;
namespace Example
{
    internal class Customer
    {
        [JsonProperty("@metadata")]
        public Metadata Metadata { get; set; }
        [JsonProperty("Name")]
        public string Name { get; set; }
        [JsonProperty("Balance")]
        public int Balance { get; set; }
        [JsonProperty("CreditLimit")]
        public int CreditLimit { get; set; }
        [JsonProperty("Orders")]
        public Order[] Orders { get; set; }
    }
}

Use Native HTTPClient to make REST Calls

Use the @authentication to validate and return an apikey

          using (var client = new HttpClient())
            {
                var authInfo = new { username = user, password = pass };
                HttpContent content = new StringContent(JsonConvert.SerializeObject(authInfo), Encoding.UTF8, "application/json");
                try
                {
                    using (HttpResponseMessage response = client.PostAsync(BaseURLHelper.BaseURL +"/@authentication", content).Result)
                    {
                        response.EnsureSuccessStatusCode();
                        var responseBody = await response.Content.ReadAsStringAsync();
                        dynamic authoResponse = JObject.Parse(responseBody);
                        apiKey = authoResponse.apikey;
                    }
                }
                catch (HttpRequestException)
                {
                    Debug.WriteLine("Login attempt failed.");
                    apiKey = "";
                }
            }

Use the API key in each subsequent call to API Server

using (client = new HttpClient())
{ 
    HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, requestURL);
    requestMessage.Headers.Add("Authorization", string.Format("CALiveAPICreator {0}", ApiHelper.ApiKey + ":1"));

    var getResponse =  client.SendAsync(requestMessage).Result;

    getResponse.EnsureSuccessStatusCode();
    responseBody = await getResponse.Content.ReadAsStringAsync();
}

OR Use NuGet library for RESTSharp [https://github.com/restsharp/RestSharp]

 var client = new RestClient("http://localhost:8080/rest");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource

// add parameters for all properties on an object
request.AddObject(object);

// or just whitelisted properties
request.AddObject(object, "PersonId", "Name", ...);

// easily add HTTP Headers
request.AddHeader("header", "value");

// add files to upload (works with compatible verbs)
request.AddFile(path);

// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string

// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
IRestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;

// or download and save file to disk
client.DownloadData(request).SaveAs(path);

// easy async support
client.ExecuteAsync(request, response => {
    Console.WriteLine(response.Content);
});

// async with deserialization
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
    Console.WriteLine(response.Data.Name);
});

// abort the request on demand
asyncHandle.Abort();

Binding the REST call with the Object Model (POCO)

            String requestTemplate = Application.Current.Resources["GetCustomers"] as String;           
            String requesturl = String.Format(requestTemplate, BaseURLHelper.BaseURL );

            using (HttpClient client = new HttpClient())
            {                
                    try
                    {
                        string response = await HttpHelper.GetAsync(client, requesturl);
                        CustomerList newCustomers = JsonConvert.DeserializeObject<CustomerList>(response);
                        customerList.AddRange(newCustomers.Take<Customers>(20));
                        String nextBatch = (string)JArray.Parse(response).Last["@metadata"]["next_batch"];
                    }
                    catch (Exception)
                    {
                        Debug.WriteLine("Just a break point.");
                    }
             
            }

Important Notes on @Metadata: This contains the checksum value which is required for an PUT or DELETE (provides optimistic locking for the rules). The next_batch provides paging logic to retrieve subsequent batches of resources or sub-resources.
ċ
pocogen.PNG
(339k)
Val Huber,
Feb 16, 2016, 2:35 PM
Comments