Przejdź do treści stopki
POMOC .NET

.NET Aspire (Jak to działa dla programistów)

.NET Aspire stands as a decisive, cloud-ready stack framework tailored for constructing observable, production-ready, distributed applications. Delivered through a set of NuGet packages, Aspire efficiently addresses various cloud-native service discovery considerations and aims to provide consistent setup patterns. In the realm of .NET cloud-native apps, the norm involves smaller, interlinked components or microservices in distributed apps, departing from the traditional monolithic code structure. These applications typically rely on numerous services like databases, messaging systems, cloud resources, and caching.

Distributed applications, in this context, leverage computational resources spanning multiple nodes, such as containers operating on diverse hosts. Effective communication across network boundaries is essential for these nodes to collaboratively deliver responses to end users. Specifically, a cloud-native distributed application, is a distinct category within distributed applications, capitalizing on the scalability, resilience, and manageability inherent in cloud-native app infrastructures.

In this article, we will discuss the .NET Aspire components to create a web application. Also, we will use the IronPDF library to create and download PDF files in the Aspire .NET project component.

1. Introduction to .NET Aspire

.NET Aspire application stands as a purposeful initiative aimed at enhancing the development experience for .NET cloud-native apps within the .NET ecosystem. It introduces a cohesive and opinionated suite of tools and design patterns crafted to facilitate the seamless construction and operation of distributed apps. The core objectives of .NET Aspire starter application encompass:

  1. Orchestration: .NET Aspire orchestration assists features robust capabilities for orchestrating multi-project applications and their intricate dependencies. This functionality ensures smooth execution and seamless connectivity between diverse components of .NET projects.
  2. Components: The components offered by .NET Aspire orchestration are encapsulated within NuGet packages, representing widely utilized services like local Redis container resource or Postgres. These components are characterized by standardized interfaces, guaranteeing consistent and seamless integration with your application. By leveraging these pre-packaged components, developers can expedite the development process and maintain a higher level of interoperability and configurable cloud-native applications using .NET Aspire project templates.
  3. Tooling: .NET Aspire starter templates incorporate a comprehensive set of tools tailored to streamline the development workflow. Project templates and tooling experiences are thoughtfully integrated into Visual Studio and the .NET CLI, empowering developers to create and interact with .NET Aspire apps effortlessly. This inclusive tooling framework enhances productivity and provides a cohesive environment for developing and managing .NET Aspire app configurations and project templates.

In essence, .NET Aspire serves as a holistic solution, addressing key aspects of specific cloud-native concerns such as orchestration, component integration, and tooling, all aimed at elevating the efficiency and consistency of building and deploying .NET cloud-native applications.

2. Getting Started with .NET Aspire

Before engaging with .NET Aspire, ensure that the following components are locally installed:

  1. .NET 8.0: Make sure to have .NET 8.0 installed on your system.
  2. .NET Aspire Workload: Acquire the .NET Aspire workload by either utilizing the VS installer or executing the dotnet workload install aspire command.
  3. Integrated Developer Environment (IDE) or Code Editor: Visual Studio 2022 should be installed on the system beforehand.

If all these requirements are met, you are good to go with the development of your first .NET Aspire components that handle apps.

3. Create a New .NET Aspire Project

To create .NET Aspire apps, follow the following steps.

  1. Open Visual Studio and click on Create a new project.
  2. Pojawi się nowe okno. In this new window, search Aspire on the search bar.
  3. A list will appear below, from that list select the Aspire Starter apphost project and package references and click on Next.
  4. A new window will appear. In this new window write the project name and click on Next.
  5. In this window select the target framework and click on the Create button.

The .NET Aspire application will be created in a few seconds, and you will be good to get started with the development and customization.

4. Running and Testing the .NET Aspire application

Once the project is created just click on the Run button, it will take some time to create a build and after that, it will open a web page of our Aspire web application Home page.

This home page will contain our .NET Aspire Cloud-native apps stack for building observable production-ready .NET Aspire starter applications.

.NET Aspire (How it Works For Developers): Figure 1 - Aspire Home Page

