Przejdź do treści stopki
POMOC .NET

Topshelf C# (Jak to działa dla programistów)

A well-liked open-source package called Topshelf was created to make creating Windows services in .NET easier. The framework it offers simplifies and makes sense for creating, deploying, and administering Windows services, freeing developers to concentrate on the business logic instead of the complexities of service control management. Combined with IronPDF, a feature-rich C# library for creating and modifying PDF files, developers may build dependable and strong services that can manage intricate document processing jobs.

This connection provides a seamless solution for enterprises that require effective and automated document workflows by automating the creation, revision, and distribution of PDFs within a full Windows service framework. Developers can obtain a high degree of functionality and maintainability in their service applications, guaranteeing both robustness and ease of use, by utilizing Topshelf with IronPDF for .NET in C#.

What is Topshelf C#?

The development, setup, and implementation of Windows services are made easier with the help of the open-source project Topshelf .NET package. By removing a lot of the complexity from the process of creating Windows services, developers are able to concentrate more on the essential features of their apps rather than the nuances of Windows service administration.

With few code changes, Topshelf makes it simple for developers to turn console apps into services. It also offers a fluid API for establishing service settings, including dependencies, recovery options, and actions to start and stop services. For .NET developers wishing to effectively create stable and manageable Windows services, Topshelf is a well-liked option due to its ease of use and adaptability.

Topshelf C# (How It Works For Developers): Figure 1

A number of capabilities offered by Topshelf make it easier to design and maintain Windows services in .NET. Oto kilka jego najważniejszych cech:

Łatwość użytkowania

Topshelf provides a basic and fluid API that simplifies the process of configuring and administering Windows services using it. Console apps can be readily converted into services by developers with little to no code modifications.

Configuration Flexibility

Start, stop, pause, and continue actions are among the configuration options it supports. Service dependencies and recovery options for service classes can also be specified by developers.

Installation and Uninstallation

Deployment of hosting services written using the .NET Framework is facilitated by Topshelf's built-in functions for installing and uninstalling services. Programmatically or via the command line, services can be installed.

Logging

Topshelf facilitates developers' ability to efficiently log service operations and faults by integrating with well-known logging frameworks like log4net, NLog, and Serilog.

Service Control

It is compatible with all of the common Windows service controls, such as pause, continue, start, and stop. Developers now have total control over the whole service lifecycle.

Exception Handling

Robust exception handling is a feature of Topshelf that guarantees services can handle faults gracefully and remain stable.

Multiple Service Instances

It provides flexibility for complicated service architectures by enabling the creation and management of many service instances inside the same application.

Custom Command Line Options

Custom command line options allow developers to further customize and control the behavior of their services.

Environment Awareness

Whether it's a production server, a test environment, or a development system, Topshelf can recognize and adjust to its surroundings.

Support for Dependency Injection

Topshelf facilitates better software architecture and makes managing service dependencies easier when used in conjunction with dependency injection frameworks.

Cross-Platform Capabilities

Topshelf was mostly created for Windows, but it can also execute services on Linux and macOS when utilizing .NET Core, which increases its compatibility with other operating systems.

Create and Config Topshelf C

Use Topshelf in C# to create and configure a Windows service by doing the following steps:

Utwórz nowy projekt Visual Studio

W programie Visual Studio łatwo jest utworzyć projekt konsolowy. To start a Console Application in the Visual Studio environment, follow these simple steps:

Before using Visual Studio, make sure you have installed it on your computer.

Rozpocznij nowy projekt

After choosing File, Project, select the New menu.

Topshelf C# (How It Works For Developers): Figure 2

Either select "Console App" or "Console App (.NET Core)" from the list of project template references below.

To give your project a name, please fill out the "Name" field.

Topshelf C# (How It Works For Developers): Figure 3

Select the location for the project's storage.

The Console application project will open when you click "Create".

Topshelf C# (How It Works For Developers): Figure 4

Install Topshelf via NuGet

Using the NuGet Package Manager, add Topshelf to your project initially. In the Package Manager and Console application, execute the following command:

Install-Package Topshelf

Create a Service Class

Describe the class's service logic. Start and Stop, among other service actions, should be implemented in this class.

using System;
using Topshelf;

namespace MyWindowsService
{
    // Define a simple service class with Start and Stop methods
    public class MyService
    {
        public bool Start()
        {
            // Service start logic
            Console.WriteLine("Service Started.");
            return true;
        }

        public bool Stop()
        {
            // Service stop logic
            Console.WriteLine("Service Stopped.");
            return true;
        }
    }

    // Main program class to run the Topshelf service
    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                // Configure the service
                x.Service<MyService>(s =>
                {
                    s.ConstructUsing(name => new MyService());
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });

                // Run the service as a local system
                x.RunAsLocalSystem();

