Example: C# .NET Device API

Sample code to consume the Device API using C#.

using MultipartDataMediaFormatter;
using MultipartDataMediaFormatter.Infrastructure;
using Newtonsoft.Json.Linq;using System;using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
string API_KEY = "YOUR API KEY";
string SECRET = "YOUR SECRET KEY";
private void Main()
{
    //GET ALL DEVICES
    GetDevice(null);
    //GET DEVICE BY ID            
    GetDevice(1);
    //PATCH/UPDATE DEVICE BY ID
    UpdateDevice("device", 1);
    //UPLOAD FILE to FILEGROUP (FILEGROUPID 11)
    Upload("filegroupfile", "C:\\web.png",11,"localcontent/web.png");
}
private void GetDevice(int? deviceID)        
{
    string apiHost = "https://www.kbremote.net"; //API HOST
    string apiPath = "api"; //PATH TO API
    string apiFunction = "device"; //API FUNCTION NAME
    string url = string.Join("/", apiHost, apiPath, apiFunction);
    if (deviceID != null)
        url = string.Join("/", url, deviceID.ToString());
        
    string timeStamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
    
    //CREATE REQUEST TO SERVER
    WebRequest request = WebRequest.Create(url);
    //SET REQUEST TYPE
    request.Method = "GET";
    
    //CREATE MESSAGE IN STANDARD FORMAT TO HASH
    string message = string.Join("/", request.Method + timeStamp, apiPath, apiFunction);
    if (deviceID != null)
        message = string.Join("/", message, deviceID.ToString());
        
    //HASH THE MESSAGE
    string messageHash = ComputeHash(SECRET, message);
    request.Headers.Add("Authentication", API_KEY + ":" + messageHash);
    request.Headers.Add("Timestamp", timeStamp);
    try
    {
        //EXECUTE REQUEST AND GET RESPONSE
        WebResponse response = request.GetResponse();
        //GET THE RESPONSE STREAM TO STRING
        Stream stream = response.GetResponseStream();
        StreamReader reader = new StreamReader(stream);
        String jsonString = reader.ReadToEnd();
        reader.Close();
        
        //PARSE RESPONSE STRING INTO JSON.NET ARRAY                
        if (deviceID == null)
        {
            JArray json = JArray.Parse(jsonString);
            Console.WriteLine(json.ToString());
        }
        else //USE JOBJECT IF ONLY EXPECTING SINGLE DEVICE  
        {
            JObject json = JObject.Parse(jsonString);
            Console.WriteLine(json.ToString());
        }
    }
    catch (WebException ex)
    {
        if (ex.Response != null) //HANDLE HTTP ERROR CODE
        {
            HttpWebResponse httpResponse = (HttpWebResponse)ex.Response;
            Console.WriteLine("Http status code: " + httpResponse.StatusCode);
        }
        else //HANDLE SOMETHING MORE SERIOUS SUCH AS NETWORK CONNECTION NOT AVAILABLE
        {
            Console.WriteLine(ex.Message);
        }
    }
}
public static void UpdateDevice(string api, int id)
{
    string apiHost = "https://www.kbremote.net"; //API HOST
    string apiPath = "api"; //PATH TO API
    string apiFunction = api; //API FUNCTION NAME
    string url = string.Join("/", apiHost, apiPath, apiFunction);
    url = string.Join("/", url, id);
    string timeStamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
    Console.WriteLine(timeStamp);
    //CREATE REQUEST TO SERVER
    WebRequest request = WebRequest.Create(url);
    //SET REQUEST TYPE
    request.Method = "PATCH";
    //CREATE MESSAGE IN STANDARD FORMAT TO HASH
    string message = string.Join("/", request.Method + timeStamp, apiPath, apiFunction);
    message = string.Join("/", message, id);
    //HASH THE MESSAGE
    string messageHash = ComputeHash(SECRET, message);
    request.Headers.Add("Authentication", API_KEY + ":" + messageHash);
    request.Headers.Add("Timestamp", timeStamp);
    // Set the content type of the data being posted.
    request.ContentType = "application/json";
    //CREATE PATCH/UPDATE OBJECT
    APIPatchDevice apiPatchDevice = new APIPatchDevice();
    apiPatchDevice.DeviceGroupID = null;
    apiPatchDevice.Name = "My Device Name";
    apiPatchDevice.UpdateOverrideUrl = false;
    apiPatchDevice.OverrideUrl = null;
    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        string json = JsonConvert.SerializeObject(apiPatchDevice);
        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();
        try
        {
            //EXECUTE REQUEST AND GET RESPONSE
            WebResponse response = request.GetResponse();
            //GET THE RESPONSE STREAM TO STRING
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            String jsonString = reader.ReadToEnd();
            reader.Close();
            //PARSE RESPONSE STRING INTO JSON.NET ARRAY
            JObject jObject = JObject.Parse(jsonString);
            Console.WriteLine(jObject);
        }
        catch (WebException ex)
        {
            if (ex.Response != null) //HANDLE HTTP ERROR CODE
            {
                HttpWebResponse httpResponse = (HttpWebResponse)ex.Response;
                Console.WriteLine("Http status code: " + httpResponse.StatusCode);
            }
            else //HANDLE SOMETHING MORE SERIOUS SUCH AS NETWORK CONNECTION NOT AVAILABLE
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
public static void Upload(string api, string localFilePath, int fileGroupID, string remotePath)
{
    string apiHost = "https://www.kbremote.net"; //API HOST
    string apiPath = "api"; //PATH TO API
    string apiFunction = api; //API FUNCTION NAME
    string url = string.Join("/", apiHost, apiPath, apiFunction);
    string timeStamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
    //CREATE MESSAGE IN STANDARD FORMAT TO HASH
    string message = string.Join("/", "POST" + timeStamp, apiPath, apiFunction);
    //HASH THE MESSAGE
    string messageHash = ComputeHash(SECRET, message);
    var filePath = localFilePath;
    HttpClient httpClient = new HttpClient();
    httpClient.DefaultRequestHeaders.Add("Authentication", API_KEY + ":" + messageHash);
    httpClient.DefaultRequestHeaders.Add("Timestamp", timeStamp);
    MultipartFormDataContent form = new MultipartFormDataContent();
    FileStream fs = File.OpenRead(filePath);
    var streamContent = new StreamContent(fs);
    var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
    imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png");
    form.Add(imageContent, "file", Path.GetFileName(filePath));
    form.Add(new StringContent(fileGroupID.ToString()), String.Format("\"{0}\"", "filegroupid"));
    form.Add(new StringContent(remotePath), String.Format("\"{0}\"", "path"));
    
    var mediaTypeFormatter = new FormMultipartEncodedMediaTypeFormatter(new MultipartFormatterSettings()
    {
        SerializeByteArrayAsHttpFile = true,
        CultureInfo = CultureInfo.CurrentCulture,
        ValidateNonNullableMissedProperty = true
    });
    using (HttpResponseMessage response = httpClient.PostAsync(url, form).Result)
    {
        if (response.StatusCode != HttpStatusCode.OK)
        {
            var err = response.Content.ReadAsStringAsync().Result;
        }
        var resultModel = response.Content.ReadAsAsync<APIFilePostResponse<String>>(new[] { mediaTypeFormatter }).Result;
        String json = JsonConvert.SerializeObject(resultModel);
        Console.WriteLine(json);
    }
}
public class APIFilePostResponse<T>
{
        public bool uploaded { get; set; }
        public string message { get; set; }
}
private static string ComputeHash(string secret, string message)
{
    var key = Encoding.UTF8.GetBytes(secret.ToUpper());
    string hashString;
    using (var hmac = new HMACSHA256(key))
    {
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
        hashString = Convert.ToBase64String(hash);
    }
    return hashString;
}

This article was helpful for 3 people. Is this article helpful for you?