Now click on the links to interact with .NET. For now click on the .NET Aspire web frontend project and package references. It will open the new webpage with a different port name.

.NET Aspire (How it Works For Developers): Figure 2 - New Webpage

5. Introducing IronPDF C

IronPDF documentation describes it as a powerful and versatile C# library that empowers developers to effortlessly integrate advanced PDF generation and manipulation capabilities into their applications. Developed by Iron Software, this feature-rich library offers a comprehensive set of tools for creating, modifying, and rendering PDF documents directly within C# applications.

With IronPDF, developers can seamlessly generate PDFs from various sources, such as HTML, images, and existing documents, while maintaining precise control over formatting and layout. Whether it's creating dynamic reports, converting HTML content to PDF, or adding annotations to existing documents, IronPDF streamlines the PDF handling process, making it an invaluable asset for C# developers seeking a reliable and efficient solution for their document management needs.

5.1. Instalacja IronPDF

To seamlessly install IronPDF, leverage the NuGet Package Manager within Visual Studio. The designated package for installation is titled IronPDF. Simply copy and paste the following command into the Package Manager Console and hit enter:

Install-Package IronPdf

5.2. Integrating IronPDF with Aspire Component

Integrating IronPDF with the Aspire component is the same as integrating with the Blazor web application because the Aspire components can use the Blazor application as a component. In this code example, we will change the code of the Counter Page to create and download a PDF file.

Open the counter.razor file and replace the code with the below code.

@page "/PrintPDF"
@rendermode InteractiveServer
@using IronPdf
<PageTitle>Print PDF</PageTitle>
<h1>IronPDF</h1>
<p role="status">Click on the button below to create and download the PDF file </p>
<button class="btn btn-primary" @onclick="IncrementCount">Print</button>
@code {
    private int currentCount = 0;

    /// <summary>
    /// Handles the click event of the "Print" button.
    /// This function will generate a PDF from an HTML string and prompt the user to download it.
    /// </summary>
    private void IncrementCount()
    {
        var renderer = new ChromePdfRenderer();
        // Create a PDF from an HTML string using C#
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
        // Export to a file using JavaScript Interop to initiate download
        JSRuntime.InvokeVoidAsync("saveAsFile", "output.pdf", Convert.ToBase64String(pdf.Stream.ToArray()));
    }
}
@page "/PrintPDF"
@rendermode InteractiveServer
@using IronPdf
<PageTitle>Print PDF</PageTitle>
<h1>IronPDF</h1>
<p role="status">Click on the button below to create and download the PDF file </p>
<button class="btn btn-primary" @onclick="IncrementCount">Print</button>
@code {
    private int currentCount = 0;

    /// <summary>
    /// Handles the click event of the "Print" button.
    /// This function will generate a PDF from an HTML string and prompt the user to download it.
    /// </summary>
    private void IncrementCount()
    {
        var renderer = new ChromePdfRenderer();
        // Create a PDF from an HTML string using C#
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
        // Export to a file using JavaScript Interop to initiate download
        JSRuntime.InvokeVoidAsync("saveAsFile", "output.pdf", Convert.ToBase64String(pdf.Stream.ToArray()));
    }
}
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: @page "/PrintPDF" @rendermode InteractiveServer using IronPdf <PageTitle> Print PDF</PageTitle> <h1> IronPDF</h1> <p role="status"> Click on the button below to create and download the PDF file </p> <button class="btn btn-primary" onclick="IncrementCount"> Print</button> @code
"btn btn-primary" onclick="IncrementCount"> Print</button> code
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Friend @page "/PrintPDF" @rendermode InteractiveServer using IronPdf <PageTitle> Print PDF</PageTitle> <h1> IronPDF</h1> <p role="status"> Click on the button below to create and download the PDF file </p> <button Class="btn btn-primary" onclick
"status"> Click on the button below [to] create [and] download the PDF file </p> <button Class="btn btn-primary" onclick
Private Private Friend page "/PrintPDF" rendermode InteractiveServer [using] IronPdf (Of PageTitle) Print PDF</PageTitle> (Of h1) IronPDF</h1> <p role="status"> Click on the button below [to] create [and] download the PDF file </p> <button Class
	Private currentCount As Integer = 0

	''' <summary>
	''' Handles the click event of the "Print" button.
	''' This function will generate a PDF from an HTML string and prompt the user to download it.
	''' </summary>
	Private Sub IncrementCount()
		Dim renderer = New ChromePdfRenderer()
		' Create a PDF from an HTML string using C#
		Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
		' Export to a file using JavaScript Interop to initiate download
		JSRuntime.InvokeVoidAsync("saveAsFile", "output.pdf", Convert.ToBase64String(pdf.Stream.ToArray()))
	End Sub