                // Set service details
                x.SetServiceName("MyService");
                x.SetDisplayName("My Service");
                x.SetDescription("This is a sample service created using Topshelf.");
            });
        }
    }
}
using System;
using Topshelf;

namespace MyWindowsService
{
    // Define a simple service class with Start and Stop methods
    public class MyService
    {
        public bool Start()
        {
            // Service start logic
            Console.WriteLine("Service Started.");
            return true;
        }

        public bool Stop()
        {
            // Service stop logic
            Console.WriteLine("Service Stopped.");
            return true;
        }
    }

    // Main program class to run the Topshelf service
    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                // Configure the service
                x.Service<MyService>(s =>
                {
                    s.ConstructUsing(name => new MyService());
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });

                // Run the service as a local system
                x.RunAsLocalSystem();

                // Set service details
                x.SetServiceName("MyService");
                x.SetDisplayName("My Service");
                x.SetDescription("This is a sample service created using Topshelf.");
            });
        }
    }
}
Imports System
Imports Topshelf

Namespace MyWindowsService
	' Define a simple service class with Start and Stop methods
	Public Class MyService
		Public Function Start() As Boolean
			' Service start logic
			Console.WriteLine("Service Started.")
			Return True
		End Function

		Public Function [Stop]() As Boolean
			' Service stop logic
			Console.WriteLine("Service Stopped.")
			Return True
		End Function
	End Class

	' Main program class to run the Topshelf service
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			HostFactory.Run(Sub(x)
				' Configure the service
				x.Service(Of MyService)(Sub(s)
					s.ConstructUsing(Function(name) New MyService())
					s.WhenStarted(Function(tc) tc.Start())
					s.WhenStopped(Function(tc) tc.Stop())
				End Sub)

				' Run the service as a local system
				x.RunAsLocalSystem()

				' Set service details
				x.SetServiceName("MyService")
				x.SetDisplayName("My Service")
				x.SetDescription("This is a sample service created using Topshelf.")
			End Sub)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Topshelf C# (How It Works For Developers): Figure 5

Configure the Service

The mechanism for initiating and terminating the service is contained in the MyService class. The service definition and its lifecycle methods (Start and Stop) are connected to the corresponding service actions in the Program class, which houses the Topshelf configuration. The service's properties, such as its name, display name, and description, are set using the run method of a single service class. Using Topshelf to manage and deploy Windows services is made simple by this succinct configuration.

Build and Install the Service

As you construct your project, make sure it is error-free. Use the install command together with the compiled executable to launch the service from the command line:

MyWindowsService.exe install
MyWindowsService.exe install
SHELL

Start the Service

Use the following command to launch the service after it has been installed:

MyWindowsService.exe start
MyWindowsService.exe start
SHELL

Uninstall the Service

Use the following to command prompt you to uninstall the service if necessary:

MyWindowsService.exe uninstall
MyWindowsService.exe uninstall
SHELL

This example shows you how to use Topshelf in C# to create and configure a Windows service. Topshelf streamlines the procedure, facilitating the definition, installation, setup, and administration of Windows services with little to no code.

Pierwsze kroki

To begin building a Windows service in C# using IronPDF and Topshelf, take the following actions:

Czym jest IronPDF?

IronPDF for .NET Libraries is a feature-rich .NET library that C# programs can use to create, read, and edit PDF documents. With this program, developers can easily produce print-ready, high-quality PDFs from HTML, CSS, and JavaScript content. The ability to split and merge PDFs, watermark documents, add headers and footers, and convert HTML to PDF are a few of the essential functions. IronPDF supports both the .NET Framework and .NET Core, making it useful for a wide range of applications.

Because PDFs are simple to integrate and have a wealth of documentation, developers may easily incorporate them into their programs. IronPDF ensures that the generated PDFs closely resemble the source HTML content by handling complex layouts and formatting with ease.

Topshelf C# (How It Works For Developers): Figure 6

Funkcje IronPDF

Generowanie plików PDF z HTML

Konwertuj JavaScript, HTML i CSS do formatu PDF. Obsługuje zapytania o media i responsywny projekt, dwa współczesne standardy internetowe. Przydatne do dynamicznego ozdabiania faktur, raportów i dokumentów PDF za pomocą HTML i CSS.

Edycja plików PDF

Do istniejących plików PDF można dodawać tekst, zdjęcia i inne treści. Extract text and pictures out of PDF files. Połącz wiele plików PDF w jeden plik. Podziel pliki PDF na wiele oddzielnych dokumentów. Należy uwzględnić znaki wodne, adnotacje, nagłówki i stopki.

Konwersja plików PDF

Convert several file formats, including Word, Excel, and picture files, to PDF format. PDF to image conversion (PNG, JPEG, etc.).

Wydajność i niezawodność

Wysoka wydajność i niezawodność to cechy projektowe pożądane w środowiskach przemysłowych. Z łatwością zarządza dużymi zbiorami dokumentów.

