skip to Main Content

Basically I already try deciding using if else like this:

static async Task Main(string[] args)
{
    string licenseKey = Environment.GetEnvironmentVariable("LICENSE_KEY");

    if (string.IsNullOrEmpty(licenseKey))
    {
        Console.WriteLine("LICENSE_KEY not found.");
        return;
    }

    if (args.Contains("--console") || Environment.GetEnvironmentVariable("RUN_AS_SERVICE") != "true")
    {
        Console.WriteLine("Running as console.");
        var cancellationTokenSource = new CancellationTokenSource();
        var task = RunAsConsoleAsync(cancellationTokenSource.Token);
        await task;
    }
    else
    {
        Console.WriteLine("Running as Windows service.");
        RunAsWindowsService();
    }
}

The problem is, I already try to install my App.exe as a Windows service. But my program is still using the first one, where running on console. To be honest, I am not using environment variable RUN_AS_SERVICE, because that was not efficient for client in the future.

Here is my code for supporting program to run as service:

static void RunAsWindowsService()
{
    EventLog eventLog = new EventLog();

    if (!EventLog.SourceExists("TelegramBotService"))
    {
        EventLog.CreateEventSource("TelegramBotService", "Application");
    }

    eventLog.Source = "TelegramBotService";
    eventLog.Log = "Application";

    HostFactory.Run(x =>
    {
        x.Service<TelegramBotService>(s =>
        {
            s.ConstructUsing(name => new TelegramBotService(eventLog));

            s.WhenStarted(tc =>
            {
                try
                {
                    Task.Run(() => tc.StartAsync()).GetAwaiter().GetResult();
                    eventLog.WriteEntry("Service started successfully.", EventLogEntryType.Information);
                }
                catch (Exception ex)
                {
                    eventLog.WriteEntry($"Error saat menjalankan service: {ex.Message}", EventLogEntryType.Error);
                }
            });

            s.WhenStopped(tc =>
            {
                try
                {
                    tc.Stop();
                    eventLog.WriteEntry("Service stopped successfully.", EventLogEntryType.Information);
                }
                catch (Exception ex)
                {
                    eventLog.WriteEntry($"Error saat menghentikan service: {ex.Message}", EventLogEntryType.Error);
                }
            });
        });

        x.RunAsLocalSystem();
        x.SetDescription("Telegram Bot Service");
        x.SetDisplayName("TelegramBotService");
        x.SetServiceName("TelegramBotService");

        // Pengaturan agar service mulai otomatis dan bisa recovery
        x.StartAutomatically();
        x.EnableServiceRecovery(r => r.RestartService(1)); // Restart setelah 1 menit jika terjadi kesalahan
    });
}

So maybe you guys have any idea, for a better if else check? personally I’ll add environment variable if I don’t have any idea til tomorrow.

2

Answers


  1. Chosen as BEST ANSWER

    nvm, my supervisor tell me to do this :

    static void Main(string[] args)
            {
                if (!Environment.UserInteractive)
                {
                    
                    // running as service            
                    
                }
                else
                {
                    // running as console app
                    
                    
                }
    
                
    
            }


  2. I see you have an answer, but to answer specifically about why your code wasn’t running as expected.

    Environment.GetEnvironmentVariable() returns the value of the requested environment variable, or null if not found.

    Environment.GetEnvironmentVariable("RUN_AS_SERVICE") != "true")

    is saying if the return value of GetEnvironmentVariable() does not equal "true", then run the code.

    Since you said that you were not setting RUN_AS_SERVICE, the call to retrieve it will return null. null does not equal "true", satisfying the condition and running the program in console mode.

    If you want the program to default running as a service, my change would be to your if statement:

    if (args.Contains("--console") || Environment.GetEnvironmentVariable("RUN_AS_SERVICE") == "false")

    To run in console mode you have to either specifically request it with --console, or set RUN_AS_SERVICE to "false".

    Microsoft Documentation on GetEnvironmentVariable()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search