Decide program running as Windows service / console cmd C# .NET [duplicate]

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.

New contributor

RIzky Satria P is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

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()

nvm, my supervisor told me to do this:

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

New contributor

RIzky Satria P is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Decide program running as Windows service / console cmd C# .NET [duplicate]

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.

New contributor

RIzky Satria P is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

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()

nvm, my supervisor told me to do this:

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

New contributor

RIzky Satria P is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật