Click here to Skip to main content
16,022,875 members
Articles / Web Development / ASP.NET
Tip/Trick

Getting Tickets Information from Zendesk API

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
5 Jun 2014CPOL 31.5K   505   3   14
Communicating with Zendesk API

Introduction

This tip shows how to connect to Zendesk and fetch tickets information through the API.

Using the Code

Since API responses are based on JSON format, you will need Newtonsoft and RestSharp libraries. Simply install from Nuget and refer to the following namespaces:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
using RestSharp;  

Declare the following variables:

C#
/// <summary>
/// Zend desk username
/// </summary>
private static string _Username = "<UserName>";

/// <summary>
/// Zendesk password
/// </summary>
private static string _Password = "<Password>";

/// <summary>
/// Zendesk URI
/// </summary>
private static string requestUri = "https://<YourcompnayName>.zendesk.com/";

On button click:

C#
protected void btnLoadtickets_Click(object sender, EventArgs e)
    {
        gvTaskList.DataSource = GetZenDeskJobList();
        gvTaskList.DataBind();
    }

GetZenDeskJobList() method communicates with Zendesk API. Here we are using while loop to fetch records since JSON response is not on continues format.

C#
public static List<ZenDeskJob> GetZenDeskJobList()
     {
         string username = _Username;
         string password = _Password;

         JObject userInfo;

         List<ZenDeskJob> zenDeskJobs = new List<ZenDeskJob>();
         var client = new RestClient(requestUri);
         client.AddDefaultHeader("Accept", "application/json");
         client.Authenticator = new HttpBasicAuthenticator(username, password);
         string currentResource = "/api/v2/tickets.json";

         Dictionary<string, string> currentUserList = new Dictionary<string, string>();

         currentUserList = CreateUserList();

         do
         {
             var request = new RestRequest(currentResource, Method.GET);

             IRestResponse response = client.Execute(request);
             var content = response.Content;

             userInfo = JObject.Parse(content);

             foreach (var user in userInfo)
             {
                 if (user.Key == "tickets")
                 {
                     foreach (var x in user.Value)
                     {
                         AddTicketInfoToList(x, zenDeskJobs, currentUserList);
                     }
                 }
                 if (user.Key == "next_page")
                 {
                     if (user.Value.ToString() != string.Empty)
                     {
                         currentResource = user.Value.ToString().Replace(requestUri, string.Empty);

                     }
                     else
                     {
                         currentResource = string.Empty;
                     }
                 }
             }
         }
         while (currentResource != string.Empty);

         return zenDeskJobs;

     }

AddTicketInfoToList() method reads the JSON response and query required output.

C#
/// <summary>
/// Add ticket information to list
/// </summary>
/// <param name="jtoken">Jtoken</param>
/// <param name="zenDeskJobs">List of zendesk jobs</param>
/// <param name="userList">List of users</param>
private static void AddTicketInfoToList(JToken jtoken, List<ZenDeskJob> zenDeskJobs, Dictionary<string, string> userList)
{
    ZenDeskJob singleTicket = new ZenDeskJob();

    JObject jObject = JObject.Parse(jtoken.ToString());

    var y = jtoken["custom_fields"];

    JObject joType = y.Children<JObject>().FirstOrDefault
    (o => o["id"] != null &&
    o["id"].ToString() == "20256231");
    JObject joSite = y.Children<JObject>().FirstOrDefault
    (o => o["id"] != null &&
    o["id"].ToString() == "20598381");
    JObject joTimeSpent = y.Children<JObject>().FirstOrDefault
    (o => o["id"] != null &&
    o["id"].ToString() == "20285557");

    var legend = joType.GetValue("value");
    var timeSpent = joTimeSpent.GetValue("value");

    if (legend != null && legend.ToString() == "charge_hourly_rate"
    && jtoken["status"] != null
    && jtoken["status"].ToString() == "solved")
    {
        singleTicket.ZenDeskId = jObject["id"] != null ?
        jObject["id"].ToString() : string.Empty;

        string currentUserID = jObject["assignee_id"].ToString();
        string assigneeName = string.Empty;

        userList.TryGetValue(currentUserID, out assigneeName);

        singleTicket.Assignee = assigneeName;

        singleTicket.TaskName = jObject["subject"] != null ?
        jObject["subject"].ToString() : string.Empty;

        singleTicket.TotalTimeSpent = timeSpent != null ? timeSpent.ToString() : string.Empty; ;

        singleTicket.URL = "https://yourcompany.zendesk.com/agent/#/tickets/" +
        (jObject["id"] != null ? jObject["id"].ToString() : string.Empty);

        zenDeskJobs.Add(singleTicket);
    }
}

Here, we need to mention user name which ticket is assigned.

C#
/// <summary>
/// Creating zendesk user list
/// </summary>
/// <returns>concurrent dictionary</returns>
private static Dictionary<string, string> CreateUserList()
{
    string username = _Username;
    string password = _Password;

    JObject userInfo;

    Dictionary<string, string> userList = new Dictionary<string, string>();
    var client = new RestClient(requestUri);
    client.AddDefaultHeader("Accept", "application/json");
    client.Authenticator = new HttpBasicAuthenticator(username, password);
    string currentResource = "/api/v2/users.json";

    do
    {
        var request = new RestRequest(currentResource, Method.GET);

        IRestResponse response = client.Execute(request);
        var content = response.Content;

        userInfo = JObject.Parse(content);

        foreach (var user in userInfo)
        {
            if (user.Key == "users")
            {
                foreach (var x in user.Value)
                {
                    userList.Add(x["id"].ToString(),
                    x["name"] != null ? x["name"].ToString() : string.Empty);
                }
            }
            if (user.Key == "next_page")
            {
                if (user.Value.ToString() != string.Empty)
                {
                    currentResource = user.Value.ToString().Replace(requestUri, string.Empty);

                }
                else
                {
                    currentResource = string.Empty;
                }
            }
        }
    }
    while (currentResource != string.Empty);

    return userList;

}

We need another simple class to hold basic zendesk records to bind the grid.

C#
/// <summary>
/// Zendesk job business entities
/// </summary>
public class ZenDeskJob
{
    /// <summary>
    /// Gets or sets ZenDeskId
    /// </summary>
    public string ZenDeskId
    {
        get;
        set;
    }

    /// <summary>
    /// Gets or sets task names
    /// </summary>
    public string TaskName
    {
        get;
        set;
    }

    /// <summary>
    /// Gets or sts total time spent
    /// </summary>
    public string TotalTimeSpent
    {
        get;
        set;
    }

    /// <summary>
    /// Gets or sets assignee
    /// </summary>
    public string Assignee
    {
        get;
        set;
    }

    /// <summary>
    /// Gets or sets ticket url
    /// </summary>
    public string URL
    {
        get;
        set;
    }
}

Once the Load Ticket button is pressed, conditioned zendesk tickets will be displayed on the grid. Output will look like below:

Image 1

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.