C# add service to Services.msc

Created a service using C# .NET.  How do I add the service to services.msc?
LVL 2
CipherISAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Florian LenschowCommented:
It is explained in the documentation. You first need to add an installer to your service (Adding installers to the Service) and then you can install it using installutil.exe (Installing the Service)
0
CipherISAuthor Commented:
I did that.  It is prompting me for credentials and I don't think it should.  I also keep getting "Access is Denied"
0
CipherISAuthor Commented:
    partial class ProjectInstaller
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ExportProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();
            this.ExportInstaller = new System.ServiceProcess.ServiceInstaller();
            // 
            // ExportProcessInstaller
            // 
            this.ExportProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalService;
            //this.ExportProcessInstaller.Password = null;
            //this.ExportProcessInstaller.Username = null;
            this.ExportProcessInstaller.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_AfterInstall);
            // 
            // ExportInstaller
            // 
            this.ExportInstaller.Description = "Export Service";
            this.ExportInstaller.DisplayName = "Export Service";
            this.ExportInstaller.ServiceName = "Export Service" ;
            this.ExportInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
            this.ExportInstaller.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceInstaller1_AfterInstall);
            // 
            // ProjectInstaller
            // 
            this.Installers.AddRange(new System.Configuration.Install.Installer[] {
            this.ExportProcessInstaller,
            this.ExportInstaller});

        }

        #endregion

        private System.ServiceProcess.ServiceProcessInstaller ExportProcessInstaller;
        private System.ServiceProcess.ServiceInstaller ExportInstaller;
    }

Open in new window

0
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Florian LenschowCommented:
I think it is required to have Admin rights when installing a service. Do you run the command prompt as Admin?
0
Chinmay PatelChief Technical NinjaCommented:
It is prompting for credentials as Windows Service always runs in a context of user. This "user" has to be defined when you are installing the service. If you are getting access denied we will have to investigate if you have proper privileges to install a Windows Service or not.
0
CipherISAuthor Commented:
Set cmd to run with admin rights.  I get

"The account name is invalid or does not exist, or the password is invalid for the account name specified
0
Chinmay PatelChief Technical NinjaCommented:
can you tell me in which format you are entering username and password? your username should be something like this - if you are not connected to Active Directory then MachineName\UserName and if you are connected to AD then domainname\UserName.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CipherISAuthor Commented:
So,

MachineName\UserName

allowed me to get past the Set Login.

However, I attempt to start the service and now I receive

"The ExportApp service on Local Computer started and then stopped.  Some services stop automatically if they are not in use by other services or programs".

Any ideas?

When I put this on a server will I need credentials there to?

Thanks
0
Chinmay PatelChief Technical NinjaCommented:
Yes. you will need the credentials. And you have to start a thread or some other process that will wait indefinitely otherwise this is going to happen for sure. Basically if your service is not throwing an exception it will just run the OnStart method and move on.
0
CipherISAuthor Commented:
So, figured out the error.

Service cannot be started. System.ArgumentException: Empty path name is not legal.
   at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
   at System.IO.StreamWriter..ctor(String path, Boolean append)
   at Export.Classes.ExportResult.WriteError(String value, String filename) in c:\xxxx\Development\Export\I\Classes\ExportResult.cs:line 26

In the below code I put in ALL CAPS where I believe it is failing.  I have an AppSettings class which is getting the values with no problems in winform.  Any issues with app.config and services?
        public static void WriteResult(string value, string filename)
        {
            using (StreamWriter sw = new StreamWriter(filename, false))
            {
                string datevalue = DateTime.Now.ToString("yyyyMMdd");
                string timevalue = DateTime.Now.ToLongTimeString();
                string result = "At " + datevalue + " " + timevalue + " successfully exported " + value + ".";

                sw.WriteLine(result);
            }
        }

        public static void WriteError(string value, string filename)
        {
            using (StreamWriter sw = new StreamWriter(filename, false))  //THIS IS LINE 26
            {
                StringBuilder result = new StringBuilder();
                result.AppendLine("At " + DateTime.Now.ToString("yyyyMMdd") + " " + DateTime.Now.ToLongTimeString() + " the below error occured.");
                result.AppendLine(value);

                //string result = "At " + datevalue + " " + timevalue + " successfully exported " + value + ".";

                sw.WriteLine(result);
            }
        }

        public static void WriteLog(string value, string filename)
        {
            using (StreamWriter sw = new StreamWriter(filename, true))
            {
                sw.WriteLine(value);
            }
        }
    }

Open in new window

