Last active
January 5, 2021 21:49
-
-
Save derekantrican/1ac9702c7b13317226ec0c3212906a6a to your computer and use it in GitHub Desktop.
A modified version of the FreshDesk C# API sample for creating a ticket with an attachment: https://github.com/freshdesk/fresh-samples/blob/master/C-Sharp/CreateTicketWithAttachment.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*---------------------------------------------------------------------------------------------------------- | |
* THIS CLASS DEPENDS ON THE FOLLOWING: | |
* System.Web.Extensions reference | |
* MimeTypeMap.List nuget package (https://www.nuget.org/packages/MimeTypeMap.List/) | |
* | |
* | |
* ALSO: do not forget to fill in your FreshDesk domain and FreshDesk API (lines 23 & 24) | |
* ---------------------------------------------------------------------------------------------------------- | |
*/ | |
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Net; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Web.Script.Serialization; | |
namespace Freshdesk | |
{ | |
public class FreshDesk | |
{ | |
private const string fdDomain = "YOUR_DOMAIN"; | |
private const string _APIKey = "YOUR_API_KEY"; | |
private const string path = "/api/v2/tickets"; | |
private const string _Url = "https://" + fdDomain + ".freshdesk.com" + path; | |
public static string SubmitTicket(string name, string email, string subject, string description, List<string> attachments = null) | |
{ | |
Dictionary<string, string> payload = new Dictionary<string, string> | |
{ | |
{ "name", name }, | |
{ "email", email }, | |
{ "subject", subject }, | |
{ "description", description }, | |
{ "status", "2" }, | |
{ "priority", "2" }, | |
}; | |
string timestamp = $"{DateTime.Now.Ticks:x}"; | |
string boundary = $"----------------------------{timestamp}"; | |
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_Url); | |
request.Headers.Clear(); | |
request.ContentType = $"multipart/form-data; boundary={boundary}"; | |
request.Method = "POST"; | |
request.KeepAlive = true; | |
string login = $"{_APIKey}:X"; // It could be your username:password also. | |
string credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(login)); | |
request.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}"; | |
using (Stream requestStream = request.GetRequestStream()) | |
{ | |
foreach (string key in payload.Keys) | |
{ | |
byte[] data = Encoding.UTF8.GetBytes($"--{boundary}\r\nContent-Disposition: form-data; name=\"{key}\"\r\n\r\n{payload[key]}\r\n"); | |
requestStream.Write(data, 0, data.Length); | |
} | |
if (attachments != null) | |
{ | |
foreach (string filePath in attachments) | |
{ | |
FileInfo file = new FileInfo(filePath); | |
string contentType = MimeTypeMap.List.MimeTypeMap.GetMimeType(file.Extension).First(); | |
byte[] attachment = Encoding.UTF8.GetBytes($"--{boundary}\r\nContent-Disposition: form-data; name=\"attachments[]\"; filename=\"{file.Name}\"\r\n" + | |
$"Content-Type: {contentType}\r\n\r\n"); | |
using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) | |
{ | |
byte[] fileData = new byte[fileStream.Length]; | |
fileData.Concat(new byte[fileStream.Length]); | |
fileStream.Read(fileData, 0, fileData.Length); | |
attachment = attachment.Concat(fileData).Concat(Encoding.UTF8.GetBytes("\r\n")).ToArray(); | |
} | |
requestStream.Write(attachment, 0, attachment.Length); | |
} | |
} | |
byte[] finalBoundaryBytes = Encoding.UTF8.GetBytes($"--{boundary}--"); | |
requestStream.Write(finalBoundaryBytes, 0, finalBoundaryBytes.Length); | |
} | |
try | |
{ | |
Console.WriteLine("Submitting Request"); | |
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) | |
{ | |
using (Stream dataStream = response.GetResponseStream()) | |
{ | |
using (StreamReader reader = new StreamReader(dataStream, Encoding.UTF8)) | |
{ | |
string responseBody = reader.ReadToEnd(); | |
JavaScriptSerializer serializer = new JavaScriptSerializer(); | |
Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(responseBody); | |
//return status code | |
Console.WriteLine($"Status Code: {(int)response.StatusCode} {response.StatusCode}"); | |
//return location header | |
Console.WriteLine($"Location: {response.Headers["Location"]}"); | |
//return the response | |
Console.Out.WriteLine(responseBody); | |
System.Diagnostics.Debug.WriteLine($"X-Request-Id: {response.Headers["X-Request-Id"]}"); | |
System.Diagnostics.Debug.WriteLine($"Timestamp: {DateTime.UtcNow}"); | |
return $"https://{fdDomain}.freshdesk.com/a/tickets/{json["id"]}"; //Return the ticket URL | |
} | |
} | |
} | |
} | |
catch (WebException ex) | |
{ | |
Console.WriteLine($"Failed to submit FreshDesk ticket ({((HttpWebResponse)ex.Response).StatusCode} {(int)((HttpWebResponse)ex.Response).StatusCode}): {ex.Message} {ex.StackTrace}"); | |
Console.WriteLine($"X-Request-Id: {ex.Response.Headers["X-Request-Id"]} ; Timestamp: {timestamp}"); | |
using (Stream responseStream = ex.Response.GetResponseStream()) | |
{ | |
using (StreamReader reader = new StreamReader(responseStream)) | |
{ | |
Logger.LogError(reader.ReadToEnd()); | |
} | |
} | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine("ERROR"); | |
Console.WriteLine(ex.Message); | |
} | |
return null; //Return a null URL in case of error | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment