I'm writing my first custom Activity for a UiPath RPA workflow in which I need to async send a filestream to the backend. This is what I've come up with but I just have this feeling that this doensn't quite work:
class SendFiles : AsyncCodeActivity<string>
{
private readonly HttpClient client = new HttpClient();
private readonly string url = "";
[Category("Input")]
[RequiredArgument]
public InArgument<List<string>> Files { get; set; }
[Category("Input")]
[RequiredArgument]
public string BearerToken { get; set; }
[Category("Output")]
public OutArgument JsonResult { get; set; }
protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
{
foreach (var filePath in Files.Get(context))
{
try
{
using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
HttpContent content = new StreamContent(fs);
client.PostAsync(url, content);
}
}
catch (IOException e)
{
Console.WriteLine(e.Message);
throw;
}
}
return null;
}
protected override string EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
{
throw new NotImplementedException();
}
}
After sending the whole batch, I want to wait for the result of te backend processing all these files. how can I accomplish this?
// make outer content
MultipartFormDataContent formdata = new MultipartFormDataContent();
...
// in foreach add every filestream to outer content
FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
HttpContent content = new StreamContent(fs);
string name = GetFileName(filePath);
content.Headers.Add("Content-Type", GetFileType(name));
formdata.Add(content, "files", name);
...
// after foreach, send whole outer content in one go
var resultPost = client.PostAsync(url, formdata).Result;
response = resultPost.Content.ReadAsStringAsync().Result;
succesfullRequest = resultPost.IsSuccessStatusCode;