End Class
$vbLabelText   $csharpLabel

After that write the JavaScript code to download the PDF File. Write this code in the script tag in the scope of the HTML body tag. Below is the code to add to your project.

<script type="text/javascript">
    function saveAsFile(filename, bytesBase64) {
        if (navigator.msSaveBlob) {
            //Download document in Edge browser
            var data = window.atob(bytesBase64);
            var bytes = new Uint8Array(data.length);
            for (var i = 0; i < data.length; i++) {
                bytes[i] = data.charCodeAt(i);
            }
            var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
            navigator.msSaveBlob(blob, filename);
            window.navigator.msSaveOrOpenBlob(blob);
        }
        else {
            var link = document.createElement('a');
            link.download = filename;
            link.href = "data:application/octet-stream;base64," + bytesBase64;
            document.body.appendChild(link); // Needed for Firefox
            link.click();
            document.body.removeChild(link);
        }
    }
</script>
<script type="text/javascript">
    function saveAsFile(filename, bytesBase64) {
        if (navigator.msSaveBlob) {
            //Download document in Edge browser
            var data = window.atob(bytesBase64);
            var bytes = new Uint8Array(data.length);
            for (var i = 0; i < data.length; i++) {
                bytes[i] = data.charCodeAt(i);
            }
            var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
            navigator.msSaveBlob(blob, filename);
            window.navigator.msSaveOrOpenBlob(blob);
        }
        else {
            var link = document.createElement('a');
            link.download = filename;
            link.href = "data:application/octet-stream;base64," + bytesBase64;
            document.body.appendChild(link); // Needed for Firefox
            link.click();
            document.body.removeChild(link);
        }
    }
</script>
JAVASCRIPT

Just run the code after that it will look something like the below image.

.NET Aspire (How it Works For Developers): Figure 3 - Blazor

To create and download a PDF file click on the Print button. It will create and download the PDF file named output.pdf file.

.NET Aspire (How it Works For Developers): Figure 4 - PDF Download

6. Podsumowanie

.NET Aspire staje się kluczowym frameworkiem, zaprojektowanym specjalnie do tworzenia solidnych, obserwowalnych i rozproszonych aplikacji w środowisku chmury. Dzięki spójnemu zestawowi narzędzi i wzorców projektowych .NET Aspire upraszcza złożoność związaną z tworzeniem aplikacji natywnych dla chmury, oferując płynną koordynację, integrację komponentów oraz przyjazną dla użytkownika platformę narzędziową. Koncentrując się na skalowalności, odporności i łatwości zarządzania, .NET Aspire wpisuje się w zmianę paradygmatu w kierunku mikrousług i architektur rozproszonych.

Rozpoczynając pracę z .NET Aspire, programiści zyskują dostęp do kompleksowej Suite funkcji, od skoordynowanych aplikacji wieloprojektowych po standardowe komponenty zawarte w pakietach NuGet. Przestrzegając wymagań wstępnych i postępując zgodnie z prostymi krokami opisanymi w przewodniku, programiści mogą bez wysiłku tworzyć, uruchamiać i testować aplikacje .NET Aspire.

Ponadto integracja IronPDF z komponentami Aspire podkreśla rozszerzalność i wszechstronność frameworka, umożliwiając programistom płynne włączanie zaawansowanych funkcji generowania i manipulacji plikami PDF do ich aplikacji natywnych dla chmury. Ogólnie rzecz biorąc, .NET Aspire, dzięki jasno określonym celom i przyjaznemu dla użytkownika podejściu, stanowi cenne narzędzie dla programistów poszukujących wydajnego i spójnego rozwiązania do tworzenia i wdrażania aplikacji natywnych dla chmury w ekosystemie .NET.

