I have made one console application for email notification in c#.
Can i convert this console application in to window service?
Thanks.
In visual studio, create a "Windows Service" project instead of a "Console Application". Look in the code that gets generated for you. There will be an OnStart() and OnStop() method. Those are the methods that will be called when your service is started and stopped. Put your code in those methods and you will have a Windows Service.
Contrary to some of the suggestions made by other answers, you probably can't do what you want using a Windows Service. It can't display the "notification" you expect because services can't display any kind of user interface.
The appropriate solution is to create a regular application that runs in the background without showing any windows. You can't do this with a console application (well, you can, but let's not overcomplicate things) because each time you run it, the console window will be displayed. But if you create a standard Windows application (either a Windows Forms or WPF application) then just don't create a window, everything will work out just fine.
You'll probably want to create and place an icon into the taskbar's notification area, which will handle displaying the notification upon the arrival of email. If you're creating a WinForms application, this can be done easily by using the NotifyIcon component.
Something like (warning, written without the aid of a compiler!):
static class Program
{
[STAThread]
static void Main()
{
// Standard infrastructure code
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Create a context menu and add item(s) to it
ContextMenu mnu = new ContextMenu();
MenuItem mnuExit = new MenuItem("E&xit");
mnu.MenuItems.Add(mnuExit);
mnuExit.Click += mnuExit_Click);
// Create the NotifyIcon
NotifyIcon ni = new NotifyIcon();
ni.Icon = new Icon(GetType(), "icon.ico");
ni.Text = "Email Notifier";
ni.ContextMenu = mnu;
ni.Visible = true;
// Run the application
Application.Run();
// Before exiting, remove the NotifyIcon from the taskbar
ni.Visible = false;
}
private static void mnuExit_Click(object Sender, EventArgs e)
{
Application.Exit();
}
}
When I go about this, I write the application in a class that does not consider its self a console application. By that I mean I dont write to the Console. I use log4net to write everything to... just log to Info. Use the console app to call the application class and in the app.config you can have an appender for console logging... so you get the console output. In the windows service this will just write to a file or not at all for the Info level logging. Its important to note the differences between a console app and a service... a service is not interactive and you can not input anything, so you app must consider this. For the windows service use the same class, but use the windows service project to start it.
ApplicationLogic: Has all the logic to run the application. Can take the arguments to make the app run the way it needs to, but does not interact with the console (can, but it would be bad design). Writes everything to logging (log4net maybe).
ConsoleApp: Is a wrapper around ApplicationLogic that can prompt the user for what ever it needs, can prompt for input and send it to ApplicationLogic. Has a log4net console appender if you need to see the output from ApplicationLogic.
WindowsService: Is a wrapper around ApplicationLogic. Has predetermined logic to keep it looping and running the Application logic. Logs to a file, no console output.
Related
I've been using Windows in my audio/video production company. I've created a few Console Apps in C# that make a POST request to our Transcoding server. Through the Registry Editor in Windows I was able to create a right-click menu option and feed the path as Command Line Argument to my Console App. The app picks up the filepath, does some checks and the executes the POST request.
Since we're on Mac now, I'm trying to rebuild this functionality. I noticed the easiest way to create a right-click menu option is to build a Quick Service in Automator.
I've Set the Automator workflow to 'Workflow recieves current files or folders in any application. Then I'm using this AppleScript to fire up the Console Application:
on run {input, parameters}
tell application "Terminal"
do script "/File/Path/To/MacRightClickTest"
end tell
end run
The Console App runs this test code:
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Script Started!");
foreach (string arg in args)
{
Console.WriteLine(arg);
}
Console.ReadLine();
}
}
The Terminal does show 'Script Started' but does not show anything else.
How can I input the right clicked file(path) into my Console App on Mac? Can I use the input parameter in the AppleScript in some way?
Any help in the right direction will be appreciated.
Thanks!
Erik
I have a Window Service , that is running on my machine . I have separate console application in the same solution that is performing some functionality. In order to access the functions of the console application , I have add the *.exe file of the console application as a reference to the Window Service project.
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
{
// TODO: Insert monitoring activities here.
EventLog.WriteEntry("Monitoring the System", EventLogEntryType.Information);
string[] arr = new string[] { };
ConsoleApplication.Program.Main(null);
}
The Console application works perfectly file if I directly run through Visual Studio. However , If I call the Main() method from the Window Service I am getting a null pointer exception.
public static void Main(string[] args)
{
try
{
//CODE BREAKS HERE ON READING FROM CONFIG FILE
string genesis_sel= ConfigurationSettings.AppSettings["genesis_sel"].ToString();
}
catch (Exception ex)
{
//Exception code
}
}
Below is a snapshot of the Console application Project running in Visual Studio.
I am not sure what's causing the code to break while accessing the main method from a Window service.
Any suggestions?
Update: Added snapshot of the config file. I don't believe it's a rad access issue from the configuration file as it is reading correctly when I run the console application alone. There is an initialization issue when I access it through the window Service.
UPDATE Replaced the main method with a single event log , but still getting the same exception.
When you call the method it is running as part of your service, so it uses Environment and settings from your service. That means that you should have correct data in AppSettings of your service project. To bring more clarity: In this case function Main is part of your service and not a separate application root.
Otherwise you can run your console as separate process, but in that case you are loosing part of Control functions.
I would suggest, to separate common logic in a separate project/dll and call functions from it, it will be more clean and not so confusing
I am using Semantic Logging Application Block in our asp.net c# application. I am developing using Visual Studio 2013. I have created a listener which logs to a flat file and this works fine.
But I cannot get Console.LogToConsole to work. i.e., I don't see the log message in the Visual Studio Output window. I have checked the Immediate window and the log messages are not visible there either. Any suggestions are much appreciated.
Bit late to the party but you can create a custom event listener that writes to whatever you prefer (in this case Debug) like so:
internal class MyEventListener : EventListener
{
protected override void OnEventSourceCreated(EventSource eventSource)
{
base.OnEventSourceCreated(eventSource);
Debug.WriteLine("Listener attached to the source");
}
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
ICollection readOnlyCollectionObject = (ICollection)eventData.Payload;
object[] payload = new ArrayList(readOnlyCollectionObject).ToArray();
Debug.WriteLine(eventData.Message, payload);
}
}
And then, with our custom event listener built, we simply fire it up in the normal fashion:
var listener = new MyEventListener();
listener.EnableEvents(MyEventSource.Log, EventLevel.Informational);
MyEventSource.Log.MyEvent("Hello from the Immediate window!");
Credit to: http://www.shujaat.net/2013/08/slab-reactive-event-sourcing.html
I ran into the same thing as I first started with visual studio. Console.LogToConsole does what it says, logs to the console in a console app. Neither the Output nor Immediate windows are the console. The console looks like a DOS window. You wouldn't see this running an ASP.Net site. You would have to specifically create a console application. One note to mention, if you're debugging or running a console app within visual studio, sometimes the console window would be behind visual studio. Look for the icon that pops up in your windows task bar. Hope this helps!
Basically I need my application to run from system start until system shutdown. I figured out the following approach:
create MyApp.exe and MyService.exe
MyApp should install MyService as a service
MyService is supposed to run at startup and periodically check if MyApp is running. If it's not than start it.
That's the code I wrote for my service:
protected override void OnStart(string[] args)
{
while(true)
{
int processesCount =
Process.GetProcessesByName(Settings.Default.MyAppName).Count() +
Process.GetProcessesByName(Settings.Default.MyAppName + ".vshost").Count() +
Process.GetProcessesByName(Settings.Default.MyAppUpdaterName).Count();
if(processesCount==0)
{
//restore
var p = new Process { StartInfo = { FileName = Settings.Default.MyAppName, Arguments = "" } };
p.Start();
}
else
{
}
System.Threading.Thread.Sleep(3000);
}
}
How can I install this process so that it starts on windows start?
I'm not sure if this infinite loop in OnStart method is a good idea. Is it?
Is the general idea ok?
What I've done is have a windows service that runs the logic and main application code. Then if you need a GUI for it, have the windows service expose a web service via WCF and create a windows app that calls to the web service. On install, put you windows app in the windows startup.
This model will have the main application code running all the time, but the GUI is only up when a user is logged in.
Is the general idea ok?
As Hans points out in comments this is hostile to the user and fortunately won't work on Vista or later because services run in their own windows station. Put whatever logic you need to run all the time in the service and use an IPC mechanism such as WCF to communicate with an (optionally) running UI. If the user disables the service or exits the GUI respect their wishes...
How can I install this process so that it starts on windows start?
Add an entry to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run or HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Runthat points to your GUI application.
I'm not sure if this infinite loop in OnStart method is a good idea.
Is it?
No. You need to return from OnStart if you need to do work after OnStart returns create a Thread to do that work.
I'm building a Windows Service that uses FileSystemWatcher, and runs in the background.
I don't want to keep on uninstalling and installing the service every time I want to debug, so would like to do most of my development in a normal program before moving it into a service. But I'm quite new to this, and when I run it, it just runs through the block and exits.
What would be a good way to keep the program running?
http://einaregilsson.com/run-windows-service-as-a-console-program/
I've used this before to debug my service as a Console application based on whether its running in an interactive user environment.
public partial class DemoService : ServiceBase
{
static void Main(string[] args)
{
DemoService service = new DemoService();
if (Environment.UserInteractive)
{
service.OnStart(args);
Console.WriteLine("Press any key to stop program");
Console.Read();
service.OnStop();
}
else
{
ServiceBase.Run(service);
}
}
while (true)
{
// Execute your program's functionality here.
}
I wrote a 7 part series a while ago titled: Building a Windows Service. It covers all the intricacies of building services, making them friendly to debug, and self-installing.
The basic feature set I was looking for was as follows:
Building a service that can also be used from the console
Proper event logging of service startup/shutdown and other activities
Allowing multiple instances by using command-line arguments
Self installation of service and event log
Proper event logging of service exceptions and errors
Controlling of start-up, shutdown and restart options
Handling custom service commands, power, and session events
Customizing service security and access control
The final result was a Visual Studio project template that creates a working service, complete with all of the above, in a single step. It's been a great time saver for me.
see Building a Windows Service – Part 7: Finishing touches for a link to the project template and install instructions.
Here’s documentation from MSDN # http://msdn.microsoft.com/en-us/library/7a50syb3(v=vs.80).aspx?ppud=4 . I have tried it before and it works under .NET Framework 3.x. I could not find my descriptive notes on it, at the moment.
Use the pragma #If DEBUG for debugging purposes like console outputs. Another is using the Debug object.
If you have any trouble with this, say so. I may be able to find my notes or make a Windows Service app myself, just to see if the steps on MSDN still work.