C# обработать большие сценарии загрузки отчеты о успехе до завершения httpclientC#

Место общения программистов C#
Ответить
Anonymous
 C# обработать большие сценарии загрузки отчеты о успехе до завершения httpclient

Сообщение Anonymous »

Попытка получить задачу потока данных SSIS для загрузки большого запроса (и захватить результирующий большой ответ) в облако. Код работает нормально, но отчеты задачи сценария завершены (и поток управления перемещается к следующему шагу) задолго до завершения загрузки и ответа. Я не уверен, что я ожидаю, что код сделает что -то, что не так, или у меня есть код неверным: < /p>

Код: Выделить всё

#region Namespaces
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
#endregion

namespace ST_fceb5e6b88ee4a39b755793d4261bec8
{

[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{

public async void Main()
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var handler = new HttpClientHandler();
handler.UseCookies = false;
string hostURL = @"https://myupload.com?id=12345";
string fileToLoad = Dts.Variables["User::SourceFileName"].Value.ToString();
string OutputFile = @"D:\BadStuffHappenedFolder\OutputErrors.txt";

try
{
//==================
using (var httpClient = new HttpClient(handler))
{
httpClient.BaseAddress = new Uri(hostURL);
System.Windows.Forms.MessageBox.Show("New Http Client");
using (var multipartFormContent = new MultipartFormDataContent())
{

//Load the file and set the file's Content-Type header
using (var fileStreamContent = new StreamContent(File.OpenRead(fileToLoad)))
{
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("text/csv");

//Add the file
multipartFormContent.Add(fileStreamContent, name: "file", fileName: Path.GetFileName(fileToLoad));
System.Windows.Forms.MessageBox.Show("Ready to send!");

//Send it
HttpResponseMessage response = await httpClient.PostAsync(hostURL, multipartFormContent);
System.Windows.Forms.MessageBox.Show(response.ToString());

response.EnsureSuccessStatusCode();
//string responseBody = await response.Content.ReadAsStringAsync();

using (Stream contentStream = await response.Content.ReadAsStreamAsync())
{
// Check if the file exists before attempting to delete it
if (File.Exists(OutputFile))
{
try
{
File.Delete(OutputFile);
System.Windows.Forms.MessageBox.Show($"File '{OutputFile}' deleted successfully.");
}
catch (IOException ex)
{
System.Windows.Forms.MessageBox.Show($"Error deleting file: {ex.Message}");
}
}
// Create or open the file for writing
using (FileStream fileStream = File.Create(OutputFile))
{
// Copy the content stream to the file stream
await contentStream.CopyToAsync(fileStream);
}
}

System.Windows.Forms.MessageBox.Show("script Complete");
}
}
}

//==================
//create the archive filename and rename the file just used
var now = DateTime.Now.ToString("yyyyMMdd_HHmm");
var archiveFile = fileToLoad.Replace(".csv", "") + "_"  + now + ".csv";

if (File.Exists(archiveFile))
{
File.Delete(archiveFile);
}

File.Move(fileToLoad, archiveFile);

//now delete the original file
if (File.Exists(archiveFile))
{
File.Delete(fileToLoad);
}
}
catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}

Dts.TaskResult = (int)ScriptResults.Success;
}

#region ScriptResults declaration

enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};

#endregion
}
}
Скрипт messagebox "заполняется" сразу же появляется - а затем через 15-20 секунд спустя messagebox для кода ответа появляется. В противном случае все завершается правильно, включая регистрацию ошибок ответа. Это написано в Visual Studio 2022
Любая помощь очень ценится! < /P>

Подробнее здесь: https://stackoverflow.com/questions/797 ... ient-is-fi
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»