Event Log - EntryWrittenEventArgs returning Event ID's - c#

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);
}
}

Related

Log Appium testresults to console

Appium won't log the test results (of the UI-tests, executed with adb emulator) to the debug output (Deug.WriteLine).
According to the documentation, get test logs is possible with the following line
ILogs logs = driver.Manage().Logs;
Hower, Appium has different log types:
Browser
Client
Driver
Profiler
Server
I tried every single log type with the following code. But by executing I don't get any result and the test will (where I put the code) fail. Does anyone have a solution for this problem?
ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Browser);
// ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Client);
// ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Driver);
// ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Profiler);
// ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Server);
foreach (var log in logs)
{
Debug.WriteLine("Time: " + log.Timestamp);
Debug.WriteLine("Message: " + log.Message);
Debug.WriteLine("Level: " + log.Level);
}
I just figure out.
Check this article first
relaxed Security AppiumService
Get the log type
IReadOnlyCollection<string> logTypes = driver.Manage().Logs.AvailableLogTypes;
foreach (string logType in logTypes)
{
Console.WriteLine(logType);
//logcat
//bugreport
//server
}
Print logs
public static void PrintLogs(string logType)
{
try
{
ILogs _logs = driver.Manage().Logs;
var browserLogs = _logs.GetLog(logType);
if (browserLogs.Count > 0)
{
foreach (var log in browserLogs)
{
//log the message in a file
Console.WriteLine(log);
}
}
}
catch(Exception e)
{
//There are no log types present
Console.WriteLine(e.ToString());
}
Picture : C# Console Print appium log
In java I am doing it using the following code:
List<LogEntry> logEntries = driver.manage().logs().get("logcat").getAll();
for (LogEntry logEntry : logEntries) {
System.out.println(logEntry);
}
Not sure if this method works for C#. Please give it a try
List<LogEntry> logEntries = _driver.Manage().Logs().Get("logcat").GetAll();

How to store persistent User Connection Strings with .NET WPF Click-Once

We're developing a Click-Once WPF Windows Application that retrieves all its data from a database. I implemented a Form where a User could enter the corresponding data and using a SqlConnectionStringBuilder we build the Connection String and that works just fine.
We then add the Connection String to the ConfigurationManager using
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
If we use some other ConfigurationUserLevel, the application crashes (I don't know why yet, but I believe the Entity Framework Model tries to load the connection string and doesn't find it, because the file is not stored in the correct User Level?). Now, we store the connection string in a separate file and load it in App.config so we don't have to check it into Version Control:
<connectionStrings configSource="connections.config"/>
We don't deploy this file because it contains our own development connection strings. Rather, we create an empty file for deployment where the user-entered connection string will be stored. This works completely fine.
Our problem is that with a click-once update, the file will be "lost". What is the best way to store persistent per-user connection strings encrypted in a configuration file? Or should we completely switch to Registry? Or create our own encrypted File somewhere outside the %APPDATA%/Local/Apps/2.0/...../ folders and load it manually when initializing the Entity Framework Context?
You can go to MSDN site it might help you
https://msdn.microsoft.com/en-us/library/dd997001.aspx
with the help of below code, you need to modify this code for your requirement, hope this will help.
To create a custom ClickOnce application installer
In your ClickOnce application, add references to System.Deployment and System.Windows.Forms.
Add a new class to your application and specify any name. This walkthrough uses the name MyInstaller.
Add the following Imports or using statements to the top of your new class.
using System.Deployment.Application;
using System.Windows.Forms;
Add the following methods to your class.
These methods call InPlaceHostingManager methods to download the deployment manifest, assert appropriate permissions, ask the user for permission to install, and then download and install the application into the ClickOnce cache. A custom installer can specify that a ClickOnce application is pre-trusted, or can defer the trust decision to the AssertApplicationRequirements method call. This code pre-trusts the application
Note:- Permissions assigned by pre-trusting cannot exceed the permissions of the custom installer code.
InPlaceHostingManager iphm = null;
public void InstallApplication(string deployManifestUriStr)
{
try
{
Uri deploymentUri = new Uri(deployManifestUriStr);
iphm = new InPlaceHostingManager(deploymentUri, false);
}
catch (UriFormatException uriEx)
{
MessageBox.Show("Cannot install the application: " +
"The deployment manifest URL supplied is not a valid URL. " +
"Error: " + uriEx.Message);
return;
}
catch (PlatformNotSupportedException platformEx)
{
MessageBox.Show("Cannot install the application: " +
"This program requires Windows XP or higher. " +
"Error: " + platformEx.Message);
return;
}
catch (ArgumentException argumentEx)
{
MessageBox.Show("Cannot install the application: " +
"The deployment manifest URL supplied is not a valid URL. " +
"Error: " + argumentEx.Message);
return;
}
iphm.GetManifestCompleted += new EventHandler<GetManifestCompletedEventArgs>(iphm_GetManifestCompleted);
iphm.GetManifestAsync();
}
void iphm_GetManifestCompleted(object sender, GetManifestCompletedEventArgs e)
{
// Check for an error.
if (e.Error != null)
{
// Cancel download and install.
MessageBox.Show("Could not download manifest. Error: " + e.Error.Message);
return;
}
// bool isFullTrust = CheckForFullTrust(e.ApplicationManifest);
// Verify this application can be installed.
try
{
// the true parameter allows InPlaceHostingManager
// to grant the permissions requested in the applicaiton manifest.
iphm.AssertApplicationRequirements(true) ;
}
catch (Exception ex)
{
MessageBox.Show("An error occurred while verifying the application. " +
"Error: " + ex.Message);
return;
}
// Use the information from GetManifestCompleted() to confirm
// that the user wants to proceed.
string appInfo = "Application Name: " + e.ProductName;
appInfo += "\nVersion: " + e.Version;
appInfo += "\nSupport/Help Requests: " + (e.SupportUri != null ?
e.SupportUri.ToString() : "N/A");
appInfo += "\n\nConfirmed that this application can run with its requested permissions.";
// if (isFullTrust)
// appInfo += "\n\nThis application requires full trust in order to run.";
appInfo += "\n\nProceed with installation?";
DialogResult dr = MessageBox.Show(appInfo, "Confirm Application Install",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr != System.Windows.Forms.DialogResult.OK)
{
return;
}
// Download the deployment manifest.
iphm.DownloadProgressChanged += new EventHandler<DownloadProgressChangedEventArgs>(iphm_DownloadProgressChanged);
iphm.DownloadApplicationCompleted += new EventHandler<DownloadApplicationCompletedEventArgs>(iphm_DownloadApplicationCompleted);
try
{
// Usually this shouldn't throw an exception unless AssertApplicationRequirements() failed,
// or you did not call that method before calling this one.
iphm.DownloadApplicationAsync();
}
catch (Exception downloadEx)
{
MessageBox.Show("Cannot initiate download of application. Error: " +
downloadEx.Message);
return;
}
}
/*
private bool CheckForFullTrust(XmlReader appManifest)
{
if (appManifest == null)
{
throw (new ArgumentNullException("appManifest cannot be null."));
}
XAttribute xaUnrestricted =
XDocument.Load(appManifest)
.Element("{urn:schemas-microsoft-com:asm.v1}assembly")
.Element("{urn:schemas-microsoft-com:asm.v2}trustInfo")
.Element("{urn:schemas-microsoft-com:asm.v2}security")
.Element("{urn:schemas-microsoft-com:asm.v2}applicationRequestMinimum")
.Element("{urn:schemas-microsoft-com:asm.v2}PermissionSet")
.Attribute("Unrestricted"); // Attributes never have a namespace
if (xaUnrestricted != null)
if (xaUnrestricted.Value == "true")
return true;
return false;
}
*/
void iphm_DownloadApplicationCompleted(object sender, DownloadApplicationCompletedEventArgs e)
{
// Check for an error.
if (e.Error != null)
{
// Cancel download and install.
MessageBox.Show("Could not download and install application. Error: " + e.Error.Message);
return;
}
// Inform the user that their application is ready for use.
MessageBox.Show("Application installed! You may now run it from the Start menu.");
}
void iphm_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
// you can show percentage of task completed using e.ProgressPercentage
}
To attempt installation from your code, call the InstallApplication method. For example, if you named your class MyInstaller, you might call InstallApplication in the following way.
MyInstaller installer = new MyInstaller();
installer.InstallApplication(#"\\myServer\myShare\myApp.application");
MessageBox.Show("Installer object created.");

CefSharp crashing in SharePoint Timer Job

I am attempting to schedule a CefSharp rendering of pages stored in SharePoint via a SharePoint Timer Job. However, the OWSTIMER.exe service crashes almost immediately after calling Cef.Initialize(), throwing next to no errors.
The Subscription Class is:
internal class Subscriptions: IDisposable
{
internal Subscriptions()
{
db = // CreateConnection();
if (Cef.IsInitialized == false)
{
var settings = new CefSettings
{
CachePath = "cache",
BrowserSubprocessPath = "ProjectBin\\CefSharp.BrowserSubprocess.exe",
LogSeverity = LogSeverity.Default,
};
Cef.Initialize(settings);
}
}
internal void RunTodaysSubscriptions()
{
var subs = db.tt_ScheduledJobs.Where(sj => sj.Date <= DateTime.Today).Select(sj => sj.tt_Subscription).ToList();
foreach (var sub in subs)
{
ExecuteSubscription(sub);
SetNextSchedule(sub);
}
}
private void ExecuteSubscription(tt_Subscription subscription)
{
tt_JobHistory historyEntry = new tt_JobHistory();
historyEntry.SubscriptionKey = subscription.SubscriptionKey;
historyEntry.StartDate = DateTime.Now;
historyEntry.Status = "In Progress";
dfe.tt_JobHistory.Add(historyEntry);
dfe.SaveChanges();
string url = //path to file
using (SubscriptionExecution se = new SubscriptionExecution(
url,
subscription.SubscriptionKey,
subscription.Format))
{
//Completed represents either a response from the dashboard that the export either succeded
//or failed. If there is no response (i.e. a javascript error preventing the dashboard from executing
//an export, then we would hit the timeout of 5 minutes and shutdown this process.
if (SpinWait.SpinUntil(() => se.Completed == true, 120000) == true)
{
//Had a response from dashboard, could be a success or failure
if (se.ServerModel.Success == true) SuccessHistoryEntry(historyEntry);
else ErrorHistoryEntry(se.ServerModel.Message, historyEntry);
}
else
{
ErrorHistoryEntry("Process timed out generating subscription", historyEntry);
}
}
db.SaveChanges();
}
// ...
}
SubscriptionExecution is:
internal class SubscriptionExecution : IDisposable
{
// ...
internal SubscriptionExecution(string url, int subscriptionId, string fileType, string logLocation)
{
LogLocation = logLocation;
SubscriptionId = subscriptionId;
FileType = fileType;
Completed = false;
ServerModel = new ServerModel();
ServerModel.PropertyChanged += new PropertyChangedEventHandler(ServerModel_PropertyChanged);
browser = new ChromiumWebBrowser(url);
browser.RegisterJsObject("serverModel", ServerModel);
browser.LoadingStateChanged += LoadingStateChanged;
if (LogLocation != string.Empty) browser.ConsoleMessage += BrowserConsoleMessage;
}
private void ServerModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Success")
{
Completed = true;
}
}
// ...
}
There's a loadingStateChange function that injects some javascript that modifies the ServerModel.Success field when an event happens.
However, I can't seem to get this far. Except in one specific circumstance, the timerjob reaches the Cef.Initialize(settings) section, and then immediately restarts. Unfortunately, outside the event log, there is no error message to be found.
In the Windows Event Log, there is
which is indicating an error in libcef.dll
I've installed the libcef.dll.pdb symbols for this version of cefsharp (v57).
The CefSharp troubleshooting guide suggests that in instances like this, there should be logfiles or error dumps. There should be a file 'debug.log' in the folder with the executable, and perhaps a mini crashdump file in AppData\Local\CrashDumps.
However, as this is a SharePoint Timer job, these files don't seem to be appearing. I did find a debug.log file inside the 15 hive bin (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\BIN); however this file is empty.
I can't find the CrashDumps folder anywhere; checked under all user accounts on the machine, especially the running account and the SharePoint Timer Job managed account.
The one specific circumstance that I can get the code to run without restarting the timer job is immediately after the server is restarted. Restarting the server has (temporarily) fixed a few other problems around this issue, and so I suspect it might be related. Namely, I have had trouble retracting and redeploying the farm solution. This throws a couple of different errors:
on retracting: <SERVER>: The process cannot access the file 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\BIN...\icudtl.dat' because it is being used by another process.
Error: The removal of this file failed: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\BIN...\icudtl.dat.
on deploying: The requested operation cannot be performed on a file with a user-mapped section open.
I've attempted to find what other process is using icudtl.dat using Process Explorer, but all I could find was chrome, which was accessing a different copy. Killing all chrome processes and trying again also did not solve the problem.

Windows Application Log Events being 'missed' somehow with my EventLog

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
}

Reading EventLog C# Errors

I have this code in my ASP.NET application written in C# that is trying to read the eventlog, but it returns an error.
EventLog aLog = new EventLog();
aLog.Log = "Application";
aLog.MachineName = "."; // Local machine
foreach (EventLogEntry entry in aLog.Entries)
{
if (entry.Source.Equals("tvNZB"))
Label_log.Text += "<p>" + entry.Message;
}
One of the entries it returns is "The description for Event ID '0' in Source 'tvNZB' 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:'Service started successfully.'"
I only want the 'Service started successfully'. Any ideas?
Try this :)
EventLog aLog = new EventLog();
aLog.Log = "Application";
aLog.MachineName = "."; // Local machine
string message = "\'Service started\'";
foreach (EventLogEntry entry in aLog.Entries)
{
if (entry.Source.Equals("tvNZB")
&& entry.EntryType == EventLogEntryType.Information)
{
if (entry.Message.EndsWith(message))
{
Console.Out.WriteLine("> " + entry.Message);
//do stuff
}
}
}
It works on Win XP home. The message might be different on another OS.
Best way: dump entry.Message by System.Diagnostics.Trace.Write and see the exact message.
Hope it works smoothly :)

Categories