Windows Service Issue in C# - c#

I have designed a window service in which I called RunProgram Method from OnStart().. But when I install its pakage it is not showing in service console.... Any suggestions are most welcome....
protected override void OnStart(string[] args)
{
base.OnStart(args);
rd = new Thread(new ThreadStart(RunProgram));
rd.Start();
}
my Installer class is as follows....
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Management;
using System.ServiceProcess;
using System.Linq;
namespace WindowsService1
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
public System.ServiceProcess.ServiceController serviceController = new ServiceController();
private void ProjectInstaller_Committed(object sender, InstallEventArgs e)
{
serviceController.ServiceName = "MyTestingService";
ConnectionOptions coOptions = new ConnectionOptions();
coOptions.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope mgmtScope = new System.Management.ManagementScope(#"root\CIMV2", coOptions);
mgmtScope.Connect();
ManagementObject wmiService;
wmiService = new ManagementObject("Win32_Service.Name='" + this.serviceController.ServiceName + "'");
ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");
InParam["DesktopInteract"] = true;
ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);
this.serviceController.Start();
}
}
}
My Service Class is as follows....
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.IO;
using System.Web;
using System.Threading;
namespace WindowsService1
{
public partial class MyTestingService : ServiceBase
{
public MyTestingService()
{
InitializeComponent();
}
System.Threading.Thread rd;
protected override void OnStart(string[] args)
{
base.OnStart(args);
rd = new Thread(new ThreadStart(RunProgram));
rd.Start();
}
protected override void OnStop()
{
}
public void RunProgram()
{
//My Code to do here
}
}
}

Have you any logging file? Maybe there is some error in your webservice. You can debug your webservice too.
static void Main()
{
#if (!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new Service1Component() };
ServiceBase.Run(ServicesToRun);
#else
Service1Component s = new Service1Component();
s.RunProgram();
#endif
}
P.s. s.RunProgram() is your method that you can use it for debug.

have you tried this?
http://msdn.microsoft.com/en-us/library/zt39148a.aspx
I remember that in old services prior to .NET you shoud also register the service installing it
The installer had a specific key, smth like "autoregister"

Once you have your service built, you have to run the following command from a Visual Studio Command Propt:
installutil [/u[ninstall]] [options] assembly [[options] assembly] ...
Full info here

Please cross check whether you have done the following steps:
1.After creating the windows service project go to the service class's design view(just double click the service1.cs class).
2.In the design view right click and select Add Installer. This will create an Installer class named ProjectInstaller.cs. With out ProjectInstaller.cs or any error in configuring ProjectInstaller.cs may result in non-showing of the service in service console.
3.Go to the design view of ProjectInstaller.cs you will find two installers there->
a.**ServiceInstaller1**
b.**ServiceProcessInstaller1**
4.Right click ServiceInstaller1 and go to the properties tab
a.Edit the ServiceName with the name you want to
see your service in the service console.
b.Change the **StartType** to **Automatic**.
5.Right click ServiceProcessInstaller1 and go to the properties tab
a.Change the account to **LocalService**
6. Save and try it.
Hope this will help you........

Related

How to use .dll 32bit run on Excel 64bit VSTO C#

