Window Service not accessing external method - c#

I m a bit new here . I am trying to learn window service from microsoft tutorial :
http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx
I installed and run it perfectly ..event logs are working Fine ...Now I am trying access One function in another c# project (named ASMSFetch) which has reference to the service project ...
This is Service .cs file code
public partial class MyNewService : ServiceBase
{
public MyNewService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
ASMSFetch.Program.UpdateSMS();
}
}
and ASMSFetch Project Program.cs
public class Program
{
static void Main(string[] args)
{
UpdateSMS();
}
public static void UpdateSMS()
{
Console.WriteLine("UpdateSMS started");
Console.ReadLine();
}
But that "UpdateSMS started" messege doesnot appear when I install and run the service from computer management -> service section ..
I tried to search it .but couldnt able to find reasonable .
Any suggestion would be helpful ...

See here...
http://msdn.microsoft.com/en-us/library/76477d2t(v=vs.110).aspx
Under item #4 - you need to call your service. If the above is all your code, then you're missing that and nothing is actually starting the service. When the OS starts your service, all it does is call the Main() method, just like any other EXE.
You need to add a line like this:
System.ServiceProcess.ServiceBase.Run(new MyNewService());

Related

VS “A project with an Output type of Class Library cannot be started directly”

I'm novice in C#. I've cloned the project, built it successfully.
Now I want to debug Postman POST request.
I found the place where that request in handled in Project. That .cs file looks like this:
namespace Blah.Something
{
public class SomethingRequest: IInterface
{
...
public object DoRequest (SomeRequest request)
{
...
}
}
}
When I start SomethingRequest class, I have this error:
I've tried to set .csproj in which SomethingRequest class is located as "Set as a Startup Project" as per suggestion here, and then rebuilt the solution, but I keep receiving same error. Can anyone help me to resolve that issue?
You can't run the classlibrary directly.
I have two solutions and you may refer to it.
First, Please create a new project(such as console app) to call the method in that library.
Like the following:
Classlibrary:
namespace Testlibrary
{
public class Student
{
public void SayHello(string name)
{
Console.WriteLine("Hello, I am {0}",name);
}
}
}
Console app:(Please add reference)
using System;
using Testlibrary;
namespace _1.Test_for_using_library
{
class Program
{
static void Main(string[] args)
{
Student s = new Student();
s.SayHello("Jack");
Console.ReadKey();
}
}
}
Result:
Second, you can change the classlibrary to the console app to call the method.
Right click the Classlibrary->Properties-> Change Output type to Console Application -> Add the following code in the Student Class.
static void Main()
{
Student student = new Student();
student.SayHello("Jack");
Console.ReadKey();
}
Finally, you will the same result as the before.

Starting a WCF from its own class constructor

I have a self hosted named pipes (not using http) wcf hosted in a class library. I am able to start the WCF by using the following method in the class library:
ServiceHost serviceHost;
public void startService()
{
// Create the service host
...
// Open Service Host
serviceHost.Open();
}
And then from a winforms test program running the following from a button click:
MyClassLib.MySvc testSvc;
private void button2_Click(object sender, EventArgs e)
{
testSvc = new MyClassLib.MySvc();
testSvc.startService();
}
This does correctly start the WCF running in the class library.
But this requires the winforms that is referencing the class library to call startService method.
What I would like is just to be able to start the service as soon as a reference to the class library that will be running the WCF is done.
I have attempted to add the following in the class library service's constructor:
public MySvc()
{
startService();
}
And then instantiate from the winforms:
MyClassLib.MySvc testSvc;
private void button2_Click(object sender, EventArgs e)
{
testSvc = new MyClassLib.MySvc();
//testSvc.startService(); //No need to call this
}
If I debug the code, I can see that in fact it does break at this point:
public MySvc()
{
startService(); // It does run this but service does not start
}
But this does not run the service. Any help would be appreciated.
Note #1: I believe its some type of timing issue where it does not let you start the service during the constructor method but not sure of that.
Problem resolved and yes my assumption that it was a timing issue (See Note# 1 above) was correct!
To replicate, change this:
public MySvc()
{
startService(); // It does run this but service does not start
}
To this and problem solved:
public void delayStartService()
{
Task.Delay(1000).ContinueWith(t => startService());
}
public MySvc()
{
delayStartService();
}

OnStart in serviceAppliction don't work

I building a service that will edit db data form me.I want to run Encrypt for connectionString when service starts/or recive reuqest and i can't catch the OnStart
What i am diing wrong?
My class
public class Service1 : IService1
{
protected void OnStart(string[] args)
{
string stop="";
//can't get here
//here Encrypt the section.
// section.SectionInformation.ProtectSection("DataProtectiond");
}
public string GetData(int value)
{
//my functions
}
}
While debugging a service it's very hard to catch the OnStart method. You can't run a service from Visual Studio, and in production, the OnStart method is already called before you can attach your debugger. What you can do is put the following code in the OnStart method:
System.Diagnostics.Debugger.Launch()
This will pop up a window where you can select a debugger. If you have Visual Studio solution already open, you can select this and the debugger will be attached to your service.
To "run your service" from Visual Studio, you can put something like this in your Main():
static void Main()
{
if (!Environment.UserInteractive)
{
// Startup as service.
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyServices()
};
ServiceBase.Run(ServicesToRun);
}
else
{
//Start things locally here,
//for example the same things you do in the OnStart() method of your service
}
}
Now you can simply run the program from Visual Studio, but it will also work as a service when you install it on your production server...

Why won't this service start

I have a Windows Service that I'm having some problems getting working.
The pertinent functions are as follows:
( Edited to reflect current )
static void Main()
{
if (Debugger.IsAttached)
{
ContinuumService Service = new ContinuumService();
Service.Start(new Object[] { });
while (true)
Thread.Sleep(1);
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ContinuumService()
};
ServiceBase.Run(ServicesToRun);
}
}
public ContinuumService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
}
protected override void OnStop()
{
base.OnStop();
}
My installer is set to 'Allow service to interact with desktop' ( as I cannot seem to get the service to install without this ), and I know that the service is being installed - but is incapable of starting for some reason.
It's my understanding that a service Start command will execute OnStart and wait for that method to complete. Upon completion if the process is still running, the service reports running... If this is skewed please let me know.
The exact error I am getting back from the installer is 'Service '[display name]' ([name]) failed to start. Verify that you have sufficient privileges to start system services.'; and from the log that is generated behind the installer, I get an error 1920 with the same message.
In either case - I can't come up with a valid reason why this would be the case. Any advice would be great.
I believe your problem is both the loops and lack of base.OnStart() and base.OnStop() calls. You can start and stop a basic service with no loops, and it will run perpetually. Example basic service that literally does nothing:
public class ExampleService : ServiceBase
{
private static void Main()
{
ServiceBase.Run(new[] { new ExampleService() });
}
public ExampleService()
{
// Name the Service
ServiceName = "Example Service";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
// Does nothing
}
protected override void OnStop()
{
base.OnStop();
}
}
Try implementing this, see that it works, and incrementally add your logic and test.
Apparently there was an issue in my installer. After flipping options off, on, back off, inside out, and every other direction I could, I somehow corrupted the MSI, and had to rebuild it. A full wipe of the original installer project and a fresh build installed the service successfully. This was an issue in Advanced Installer 9.3
Thanks.

Testing the Application class doesn't shutdown the application after the test is done

My WPF application has an App class, and it inherits from System.Windows.Application.
Inside this class I have my exception handling that handles DispatcherUnhandledException, so any un handled exceptions may be caught and be presented to the user.
To test this I start my test with
//Arrange
app = new App();
and then I continue with the rest of the test setup.
Later on in my test I run this code:
//Act
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new MyDlg(RaiseArgumentNullException));
This triggers ApplicationStartup to be executed in the App class.
When my next test starts it also creates a new App class, and also uses the CurrentDispatcher.Invoke to create another type of exception. However, the first Application seems to be running.
If I run my two tests one by one, they work just fine. But if I run them in sequence the second one fails.
Does anyone have any idea of how to properly shut down the Application after the test is done?
I have tried the following ways to shut the application down, but it doesn't work.
static void CloseApp()
{
Application.Current.Shutdown();
}
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Send, new MyDlg(CloseApp));
app.Shutdown();
Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Send);
This is how my code looks like:
delegate void MyDlg();
static void RaiseArgumentNullException()
{
throw new ArgumentNullException();
}
[Test]
public void MyTest()
{
//Arrange
app = new App();
//...
//Act
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new MyDlg(RaiseArgumentNullException));
//Assert....
//Tear Down
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Send, new MyDlg(CloseApp));
app.Shutdown();
Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Send);
}
And this is my App class:
public partial class App : Application
{
public App()
{
Startup += ApplicationStartup;
DispatcherUnhandledException += AppDispatcherUnhandledException;
Bootstrapper.InitializeIoc();
}
private void ApplicationStartup(object sender, StartupEventArgs e)
{
//Do startup stuff
}
void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
HandleException(e.Exception);
e.Handled = true;
}
//....
}
The Application class does not allow more than one instance of Application (or any subclass) to be created per AppDomain. This is regardless of whether the Application is still running or not. From MSDN:
Application implements the singleton pattern to provide shared access
to its window, property, and resource scope services. Consequently,
only one instance of the Application class can be created per
AppDomain.
To work around this, you could create an AppDomain in each of your tests.

Categories

Resources