Pełny samouczek dotyczący korzystania z IronPDF w aplikacjach internetowych Blazor można znaleźć na blogu IronPDF. Aby uzyskać bezpłatną wersję próbną IronPDF, odwiedź stronę licencyjną IronPDF i pobierz bezpłatną licencję probną.

Często Zadawane Pytania

Jak mogę przekonwertować HTML na PDF w języku C#?

Możesz użyć metody RenderHtmlAsPdf biblioteki IronPDF do konwersji ciągów HTML na pliki PDF. Możesz również konwertować pliki HTML na pliki PDF za pomocą metody RenderHtmlFileAsPdf.

Jaki jest cel .NET Aspire w tworzeniu aplikacji natywnych dla chmury?

.NET Aspire zostało zaprojektowane, aby pomóc programistom w tworzeniu obserwowalnych, gotowych do produkcji aplikacji rozproszonych. Zapewnia narzędzia do orkiestracji, integrację komponentów oraz kompleksowy zestaw narzędzi do zarządzania architekturami mikrousług w aplikacjach natywnych dla chmury.

W jaki sposób IronPDF integruje się z projektami .NET Aspire?

IronPDF można zintegrować z projektami .NET Aspire, aby zapewnić zaawansowane możliwości generowania i edycji plików PDF. Pozwala to programistom na płynne tworzenie plików PDF i zarządzanie nimi w ramach aplikacji natywnych dla chmury.

Jakie są typowe zastosowania IronPDF w aplikacjach internetowych?

IronPDF jest często używany w aplikacjach internetowych do generowania raportów PDF, konwersji treści HTML do formatu PDF oraz zarządzania przepływem dokumentów. Zapewnia programistom solidny zestaw narzędzi do obsługi zadań związanych z plikami PDF w aplikacjach .NET.

Jak mogę rozwiązywać problemy podczas korzystania z IronPDF w projekcie .NET?

Aby rozwiązać problemy związane z IronPDF, upewnij się, że pakiet NuGet jest poprawnie zainstalowany, a wszystkie zależności są prawidłowo odwołane. Sprawdź, czy w konsoli nie ma komunikatów o błędach, a w razie potrzeby zapoznaj się z dokumentacją IronPDF lub skontaktuj się z pomocą techniczną w celu uzyskania dalszych wskazówek.

Jakie są kluczowe komponenty frameworka .NET Aspire?

.NET Aspire oferuje funkcje koordynacji, gotowe komponenty przyspieszające tworzenie oprogramowania oraz zintegrowane narzędzia w ramach Visual Studio i .NET CLI — wszystko to zaprojektowano w celu usprawnienia tworzenia aplikacji natywnych dla chmury i zarządzania nimi.

Jakie zalety oferuje .NET Aspire dla architektury mikrousług?

.NET Aspire oferuje spójny wzorzec konfiguracji, solidną koordynację i płynną integrację komponentów, co ułatwia zarządzanie i wdrażanie architektur mikrousług w środowisku natywnym dla chmury.

Gdzie mogę dowiedzieć się więcej o korzystaniu z IronPDF w aplikacjach .NET?

Aby dowiedzieć się więcej o korzystaniu z IronPDF w aplikacjach .NET, odwiedź blog IronPDF oraz dokumentację, gdzie znajdziesz samouczki i przykłady. Zasoby te zawierają szczegółowe wskazówki dotyczące integracji i efektywnego wykorzystania IronPDF.

Jacob Mellor, Dyrektor Technologiczny @ Team Iron
Dyrektor ds. technologii

Jacob Mellor jest Chief Technology Officer w Iron Software i wizjonerskim inżynierem, pionierem technologii C# PDF. Jako pierwotny deweloper głównej bazy kodowej Iron Software, kształtuje architekturę produktów firmy od jej początku, przekształcając ją wspólnie z CEO Cameron Rimington w firmę liczą...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie