Question regarding creating windows service - c#

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.

Related

How to integrate topshelf to an existing windows service project?

I want to be able to use the TopShelf debugging abilities of my service in Visual Studio.
A lot of the examples and documentation out there refer to creating a Windows Console project in Visual Studio first, and then adding TopShelf, OWIN, etc
However, in my case I already have a perfectly good and working Windows Service project called QShipsService.sln, etc... and it uses a simple Connected Service (admittedly to old SOAP legacy services).
Can someone please direct me or provide an example of how to use TopShelf, with an existing non-Console like project?
I found my own solution...
The assumption I made was the default Windows Service project defaulting to wanting to register the program as a service and kick off the OnOpen() and OnClose() methods, once the service is running.
In my case I wanted to re-use an existing service that was based on a Timer(), and it would kick in every 4 hours to call a SOAP call and return some data. What I didn't realise was the ServiceConfigurator was trying to call its own Open() and Close() methods.
So I commented out the OnOpen and OnClose methods and allowed the configurator to call my worker process via Open() method instead, which is what I was meant to have done the first time!
For the noobs out there like me, here is the code...
//using System.ServiceProcess;
using Topshelf;
namespace QShipsService
{
static class Program
{
static void Main(string[] args)
{
HostFactory.Run(
configure =>
{
configure.Service<QShipsService.QshipsService>(
service =>
{
service.ConstructUsing(s => new QShipsService.QshipsService());
service.WhenStarted(s => s.QStart());
service.WhenStopped(s => s.QStop());
});
//Setup Account that window service use to run.
configure.RunAsLocalSystem();
//add details and names about the service
configure.SetServiceName("QshipsService");
configure.SetDisplayName("QshipsService");
configure.SetDescription("QshipsService Windows Service to extract data from the QSHIPS SOAP service. Data is recorded and maintained inside the SPOT's database in POT-DB.");
});
//## USE THIS IF WE'RE NOT USING TOPSHELF !! ##
// //this loads and starts the QshipsService (see QshipsService.cs program)
// ServiceBase[] ServicesToRun;
// ServicesToRun = new ServiceBase[]
// {
// new QShipsService.QshipsService()
// };
// ServiceBase.Run(ServicesToRun);
}
}
}

create setup for windows service c#

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.

Multiple service processes (System.ServiceProcess.ServiceBase) in one Windows Service

I've got two service processes (derived from System.ServiceProcess.ServiceBase)
MyService1 and MyService2.
I'm trying to run them both in the Main() of a Windows Service's Programm.cs.
static void Main()
{
ServiceBase[] servicesToRun = { new MyService1(), new MyService2() };
ServiceBase.Run(servicesToRun);
}
In the OnStart methods of both MyService1 and MyService2 I write to a log file so I can tell they are running.
The system builds fine and I can install the service.
But only MyService1 runs. MyService2 doesn't do a thing (i.e. no start-up log entry). When I change the order in the array:
ServiceBase[] servicesToRun = { new MyService2(), new MyService1() }
only MyService2 runs.
To try to get to the bottom of this, I'm using a little tool AndersonImes.ServiceProcess.ServicesLoader (https://windowsservicehelper.codeplex.com/) to get around the limitation that you cannot directly debug a windows service in Visual Studio. With this tool I can get both services MyService1 and MyService2 to start and run next to each other. But I still don't know why Windows is running only the first item in the ServiceBase[] servicesToRun array.
Any ideas?
I finally found the answer here: http://www.bryancook.net/2008/04/running-multiple-net-services-within.html. A well hidden resource, thanks 'bryan'! Hopefully this helps the next developer to save time...
The explanation there around ServicesDependedOn isn't quite matching what I see in my project though. It's not about starting them but making sure they are started. Check out https://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.servicesdependedon%28v=vs.110%29.aspx as well. I don't need this because they do not depend on each other.

Host Web API as Windows Service using OWIN

I'm trying to run a Web API application as a Windows Service using OWIN. However, I get the following message, when trying to start the service:
The [ServiceName] service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.
For some reason my service doesn't understand that it should keep listening to http://localhost:9000
The VS solution consists of two projects: The Web API and the Windows service.
In the Windows service project I have:
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service()
};
ServiceBase.Run(ServicesToRun);
}
}
public partial class Service : ServiceBase
{
private const string _baseAddress = "http://localhost:9000/";
private IDisposable _server = null;
public Service()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_server = WebApp.Start<Startup>(url: _baseAddress);
}
protected override void OnStop()
{
if (_server != null)
{
_server.Dispose();
}
base.OnStop();
}
}
In OnStart the Startup refers to the Startup class in the Web API project:
public class Startup
{
public void Configuration(IAppBuilder builder)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute("Default",
"{controller}/{id}",
new { id = RouteParameter.Optional });
builder.UseWebApi(config);
}
}
(It also contains some configurations for Unity and logging.)
I guess the installer part of the Windows service project is mostly irrelevant, though it could be useful to know that I have:
this.serviceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalService;
What I've tried:
To host the Web API using a console application and then host the console application as a Windows Service. But even though I included 'Console.ReadKey()', it simply stopped.
To follow this guide:
OWIN-WebAPI-Service
The weird thing is that I can get his service to work, but when I tried changing my code to match his set-up, I kept getting the same error.
Full source code:
github.com/SabrinaMH/RoundTheClock-Backend/tree/exploring_hosting
When you are getting 'service on Local Computer started and then stopped', generally means there's uncaught exception while starting the service. Take a look at Windows service on Local Computer started and then stopped error, for tips to look for that exception.
Based on what you described, my guess the issue is caused by the Startup class exists on a different project, have you tried to have the startup class within the window service project?
Also, the link from HStackOverflow (https://github.com/danesparza/OWIN-WebAPI-Service), shows a work-around approach to load controllers from different project, or dynamically resolve assembly into the current AppDomain. I guess that's also worth trying.
Hope this helps.
For that example OWIN-WebAPI-Service, you must install Package
Install-Package Microsoft.Owin.Host.HttpListener

Call Web Services from Windows Service

I created a Web Service where I take data from a database and insert
them into a list of string type. This web service is called from a
Windows Service that receives the list and retrieving the data. To do
this I added the reference to the Windows Service, but I do not know
if I get the list from the Web Service correctly. This is the code of
the windows service:
RicDati ricdati = new RicDati();
var listas = ricdati.PrelevaDati().Count();
List<string> lista = new List<string>();
lista.AddRange(ricdati.PrelevaDati());
RicDati is the class of the Web Service, PrelevaDati is the name of the method
I think is more a matter of debugging your windows service, sometimes this could be very difficult but ic an suggest a workarround.
Practically you need to create a console application or windows that practically is going to create and call a windows service instance without even intall it on your computar, this practically feels like you're debugging a normal windows application.
this is a project that uses a winform to debug win services I'm more into a consolo (because I feel it's easier), but the concept is the same so you can take a look.
enter link description here
the main code practically is the following:
using System.ServiceProcess;
using ServiceProcess.Helpers;
namespace DemoService
{
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);
ServicesToRun.LoadServices();
}
}
}
Before running it in a Service, run/debug the parts which are not service related in a console application.
Create a library project of your business processes which the service will use, but also the console application. This will contain the call to the webservices.
Test the process in the console without having the unknowns of a service.
Once the processes are working then run it in the service.

Categories