Click here to Skip to main content
14,934,818 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
windows service should be first install and then started with server explorer,administrative tools or the net start command


this is the error i m facing. I have tried starting the service from computer management - service and application, running cmd through admin rights.
below i m attaching my code.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        private Timer timer1 = null;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer1 = new Timer();
            this.timer1.Interval = 60000; //60 sec
            this.timer1.Elapsed +=new System.Timers.ElapsedEventHandler(this.timer1_Tick);
            timer1.Enabled=true;
            Library.WriteErrorLog("test windows service started");
            
        }

        protected override void OnStop()
        {
            timer1.Enabled = false;
            Library.WriteErrorLog("Test Service ended");
        }

        public void timer1_Tick(object sender, ElapsedEventArgs e)
        {
            //job
            var result = RunProcess(@"c:\", "webupknvp.Bat", "", false);
            if (result == 0)
            {
                // success
                Console.WriteLine("Sucess");
            }
            else
            {
                // failed ErrorLevel / app ExitCode
                Console.WriteLine("failed try again");
                
            }
            

        }

        public int RunProcess(string workDir, string appName, string args, bool hide = false)
            {
                    
                    Process proc = null;
                    proc = new Process();          
                    string batrun = string.Format("cmd.exe", "/c" + @"C:\Abhay\batfile"); // or @"C:\Abhay\batfile" in the end ("cmd.exe", "/c" + @"C:\Abhay\batfile")
                    proc.StartInfo.UseShellExecute = false;   //addition   	
                    proc.StartInfo.WorkingDirectory = workDir;//batrun
	                proc.StartInfo.FileName = appName;
                    proc.StartInfo.Arguments = args;
	                proc.StartInfo.CreateNoWindow = hide;
                    
	                proc.Start();
	                proc.WaitForExit();
	
	                return proc.ExitCode;
               }
    }
}


library class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace WindowsService1
{
    public static class Library
    {
        public static void WriteErrorLog(Exception ex)
        {
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\ Logfile.txt", true);
                sw.WriteLine(DateTime.Now.ToString() + ":" + ex.Source.ToString().Trim() + ";" + ex.Message.ToString().Trim());
                sw.Flush();
                sw.Close();

            }
            catch
            {

            }
        }

        public static void WriteErrorLog(string Message)
        {
            StreamWriter sw = null;
            try
            { 
            
                sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\ Logfile.txt", true);
                sw.WriteLine(DateTime.Now.ToString() + ":" + Message);
                sw.Flush();
                sw.Close();
            }
            catch
            {

            }
        }
    }
}


program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace WindowsService1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new Service1() 
            };
            ServiceBase.Run(ServicesToRun);
           
        }
    }
}


What I have tried:

I have tried starting the service from computer management - service and application, running cmd through admin rights.
Posted
Updated 16-Mar-17 4:42am
Comments
[no name] 16-Mar-17 6:53am
   
windows service should be first install and then started with server explorer,administrative tools or the net start command

other's comments are good and right. i just wan't to share the approach I use when developing Windows Services.

I don't want to unistall/install Service for a quick test during debug so I run them as console-applications.

So I use
Environment.UserInteractive
to check if I run from user-interaction (e.g. during debug, or by just clicking on the exe in WindowsExplorer) -> if true, I run the Service as console, by calling the OnStart-Method of the Service by reflection...
So my solution looks like this (comments and tracing ommited)

Somewhere in a helper library (it's generic and will work for all Services - just try it out):

public static void RunServices(ServiceBase[] aServicesToRun, string[] astrArgs)
{
    if (Environment.UserInteractive)
    {
        // run as console
        try
        {
            CallServiceMethod(aServicesToRun, "OnStart", new object[] { astrArgs });
            WaitPrompt(aServicesToRun);
            CallServiceMethod(aServicesToRun, "OnStop", null);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Service-call failed: " + ex.ToString());
            Console.ReadKey(true);
        }
    }
    else
    {
        // run as Windows service
        ServiceBase.Run(aServicesToRun);
    }
}



static void CallServiceMethod(ServiceBase[] aServicesToRun, string strMethodName, object[] aobjParams)
{
    Type type = typeof(ServiceBase);
    BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
    MethodInfo method = type.GetMethod(strMethodName, flags);

    foreach (ServiceBase service in aServicesToRun)
        method.Invoke(service, aobjParams);
}


private static void WaitPrompt(ServiceBase[] aServicesToRun)
{
    ConsoleKeyInfo key;

    do
    {
        key = Console.ReadKey(true);

        switch (key.Key)
        {
            case ConsoleKey.P:
                CallServiceMethod(aServicesToRun, "OnPause", null);
                Console.WriteLine("Action> PAUSE");
                break;
            case ConsoleKey.R:
                CallServiceMethod(aServicesToRun, "OnContinue", null);
                Console.WriteLine("Action> RESUME");
                break;
            case ConsoleKey.S:
                 // Service-Method OnStop will be called after this method ends
                 Console.WriteLine("Action> STOP");
                break;
        }
    } while (key.Key != ConsoleKey.S);
}


Then in my Service-implementation I use it like this:

static void Main(string[] astrArgs)
{
    ServiceExecutionHelper.RunServices(new ServiceBase[] { new MyService() }, astrArgs);
    // replaces ServiceBase.Run(...);
}


Maybe useful for you too...
   
Comments
Graeme_Grant 16-Mar-17 22:40pm
   
5ed! :)
r.abhaysinghania 17-Mar-17 3:07am
   
what is service execution helper? as i m getting an error in that
johannesnestler 20-Mar-17 11:12am
   
just my helper class where I put the method - just create a static class and Name it as you like to put the RunServices method there... I thought that was obvious - sorry for that...
r.abhaysinghania 23-Mar-17 3:43am
   
I figured it later on and its running thank you
   
You have to install your service first (see for example at the end of the CodeProject article provided in solution 1).

Then start it using one of the methods mentioned in the error message.

See these links for starting and stopping services from the command line:
Controlling a Service Using SC (Windows)[^]
Net start[^]
   
Comments
r.abhaysinghania 16-Mar-17 7:52am
   
I have done that. cmd did a roll back and said the service is already installed

An exception occurred during the Install phase.
System.ComponentModel.Win32Exception: The specified service already exists

The Rollback phase of the installation is beginning. See the contents of the log file for the C:\Users\Sapuser\Documents\Visual Studio 2013\Projects\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe assembly's progress. The file is located at C:\Users\Sapuser\Documents\Visual Studio 2013\Projects\WindowsService1\WindowsService1\bin\Debug\WindowsService1.InstallLog. Rolling back assembly 'C:\Users\Sapuser\Documents\Visual Studio 2013\Projects\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe'. Affected parameters are: logtoconsole = assemblypath = C:\Users\Sapuser\Documents\Visual Studio 2013\Projects\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe logfile = C:\Users\Sapuser\Documents\Visual Studio 2013\Projects\WindowsService1\WindowsService1\bin\Debug\WindowsService1.InstallLog Restoring event log to previous state for source WinService. The Rollback phase completed successfully. The transacted install has completed. The installation failed, and the rollback has been performed.
Jochen Arndt 16-Mar-17 8:14am
   
If you have already installed an older version of the service and you want to update, uninstall the old version first:

installutil /u <yourproject>.exe

See also https://msdn.microsoft.com/en-us/library/sd8zc8ha(v=vs.110).aspx

I recommend also to not install the binary from your project build path but copy it to another location and install that. Then you can rebuild while the service is active.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900