How can I start a browser from a windows service - windows-services

I need to create a windows service that when launced open a specific URL.
What I did is to override the onStart() method by adding the following lines :
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("Browser must start " + DateTime.Now);
string targetURL = "http://www.mysite.com";
System.Diagnostics.Process.Start(targetURL);
}
However this thing doesn`t work . :((
Thing is that it does write the log .than means that onStart Anybody has any ideas????

The service is usually started (when it's in Automatic startup mode) when there's no user logged in.
In general, services don't interact with user desktop and work in a separate session. If you need something to be performed for each or some of logged in users, you need to write a separate agent application, which will be automatically started on user login, and with which your service will communicate. Then the agent can start the browser or do whatever else you need.

Simple answer is, if you're using Vista or later you can't. This is due to session 0 isolation. To quote from the document linked in that page:
For more complex interactions,
developers should move their UI code
into an agent that runs in the user’s
session and handles all UI
requirements. The agent communicates
with the service through RPC or named
pipes.

Windows services don't have a GUI. What you can do is create a controller that interacts with your service and have it launch a web browser.
This link doesn't directly answer your question but contains enough links in the answers to put you on the right path: How can I run a Windows GUI application on as a service?

Related

MVC scheduled mail sending

I have got an ASP.NET MVC 4 application, and I want it to send a report e-mail every week. I've read about Quartz.NET, but it's too powerful for this easy task. Now I'm trying to use NCron, but it requires an initialiser in the Main() method (with obligatory parameter args):
class Program
{
static void Main(string[] args)
{
Bootstrap.Init(args, ServiceSetup);
}
}
Is there the way to do this in the Application_Start()? What should I pass as a args param? What other solutions can solve this task?
Author of NCron speaking…
First: I have never myself integrated NCron into a web application, and I am not sure how well it will work. For instance, as Kenneth points out, IIS will shut down your app if it does not receive any traffic, and there might be other hiccups as well.
In order to integrate NCron into a web app, I suggest that you ignore Bootstrap.Init() (designed specifically as an entry point to console apps) and rather work directly with SchedulingService:
using (var service = new SchedulingService())
{
service.Hourly().Run<DataUpdateJob>();
service.Daily().Run<RecycleCacheJob>();
service.Start();
}
Again: I have never done this myself, but please do give it a try, and let me and everyone else know how you fare.
You'll have to look up what ncrone does with those parameters. What this does is pass the command-line arguments of your windows app to the component.
If you're using it on a web app, you don't have command-line args so if it needs arguments, you will have to construct the arguments yourself (either hard-coded or from a config-file or a database or ...)
It's also possible that these are optional, then you can just pass in an empty array (but again, check the docs of ncrone)
Also, keep in mind that when your application shuts down (standard that is after 20 minutes without any activity), your cron runner will not wake it up. If that will be the case you either need to keep the application alive by assuring that at least one request is done every 20 minutes or configure IIS to keep it alive always.

Nofity User some message from a windows service

I have created a windows service which gets soem info from database and I want to notify user based on the info retreived from the DB. How can I notify user from a windows service using system tray notification? Can you please show me some sample (using IPC mechanism) to get the return value of a method used in a windows service in a system tray notification?
Thanks in advance.
There are several options such as these:
Sockets: (Not too difficult to write, has firewall problems) You can find samples for it almost everywhere.
External WinForm: (The easiest method, has security problems and might blocked by
some antivirus apps) Just create a winForm with the ability to go into
the windows notification area and then tell the service to run its
exe file.
Named Pipes: (Probably the most difficult, but it's the recommended
solution) Here is a Code Project sample.
Other tricks like: Create a hidden winform project (ShowInTask=false) and put it in StartUp. provide it with a FileSystemWatcher object and make it watch for a certain file which the service creates or deletes it to signal the winform.

SignalR.Client On -eventhandler is not receiving any events

Premise:
I have a windows service, which acts as a client to an IIS-based ASP.NET MVC3 application. They are both running on the same machine, and I'm trying to make them communicate with each other through SignalR.
I'm using the SignalR.Client library downloaded from Nuget on the windows service, and I have successfully connected it to the IIS. However, now that I'm calling a function from the MVC side SignalR Hub, which should propagate to the clients (including my Windows Service) - the Windows Service is not receiving any events.
What I've tried:
I've tried subscribing to the server side events in many ways but here is my current code:
private static Connection WebUIConnection = new HubConnection(ConfigurationManager.AppSettings["localIISLocation"]);
private static IHubProxy webUiHubProxy = new HubProxy(WebUIConnection, "Hub");
----
WebUIConnection.Credentials = new System.Net.NetworkCredential(userName, password);
webUiHubProxy.On("invoke", () => Console.WriteLine("Derp"));
WebUIConnection.Start().Wait();
On the IIS side I then call:
Clients.invoke();
So, I've tried invoking things from the windows service, and those work perfectly, however - when the information needs to go from IIS-> Windows Service, absolutely nothing happens.
Now, seeing as the SignalR has dynamic binding going inside it, I don't see any exceptions being thrown and I have absolutely no idea how to approach debugging this. I've checked the application logs with Event Viewer, and there is nothing inconclusive there.
I'm thinking, if maybe there is a system in place in Windows which disallows IIS to connect to the local machine (as a security measure), but it is weird that the connection is working perfectly in one direction and not the other.
Any ideas on how to debug this, or in fact what this could be about?
Best regards,
Lari

Is it possible to programmatically determine if my app is running as a Windows Service? [duplicate]

How can I tell if the application my code is running in, is it in a service or an application? Why do I want to know this - I'm writing some code that is injected into the target application and that code has no way of knowing this information up front, so it has to work it out itself.
I cannot rely on any code being called from the service control manager, start, stop, or command line parameters.
I'm currently looking at GetConsoleWindow() which I hope will return NULL for a service (no console) and a window handle for any application (has a console). Not sure how valid this assumption is.
Any ideas for a better solution?
Search the current process id (GetCurrentProcessId) from the list of all running services (EnumServicesStatusEx)?
The assumption of GetConsoleWindow() is not valid.
It seems to me that you care about the context of your process more. Are you asking that if your program is running in service context or the user session? If so, use ProcessIdToSessionId() http://msdn.microsoft.com/en-us/library/aa382990%28v=VS.85%29.aspx to get your session id and you will know it.
Use WMI to query for Win32_Service instances where 'ProcessId=MyProcessid'. If there is no match, then your process is not a service.
Background on WMI app creation in C++ here.
For Windows Vista or later you can check the session id. Session 0 is reserved for services and non-interactive programs. User sessions start from 1.
Use OpenProcessToken to get the current process token. Then use CheckTokenMembership to see if the token includes the WinServiceSid well-known SID.

Msmq and WCF Service

I have created a WCF service using the NetMsmq binding for which i created a private queue on my machine and executed the project. This works fine as such and my WCF service is started and accesses the message using the queue in the debugging environment. Now, I wanted to host the service using the windows service and for the same I created a new project and windows installer as well (This service runs under Local System Account). Then I tried installing this windows service using the InstallUtil command through the command prompt. When installation is happening and during the service host opening, I get an exception saying:
There was an error opening the queue. Ensure that MSMQ is installed and running, the queue exists and has proper authorization to be read from. The inner exception may contain additional information.
Inner Exception System.ServiceModel.MsmqException: An error occurred while opening the queue:Access is denied. (-1072824283, 0xc00e0025). The message cannot be sent or received from the queue. Ensure that MSMQ is installed and running. Also ensure that the queue is available to open with the required access mode and authorization.
at System.ServiceModel.Channels.MsmqQueue.OpenQueue()
at System.ServiceModel.Channels.MsmqQueue.GetHandle()
at System.ServiceModel.Channels.MsmqQueue.SupportsAccessMode(String formatName, Int32 accessType, MsmqException& msmqException)
Could anyone suggest the possible solution for the above issue? Am I missing any permissions to be set for the queue as well as the windows service, if so could you suggest where should these permissions be added?
Tom Hollander had a great three-part blog series on using MSMQ from WCF - well worth checking out!
MSMQ, WCF and IIS: Getting them to play nice (Part 1)
MSMQ, WCF and IIS: Getting them to play nice (Part 2)
MSMQ, WCF and IIS: Getting them to play nice (Part 3)
Maybe you'll find the solution to your problem mentioned somewhere!
Yes, it looks like a permissions issue.
Right click on your private queue from the Server Manager, and select Properties. Proceed to the Security tab, and make sure you have the right permissions in there for your Local System Account.
This is also confirmed in Nicholas Allen's article: Diagnosing Common Queue Errors, where the author defines the error code 0xC00E0025 as a permissions problem.
I ran into same problem, here is the solution.
Right click "My Computer" --> Manage. In Computer Management window go to "Services and Applications --> Message Queueing --> ur queue", select ur queue and access properties. Add the user running ur WCF application and give full access. This should solve the issue.
Can simple be that the service can't find the it's queue.
The queue name must exact match the endpoint address.
Example:
net.msmq://localhost/private/wf.listener_srv/service.svc
points to local queue
private$\wf.listener_srv\service.svc
If queue name and endpoint are according to each other, then is most like that the credentials defined on the IIS pool don't grant access to the queue.

Resources