So I'm just trying to explore the intricacies of C# and I wanted to make a simple program that would just kill a process. Yes I know, that is what Task Manager is for but this is supposed to be a learning experience, this is what I have so far.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace endProcess
{
class Program
{
private Process GetaProcess(string processname)
{
Process[] aProc = Process.GetProcessesByName(processname);
if (aProc.Length > 0)
return aProc[0];
else return null;
}
string selectProcess = "";
static void Main(string[] args)
{
Console.WriteLine("What process do you want to kill?");
selectProcess = Console.ReadLine();
Process myprc = Call GetAProcess(selectProcess);
myprc.Kill();
Console.ReadLine();
}
}
}
The issue comes where I made the comment. It says there should be a semicolon after GetAProcess and I have no idea why. Any help would be much appreciated.
You don't say Call GetaProcess you simply say GetaProcess
The line should look like this : Process myprc = GetaProcess(selectProcess);
Related
Hi Team I have the following code in C#, i am writting a backend-application using C# to read DeviceToCloudMEssage in Azure portal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Common;
using Microsoft.Azure.Devices.Shared;
using Microsoft.Azure.Devices;
namespace BackEndApplication
{
class Program
{
private static ServiceClient _serviceClient;
private readonly static string s_connectionString = "HostName=UniversityIOTHub.azure-devices.net;DeviceId=UniversityDeviceIOT;SharedAccessKey=******=";
private static async Task InvokeMethod()
{
var methodInvocation = new CloudToDeviceMethod("SetTelemetryInterval") { ResponseTimeout = TimeSpan.FromSeconds(30) };
methodInvocation.SetPayloadJson("10");
var response = await _serviceClient.InvokeDeviceMethodAsync("UniversityDeviceIOT", methodInvocation);
Console.WriteLine("Response status:{0}, payload", response.Status);
Console.WriteLine(response.GetPayloadAsJson());
}
static void Main(string[] args)
{
Console.WriteLine("IOT Hub Test-- BackEndApplication.\n");
_serviceClient = ServiceClient.CreateFromConnectionString(s_connectionString);
InvokeMethod().GetAwaiter().GetResult();
Console.WriteLine("Press Enter to exit.");
Console.ReadLine();
}
}
}
I am getting an authorizedException from the assemblies, one being Microsoft.Azure.Device.Common. The exception hits on InvokeMethod().GetAwaiter().GetResult(). Im also using DeviceExplore to test this exception, payload method i am also getting the same result. Please help me thanks.
What you are doing in your program is not reading DeviceToCloudMessages but invoking a direkt method.
For that you are using the wrong connectionString. The ServiceClient does not connect to your device but to IoT-Hub. So instead of using the IoT-Hub-Device connection string you have to use the IoT-Hub connection string which looks like this:
HostName=<yourIotHub>.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=<yourSharedAccessKey>=
Then you should be able to call _serviceClient.InvokeDeviceMethodAsync. This will make the IoT-Hub trigger the direct method on the device and pass on the response to the calling program.
I need to convert a C# windows service (.NET Framework 4.6.1) into a console application. So this application doesn't have a real interactive interface.
In the windows service application I have the OnStop() method to do the things I need before terminate... and exit.
Of course, I can create a file with a well-known name and in the console application periodically check for this file, but it seems to me an old style solution.
Is there a “best practice” to ask a console application to terminate gracefully having the time to complete the current processing?
So the solution I found has the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
private static bool keepRunning = true;
public static void Main(string[] args)
{
Console.WriteLine("Main started");
Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e) {
e.Cancel = true;
keepRunning = false;
};
while (keepRunning)
{
Console.WriteLine("Doing really evil things...");
System.Threading.Thread.Sleep(3000);
}
Console.WriteLine("Exited gracefully");
}
}
}
In this page, the following code is an example for changing the affinity of the current process:
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
Process myProcess = Process.GetCurrentProcess();
Console.WriteLine("ProcessorAffinity: {0}", myProcess.ProcessorAffinity);
Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr)3;
Console.WriteLine("ProcessorAffinity: {0} ", myProcess.ProcessorAffinity);
Console.ReadKey();
}
}
But the output for me is:
ProcessorAffinity: 255
ProcessorAffinity: 255
meaning that the affinity is not changed. What's the problem? And how can I change the affinity?
As #ChetanRanpariya mension in his comment, the issue is because you changeing ProcessorAffinity of one process object (returned from the second call of Process.GetCurrentProcess()) and checking it in another (returned from the first call of Process.GetCurrentProcess()). Here is corrected sample:
using (var currentProcess = Process.GetCurrentProcess())
{
Console.WriteLine($"ProcessorAffinity: {currentProcess.ProcessorAffinity}");
currentProcess.ProcessorAffinity = (System.IntPtr)3;
Console.WriteLine($"ProcessorAffinity: {currentProcess.ProcessorAffinity}");
}
I was working on a security monitor application and the best approach i found was Skype.
when a possible intrusion occurs the application calls a specified Skype ID which is probably my android phone i am done with all the image processing stuff. But i am stuck with this Skype API i wrote this piece of code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SKYPE4COMLib;
namespace SkypeCall
{
class Program
{
static void Main(string[] args)
{
Skype skype;
skype = new Skype("Skype4COM.Skype", "Skype_");
Call call = skype.PlaceCall(SkypeID);
call.StartVideoSend();
}
}
}
This initiates a voice call but in the call.StartVideoSend(); shows an error
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in SkypeCall.exe
Additional information: CALL: Action failed
i even tried this but i guess that's old API and couldn't get anything out of it.
And not even by sending commands .
if somebody would help me out i'll be grateful.
I think you need to wait until the call is connected.
easiest way would be to test the call.Status
class Program
{
static void Main(string[] args)
{
Skype skype;
skype = new SKYPE4COMLib.Skype();
string SkypeID = args[1];
Call call = skype.PlaceCall(SkypeID);
do
{
System.Threading.Thread.Sleep(1);
} while (call.Status != TCallStatus.clsInProgress);
call.StartVideoSend();
}
}
You could also add an event, however I think this will fire on every call so unless you are only using it for this project it might be too much.
class Program
{
static string SkypeID = "";
static void Main(string[] args)
{
Skype skype;
skype = new SKYPE4COMLib.Skype();
skype.CallStatus += new _ISkypeEvents_CallStatusEventHandler(skype_CallStatus);
Call call = skype.PlaceCall(SkypeID);
Console.ReadKey();
}
static void skype_CallStatus(Call pCall, TCallStatus Status)
{
if (Status == TCallStatus.clsInProgress && pCall.PartnerHandle == SkypeID) { pCall.StartVideoSend(); }
}
}
I have a console application that spawns other win32 processes using WMI ManagementClass.I have a requirement when a user kills the console application through proc explorer or by pressing ctrl+c ,the application should terminate all the child processes it created.What is the best way to achive this?
Keeping in mind that you have to take in your needs into account, you can do it like the sample below.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace KillSpawnedProcesses
{
class Program
{
static List<int> _processes = new List<int>();
static void Main(string[] args)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
StartProcesses();
Console.Read(); //to hold up console
Console.Read(); //to hold up console
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
KillProcesses();
}
static void StartProcesses()
{
for(int i = 0; i < 2; i++)
{
Process p = new Process();
p.StartInfo = new ProcessStartInfo();
p.StartInfo.FileName = "Notepad.exe";
p.Start();
_processes.Add(p.Id);
}
}
static void KillProcesses()
{
foreach(var p in _processes)
{
Process tempProcess = Process.GetProcessById(p);
tempProcess.Kill();
}
}
}
}
If the sub-process has a message queue (Win32 message pumping), you can post WM_CLOSE to its main window, or define your own message. Otherwise, you can design your inter-process notification by using Sockets, Pipes, or Synchronization objects like Events.
The worst way is to kill the sub-processes.