I was wondering if there is a way to reach the logs under the section named Application and Service Logs in the Event viewer utility in Windows. The thing is, I can read the entries under Windows Logs with the code below. I read the whole entry, and get the items with the necessary id, getting top 20 results. But I couldn't find anything on accessing the Application and Service logs section. Should I change the LogType in the EventLog constructor? Or is there a different method or class to access Application and Service logs? Trying "Application" as the logType variable doesnt work.
string str = "";
EventLog ev = new EventLog(logType, System.Environment.MachineName);
int LastLogToShow = ev.Entries.Count;
if (LastLogToShow <= 0)
Console.WriteLine("No Event Logs in the Log :" + logType);
int i;
int k = 0;
for (i = ev.Entries.Count - 1; i >= 0; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
if (CurrentEntry.EventID == id)
{
if (id == 1)
{
str += "Son Açılma \n";
str += "Olay Zamanı: " + CurrentEntry.TimeGenerated.ToLongDateString() + " " + CurrentEntry.TimeGenerated.ToShortTimeString() + "\n";
}
else if (id == 42)
{
str += "Son Kapatılma \n";
str += "Olay Zamanı: " + CurrentEntry.TimeGenerated.ToLongDateString() + " " + CurrentEntry.TimeGenerated.ToShortTimeString() + "\n";
}
else
{
str += "Event type: " + CurrentEntry.EntryType.ToString() + "\n";
str += "Event Message: " + CurrentEntry.Message + CurrentEntry + "\n";
str += "Event : " + CurrentEntry.UserName + "\n" + "\n";
str += "Olay Zamanı: " + CurrentEntry.TimeGenerated.ToLongDateString() + " " + CurrentEntry.TimeGenerated.ToShortTimeString() + "\n";
}
k++;
}
if (k > 20)
break;
}
ev.Close();
return str;
What I am looking for is under
Application and Service Logs/
Microsoft/
Windows/
TerminalServices-RemoteConnectionManager/
Operational/
Event ID 1149
I'm not sure you can access them using the EventLog class, or at least I couldn't figure out how. I did it using the EventLogQuery class instead.
I've provided an example below which I adapted from this post (C#: How to Query for an event log details with a given event id?), and should work for what you need:
using System.Diagnostics.Eventing.Reader;
string logType = "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational";
string query = "*[System/EventID=1149]";
var elQuery = new EventLogQuery(logType, PathType.LogName, query);
var elReader = new EventLogReader(elQuery);
for (EventRecord eventInstance = elReader.ReadEvent(); eventInstance != null; eventInstance = elReader.ReadEvent())
{
// .. do stuff here
}
Related
I need to copy multiple lines from text file(cisco config file): based on the below condition
if the line starts with interface copy from interface until '! '
my file is like :
!
access-list 1>
!
interface 1
ip address xx.xx.xx.xx
!
interface 2
ip address xx.xx.xx.xx
!
route 1
!
I try the below code :
var lines = File.ReadAllLines("C:\\My File2.txt");
foreach (var line1 in lines){
string firstWord = line1.Split(' ').First();
if ((firstWord == "access-list") && (!line1.Contains("remark ")))
{
TextBox1.Text = TextBox1.Text + "\r\n" + line1;
}
else if (firstWord == "nat")
{
TextBox2.Text = TextBox2.Text + "\r\n" + line1;
}
else if (firstWord == "interface")
{
var result = lines.Substring(line1.LastIndexOf('!') + 1);
TextBox3.Text = TextBox3.Text + "\r\n" + result;
}
but I get only one line as output
In case you want to keep your algorithm, this will work for you.
var lines = File.ReadAllLines("C:\\My File2.txt");
int i;
for (i = 0; i<lines.Length;i++)
{
var line1 = lines[i];
if (line1 == "!" || line1 == " ") continue;
if (line1.StartsWith("access-list")) && (!line1.Contains("remark ")))
{
TextBox1.Text = TextBox1.Text + "\r\n" + line1;
}
else if (line1.StartsWith("nat"))
{
TextBox2.Text = TextBox2.Text + "\r\n" + line1;
}
if (line1.StartsWith("interface"))
{
var str = line1;
while (!Equals(lines[i + 1], "!"))
{
str += lines[i + 1];
i++;
}
TextBox3.Text = TextBox3.Text + "\r\n" + str;
}
}
As per the file structure shown by you interface and ip address are on different lines. So you won't get it in same iteration of for loop. When you find that firstWord == "interface" you will need to set a flag that will tell you that next line is ip address and in next iteration check if that flag is true parse the current line as ip address and process it the way you want.
You should use "File.ReadAllText" instead of "File.ReadAllLines". "File.ReadAllText" returns a string with the complete text file text. After that, you can use the "String.Split" method to generate a string array.
var lines = File.ReadAllText("C:\\My File2.txt");
var seperatedStrings = lines.Split('!');
Each index of "seperatedStrings" contains what you want.
UPDATE: Here is a code snippet, that can help:
var lines = File.ReadAllText("C:\\My File2.txt");
var seperatedStrings = lines.Split('!');
foreach (var oneString in seperatedStrings)
{
if (oneString.Contains("access-list"))
{
Console.WriteLine("Access-List: " + oneString);
}else if (oneString.Contains("nat"))
{
Console.WriteLine("Nat: " + oneString);
}else if (oneString.Contains("interface"))
{
Console.WriteLine("Interface: " + oneString);
}
}
This is the output of my code snippet:
I'm getting the following exception:
"Input string was not in the correct format."
I'm taking a Json response which is comma delimited and storing it in a database. I'm not sure what is wrong.
Here is the code:
foreach (string s in skaters)
{
skaterData = s.Split(stringSeparator2, StringSplitOptions.None);
Console.WriteLine(skaterData[0] + " " + skaterData[1] + " " + skaterData[2] + " " + skaterData[3] + " " + skaterData[4] + " " + skaterData[5] +
" " + skaterData[6] + " " + skaterData[7] + " " + skaterData[8] + " " + skaterData[9] + " " + skaterData[10] + " " + skaterData[11] + " " + skaterData[12]
+ " " + skaterData[13] + " " + skaterData[14] + " " + skaterData[15]);
try
{
using (var _temp_Player = new FetcherEntities())
{
//int validPlayer;
//int validTeam;
//Skater_Season existingPlayer = _temp_Player.Skater_Season.FirstOrDefault(x => x.player_id == Convert.ToInt32(skaterData[1]) && x.team_id = Convert.ToInt32(skaterData[2]));
// if (existingPlayer != null)
// {
// Console.WriteLine("Existing player: " + existingPlayer.NAME);
// }
// else
// {
_temp_Player.Skater_Season.Add(new Skater_Season
{
player_id = Int32.Parse(skaterData[0]), //stuck here
team_id = Int32.Parse(team),
season_id = season,
Number = Int32.Parse(skaterData[1]),
POS = skaterData[2],
NAME = skaterData[3],
GP = Int32.Parse(skaterData[4]),
G = Int32.Parse(skaterData[5]),
A = Int32.Parse(skaterData[6]),
P = Int32.Parse(skaterData[7]),
plusminus = Int32.Parse(skaterData[8]),
PIM = Int32.Parse(skaterData[9]),
S = Int32.Parse(skaterData[10]),
TOIG = skaterData[11],
PP = Int32.Parse(skaterData[12]),
SH = Int32.Parse(skaterData[13]),
GWG = Int32.Parse(skaterData[14]),
OT = Int32.Parse(skaterData[15])
});
try
{
_temp_Player.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e);
}
}
}
catch (DbEntityValidationException forwardDB)
{
foreach (DbEntityValidationResult entityError in forwardDB.EntityValidationErrors)
{
foreach (DbValidationError error in entityError.ValidationErrors)
{
Console.WriteLine("Error Name: {0} : Message: {1}", error.PropertyName, error.ErrorMessage);
return false;
}
}
}
}
Also I've attached some screen shots of what the data looks like.
Its hard to tell you exactly where the error is but that message is being thrown by one of the Int32.Parse methods receiving data that it cant parse.
The best solution is to use TryParse which allows you to gracefully continue if a problem occurs.
The following is used when
int topicOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING;
MQTopic mqTopic = qmgr.AccessTopic(mqCloneSpecs.topicString, "",
MQC.MQTOPIC_OPEN_AS_PUBLICATION, topicOptions);
The above part of the program builds a list of QueueManagers and a list of Topics which are used to call a listener class in a Windows service.
int tLoopCounter = 0;
foreach (MQTopic topic in topicOut)
{
tLoopCounter++;
// NOTE: We blow up here with 2019 MQRC_HOBJ_ERROR if we access the property topic.Name
//Console.WriteLine("Loop through topics topic.IsOpen: " + topic.IsOpen);
//Console.WriteLine(" OpenOptions:" + topic.OpenOptions);
debugLocation = "4053";
Console.WriteLine(" OpenStatus=" + topic.OpenStatus);
debugLocation = "4054";
i = tLoopCounter - 1;
Console.WriteLine("i=" + i);
debugQueueInfo = " topicPut #" + tLoopCounter + " QueueMgr:" + queueManagerForTopicsOut[i].Name.TrimEnd();
// currently getting 2019 : MQRC_HOBJ_ERROR on the line below
debugLocation = "4055";
debugQueueInfo += "Topic:" + topic.Name;
Console.WriteLine("Pump:Topic.Put:" + debugLocation + ":" + debugQueueInfo);
debugLocation = "4057";
topic.Put(mqMessage);
Console.WriteLine("Pump:Topic.Put completed");
}
When I try to add the Inquire option, as shown here:
int topicOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING + MQC.MQOO_INQUIRE;
then I die with this error:
DebugLocation=Q3012 Exception: System.ApplicationException:
MQException in Acce ssQueue ---> IBM.WMQ.MQException:
MQRC_OPTIONS_ERROR
Also, the OpenStatus=True from the Console.WriteLIne at debugLocation=4053. My first thought that if it were closed, that would cause this error.
I am fairly new to C# and I have written several functioning programs, but all of them have been single thread applications. This is my first multi-threaded application and I am struggling to resolve this "Cross-thread operation not valid: Control 'cbLogType' accessed from a thread other than the one it was created on" error. My application searches Windows Event viewer for a user defined Event ID in a user defined Event Log Source(cbLogType). I am using a backgroundworker process to do all the work and I am using the worker.reportprogress to update a label, however, I receive the above error when debugging. I have tried several Invoke methods, but none seem to resolve my error. I have also tried removing the combobox and setting the Log Source directly in the code, which works to an extent, but still fails. I have included my code and any help would be greatly appreciated. I suspect that I might not be using the Invoke method correctly. Thanks in advance!
CODE:
private void bgWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
{
if (File.Exists(#"C:\Events.log"))
MessageBox.Show("File 'Events.log' already exists. All new data will be appended to the log file!", "Warning!");
string message = string.Empty;
string eventID = (tbEventID.Text);
string text;
EventLog eLog = new EventLog();
Invoke((MethodInvoker)delegate() { text = cbLogType.Text; });
eLog.Source = (this.cbLogType.Text); // I am receiving the error here
eLog.MachineName = ".";
int EventID = 0;
string strValue = string.Empty;
strValue = tbEventID.Text.Trim();
//string message = string.Empty;
EventID = Convert.ToInt32(strValue); // Convert string to integer
foreach (EventLogEntry entry in eLog.Entries)
{
int entryCount = 1;
if (cbDateFilter.Checked == true)
{
if (entry.TimeWritten > dtPicker1.Value && entry.TimeWritten < dtPicker2.Value)
if (entry.InstanceId == EventID)
message = "Event entry matching " + (tbEventID.Text) + " was found in " + (cbLogType.Text);
using (StreamWriter writer = new StreamWriter(#"C:\Events.log", true))
writer.WriteLine("EventID: " + entry.InstanceId +
"\r\nDate Created: " + entry.TimeWritten +
"\r\nEntry Type: " + entry.EntryType +
"\r\nMachinename: " + entry.MachineName +
"\r\n" +
"\r\nMessage: " + entry.Message +
"\r\n");
if (entry.InstanceId != EventID)
message = "No event ids matching " + (tbEventID.Text) + " was found in " + (cbLogType.Text);
}
else
{
if (cbDateFilter.Checked == false)
{
if (entry.InstanceId == EventID)
using (StreamWriter writer = new StreamWriter(#"C:\Events.log", true))
writer.WriteLine("EventID: " + entry.InstanceId +
"\r\nDate Created: " + entry.TimeWritten +
"\r\nEntry Type: " + entry.EntryType +
"\r\nMachinename: " + entry.MachineName +
"\r\n" +
"\r\nMessage: " + entry.Message +
"\r\n");
else if (entry.InstanceId != EventID)
message = "No event ids matching " + (tbEventID.Text) + " was found in " + (cbLogType.Text);
}
bgWorker1.ReportProgress((entryCount) * 10, message);
entryCount++;
}
}
}
}
private void bgWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lblStat.Text = e.UserState.ToString();
}
You're accessing cbLogType in a non-UI thread.
Change to
eLog.Source = text;
I'm using Redemption dll (http://www.dimastr.com/redemption/) and I've created an exe that accesses my mail box.
I run the exe in Windows Scheduler under my username and it works fine, I get an email sent to me (see below code).
When I change the runas username in Scheduler to someone else and try to access their mail box Profile I get an error. System.IO.FileLoadException
static void Main(string[] args)
{
System.Diagnostics.Debugger.Break();
object oItems;
//string outLookUser = "My Profile Name";
string outLookUser = "Other User Profile Name";
string ToEmailAddress = "abc.email#xyz.com";
string FromEmailAddress = "abc.email#xyz.com";
string outLookServer = "exchangeServer.com";
string sMessageBody =
"\n outLookUser: " + outLookUser +
"\n outLookServer: " + outLookServer +
"\n\n";
RDOSession Session = null;
try
{
rdoDefaultFolders olFolderInbox = rdoDefaultFolders.olFolderInbox;
Session = new RDOSession();
RDOFolder objFolder;
Session.LogonExchangeMailbox(outLookUser, outLookServer);
int mailboxCount = Session.Stores.Count;
string defaultStore = Session.Stores.DefaultStore.Name;
sMessageBody +=
"\n mailboxCount: " + mailboxCount.ToString() +
"\n defaultStore: " + defaultStore +
"\n\n";
//RDOStore rmpMetering = Session.Stores.GetSharedMailbox("Name of another mailbox");
//objFolder = rmpMetering.GetDefaultFolder(olFolderInbox);
objFolder = Session.GetDefaultFolder(olFolderInbox);
oItems = objFolder.Items;
int totalcount = objFolder.Items.Count;
if (totalcount > 10) totalcount = 10;
for (int loopcounter = 1; loopcounter < totalcount; loopcounter++)
{
RDOMail oItem = objFolder.Items[loopcounter];
string attachmentName = string.Empty;
foreach (RDOAttachment attachment in oItem.Attachments)
{
attachmentName += attachment.FileName + " ";
if (attachmentName.Trim() == "Data.csv")
{
attachment.SaveAsFile(#"C:\datafiles\" + attachmentName.Trim());
foreach (RDOFolder archiveFolder in objFolder.Folders)
{
if (archiveFolder.Name == "DataFileArchive")
{
oItem.MarkRead(true);
oItem.Move(archiveFolder);
}
}
}
}
sMessageBody += oItem.Subject + " " + attachmentName + "\n";
if ((oItem.UnRead))
{
//Do whatever you need this for
//sMessageBody = oItem.Body;
//oItem.MarkRead(true);
}
}
System.Web.Mail.SmtpMail.Send(ToEmailAddress,FromEmailAddress
, "Data File Processing-" + DateTime.Now.ToString()
,"" + sMessageBody);
}
catch (Exception ex)
{
Session = null;
System.Web.Mail.SmtpMail.Send(ToEmailAddress, FromEmailAddress, "Error", sMessageBody + " " + ex.Message);
}
finally
{
if ((Session != null))
{
if (Session.LoggedOn)
{
Session.Logoff();
}
}
}
}
When I try to run the same exe on another machine with me logged in I get this error,
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or ass
embly 'Interop.Redemption, Version=4.7.0.0, Culture=neutral, PublicKeyToken=null
' or one of its dependencies. The system cannot find the file specified.
File name: 'Interop.Redemption, Version=4.7.0.0, Culture=neutral, PublicKeyToken
=null'
at RPMDataFileProcessing.Program.Main(String[] args)
Has anyone got any ideas on what I'm doing wrong, can Redemption be used in this way?
I got this working in the end by ensuring that the user you are logged in as, has 'full mailbox rights' to the mail box you are trying to see.