I've written an application, a component of which watches for Events being raised in the Windows Application Log with a certain Source and EventID in order to parse data from them. However, it appears to miss some of these events for no readily apparent reason.
I have included debug messages to try to see where the issue is - this takes the form of comments sent to a text field.
When an Entry is written to the application log, a time-stamped message is added to the debug text field, and parseApplicationLogEntry() is called.
private void eventLogApplication_EntryWritten(object sender,
System.Diagnostics.EntryWrittenEventArgs e)
{
txtDebug.Text = txtDebug.Text + "\n " + DateTime.Now.ToLongTimeString() +
+ ": Application Log has been written.";
parseApplicationLogEntry();
}
The application log entry is parsed, and the Source and EventID are looked at to determine if they are what we are looking for. A time-stamped message is added to the debug text showing the Source and EventID found.
private void parseApplicationLogEntry()
{
System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application");
int entry = log.Entries.Count - 1;
string logMessage = log.Entries[entry].Message;
string logSource = log.Entries[entry].Source;
string logEventID = log.Entries[entry].InstanceId.ToString();
log.Close();
txtDebug.Text = txtDebug.Text + "\n " + DateTime.Now.ToLongTimeString() +
": Application Log Source is " + logSource;
txtDebug.Text = txtDebug.Text + "\n " + DateTime.Now.ToLongTimeString() +
": Application Log EventID is " + logEventID;
if (logSource == "ExpectedSource" & logEventID == "ExpectedEventID")
{
// Do stuff
}
}
The behaviour is as expected much of the time, however sometimes there is very odd behaviour.
For example, 13 logs were written to the application log. 3 with the looked-for source, and 10 with another source. The debug text shows 13 entries were seen, all with the unfamiliar source...
I'm not sure where to go from here.
There is no need to access the EventLog in this way to review the newest entries.
Instead of calling a method to iterate through the EventLog each time a new Entry is written, it is simpler (and safer) to access the Entry more directly using the event handler which triggers each time an Entry is written.
private void eventLog_Application_EntryWritten(object sender, EntryWrittenEventArgs e)
{
// Process e.Entry
}
Related
I am currently using Xamarin to create a multiplatform application for the phone. The app idea is basically a Pokemon encyclopedia that utilizes the PokeAPi (https://pokeapi.co/) and also uses the following wrapper library (https://gitlab.com/PoroCYon/PokeApi.NET). Currently, I want it to where if the user types in an incorrect Pokemon into the search bar, it will return an alert error to the user. However, every time I test it and enter in an invalid pokemon, the application stops and Visual Studio/Xamarin informs me of a HTTP404 error. How would I go about this?
I've tried using comparison statements in where if the API call doesn't find the pokemon name, it should pop up with an alert, but VS/Xamarin will stop running the application and display a Http404 exception. I really dont know where to go at this point.
'''
async Task PullData()
{
LoadingIcon.IsRunning = true;
string newPokemon = PokemonFind.Text;
Pokemon p = await DataFetcher.GetNamedApiObject<Pokemon>(newPokemon);
string PokemonName = p.Name;
int PokemonHeight = p.Height;
int PokemonWeight = p.Mass;
int PokemonXp = p.BaseExperience;
int PokemonOrder = p.Order;
OrderLabel.Text = "#" + PokemonOrder;
NameLabel.Text = "Name: " + PokemonName;
HeightWeightLabel.Text = "Height/Weight: " + PokemonHeight.ToString() +" dm " + "/" + PokemonWeight.ToString() + " hg";
ExpLabel.Text = "Experience on defeat: " + PokemonXp.ToString() + "XP";
LoadingIcon.IsRunning = false;
}
'''
I expected it to display an alert message instead of VS/Xamarin stopping the program and throwing me an HTTP404 exception.
Wrap your call inside a try/catch block
try
{
async Task PullData()
}
catch(HttpRequestException ex)
{
//Shows an alert error to the user
}
I am working on a simple C# Windows Service that listens to the EventLog via the "EntryWrittenEventHandler" handler and watch for logon logoff events and then write them to a DB.
The service was working as expected for a few days and then suddenly I am not seeing anything get written on logon and logoff events. I am seeing the EntryWrittenEventHandler handler be triggered on each new Security EventLog write...but within the EntryWrittenEventArgs class...I am seeing every entry be reported as "Event ID 0" and this message:
"
Message
"The description for Event ID '0' in Source '' cannot be found. The local computer may not have the necessary registry information or message DLL files to display the message, or you may not have permission to access them. The following information is part of the event:"
string
message
"The description for Event ID '0' in Source '' cannot be found. The local computer may not have the necessary registry information or message DLL files to display the message, or you may not have permission to access them. The following information is part of the event:"
string
+ owner
{System.Diagnostics.EventLogInternal}
System.Diagnostics.EventLogInternal
ReplacementStrings
{string[0]} string[]
Source
"" string
+ TimeGenerated
{12/31/1969 7:00:00 PM}
System.DateTime
+ TimeWritten
{12/31/1969 7:00:00 PM}
System.DateTime
UserName
null string"
Not sure whats going on. Opening the EventLog on the server in question...I can see all the entries as expected. The date is also from 1969...which is weird as well.
Here is my code of what is going on so far:
public Audit()
{
CanHandleSessionChangeEvent = true;
//Start the EventLog Watcher
startEventLogWatch();
}
private void startEventLogWatch()
{
EventLog eLog = new EventLog("Security");
eLog.EntryWritten += new EntryWrittenEventHandler(EventLog_OnEntryWritten);
eLog.EnableRaisingEvents = true;
}
private void EventLog_OnEntryWritten(object source, EntryWrittenEventArgs e)
{
try
{
if (e.Entry.InstanceId.ToString() == "4624")
{
EventAudit eventAuditEntry = new EventAudit();
eventAuditEntry = LogonEvent(e);
if (eventAuditEntry.ADUserName != null)
{
WriteDBEntry(eventAuditEntry);
}
}
else if (e.Entry.InstanceId.ToString() == "4647")
{
EventAudit eventAuditEntry = new EventAudit();
eventAuditEntry = LogoffEvent(e);
if (eventAuditEntry.ADUserName != null)
{
WriteDBEntry(eventAuditEntry);
}
}
}
catch (Exception ex)
{
eventLog1.WriteEntry("A general error has occured. The error message is as follows: " + ex.Message.ToString(), EventLogEntryType.Error, 2001);
}
}
I'm creating a webapp in c# using visual stdio 2008.
In the page there's a button that starts a quite long (about 1 min) processing.
During this i would like to show what the program is doing in a listbox in the same page but I don't know how to do it beacuse when the process start the page is continuously refreshing so the listbox is always empty even if in the code there are many ListBox.Items.Add("..").
Hope you can help me.
(p.s. sorry for my bad english,I'm italian)
May be your page load is taking time for other reasons, but not sure.
public static void WriteLog(string Error)
{
using (StreamWriter logfile = new StreamWriter(filePath + "Log.txt", true))
{
logfile.WriteLine(DateTime.Now.ToString() + ":" + DateTime.Now.Millisecond.ToString() + " -#: " + Error);
logfile.Close();
}
}
Use this function to log.
Call this function in Page load
WriteLog("Comments");
I'm working on an ASP.NET web application in Visual Studio 2013 and as part of the main error routine, I want it to store the errors in a Windows Event Log. However, every time I run the code, the log never gets created even when I run Visual Studio as Administrator. Would turning off UAC fix this? Code is below. Any help is appreciated. Thanks.
public static void ErrorRoutine(Exception e, string obj, string method)
{
EventLog.Delete("LogName"); // uncomment this line to delete log
EventLog log = new EventLog();
log.Source = "SourceName";
log.Log = "LogName";
if (e.InnerException != null)
{
log.WriteEntry("Error in Models, object = " + obj + ", method = " + method + ", inner exception = " +
e.InnerException.Message, EventLogEntryType.Error);
throw e.InnerException;
}
else
{
log.WriteEntry("Error in Models, object = " + obj + ", method = " + method + ", message = " + e.Message,
EventLogEntryType.Error);
throw e;
}
}
Edit: I get that this is probably not best practice but this project is actually an assignment for college and this is the exact code we were told to write, as well as being told to run VS as Administrator. I just need to find a way to make work really.
I'm wondering if it is possible to search and read from a file and display what's in the file in a message box.
I'm wanting to search for a file by its ID, which ID is known by the user. When the user enters the ID my program opens the file which shares the same ID; eg.ID.txt in the preset folder.
when it's selected it is then read and put in a MessageBox which will then display what is in the file.
Can anyone show me how to do this?
Thanks.
//Declare variables
int TID;
private void TIDFileCreate_Click(object sender, EventArgs e)
{
StreamWriter outputFile;
outputFile = File.CreateText (TID.ToString()+".txt");
outputFile.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
outputFile.WriteLine("Initial Amount" + " " +AmountLabel.Text);
outputFile.WriteLine("Date Invested" +" " +DateLabel.Text);
outputFile.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
outputFile.WriteLine("Rate Chosen" + " " + RateLabel.Text);
outputFile.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
outputFile.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
outputFile.Close();
MessageBox.Show("Transaction file for Transaction: " + TransactionIDLabel.Text + "Was Created", "Transaction File");
}
private void SearchButton_Click(object sender, EventArgs e)
{
SearchID = int.Parse(searchTextBox.Text);
string[] lines = File.ReadAllLines(#"C:\Users\Public\TestFolder\"+SearchID+".txt");
}
Can't you just use MessageBox.Show() in your SearchButton_Click method?
private void SearchButton_Click(object sender, EventArgs e)
{
SearchID = int.Parse(searchTextBox.Text);
string[] lines = File.ReadAllLines(#"C:\Users\Public\TestFolder\"+SearchID+".txt");
System.Windows.Forms.MessageBox.Show(string.Join("\r\n", lines));
}
I think that for what you want to do you should read this:
http://msdn.microsoft.com/en-us/library/ms233843.aspx
or some similar article about serialization.
This said, if the number of IDs grow in number, you should considering the adoption of a lightweight DB, i.e. SQLite, just to name one.
Take a look at the DirectoryInfo class. Something like the following should do what you want;
DirecectoryInfo dir = new DirectoryInfo(pathToRoot);
FileInfo[] files = dir.GetFiles("Id.txt"); //if using a specific name should return 1 item
TextBox.Text = File.ReadAllText(files.FirstOrDefault().FullName);
Keep in mind I have no error handling or anything here. You'll have to add that yourself, this just shows you the key classes/methods to get the files and read their contents. There are many other options like doing GetFiles(), keeping that collection in memory and then operating on them later on.