Update the interface in the secondary process - c#

I'm using selenium to perform the automation of a web task and I'm generating a simple log ... However, I would like to "unlock" the interface for the log to be inserted in real time and not at the end of the whole process.
Simple log:
void log(string texto)
{
listBox1.Invoke((MethodInvoker)delegate
{
listBox1.Items.Add(string.Format("{0} - {1}", DateTime.Now.ToString(), texto));
});
}
How im using:
//Selenium Code Here (eg.: driver = new ChromeDriver();)
log("ChromeDriver Started!");
But nothing happens, the interface keeps being updated at the end of every process.

Related

Why does .NetFramework console exe program shut down by itself after 1 day idle?

I have a Console application that is ran on the background. Its a simple server that built using NetMQ library and NLogger that works locally.
I ran the program using taskScheduler with the following command schtasks /create /sc ONSTART /tn "TheServer" /tr "C:\\Temp\TheServer.exe" /ru System
As you can se, now it will start every time the desktop is turned on and it will run as System (It means that we can see TheServer.exe is running as background through Task Manager)
Question:
My timeline was like the follows:
My PC was on on Friday morning (starting of Business day - 09:00 in the morning)
I didn't turn off my PC on Friday before I go back from work
Monday morning, I checked my PC and TheServer is already gone
Does anyone know why it happens and how to prevent it?
FYI, I write my code as follows
Program.cs
class Program
{
[STAThread]
static readonly NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
...
static void Main(string[] args)
{
try
{
var inst = Server.GetInstance();
inst.Bind();
inst.Run();
}
catch (Exception e)
{
log.Error(e.Message);
log.Error(e.StackTrace);
throw;
}
}
}
Server.cs
class Server
{
private NetMQ.Sockets.ResponseSocket rSocket = new NetMQ.Sockets.ResponseSocket();
static readonly NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
...
public void Bind()
{
try
{
//bind is only for the Responder or The Server
rSocket.Bind("tcp://127.0.0.1:32325");
}
catch (Exception e)
{
log.Error(e.Message);
log.Error(e.StackTrace);
throw;
}
}
public void Run()
{
while (true)
{
var message = server.ReceiveFrameString();
Console.WriteLine("Received {0}", message);
// processing the request
Thread.Sleep(100);
Console.WriteLine("Sending World");
server.SendFrame("World");
}
}
}
I wrap my code at Program.cs with try-catch. But nothing written in the log
Then
I tried to find some information at the Window's Event Viewer. But there are no related information why TheServer.exe stopped
Update:
Looks like I found what #PMF means.
Then one extra question. . .
Is there any way to do that through command prompt?
I tried to read https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/schtasks-create Looks like if I didn't set the /du when create the task, it will be forever (?). CMIIW
UPDATE
So yes, we decided to recreate this TheServer.exe as Windows Service. Thanks for your input and opinions.

How to re-start a console application if it crashes?

I have created a console application in C#. How can I program this application so that it will re-start itself after a crash?
If I understand your question correctly, you want to attempt to re-start a console app in the event of a crash. In C# console-apps the method defined as the entry point (usually static void main) is the root of the call stacks in the app. You essentially would need to call that method recursively. You will want to make sure that the app eventually fails if it is in some unintended or unrecoverable state.
For example in the main class:
static int retryCount;
const int numberOfRetries = 3;
static void Main(string[] args)
{
try
{
var theApp = new MyApplicationType(args);
theApp.StartMyAppLogic();
}
catch (ExpectedExceptionType expectThisTypeOfException)
{
thisMethodHandlesExceptions(expectThisTypeOfException);
}
catch (AnotherExpectedExceptionType alsoExpectThisTypeOfException)
{
thisMethodHandlesExceptions(alsoExpectThisTypeOfException);
}
catch (Exception unexpectedException)
{
if(retryCount < numberOfRetries)
{
retryCount++;
Main(args);
}
else
{
throw;
}
}
}
You can use a watchdog to process your monitor and restart it if crashed:
see: What's the best way to watchdog a desktop application?
You can use a windows service instead and set it's recovery options as indicated here: https://serverfault.com/questions/48600/how-can-i-automatically-restart-a-windows-service-if-it-crashes
You can use a scheduled task in task manager to start your application periodically , and set it to only start if previous run has ended:
https://support.microsoft.com/en-us/kb/323527
You could try something like this:
static void Main(string[] args)
{
try
{
// Application code goes here
}
catch (Exception)
{
var applicationPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
Process.Start(applicationPath);
Environment.Exit(Environment.ExitCode);
}
}
Basically, wrap all the code in a try/catch, and if any exceptions occur, the program will retrieve the .exe location with System.Reflection.Assembly.GetExecutingAssembly().Location; and then call Process.Start to run the application again.
You should control your console app from another application (watchdog, sheduler, procmon, servman, ...).
E.g. you can create your console app as a service and control it from service manager.

MapReduce.SDK: How to wait for MapReduce job?

