Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added option for download attchment #313

Merged
merged 5 commits into from
Nov 27, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion appveyor.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ image: Previous Visual Studio 2017
pull_requests:
do_not_increment_build_number: true
configuration: Release
platform: Any CPU
nuget:
disable_publish_on_pr: true
# scripts that are called at very beginning, before repo cloning
Expand Down
14 changes: 7 additions & 7 deletions src/ZendeskApi_v2.Example/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,18 @@ static void Main(string[] args)
static async Task MainAsync(string email)
{

string userEmailToSearchFor = "[email protected]";
var userEmailToSearchFor = "[email protected]";

string userName = "[email protected]"; // the user that will be logging in the API aka the call center staff
string userPassword = "&H3n!0q^3OjDLdm";
string companySubDomain = "csharpapi"; // sub-domain for the account with Zendesk
int pageSize = 5;
var userName = "[email protected]"; // the user that will be logging in the API aka the call center staff
var userPassword = "&H3n!0q^3OjDLdm";
var companySubDomain = "csharpapi"; // sub-domain for the account with Zendesk
var pageSize = 5;
var api = new ZendeskApi(companySubDomain, userName, userPassword);

var userResponse = api.Search.SearchFor<User>(userEmailToSearchFor);

long userId = userResponse.Results[0].Id.Value;
List<Ticket> tickets = new List<Ticket>();
var userId = userResponse.Results[0].Id.Value;
var tickets = new List<Ticket>();

var ticketResponse = await api.Tickets.GetTicketsByUserIDAsync(userId, pageSize, sideLoadOptions: Requests.TicketSideLoadOptionsEnum.Users); // default per page is 100

Expand Down
58 changes: 30 additions & 28 deletions src/ZendeskApi_v2/Core.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,9 @@ public RequestResult RunRequest(string resource, string requestMethod, object bo
{
try
{
string requestUrl = ZendeskUrl + resource;
var requestUrl = ZendeskUrl + resource;

HttpWebRequest req = WebRequest.Create(requestUrl) as HttpWebRequest;
var req = WebRequest.Create(requestUrl) as HttpWebRequest;

if (this.Proxy != null)
{
Expand Down Expand Up @@ -170,7 +170,7 @@ public RequestResult RunRequest(string resource, string requestMethod, object bo

var res = req.GetResponse();
var response = res as HttpWebResponse;
string responseFromServer = string.Empty;
var responseFromServer = string.Empty;
using (var responseStream = response.GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
Expand All @@ -183,18 +183,18 @@ public RequestResult RunRequest(string resource, string requestMethod, object bo
}
catch (WebException ex)
{
WebException wException = GetWebException(resource, body, ex);
var wException = GetWebException(resource, body, ex);
throw wException;
}
}

private byte[] GetFromData(HttpWebRequest req, Dictionary<string, object> formParameters)
{
string boundaryString = "FEF3F395A90B452BB8BFDC878DDBD152";
var boundaryString = "FEF3F395A90B452BB8BFDC878DDBD152";
req.ContentType = "multipart/form-data; boundary=" + boundaryString;
MemoryStream postDataStream = new MemoryStream();
StreamWriter postDataWriter = new StreamWriter(postDataStream);
bool addNewline = false;
var postDataStream = new MemoryStream();
var postDataWriter = new StreamWriter(postDataStream);
var addNewline = false;
foreach (var param in formParameters)
{
if (addNewline)
Expand Down Expand Up @@ -355,7 +355,7 @@ protected string GetAuthBearerHeader(string oAuthToken)

protected string GetAuthHeader(string userName, string password)
{
string auth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{userName}:{password}"));
var auth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{userName}:{password}"));
return $"Basic {auth}";
}

Expand All @@ -366,15 +366,16 @@ public async Task<T> GetByPageUrlAsync<T>(string pageUrl, int perPage = 100)
{
return JsonConvert.DeserializeObject<T>("");
}
var test = Regex.Split(pageUrl, "api/v2/");

var resource = Regex.Split(pageUrl, "api/v2/").Last() + "&per_page=" + perPage;
var resource = Regex.Split(pageUrl, "api/v2/").Last() + (perPage != 0 ? $"&per_page={perPage}" : "");
return await RunRequestAsync<T>(resource, RequestMethod.Get);
}

public async Task<T> RunRequestAsync<T>(string resource, string requestMethod, object body = null, int? timeout = null, Dictionary<string, object> formParameters = null)
{
var response = await RunRequestAsync(resource, requestMethod, body, timeout, formParameters);
var obj = Task.Factory.StartNew(() => JsonConvert.DeserializeObject<T>(response.Content));
var obj = Task.Factory.StartNew(() => JsonConvert.DeserializeObject<T>(response.Content, jsonSettings));
return await obj;
}

Expand All @@ -383,7 +384,7 @@ public async Task<RequestResult> RunRequestAsync(string resource, string request
var requestUrl = ZendeskUrl + resource;
try
{
HttpWebRequest req = WebRequest.Create(requestUrl) as HttpWebRequest;
var req = WebRequest.Create(requestUrl) as HttpWebRequest;
req.ContentType = "application/json";

req.Headers["Authorization"] = GetPasswordOrTokenAuthHeader();
Expand All @@ -403,7 +404,7 @@ public async Task<RequestResult> RunRequestAsync(string resource, string request
}
else if (body != null)
{
string json = JsonConvert.SerializeObject(body, jsonSettings);
var json = JsonConvert.SerializeObject(body, jsonSettings);
data = Encoding.UTF8.GetBytes(json);
}

Expand All @@ -415,12 +416,13 @@ public async Task<RequestResult> RunRequestAsync(string resource, string request
}
}

using (HttpWebResponse response = (HttpWebResponse)await req.GetResponseAsync())
using (var response = (HttpWebResponse)await req.GetResponseAsync())
{
string content = string.Empty;
using (Stream responseStream = response.GetResponseStream())
var content = string.Empty;
using (var responseStream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(responseStream))

using (var sr = new StreamReader(responseStream))
{
content = await sr.ReadToEndAsync();
}
Expand All @@ -430,18 +432,18 @@ public async Task<RequestResult> RunRequestAsync(string resource, string request
}
catch (WebException ex)
{
WebException wException = GetWebException(resource, body, ex);
var wException = GetWebException(resource, body, ex);
throw wException;
}
}

private byte[] GetFromDataAsync(HttpWebRequest req, Dictionary<string, object> formParameters)
{
string boundaryString = "FEF3F395A90B452BB8BFDC878DDBD152";
var boundaryString = "FEF3F395A90B452BB8BFDC878DDBD152";
req.ContentType = "multipart/form-data; boundary=" + boundaryString;
MemoryStream postDataStream = new MemoryStream();
StreamWriter postDataWriter = new StreamWriter(postDataStream);
bool addNewline = false;
var postDataStream = new MemoryStream();
var postDataWriter = new StreamWriter(postDataStream);
var addNewline = false;
foreach (var param in formParameters)
{
if (addNewline)
Expand Down Expand Up @@ -578,12 +580,12 @@ protected async Task<bool> GenericBoolPutAsync(string resource, object body = nu

private WebException GetWebException(string resource, object body, WebException originalWebException)
{
string error = string.Empty;
WebException innerException = originalWebException.InnerException as WebException;
var error = string.Empty;
var innerException = originalWebException.InnerException as WebException;

if (originalWebException.Response != null || (innerException != null && innerException.Response != null))
{
using (Stream stream = (originalWebException.Response ?? innerException.Response).GetResponseStream())
using (var stream = (originalWebException.Response ?? innerException.Response).GetResponseStream())
{
if (stream != null && stream.CanRead)
{
Expand All @@ -601,12 +603,12 @@ private WebException GetWebException(string resource, object body, WebException
Debug.WriteLine(originalWebException.Message);
Debug.WriteLine(error);

string headersMessage = $"Error content: {error} \r\n Resource String: {resource} + \r\n";
string bodyMessage = string.Empty;
var headersMessage = $"Error content: {error} \r\n Resource String: {resource} + \r\n";
var bodyMessage = string.Empty;

if (body != null)
{
ZenFile zenFile = body as ZenFile;
var zenFile = body as ZenFile;
if (zenFile == null)
{
bodyMessage = $" Body: {JsonConvert.SerializeObject(body, Formatting.Indented, jsonSettings)}";
Expand Down
2 changes: 1 addition & 1 deletion src/ZendeskApi_v2/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ internal static bool IsNullOrWhiteSpace(this string value)
return true;
}

for (int i = 0; i < value.Length; i++)
for (var i = 0; i < value.Length; i++)
{
if (!char.IsWhiteSpace(value[i]))
{
Expand Down
4 changes: 2 additions & 2 deletions src/ZendeskApi_v2/Models/GroupResponseBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ private long GetPageFromParameter()
return TotalPages;
}

Dictionary<string, string> dict = NextPage.GetQueryStringDict();
var dict = NextPage.GetQueryStringDict();
if (dict.ContainsKey("page"))
{
return int.Parse(dict["page"]) - 1;
Expand All @@ -76,7 +76,7 @@ private int GetPageSizeFromParameter()
return 100;
}

Dictionary<string, string> dict = page.GetQueryStringDict();
var dict = page.GetQueryStringDict();
if (dict.ContainsKey("per_page"))
{
return int.Parse(dict["per_page"]);
Expand Down
2 changes: 2 additions & 0 deletions src/ZendeskApi_v2/Models/Shared/Attachment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ public class Attachment
[JsonProperty("content_type")]
public string ContentType { get; set; }

public string MappedContentUrl { get; set; }

[JsonProperty("size")]
public long Size { get; set; }

Expand Down
33 changes: 30 additions & 3 deletions src/ZendeskApi_v2/Requests/Attachments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
#if ASYNC
using System.Threading.Tasks;
Expand All @@ -20,6 +21,7 @@ public interface IAttachments : ICore
GroupAttachmentResponse GetAttachmentsFromArticle(long? articleId);
Upload UploadAttachment(ZenFile file, int? timeout = null);
Upload UploadAttachments(IEnumerable<ZenFile> files, int? timeout = null);
bool DeleteUpload(Upload upload);
#endif

#if ASYNC
Expand All @@ -33,6 +35,9 @@ public interface IAttachments : ICore
/// <returns></returns>
Task<Upload> UploadAttachmentAsync(ZenFile file, string token = "", int? timeout = null);
Task<Upload> UploadAttachmentsAsync(IEnumerable<ZenFile> files, int? timeout = null);
Task<bool> DeleteUploadAsync(Upload upload);
Task<ZenFile> DownloadAttachmentAsync(Attachment attachment);

#endif
}

Expand Down Expand Up @@ -94,6 +99,11 @@ Upload UploadAttachment(ZenFile file, string token, int? timeout = null)
var requestResult = RunRequest<UploadResult>(resource, RequestMethod.Post, file, timeout);
return requestResult.Upload;
}

public bool DeleteUpload(Upload upload)
{
return (upload?.Token == null ? false : GenericDelete($"/uploads/{upload.Token}.json"));
}
#endif

#if ASYNC
Expand Down Expand Up @@ -134,19 +144,36 @@ public async Task<Upload> UploadAttachmentsAsync(IEnumerable<ZenFile> files, int
/// <param name="timeout"></param>
/// <returns></returns>
public async Task<Upload> UploadAttachmentAsync(ZenFile file, string token = "", int? timeout = null)
{
string resource = $"uploads.json?filename={file.FileName}";
{
var resource = $"uploads.json?filename={file.FileName}";

if (!token.IsNullOrWhiteSpace())
{
resource += $"&token={token}";
}

UploadResult result = await RunRequestAsync<UploadResult>(resource, RequestMethod.Post, file, timeout);
var result = await RunRequestAsync<UploadResult>(resource, RequestMethod.Post, file, timeout);

return result.Upload;
}

public async Task<bool> DeleteUploadAsync(Upload upload)
{
return (upload?.Token == null ? false : await GenericDeleteAsync($"/uploads/{upload.Token}.json"));
}

public async Task<ZenFile> DownloadAttachmentAsync(Attachment attachment)
{
var file = new ZenFile { FileName = attachment.FileName, ContentType = attachment.ContentType };

using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", GetPasswordOrTokenAuthHeader());
file.FileData = await client.GetByteArrayAsync(attachment.ContentUrl);
}

return file;
}

#endif

Expand Down
4 changes: 2 additions & 2 deletions src/ZendeskApi_v2/Requests/Organizations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ public bool DeleteOrganizationMembership(long id, long userId)

public JobStatusResponse DestroyManyOrganizationMemberships(IEnumerable<long> ids)
{
string idList = string.Join(",", ids.Select(i => i.ToString()).ToArray());
var idList = string.Join(",", ids.Select(i => i.ToString()).ToArray());
return GenericDelete<JobStatusResponse>($"organization_memberships/destroy_many.json?ids={idList}");
}

Expand Down Expand Up @@ -298,7 +298,7 @@ public async Task<bool> DeleteOrganizationMembershipAsync(long id, long userId)

public async Task<JobStatusResponse> DestroyManyOrganizationMembershipsAsync(IEnumerable<long> ids)
{
string idList = string.Join(",", ids.Select(i => i.ToString()).ToArray());
var idList = string.Join(",", ids.Select(i => i.ToString()).ToArray());
return await GenericDeleteAsync<JobStatusResponse>($"organization_memberships/destroy_many.json?ids={idList}");
}

Expand Down
2 changes: 1 addition & 1 deletion src/ZendeskApi_v2/Requests/Search.cs
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ public async Task<SearchResults<T>> AnonymousSearchForAsync<T>(string searchTerm

public string AddTypeToSearchTerm<T>(string searchTerm = "")
{
string typeName = typeof(T).Name;
var typeName = typeof(T).Name;

return "type:" + typeName + (!(string.IsNullOrEmpty(searchTerm.Trim())) ? " " : "") + searchTerm.Trim();
}
Expand Down
Loading