I have created a c# windows service
when I put my visual studio in debug mode and I run it , it works correctly
but when I create a setup and install it , it doesn't work(means the service installed correctly and start but my code doesn't running).
(I built setup like this https://support.microsoft.com/en-us/kb/816169)
this is my Code:
This is my Code : dropbox.com/s/eq13fng88gk714u/myTelephone.zip?dl=0
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if DEBUG
myTelephone myService1 = new myTelephone();
myService1.onDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new myTelephone()
};
ServiceBase.Run(ServicesToRun);
#endif
}
And
public partial class myTelephone : ServiceBase
{
public myTelephone()
{
InitializeComponent();
} public void onDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
//////save some data in sql server
}}
Did you even try to google this before asking?
Anyways, just use Topshelf via nuget. This way you always execute the same code when debugging and when it's installed.
As you didn't provide anything except of 'it does not work', I'll try to assume:
either your Windows service is not being installed - then see the 'your service executable'.exe.InstallLog file in the same folder where 'your service executable' is located;
or the Windows service was installed successfully but it doesn't start - then go to the Event Viewer and look for the error message there related to your service. If that's the case then most probably that's because your OnStart method goes to timeout. In this case:
Either request additional time inside the method:
// request additional 4 seconds for the start-up process
this.RequestAdditionalTime(4000);
or move the code that access the SQL database out of the method, for example, creating a new thread and doing all your staff there.
I think you are trying to install this by clickicg exe file. It is not correct.
Try next:
Open cmd
cd to directory with myTelephone.exe
run next
sc create myTelephone binpath= "myTelephone.exe" start= auto
net start myTelephone
Or you also could do add to pre-build event:
net stop $(ProjectName)
sc delete $(ProjectName)
exit /b 0
As post-build event:
sc create $(ProjectName) binpath= "$(TargetPath)" start= auto
net start $(ProjectName)
And on each build you will have installed service.
Related
Presently, I am attempting to profile a Windows service that I am working on using the new "Performance and Diagnostics" feature in Visual Studio 2013 (see http://blogs.msdn.com/b/visualstudioalm/archive/2013/07/12/performance-and-diagnostics-hub-in-visual-studio-2013.aspx). When I attempt to profile the service, I get this error message:
Cannot start service from the command line or a debugger. A Windows Service must first be intalled (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative Tool or the NET START command.
Normally when debugging the service, it works fine because I have the following code in Program.cs:
private static MySvc _serviceInstance;
private static readonly List<ServiceBase> _servicesToRun =
new List<ServiceBase>();
static void Main(string[] args)
{
_servicesToRun.Add(_serviceInstance);
if (Environment.UserInteractive)
{
_servicesToRun.ToArray().LoadServices();
}
else
{
ServiceBase.Run(_servicesToRun.ToArray());
}
}
static Program()
{
_serviceInstance = new MySvc();
}
Also, if I attempt to attach to a running app, in the dialog that appears it doesn't display any executing processes, and when I put the name of the service in there, it does not find it. Does anyone have any suggestions? TIA.
UPDATE: This is what I get when I attempt to attach to a process. Why doesn't the "Performance and Diagnostics" see any processes running on my computer? Why would it only connect to Windows Store apps instead of all exes? Please see this image:
The way I resolved the problem was the copy all the source code and make minor modifications to get everything to run in a Console application, then chose Debug->Performance and Diagnostics and ran the Console application using "Change Target" -> "Launch and executable file (.exe)"
Whem I'm writing a Windows Service and just hit F5 I get the error message that I have to install it using installutil.exe and then run it.
In practice this means everytime I change a line of code:
compile
switch to Developer Command Prompt
remove old version
install new version
start service
That is very inconvenient. Is there a better way to do it?
The best way in my opinion is to use Debug directive. Below is an example for the same.
#if(!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
// Calling MyService Constructor
new MyService()
};
ServiceBase.Run(ServicesToRun);
#else
MyService serviceCall = new MyService();
serviceCall.YourMethodContainingLogic();
#endif
Hit F5 And set a Breakpoint on your YourMethodContainingLogic Method to debug it.
I usually put the bulk of the service implementation into a class library, and then create two "front-ends" for running it - one a service project, the other a console or windows forms application. I use the console/forms application for debugging.
However, you should be aware of the differences in the environment between the debug experience and when running as a genuine service - e.g. you can accidentally end up dependent on running in a session with an interactive user, or (for winforms) where a message pump is running.
You can write this code in program.cs
//if not in Debug
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
//if debug mode
MyService service = new MyService();
service.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
in MyService class
public void OnDebug()
{
OnStart(null);
}
You cannot run Windows Service as say another console or WinForms application. It needs to be started by Windows itself.
If you don't have infrastructure ready to use as #Damien_The_Unbeliever suggests (which is what I recommend as well) you can install the service from the debug location. So you use installutil once and point it to executable located in /bin/debug. Then you start a service from services.msc and use Visual Studio > Debug > Attach to Process menu and attach to the Windows service.
You can also consider using Thread.Sleep(10000) as the first line in the OnStart call, or Debugger.Break() to help you out to be able to attach before the service executes any work. Don't forget to remove those before the release.
You can use Environment.UserInteractive variable. Details of implementation here
Here's an easy way I use to debug Windows service applications without installing them, starting via Windows Service Control Manager, attaching to debuggers, etc. The following is in VB but hopefully you get the idea.
In this example, TestService's main class is named svcTest.vb.
Within Shared Sub Main() inside svcTest.Designer.vb, the default code looks something like this:
Dim ServicesToRun() As System.ServiceProcess.ServiceBase
ServicesToRun = New System.ServiceProcess.ServiceBase() {New svcTest}
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
Comment everything out within Main() and add the following 2 lines of code.
Dim objSvc As New svcTest()
objSvc.OnStart(Nothing)
Now just set a breakpoint where you want to start debugging, hit F11 to step into the code, and then proceed as normal as if you were working with a standard desktop application. When you're finished debugging, simply reverse the changes made within Main().
This was done using Visual Studio Enterprise 2017 on Windows Server 2012 R2.
I have a windows service application. When I press the button, I want to start the service. But I'm receiving the following the error.
Window Service Start Failure:
Cannot start service from the command line or debugger. A Windows
Service must first be installed (using installutil.exe) and then started
with the ServerExplorer, Windows Service Administrative tool or the NET
START command.
C# Code:
namespace WindowsFormsApplication1
{
partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
RegistryKey KEY = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\baslat", true);
KEY.DeleteValue("timer",true);
}
protected override void OnShutdown()
{
RegistryKey KEY = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\baslat", true);
KEY.SetValue("timer","");
}
}
}
It's telling you what to do. You need to install the service inside windows. Then you can stop and start it using the windows service control manager.
You can't start it like an exe as services have different entry points. However there is nothing stopping you from having an exe that runs under the SCM and as a normal program.
You need to install the service, as the error message suggest :
installutil.exe yourservice.exe
Then you can start it with :
net start yourservice
I've created a small executable that can be launched either as a normal application by calling MyApp.exe or as a service by calling MyApp.exe -s. Because I'm trying to keep as simple as possible, I "install" this app by manually running
sc create MyAppService binPath= "C:\MyApp\MyApp.exe -s"
Then I start the service with net start MyAppService like normal.
On two Windows XP machines and two Windows 2000 machines, this works fine. However, on two different Windows XP Embedded machines, when I try to start the service I get the message:
System error 1083 has occurred.
The executable program that this service is configured to run in does not implement the service.
On one machine, I was able to fix this by uninstalling and reinstalling .NET 2.0, but on the second machine this did not work.
I'm not sure how to go about debugging this, and searching google only seems to turn up specific services that fail with this message such as BITS and an Exchange service.
Below are the classes MyApp, which is the startup class, and MyAppService, which is the class that extends ServiceBase. Thanks in advance for any direction on this.
MyApp.cs
static class MyApp
{
[STAThread] static void Main( string[] args )
{
....
switch ( arg1 )
{
case "-s":
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyAppService() };
ServiceBase.Run( ServicesToRun );
break;
....
}
}
}
MyAppService.cs:
class MyAppService : ServiceBase
{
static MyAppService()
{
// ...
}
protected override void OnStart( string[] args )
{
// ...
}
}
On the desktop, this can happen if the service isn't registered correctly in the Windows Registry under the account that the svchost instance is supposed to run under. I don't have experience in XPe, but try looking in HKLM\Software\Microsoft\Windows NT\CurrentVersion\Svchost and make sure that MyAppService is correctly listed for the account.
Try to check in the Event log if there is useful info including Security log.
It seems did not recognize the MyAppService as a service or MyApp.exe does not expose any services to the XPe. Focus on this thing to get the root cause.
For fast testing, you can get XPe run in your development PC by using VMWare. VMWare has the way to copy the current running XPe into image and copy to your PC but not sure if it can work properly.
It appears that I have the same problem. The ServiceController.Start() does not start service successfully. The application is in C# .NET2 and running in Window XPe. The work around is below:
TimeSpan timeout = TimeSpan.FromMilliseconds(20000);
while (true)
{
ServiceController service = new ServiceController("myservice");
service.MachineName = ".";
try
{
service.Start()
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
service.Stop();
continue;
}
}
after looping 2 or 3 times, the service usually get started successfully.
But 30-40 seconds has passed. This is not acceptable.
Dos anybody have experienced on this issue? Thanks!
I have got few questions regarding creating windows service.
I have created a windows service.But Im getting an error reagrding that.
public partial class xyz : servicebase
{
public xyz()
{
InitializeCompoenent();
}
}
it couldn't resolve InitializeComponent().Does anybody any reason.
I have set it up out as console application instead of windows application.
You used the console application template? That's not right you would have to do allot of manual work like creating the InitializeComponent() method. The best solution is to create a new project using the Windows Service application template. For complete instructions see http://msdn.microsoft.com/en-us/library/zt39148a.aspx
On your project select Add->New item->Windows Service. Give a name to your service.
Now, imports the necessary code you were using from your console file (I'm guessing from the lack of information) to the service file.
So, now you will have a valid window service component in your project. You can remove the old console file.
Don't forget to modify the code in the main in Program.cs:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new YourService();
};
ServiceBase.Run(ServicesToRun);
}
}
If you want to run from the command-line for debugging purposes then check this out this answer.