Déploiement d’une application serveur C #

J’ai récemment terminé la création d’un serveur multithread en tant qu’application console en C #. À l’origine, il s’exécute sur un ordinateur d’entreprise exposé à Internet par transfert de port. Cependant, je pense qu’il faudra peut-être passer à une configuration de serveur réelle à mesure que les clients augmentent. Je n’ai jamais eu à le faire avant, alors je me demandais:

Que dois-je faire pour déployer une application console C # comme celle-ci sur un serveur? Faut-il le convertir en service? Pourrais-je obtenir un VPS et l’exécuter?

J’apprécierais vraiment toutes les réponses ou suggestions, merci

En c #, il est très simple d’écrire un service Windows. J’aime combiner une application console et des services. Je combine ceci, car pour des raisons de débogage, une application de console est plus efficace et pour la production, le service est meilleur. En tant que base de service, j’utilise toujours:

Program.cs:

#define __USE_AS_CONSOLE___ using MyService.Service; using System; using System.Collections.Generic; using System.Configuration.Install; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Principal; using System.Text; using System.Threading.Tasks; using System.IO; using System.Diagnostics; namespace MyService { public class Program { #region Private Member private static ASServiceBase myServiceBase; private static ssortingng serviceName; #endregion #region Console const bool ShowConsole = true; [DllImport("kernel32.dll", SetLastError = true)] public static extern bool AllocConsole(); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool FreeConsole(); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern bool SetDllDirectory(ssortingng lpPathName); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern bool AddDllDirectory(ssortingng lpPathName); #endregion static void Main(ssortingng[] args) { AppDomain.CurrentDomain.AssemblyResolve += ResolveError; ssortingng installCommand = ""; serviceName = GetServiceName(); foreach(ssortingng arg in args) { if (arg.ToLower().StartsWith("/install")) { installCommand = "/install"; } else if (arg.ToLower().StartsWith("/uninstall")) { installCommand = "/uninstall"; } } if (System.Environment.UserInteractive) { ssortingng parameter = ""; foreach (ssortingng arg in args) { parameter += arg; if (!arg.EndsWith(" ")) { parameter += ""; } } switch (installCommand) { case "/install": if (!IsAdministrator()) { System.Console.WriteLine("Die Anwendung muss als Administrator installiert werden."); System.Console.ReadLine(); return; } ManagedInstallerClass.InstallHelper(new ssortingng[] { Assembly.GetExecutingAssembly().Location }); return; break; case "/uninstall": if (!IsAdministrator()) { System.Console.WriteLine("Die Anwendung muss als Administrator installiert werden."); System.Console.ReadLine(); return; } ManagedInstallerClass.InstallHelper(new ssortingng[] { "/u", Assembly.GetExecutingAssembly().Location }); return; break; } AllocConsole(); myServiceBase = new ASServiceBase(); myServiceBase.Start(); System.Console.ReadLine(); } else { // =============================================== // Start Console AllocConsole(); System.Console.WriteLine("Version 1.0"); myServiceBase = new ASServiceBase(); //Start service System.ServiceProcess.ServiceBase.Run(myServiceBase); } } public static bool IsAdministrator() { var identity = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } #region [Resolve Error] ///  /// Resolve Error ///  ///  ///  private static Assembly ResolveError(object sender, ResolveEventArgs args) { try { Assembly cMyAssembly = null; ssortingng strTempAssmbPath = ssortingng.Empty; Assembly objExecutingAssemblies = Assembly.GetExecutingAssembly(); AssemblyName[] arrReferencedAssmbNames = objExecutingAssemblies.GetReferencedAssemblies(); AssemblyName myAssemblyName = Array.Find(arrReferencedAssmbNames, a => a.Name == args.Name); if (myAssemblyName != null) { cMyAssembly = Assembly.LoadFrom(myAssemblyName.CodeBase); } else { ssortingng rootFolder = GetAssemblyPath(args, ""); if (!ssortingng.IsNullOrEmpty(rootFolder)) { if (File.Exists(rootFolder)) { // Loads the assembly from the specified path. cMyAssembly = Assembly.LoadFrom(rootFolder); } } ssortingng assemblyFolder = GetAssemblyPath(args, "Assemblies\\"); if (!ssortingng.IsNullOrEmpty(assemblyFolder)) { if (File.Exists(assemblyFolder)) { // Loads the assembly from the specified path. cMyAssembly = Assembly.LoadFrom(assemblyFolder); } } } // Returns the loaded assembly. return cMyAssembly; } catch (Exception exc) { FileLog.WriteLog("Fehler in Init.ResolveError:\r\n" + exc.ToSsortingng()); return null; } } private static ssortingng GetAssemblyPath(ResolveEventArgs args, ssortingng AdditionalDirectory) { ssortingng returnValue = null; ssortingng cRMSAssemblyFolder = GlobalSettings.StudioPath + "\\" + AdditionalDirectory; Assembly cMyAssembly = null; ssortingng strTempAssmbPath = ssortingng.Empty; Assembly objExecutingAssemblies = Assembly.GetExecutingAssembly(); AssemblyName[] arrReferencedAssmbNames = objExecutingAssemblies.GetReferencedAssemblies(); AssemblyName myAssemblyName = Array.Find(arrReferencedAssmbNames, a => a.Name == args.Name); if (myAssemblyName == null) { if (args.Name.Contains(",")) { strTempAssmbPath = Path.Combine(cRMSAssemblyFolder, args.Name.Subssortingng(0, args.Name.IndexOf(",")) + ".dll"); } else { strTempAssmbPath = Path.Combine(cRMSAssemblyFolder, args.Name + ".dll"); } returnValue = strTempAssmbPath; } return returnValue; } #endregion } } 

