Попытка получить задачу потока данных 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
}
}
< /code>
Скрипт Messagebox "Заполняется" появляется немедленно - а затем через 15-20 секунд появится Bessagebox для кода ответа. В противном случае все завершается правильно, включая регистрацию ошибок ответа. Это написано в Visual Studio 2022
Любая помощь очень ценится! < /P>
Подробнее здесь: https://stackoverflow.com/questions/797 ... ient-is-fi
C# обработать большие сценарии загрузки отчеты о успехе до завершения httpclient ⇐ C#
Место общения программистов C#
1757771112
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
}
}
< /code>
Скрипт Messagebox "Заполняется" появляется немедленно - а затем через 15-20 секунд появится Bessagebox для кода ответа. В противном случае все завершается правильно, включая регистрацию ошибок ответа. Это написано в Visual Studio 2022
Любая помощь очень ценится! < /P>
Подробнее здесь: [url]https://stackoverflow.com/questions/79763746/c-sharp-process-large-upload-script-task-reports-success-before-httpclient-is-fi[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия