This thread has been locked.

TI-API: .net add-on working with order api

Part Number: TI-API


Hello,

I am programming new feature for erp system i'm working with. It is c# based. Can somebody show me examples of getting token or post calls classes?

I have few problem with json handling...

  • Hello! We actually have a library of C# wrapper classes and example code in development, which will be made widely available in early January. :)

    In that system, we developed a utility class which handles HTTP requests by deserializing the JSON response into a given class (using the open source Json.NET library). This means that for each possible JSON output, we have defined a class or hierarchy of classes in order to represent the structure. The function itself is written using a generic class 'T' so it can be used for any such class. Below is the generic function for POST requests, where the _client field refers to a private object of type HttpClient. There is also logic to pass a token if desired, since the class has logic to automatically retrieve it.

    public async Task<T> Post<T>(string uri, HttpContent payload, bool authorize=true)
            {
                // Clear HTTP client headers.
                _client.DefaultRequestHeaders.Clear();

                // If authorization enabled, pass token in headers.
                if(authorize)
                {
                    await _VerifyAccessToken();
                    _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + AccessToken);
                }
                // Store response string.
                string responseString = "";
                string statusCode = "???";

                // Try-catch block to attempt HTTP request.
                try
                {
                    // Attempt HTTP post request.
                    var response = await _client.PostAsync
                    (
                        requestUri: uri,
                        content: payload
                    );

                    // Retrieve response as string.
                    responseString = await response.Content.ReadAsStringAsync();
                    statusCode = response.StatusCode.ToString();

                    // Ensure that status code is successful (200-299).
                    response.EnsureSuccessStatusCode();
                }
           
                catch(Exception e)
                {
                    Console.WriteLine("ERROR: Post request at URI {0} failed (code {1}). Error message and server response below:", uri, statusCode);
                    Console.WriteLine(e.Message);
                    Console.WriteLine(responseString);
                }

                // Try to convert JSON to C# object.
                try
                {
                    // Deserialize response as indicated type.
                    var responseJson = JsonConvert.DeserializeObject<T>(responseString);

                    // Return object.
                    return responseJson;
                }

                catch(Exception e)
                {
                    Console.WriteLine("ERROR: Failed to deserialize JSON object. Error message and server response below:");
                    Console.WriteLine(e.Message);
                    Console.WriteLine(responseString);
                }

                return default(T);
            }

    To acquire a token to begin with, the same utility class calls that POST function with the values necessary to retrieve the token from TI's server. Notice that authorization is set to false because not only do we not currently have a token, but our goal here is precisely to acquire that token. The function assumes public string fields ClientID and ClientSecret, corresponding tto the user's API credentials, and Server corresponding to the base URL of the TI server (for you, it will be "">https://transact.ti.com").

    public async Task<string> RefreshToken()
            {
                // Define payload to acquire access token.
                var payload = new Dictionary<string, string>
                {
                    {"grant_type", "client_credentials"},
                    {"client_id", ClientID},
                    {"client_secret", ClientSecret}
                };

                // Set token string initially to "Failed to acquire."
                AccessToken = "Failed to acquire.";

                // Try to make post request.
                try
                {
                    // Indicate that we are attempting to acquire a token.
                    Console.WriteLine("Attempting to acquire access token to server {0} with client ID {1}.", Server, ClientID);

                    // Make request. Set authorization to false since we do not have a token yet.
                    var uri = "v1/oauth";
                    var response = await Post<Dictionary<string, string>>(
                        uri: uri,
                        payload: new FormUrlEncodedContent(payload),
                        authorize: false
                    );

                    // Retrieve token from server response.
                    AccessToken = response["access_token"];

                    // Get expiration time by combining expires_in and issued_at.
                    // The latter is in milliseconds rather than seconds, so divide by 1000.
                    float issuedAt = float.Parse(response["issued_at"]) / 1000;
                    float expiresIn = float.Parse(response["expires_in"]);
                    ExpirationTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                    ExpirationTime = ExpirationTime.AddSeconds(issuedAt + expiresIn);

                    //Indicate that token has been created.
                    Console.WriteLine("Token {0} has been created; expires at {1:MM/dd/yy H:mm:ss zzz}.", AccessToken, ExpirationTime);
                }
                catch(Exception e)
                {
                    Console.WriteLine("ERROR: Failed to acquire access token or determine expiration time.");
                    Console.WriteLine(e);
                }

                return AccessToken;
            }

    In the example above, rather than defining and referring to a class definition for the server response, we request the function to deserialize the output as a dictionary of string values to string values. This will be okay for simple JSON structures, but is not viable for nested structures or structures with more complex contents. Something you can do to quickly develop such classes is to first make the API call on an API client like Insomnia or Postman, copy the JSON server response as a string, and use a JSON-to-C# converter which analyzes the JSON structure and generates a C# class structure based on it.

    I hope this is a helpful starting point! Again, the complete tool will be made available in January so that you can make use of not only this utility class but also specific wrapper classes for each of the TI store APIs. :)

**Attention** This is a public forum