I have 2 projects in a solution :One is Console Project where communicate with PLC and another is Excel add-in project.
My Problem: using .dll (x32bit) and run on Excel 64bit. Control button by Ribbon button to connect or disconnect to PLC. So, I added Excel add-in project in Console Project's references to use Excel add-in public class. But, i cannot call constructor of VSTO Addin
public ThisAddIn(global::Microsoft.Office.Tools.Word.ApplicationFactory factory, global::System.IServiceProvider serviceProvider) :
base(factory, serviceProvider, "AddIn", "ThisAddIn") {
Globals.Factory = factory;
}
Here my code in Console:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using Microsoft.Office.Tools.Ribbon;
using PLC2EXCEL_Addin;
using DATABUILDERAXLibLB;
using Microsoft.Office.Tools.Ribbon;
using System.Runtime.InteropServices;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;
namespace PLC2EXCEL
{
class Program
{
public static DBCommManager dBCommManager = new DBCommManager();
static void Main(string[] args)
{
dBCommManager.PLC=DBPlcId.DBPLC_KV3000;
dBCommManager.Peer = "USB";
//Microsoft.Office.Tools.Excel.ApplicationFactory _fatory ;
//_fatory.GetRibbonFactory();
//ThisAddIn thisAddIn = new ThisAddIn(Microsoft.Office.Tools.Excel.ApplicationFactory,IServerProvider); //i am not sure about this
PLC2EXCEL_Ribbon pLC2EXCEL_Ribbon = new PLC2EXCEL_Ribbon();
if (pLC2EXCEL_Ribbon != null)
pLC2EXCEL_Ribbon.connectPLC_btn.Click += new RibbonControlEventHandler(startPLC2Excel);
dBCommManager.Connect();
Console.WriteLine("Connect PLC OK");
Console.ReadLine();
}
public event EventHandler startPLC2Excel1;
public static void startPLC2Excel(object sender, RibbonControlEventArgs eventArgs)
{
//DATABUILDERAXLibLB.DBCommManager dBCommManager = new DBCommManager();
//dBCommManager.PLC = DBPlcId.DBPLC_KV3000;
//dBCommManager.Peer = "USB";
dBCommManager.Connect();
Console.WriteLine("Connect PLC OK");
Console.ReadLine();
}
}
}
And code in Ribbon of Excel Addin:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Tools.Ribbon;
namespace PLC2EXCEL_Addin
{
public partial class PLC2EXCEL_Ribbon
{
private void PLC2EXCEL_Ribbon_Load(object sender, RibbonUIEventArgs e)
{
}
[ComVisible(true)]
public void connectPLC_btn_Click(object sender, RibbonControlEventArgs e) //How to catch this event from Console project
{
//Catch event
MessageBox.Show("Connect to PLC");
}
public void abc() { }
}
}
Sorry any inconvenience, this is my first post.
Thank in advance.
Impossible to use .dll 32bit on 64bit Excel,So I have solved my problem by create 2 separate projects:
One is C# app adding .dll 32bit and communicate to PLC and send data
to opened excel file.
Anther is Excel Addin with ribbon buttons,
launch/stop executive C# app when click button

C# UI Test being ignored and not running?

So I wrote a test and am trying to run it but when I right click it and hit, "Run Selected Test" the green loading bar moves up for less than a second and just stops. Fairly new to this so excuse my ignorance.
Test being ignored & not running.
This is the stack trace I get from the test output when I try to run it.
This is my session class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium.Windows;
using OpenQA.Selenium.Remote;
public class CCSession
{
// Note: append /wd/hub to the URL if you're directing the test at Appium
protected const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
protected static WindowsDriver<WindowsElement> session;
private const string ExcelAppId = #"C:\Program Files\Microsoft Office\root\Office16\EXCEL.exe"; // test
public static void Setup(TestContext context)
{
// Launch Excel application if it is not yet launched
if (session == null)
{
// Create a new session to launch Excel application
DesiredCapabilities appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("app", ExcelAppId);
appCapabilities.SetCapability("deviceName", "WindowsPC");
session = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
Assert.IsNotNull(session);
session.FindElementByName("Blank workbook").Click();
// Verify that Excel is started with untitled new file
Assert.AreEqual("Book1 - Excel", session.Title);
// Set implicit timeout to 1.5 seconds to make element search to retry every 500 ms for at most three times
session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1.5);
}
}
public static void TearDown()
{
// Close the application and delete the session
if (session != null)
{
session.Close();
try
{
// Dismiss Save dialog if it is blocking the exit
session.FindElementByName("Don't Save").Click();
}
catch { }
session.Quit();
session = null;
}
}
}
Test class:
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Api.Dto;
using CEL.CostCalculator.Api.CalculationResults;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA;
using OpenQA.Selenium.Appium.Windows;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Remote;
using Tests.Fixtures.DataPorts;
[TestClass]
public class CCExcelAddInTests : CCSession
{
[TestMethod]
public void EditorEnterText()
{
Assert.AreEqual("Book1 - Excel", session.Title);
}
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
Setup(context);
}
[ClassCleanup]
public static void ClassCleanup()
{
TearDown();
}
}
Any help's appreciated. :)
My test projects .csproj file was corrupted. Corrected and tests are visibly running again.

How to start a process/application on windows connection change event using C#

