Using the SmartObject OData v3 API in C#

The following C# code shows how to get data from a SmartObject using the OData API. The sample uses Basic authentication but you can also use OAuth by setting up the header similarly to the code described in the Workflow REST API topics.

Copy

Get data from a SmartObject using the OData API

//get the raw data from the OData Feed
//set the environment URLs and the SmartObject to query
//TODO: replace these values with appropriate values for your environment and target SmartObject
string BaseK2SmOUri = @"https://k2.denallix.com/api/odata/v3/";
string SmartObjectSystemName = @"Sales_Product_SampleDatabase";

//set credentials for basic auth
//TODO: replace these values with appropriate values for your env
string username = @"Denallix\Administrator";
string password = "K2pass!";

//example: using a WebClient to read the response
var webclient = new WebClient
{
    Credentials = new NetworkCredential(username, password)
};
var webClientResponse = webclient.DownloadString(BaseK2SmOUri + SmartObjectSystemName);
//output reponse as a string for simplicity
//TODO: you will probably want to do some JSON deserialization here
Console.WriteLine("** WEBCLIENT START **");
Console.WriteLine(webClientResponse.ToString());
Console.WriteLine("** WEBCLIENT END **");

//example: using a HTTPWebRequest to read the response
Console.WriteLine("** HTTPWEBREQUEST START **");
System.Net.HttpWebRequest request = WebRequest.Create(BaseK2SmOUri + SmartObjectSystemName) as HttpWebRequest;
//set the credentials
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
//get the response
System.Net.WebResponse response = request.GetResponse();
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader responseReader = new System.IO.StreamReader(responseStream);
//read the response to output as a string for simplicity
//TODO: you will probably want to do some JSON deserialization here
string responsestring = responseReader.ReadToEnd();
Console.WriteLine(responsestring);
Console.WriteLine("** HTTPWEBREQUEST END **");
responseReader.Close();
responseStream.Dispose();
responseStream.Dispose();