From fe7f11038381f596f3024e8727096c703eeda480 Mon Sep 17 00:00:00 2001 From: agent-aspose-html-examples Date: Fri, 2 Oct 2026 23:26:24 +0500 Subject: [PATCH] =?UTF-8?q?feat(save-file-from-url):=20Add=2028=20and=20re?= =?UTF-8?q?move=2026=20renamed=20Aspose.HTML=20.NET=20C#=20examples=20for?= =?UTF-8?q?=20Save=20File=20From=20Url=20=E2=80=94=20Aspose.HTML=20for=20.?= =?UTF-8?q?NET=2026.9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...e-name-avoid-overwriting-existing-files.cs | 40 +++++++ ...e_name_avoid_overwriting_existing_files.cs | 36 ------ ...-sendasync-await-response-before-saving.cs | 42 +++++++ ...als-requestmessage-protected-resources.cs} | 40 +++---- ...out-for-requestmessage-to-avoid-hanging.cs | 28 +++++ ...out_for_requestmessage_to_avoid_hanging.cs | 35 ------ ...es-downloaded-file-to-current-directory.cs | 46 ++++++++ ...m-destination-path-copy-response-stream.cs | 76 +++++++++++++ ...tion-path-performs-download-save-logic.cs} | 0 ...cs => create-uri-object-for-target-url.cs} | 6 +- ...saves_downloaded_file_current_directory.cs | 40 ------- ...m_destination_path_copy_response_stream.cs | 31 ------ ...-of-urls-saving-each-response-uniquely.cs} | 22 ++-- ...-url-and-use-as-default-local-file-name.cs | 66 +++++++++++ ..._url_and_use_as_default_local_file_name.cs | 58 ---------- ...-3xx-location-headers-resending-request.cs | 61 ++++++++++ ..._3xx_location_headers_resending_request.cs | 87 --------------- ...to-three-times-transient-network-errors.cs | 50 +++++++++ ...nsient-failures-downloading-large-files.cs | 71 ++++++++++++ ...c_send_and_await_response_before_saving.cs | 40 ------- ...to_three_times_transient_network_errors.cs | 46 -------- ...nsient_failures_downloading_large_files.cs | 83 -------------- ...m-in-chunks-reporting-bytes-transferred.cs | 41 +++++++ ...start-completion-timestamps-to-log-file.cs | 73 ++++++++++++ ...ream_chunks_reporting_bytes_transferred.cs | 44 -------- ...t_and_completion_timestamps_to_log_file.cs | 57 ---------- ...te-report-percentage-completed-download.cs | 61 ++++++++++ ...te_report_percentage_completed_download.cs | 86 -------------- ...end-or-sendasync-obtain-responsemessage.cs | 38 +++++++ ...nd_or_sendasync_obtain_response_message.cs | 30 ----- ...estmessage-to-request-localized-content.cs | 43 +++++++ ...ader-requestmessage-before-downloading.cs} | 15 +-- ... => set-http-method-get-requestmessage.cs} | 9 +- ...r-requestmessage-before-sending-request.cs | 37 ++++++ ...estmessage_to_request_localized_content.cs | 38 ------- ...n_requestmessage_before_sending_request.cs | 40 ------- ...us-download-operation-cancelled-by-user.cs | 50 +++++++++ ...-data-before-writing-to-disk-validation.cs | 80 +++++++++++++ ...esponsemessage-disposed-after-operation.cs | 60 ++++++++++ ...download_operation_cancellation_by_user.cs | 50 --------- ...-and-size-matches-content-length-header.cs | 64 +++++++++++ ..._and_size_matches_content_length_header.cs | 63 ----------- ...tatus-code-equals-200-before-processing.cs | 49 ++++++++ ...atches-expected-file-type-before-saving.cs | 91 +++++++++++++++ ...tatus_code_equals_200_before_processing.cs | 38 ------- ...atches_expected_file_type_before_saving.cs | 105 ------------------ ...onse-verify-file-saving-logic-correctly.cs | 76 +++++++++++++ ...onse_verify_file_saving_logic_correctly.cs | 101 ----------------- 48 files changed, 1281 insertions(+), 1162 deletions(-) create mode 100644 save-file-from-url/append-timestamp-saved-file-name-avoid-overwriting-existing-files.cs delete mode 100644 save-file-from-url/append_timestamp_to_saved_file_name_avoid_overwriting_existing_files.cs create mode 100644 save-file-from-url/asynchronous-file-download-using-document-sendasync-await-response-before-saving.cs rename save-file-from-url/{configure_basic_authentication_credentials_in_request_message_for_protected_resources.cs => configure-basic-authentication-credentials-requestmessage-protected-resources.cs} (56%) create mode 100644 save-file-from-url/configure-timeout-for-requestmessage-to-avoid-hanging.cs delete mode 100644 save-file-from-url/configure_timeout_for_requestmessage_to_avoid_hanging.cs create mode 100644 save-file-from-url/create-console-application-accepts-url-argument-saves-downloaded-file-to-current-directory.cs create mode 100644 save-file-from-url/create-filestream-destination-path-copy-response-stream.cs rename save-file-from-url/{create_helper_method_accepts_url_destination_path_performs_download_save_logic.cs => create-helper-method-accepts-url-destination-path-performs-download-save-logic.cs} (100%) rename save-file-from-url/{create_uri_object_for_target_url.cs => create-uri-object-for-target-url.cs} (50%) delete mode 100644 save-file-from-url/create_console_accepts_url_saves_downloaded_file_current_directory.cs delete mode 100644 save-file-from-url/create_filestream_destination_path_copy_response_stream.cs rename save-file-from-url/{download_multiple_files_sequentially_iterating_over_url_list_and_saving_each_response_uniquely.cs => download-multiple-files-sequentially-iterating-list-of-urls-saving-each-response-uniquely.cs} (72%) create mode 100644 save-file-from-url/extract-file-name-from-url-and-use-as-default-local-file-name.cs delete mode 100644 save-file-from-url/extract_file_name_from_url_and_use_as_default_local_file_name.cs create mode 100644 save-file-from-url/handle-http-redirects-following-3xx-location-headers-resending-request.cs delete mode 100644 save-file-from-url/handle_http_redirects_following_3xx_location_headers_resending_request.cs create mode 100644 save-file-from-url/implement-error-handling-retries-download-up-to-three-times-transient-network-errors.cs create mode 100644 save-file-from-url/implement-retry-policy-exponential-backoff-transient-failures-downloading-large-files.cs delete mode 100644 save-file-from-url/implement_asynchronous_file_download_using_async_send_and_await_response_before_saving.cs delete mode 100644 save-file-from-url/implement_error_handling_retries_download_up_to_three_times_transient_network_errors.cs delete mode 100644 save-file-from-url/implement_retry_policy_exponential_backoff_transient_failures_downloading_large_files.cs create mode 100644 save-file-from-url/log-download-progress-reading-response-stream-in-chunks-reporting-bytes-transferred.cs create mode 100644 save-file-from-url/log-download-start-completion-timestamps-to-log-file.cs delete mode 100644 save-file-from-url/log_download_progress_reading_response_stream_chunks_reporting_bytes_transferred.cs delete mode 100644 save-file-from-url/log_download_start_and_completion_timestamps_to_log_file.cs create mode 100644 save-file-from-url/progress-callback-delegate-report-percentage-completed-download.cs delete mode 100644 save-file-from-url/provide_progress_callback_delegate_report_percentage_completed_download.cs create mode 100644 save-file-from-url/send-request-via-document-send-or-sendasync-obtain-responsemessage.cs delete mode 100644 save-file-from-url/send_request_via_document_send_or_sendasync_obtain_response_message.cs create mode 100644 save-file-from-url/set-accept-language-header-in-requestmessage-to-request-localized-content.cs rename save-file-from-url/{set_custom_user_agent_header_request_message_before_downloading.cs => set-custom-user-agent-header-requestmessage-before-downloading.cs} (77%) rename save-file-from-url/{set_http_method_get_request_message.cs => set-http-method-get-requestmessage.cs} (65%) create mode 100644 save-file-from-url/set-referer-header-requestmessage-before-sending-request.cs delete mode 100644 save-file-from-url/set_accept_language_header_in_requestmessage_to_request_localized_content.cs delete mode 100644 save-file-from-url/set_referer_header_in_requestmessage_before_sending_request.cs create mode 100644 save-file-from-url/use-cancellation-token-allow-asynchronous-download-operation-cancelled-by-user.cs create mode 100644 save-file-from-url/use-memorystream-temporarily-hold-response-data-before-writing-to-disk-validation.cs create mode 100644 save-file-from-url/use-using-block-ensure-requestmessage-responsemessage-disposed-after-operation.cs delete mode 100644 save-file-from-url/use_cancellation_token_to_allow_asynchronous_download_operation_cancellation_by_user.cs create mode 100644 save-file-from-url/validate-saved-file-exists-and-size-matches-content-length-header.cs delete mode 100644 save-file-from-url/validate_saved_file_exists_and_size_matches_content_length_header.cs create mode 100644 save-file-from-url/verify-http-response-status-code-equals-200-before-processing.cs create mode 100644 save-file-from-url/verify-response-content-type-header-matches-expected-file-type-before-saving.cs delete mode 100644 save-file-from-url/verify_http_response_status_code_equals_200_before_processing.cs delete mode 100644 save-file-from-url/verify_response_content_type_header_matches_expected_file_type_before_saving.cs create mode 100644 save-file-from-url/write-unit-tests-mock-http-response-verify-file-saving-logic-correctly.cs delete mode 100644 save-file-from-url/write_unit_tests_mock_http_response_verify_file_saving_logic_correctly.cs diff --git a/save-file-from-url/append-timestamp-saved-file-name-avoid-overwriting-existing-files.cs b/save-file-from-url/append-timestamp-saved-file-name-avoid-overwriting-existing-files.cs new file mode 100644 index 0000000..eae4c38 --- /dev/null +++ b/save-file-from-url/append-timestamp-saved-file-name-avoid-overwriting-existing-files.cs @@ -0,0 +1,40 @@ +// Append a timestamp to the saved file name to avoid overwriting existing files. + +using System; +using System.IO; +using System.Text; + +class Program +{ + static void Main() + { + try + { + string htmlContent = "

Hello World

