.NET HELP

.NET Aspire (How it Works For Developers)

Published January 4, 2024
Share:

.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 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. A new window will appear. 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 web frontend project and package references link. 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 is 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. Installing 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;
    private void IncrementCount()
    {
        var renderer = new ChromePdfRenderer();
        // Create a PDF from a HTML string using C#
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
        // Export to a file or Stream
        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;
    private void IncrementCount()
    {
        var renderer = new ChromePdfRenderer();
        // Create a PDF from a HTML string using C#
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
        // Export to a file or Stream
        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
	Private Sub IncrementCount()
		Dim renderer = New ChromePdfRenderer()
		' Create a PDF from a HTML string using C#
		Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
		' Export to a file or Stream
		JSRuntime.InvokeVoidAsync("saveAsFile", "output.pdf", Convert.ToBase64String(pdf.Stream.ToArray()))
	End Sub
End Class
VB   C#

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>
<script type="text/javascript"> [function] saveAsFile(filename, bytesBase64)
If True Then
		If navigator.msSaveBlob Then
			'Download document in Edge browser
			Dim data = window.atob(bytesBase64)
			Dim bytes = New Uint8Array(data.length)
			For i = 0 To data.length - 1
				bytes (i) = data.charCodeAt(i)
			Next i
			Dim blob As New Blob((bytes.buffer), { type:= "application/octet-stream" })
			navigator.msSaveBlob(blob, filename)
			window.navigator.msSaveOrOpenBlob(blob)
		Else
			Dim link = document.createElement("a"c)
			link.download = filename
			link.href = "data:application/octet-stream;base64," & bytesBase64
			document.body.appendChild(link) ' Needed for Firefox
			link.click()
			document.body.removeChild(link)
		End If
End If
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'</script>
VB   C#

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. Conclusion

.NET Aspire emerges as a pivotal framework, purposefully designed to develop robust, observable, and distributed applications in the cloud environment. By providing a cohesive set of tools and design patterns, .NET Aspire simplifies the complexities associated with building cloud-native applications, offering seamless orchestration, component integration, and a user-friendly tooling framework. With a focus on scalability, resilience, and manageability, .NET Aspire aligns with the paradigm shift towards microservices and distributed architectures.

As developers embark on their journey with .NET Aspire, they gain access to a comprehensive suite of features, from orchestrated multi-project applications to standardized components encapsulated in NuGet packages. By adhering to the prerequisites and following the straightforward steps outlined in the guide, developers can effortlessly create, run, and test .NET Aspire applications.

Furthermore, the integration of IronPDF into Aspire components showcases the extensibility and versatility of the framework, enabling developers to seamlessly incorporate advanced PDF generation and manipulation capabilities into their cloud-native applications. Overall, .NET Aspire, with its well-defined objectives and user-friendly approach, positions itself as a valuable asset for developers seeking an efficient and consistent solution for building and deploying cloud-native applications within the .NET ecosystem.

For a complete tutorial on using IronPDF with Blazor web applications visit here. To get a free trial of IronPDF, visit here to get your free trial license.

< PREVIOUS
C# Protected (How it Works For Developers)
NEXT >
Automapper C# (How it Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >