What's wrong my windows service on windows 2012? - c#

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!

Related

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.

Windows service webs server cannot connect to other machines

I am attempting to design a windows service that contains a web server to do basic get request handling. Requests from the localhost work just find but I am unable to process requests from other machines. On python, setting the IP address to 0.0.0.0 allows the server to process requests from any IP on the network. I have found examples that use http://*:port/ or http://+:port/ to obtain this functionality in C# but these have not worked for me.
I am currently starting a HttpListener (WebServer.cs) when the windows service (UsherService.cs) receives its start command. If there is a better way to do this, I'd appreciate that answer as well.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace UsherService
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new UsherService()
};
ServiceBase.Run(ServicesToRun);
}
}
}
UsherService.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace UsherService
{
public partial class UsherService : ServiceBase
{
WebServer ws;
public UsherService()
{
InitializeComponent();
}
public static string SendResponse(HttpListenerRequest request)
{
return string.Format("<HTML><BODY>My web page.<br>{0}</BODY></HTML>", DateTime.Now);
}
protected override void OnStart(string[] args)
{
try
{
ws = new WebServer(SendResponse, "http://*:5000/");
ws.Run();
System.IO.File.AppendAllText(#"C:\Users\kburd\Desktop\WriteText.txt", "Started Successfully");
}
catch(Exception e)
{
System.IO.File.AppendAllText(#"C:\Users\kburd\Desktop\WriteText.txt", e.Message);
}
}
protected override void OnStop()
{
System.IO.File.AppendAllText(#"C:\Users\kburd\Desktop\WriteText.txt", "Stopped Successfully");
}
}
}
WebServer.cs
using System;
using System.Net;
using System.Text;
using System.Threading;
public class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, string> _responderMethod;
public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
{
if (!HttpListener.IsSupported)
throw new NotSupportedException(
"Needs Windows XP SP2, Server 2003 or later.");
// URI prefixes are required
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// A responder method is required
if (method == null)
throw new ArgumentException("method");
foreach (string s in prefixes)
{
_listener.Prefixes.Add(s);
System.IO.File.AppendAllText(#"C:\Users\kburd\Desktop\WriteText2.txt", s);
}
_responderMethod = method;
_listener.Start();
}
public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
: this(prefixes, method) { }
public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
string rstr = _responderMethod(ctx.Request);
byte[] buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch { } // suppress any exceptions
finally
{
// always close the stream
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch { } // suppress any exceptions
});
}
public void Stop()
{
_listener.Stop();
_listener.Close();
}
}
The firewall was blocking the localhost from communicating to other devices on the network. I had to allow for communication over that port

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

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

Windows Service Issue in 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........

Categories