Algorytm C# - Przykład 2: dodanie załącznika
Podsumowanie:Poniższy kod akcji C# pozwala na dodanie załącznika do dokumentu. Należy określić identyfikator dokumentu oraz identyfikator definicji dokumentu.
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using CSharpScript.WebServiceRunner.Models;
var baseUri = new System.Uri(TenantBaseUrl);
var _endpointUri = new System.Uri(baseUri, "publicapi/attachment/uploadAttachment");
var _authUri = new System.Uri(baseUri, "connect/token");
var _userName = "tutaj nazwa użytkownika, który ma dostęp do public-api";
var _userPassword = "tutaj hasło użytkownika";
var _scope = "public-api";
var _clientSecret = "secret";
var _clientId = "openjs";
var recordId = 0; //tutaj podajemy id instancji dokumentu biznesowego, id rekordu
var businessDocumentId = 0; //tutaj podajemy id definicji dokumentu biznesowego
var overwrite = false; //czy załącznik ma zostać nadpisany? należy ustawić na true jeżeli instancja dokumentu posiada już załącznik o podanej nazwie
var pathToFile = @"C:\temp\plik_tekstowy.txt"; //ścieżka do pliku załącznika
var attachmentFileName = System.IO.Path.GetFileName(pathToFile); //nazwa załącznika w dokumencie biznesowym, domyślnie jest taka sama jak nazwa pliku ale tutaj można ją nadpisać
var request = new RestRequestModel()
{
Method = HttpMethod.Post,
Url = $"{_endpointUri.AbsoluteUri}?recordId={recordId}&businessDocumentId={businessDocumentId}&overwrite={overwrite}",
AuthType = ApiConnector.Enums.AuthType.OAuth2Password,
AuthUrl = _authUri.AbsoluteUri,
UserName = _userName,
Password = _userPassword,
ClientId = _clientId,
ClientSecret = _clientSecret,
Scope = _scope,
};
var boundary = System.Guid.NewGuid().ToString();
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent(boundary))
{
client.DefaultRequestHeaders.Accept.Clear();
if (request.Headers?.Any() == true)
{
foreach (var item in request.Headers)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
client.Timeout = TimeSpan.FromMinutes(10);
formData.Headers.Remove("Content-Type");
formData.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
await PrepareAuth(client, request.AuthUrl, request.UserName, request.Password, request.ClientId, request.ClientSecret, request.Scope);
var fileContent = await ReadFile(pathToFile);
HttpContent bytesContent = new ByteArrayContent(fileContent);
formData.Add(bytesContent, "file", attachmentFileName);
var response = await client.PostAsync(request.Url, formData);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
NLog.LogManager.GetCurrentClassLogger().Trace(responseBody);
}
private async Task<byte[]> ReadFile(string pathToFile)
{
using (var stream = System.IO.File.Open(pathToFile, System.IO.FileMode.Open))
{
byte[] result = new byte[stream.Length];
await stream.ReadAsync(result, 0, (int)stream.Length);
return result;
}
}
private async Task PrepareAuth(HttpClient client, string authServer, string userName, string password, string clientId, string clientSecret, string scope)
{
var token = await GetBearerToken(authServer, userName, password, clientId, clientSecret, scope);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
}
private async Task<string> GetBearerToken(string authServer, string userName, string password, string clientId, string clientSecret, string scope)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.Timeout = TimeSpan.FromMinutes(10);
var contentValues = new System.Collections.Generic.Dictionary<string, string>();
contentValues.Add("grant_type", "password");
if (!string.IsNullOrWhiteSpace(clientId))
{
contentValues.Add("client_id", clientId);
}
if (!string.IsNullOrWhiteSpace(clientSecret))
{
contentValues.Add("client_secret", clientSecret);
}
if (!string.IsNullOrWhiteSpace(scope))
{
contentValues.Add("scope", scope);
}
if (!string.IsNullOrWhiteSpace(password))
{
contentValues.Add("password", password);
}
if (!string.IsNullOrWhiteSpace(userName))
{
contentValues.Add("username", userName);
}
var content = new FormUrlEncodedContent(contentValues);
var httpResponse = await client.PostAsync(authServer, content, default);
if (httpResponse == null)
{
throw new Shared.Exceptions.TranslatedException("Api.ActionModule.ConnectionFailed");
}
var response = await httpResponse.Content.ReadAsStringAsync();
dynamic objectResponse = Newtonsoft.Json.JsonConvert.DeserializeObject(response);
if (objectResponse == null || objectResponse.access_token == null)
{
throw new Exception(response);
}
return objectResponse.access_token;
}
|← Algorytm C# - Przykład 1: zmiana statusu dokumentów i wysyłka e-mail |↑ Do góry |→ Algorytm C# - Przykład 3: pobranie załącznika |