"; + byte[] bytes = Encoding.UTF8.GetBytes(htmlContent); + using (var inputStream = new MemoryStream(bytes)) + using (var document = new Aspose.Html.HTMLDocument(inputStream, "about:blank")) + { + var metaElements = document.GetElementsByTagName("meta"); + foreach (Aspose.Html.Dom.Element meta in metaElements) + { + if (meta.GetAttribute("name") == "description") + { + meta.SetAttribute("content", "new description"); + } + } + + string outputDir = Path.Combine(Directory.GetCurrentDirectory(), "Output"); + Directory.CreateDirectory(outputDir); + string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmssfff"); + string outputPath = Path.Combine(outputDir, $"result_{timestamp}.html"); + document.Save(outputPath); + Console.WriteLine($"Saved to {outputPath}"); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/append_timestamp_to_saved_file_name_avoid_overwriting_existing_files.cs b/save-file-from-url/append_timestamp_to_saved_file_name_avoid_overwriting_existing_files.cs deleted file mode 100644 index 3be3238..0000000 --- a/save-file-from-url/append_timestamp_to_saved_file_name_avoid_overwriting_existing_files.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Append a timestamp to the saved file name to avoid overwriting existing files. - -class Program -{ - static void Main() - { - try - { - string htmlContent = "

Hello World

"; - byte[] bytes = System.Text.Encoding.UTF8.GetBytes(htmlContent); - using (var inputStream = new System.IO.MemoryStream(bytes)) - using (var document = new Aspose.Html.HTMLDocument(inputStream, "about:blank")) - { - var metaElements = document.GetElementsByTagName("meta"); - foreach (Aspose.Html.Dom.Element meta in metaElements) - { - if (meta.GetAttribute("name") == "description") - { - meta.SetAttribute("content", "Updated description"); - } - } - - string outputDir = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "output"); - System.IO.Directory.CreateDirectory(outputDir); - string timestamp = System.DateTime.Now.ToString("yyyyMMdd_HHmmss"); - string outputPath = System.IO.Path.Combine(outputDir, $"result_{timestamp}.html"); - document.Save(outputPath); - System.Console.WriteLine($"Document saved to: {outputPath}"); - } - } - catch (System.Exception ex) - { - System.Console.WriteLine(ex.Message); - } - } -} \ No newline at end of file diff --git a/save-file-from-url/asynchronous-file-download-using-document-sendasync-await-response-before-saving.cs b/save-file-from-url/asynchronous-file-download-using-document-sendasync-await-response-before-saving.cs new file mode 100644 index 0000000..836baf3 --- /dev/null +++ b/save-file-from-url/asynchronous-file-download-using-document-sendasync-await-response-before-saving.cs @@ -0,0 +1,42 @@ +// Implement asynchronous file download using Document.SendAsync and await the response before saving. + +using System; +using System.IO; +using System.Threading.Tasks; +using Aspose.Html; +using Aspose.Html.Net; + +class Program +{ + static async Task Main(string[] args) + { + try + { + string url = "https://example.com/sample.bin"; + string outputPath = "downloaded_file.bin"; + + using (HTMLDocument document = new HTMLDocument()) + { + Url requestUrl = new Url(url); + RequestMessage request = new RequestMessage(requestUrl); + + ResponseMessage response = await Task.Run(() => document.Context.Network.Send(request)); + + if (response.IsSuccess) + { + byte[] contentBytes = response.Content.ReadAsByteArray(); + File.WriteAllBytes(outputPath, contentBytes); + Console.WriteLine($"File downloaded successfully to '{outputPath}'."); + } + else + { + Console.WriteLine($"Failed to download file. Status code: {response.StatusCode}"); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/configure_basic_authentication_credentials_in_request_message_for_protected_resources.cs b/save-file-from-url/configure-basic-authentication-credentials-requestmessage-protected-resources.cs similarity index 56% rename from save-file-from-url/configure_basic_authentication_credentials_in_request_message_for_protected_resources.cs rename to save-file-from-url/configure-basic-authentication-credentials-requestmessage-protected-resources.cs index 9b747a3..12b2830 100644 --- a/save-file-from-url/configure_basic_authentication_credentials_in_request_message_for_protected_resources.cs +++ b/save-file-from-url/configure-basic-authentication-credentials-requestmessage-protected-resources.cs @@ -2,28 +2,35 @@ namespace Example { + class AuthValidator : Aspose.Html.Net.MessageHandler + { + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + Next(context); + string authHeader = context.Request.Headers["Authorization"]; + if (!string.IsNullOrEmpty(authHeader)) + System.Console.WriteLine("Authorization header present: " + authHeader); + else + System.Console.WriteLine("Authorization header missing"); + } + } + class Program { static void Main(string[] args) { try { - // Create configuration - var configuration = new Aspose.Html.Configuration(); - - // Get network service - var network = configuration.GetService(); + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - // Add a message handler to inspect Authorization header + Aspose.Html.Services.INetworkService network = configuration.GetService(); network.MessageHandlers.Add(new AuthValidator()); - // Create request with basic authentication - var request = new Aspose.Html.Net.RequestMessage("https://example.com/protected"); + Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage("https://example.com/protected"); request.Credentials = new System.Net.NetworkCredential("user", "pass"); request.PreAuthenticate = true; - // Load the HTML document using the authenticated request - using (var document = new Aspose.Html.HTMLDocument(request, configuration)) + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(request, configuration)) { string html = document.DocumentElement != null ? document.DocumentElement.OuterHTML : string.Empty; System.Console.WriteLine("Loaded HTML length: " + html.Length); @@ -35,17 +42,4 @@ static void Main(string[] args) } } } - - public class AuthValidator : Aspose.Html.Net.MessageHandler - { - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - Next(context); - string authValue = context.Request.Headers["Authorization"]; - if (!string.IsNullOrEmpty(authValue)) - System.Console.WriteLine("Authorization header present: " + authValue); - else - System.Console.WriteLine("Authorization header missing"); - } - } } \ No newline at end of file diff --git a/save-file-from-url/configure-timeout-for-requestmessage-to-avoid-hanging.cs b/save-file-from-url/configure-timeout-for-requestmessage-to-avoid-hanging.cs new file mode 100644 index 0000000..3b38838 --- /dev/null +++ b/save-file-from-url/configure-timeout-for-requestmessage-to-avoid-hanging.cs @@ -0,0 +1,28 @@ +// Configure a timeout for the RequestMessage to avoid hanging. + +using System; + +class Program +{ + static void Main() + { + try + { + Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage("https://example.com"); + request.Timeout = System.TimeSpan.FromSeconds(10); + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(request)) + { + string html = document.DocumentElement != null ? document.DocumentElement.OuterHTML : string.Empty; + System.Console.WriteLine(html); + } + } + catch (System.TimeoutException) + { + System.Console.WriteLine("The request timed out."); + } + catch (System.Exception ex) + { + System.Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/configure_timeout_for_requestmessage_to_avoid_hanging.cs b/save-file-from-url/configure_timeout_for_requestmessage_to_avoid_hanging.cs deleted file mode 100644 index 47a1b53..0000000 --- a/save-file-from-url/configure_timeout_for_requestmessage_to_avoid_hanging.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Configure a timeout for the RequestMessage to avoid hanging. - -using System; - -class Program -{ - static void Main() - { - try - { - Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage("https://example.com"); - request.Timeout = System.TimeSpan.FromSeconds(10); - try - { - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(request)) - { - string html = document.DocumentElement != null ? document.DocumentElement.OuterHTML : string.Empty; - System.Console.WriteLine(html); - } - } - catch (System.TimeoutException) - { - System.Console.WriteLine("The request timed out."); - } - catch (System.Exception ex) - { - System.Console.WriteLine("Error: " + ex.Message); - } - } - catch (System.Exception ex) - { - System.Console.WriteLine("Unexpected error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/save-file-from-url/create-console-application-accepts-url-argument-saves-downloaded-file-to-current-directory.cs b/save-file-from-url/create-console-application-accepts-url-argument-saves-downloaded-file-to-current-directory.cs new file mode 100644 index 0000000..7d7f16e --- /dev/null +++ b/save-file-from-url/create-console-application-accepts-url-argument-saves-downloaded-file-to-current-directory.cs @@ -0,0 +1,46 @@ +// Create a console application that accepts a URL argument and saves the downloaded file to the current directory. + +using System; +using System.IO; + +class Program +{ + static void Main(string[] args) + { + try + { + string urlString = args.Length > 0 ? args[0] : "https://example.com"; + var url = new Aspose.Html.Url(urlString); + var document = new Aspose.Html.HTMLDocument(); + var request = new Aspose.Html.Net.RequestMessage(url); + var response = document.Context.Network.Send(request); + + if (!response.IsSuccess) + throw new Exception($"Failed to download. Status code: {response.StatusCode}"); + + byte[] contentBytes = response.Content.ReadAsByteArray(); + + string fileName; + try + { + var uri = new Uri(urlString); + fileName = Path.GetFileName(uri.LocalPath); + if (string.IsNullOrEmpty(fileName)) + fileName = "index.html"; + } + catch + { + fileName = "downloaded.html"; + } + + string outputPath = Path.Combine(Environment.CurrentDirectory, fileName); + File.WriteAllBytes(outputPath, contentBytes); + + Console.WriteLine($"File saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/create-filestream-destination-path-copy-response-stream.cs b/save-file-from-url/create-filestream-destination-path-copy-response-stream.cs new file mode 100644 index 0000000..5b24525 --- /dev/null +++ b/save-file-from-url/create-filestream-destination-path-copy-response-stream.cs @@ -0,0 +1,76 @@ +// Create a FileStream for the destination path and copy the response stream to it. + +using System; + +public class MemoryStreamProvider : Aspose.Html.IO.ICreateStreamProvider +{ + public System.Collections.Generic.List Streams = new System.Collections.Generic.List(); + + public System.IO.Stream GetStream(string name, string extension) + { + var ms = new System.IO.MemoryStream(); + Streams.Add(ms); + return ms; + } + + public System.IO.Stream GetStream(string name, string extension, int page) + { + var ms = new System.IO.MemoryStream(); + Streams.Add(ms); + return ms; + } + + public void ReleaseStream(System.IO.Stream stream) + { + // No action needed + } + + public void Dispose() + { + foreach (var s in Streams) + { + s.Dispose(); + } + } +} + +public class Program +{ + public static void Main() + { + try + { + // Create a minimal HTML file + string htmlPath = "sample.html"; + string htmlContent = "

Hello Aspose.HTML

"; + System.IO.File.WriteAllText(htmlPath, htmlContent); + + // Load the HTML document + var document = new Aspose.Html.HTMLDocument(htmlPath); + + // Prepare provider and options + var provider = new MemoryStreamProvider(); + var options = new Aspose.Html.Saving.PdfSaveOptions(); + + // Convert HTML to PDF using the provider + Aspose.Html.Converters.Converter.ConvertHTML(document, options, provider); + + // Retrieve the generated stream + var resultStream = provider.Streams[0]; + resultStream.Position = 0; + + // Copy the result stream to a file + string outputPath = "output.pdf"; + using (var fileStream = new System.IO.FileStream(outputPath, System.IO.FileMode.Create, System.IO.FileAccess.Write)) + { + resultStream.CopyTo(fileStream); + } + + Console.WriteLine("Conversion completed. PDF saved to " + outputPath); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/create_helper_method_accepts_url_destination_path_performs_download_save_logic.cs b/save-file-from-url/create-helper-method-accepts-url-destination-path-performs-download-save-logic.cs similarity index 100% rename from save-file-from-url/create_helper_method_accepts_url_destination_path_performs_download_save_logic.cs rename to save-file-from-url/create-helper-method-accepts-url-destination-path-performs-download-save-logic.cs diff --git a/save-file-from-url/create_uri_object_for_target_url.cs b/save-file-from-url/create-uri-object-for-target-url.cs similarity index 50% rename from save-file-from-url/create_uri_object_for_target_url.cs rename to save-file-from-url/create-uri-object-for-target-url.cs index 01e96f6..9491e89 100644 --- a/save-file-from-url/create_uri_object_for_target_url.cs +++ b/save-file-from-url/create-uri-object-for-target-url.cs @@ -8,12 +8,12 @@ static void Main() { try { - var targetUri = new System.Uri("https://www.example.com"); - Console.WriteLine($"Target URL: {targetUri}"); + var targetUri = new Uri("https://www.example.com"); + Console.WriteLine("Created Uri: " + targetUri); } catch (Exception ex) { - Console.WriteLine($"Error: {ex.Message}"); + Console.WriteLine("Error: " + ex.Message); } } } \ No newline at end of file diff --git a/save-file-from-url/create_console_accepts_url_saves_downloaded_file_current_directory.cs b/save-file-from-url/create_console_accepts_url_saves_downloaded_file_current_directory.cs deleted file mode 100644 index e040ed5..0000000 --- a/save-file-from-url/create_console_accepts_url_saves_downloaded_file_current_directory.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Create a console application that accepts a URL argument and saves the downloaded file to the current directory. - -using System; -using System.IO; - -namespace AsposeHtmlDownloadExample -{ - class Program - { - static void Main(string[] args) - { - try - { - string urlString = args.Length > 0 ? args[0] : "https://example.com"; - var url = new Aspose.Html.Url(urlString); - var document = new Aspose.Html.HTMLDocument(); - var request = new Aspose.Html.Net.RequestMessage(url); - var response = document.Context.Network.Send(request); - if (!response.IsSuccess) - { - Console.WriteLine($"Failed to download content. Status: {response.StatusCode}"); - return; - } - byte[] contentBytes = response.Content.ReadAsByteArray(); - string fileName = Path.GetFileName(new Uri(urlString).AbsolutePath); - if (string.IsNullOrEmpty(fileName)) - { - fileName = "output.html"; - } - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), fileName); - File.WriteAllBytes(outputPath, contentBytes); - Console.WriteLine($"File saved to: {outputPath}"); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } - } -} \ No newline at end of file diff --git a/save-file-from-url/create_filestream_destination_path_copy_response_stream.cs b/save-file-from-url/create_filestream_destination_path_copy_response_stream.cs deleted file mode 100644 index e83e5b1..0000000 --- a/save-file-from-url/create_filestream_destination_path_copy_response_stream.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Create a FileStream for the destination path and copy the response stream to it. - -using System; -using System.IO; -using System.Net.Http; - -class Program -{ - static void Main() - { - try - { - string url = "https://example.com"; - string outputPath = "example.html"; - - using (HttpClient httpClient = new HttpClient()) - using (HttpResponseMessage response = httpClient.GetAsync(url).GetAwaiter().GetResult()) - using (Stream responseStream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()) - using (FileStream fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) - { - responseStream.CopyTo(fileStream); - } - - Console.WriteLine("Download completed successfully."); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/save-file-from-url/download_multiple_files_sequentially_iterating_over_url_list_and_saving_each_response_uniquely.cs b/save-file-from-url/download-multiple-files-sequentially-iterating-list-of-urls-saving-each-response-uniquely.cs similarity index 72% rename from save-file-from-url/download_multiple_files_sequentially_iterating_over_url_list_and_saving_each_response_uniquely.cs rename to save-file-from-url/download-multiple-files-sequentially-iterating-list-of-urls-saving-each-response-uniquely.cs index 5ebf60e..86bc5d0 100644 --- a/save-file-from-url/download_multiple_files_sequentially_iterating_over_url_list_and_saving_each_response_uniquely.cs +++ b/save-file-from-url/download-multiple-files-sequentially-iterating-list-of-urls-saving-each-response-uniquely.cs @@ -1,18 +1,19 @@ // Download multiple files sequentially by iterating over a list of URLs and saving each response uniquely. using System; -using System.IO; using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; using Aspose.Html; using Aspose.Html.Net; class Program { - static void Main(string[] args) + static async Task Main(string[] args) { try { - var urls = new List + List urls = new List { "https://example.com/file1.txt", "https://example.com/file2.jpg" @@ -21,23 +22,24 @@ static void Main(string[] args) string outputDir = "DownloadedFiles"; Directory.CreateDirectory(outputDir); - using (HTMLDocument document = new HTMLDocument()) + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument()) { - int index = 1; foreach (string urlString in urls) { - Url url = new Url(urlString); - RequestMessage request = new RequestMessage(url); - ResponseMessage response = document.Context.Network.Send(request); + Aspose.Html.Url url = new Aspose.Html.Url(urlString); + Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(url); + Aspose.Html.Net.ResponseMessage response = document.Context.Network.Send(request); if (response.IsSuccess) { byte[] contentBytes = response.Content.ReadAsByteArray(); + string fileName = Path.GetFileName(urlString); if (string.IsNullOrEmpty(fileName)) { - fileName = $"file_{index}"; + fileName = $"file_{Guid.NewGuid()}.bin"; } + string savePath = Path.Combine(outputDir, fileName); File.WriteAllBytes(savePath, contentBytes); Console.WriteLine($"Saved: {savePath}"); @@ -46,8 +48,6 @@ static void Main(string[] args) { Console.WriteLine($"Failed to download: {urlString}, Status: {response.StatusCode}"); } - - index++; } } } diff --git a/save-file-from-url/extract-file-name-from-url-and-use-as-default-local-file-name.cs b/save-file-from-url/extract-file-name-from-url-and-use-as-default-local-file-name.cs new file mode 100644 index 0000000..4fac08e --- /dev/null +++ b/save-file-from-url/extract-file-name-from-url-and-use-as-default-local-file-name.cs @@ -0,0 +1,66 @@ +// Extract the file name from the URL and use it as the default local file name. + +using System; +using System.IO; +using System.Net.Http; +using Aspose.Html; +using Aspose.Html.Collections; +using Aspose.Html.Dom; +using Aspose.Html.Net; + +class Program +{ + static void Main(string[] args) + { + try + { + string inputUrl = "https://example.com/sample.html"; + string outputDir = "DownloadedImages"; + + Directory.CreateDirectory(outputDir); + + using (HttpClient httpClient = new HttpClient()) + { + // Download HTML content + string htmlContent = httpClient.GetStringAsync(inputUrl).GetAwaiter().GetResult(); + + // Load HTML document with base URI + using (HTMLDocument document = new HTMLDocument(htmlContent, inputUrl)) + { + // Get all elements + HTMLCollection images = document.GetElementsByTagName("img"); + + for (int i = 0; i < images.Length; i++) + { + Element imgElement = (Element)images[i]; + string src = imgElement.GetAttribute("src"); + if (string.IsNullOrWhiteSpace(src)) + continue; + + // Resolve image URL against document base URI + Url imageUrl = new Url(src, document.BaseURI); + string imageUrlString = imageUrl.ToString(); + + // Download image bytes + byte[] imageBytes = httpClient.GetByteArrayAsync(imageUrlString).GetAwaiter().GetResult(); + + // Extract file name from URL + string fileName = Path.GetFileName(imageUrlString); + if (string.IsNullOrEmpty(fileName)) + fileName = $"image_{i}.bin"; + + // Save image to output directory + string savePath = Path.Combine(outputDir, fileName); + File.WriteAllBytes(savePath, imageBytes); + } + } + } + + Console.WriteLine("Images downloaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/extract_file_name_from_url_and_use_as_default_local_file_name.cs b/save-file-from-url/extract_file_name_from_url_and_use_as_default_local_file_name.cs deleted file mode 100644 index b2a48b8..0000000 --- a/save-file-from-url/extract_file_name_from_url_and_use_as_default_local_file_name.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Extract the file name from the URL and use it as the default local file name. - -using System; -using System.IO; -using System.Net.Http; -using Aspose.Html; -using Aspose.Html.Collections; -using Aspose.Html.Dom; -using Aspose.Html.Net; - -class Program -{ - static void Main(string[] args) - { - try - { - // Prepare sample HTML with an image - string inputPath = "input.html"; - string htmlContent = ""; - File.WriteAllText(inputPath, htmlContent); - - // Output directory for downloaded images - string outputDir = "downloaded_images"; - Directory.CreateDirectory(outputDir); - - using (HTMLDocument document = new HTMLDocument(inputPath)) - using (HttpClient httpClient = new HttpClient()) - { - HTMLCollection images = document.GetElementsByTagName("img"); - for (int i = 0; i < images.Length; i++) - { - Element imgElement = (Element)images[i]; - string src = imgElement.GetAttribute("src"); - if (string.IsNullOrEmpty(src)) - continue; - - Url imageUrl = new Url(src, document.BaseURI); - string urlString = imageUrl.ToString(); - - // Extract file name from URL - string fileName = Path.GetFileName(urlString); - if (string.IsNullOrEmpty(fileName)) - continue; - - string savePath = Path.Combine(outputDir, fileName); - byte[] imageBytes = httpClient.GetByteArrayAsync(urlString).GetAwaiter().GetResult(); - File.WriteAllBytes(savePath, imageBytes); - } - } - - Console.WriteLine("Images downloaded successfully."); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/save-file-from-url/handle-http-redirects-following-3xx-location-headers-resending-request.cs b/save-file-from-url/handle-http-redirects-following-3xx-location-headers-resending-request.cs new file mode 100644 index 0000000..187a3f7 --- /dev/null +++ b/save-file-from-url/handle-http-redirects-following-3xx-location-headers-resending-request.cs @@ -0,0 +1,61 @@ +// Handle HTTP redirects by following 3xx Location headers and resending the request. + +using System; + +class Program +{ + static void Main() + { + try + { + // Create configuration and attach redirect handler + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + Aspose.Html.Services.INetworkService networkService = configuration.GetService(); + networkService.MessageHandlers.Add(new RedirectHandler()); + + // Input URL (may respond with a 3xx redirect) and output file path + string url = "http://example.com/redirect"; + string outputPath = "output.html"; + + // Load the document using the configuration with the redirect handler + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) + { + document.Save(outputPath); + } + + Console.WriteLine("Document saved to " + outputPath); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} + +// Message handler that follows a single HTTP redirect (3xx) by resending the request to the Location header. +class RedirectHandler : Aspose.Html.Net.MessageHandler +{ + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + // Perform the initial request + Next(context); + + // Check for redirect status code + int statusCode = (int)context.Response.StatusCode; + if (statusCode >= 300 && statusCode < 400) + { + // Get the Location header value + object locationHeader = context.Response.Headers["Location"]; + if (locationHeader != null) + { + string location = locationHeader.ToString(); + if (!string.IsNullOrEmpty(location)) + { + // Update request URI to the new location and resend the request + context.Request.RequestUri = new Aspose.Html.Url(location); + Next(context); + } + } + } + } +} \ No newline at end of file diff --git a/save-file-from-url/handle_http_redirects_following_3xx_location_headers_resending_request.cs b/save-file-from-url/handle_http_redirects_following_3xx_location_headers_resending_request.cs deleted file mode 100644 index dfbff60..0000000 --- a/save-file-from-url/handle_http_redirects_following_3xx_location_headers_resending_request.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Handle HTTP redirects by following 3xx Location headers and resending the request. - -using System; -using System.Collections.Generic; - -class RedirectHandler : Aspose.Html.Net.MessageHandler -{ - private const int MaxRedirects = 5; - private readonly Dictionary _redirectCounts = new Dictionary(); - - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - // First attempt - Next(context); - - int statusCode = (int)context.Response.StatusCode; - if (statusCode >= 300 && statusCode < 400) - { - object locationHeader = context.Response.Headers["Location"]; - if (locationHeader != null) - { - string location = locationHeader.ToString(); - string requestKey = context.Request.RequestUri.ToString(); - - int count = 0; - if (_redirectCounts.TryGetValue(requestKey, out int existing)) - { - count = existing; - } - - if (count < MaxRedirects) - { - _redirectCounts[requestKey] = count + 1; - - // Resolve new URL (absolute or relative) - Aspose.Html.Url newUrl; - if (Uri.IsWellFormedUriString(location, UriKind.Absolute)) - { - newUrl = new Aspose.Html.Url(location); - } - else - { - // Combine with base URL - string baseUrl = context.Request.RequestUri.Protocol + "://" + context.Request.RequestUri.Host + context.Request.RequestUri.Pathname; - newUrl = new Aspose.Html.Url(baseUrl, location); - } - - context.Request.RequestUri = newUrl; - - // Resend the request after redirect - Next(context); - } - } - } - } -} - -class Program -{ - static void Main() - { - try - { - // Input URL that may redirect - string url = "http://httpbin.org/redirect/1"; - // Output file path - string outputPath = "output.html"; - - // Create configuration and add redirect handler - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - Aspose.Html.Services.INetworkService networkService = configuration.GetService(); - networkService.MessageHandlers.Add(new RedirectHandler()); - - // Load document with configuration - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) - { - document.Save(outputPath); - } - - Console.WriteLine("Document saved to: " + outputPath); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/save-file-from-url/implement-error-handling-retries-download-up-to-three-times-transient-network-errors.cs b/save-file-from-url/implement-error-handling-retries-download-up-to-three-times-transient-network-errors.cs new file mode 100644 index 0000000..ee08bf5 --- /dev/null +++ b/save-file-from-url/implement-error-handling-retries-download-up-to-three-times-transient-network-errors.cs @@ -0,0 +1,50 @@ +// Implement error handling that retries the download up to three times for transient network errors. + +using System; + +public class RetryHandler : Aspose.Html.Net.MessageHandler +{ + private readonly int _maxRetries; + public RetryHandler(int maxRetries) + { + _maxRetries = maxRetries; + } + + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + for (int attempt = 0; attempt <= _maxRetries; attempt++) + { + Next(context); + if ((int)context.Response.StatusCode < 500) + break; + } + } +} + +public class Program +{ + public static void Main(string[] args) + { + try + { + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + Aspose.Html.Services.INetworkService networkService = configuration.GetService(); + networkService.MessageHandlers.Add(new RetryHandler(3)); + + string url = "https://example.com"; + string outputPath = "output.pdf"; + + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) + using (Aspose.Html.Rendering.Pdf.PdfDevice device = new Aspose.Html.Rendering.Pdf.PdfDevice(outputPath)) + { + document.RenderTo(device); + } + + Console.WriteLine("Conversion completed successfully."); + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/implement-retry-policy-exponential-backoff-transient-failures-downloading-large-files.cs b/save-file-from-url/implement-retry-policy-exponential-backoff-transient-failures-downloading-large-files.cs new file mode 100644 index 0000000..a55517b --- /dev/null +++ b/save-file-from-url/implement-retry-policy-exponential-backoff-transient-failures-downloading-large-files.cs @@ -0,0 +1,71 @@ +// Implement a retry policy with exponential backoff for transient failures when downloading large files. + +using System; +using System.Threading; +using Aspose.Html; +using Aspose.Html.Net; +using Aspose.Html.Services; +using Aspose.Html.Rendering.Pdf; + +public sealed class RetryHandler : Aspose.Html.Net.MessageHandler +{ + private readonly int _maxRetries; + + public RetryHandler(int maxRetries) + { + _maxRetries = maxRetries; + } + + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + for (int attempt = 0; attempt <= _maxRetries; attempt++) + { + Next(context); + + int statusCode = (int)context.Response.StatusCode; + if (statusCode < 500) + { + // Success or non‑transient error, stop retrying + break; + } + + // Transient server error, apply exponential backoff before next attempt + int delayMilliseconds = (int)Math.Pow(2, attempt) * 1000; // 1s, 2s, 4s, ... + Thread.Sleep(delayMilliseconds); + } + } +} + +public class Program +{ + public static void Main() + { + try + { + // Input URL of a large file (HTML page) to download + string url = "https://example.com/largefile.html"; + // Output PDF path + string outputPath = "downloaded.pdf"; + // Maximum retry attempts + int maxAttempts = 5; + + // Configure Aspose.HTML with the retry handler + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + Aspose.Html.Services.INetworkService networkService = configuration.GetService(); + networkService.MessageHandlers.Insert(0, new RetryHandler(maxAttempts)); + + // Load the document and render to PDF + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) + using (Aspose.Html.Rendering.Pdf.PdfDevice device = new Aspose.Html.Rendering.Pdf.PdfDevice(outputPath)) + { + document.RenderTo(device); + } + + Console.WriteLine("Download and conversion completed successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/implement_asynchronous_file_download_using_async_send_and_await_response_before_saving.cs b/save-file-from-url/implement_asynchronous_file_download_using_async_send_and_await_response_before_saving.cs deleted file mode 100644 index 9a64e77..0000000 --- a/save-file-from-url/implement_asynchronous_file_download_using_async_send_and_await_response_before_saving.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Implement asynchronous file download using Document.SendAsync and await the response before saving. - -using System; -using System.IO; -using System.Threading.Tasks; - -class Program -{ - static async Task Main() - { - try - { - string urlString = "https://example.com/sample.txt"; - string outputPath = "downloaded_sample.txt"; - - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument()) - { - Aspose.Html.Url url = new Aspose.Html.Url(urlString); - Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(url); - - Aspose.Html.Net.ResponseMessage response = await Task.Run(() => document.Context.Network.Send(request)); - - if (response.IsSuccess) - { - byte[] contentBytes = response.Content.ReadAsByteArray(); - File.WriteAllBytes(outputPath, contentBytes); - Console.WriteLine($"File downloaded and saved to '{outputPath}'."); - } - else - { - Console.WriteLine($"Failed to download. Status code: {response.StatusCode}"); - } - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/save-file-from-url/implement_error_handling_retries_download_up_to_three_times_transient_network_errors.cs b/save-file-from-url/implement_error_handling_retries_download_up_to_three_times_transient_network_errors.cs deleted file mode 100644 index 848e292..0000000 --- a/save-file-from-url/implement_error_handling_retries_download_up_to_three_times_transient_network_errors.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Implement error handling that retries the download up to three times for transient network errors. - -namespace MyApp -{ - class Program - { - static void Main(string[] args) - { - try - { - string url = "https://example.com"; - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - Aspose.Html.Services.INetworkService networkService = configuration.GetService(); - networkService.MessageHandlers.Add(new RetryHandler(3)); - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) - { - System.Console.WriteLine(document.Title); - } - } - catch (System.Exception ex) - { - System.Console.WriteLine("Error: " + ex.Message); - } - } - } - - class RetryHandler : Aspose.Html.Net.MessageHandler - { - private readonly int maxRetries; - public RetryHandler(int maxRetries) - { - this.maxRetries = maxRetries; - } - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - for (int attempt = 0; attempt <= this.maxRetries; attempt++) - { - Next(context); - if ((int)context.Response.StatusCode < 500) - { - break; - } - } - } - } -} \ No newline at end of file diff --git a/save-file-from-url/implement_retry_policy_exponential_backoff_transient_failures_downloading_large_files.cs b/save-file-from-url/implement_retry_policy_exponential_backoff_transient_failures_downloading_large_files.cs deleted file mode 100644 index 9f26783..0000000 --- a/save-file-from-url/implement_retry_policy_exponential_backoff_transient_failures_downloading_large_files.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Implement a retry policy with exponential backoff for transient failures when downloading large files. - -using System; -using System.IO; -using System.Net.Http; -using System.Threading; - -public sealed class RetryHandler : Aspose.Html.Net.MessageHandler -{ - private readonly int _maxRetries; - public RetryHandler(int maxRetries) - { - _maxRetries = maxRetries; - } - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - for (int attempt = 0; attempt <= _maxRetries; attempt++) - { - Next(context); - if ((int)context.Response.StatusCode < 500) - break; - } - } -} - -class Program -{ - static void Main() - { - try - { - // Configure Aspose.HTML network service with retry handler - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - Aspose.Html.Services.INetworkService network = configuration.GetService(); - network.MessageHandlers.Add(new RetryHandler(3)); - - // Example download with exponential backoff - string url = "https://www.example.com"; - string outputPath = "example.html"; - int maxAttempts = 5; - - DownloadFileWithRetry(url, outputPath, maxAttempts); - Console.WriteLine("Download completed successfully."); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } - - static void DownloadFileWithRetry(string url, string outputPath, int maxAttempts) - { - Exception lastException = null; - using (HttpClient client = new HttpClient()) - { - for (int attempt = 1; attempt <= maxAttempts; attempt++) - { - try - { - using (HttpResponseMessage response = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).Result) - { - response.EnsureSuccessStatusCode(); - using (Stream contentStream = response.Content.ReadAsStreamAsync().Result) - using (FileStream fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.None)) - { - contentStream.CopyTo(fileStream); - } - } - // Success, exit method - return; - } - catch (Exception ex) when (ex is HttpRequestException || ex is IOException) - { - lastException = ex; - int delay = (int)Math.Pow(2, attempt) * 1000; // exponential backoff in milliseconds - Thread.Sleep(delay); - } - } - } - // All attempts failed - throw lastException ?? new Exception("Download failed without captured exception."); - } -} \ No newline at end of file diff --git a/save-file-from-url/log-download-progress-reading-response-stream-in-chunks-reporting-bytes-transferred.cs b/save-file-from-url/log-download-progress-reading-response-stream-in-chunks-reporting-bytes-transferred.cs new file mode 100644 index 0000000..1ffea42 --- /dev/null +++ b/save-file-from-url/log-download-progress-reading-response-stream-in-chunks-reporting-bytes-transferred.cs @@ -0,0 +1,41 @@ +// Log the download progress by reading the response stream in chunks and reporting bytes transferred. + +using System; +using System.IO; + +class Program +{ + static void Main() + { + try + { + // Create a minimal HTMLDocument to access the network service + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument()) + { + // Prepare the request + Aspose.Html.Url url = new Aspose.Html.Url("https://example.com"); + Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(url); + + // Send the request + Aspose.Html.Net.ResponseMessage response = document.Context.Network.Send(request); + + // Check if the request succeeded + if (!response.IsSuccess) + { + Console.WriteLine($"Request failed with status code: {response.StatusCode}"); + return; + } + + // Read the response content as a byte array + byte[] contentBytes = response.Content.ReadAsByteArray(); + Console.WriteLine($"Downloaded {contentBytes.Length} bytes"); + + Console.WriteLine("Download completed successfully."); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/log-download-start-completion-timestamps-to-log-file.cs b/save-file-from-url/log-download-start-completion-timestamps-to-log-file.cs new file mode 100644 index 0000000..80cd2f7 --- /dev/null +++ b/save-file-from-url/log-download-start-completion-timestamps-to-log-file.cs @@ -0,0 +1,73 @@ +// Log download start and completion timestamps to a log file. + +using System; +using System.IO; +using System.Diagnostics; + +class Program +{ + static void Main() + { + try + { + // Prepare directories and files + string dataDir = Path.Combine(Directory.GetCurrentDirectory(), "Data"); + Directory.CreateDirectory(dataDir); + + string htmlPath = Path.Combine(dataDir, "sample.html"); + if (!File.Exists(htmlPath)) + { + File.WriteAllText(htmlPath, "Sample

Hello, Aspose.HTML!

"); + } + + string logPath = Path.Combine(dataDir, "download.log"); + string outputPdfPath = Path.Combine(dataDir, "output.pdf"); + + // Configure Aspose.HTML with custom message handler + var configuration = new Aspose.Html.Configuration(); + var networkService = configuration.GetService(); + networkService.MessageHandlers.Add(new TimeLoggerMessageHandler(logPath)); + + // Load HTML document and render to PDF (triggers network operations) + using (var document = new Aspose.Html.HTMLDocument(htmlPath, configuration)) + using (var device = new Aspose.Html.Rendering.Pdf.PdfDevice(outputPdfPath)) + { + document.RenderTo(device); + } + + Console.WriteLine("Conversion completed successfully."); + Console.WriteLine($"Log written to: {logPath}"); + } + catch (Exception ex) + { + Console.Error.WriteLine("An error occurred: " + ex.Message); + } + } +} + +public sealed class TimeLoggerMessageHandler : Aspose.Html.Net.MessageHandler +{ + private readonly string _logFilePath; + + public TimeLoggerMessageHandler(string logFilePath) + { + _logFilePath = logFilePath; + } + + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + DateTime startTime = DateTime.UtcNow; + Next(context); + DateTime endTime = DateTime.UtcNow; + TimeSpan elapsed = endTime - startTime; + + using (var writer = new StreamWriter(_logFilePath, true)) + { + writer.WriteLine("Request URI: " + context.Request.RequestUri); + writer.WriteLine("Start: " + startTime.ToString("O")); + writer.WriteLine("End: " + endTime.ToString("O")); + writer.WriteLine("Elapsed (ms): " + elapsed.TotalMilliseconds); + writer.WriteLine(new string('-', 40)); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/log_download_progress_reading_response_stream_chunks_reporting_bytes_transferred.cs b/save-file-from-url/log_download_progress_reading_response_stream_chunks_reporting_bytes_transferred.cs deleted file mode 100644 index fe81d20..0000000 --- a/save-file-from-url/log_download_progress_reading_response_stream_chunks_reporting_bytes_transferred.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Log the download progress by reading the response stream in chunks and reporting bytes transferred. - -namespace AsposeHtmlDownloadProgress -{ - class Program - { - static void Main() - { - try - { - var url = new Aspose.Html.Url("https://example.com"); - var request = new Aspose.Html.Net.RequestMessage(url); - using (var tempDoc = new Aspose.Html.HTMLDocument()) - { - var response = tempDoc.Context.Network.Send(request); - if (!response.IsSuccess) - { - System.Console.WriteLine($"Request failed with status: {response.StatusCode}"); - return; - } - - var contentBytes = response.Content.ReadAsByteArray(); - - using (var ms = new System.IO.MemoryStream(contentBytes)) - { - const int bufferSize = 8192; - var buffer = new byte[bufferSize]; - int bytesRead; - long totalBytes = 0; - while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) > 0) - { - totalBytes += bytesRead; - System.Console.WriteLine($"Downloaded {totalBytes} bytes"); - } - } - } - } - catch (System.Exception ex) - { - System.Console.WriteLine($"Error: {ex.Message}"); - } - } - } -} \ No newline at end of file diff --git a/save-file-from-url/log_download_start_and_completion_timestamps_to_log_file.cs b/save-file-from-url/log_download_start_and_completion_timestamps_to_log_file.cs deleted file mode 100644 index bbb4772..0000000 --- a/save-file-from-url/log_download_start_and_completion_timestamps_to_log_file.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Log download start and completion timestamps to a log file. - -using System; -using System.IO; -using Aspose.Html; -using Aspose.Html.Net; -using Aspose.Html.Services; - -public sealed class TimeLoggerMessageHandler : Aspose.Html.Net.MessageHandler -{ - private readonly string _logFilePath; - public TimeLoggerMessageHandler(string logFilePath) - { - _logFilePath = logFilePath; - } - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - DateTime startTime = DateTime.UtcNow; - using (StreamWriter writer = new StreamWriter(_logFilePath, true)) - { - writer.WriteLine("Start: " + startTime.ToString("o") + " | URI: " + context.Request.RequestUri); - } - Next(context); - DateTime endTime = DateTime.UtcNow; - using (StreamWriter writer = new StreamWriter(_logFilePath, true)) - { - writer.WriteLine("End: " + endTime.ToString("o") + " | URI: " + context.Request.RequestUri); - writer.WriteLine(new string('-', 40)); - } - } -} - -public class Program -{ - public static void Main(string[] args) - { - try - { - string logPath = Path.Combine(Directory.GetCurrentDirectory(), "download_log.txt"); - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - Aspose.Html.Services.INetworkService networkService = configuration.GetService(); - networkService.MessageHandlers.Add(new TimeLoggerMessageHandler(logPath)); - - string url = "https://example.com"; - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) - { - string outputPath = Path.Combine(Directory.GetCurrentDirectory(), "output.html"); - document.Save(outputPath); - Console.WriteLine("Document saved to " + outputPath); - } - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/save-file-from-url/progress-callback-delegate-report-percentage-completed-download.cs b/save-file-from-url/progress-callback-delegate-report-percentage-completed-download.cs new file mode 100644 index 0000000..1070e3a --- /dev/null +++ b/save-file-from-url/progress-callback-delegate-report-percentage-completed-download.cs @@ -0,0 +1,61 @@ +// Provide a progress callback delegate to report percentage completed during download. + +using System; +using System.Diagnostics; +using Aspose.Html.Net; + +public sealed class ProgressMessageHandler : Aspose.Html.Net.MessageHandler +{ + private readonly Action _progressCallback; + + public ProgressMessageHandler(Action progressCallback) + { + _progressCallback = progressCallback ?? throw new ArgumentNullException(nameof(progressCallback)); + } + + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + // Report start of download (0%) + _progressCallback(0); + // Continue with the request + Next(context); + // Report completion of download (100%) + _progressCallback(100); + } +} + +public class Program +{ + public static void Main() + { + try + { + // Define input URL and output PDF path + string url = "https://example.com"; + string outputPdfPath = "output.pdf"; + + // Create configuration and attach progress handler + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + Aspose.Html.Services.INetworkService networkService = configuration.GetService(); + networkService.MessageHandlers.Add(new ProgressMessageHandler(percent => + { + Console.WriteLine($"Download progress: {percent}%"); + })); + + // Load HTML document from the URL + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) + // Render to PDF + using (Aspose.Html.Rendering.Pdf.PdfDevice device = new Aspose.Html.Rendering.Pdf.PdfDevice(outputPdfPath)) + { + Stopwatch conversionTimer = Stopwatch.StartNew(); + document.RenderTo(device); + conversionTimer.Stop(); + Console.WriteLine($"Conversion completed in {conversionTimer.Elapsed.TotalSeconds:F2} seconds."); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/provide_progress_callback_delegate_report_percentage_completed_download.cs b/save-file-from-url/provide_progress_callback_delegate_report_percentage_completed_download.cs deleted file mode 100644 index 4d0d948..0000000 --- a/save-file-from-url/provide_progress_callback_delegate_report_percentage_completed_download.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Provide a progress callback delegate to report percentage completed during download. - -using System; -using System.IO; -using System.Net.Http; -using System.Text; -using System.Threading.Tasks; -using Aspose.Html; -using Aspose.Html.Net; -using Aspose.Html.Rendering.Pdf; - -public sealed class RequestLoggingHandler : Aspose.Html.Net.MessageHandler -{ - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - System.Diagnostics.Stopwatch requestTimer = System.Diagnostics.Stopwatch.StartNew(); - this.Next(context); - requestTimer.Stop(); - System.Console.WriteLine("Request: " + context.Request.RequestUri + " | " + requestTimer.ElapsedMilliseconds + " ms"); - } -} - -public class Program -{ - private static async Task DownloadHtmlAsync(string url, Action progress) - { - using (HttpClient client = new HttpClient()) - { - using (HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead)) - { - response.EnsureSuccessStatusCode(); - long? contentLength = response.Content.Headers.ContentLength; - using (Stream stream = await response.Content.ReadAsStreamAsync()) - using (MemoryStream ms = new MemoryStream()) - { - byte[] buffer = new byte[8192]; - long totalRead = 0; - int read; - while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0) - { - ms.Write(buffer, 0, read); - totalRead += read; - if (contentLength.HasValue && contentLength.Value > 0) - { - int percent = (int)(totalRead * 100 / contentLength.Value); - progress(percent); - } - } - return Encoding.UTF8.GetString(ms.ToArray()); - } - } - } - } - - public static async Task Main(string[] args) - { - try - { - string url = "https://example.com"; - string htmlPath = "sample.html"; - string outputPdfPath = "output.pdf"; - - Action progressCallback = percent => Console.WriteLine($"Download progress: {percent}%"); - - string htmlContent = await DownloadHtmlAsync(url, progressCallback); - File.WriteAllText(htmlPath, htmlContent, Encoding.UTF8); - - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - Aspose.Html.Services.INetworkService networkService = configuration.GetService(); - networkService.MessageHandlers.Add(new RequestLoggingHandler()); - - System.Diagnostics.Stopwatch conversionTimer = System.Diagnostics.Stopwatch.StartNew(); - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(htmlPath, configuration)) - using (Aspose.Html.Rendering.Pdf.PdfDevice device = new Aspose.Html.Rendering.Pdf.PdfDevice(outputPdfPath)) - { - document.RenderTo(device); - } - conversionTimer.Stop(); - Console.WriteLine("Conversion completed in " + conversionTimer.Elapsed.TotalSeconds.ToString("F2") + " seconds."); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/save-file-from-url/send-request-via-document-send-or-sendasync-obtain-responsemessage.cs b/save-file-from-url/send-request-via-document-send-or-sendasync-obtain-responsemessage.cs new file mode 100644 index 0000000..cf4566c --- /dev/null +++ b/save-file-from-url/send-request-via-document-send-or-sendasync-obtain-responsemessage.cs @@ -0,0 +1,38 @@ +// Send the request via Document.Send (or SendAsync) and obtain a ResponseMessage. + +using System; + +class Program +{ + static void Main(string[] args) + { + try + { + // Create configuration + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + + // Create an empty HTMLDocument with the configuration + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(configuration)) + { + // Define the request URL + Aspose.Html.Url url = new Aspose.Html.Url("https://example.com"); + + // Create a request message + Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(url); + + // Send the request and obtain the response + Aspose.Html.Net.ResponseMessage response = document.Context.Network.Send(request); + + // Output basic response information + bool isSuccess = response.IsSuccess; + Console.WriteLine("Request succeeded: " + isSuccess); + byte[] contentBytes = response.Content.ReadAsByteArray(); + Console.WriteLine("Response content length: " + contentBytes.Length); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/send_request_via_document_send_or_sendasync_obtain_response_message.cs b/save-file-from-url/send_request_via_document_send_or_sendasync_obtain_response_message.cs deleted file mode 100644 index d898190..0000000 --- a/save-file-from-url/send_request_via_document_send_or_sendasync_obtain_response_message.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Send the request via Document.Send (or SendAsync) and obtain a ResponseMessage. - -using System; - -class Program -{ - static void Main() - { - try - { - string urlString = "https://example.com"; - Aspose.Html.Url url = new Aspose.Html.Url(urlString); - Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(url); - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument()) - { - Aspose.Html.Net.ResponseMessage response = document.Context.Network.Send(request); - System.Console.WriteLine("Status code: " + response.StatusCode); - byte[] contentBytes = response.Content.ReadAsByteArray(); - System.Console.WriteLine("Content length: " + contentBytes.Length); - string content = System.Text.Encoding.UTF8.GetString(contentBytes); - System.Console.WriteLine("First 200 characters:"); - System.Console.WriteLine(content.Substring(0, System.Math.Min(200, content.Length))); - } - } - catch (System.Exception ex) - { - System.Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/save-file-from-url/set-accept-language-header-in-requestmessage-to-request-localized-content.cs b/save-file-from-url/set-accept-language-header-in-requestmessage-to-request-localized-content.cs new file mode 100644 index 0000000..02bdee6 --- /dev/null +++ b/save-file-from-url/set-accept-language-header-in-requestmessage-to-request-localized-content.cs @@ -0,0 +1,43 @@ +// Set Accept-Language header in RequestMessage to request localized content. + +using System; +using Aspose.Html; +using Aspose.Html.Net; +using Aspose.Html.Services; +using Aspose.Html.Saving; +using Aspose.Html.Converters; + +class AcceptLanguageHandler : Aspose.Html.Net.MessageHandler +{ + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + context.Request.Headers["Accept-Language"] = "en-US,en;q=0.9"; + Next(context); + } +} + +class Program +{ + static void Main(string[] args) + { + try + { + var configuration = new Aspose.Html.Configuration(); + var network = configuration.GetService(); + network.MessageHandlers.Add(new AcceptLanguageHandler()); + + string url = "https://example.com"; + using (var document = new Aspose.Html.HTMLDocument(url, configuration)) + { + var options = new Aspose.Html.Saving.PdfSaveOptions(); + string outputPath = "output.pdf"; + Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); + Console.WriteLine("Conversion completed successfully."); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/set_custom_user_agent_header_request_message_before_downloading.cs b/save-file-from-url/set-custom-user-agent-header-requestmessage-before-downloading.cs similarity index 77% rename from save-file-from-url/set_custom_user_agent_header_request_message_before_downloading.cs rename to save-file-from-url/set-custom-user-agent-header-requestmessage-before-downloading.cs index d9ede9c..2e42aa7 100644 --- a/save-file-from-url/set_custom_user_agent_header_request_message_before_downloading.cs +++ b/save-file-from-url/set-custom-user-agent-header-requestmessage-before-downloading.cs @@ -1,12 +1,6 @@ // Set custom User-Agent header in RequestMessage before downloading. using System; -using System.IO; -using Aspose.Html; -using Aspose.Html.Net; -using Aspose.Html.Services; -using Aspose.Html.Saving; -using Aspose.Html.Converters; class Program { @@ -14,24 +8,23 @@ static void Main() { try { - string url = "https://example.com"; - string outputPath = "output.pdf"; - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); Aspose.Html.Services.INetworkService network = configuration.GetService(); network.MessageHandlers.Add(new UserAgentHandler()); + string url = "https://example.com"; using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) { Aspose.Html.Saving.PdfSaveOptions options = new Aspose.Html.Saving.PdfSaveOptions(); + string outputPath = "output.pdf"; Aspose.Html.Converters.Converter.ConvertHTML(document, options, outputPath); } - System.Console.WriteLine("Conversion completed successfully."); + Console.WriteLine("Conversion completed successfully."); } catch (Exception ex) { - System.Console.WriteLine("Error: " + ex.Message); + Console.WriteLine("Error: " + ex.Message); } } } diff --git a/save-file-from-url/set_http_method_get_request_message.cs b/save-file-from-url/set-http-method-get-requestmessage.cs similarity index 65% rename from save-file-from-url/set_http_method_get_request_message.cs rename to save-file-from-url/set-http-method-get-requestmessage.cs index 39e712e..8b4eb7a 100644 --- a/save-file-from-url/set_http_method_get_request_message.cs +++ b/save-file-from-url/set-http-method-get-requestmessage.cs @@ -8,24 +8,21 @@ static void Main() { try { - // Create configuration Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - // Create request and set HTTP method to GET using (Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage("https://example.com")) { request.Method = Aspose.Html.Net.HttpMethod.Get; - // Load the HTML document using the request using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(request, configuration)) { - Console.WriteLine("Document loaded. Title: " + document.Title); + System.Console.WriteLine("Document title: " + document.Title); } } } - catch (Exception ex) + catch (System.Exception ex) { - Console.WriteLine("Error: " + ex.Message); + System.Console.WriteLine("Error: " + ex.Message); } } } \ No newline at end of file diff --git a/save-file-from-url/set-referer-header-requestmessage-before-sending-request.cs b/save-file-from-url/set-referer-header-requestmessage-before-sending-request.cs new file mode 100644 index 0000000..8f17d54 --- /dev/null +++ b/save-file-from-url/set-referer-header-requestmessage-before-sending-request.cs @@ -0,0 +1,37 @@ +// Set the Referer header in RequestMessage before sending the request. + +using System; + +class Program +{ + static void Main() + { + try + { + var configuration = new Aspose.Html.Configuration(); + var networkService = configuration.GetService(); + networkService.MessageHandlers.Add(new RefererHeaderHandler()); + + string url = "https://www.example.org/"; + using (var document = new Aspose.Html.HTMLDocument(url, configuration)) + { + string outputPath = "output.html"; + document.Save(outputPath); + Console.WriteLine($"Document saved to {outputPath}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} + +class RefererHeaderHandler : Aspose.Html.Net.MessageHandler +{ + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + context.Request.Headers["Referer"] = "https://example.com/"; + Next(context); + } +} \ No newline at end of file diff --git a/save-file-from-url/set_accept_language_header_in_requestmessage_to_request_localized_content.cs b/save-file-from-url/set_accept_language_header_in_requestmessage_to_request_localized_content.cs deleted file mode 100644 index df2dbf3..0000000 --- a/save-file-from-url/set_accept_language_header_in_requestmessage_to_request_localized_content.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Set Accept-Language header in RequestMessage to request localized content. - -using System; - -class AcceptLanguageHandler : Aspose.Html.Net.MessageHandler -{ - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - context.Request.Headers["Accept-Language"] = "fr-FR"; - Next(context); - } -} - -class Program -{ - static void Main() - { - try - { - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - Aspose.Html.Services.INetworkService network = configuration.GetService(); - network.MessageHandlers.Add(new AcceptLanguageHandler()); - - string url = "https://example.com"; - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) - { - string outputPath = "output.html"; - document.Save(outputPath); - } - - Console.WriteLine("Document saved successfully."); - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/save-file-from-url/set_referer_header_in_requestmessage_before_sending_request.cs b/save-file-from-url/set_referer_header_in_requestmessage_before_sending_request.cs deleted file mode 100644 index 8172022..0000000 --- a/save-file-from-url/set_referer_header_in_requestmessage_before_sending_request.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Set the Referer header in RequestMessage before sending the request. - -using System; -using Aspose.Html; -using Aspose.Html.Net; -using Aspose.Html.Services; - -class RefererHandler : Aspose.Html.Net.MessageHandler -{ - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - context.Request.Headers["Referer"] = "https://example.com/"; - Next(context); - } -} - -class Program -{ - static void Main(string[] args) - { - try - { - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - Aspose.Html.Services.INetworkService networkService = configuration.GetService(); - networkService.MessageHandlers.Add(new RefererHandler()); - - string url = "https://www.example.com/"; - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) - { - string outputPath = "output.html"; - document.Save(outputPath); - Console.WriteLine("Document saved to: " + outputPath); - } - } - catch (Exception ex) - { - Console.WriteLine("Error: " + ex.Message); - } - } -} \ No newline at end of file diff --git a/save-file-from-url/use-cancellation-token-allow-asynchronous-download-operation-cancelled-by-user.cs b/save-file-from-url/use-cancellation-token-allow-asynchronous-download-operation-cancelled-by-user.cs new file mode 100644 index 0000000..a28944d --- /dev/null +++ b/save-file-from-url/use-cancellation-token-allow-asynchronous-download-operation-cancelled-by-user.cs @@ -0,0 +1,50 @@ +// Use a cancellation token to allow the asynchronous download operation to be cancelled by the user. + +using System; +using System.Threading; +using System.Threading.Tasks; + +class Program +{ + static void Main() + { + try + { + string url = "https://example.com"; + using (CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(5))) + { + CancellationToken token = cts.Token; + + Task downloadTask = Task.Run(() => + { + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument()) + { + Aspose.Html.Url aspUrl = new Aspose.Html.Url(url); + Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(aspUrl); + Aspose.Html.Net.ResponseMessage response = document.Context.Network.Send(request); + if (response.IsSuccess) + { + byte[] contentBytes = response.Content.ReadAsByteArray(); + return contentBytes; + } + else + { + throw new Exception($"Request failed with status code {response.StatusCode}"); + } + } + }, token); + + byte[] result = downloadTask.GetAwaiter().GetResult(); + Console.WriteLine($"Downloaded {result.Length} bytes."); + } + } + catch (OperationCanceledException) + { + Console.WriteLine("Download was cancelled."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/use-memorystream-temporarily-hold-response-data-before-writing-to-disk-validation.cs b/save-file-from-url/use-memorystream-temporarily-hold-response-data-before-writing-to-disk-validation.cs new file mode 100644 index 0000000..01e3195 --- /dev/null +++ b/save-file-from-url/use-memorystream-temporarily-hold-response-data-before-writing-to-disk-validation.cs @@ -0,0 +1,80 @@ +// Use a MemoryStream to temporarily hold the response data before writing to disk for validation. + +using System; +using System.IO; +using System.Collections.Generic; + +class MemoryStreamProvider : Aspose.Html.IO.ICreateStreamProvider, IDisposable +{ + public List Streams = new List(); + + public Stream GetStream(string name, string extension) + { + var ms = new MemoryStream(); + Streams.Add(ms); + return ms; + } + + public Stream GetStream(string name, string extension, int page) + { + var ms = new MemoryStream(); + Streams.Add(ms); + return ms; + } + + public void ReleaseStream(Stream stream) + { + // No action needed + } + + public void Dispose() + { + foreach (var s in Streams) + { + s.Dispose(); + } + } +} + +class Program +{ + static void Main() + { + try + { + string htmlPath = "sample.html"; + string outputPath = "output.pdf"; + + if (!File.Exists(htmlPath)) + { + File.WriteAllText(htmlPath, "Sample

Hello, Aspose.HTML!

"); + } + + var provider = new MemoryStreamProvider(); + + var document = new Aspose.Html.HTMLDocument(htmlPath); + var options = new Aspose.Html.Saving.PdfSaveOptions(); + + Aspose.Html.Converters.Converter.ConvertHTML(document, options, provider); + + if (provider.Streams.Count > 0) + { + MemoryStream resultStream = provider.Streams[0]; + resultStream.Position = 0; + using (FileStream fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) + { + resultStream.CopyTo(fileStream); + } + } + + provider.Dispose(); + document.Dispose(); + + Console.WriteLine("Conversion completed successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/use-using-block-ensure-requestmessage-responsemessage-disposed-after-operation.cs b/save-file-from-url/use-using-block-ensure-requestmessage-responsemessage-disposed-after-operation.cs new file mode 100644 index 0000000..439bb65 --- /dev/null +++ b/save-file-from-url/use-using-block-ensure-requestmessage-responsemessage-disposed-after-operation.cs @@ -0,0 +1,60 @@ +// Use a using block to ensure RequestMessage and ResponseMessage are disposed after the operation. + +using System; +using System.Collections.Generic; +using Aspose.Html; +using Aspose.Html.Net; +using Aspose.Html.Services; + +public sealed class LoggingHandler : Aspose.Html.Net.MessageHandler +{ + private readonly List _messages = new List(); + public IReadOnlyList Messages => _messages.AsReadOnly(); + + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + // Set a timeout for the request + context.Request.Timeout = TimeSpan.FromSeconds(10); + + // Ensure request and response are disposed after processing + using (var request = context.Request) + using (var response = context.Response) + { + Next(context); + _messages.Add($"Request {request.RequestUri} returned status {response.StatusCode}"); + } + } +} + +public class Program +{ + public static void Main() + { + try + { + // Create configuration and obtain network service + var configuration = new Aspose.Html.Configuration(); + var networkService = configuration.GetService(); + + // Add custom message handler + var handler = new LoggingHandler(); + networkService.MessageHandlers.Add(handler); + + // Load a document using the configuration (network requests will be logged) + using (var document = new Aspose.Html.HTMLDocument("https://example.com", configuration)) + { + // Document processing can be done here if needed + } + + // Output logged messages + foreach (var message in handler.Messages) + { + Console.WriteLine(message); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/use_cancellation_token_to_allow_asynchronous_download_operation_cancellation_by_user.cs b/save-file-from-url/use_cancellation_token_to_allow_asynchronous_download_operation_cancellation_by_user.cs deleted file mode 100644 index ba4af34..0000000 --- a/save-file-from-url/use_cancellation_token_to_allow_asynchronous_download_operation_cancellation_by_user.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Use a cancellation token to allow the asynchronous download operation to be cancelled by the user. - -namespace Example -{ - class Program - { - static async System.Threading.Tasks.Task Main(string[] args) - { - try - { - string urlString = "https://example.com"; - string outputPath = "downloaded.html"; - - using (System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource()) - { - cts.CancelAfter(System.TimeSpan.FromSeconds(5)); - - await System.Threading.Tasks.Task.Run(() => - { - cts.Token.ThrowIfCancellationRequested(); - - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument()) - { - Aspose.Html.Url url = new Aspose.Html.Url(urlString); - Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(url); - Aspose.Html.Net.ResponseMessage response = document.Context.Network.Send(request); - if (!response.IsSuccess) - { - throw new System.Exception($"Request failed with status code {response.StatusCode}"); - } - - byte[] contentBytes = response.Content.ReadAsByteArray(); - System.IO.File.WriteAllBytes(outputPath, contentBytes); - } - }, cts.Token); - } - - System.Console.WriteLine("Download completed successfully."); - } - catch (System.OperationCanceledException) - { - System.Console.WriteLine("Download was cancelled."); - } - catch (System.Exception ex) - { - System.Console.WriteLine($"Error: {ex.Message}"); - } - } - } -} \ No newline at end of file diff --git a/save-file-from-url/validate-saved-file-exists-and-size-matches-content-length-header.cs b/save-file-from-url/validate-saved-file-exists-and-size-matches-content-length-header.cs new file mode 100644 index 0000000..4db8f47 --- /dev/null +++ b/save-file-from-url/validate-saved-file-exists-and-size-matches-content-length-header.cs @@ -0,0 +1,64 @@ +// Validate that the saved file exists and its size matches the Content-Length header. + +using System; + +class Program +{ + static void Main() + { + try + { + // URL of a sample HTML page (Content-Length header is expected) + string url = "https://www.example.com"; + + // Download content + System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); + System.Net.Http.HttpResponseMessage response = client.GetAsync(url).Result; + if (!response.IsSuccessStatusCode) + throw new Exception($"Failed to download content. Status code: {response.StatusCode}"); + + // Get Content-Length header + if (!response.Content.Headers.ContentLength.HasValue) + throw new Exception("Content-Length header is missing in the response."); + + long contentLength = response.Content.Headers.ContentLength.Value; + + // Read content as byte array + byte[] data = response.Content.ReadAsByteArrayAsync().Result; + + // Save to file + string htmlPath = "downloaded.html"; + System.IO.File.WriteAllBytes(htmlPath, data); + + // Validate file existence + if (!System.IO.File.Exists(htmlPath)) + throw new Exception("Saved HTML file does not exist."); + + // Validate file size matches Content-Length + long fileSize = new System.IO.FileInfo(htmlPath).Length; + if (fileSize != contentLength) + throw new Exception($"File size ({fileSize}) does not match Content-Length header ({contentLength})."); + + System.Console.WriteLine("HTML file saved and size matches Content-Length header."); + + // Convert saved HTML to PDF using Aspose.HTML + string pdfPath = "output.pdf"; + Aspose.Html.Saving.PdfSaveOptions options = new Aspose.Html.Saving.PdfSaveOptions(); + Aspose.Html.Converters.Converter.ConvertHTML(htmlPath, options, pdfPath); + + // Verify PDF conversion + if (!System.IO.File.Exists(pdfPath)) + throw new Exception("PDF conversion failed: output file not found."); + + long pdfSize = new System.IO.FileInfo(pdfPath).Length; + if (pdfSize == 0) + throw new Exception("PDF conversion resulted in an empty file."); + + System.Console.WriteLine("PDF conversion succeeded and output file is valid."); + } + catch (Exception ex) + { + System.Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/validate_saved_file_exists_and_size_matches_content_length_header.cs b/save-file-from-url/validate_saved_file_exists_and_size_matches_content_length_header.cs deleted file mode 100644 index 6bd1645..0000000 --- a/save-file-from-url/validate_saved_file_exists_and_size_matches_content_length_header.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Validate that the saved file exists and its size matches the Content-Length header. - -using System; -using System.IO; -using System.Net.Http; -using System.Threading.Tasks; -using Aspose.Html; - -class Program -{ - static async Task Main(string[] args) - { - try - { - // URL of the file to download - string url = "https://www.w3.org/TR/PNG/iso_8859-1.txt"; - // Local path to save the downloaded file - string localPath = "downloaded.txt"; - - using (HttpClient client = new HttpClient()) - { - // Get Content-Length header via HEAD request - HttpRequestMessage headRequest = new HttpRequestMessage(HttpMethod.Head, url); - HttpResponseMessage headResponse = await client.SendAsync(headRequest); - headResponse.EnsureSuccessStatusCode(); - long? contentLength = headResponse.Content.Headers.ContentLength; - - // Download the file content - HttpResponseMessage getResponse = await client.GetAsync(url); - getResponse.EnsureSuccessStatusCode(); - byte[] data = await getResponse.Content.ReadAsByteArrayAsync(); - - // Save to local file - File.WriteAllBytes(localPath, data); - - // Validate file existence - if (!File.Exists(localPath)) - { - throw new FileNotFoundException($"The file '{localPath}' was not found after saving."); - } - - // Validate file size matches Content-Length header (if header is present) - long fileSize = new FileInfo(localPath).Length; - if (contentLength.HasValue && fileSize != contentLength.Value) - { - throw new InvalidOperationException($"File size ({fileSize} bytes) does not match Content-Length header ({contentLength.Value} bytes)."); - } - - // Load the saved file with Aspose.HTML to demonstrate usage - using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(localPath)) - { - // Simple operation: get text content length - string text = document.Body.TextContent; - Console.WriteLine($"Conversion verification passed. Text length: {text.Length}"); - } - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } -} \ No newline at end of file diff --git a/save-file-from-url/verify-http-response-status-code-equals-200-before-processing.cs b/save-file-from-url/verify-http-response-status-code-equals-200-before-processing.cs new file mode 100644 index 0000000..f255061 --- /dev/null +++ b/save-file-from-url/verify-http-response-status-code-equals-200-before-processing.cs @@ -0,0 +1,49 @@ +// Verify the HTTP response status code equals 200 before processing. + +using System; + +class StatusCheckHandler : Aspose.Html.Net.MessageHandler +{ + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + // Perform the request + Next(context); + // Verify HTTP status code is 200 (OK) + if (context.Response.StatusCode != System.Net.HttpStatusCode.OK) + { + throw new Exception($"HTTP request failed with status code {(int)context.Response.StatusCode}"); + } + } +} + +class Program +{ + static void Main(string[] args) + { + try + { + // Create Aspose.HTML configuration + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + + // Obtain the network service from the configuration + Aspose.Html.Services.INetworkService network = configuration.GetService(); + + // Add the custom status‑check handler + network.MessageHandlers.Add(new StatusCheckHandler()); + + // URL to load (replace with any reachable URL) + string url = "https://example.com"; + + // Load the HTML document using the configuration with the handler attached + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) + { + // Example processing: output the document title + Console.WriteLine("Title: " + document.Title); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/verify-response-content-type-header-matches-expected-file-type-before-saving.cs b/save-file-from-url/verify-response-content-type-header-matches-expected-file-type-before-saving.cs new file mode 100644 index 0000000..e3b0151 --- /dev/null +++ b/save-file-from-url/verify-response-content-type-header-matches-expected-file-type-before-saving.cs @@ -0,0 +1,91 @@ +// Verify the response Content-Type header matches the expected file type before saving. + +using System; +using System.Collections.Generic; +using System.IO; + +class MyHandler : Aspose.Html.Net.MessageHandler +{ + public static List capturedHeaders = new List(); + + public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) + { + Next(context); + foreach (object headerItem in context.Response.Headers) + { + if (headerItem != null) + { + capturedHeaders.Add(headerItem.ToString()); + } + } + } +} + +class Program +{ + static string GetMimeTypeForDocumentOptions(object options) + { + if (options is Aspose.Html.Saving.PdfSaveOptions) + return "application/pdf"; + if (options is Aspose.Html.Saving.DocSaveOptions) + return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; + if (options is Aspose.Html.Saving.XpsSaveOptions) + return "application/vnd.ms-xpsdocument"; + return string.Empty; + } + + static void Main() + { + try + { + // Input URL and output file + string url = "https://example.com/sample.html"; + string outputPath = Path.Combine(Path.GetTempPath(), "output.pdf"); + + // Ensure output directory exists + string outputDir = Path.GetDirectoryName(outputPath); + if (!Directory.Exists(outputDir)) + Directory.CreateDirectory(outputDir); + + // Configure network service with custom handler to capture headers + Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); + Aspose.Html.Services.INetworkService networkService = configuration.GetService(); + networkService.MessageHandlers.Add(new MyHandler()); + + // Load HTML document from URL using the configuration + using (Aspose.Html.HTMLDocument document = new Aspose.Html.HTMLDocument(url, configuration)) + { + // Verify Content-Type header matches expected MIME type for PDF + string contentType = null; + foreach (string header in MyHandler.capturedHeaders) + { + if (header.StartsWith("Content-Type:", StringComparison.OrdinalIgnoreCase)) + { + int colonIndex = header.IndexOf(':'); + if (colonIndex >= 0 && colonIndex + 1 < header.Length) + { + contentType = header.Substring(colonIndex + 1).Trim(); + } + break; + } + } + + Aspose.Html.Saving.PdfSaveOptions pdfOptions = new Aspose.Html.Saving.PdfSaveOptions(); + string expectedMime = GetMimeTypeForDocumentOptions(pdfOptions); + + if (!string.IsNullOrEmpty(contentType) && !string.Equals(contentType, expectedMime, StringComparison.OrdinalIgnoreCase)) + { + Console.WriteLine($"Warning: Content-Type header '{contentType}' does not match expected '{expectedMime}'."); + } + + // Convert and save the document as PDF + Aspose.Html.Converters.Converter.ConvertHTML(document, pdfOptions, outputPath); + Console.WriteLine($"Document saved to: {outputPath}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/verify_http_response_status_code_equals_200_before_processing.cs b/save-file-from-url/verify_http_response_status_code_equals_200_before_processing.cs deleted file mode 100644 index e9097ab..0000000 --- a/save-file-from-url/verify_http_response_status_code_equals_200_before_processing.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Verify the HTTP response status code equals 200 before processing. - -using System; - -public class Program -{ - public static void Main(string[] args) - { - try - { - var configuration = new Aspose.Html.Configuration(); - var network = configuration.GetService(); - network.MessageHandlers.Add(new StatusCodeHandler()); - - string url = "https://example.com"; - using (var document = new Aspose.Html.HTMLDocument(url, configuration)) - { - System.Console.WriteLine("Document title: " + document.Title); - } - } - catch (Exception ex) - { - System.Console.Error.WriteLine("Error: " + ex.Message); - } - } -} - -public class StatusCodeHandler : Aspose.Html.Net.MessageHandler -{ - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - Next(context); - if (context.Response.StatusCode != System.Net.HttpStatusCode.OK) - { - throw new InvalidOperationException($"HTTP request failed with status code {context.Response.StatusCode}"); - } - } -} \ No newline at end of file diff --git a/save-file-from-url/verify_response_content_type_header_matches_expected_file_type_before_saving.cs b/save-file-from-url/verify_response_content_type_header_matches_expected_file_type_before_saving.cs deleted file mode 100644 index 8b2290f..0000000 --- a/save-file-from-url/verify_response_content_type_header_matches_expected_file_type_before_saving.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Verify the response Content-Type header matches the expected file type before saving. - -using System; -using System.Collections.Generic; -using System.IO; -using Aspose.Html; -using Aspose.Html.Net; -using Aspose.Html.Services; -using Aspose.Html.Saving; - -class ResponseHeaderHandler : Aspose.Html.Net.MessageHandler -{ - public static List capturedHeaders = new List(); - public override void Invoke(Aspose.Html.Net.INetworkOperationContext context) - { - Next(context); - foreach (object headerItem in context.Response.Headers) - { - if (headerItem != null) - { - capturedHeaders.Add(headerItem.ToString()); - } - } - } -} - -class Program -{ - static void Main() - { - try - { - // Input URL and output file - string url = "https://example.com/sample.pdf"; - string outputPath = Path.Combine(Path.GetTempPath(), "downloaded_sample.pdf"); - - // Prepare configuration with custom message handler - Aspose.Html.Configuration configuration = new Aspose.Html.Configuration(); - Aspose.Html.Services.INetworkService networkService = configuration.GetService(); - networkService.MessageHandlers.Add(new ResponseHeaderHandler()); - - // Create a temporary document to access the network context - using (Aspose.Html.HTMLDocument tempDoc = new Aspose.Html.HTMLDocument()) - { - // Build request and send it - Aspose.Html.Url requestUrl = new Aspose.Html.Url(url); - Aspose.Html.Net.RequestMessage request = new Aspose.Html.Net.RequestMessage(requestUrl); - Aspose.Html.Net.ResponseMessage response = tempDoc.Context.Network.Send(request); - - if (!response.IsSuccess) - { - throw new Exception($"Request failed with status code {response.StatusCode}."); - } - - // Read response content - byte[] contentBytes = response.Content.ReadAsByteArray(); - - // Determine expected MIME type for PDF output - Aspose.Html.Saving.PdfSaveOptions pdfOptions = new Aspose.Html.Saving.PdfSaveOptions(); - string expectedMime = GetMimeTypeForDocumentOptions(pdfOptions); - - // Extract Content-Type header from captured headers - string contentTypeHeader = null; - foreach (string header in ResponseHeaderHandler.capturedHeaders) - { - if (header.StartsWith("Content-Type:", StringComparison.OrdinalIgnoreCase)) - { - contentTypeHeader = header.Substring("Content-Type:".Length).Trim(); - break; - } - } - - if (contentTypeHeader == null) - { - throw new Exception("Content-Type header not found in response."); - } - - // Verify that the response Content-Type matches the expected MIME type - if (!contentTypeHeader.StartsWith(expectedMime, StringComparison.OrdinalIgnoreCase)) - { - throw new Exception($"MIME type mismatch. Expected: {expectedMime}, Received: {contentTypeHeader}"); - } - - // Save the content to file - System.IO.File.WriteAllBytes(outputPath, contentBytes); - Console.WriteLine($"File saved successfully to: {outputPath}"); - } - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } - - static string GetMimeTypeForDocumentOptions(object options) - { - if (options is Aspose.Html.Saving.PdfSaveOptions) - return "application/pdf"; - if (options is Aspose.Html.Saving.DocSaveOptions) - return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; - if (options is Aspose.Html.Saving.XpsSaveOptions) - return "application/vnd.ms-xpsdocument"; - return "application/octet-stream"; - } -} \ No newline at end of file diff --git a/save-file-from-url/write-unit-tests-mock-http-response-verify-file-saving-logic-correctly.cs b/save-file-from-url/write-unit-tests-mock-http-response-verify-file-saving-logic-correctly.cs new file mode 100644 index 0000000..46f2ec2 --- /dev/null +++ b/save-file-from-url/write-unit-tests-mock-http-response-verify-file-saving-logic-correctly.cs @@ -0,0 +1,76 @@ +// Write unit tests that mock the HTTP response to verify the file saving logic works correctly. + +using System; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using Aspose.Html; +using Aspose.Html.Converters; +using Aspose.Html.Saving; + +class Program +{ + static void Main() + { + try + { + // Prepare sample HTML with a data URI image + string html = ""; + + // Create a temporary directory for extracted resources and output + string tempDir = Path.Combine(Path.GetTempPath(), "AsposeHtmlTest"); + Directory.CreateDirectory(tempDir); + + // Replace data URIs with physical files + Regex regex = new Regex(@"data:(?[^;]+);(?[^,]+),(?.+)", RegexOptions.IgnoreCase); + int index = 0; + string rewrittenHtml = regex.Replace(html, match => + { + string mediaType = match.Groups["mediaType"].Value; + string encodingMarker = match.Groups["encodingMarker"].Value; + string payload = match.Groups["payload"].Value; + byte[] bytes = string.Equals(encodingMarker, "base64", StringComparison.OrdinalIgnoreCase) + ? Convert.FromBase64String(payload) + : Encoding.UTF8.GetBytes(Uri.UnescapeDataString(payload)); + string extension = mediaType.Contains("png") ? ".png" : + (mediaType.Contains("jpeg") ? ".jpg" : ".bin"); + string filePath = Path.Combine(tempDir, "datauri_" + (index++) + extension); + File.WriteAllBytes(filePath, bytes); + return filePath.Replace("\\", "/"); + }); + + // Base URI for the document + string baseUri = tempDir.Replace("\\", "/") + "/"; + + // Load the HTML document from the rewritten content + using (HTMLDocument document = new HTMLDocument(rewrittenHtml, baseUri)) + { + // Set PDF save options + PdfSaveOptions options = new PdfSaveOptions(); + + // Define output PDF path + string pdfPath = Path.Combine(tempDir, "output.pdf"); + + // Perform conversion + Aspose.Html.Converters.Converter.ConvertHTML(document, options, pdfPath); + + // Verify the PDF file was created and is not empty + if (!File.Exists(pdfPath)) + { + throw new Exception("PDF file was not created."); + } + + if (new FileInfo(pdfPath).Length == 0) + { + throw new Exception("PDF file is empty."); + } + + Console.WriteLine("Conversion verification passed. PDF saved at: " + pdfPath); + } + } + catch (Exception ex) + { + Console.WriteLine("Error: " + ex.Message); + } + } +} \ No newline at end of file diff --git a/save-file-from-url/write_unit_tests_mock_http_response_verify_file_saving_logic_correctly.cs b/save-file-from-url/write_unit_tests_mock_http_response_verify_file_saving_logic_correctly.cs deleted file mode 100644 index 93dd335..0000000 --- a/save-file-from-url/write_unit_tests_mock_http_response_verify_file_saving_logic_correctly.cs +++ /dev/null @@ -1,101 +0,0 @@ -// Write unit tests that mock the HTTP response to verify the file saving logic works correctly. - -using System; -using System.IO; -using System.Net; -using System.Net.Http; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -class Program -{ - static void Main() - { - try - { - RunTestAsync().GetAwaiter().GetResult(); - } - catch (Exception ex) - { - Console.WriteLine($"Error: {ex.Message}"); - } - } - - private static async Task RunTestAsync() - { - // Arrange - string testUrl = "http://example.com/test"; - byte[] expectedContent = Encoding.UTF8.GetBytes("Hello World"); - string tempDir = Path.Combine(Path.GetTempPath(), "AsposeHtmlMockTest"); - Directory.CreateDirectory(tempDir); - string outputPath = Path.Combine(tempDir, "output.bin"); - - var mockHandler = new MockHttpMessageHandler(testUrl, expectedContent); - using var httpClient = new HttpClient(mockHandler); - - // Act - await SaveContentAsync(testUrl, outputPath, httpClient); - - // Assert - if (!File.Exists(outputPath)) - throw new InvalidOperationException("Output file was not created."); - - byte[] actualContent = await File.ReadAllBytesAsync(outputPath); - if (actualContent.Length == 0) - throw new InvalidOperationException("Output file is empty."); - - if (actualContent.Length != expectedContent.Length) - throw new InvalidOperationException("Output file size does not match expected size."); - - for (int i = 0; i < actualContent.Length; i++) - { - if (actualContent[i] != expectedContent[i]) - throw new InvalidOperationException("Output file content does not match expected content."); - } - - Console.WriteLine("File saving verification passed."); - } - - private static async Task SaveContentAsync(string url, string outputPath, HttpClient client) - { - using HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); - response.EnsureSuccessStatusCode(); - - using Stream contentStream = await response.Content.ReadAsStreamAsync(); - using FileStream fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.None); - await contentStream.CopyToAsync(fileStream); - } - - private class MockHttpMessageHandler : HttpMessageHandler - { - private readonly string _expectedUrl; - private readonly byte[] _responseContent; - - public MockHttpMessageHandler(string expectedUrl, byte[] responseContent) - { - _expectedUrl = expectedUrl; - _responseContent = responseContent; - } - - protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - if (request.RequestUri?.ToString() != _expectedUrl) - { - var notFound = new HttpResponseMessage(HttpStatusCode.NotFound) - { - RequestMessage = request - }; - return Task.FromResult(notFound); - } - - var response = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new ByteArrayContent(_responseContent), - RequestMessage = request - }; - response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); - return Task.FromResult(response); - } - } -} \ No newline at end of file