01. Create WindowsService new project
02. Right Click on Sevice1.cs [Design] then click on "Add installer"
03. Then right click on ProjectInstaller.cs [Design] and select "View Code"
04. Open ProjectInstaller.Designer.cs then use below code
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
//
// serviceInstaller1
//
this.serviceInstaller1.ServiceName = "ERP Service";
this.serviceInstaller1.Description = "ERP Service";
this.serviceInstaller1.DisplayName = "ERP Service";
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}
05. Open Service1.cs class
public partial class Service1 : ServiceBase
{
Timer timer = new Timer(); // name space(using System.Timers;)
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
LogWritter("Service is started at " + DateTime.Now);
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 5000; //number in milisecinds
timer.Enabled = true;
}
protected override void OnStop()
{
LogWritter("Service is stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
LogWritter("Service is recall at " + DateTime.Now);
}
public void LogWritter(string message)
{
string fileName = DateTime.Now.ToString("dd-MMM-yyyy") + "_IKR.Log";
string appPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
int index = appPath.LastIndexOf("\\");
appPath = appPath.Remove(index);
string path = Path.Combine(appPath, "IKRLog" + DateTime.Now.Year.ToString());
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
File.AppendAllText(path + "\\" + fileName, "\r\n" + DateTime.Now.ToString("dd HH:mm:ss.f") + "\t" + message);
//string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
//if (!Directory.Exists(path))
//{
// Directory.CreateDirectory(path);
//}
//string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
//if (!File.Exists(filepath))
//{
// // Create a file to write to.
// using (StreamWriter sw = File.CreateText(filepath))
// {
// sw.WriteLine(Message);
// }
//}
//else
//{
// using (StreamWriter sw = File.AppendText(filepath))
// {
// sw.WriteLine(Message);
// }
//}
}
}
07. Open Command Propmt (Run as Administrator)
Goto : cd c:\Windows\Microsoft.NET\Framework\v4.0.30319
08. Type : InstallUtil.exe "C:\Users\Hameem\Documents\Visual Studio 2015\Projects\ERPService\ERPService\bin\Debug\ProjectName.exe"
Done.
Open Services and you will find your service into services.
0 Comments