Windows Service without the VS2005 template - c#

I have the VS2005 standard edition and MS says this:
Note: The Windows Service Application
project templates and associated
functionality are not available in the
Standard Edition of Visual Basic and
Visual C# .NET...
Is it possible to write a Windows Service application without upgrading my VS2005 Standard edition?

If you can cut and paste, an example is enough.
A simple service to periodically log the status of another service. The example does not include the ServiceInstaller class (to be called by the install utility when installing a service application), so installing is done manually.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Timers;
namespace SrvControl
{
public partial class Service1 : ServiceBase
{
Timer mytimer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if (mytimer == null)
mytimer = new Timer(5 * 1000.0);
mytimer.Elapsed += new ElapsedEventHandler(mytimer_Elapsed);
mytimer.Start();
}
void mytimer_Elapsed(object sender, ElapsedEventArgs e)
{
var srv = new ServiceController("MYSERVICE");
AppLog.Log(string.Format("MYSERVICE Status {0}", srv.Status));
}
protected override void OnStop()
{
mytimer.Stop();
}
}
public static class AppLog
{
public static string z = "SrvControl";
static EventLog Logger = null;
public static void Log(string message)
{
if (Logger == null)
{
if (!(EventLog.SourceExists(z)))
EventLog.CreateEventSource(z, "Application");
Logger = new EventLog("Application");
Logger.Source = z;
}
Logger.WriteEntry(message, EventLogEntryType.Information);
}
}
}

Yes, look here:
http://www.codeproject.com/KB/system/WindowsService.aspx

Sure, you just need to write the code yourself. It's not actually very hard. Here are a couple of references to how to do it:
http://msdn.microsoft.com/en-us/magazine/cc301845.aspx
http://www.aspfree.com/c/a/C-Sharp/Creating-a-Windows-Service-with-C-Sharp-introduction/

Related

Windows service stops right after launching

I have following problem with the windows service I was writing:
When I start the service it stops immediately. When I was using a console app it wasn't crushing. I have no idea what's the cause of this problem.
Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ServiceModel;
using System.ServiceProcess;
using System.Configuration;
using System.Configuration.Install;
using WindowsService;
namespace WS
{
[ServiceContract(Namespace = "http://WS")]
public interface INewsReader
{
}
public class NewsReaderService : INewsReader
{
public NewsReaderService()
{
var config = new Config();
var scheduled = new Schedule(config);
scheduled.ExecuteScheduledEvents();
while (true)
{
System.Threading.Thread.Sleep(1000);
int i = 0;
}
}
}
public class NewsReaderWindowsService : ServiceBase
{
public ServiceHost serviceHost = null;
public NewsReaderWindowsService()
{
ServiceName = "NewsReaderWindowsService";
}
public static void Main()
{
ServiceBase.Run(new NewsReaderWindowsService());
}
protected override void OnStart(string[] args)
{
var thread = new System.Threading.Thread(() =>
{
while (true)
{
int i = 0;
System.Threading.Thread.Sleep(1000);
}
});
thread.Start();
serviceHost = new ServiceHost(typeof(NewsReaderService));
serviceHost.Open();
}
protected override void OnStop()
{
}
}
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller process;
private ServiceInstaller service;
public ProjectInstaller()
{
process = new ServiceProcessInstaller();
process.Account = ServiceAccount.LocalSystem;
service = new ServiceInstaller();
service.ServiceName = "NewsReaderWindowsService";
Installers.Add(process);
Installers.Add(service);
}
}
}
Well, first of all I think your OnStart method is written badly. I can't see the reason for creating a, basicly, empty thread. You should there only initialize service (If necessary), immediately start a new thread that will work for whole time and leave the OnStart method.
Second of all use try catch block, because in my opinion somewhere in there is exception and that's why your windows service stops.
Thirdly see this example WCF Hosting with Windows Service

c# Windows service with Timer not executing code

I Have following code, which does not executed when windows service starts
I found solutions here but they didn't work for me.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Configuration;
using System.Threading.Tasks;
namespace TFS_JIRA_sync
{
public partial class SyncProcess : ServiceBase
{
public SyncProcess()
{
InitializeComponent();
}
private System.Timers.Timer timer = new System.Timers.Timer();
protected override void OnStart(string[] args)
{
this.timer.Interval = ScanPeriod.period * 60000; //turn minutes to miliseconds
this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);//OnTimer;
this.timer.Enabled = true;
this.timer.AutoReset = true;
this.timer.Start();
}
private void OnTimer(object sender, System.Timers.ElapsedEventArgs e)
{
Processing proc = new Processing();
proc.doProcess();
}
protected override void OnStop()
{
}
}
}
In Programm:
using System;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Threading.Tasks;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace TFS_JIRA_sync
{
static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new SyncProcess()
};
ServiceBase.Run(ServicesToRun);
//Processing proc = new Processing();
//proc.doProcess();
}
}
}
When I comment part starting "ServiceBase[]..." and uncomment "Processing ..." in Programm class it works fine.
But when my code run as Windows service - Nothing happens
As I see your service is not going to run all the time
this.timer.Interval = ScanPeriod.period * 60000;. For your scenario
rather than having a windows service with a timer (and spending time on resolving the issue), I'd recommended to use a scheduled task (as suggested by this answer).
It references a Jon Gallow's article, that gives a lot of reasons why it is better to use a scheduled task.
If you're writing a Windows Service that runs a timer, you should re-evaluate your solution.
Put Console.ReadLine() in your code:
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new SyncProcess()
};
ServiceBase.Run(ServicesToRun);
Console.ReadLine();
}

Self-install of WInService