Zainstaluj IronPDF

To gain the tools you need to work with PDFs in .NET projects, install the IronPDF package.

Install-Package IronPdf

Create Your Service Class With IronPDF

Define the functionality of IronPDF for creating and modifying PDF files as well as the service logic for the class.

using System;
using IronPdf;
using Topshelf;

namespace PdfService
{
    // Define a service class with PDF generation logic
    public class MyPdfService
    {
        public bool Start()
        {
            Console.WriteLine("Service Starting...");
            GeneratePdf();
            return true;
        }

        public bool Stop()
        {
            Console.WriteLine("Service Stopping...");
            return true;
        }

        // Method to generate a PDF using IronPDF
        private void GeneratePdf()
        {
            var renderer = new HtmlToPdf();
            var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, PDF!</h1>");
            pdf.SaveAs("GeneratedDocument.pdf");
            Console.WriteLine("PDF Generated.");
        }
    }

    // Main program to configure and run the service using Topshelf
    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service<MyPdfService>(s =>
                {
                    s.ConstructUsing(name => new MyPdfService());
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });

                x.RunAsLocalSystem();
                x.SetServiceName("MyPdfService");
                x.SetDisplayName("My PDF Service");
                x.SetDescription("A service that generates PDF files using IronPDF and Topshelf.");
            });
        }
    }
}
using System;
using IronPdf;
using Topshelf;

namespace PdfService
{
    // Define a service class with PDF generation logic
    public class MyPdfService
    {
        public bool Start()
        {
            Console.WriteLine("Service Starting...");
            GeneratePdf();
            return true;
        }

        public bool Stop()
        {
            Console.WriteLine("Service Stopping...");
            return true;
        }

        // Method to generate a PDF using IronPDF
        private void GeneratePdf()
        {
            var renderer = new HtmlToPdf();
            var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, PDF!</h1>");
            pdf.SaveAs("GeneratedDocument.pdf");
            Console.WriteLine("PDF Generated.");
        }
    }

    // Main program to configure and run the service using Topshelf
    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service<MyPdfService>(s =>
                {
                    s.ConstructUsing(name => new MyPdfService());
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });

                x.RunAsLocalSystem();
                x.SetServiceName("MyPdfService");
                x.SetDisplayName("My PDF Service");
                x.SetDescription("A service that generates PDF files using IronPDF and Topshelf.");
            });
        }
    }
}
Imports System
Imports IronPdf
Imports Topshelf

Namespace PdfService
	' Define a service class with PDF generation logic
	Public Class MyPdfService
		Public Function Start() As Boolean
			Console.WriteLine("Service Starting...")
			GeneratePdf()
			Return True
		End Function

		Public Function [Stop]() As Boolean
			Console.WriteLine("Service Stopping...")
			Return True
		End Function

		' Method to generate a PDF using IronPDF
		Private Sub GeneratePdf()
			Dim renderer = New HtmlToPdf()
			Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello, PDF!</h1>")
			pdf.SaveAs("GeneratedDocument.pdf")
			Console.WriteLine("PDF Generated.")
		End Sub
	End Class

	' Main program to configure and run the service using Topshelf
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			HostFactory.Run(Sub(x)
				x.Service(Of MyPdfService)(Sub(s)
					s.ConstructUsing(Function(name) New MyPdfService())
					s.WhenStarted(Function(tc) tc.Start())
					s.WhenStopped(Function(tc) tc.Stop())
				End Sub)

				x.RunAsLocalSystem()
				x.SetServiceName("MyPdfService")
				x.SetDisplayName("My PDF Service")
				x.SetDescription("A service that generates PDF files using IronPDF and Topshelf.")
			End Sub)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Developers can rapidly design strong Windows services for PDF production and manipulation by combining Topshelf with IronPDF in C#. Topshelf offers a fluid and user-friendly API that makes setting up and managing Windows services easier.

Topshelf C# (How It Works For Developers): Figure 7

A MyPdfService class, which implements methods for starting (Start) and ending (Stop) the service, encapsulates the service logic in the example given. IronPDF is used in the Start method to create a simple PDF document using HTML from HTML text. The ability to render HTML into a PDF format using IronPDF's HtmlToPdf class is demonstrated, showing how to turn basic HTML information (such as "

Hello, PDF!

") into a PDF file ("GeneratedDocument.pdf").

Topshelf C# (How It Works For Developers): Figure 8

Ta integracja pokazuje, w jaki sposób Topshelf zarządza cyklem życia usługi, aby zapewnić jej działanie jako pełnoprawnej usługi systemu Windows, oraz w jaki sposób IronPDF z łatwością radzi sobie z trudnym procesem tworzenia plików PDF. Dzięki połączonym możliwościom Topshelf i IronPDF w języku C# ta integracja idealnie nadaje się do aplikacji wymagających automatycznego tworzenia lub modyfikacji dokumentów. Zapewnia niezawodność i łatwość konserwacji.