I'm using the Microsoft MapReduce SDK to start a Mapper only job.
The call to hadoop.MapReduceJob.ExecuteJob is throwing a "Response status code does not indicate success: 404 (not found)" exception immediately.
When inspecting the HDInsight Query Console the job successfully starts and finishes later. It also writes proper output files.
My guess is, ExecuteJob is trying to access output data before the job has finished.
What is the correct way to handle this situation?
using System;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Microsoft.WindowsAzure.Management.HDInsight;
using Microsoft.Hadoop.MapReduce;
using AzureAnalyzer.MultiAnalyzer;
namespace AzureAnalyzer
{
class Program
{
static void Main(string[] args)
{
IHadoop hadoop = Hadoop.Connect(Constants.azureClusterUri, Constants.clusterUser,
Constants.hadoopUser, Constants.clusterPassword, Constants.storageAccount,
Constants.storageAccountKey, Constants.container, true);
try {
var output = hadoop.MapReduceJob.ExecuteJob<MultiAnalyzerJob>();
}
catch (Exception ex)
{
Console.WriteLine("\nException: " + ex.Message);
}
}
}
}
I got another way to do the same thing but takes a bit of effort since it requires the mapper and reducer files to be transferred to the hadoop cluster storage.
you need to add Microsoft.Hadoop.Client then Microsoft Azure HDInsight NuGet package as well.
var jobcred = new BasicAuthCredential();
jobcred.UserName = "clusteruserid";
jobcred.Password = "clusterpassword";
jobcred.Server = new Uri("https://clusterurl");
StreamingMapReduceJobCreateParameters jobpara = new StreamingMapReduceJobCreateParameters()
{
JobName="mapreduce",
Mapper = "Mapper.exe",
Reducer = "Reducer.exe",
Input= "wasb:///mydata/input",
Output = "wasb:///mydata/Output",
StatusFolder= "wasb:///mydata/sOutput"
};
jobpara.Files.Add("wasb:///mydata/Mapper.exe");
jobpara.Files.Add("wasb:///mydata/Reducer.exe");
// Create a Hadoop client to connect to HDInsight.
var jobClient = JobSubmissionClientFactory.Connect(jobcred);
// Run the MapReduce job.
JobCreationResults mrJobResults = jobClient.CreateStreamingJob(jobpara);
// Wait for the job to complete.
Console.Write("Job running...");
JobDetails jobInProgress = jobClient.GetJob(mrJobResults.JobId);
while (jobInProgress.StatusCode != JobStatusCode.Completed
&& jobInProgress.StatusCode != JobStatusCode.Failed)
{
Console.Write(".");
jobInProgress = jobClient.GetJob(jobInProgress.JobId);
Thread.Sleep(TimeSpan.FromSeconds(10));
}
// Job is complete.
Console.WriteLine("!");
Console.WriteLine("Job complete!");
Console.WriteLine("Press a key to end.");
Console.Read();
Hope this helps. I was able to run jobs without throwing any exceptions.
this in fact waits for the job to be complete.
Please verify if all required services to run the program are up and running. The 404 error indicates that some URL the program tries to access internally is not accessible.

How to schedule a [WebMethod] in Web Services in .net?

I just got to learn a bit about web services in .net (.asmx and all stuff)
For my project i need to schedule a program which cralwels a set of websites and then update the newly available data to the database every 30 minute.
I have created a [WebMethod] for both the crawler code to run and for database updation if available.
But i want that this [WebMethod] get automate and runs for every 30 minutes?
it is not necessary create a WebMethod to do this, you can make in the server side, and for schedule operations, I always use Quartz.net
I may be incorrect but it looks like you want to schedule a background task using asp.net? I haven't used Quartz.Net but I have done this using a simple example provided by Jeff Attwood. The following code is from Global.asax.cs and on application startup schedules a recurring job every 60 minutes:
void Application_Start(object sender, EventArgs e)
{
var refreshMinutes = 60;
AddTask("UpdateInfo",
(int)TimeSpan.FromMinutes(refreshMinutes).TotalSeconds);
}
private void AddTask(string name, int seconds)
{
OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
HttpRuntime.Cache.Insert(name, seconds, null,
DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration,
CacheItemPriority.NotRemovable, OnCacheRemove);
}
public void CacheItemRemoved(string key, object v, CacheItemRemovedReason r)
{
if ("UpdateInfo".Equals(key))
{
try
{
new SearchService().UpdateInfo();
}
catch (Exception ex)
{
logger.Error("UpdateInfo threw an exception: {0} {1}", ex.Message, ex.StackTrace);
}
}
AddTask(key, Convert.ToInt32(v));
}
Note Phil Haack has a post on The Dangers of Implementing Recurring Background Tasks In ASP.NET which provides some useful techniques for making the process more robust.

C# Determine when an external app is run or exited [duplicate]

Is there a way to determine when the last time a specific machine last ran a process?
I can use the following to determine if a process is running, but the application cannot grab the process if it has since stopped.
Process[] process = Process.GetProcessesByName(processName, serverName);
WMI provides a way to track processes starting and terminating with the Win32_ProcessTrace classes. Best shown with an example. Start a new Console application, Project + Add Reference, select System.Management. Paste this code:
using System;
using System.Management;
class Process {
public static void Main() {
ManagementEventWatcher startWatch = new ManagementEventWatcher(
new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
startWatch.EventArrived += new EventArrivedEventHandler(startWatch_EventArrived);
startWatch.Start();
ManagementEventWatcher stopWatch = new ManagementEventWatcher(
new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
stopWatch.EventArrived += new EventArrivedEventHandler(stopWatch_EventArrived);
stopWatch.Start();
Console.WriteLine("Press any key to exit");
while (!Console.KeyAvailable) System.Threading.Thread.Sleep(50);
startWatch.Stop();
stopWatch.Stop();
}
static void stopWatch_EventArrived(object sender, EventArrivedEventArgs e) {
Console.WriteLine("Process stopped: {0}", e.NewEvent.Properties["ProcessName"].Value);
}
static void startWatch_EventArrived(object sender, EventArrivedEventArgs e) {
Console.WriteLine("Process started: {0}", e.NewEvent.Properties["ProcessName"].Value);
}
}
Edit the manifest so this program runs elevated. Then simply start some programs to see it at work. Beware that it is not especially quick.
You won't be able to do this using the Process class. However, it should be possible to figure out when an application was last run by configuring audit process tracking in Windows. The following links might get you started:
Audit process tracking
How can I track what programs come and go on my machine?
The process tracking will create entries in the Windows event log which you can then access using C#.

Categories