Code to remote connect to readt the eventviewer status & send email if any failure using C#

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi All,
I do have two requirements:
1.Need to remote connect a remote machine to read the eventviewers status log
2.Send email only if any failure through the status log.
This is my sample piece of code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32.TaskScheduler;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Eventing;
using System.Net;
using System.Net.Mail;
using System.Data.SqlClient;
using System.Data;
using System.Devices;
using System.Management;
using System.IO;
using System.Collections.Specialized;
using System.Collections;
using System.Net.NetworkInformation;
using System.Security;
namespace TaskSchedulerRemote
{
class Program
{
// Connect to the computer "REMOTE" using credentials
// TaskService ts = new TaskService("\REMOTE", "myusername", "MYDOMAIN", "mypassword");
void EnumAllTasks()
{
using (TaskService ts = new TaskService())
EnumFolderTasks(ts.RootFolder);
}
void EnumFolderTasks(TaskFolder fld)
{
foreach (Task task in fld.Tasks)
ActOnTask(task);
foreach (TaskFolder sfld in fld.SubFolders)
EnumFolderTasks(sfld);
}
void ActOnTask(Task t)
{
// Do something interesting here
}

static IEnumerable<string> GetServices(string host, string username, string password)
{
string ns = @"\\{0}\root\CIMV2";
string query = "SELECT * FROM win32_win32_NTLogEvent" + "Where Logfile = System";

ConnectionOptions options = new ConnectionOptions();
if (!string.IsNullOrEmpty(username))
{
options.Username = username;
options.Password = password;
}
options.EnablePrivileges = true;
ManagementScope scope = new ManagementScope(string.Format(@"\{0}{1}", host, ns), options);
scope.Connect();

ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, new ObjectQuery(query));
ManagementObjectCollection retObjectCollection = searcher.Get();
DataTable dt = new DataTable();
dt.Columns.Add("EntryType");
dt.Columns.Add("TimeGenerated");
dt.Columns.Add("Source");
dt.Columns.Add("Message");
dt.Columns.Add("Category");
foreach (ManagementObject mo in searcher.Get())
{

yield return mo.GetText(TextFormat.Mof);
}
}

static void Main(string[] args)
{
using (TaskService task = new TaskService())
{
List<string> lst = new List<string>();
lst = GetServices("IP ADDRESS", "Username", "Password").ToList();
//logType can be Application, Security, System or any other Custom Log.
string logType = "Application";
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);
// Read the last 2 records in the specified log.
int i;
for (i = ev.Entries.Count - 1; i >= LastLogToShow - 2; i--)
{
EventLogEntry CurrentEntry = ev.Entries;
Console.WriteLine("Event ID : " + CurrentEntry.EventID);
Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
Console.WriteLine("Message : " + CurrentEntry.Message + "n");
}
ev.Close();
//Process process_conectoin = new Process();
//string exe = Environment.ExpandEnvironmentVariables(@"%SystemRoot%system32mstsc.exe");
//if (exe != null)
//{
// process_conectoin.StartInfo.FileName = exe;
// process_conectoin.StartInfo.Arguments = "/v " + "172.21.55.24";//ip or name of computer to connect
// process_conectoin.StartInfo.Domain="UKROI";
// process_conectoin.StartInfo.UserName="xu77";
// char[] pwd={M,a,r,c,h,2,0,1,3};
// System.Security.SecureString ss = new System.Security.SecureString();
// ss.AppendChar(M);
// ss.AppendChar(a);
// ss.AppendChar(r);
// ss.AppendChar(c);
// ss.AppendChar(h);
// ss.AppendChar(2);
// ss.AppendChar(0);
// ss.AppendChar(1);
// ss.AppendChar(3);

// process_conectoin.StartInfo.Password = ss;
// process_conectoin.Start();
// //Process.Start(Server.MapPath("Filename.rdp"));
//}
TaskDefinition td = task.NewTask();
DailyTrigger wt = new DailyTrigger();
wt.StartBoundary = DateTime.Today.AddDays(1);
td.Triggers.Add(wt);
DataTable dataTable = new DataTable();
dataTable.Columns.Add("TaskName");
dataTable.Columns.Add("TaskSchedule");
dataTable.Columns.Add("TaskNextRun");
dataTable.Columns.Add("TaskLastRun");
dataTable.Columns.Add("State");
dataTable.AcceptChanges();
DataRow dataRow;
StringBuilder sbTaskSchedule = new StringBuilder();

//MailMessage Msg = new MailMessage();
//MailAddress fromMail = new MailAddress("emailid");
//// Sender e-mail address.
//Msg.From = fromMail;
//// Recipient e-mail address.
//Msg.To.Add(new MailAddress("emailid"));
//Msg.Priority = MailPriority.High;
//// Subject of e-mail
//Msg.Subject = "Scheduled Task Status Report:" + System.DateTime.Now;


//Msg.Body += "<html><body><Table><tr><td>Hi All,</td></tr><tr><td>Please find below the status report of schduled task :</td></tr></Table></body></html><html><body>";
//Msg.Body += "<html><body><Table><tr><td>Regards,</td></tr><tr><td></td></tr><tr><td></td></tr>" +
//"<tr><td><b>NOTE: This is an automated mail. Please, do not reply.</b> </td></tr></table></body></html>";
//Msg.IsBodyHtml = true;
//string sSmtpServer = "";
//sSmtpServer = "mailservername";
//SmtpClient a = new SmtpClient();
//a.Host = sSmtpServer;
//a.EnableSsl = false;
//try
//{
// Console.WriteLine("Sending mail...");
// a.Send(Msg);
// Console.WriteLine("Mail was sent successfully!");
//}
//catch (Exception ep)
//{
// Console.WriteLine("failed to send mail:");
// Console.WriteLine(ep.Message);
//}

}
}

}
}


Please advise.
Many Thanks,
Sisir



View the full article
 
Back
Top