Installateur de service:

 using System; using System.Configuration.Install; using System.ComponentModel; using System.ServiceProcess; using System.IO; using System.Net.Sockets; using System.Net; using System.Threading; using System.Configuration; using System.Diagnostics; ///  /// Installerklasse für den Service ///  [RunInstaller(true)] public class QServiceInstaller : Installer { #region private Member private ServiceInstaller myThisService; private IContainer components; private ServiceProcessInstaller myThisServiceProcess; #endregion public QServiceInstaller() { myThisService = new ServiceInstaller(); myThisServiceProcess = new ServiceProcessInstaller(); ssortingng Path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); myThisServiceProcess.Account = ServiceAccount.LocalSystem; myThisService.ServiceName = "Your application name"; myThisService.StartType = ServiceStartMode.Automatic; Installers.Add(myThisService); Installers.Add(myThisServiceProcess); } private void InitializeComponent() { } } 

Votre base de service:

 using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading; namespace MyService.Service { public class ASServiceBase : ServiceBase { #region Private Member private Thread myServiceThread; private bool myDoStop; #endregion #region Constructor ///  /// Constructor ///  public ASServiceBase() { myDoStop = false; } #endregion #region Public Methods #region OnStart protected override void OnStart(ssortingng[] args) { Start(); } ///  /// Start ///  public void Start() { myServiceThread = new Thread(new ThreadStart(Do)); myServiceThread.Start(); MainThread = myServiceThread; } #endregion #region Do Anything ///  /// Execute ///  public void Do() { while (!myDoStop) { // Do some stuff Thread.Sleep(10); } LoggingManager.Singleton.Deactivate(); // ===================================================================================== // Stop anything // ===================================================================================== } #endregion #region OnStop protected override void OnStop() { Stop(); } ///  /// Stop ///  public void Stop() { myDoStop = true; } #endregion #endregion #region Private Methods #endregion #region Public Member ///  /// Main Thread ///  public static Thread MainThread { get; set; } #endregion } } 

J’espère que mon code aide. Demandez si vous avez des questions

Il vaut mieux créer un service pour ce type de programme. La sortie de l’application console utilise beaucoup de ressources et doit être démarrée manuellement. Alors qu’un service peut être exécuté sur chaque ordinateur, le démarrage sans qu’un utilisateur ne soit même connecté.

Pour le déployer, le meilleur moyen consiste à créer un processus d’installation, puis à l’installer sur le serveur. Vous pouvez ensuite créer un processus de mise à jour pour votre serveur afin de ne pas avoir à l’installer pour chaque mise à jour que vous effectuez.