Hi,
So I am working on an application which tracks the user’s activity in order to accurately track time. This means the time is being tracked on the application and now I want to send the time tracked to the relevant issue in Jira.
So far I’ve been using a console application to try and achieve this goal as a test, but I’ve been running into some issues:
Getting this error:
{"errorMessages":["Worklog body is not valid.","Worklog must not be null."],"errors":{"worklog":"INVALID_INPUT"}}
This is my JiraTimeLogger.cs code:
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace JiraTimeLogger
{
public class JiraClient
{
private readonly HttpClient _httpClient;
public JiraClient(string jiraDomain, string username, string apiToken)
{
_httpClient = new HttpClient
{
BaseAddress = new Uri($"https://{jiraDomain}.atlassian.net/")
};
var authToken = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{apiToken}"));
_httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authToken);
}
public async Task LogWorkAsync(string issueIdOrKey, string timeSpent, string comment)
{
var url = $"rest/api/3/issue/{issueIdOrKey}/worklog";
var payload = new
{
timeSpentSeconds = 60,
comment = comment,
started = "2024-11-06T13:11:01.778-0500"
//started = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ssK")
};
var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Work logged successfully.");
}
else
{
Console.WriteLine($"Error: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
}
}
}
}
This is my code in Program.cs:
#region Main
using JiraTimeLogger;
var jiraDomain = "andytesting";
var username = "andries.benade@xxx.co.za";
var apiToken = "xxx";
#region Jira Logger
// Initialize the Jira client
var jiraClient = new JiraClient(jiraDomain, username, apiToken);
// Log work
var issueIdOrKey = "CCS-7";
var timeSpent = "1h";
var comment = "Eating old baked beans";
await jiraClient.LogWorkAsync(issueIdOrKey, timeSpent, comment);
#endregion
Console.WriteLine("End of Process.");
Console.ReadLine();
#endregion
On an additional note: As you can see in my JiraTimeLogger class, I have also hard coded the date since it would otherwise say my date is in the incorrect format, but looking at the way I specified the date format in the comment, it seems correct to me.