Wnioski

Podsumowując, tworzenie i administrowanie usługami Windows, które obejmują tworzenie i edycję plików PDF, jest możliwe dzięki połączeniu bibliotek Topshelf i IronPDF w języku C#. Oferując przyjazny dla użytkownika interfejs API do konfiguracji i zarządzania usługami, Topshelf usprawnia wdrażanie usług Windows. Ułatwiając płynne generowanie dokumentów PDF na podstawie informacji HTML w ramach logiki usługi, IronPDF tymczasowo poprawia funkcjonalność.

Ta integracja gwarantuje niezawodną i wysoką wydajność w zautomatyzowanych procesach obiegu dokumentów, a jednocześnie usprawnia proces tworzenia oprogramowania. Topshelf z IronPDF w języku C# wyróżnia się jako elastyczna i skuteczna opcja, umożliwiająca programistom łatwe tworzenie złożonych rozwiązań do przetwarzania dokumentów, czy to w celu tworzenia raportów, faktur, czy też wykonywania innych zadań związanych z plikami PDF.

Informacje dotyczące licencji IronPDF i Iron Software łączą niezwykle elastyczne systemy i pakiet oprogramowania Iron Software z podstawowym wsparciem, oferując programistom więcej aplikacji i funkcji online, a także bardziej efektywne tworzenie oprogramowania.

Jeśli opcje licencji są jasne i dostosowane do projektu, programiści mogą łatwiej określić, który model jest optymalny. Korzyści te pozwalają programistom rozwiązywać szeroki zakres problemów w jasny, skuteczny i spójny sposób.

Często Zadawane Pytania

W jaki sposób Topshelf upraszcza tworzenie usług Windows w środowisku .NET?

Topshelf udostępnia proste API, które pozwala programistom przekształcać aplikacje konsolowe w usługi Windows przy minimalnych zmianach w kodzie. Koncentruje się na łatwości użytkowania, elastyczności konfiguracji i solidnej obsłudze wyjątków, umożliwiając programistom skupienie się na logice biznesowej, a nie na złożoności zarządzania usługami.

Czy Topshelf może być używany na platformach innych niż Windows?

Tak, chociaż Topshelf jest przeznaczony przede wszystkim dla systemu Windows, może również działać na systemach Linux i macOS przy użyciu .NET Core, co zwiększa jego możliwości międzyplatformowe.

Jakie korzyści oferuje integracja IronPDF z Topshelf?

Integracja IronPDF z Topshelf pozwala programistom zautomatyzować przepływ pracy z dokumentami PDF w ramach usług Windows. To połączenie zapewnia solidne rozwiązanie do tworzenia, modyfikowania i dystrybucji dokumentów PDF, wykorzystujące funkcje zarządzania usługami Topshelf oraz funkcje PDF IronPDF.

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

Możesz użyć IronPDF do konwersji treści HTML, CSS i JavaScript na dokumenty PDF, korzystając z metod przeznaczonych do konwersji HTML na PDF. IronPDF obsługuje nowoczesne standardy internetowe i responsywny projekt, zapewniając wysoką jakość plików PDF.

Jak wygląda proces tworzenia usługi Windows przy użyciu Topshelf?

Aby zbudować usługę Windows za pomocą Topshelf, należy utworzyć nowy projekt w Visual Studio, zainstalować Topshelf za pośrednictwem NuGet, napisać klasę usługi z metodami Start i Stop, skonfigurować usługę przy użyciu API Topshelf, a następnie skompilować projekt. Na koniec należy zainstalować i uruchomić usługę za pomocą poleceń wiersza poleceń.

Jakie są kluczowe funkcje Topshelf w zakresie zarządzania usługami?

Topshelf oferuje takie funkcje, jak łatwość obsługi, elastyczność konfiguracji, rejestrowanie, solidne obsługiwanie wyjątków, obsługa wielu instancji usług oraz zgodność z popularnymi kontrolkami usług Windows, co czyni go wszechstronnym narzędziem dla programistów .NET.

Jak wdrożyć zautomatyzowane przepływy pracy z dokumentami przy użyciu usług Windows?

Zautomatyzowane przepływy pracy z dokumentami można wdrożyć poprzez integrację Topshelf z IronPDF, tworząc usługi Windows, które obsługują zadania takie jak generowanie, modyfikacja i dystrybucja plików PDF, a wszystko to w ramach struktury usług.

Jakie opcje licencyjne są dostępne dla IronPDF?

IronPDF oferuje elastyczne opcje licencyjne dostosowane do różnych potrzeb projektowych, umożliwiając programistom wydajną integrację funkcji PDF z ich aplikacjami zgodnie z konkretnymi wymaganiami.

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