/// <summary> /// Add a binary attachment to existing record /// Can be file/image/mail/... depending on what ServiceNow allows /// </summary> /// <typeparam name="T"></typeparam> /// <param name="recordId">Record sys_id</param> /// <param name="filename">Name of the attachment</param> /// <param name="file">The attachment in binary format</param> /// <returns></returns> public async Task <RestResponseSingle <Attachment> > PostAttachment <T>(string recordId, string filename, byte[] file) where T : Record { if (string.IsNullOrWhiteSpace(recordId)) { throw new ArgumentNullException(nameof(recordId)); } if (!RecordNumber.IsValidId(recordId)) { throw new ArgumentException("Invalid record ID.", nameof(recordId)); } if (string.IsNullOrWhiteSpace(filename)) { throw new ArgumentNullException(nameof(filename)); } if (file == null || file.Length == 0) { throw new ArgumentNullException(nameof(file)); } // Convert to safe values var nvs = new NameValueCollection { { "table_name", RecordTable.GetTableName <T>() }, { "table_sys_id", recordId }, { "file_name", HttpUtility.UrlEncode(filename) } }; // Build url with keys var urlBuilder = new StringBuilder(); urlBuilder.Append("attachment/file?"); for (var i = 0; i < nvs.Keys.Count; i++) { if (i > 0) { urlBuilder.Append("&"); } var key = nvs.Keys[i]; urlBuilder.AppendFormat("{0}={1}", key, nvs[key]); } var url = urlBuilder.ToString(); // Post var response = await _Client.PostAsFileAsync(url, filename, file); if (response.IsSuccessStatusCode) { return(await response.Content.ReadAsJsonAsync <RestResponseSingle <Attachment> >()); } else { return new RestResponseSingle <Attachment>() { ErrorMsg = $"POST attachment error ({response.StatusCode}): {response.ReasonPhrase}" } }; } #endregion }
/// <summary> /// Get ServiceNow record of type T (which must inherit from Record) by id /// </summary> /// <typeparam name="T">Record type (example: SupportRequest)</typeparam> /// <param name="id">ServiceNow sys_id</param> /// <returns></returns> public Task <RestResponseSingle <T> > GetById <T>(string id) where T : Record { if (string.IsNullOrWhiteSpace(id)) { throw new ArgumentNullException(nameof(id)); } if (!RecordNumber.IsValidId(id)) { throw new ArgumentException("Invalid record ID.", nameof(id)); } return(Get <RestResponseSingle <T> >($"{GetUrl<T>()}/{id}?sysparm_limit=1&sysparm_fields={RecordTable.GetFieldList<T>()}")); }