I've googled this one
but when i'm trying to apply it i get an error. So install/uninstall works fine, but service itself just doesn't start and after timeout it says that service doesn't respond. I don't know why. When i'm attaching to process it even doesn't enter into Main() method, static constructors and so on. I've used this addon for attach.
public static void Main()
{
AppDomain.CurrentDomain.UnhandledException += OnException;
if (Environment.UserInteractive)
{
AskUserForInstall();
}
else
{
ServiceBase.Run(new NotificatorService());
}
}
Service is also very simple:
using System.ServiceProcess;
using System.Windows;
namespace AZNotificator
{
public partial class NotificatorService : ServiceBase
{
static NotificatorService()
{
int x = 5;
}
public NotificatorService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
MessageBox.Show("Hello");
}
protected override void OnStop()
{
}
}
}
You can not call MessageBox.Show("Hello"); from the windows service since the service does not have the GUI.
If you want to do some interaction from the windows service have a look at this article
http://msdn.microsoft.com/en-us/library/ms683502(VS.85).aspx
So remove MessageBox.Show("Hello"); from your OnStart method and your service should start just fine.

My service does not loop

It is my first program for service.
If i run this code as Console, LOOP works, but if I convert it to service, it does the operation initially, but does not LOOP.
Could you help me correct it?
tnx
using System;
using System.Net;
using KICBservice;
using System.Data;
using ConsoleApplication1.Classes;
using System.IO;
using System.ServiceProcess;
using System.Configuration.Install;
using System.ComponentModel;
namespace KICBService
{
[RunInstaller(true)]
public class MyWindowsServiceInstaller : Installer
{
public MyWindowsServiceInstaller()
{
var processInstaller = new ServiceProcessInstaller();
var serviceInstaller = new ServiceInstaller();
//set the privileges
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.DisplayName = "KICB_Payment";
serviceInstaller.StartType = ServiceStartMode.Manual;
//must be the same as what was set in Program's constructor
serviceInstaller.ServiceName = "KICB_Payment";
this.Installers.Add(processInstaller);
this.Installers.Add(serviceInstaller);
}
}
class Program : ServiceBase
{
static void Main(string[] args)
{
ServiceBase.Run(new Program());
KICBservice.Service1SoapClient kicb = new KICBservice.Service1SoapClient();
kicb.ClientCredentials.Windows.ClientCredential = new NetworkCredential("register", "KICBregistr1");
kicb.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
while (true)
{
try
{
kicb.Open();
StreamWriter tw = File.AppendText("c:\\KICB.log");
NewPayment np = new NewPayment();
np = kicb.GetPayment("register", "KICBregistr1");
// Operation with Database
tw.WriteLine("----------------");
tw.WriteLine(DateTime.Now);
tw.Close();
kicb.Close();
System.Threading.Thread.Sleep(60000);
}
catch (Exception ex)
{
kicb.Abort();
}
}
}
public Program()
{
this.ServiceName = "KICB_Payment";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
//TODO: place your start code here
}
protected override void OnStop()
{
base.OnStop();
//TODO: clean up any variables and stop any threads
}
}
}
I am pasting full code of my program.
Where is that first code located?
Without that context, my best guess is that your OnStart() method fires, and then the service quits as soon the method ends because there's nothing left to do.
Also, I'm not a fan of the while (true) { Sleep(60000); // do work } pattern for services. Instead, you want to look for a function that actually blocks execution to keep your code going. Examples include TcpListener.AcceptTcpClient() and Thread.Join(). If you can't find something like that for the meat of your service, you may want to do something like set up a scheduled task instead.
You've placed the code outside of a function. What you have shown in the question should not even compile, and it certainly won't loop.
Note the //TODO: comment in the OnStart function definition:
protected override void OnStart(string[] args)
{
base.OnStart(args);
//TODO: place your start code here
}

Does WqlEventQuery contain a constructor with 1 argument?

I am trying to create a simple service in C# using VS2008 that creates a text file when the computer goes into sleep mode. My current code throws out the following error:
'SleepNotifierService.WqlEventQuery' does not contain a constructor that takes '1' arguments
Now I looked in the Object browser, and it looks like it does take in one argument. This is what the browser had to say:
public WqlEventQuery(string queryOrEventClassName)
Here is 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.Management;
using System.IO;
namespace SleepNotifierService
{
public class WqlEventQuery : EventQuery { }
public partial class Service1 : ServiceBase
{
ManagementEventWatcher _watcher;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WqlEventQuery query = new WqlEventQuery("Win32_PowerManagementEvent");
_watcher = new ManagementEventWatcher(query);
_watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
_watcher.Start();
}
protected override void OnStop()
{
_watcher.Stop();
}
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
try
{
int eventType = Convert.ToInt32(e.NewEvent.Properties["EventType"].Value);
switch (eventType)
{
case 4:
Sleep();
break;
case 7:
Resume();
break;
}
}
catch (Exception ex)
{
//Log(ex.Message);
}
}
public void Sleep()
{
StreamWriter SW;
SW = File.CreateText("c:\\MyTextFile.txt");
SW.WriteLine("Sleep mode initiated");
SW.Close();
}
public void Resume()
{
}
}
}
Am I interpreting that object browser wrong? I'm new to creating services and C#/.NET in general so it might be something trivial.
Appreciate any help,
Tomek
You're using wrong WqlEventQuery. There's one defined in System.Management and it indeed has a one-argument constructor, but there's also your custom WqlEventQuery class.
If you want to use .NET BCL's class, you'll have to fully qualify it:
var query = new System.Management.WqlEventQuery("Win32_PowerManagementEvent");
or even prefix it with global keyword:
var query = new global::System.Management.WqlEventQuery("Win32_PowerManagementEvent");

Categories

Resources