I have a winforms applications which is reading strings using sockets and the sockets are under backgroundWorker thread.
Things are working fine, but as per the new company standards my manager wants it to be run as service rather putting this winforms application in the startup folder always.
The problem is that we are using below line of code in this winforms application
Invoke(new MethodInvoker(
delegate { _logger.Error((String.Format("Error: {0}", _socketError))); }
));
Can somebody guide what ca I do to use the above line of code in the windowserverice project
please suggest
Thanks
Update: I need to use invoke because this statement is running in the DoWork event of backgroundWorker component.
Since _logger is just writing to a log file, I do not understand the original intention behind using Invoke in the first place. I think you will be safe replacing that line with:
_logger.Error(String.Format("Error: {0}", _socketError));
Related
I have a C++ application (calling functions of an SDK for a specific hardware component), and want to display its data in a C# GUI. The C# part is a DLL which the C++ calls. (This is by request from the customer so I don't have much choice about it.)
I'm not very well versed in C#, so might be missing something obvious, but I'm running into problems both displaying the GUI and updating it.
I access the C# code using this method, with code roughly like this (ptr is a class variable):
// Initialize COM.
CoInitialize(NULL);
ptr = new IPtr(__uuidof(ManagedClass));
(*ptr)->ShowForm();
then in another thread:
if (updating) (*ptr)->Update(data)
On the C# side we have:
FormClass myForm;
void ShowForm()
{
myForm = new FormClass();
Application.Run(myForm);
}
void Update(Data data)
{
myForm.Update(data)
}
When I use Application.Run or ShowDialog to show my GUI, the form shows nicely but the update makes the application crash. Using Show has the GUI get stuck. Using BeginInvoke resulted in the GUI never appearing.
Is there any recommended way for me to start the GUI given this setup? Would it help to somehow use Invoke/BackgroundWorker in Update rather than calling myForm's method directly?
You must update C# GUI on the the UI thread. See this answer for how to synchronize from another thread to the GUI thread.
C# Windows Forms Application - Updating GUI from another thread AND class?
You might also find the Debug Location toolbar handy to determine what thread you are currently in when debugging in Visual Studio
https://blogs.msdn.microsoft.com/davedev/2012/07/18/where-is-the-suspend-resume-and-terminate-toolbar-in-visual-studio-2012-ultimate/
I've a set of queries which I want to execute only once in day, I know this is possible using TaskScheduler in C#. But I am not getting any example suitable for my requirements. Can anybody give a example code for this?
You can try FluentScheduler. The documentation has the sample codes all you need. Firstly I thought it is for web only, but now I think you can use it for using with Desktop Application too. But not sure and not tested.
https://fluentscheduler.codeplex.com/documentation
EDIT You can also use Task Scheduler -
First create a console application that can run and do all your tasks. You can even invoke other processes with it. Then build the executable and save it in a safe location.
Then go to Administrative Tools > Task Sheduler And create a new task by clicking Action > New Task. You will see a screen like this -
Select your executable and other permissions there.
Now to run it in schedule move to next tab 'Triggers' and click add at the bottom. You will see a screen like this -
Now add your desired schedules. Make sure you use logs, because you will not be able to see the outputs directly. Either you can use windows event viewer or write to custom text file for your convenience.
Task Scheduler is a part of windows itself. It does not have a
dependency on C# or C++ anything. Basically you tell windows that it
will run the specific program at a regular schedule. It is the job of the
executed program to initialize all environment and execute appropriate
code. So even if you use task scheduler you have to make sure that the
program you are using to run with it, has all other options and codes
right.
The Timer is probably the best solution for you.
var timer = new Timer {AutoReset = true, Interval = 30000}; 1s = 1000ms
timer.Elapsed += timer_Elapsed;
timer.Start();
.......
public void timer_Elapsed(object source, System.Timers.ElapsedEventArgs e)
{
// do stuff here that will execute every 30 seconds
}
If you need a reliable scheduler, writing your own from scratch might take more effort than expected. What if the machine gets rebooted? What if it happens 10 seconds before execution time? Should the task be executed late or not at all? Where will the data be persisted? You have to think about all these things.
Alternatively, you could use Quartz.NET. It is a C# port of popular Java job scheduling framework. The codebase is well tested and robust. Have a look at it here:
http://www.quartz-scheduler.net/
I am still pretty much new to c# so you will have to bear with me.
I have developed a windows form program which updates some SQL records as an end of day process for one of our clients.
The next step is that I need to install the program on a server and simulate a button click in the program to become a scheduled task.
I know how to setup the task on the server side where you start program and enter the arguments. But I am unsure as to what code I need to include in my program to achieve this.
Consider using Windows Task Scheduler.
You could extract your business logic to a separate DLL and write a simple Console app that will just run your task after accepting the parameters through command line.
My recommendation would be to get away from running a GUI-based/windowed application from a scheduled task - this is generally madness in practice. Ideally, deploy a console-based version of your application that requires execution (perhaps with parameter arguments) and doesn't require any user (or quasi-user-) interaction.
If you simply can't create a 'system version' of your application, then I guess you have two choices, both immensely ugly: 1) create some kind of macro script which is executed instead of your program, this script could execute the program and issue 'the click', 2) perform 'the click' on startup of your application by invoking the button click handler (maybe based on a parameter to give it a duality in execution modes.)
I think you are also asking about command-line argument passing. See the answers to this question.
In particular, I highly recommend the accepted answer: NDesk.Options.
I have similar task to do making winforms as windows task. what i did is
in windows task scheduler in the task tab,under Run put your exe and then /Auto,it will run as schedule.
Example:winform.exe /Auto
If I'm understanding your question correctly, this is how you could possibly proceed:
Best way to parse command line arguments in C#? -> check the answers and choose a library to process the args or write your own code to do so.
Create a scheduled task if those arguments are present by Creating Scheduled Tasks
If it is a windows application, just go to the bin folder, get the executable file, and finally schedule a task for it by using windows schedule task and choose the exe file as you targeted application.
if it is web application, you may want to include your code in a quartz.net scheduled job, details are on quartz.net website.
Very popular solution is Quartz.NET http://quartznet.sourceforge.net/
Take a look in the Timer class
http://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx
Why not extract your database update logic as a windows service
you can segregate the sql handling part in a separate DLL and use the common DLL for both your form application and the windows service.
A window service run in background and can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface.
Moreover you need not to install any third party software for same and window service code base can be ported to any windows machine with required version of .Net Framework installed.
Add reference: Microsoft.Win32.TaskScheduler
then write this code:
using (TaskService ts = new TaskService())
Microsoft.Win32.TaskScheduler.Task task = ts.GetTask(TaskName);
task.Run(); //start
task.Stop(); //End
I'm coding a console application that is reading and writing some stuff at different intervals during the day. I want this later (if its "final") as a service. For now a simple console application is better (that's how I thought) because its easier to use and I can see the result without having to register/start/end the service. Is it easy to later, if I'm done with the testing, just create a new service project and copy the code from the console application?
I heard now that we should not use Timer in a service. But I'm using System.Threading.Timer in my console application a lot. Does it mean that I'll be in trouble? Is it this "testing on console app and then using it on service" thing not a good idea? Any suggestions?
You can create Windows service and Right click->Properties and change Output Type as Console Application do your developement.Once you have done with development change back Output Type as Windows Application.
Take a look at this link to know deep about the both timers.
The problem with System.Threading.Timer is that there's no easy way to start/stop the timer. And because of that, you can't realiably use it for tasks which could possibly take LONGER than the timer interval.
Switch to System.Timers.Timer instead:
http://netpl.blogspot.com/2010/05/systemwindowsformstimer-vs.html
A good solution for you - is to try Application As Service software
You can launch every application as a service.
Well
this is a really simple question, the search tearms are just not that great.
How do I check in some library if I am currently running as a console application, vs. a WPF window application?
Thanks for any tips,
Chris
You can check whether the current thread is a WPF UI thread by checking Dispatcher.Current.
There's more, what if your library method is called from a worker thread? You didn't tell why you need to know, preventing a good answer. One approach is that the app that uses your library never has any trouble knowing whether its console or WPF. Expose a property to allow it to tell you. Another is using events so the app can simply implement the event handler to its liking. Dependency Injection is another.
You can check if the executed statements are running in a WPF host with the following statement:
if (System.Windows.Application.Current != null)
{
//statements for WPF mode
}
else
{
//statements for non WPF mode...
}
For this you must reference PresentationFramework.dll
ILDasm will have an entry in the manifest as follows :
.subsystem 0x0003 // WINDOWS_CUI
.subsystem 0x0002 // WINDOWS_GUI
based on the subsystemtype you can tell if its GUI or CUI.
This information is also available from the following command :
dumpbin ConsoleApplication1.exe /headers
From your library query for entry assembly and get its full path(Assembly.GetEntryAssembly().CodeBase) and then you can issue any of these command to know the subsystem.