Code that calls ExportResult class
    public partial class Service1 : ServiceBase
    {
        private Timer Schedular;
        private string logfile = AppSettings.GetExportLocationArchive() + AppSettings.GetServiceLog();

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                string filename = AppSettings.GetExportLocationArchive() + AppSettings.GetServiceLog();
                ExportResult.WriteLog("Service Started", filename);

                System.Diagnostics.Debugger.Launch();
                this.ScheduleService();
            }
            catch (Exception ex)
            {
                string filename = AppSettings.GetExportLocationArchive() + AppSettings.GetExportErrorFileName();
                ExportResult.WriteError(ex.ToString(), filename);  //SEEMS TO BE FAILING HERE
            }
        }

        protected override void OnStop()
        {
            this.Schedular.Dispose();
        }

        public void ScheduleService()
        {
            try
            {
                Schedular = new Timer(new TimerCallback(SchedularCallback));
                string mode = AppSettings.GetMode();
                //this.WriteToFile("Simple Service Mode: " + mode + " {0}");
                ExportResult.WriteLog("Simple Service Mode: " + mode + " {0}", logfile);

                //Set the Default Time.
                DateTime scheduledTime = DateTime.MinValue;

                if (mode == "DAILY")
                {
                    //Get the Scheduled Time from AppSettings.
                    scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]);
                    if (DateTime.Now > scheduledTime)
                    {
                        //If Scheduled Time is passed set Schedule for the next day.
                        scheduledTime = scheduledTime.AddDays(1);
                    }
                }

                if (mode.ToUpper() == "INTERVAL")
                {
                    //Get the Interval in Minutes from AppSettings.
                    int intervalMinutes = AppSettings.GetIntervalMinutes();

                    //Set the Scheduled Time by adding the Interval to Current Time.
                    scheduledTime = DateTime.Now.AddMinutes(intervalMinutes);
                    if (DateTime.Now > scheduledTime)
                    {
                        //If Scheduled Time is passed set Schedule for the next Interval.
                        scheduledTime = scheduledTime.AddMinutes(intervalMinutes);
                    }
                }

                TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);

                string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
                ExportResult.WriteLog(schedule, logfile);

                ExportResult.WriteLog("Items Region Export Service scheduled to run after: " + schedule + " {0}", logfile);
                //this.WriteToFile("Items Region Export Service scheduled to run after: " + schedule + " {0}");

                //Get the difference in Minutes between the Scheduled and Current Time.
                int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);

                //Change the Timer's Due Time.
                Schedular.Change(dueTime, Timeout.Infinite);
            }
            catch (Exception ex)
            {
                string filename = AppSettings.GetExportLocationArchive() + AppSettings.GetExportErrorFileName();
                ExportResult.WriteError(ex.ToString(), filename);

                //Stop the Windows Service.
                using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("ExportApp"))
                {
                    serviceController.Stop();
                }
            }
        }

        private void SchedularCallback(object e)
        {
            ExportResult.WriteLog("Items Region Export Service Log: {0}", logfile);
            this.ScheduleService();
            ExportData.PerformExport();
        }

        private void WriteToFile(string text)
        {
            string filename = AppSettings.GetExportLocationArchive() + AppSettings.GetServiceLog();
            ExportResult.WriteLog(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")), filename);
        }
    }

Open in new window

0
Chinmay PatelChief Technical NinjaCommented:
Check event log it will have more details on the exact error. Also did you associate an EventSource with your service?
0
CipherISAuthor Commented:
Associate EventSource with service?
0
Chinmay PatelChief Technical NinjaCommented:
Check this out : https://blogs.msdn.microsoft.com/helloworld/2008/12/11/how-to-create-custom-event-log-for-windows-service/

but before that do check your Application Event Log. Let me know if there are any errors related to your Service.
0
CipherISAuthor Commented:
That is where I got the error regarding the "Empty path name is not legal", from the Event Viewer
0
CipherISAuthor Commented:
This is what I'm getting in Event Viewer.

 Service cannot be started. System.ArgumentException: Empty path name is not legal. at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost) at System.IO.StreamWriter..ctor(String path, Boolean append) at ItemsRegionExport.Classes.ExportResult.WriteError(String value, String filename) in c:\Carlos\Development\ItemsRegionExport\ItemsRegionExport\Classes\ExportResult.cs:line 26 at ItemsRegionExport.Service1.OnStart(String[] args) in c:\Carlos\Development\ItemsRegionExport\ItemsRegionExport\Service1.cs:line 39 at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
This is the code "OnStart"
        protected override void OnStart(string[] args)
        {
            try
            {
                //ExportResult.WriteLog("Service Started", logfile);

                //System.Diagnostics.Debugger.Launch();
                //this.ScheduleService();
            }
            catch (Exception ex)
            {
                string s = @"C:\Export\Archive\_ExportError.txt";
                ExportResult.WriteError(ex.ToString(), filename);
            }
        }

Open in new window

0
Chinmay PatelChief Technical NinjaCommented:
Try debugging the Service by attaching Visual Studio's debugger to it. This will sort out where and why it is failing.
0
CipherISAuthor Commented:
Put System.Disagnostics.Debugger.Launch in a bunch of areas in the app.  Even put it in the ExportResult.WriteError.  Not launching.
        public Service1()
        {
            System.Diagnostics.Debugger.Launch();
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                System.Diagnostics.Debugger.Launch();
                //ExportResult.WriteLog("Service Started", logfile);

                //this.ScheduleService();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debugger.Launch();
                string s = @"C:\Export\Archive\_ExportError.txt";
                ExportResult.WriteError(ex.ToString(), s);
            }
        }

Open in new window

0
Chinmay PatelChief Technical NinjaCommented:
0
CipherISAuthor Commented:
Can't atttach it.  It is greyed out.  I try to start the service to see if it goes from grey to black but the attach button is NOT enabled.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.