Semantic Application Logging Block - Console logging in asp.net application - c#

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!

Related

How to input filepath into Console App on Mac when using Automator Quick Service

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

Performance and diagnostics with "Cannot start service... A Windows Service must first be intalled (using installutil.exe)..."

Presently, I am attempting to profile a Windows service that I am working on using the new "Performance and Diagnostics" feature in Visual Studio 2013 (see http://blogs.msdn.com/b/visualstudioalm/archive/2013/07/12/performance-and-diagnostics-hub-in-visual-studio-2013.aspx). When I attempt to profile the service, I get this error message:
Cannot start service from the command line or a debugger. A Windows Service must first be intalled (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative Tool or the NET START command.
Normally when debugging the service, it works fine because I have the following code in Program.cs:
private static MySvc _serviceInstance;
private static readonly List<ServiceBase> _servicesToRun =
new List<ServiceBase>();
static void Main(string[] args)
{
_servicesToRun.Add(_serviceInstance);
if (Environment.UserInteractive)
{
_servicesToRun.ToArray().LoadServices();
}
else
{
ServiceBase.Run(_servicesToRun.ToArray());
}
}
static Program()
{
_serviceInstance = new MySvc();
}
Also, if I attempt to attach to a running app, in the dialog that appears it doesn't display any executing processes, and when I put the name of the service in there, it does not find it. Does anyone have any suggestions? TIA.
UPDATE: This is what I get when I attempt to attach to a process. Why doesn't the "Performance and Diagnostics" see any processes running on my computer? Why would it only connect to Windows Store apps instead of all exes? Please see this image:
The way I resolved the problem was the copy all the source code and make minor modifications to get everything to run in a Console application, then chose Debug->Performance and Diagnostics and ran the Console application using "Change Target" -> "Launch and executable file (.exe)"

Keep C# application running

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.

Windows Services for Console application in C#.net

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.

Windows Service Not Starting After Installing

Well, I have created a new windows service and the install from Visual Studio.
When I am done installing, how can I start the service ?
I need something that will allow me to start the process, or an exe.. something?
The Installer is : Visual Studio Installer - Setup Project.
Any help?
My question in order:
Why the service don't start?
How can i control what happen after intall ? Where is the code for it?
Thanks!
even you Set the startup type to Automatic it will not start your service automatically until the machine restart. what you can do is create event handler for AfterInstall event of your service installer class and start the service using ServiceController Start method as below
public serviceInstaller()
{
this.AfterInstall += new InstallEventHandler(serviceInstaller_AfterInstall);
}
void serviceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
ServiceController sc = new ServiceController(serviceInstaller.ServiceName);
sc.Start();
}
you can create event using the visual studio event window as well.
to start your service you can either execute the command:
net start YourServiceName
or go to Control Panel -> Admin tools -> Services and select your service and click start.
full path above depends also on your actual windows version.
even if you did not use any logging, in general service failures are recorded in the Windows Event Log so open Event Viewer and see latest events.
Set the startup type to Automatic in the ServiceInstaller class properties (you can do it in the Designer file).
A windows service needs to be installed ( it should tell you what to do if you try debugging it ), then started in the server manager. Then you can attach to it.
They are a bit of a pain to debug, TBH.
What does the service do? is it opening SQL connections?
looking for a file?
check in your event viewer where the service is installed for errors after you try to start it, it will give us a better understanding.
It is impossible to understand your question unless you take interest in making it understandable.
However from my assumption,
Goto Visual studio Tools => Visual Studio command prompt
use command net start <>
If fails starting the servicce, Check event log (eventvwr.msc in run dialog) to see if there any relevant errors logged.
Your Windows service working in some systems.
If you face some system getting error Windows Service not starting after installing if manually/automatically.
if the service starts and stops like that, it means your code is throwing an unhandled exception. This is pretty difficult to debug, but there are a few options.
Consult the Windows Event Viewer.
Event Viewer - eventvwr.msc
Normally you can get to this by going to the computer/server manager, then clicking Event Viewer -> Windows Logs -> Application. You can see what threw the exception here, which may help, but you don't get the stack trace.
Event Viewer Log Image
Add try/catch block in your service start method.
Let you check whether you are using any hot code(For Ex: "D:\"). That drive is not available in installed system.
This will helps a lot!

Categories