I can detect the network connection change event while running a C# code, how would I register an exe when Windows detects this event. What all details would I need. Below is how I am using this :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
testing t = new testing();
Console.Read();
}
}
public class testing{
public testing()
{
NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
}
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
if (e.IsAvailable)
{
Console.WriteLine("network is available");
}
}
}
}
What you could maybe do is in your method that is triggered to start a new process and execute your exe

What's wrong my windows service on windows 2012?

I have written multiple windows services in one exe & created setup/deployment package to install on destination server (windows 2012). I can see all services in Services & able to start them but it is not performing required action..Weird!!
Program.cs
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new service1(),
new service2(),
new service3()
};
ServiceBase.Run(ServicesToRun);
service1.cs
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.Configuration;
using System.Net;
using System.Xml;
using System.IO;
namespace MyService
{
partial class service1: ServiceBase
{
public service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
StreamWriter str = new StreamWriter("D:\\temp\\Text1.txt", true);
str.WriteLine("text");
str.Close();
try
{
//more functionality
EventLog.WriteEntry("done", "done desc", EventLogEntryType.Information);
}
}
catch (Exception ex)
{
EventLog.WriteEntry("Error", ex.Message, EventLogEntryType.Error);
}
}
protected override void OnStop()
{
base.OnStop();
}
}
}
When I start service1 manually, it doesn't perform any action..Neither I see text file getting created nor any error/info in event log. What's wrong? Am I missing something wrong???
Appreciate for help!

Getting a Service to Run Inside of an Azure Worker Role

I have a windows service that I need to migrate to onto Azure as a Worker Role. Everything builds fine in my Azure solution. However, when I upload everything only the web role starts. The worker role instance gets stuck cycling between the following two statuses without ever starting.
Waiting for the role to start...
Stabilizing role...
Since the instance is failing to start I suspect my problem lies somewhere in my WorkerRole.cs code. Below you'll find that code. I've also included the code for the service in case it's relevant to the question. What did I do wrong?
This is my WorkerRole.cs file:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using System.ServiceProcess;
namespace SBMWorker
{
public class WorkerRole : RoleEntryPoint
{
public override void Run()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
//Thread.Sleep(Timeout.Infinite);
}
}
}
This is my Service1.cs 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 Lesnikowski.Mail;
namespace SBMWorker
{
public partial class Service1 : ServiceBase
{
private System.Timers.Timer mainTimer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
// config the timer interval
mainTimer = new System.Timers.Timer(foo.Framework.Configuration.SecondsToWaitBeforeCheckingForEmailsToProcess * 1000);
// handling
mainTimer.Elapsed += new System.Timers.ElapsedEventHandler(mainTimer_Elapsed);
// startup the timer.
mainTimer.Start();
// log that we started
foo.Framework.Log.Add(foo.Framework.Log.Types.info, "SERVICE STARTED");
}
catch (Exception ex)
{
try
{
foo.Framework.Log.Add(ex, true);
}
catch{throw;}
// make sure the throw this so the service show as stopped ... we dont want this service just hanging here like
// its running, but really just doing nothing at all
throw;
}
}
protected override void OnStop()
{
if (mainTimer != null)
{
mainTimer.Stop();
mainTimer = null;
}
// log that we stopped
foo.Framework.Log.Add(foo.Framework.Log.Types.info, "SERVICE STOPPED");
}
void mainTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
mainTimer.Stop();
bool runCode = true;
if (runCode)
{
try
{
// call processing
foo.Framework.EmailPackageUpdating.ProcessEmails();
}
catch(Exception ex)
{
try
{
// handle error
foo.Framework.Log.Add(ex, false);
}
catch { throw; }
}
}
mainTimer.Start();
}
}
}
I think the root of your problem is that you basically can't install a service programmatically in Azure roles. You need to use a .cmd startup script and the InstallUtil to properly install the service then you can start it from the script or from your code (think from the script is often preferred for order-of-execution reasons).
Here's a blog post on how to do it: http://blogs.msdn.com/b/golive/archive/2011/02/11/installing-a-windows-service-in-a-worker-role.aspx
Here's another blog post that takes a little different approach (creating a .Net app that executes the installation, but again as part of the startup script): http://www.bondigeek.com/blog/2011/03/25/runninginstalling-a-windows-service-in-an-azure-web-role/
Hope that helps

Categories