get network computer System.Environment.TickCount - c#

I've been searching to find out how to get a remote PC's System.Environment.TickCount.
Using this simple code gets the info I want from my local PC but I can't work out how to get the same info for each PC in our domain network. I want to run this from our server.
TimeSpan t = TimeSpan.FromMilliseconds(System.Environment.TickCount);
MessageBox.Show(t.Days.ToString() + "days, " + t.Hours.ToString() + "hrs & " + t.Minutes.ToString() + "mins.");
I've got this code to get all computer names in the network:
public List<String> ListNetworkComputers()
{
List<String> _ComputerNames = new List<String>();
String _ComputerSchema = "Computer";
System.DirectoryServices.DirectoryEntry _WinNTDirectoryEntries = new System.DirectoryServices.DirectoryEntry("WinNT:");
foreach (System.DirectoryServices.DirectoryEntry _AvailDomains in _WinNTDirectoryEntries.Children)
{
foreach (System.DirectoryServices.DirectoryEntry _PCNameEntry in _AvailDomains.Children)
{
if (_PCNameEntry.SchemaClassName.ToLower().Contains(_ComputerSchema.ToLower()))
{
_ComputerNames.Add(_PCNameEntry.Name);
}
}
}
return _ComputerNames;
}
How can I use this info to get the System.Environment.TickCount from each PC?
I've tried PsExec.exe but I've really got no clue how to get it to work for me. I tried this but it doesn't work:
var list = ListNetworkComputers();
foreach (var pc in list)
{
string output = "";
using (var process = new System.Diagnostics.Process())
{
process.StartInfo.FileName = #"C:\PsExec.exe";
process.StartInfo.Arguments = #"\\" + pc + " cmd /c echo " + "System.Environment.TickCount";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
output = process.StandardOutput.ReadToEnd();
}
int count = 0;
Int32.TryParse(output, out count);
TimeSpan ts = TimeSpan.FromMilliseconds(count);
MessageBox.Show(pc + ": " + ts.Days.ToString() + "days, " + ts.Hours.ToString() + "hrs & " + ts.Minutes.ToString() + "mins.");
}

Instead of using "cmd.exe", maybe you can use PowerShell? If so, it's a simple command to print that property: [System.Environment]::TickCount

I needed to do the same thing: get a remote PC's System.Environment.TickCount.
I came up with this solution (using Windows Management Instrumentation or WMI LocalDateTime - LastBootUpTime), but it's not 100% accurate compared to Environment.TickCount (see code comment below).
So I checked for other solutions online. Turns out #HansPassant suggested the same thing. For my use case, the +/-100 ticks discrepancy shouldn't matter.
using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Options;
using System;
using System.Linq;
using System.Security;
namespace TickCountTest
{
class Program
{
/// <summary>
/// Print the system TickCount (converted from Win32_OperatingSystem LocalDateTime - LastBootUpTime properties).
/// Why? Because this technique can be used to get TickCount from a Remote machine.
/// </summary>
public static void Main(string[] args)
{
var tickCount = GetRemoteMachineTickCount("REMOTEMACHINENAME");
if (!tickCount.HasValue)
{
throw new NullReferenceException("GetRemoteMachineTickCount() response was null.");
}
Console.WriteLine($"TickCount: {tickCount}");
Console.ReadKey();
}
/// <summary>
/// Retrieves the duration (TickCount) since the system was last started from a remote machine.
/// </summary>
/// <param name="computerName">Name of computer on network to retrieve tickcount for</param>
/// <returns>WMI Win32_OperatingSystem LocalDateTime - LastBootUpTime (ticks)</returns>
private static int? GetRemoteMachineTickCount(string computerName)
{
string namespaceName = #"root\cimv2";
string queryDialect = "WQL";
DComSessionOptions SessionOptions = new DComSessionOptions();
SessionOptions.Impersonation = ImpersonationType.Impersonate;
var baseLineTickCount = Environment.TickCount; // Note: to determine discrepancy
CimSession session = CimSession.Create(computerName, SessionOptions);
string query = "SELECT * FROM Win32_OperatingSystem";
var cimInstances = session.QueryInstances(namespaceName, queryDialect, query);
if (cimInstances.Any())
{
var cimInstance = cimInstances.First();
var lastBootUpTime = Convert.ToDateTime(cimInstance.CimInstanceProperties["LastBootUpTime"].Value);
var localDateTime = Convert.ToDateTime(cimInstance.CimInstanceProperties["LocalDateTime"].Value);
var timeSpan = localDateTime - lastBootUpTime;
var tickCount = Convert.ToInt32(timeSpan.TotalMilliseconds);
var discrepancy = tickCount - baseLineTickCount; // Note: discrepancy about +/- 100 ticks
return tickCount;
}
return null;
}
}
}

Related

Process.Start can't access roblox protocol

I'm trying to launch roblox from c#, but it seems it cannot find the roblox-protocol.
I tried the code I use in windows run and it did find, but once I try it with Process.Start it says the file could not be found.
public static string LaunchRoblox(string authTicket)
{
Random rnd = new Random();
long browserTrackerId = 55393295400 + rnd.Next(1, 100);
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
int launchTime = (int)t.TotalSeconds * 1000;
string url = $#"roblox-player:1+launchmode:play+gameinfo:{authTicket}+launchtime:{launchTime}+placelauncherurl:https://assetgame.roblox.com/game/PlaceLauncher.ashx?request=RequestGame&browserTrackerId=" + browserTrackerId + "&placeId=185655149&isPlayTogetherGame=false+browsertrackerid:" + browserTrackerId + "+robloxLocale:en_us+gameLocale:en_us";
return url;
}
static void Main(string[] args)
{
Program.x_crsf_token = GetXCSRFToken();
Console.Write("Sucessfully obtained X-CRSF-Token: " + Program.x_crsf_token);
Console.WriteLine("");
string AuthTicket = GetAuthTicket();
Console.Write("Sucessfully obtained AuthTicket: " + AuthTicket);
Console.WriteLine("");
string joiner = LaunchRoblox(AuthTicket);
Console.Write("Trying to launch roblox with:" + joiner);
Console.WriteLine("");
var game = Process.Start(joiner);
game.WaitForExit();
}
This is the error I get
What you do works in .NET Framework. But your error message shows that you are using .NET 6.0. For any .NET Core and later you would need to do something like:
var psi = new ProcessStartInfo(joiner)
{
UseShellExecute = true
};
var game = Process.Start(psi);

how to set a timeout when executing Powershell & Powercli commands inside asp.net mvc

I am working on an asp.net mvc web application, and i have the following code which define a loop over a list of servers and execute PowerCli commands inside my asp.net mvc for each server:-
//Start Loop
var shell = PowerShell.Create();
var shell2 = PowerShell.Create();
var shell3 = PowerShell.Create();
string PsCmd = "add-pssnapin VMware.VimAutomation.Core; $vCenterServer = '" + vCenterName + "';$vCenterAdmin = '" + vCenterUsername + "' ;$vCenterPassword = '" + vCenterPassword + "';" + System.Environment.NewLine;
PsCmd = PsCmd + "$VIServer = Connect-VIServer -Server $vCenterServer -User $vCenterAdmin -Password $vCenterPassword;" + System.Environment.NewLine;
PsCmd = PsCmd + "Get-VMHost " + System.Environment.NewLine;
string PsCmd2 = "add-pssnapin VMware.VimAutomation.Core; $vCenterServer = '" + vCenterName + "';$vCenterAdmin = '" + vCenterUsername + "' ;$vCenterPassword = '" + vCenterPassword + "';" + System.Environment.NewLine;
PsCmd2 = PsCmd2 + "$VIServer = Connect-VIServer -Server $vCenterServer -User $vCenterAdmin -Password $vCenterPassword;" + System.Environment.NewLine;
PsCmd2 = PsCmd2 + " Get-VMHost " + vCenterName + "| Get-VMHostNetworkAdapter -VMKernel" + System.Environment.NewLine;
shell.Commands.AddScript(PsCmd);
shell2.Commands.AddScript(PsCmd2);
dynamic results = shell.Invoke();
dynamic results2 = shell2.Invoke();
// end of loop
but i have noted that sometimes the shell commands will hang and the execution never ends,, so can i define a timeout behavior ,, so that after 5 minutes to skip the commands if no results were returned ...
You will have to roll your own timeout command. Below is code I wrote based on a MSDN Blog entry by Keith Babinec - Executing PowerShell scripts from C#. I wrote the sample in Console Application for demonstration purposes only. I find it easier to see what is happen. You can convert it to Asp.Net application by removing the Console Output and other adjustments.
Here is Program.cs
using System;
using System.Management.Automation;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string script = "Write-Host \"Testing lopping...\"" + Environment.NewLine
+ "for ($i=1; $i -le 5; $i++)" + Environment.NewLine
+ "{" + Environment.NewLine
+ "Write-Output $i" + Environment.NewLine
+ "Start-Sleep -s 3" + Environment.NewLine
+ "}" + Environment.NewLine
+ "Write-Host \"Done!\"" + Environment.NewLine;
PowerShell shell = PowerShell.Create();
shell.AddScript(script);
PowerShellHelper helper = new PowerShellHelper(shell);
try
{
// the script above should take 15 seconds to execute
// do timeout of 10 minutes
helper.ExecuteAsynchronously(new TimeSpan(0, 10, 0));
// do a really short timeout - 2 seconds
helper.ExecuteAsynchronously(new TimeSpan(0, 0, 2));
}
catch(TimeoutException te)
{
Console.WriteLine("\n\nScript took long!");
}
Console.WriteLine("Demo Finish");
Console.ReadLine();
}
}
}
And here is PowerShellHelper.cs
using System;
using System.Management.Automation;
using System.Threading;
// This code was build from MSDN Blogs entry by Keith Babinec
// http://blogs.msdn.com/b/kebab/archive/2014/04/28/executing-powershell-scripts-from-c.aspx
namespace ConsoleApplication1
{
class PowerShellHelper
{
private PowerShell shell_;
public PowerShellHelper(PowerShell shell)
{
shell_ = shell;
}
public void ExecuteAsynchronously(TimeSpan timeout)
{
// prepare a new collection to store output stream objects
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
outputCollection.DataAdded += outputCollection_DataAdded;
// begin invoke execution on the pipeline
// use this overload to specify an output stream buffer
IAsyncResult result = shell_.BeginInvoke<PSObject, PSObject>(null, outputCollection);
// start the timer
DateTime startTime = DateTime.Now;
// do something else until execution has completed.
// this could be sleep/wait, or perhaps some other work
while (result.IsCompleted == false)
{
Console.WriteLine("Waiting for pipeline to finish...");
Thread.Sleep(100);
// we check on our timeout here
TimeSpan elasped = DateTime.Now.Subtract(startTime);
if (elasped > timeout)
{
// we can do a few things here, I like to throw exception
throw new TimeoutException("Powershell script taking too long");
}
}
Console.WriteLine("Execution has stopped. The pipeline state: " + shell_.InvocationStateInfo.State);
foreach (PSObject outputItem in outputCollection)
{
//TODO: handle/process the output items if required
if (outputItem != null)
{
Console.WriteLine(outputItem.BaseObject.ToString());
}
}
}
/// <summary>
/// Event handler for when data is added to the output stream.
/// </summary>
/// <param name="sender">Contains the complete PSDataCollection of all output items.</param>
/// <param name="e">Contains the index ID of the added collection item and the ID of the PowerShell instance this event belongs to.</param>
private void outputCollection_DataAdded(object sender, DataAddedEventArgs e)
{
// do something when an object is written to the output stream
Console.WriteLine("Object added to output.");
}
}
}
I prefer this short construction:
using (PowerShell ps = PowerShell.Create())
{
ps.AddScript(script);
var psAsyncResult = ps.BeginInvoke();
if (psAsyncResult.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
// Execution finished
var results = ps.EndInvoke(psAsyncResult);
}
else
{
// Execution terminated by timeout
Console.WriteLine($"Unable to complete running powershell script within {timeoutMilliseconds} milliseconds");
}
}
Powershell invocation with timeout
There is a much shorter (thus less error-prone) solution:
using (PowerShell ps = PowerShell.Create())
{
ps.AddScript(script);
Task invocationTask = ps.InvokeAsync();
try
{
// Ensure the task is waited for the timeout duration.
// As documentation says if the timeout is reached then the task is faulted
if (!invocationTask.Wait(timeout))
{
isTimeouted = true;
}
}
finally
{
// task may not be completed here
// and disposal of not completed task will raise an exception
if (invocationTask != null && invocationTask.IsCompleted)
{
invocationTask.Dispose();
}
}
}

confusion excel install location in registry

I am required to detect excel install location in registry and open an excel file .I have found an example code .
I have two problems Firstly there is no InstallRoot directorty in the given registry path in that code
RegistryKey rootdir = excelKey.OpenSubKey(currentVersion +
#".0\Excel\InstallRoot");
But It does exist under this path (SOFTWARE\Wow6432Node\MicroSoft\Office)
The Other problem I was getting the the message that says "can't Open in excel
because excel is not installed."So I thought that CurrentVersion returns worng value
in my case (since office 2007) It returns 120.0 instead 12.0
public void OpenInExcel(string filename)
{
string dir = "";
RegistryKey key = Registry.LocalMachine;
RegistryKey excelKey = key.OpenSubKey(#"SOFTWARE\MicroSoft\Office");
if (excelKey != null)
{
foreach (string valuename in excelKey.GetSubKeyNames())
{
int version = 9;
double currentVersion=0;
if (Double.TryParse(valuename, out currentVersion) && currentVersion >= version)
{
RegistryKey rootdir = excelKey.OpenSubKey(currentVersion + #".0\Excel\InstallRoot");
if (rootdir != null)
{
dir = rootdir.GetValue(rootdir.GetValueNames()[0]).ToString();
break;
}
}
}
}
if (dir != "")
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = dir + #"Excel.exe";
startInfo.Arguments = "\"" + fileName + "\"";
startInfo.UseShellExecute = false;
using (Process process = new Process())
{
process.StartInfo = startInfo;
try
{
process.Start();
}
catch (Exception ex)
{
Console.WriteLine("\n\nCould not start Excel process.");
Console.WriteLine(ex);
}
}
}
else
{
MessageBox.Show("Can't Open in excel because excel is not installed.");
}
}
#Edit:I think something goes wrong at this line that returns wrong value because It Works this way
RegistryKey rootdir = excelKey.OpenSubKey(
#"12.0\Excel\InstallRoot");
I dont know why TryParse returns 120.0
This isn't intended to be an answer to your question, but it might help you get the correct version number, and I can't post all this code in a comment.
public const string CProgIdOutlook = "Outlook.Application";
/// <summary>
/// Method to get the Outlook version number, which will presumably be 11 (2003), 12 (2007),
/// 14 (2010) or 15 (2013). (I wonder what happened to version 13?) An exception is thrown if
/// this method is unable to provide an answer.
///
/// The technique used to get the version number of the "current" installed version of Outlook
/// is one of many possible methods that are described in various Internet sources, and is
/// hopefully the most likely to provide the correct answer with the least side-effects.
/// Problems with some of the alternative registry-based methods typically show up when
/// multiple versions of Outlook are installed or have been installed. The registry values can
/// also depend on x86 vs. x64 systems and whether Outlook was installed for one user or for
/// all users. Techniques involving querying the Outlook automation object have the
/// disadvantage of an instance of the Outlook program getting created - this can be seen in
/// Task Manager.
///
/// The idea for this code came from here: http://support.microsoft.com/kb/240794
/// </summary>
/// <returns>11 (2003), 12 (2007), 14 (2010) or 15 (2013)</returns>
private static int GetOutlookVersion()
{
const string CRegistryKey = #"SOFTWARE\Classes\" + GroupwareProgIds.CProgIdOutlook;
int outlookVersion;
using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(CRegistryKey))
{
outlookVersion = GetOutlookVersion(registryKey);
if (outlookVersion != -1)
return outlookVersion;
}
using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(CRegistryKey))
{
outlookVersion = GetOutlookVersion(registryKey);
if (outlookVersion != -1)
return outlookVersion;
}
throw new MerliniaException(0x2d4a67fu, "No registry entry for " + CRegistryKey);
}
/// <summary>
/// Sub-method of above method to do the work for either HKLM or HKCU.
/// </summary>
/// <returns>11 (2003), 12 (2007), 14 (2010) or 15 (2013), or -1 for error</returns>
private static int GetOutlookVersion(RegistryKey registryKey1)
{
const string CCurVer = "CurVer";
if (registryKey1 == null)
return -1;
using (RegistryKey registryKey2 = registryKey1.OpenSubKey(CCurVer))
{
if (registryKey2 == null)
throw new MerliniaException(0x2d43e5au,
"No registry entry for " + registryKey1 + "\\" + CCurVer);
string currentOutlookAppName = registryKey2.GetValue(null) as string;
if (currentOutlookAppName != null)
{
string[] sa = currentOutlookAppName.Split('.');
if (sa.Length == 3)
{
int outlookVersion;
if (int.TryParse(sa[2], NumberStyles.Integer,
CultureInfo.InvariantCulture, out outlookVersion))
return outlookVersion;
}
}
throw new MerliniaException(0x2d4b29du,
"Invalid registry content for " + registryKey1 + "\\" + CCurVer);
}
}
The problem is about double type and Culture.
I try explain:
You get double 12.0 value.
And ToString convert to 12.0 in Culture en-US and convert to 120.0 in Culture es-ES (decimal separators not the same).
The problem was parsing the version as a double.
Since the computer culture considers , as decimal separator and . as thousands separator
You can changes the code like this (when you tried Double.TryParse):
if (Double.TryParse(valuename, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out currentVersion) && currentVersion >= version)

mono-service keeps reserving memory untill raspberry pi is out of mem

So I have a background service written in C# which connects to a RFID-reader and reads out all the tags he sees. After that the service will place all tags in a database running on the Raspberry Pi as well. The problem is when I start the service that it keeps consuming more and more memory from the Pi. I've already ran it with mono-service --profile=default:alloc but this returns errors. Does anybody see anything in my code which could cause this memory usage?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using Impinj.OctaneSdk;
using MySql.Data.MySqlClient;
using Raspberry.IO.GeneralPurpose;
using System.IO.Ports;
using System.Xml;
using System.Threading;
namespace RFIDdaemon
{
public partial class RFIDdaemon : ServiceBase
{
// Create an instance of the ImpinjReader class.
static ImpinjReader reader = new ImpinjReader();
static int opIdUser, opIdTid;
static MySQL _oMySql = new MySQL(Properties.Resources.DatabaseHostname, Properties.Resources.Database, Properties.Resources.Uid, Properties.Resources.Pwd);
// Create a Dictionary to store the tags we've read.
static OutputPinConfiguration led1 = ConnectorPin.P1Pin18.Output();
static GpioConnection connection = new GpioConnection(led1);
static XmlDocument Power = new XmlDocument();
private Thread _oThread;
private ManualResetEvent _oManualResetEvent = new ManualResetEvent(false);
static string userData, tidData, epcData;
public RFIDdaemon()
{
this.ServiceName = "RFIDdaemon";
this.AutoLog = false;
InitializeComponent();
}
protected override void OnStart(string[] args)
{
if (_oThread == null)
{
_oThread = new Thread(Reader);
}
if (!_oThread.IsAlive)
{
_oManualResetEvent.Reset(); //Reset reset event te continue thread
_oThread = new Thread(Reader); //New thread
_oThread.Name = "RFIDreader";
_oThread.IsBackground = true;
_oThread.Start();
}
}
protected override void OnStop()
{
// Stop reading.
reader.Stop();
GC.Collect();
// Disconnect from the reader.
reader.Disconnect();
connection.Close();
}
static void Reader()
{
try
{
// Connect to the reader.
// Change the ReaderHostname constant in SolutionConstants.cs
// to the IP address or hostname of your reader.
reader.Connect(Properties.Resources.ReaderIP);
// Assign the TagOpComplete event handler.
// This specifies which method to call
// when tag operations are complete.
reader.TagOpComplete += OnTagOpComplete;
// Get the default settings
// We'll use these as a starting point
// and then modify the settings we're
// interested in.
Settings settings = reader.QueryDefaultSettings();
double[] Results = ReadXml();
if(Results != null)
{
settings.Antennas.GetAntenna(1).TxPowerInDbm = Results[0];
settings.Antennas.GetAntenna(1).RxSensitivityInDbm = Results[1];
}
// Create a tag read operation for User memory.
TagReadOp readUser = new TagReadOp();
// Read from user memory
readUser.MemoryBank = MemoryBank.User;
// Read two (16-bit) words
readUser.WordCount = 2;
// Starting at word 0
readUser.WordPointer = 0;
// Create a tag read operation for TID memory.
TagReadOp readTid = new TagReadOp();
// Read from TID memory
readTid.MemoryBank = MemoryBank.Tid;
// Read two (16-bit) words
readTid.WordCount = 8;
// Starting at word 0
readTid.WordPointer = 0;
// Add these operations to the reader as Optimized Read ops.
// Optimized Read ops apply to all tags, unlike
// Tag Operation Sequences, which can be applied to specific tags.
// Speedway Revolution supports up to two Optimized Read operations.
settings.Report.OptimizedReadOps.Add(readUser);
settings.Report.OptimizedReadOps.Add(readTid);
// Store the operation IDs for later.
opIdUser = readUser.Id;
opIdTid = readTid.Id;
// Apply the newly modified settings.
reader.ApplySettings(settings);
// Start reading.
reader.Start();
}
catch (OctaneSdkException e)
{
// Handle Octane SDK errors.
Console.WriteLine("Octane SDK exception: {0}", e.Message);
//Console.ReadLine();
}
catch (Exception e)
{
// Handle other .NET errors.
Console.WriteLine("Exception : {0}", e.Message);
}
}
// This event handler will be called when tag
// operations have been executed by the reader.
static void OnTagOpComplete(ImpinjReader reader, TagOpReport report)
{
try
{
userData = tidData = epcData = "";
// Loop through all the completed tag operations
foreach (TagOpResult result in report)
{
// Was this completed operation a tag read operation?
if (result is TagReadOpResult)
{
// Cast it to the correct type.
TagReadOpResult readResult = result as TagReadOpResult;
// Save the EPC
epcData = readResult.Tag.Epc.ToHexString();
// Are these the results for User memory or TID?
if (readResult.OpId == opIdUser)
userData = readResult.Data.ToHexString();
if (readResult.OpId == opIdTid)
tidData = readResult.Data.ToHexString();
if (epcData != "")
{
InsertTag(epcData, tidData, userData, DateTime.Now);
}
readResult = null;
}
}
userData = tidData = epcData = null;
}
catch
{
}
}
static void InsertTag(string EPC, string TID, string User, DateTime TagreadTime)
{
try
{
DataTable Time = _oMySql.Select("SELECT Tijd FROM biketable WHERE EPC = '" + EPC + "';").Tables[0];
DateTime OldTime = Convert.ToDateTime(Time.Rows[0][0]);
TimeSpan diff = TagreadTime.Subtract(OldTime);
string formatForMySql = TagreadTime.ToString("yyyy-MM-dd HH:mm:ss");
if (diff.TotalSeconds > 20)
{
connection.Blink(led1, 100);
if (_oMySql.Select("SELECT Binnen From biketable WHERE EPC = '" + EPC + "';").Tables[0].Rows[0][0].ToString() == "True")
_oMySql.Update("UPDATE biketable SET Tijd = '" + formatForMySql + "', TID = '" + TID + "', UserMem ='" + User + "', Binnen = 'False' WHERE EPC = '" + EPC + "';");
else
_oMySql.Update("UPDATE biketable SET Tijd = '" + formatForMySql + "', TID = '" + TID + "', UserMem ='" + User + "', Binnen = 'True' WHERE EPC = '" + EPC + "';");
}
Time = null;
formatForMySql = null;
}
catch
{
}
}
static double[] ReadXml()
{
double[] Results = new double[2];
try
{
string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Power.Load(dir + #"\\Power.XML");
XmlNodeList TXpower = Power.GetElementsByTagName("TXpower");
XmlNodeList RXpower = Power.GetElementsByTagName("RXpower");
Results[0] = System.Convert.ToDouble(TXpower[0].InnerXml);
Results[1] = System.Convert.ToDouble(RXpower[0].InnerXml);
return Results;
}
catch (Exception e)
{
return null;
}
}
}
}
when I run tail -n 1000 /var/log/syslog I get the following messages: note the last messages where it kills the service
http://cl.ly/image/343p2i2y251L
How can I easily detect the memory leak?
Thanks in advance

Get Operational log EventLog fails

I get InvalidOperationException when I run this code:
static void Main(string[] args)
{
var aLog = new EventLog("Microsoft-Windows-Diagnostics-Performance/Operational");
EventLogEntry entry;
var entries = aLog.Entries;
var stack = new Stack<EventLogEntry>();
for (var i = 0; i < entries.Count; i++)
{
entry = entries[i];
stack.Push(entry);
}
entry = stack.Pop();// only display the last record
Console.WriteLine("[Index]\t" + entry.Index +
"\n[EventID]\t" + entry.InstanceId +
"\n[TimeWritten]\t" + entry.TimeWritten +
"\n[MachineName]\t" + entry.MachineName +
"\n[Source]\t" + entry.Source +
"\n[UserName]\t" + entry.UserName +
"\n[Message]\t" + entry.Message +
"\n---------------------------------------------------\n");
}
Exception says that:
Microsoft-Windows-Diagnostics-Performance/Operational doesn't exist on this computer
Why?
Updated
Since you are using EventLog class, the valid "categories" (for sure this is not the correct word to name it...) for your constructor must be Application, System or any other Log Name available under Windows Log tree, not under Applications And Services Log tree.
const string LogName = "Microsoft-Windows-Diagnostics-Performance/Operational";
var query = new EventLogQuery(LogName, PathType.LogName, "*[System/Level=2]");
using (var reader = new EventLogReader(query))
{
var currentEvent = reader.ReadEvent();
while (currentEvent != null)
{
// Do your stuff here...
// Read next event.
currentEvent = reader.ReadEvent();
}
}
This snippet code works for me.
Remember to run this under elevated privileges. If not, you'll receive an Unauthorized exception throw.
First Answer
Because you are initializing your EventLog class with a category that doesn't exists.
Typical valid categories would be Application, System, etc.
The single parameter constructor for EventLog refers to a log of the registry. [^]

Categories