public void Save(System.Diagnostics.EventLog eventLog) { ConnectionManager connectionManager = new ConnectionManager(); NpgsqlConnection conn = connectionManager.getConnection(); string strInsert = "INSERT INTO sys_sms_settings( " + "friexecuted, frischedule, monexecuted, monschedule, sms_password, " + "satexecuted, satschedule, sunexecuted, sunschedule, thuexecuted, " + "thuschedule, todschedule, tueexecuted, tueschedule, sms_user, " + "wedexecuted, wedschedule) " + "VALUES ('" + friExecuted + "', '" + friSchedule + "', '" + monExecuted + "', '" + monSchedule + "', '" + sms_password + "', '" + satExecuted + "', '" + satSchedule + "', '" + sunExecuted + "', '" + sunSchedule + "', '" + thuExecuted + "', '" + thuSchedule + "', '" + todSchedule + "', '" + tueExecuted + "', '" + tueSchedule + "', '" + sms_user + "', '" + wedExecuted + "', '" + wedSchedule + "')"; NpgsqlCommand command = new NpgsqlCommand(strInsert, conn); int rowsaffected; try { new NpgsqlCommand("delete from sys_sms_settings", conn).ExecuteNonQuery(); rowsaffected = command.ExecuteNonQuery(); eventLog.WriteEntry("Actualizacion de configuracion efectuada.", System.Diagnostics.EventLogEntryType.Information); } finally { conn.Close(); } }
private void fSplashScreen_Load(object sender, EventArgs e) { System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog(); appLog.Source = "ISSU Sipariş Takip Programı"; appLog.WriteEntry("Program başlatıldı."); this.CenterToScreen(); }
private void checkSerial() { try { LicenceMgr.ModifyRegistry myRegistry = new LicenceMgr.ModifyRegistry(); myRegistry.SubKey = "SOFTWARE\\IssuSiparis"; string mySerial = myRegistry.Read("SERIAL"); //MessageBox.Show("Mevcut:" + mySerial + "\nYeni :" + LicenceMgr.FingerPrint.Value()); if (mySerial == null || mySerial != LicenceMgr.FingerPrint.Value()) { throw new Exception("Lisans hatası."); } fSiparis frmSiparis = new fSiparis(); frmSiparis.Show(); this.Visible = false; } catch (Exception ex) { timer1.Enabled = false; MessageBox.Show("Lisanssız Program kullanımı. \nLütfen 0533 245 22 46 numaralı telefondan bilgi alınız.", "Lisanssız Kullanım", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog(); appLog.Source = "ISSU Sipariş Takip Programı"; appLog.WriteEntry("Lisans Hatası. Programdan çıkıldı."); Application.Exit(); } finally { this.Cursor = Cursors.Default; } }
public static void WriteEventLogEntry(string message, string appName) { // Create an instance of EventLog System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog(); // Check if the event source exists. If not create it. if (!System.Diagnostics.EventLog.SourceExists(appName)) { System.Diagnostics.EventLog.CreateEventSource(appName, "Application"); } // Set the source name for writing log entries. eventLog.Source = appName; // Create an event ID to add to the event log int eventId = 8; // Write an entry to the event log. eventLog.WriteEntry(message, System.Diagnostics.EventLogEntryType.Error, eventId); // Close the Event Log eventLog.Close(); }
public Window1() { InitializeComponent(); try { el = new System.Diagnostics.EventLog("Application", Environment.MachineName, "Audio_Vista"); this.Closing += new System.ComponentModel.CancelEventHandler(Window1_Closing); npsVistaAudio = new VMuktiService.NetPeerServer("net.tcp://localhost:6060/NetP2PRTCVista"); npsVistaAudio.AddEndPoint("net.tcp://localhost:6060/NetP2PRTCVista"); npsVistaAudio.OpenServer(); npcRTCVistaClient = new VMuktiService.NetPeerClient(); objNetP2PRTCVista = new clsNetTcpRTCVistaService(); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcJoin += new clsNetTcpRTCVistaService.DelsvcJoin(Window1_entsvcJoin); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcCreateRTCClient += new clsNetTcpRTCVistaService.DelsvcCreateRTCClient(Window1_entsvcCreateRTCClient); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcRegisterSIPPhone += new clsNetTcpRTCVistaService.DelsvcRegisterSIPPhone(Window1_entsvcRegisterSIPPhone); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcAnswer += new clsNetTcpRTCVistaService.DelsvcAnswer(Window1_entsvcAnswer); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcDial += new clsNetTcpRTCVistaService.DelsvcDial(Window1_entsvcDial); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcHangup += new clsNetTcpRTCVistaService.DelsvcHangup(Window1_entsvcHangup); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcHold += new clsNetTcpRTCVistaService.DelsvcHold(Window1_entsvcHold); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcSendDTMF += new clsNetTcpRTCVistaService.DelsvcSendDTMF(Window1_entsvcSendDTMF); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcTransfer += new clsNetTcpRTCVistaService.DelsvcTransfer(Window1_entsvcTransfer); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcRTCEvent += new clsNetTcpRTCVistaService.DelsvcRTCEvent(Window1_entsvcRTCEvent); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcUnJoin += new clsNetTcpRTCVistaService.DelsvcUnJoin(Window1_entsvcUnJoin); ClientNetP2PRTCVistaChannel = (INetTcpRTCVistaServiceChannel)npcRTCVistaClient.OpenClient <INetTcpRTCVistaServiceChannel>("net.tcp://localhost:6060/NetP2PRTCVista", "NetP2PRTCVistaMesh", ref objNetP2PRTCVista); ClientNetP2PRTCVistaChannel.svcJoin(); } catch (Exception ex) { el.WriteEntry("Window1:" + ex.Message); el.Close(); } }
static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //exception handler Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); //if the exe was passed a filename argument then run the script if (args.Length > 0) { string filePath = args[0]; if (!System.IO.File.Exists(filePath)) { using (System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog("Application")) { eventLog.Source = "Application"; eventLog.WriteEntry("An attempt was made to run a sharpRPA script file from '" + filePath + "' but the file was not found. Please verify that the file exists at the path indicated.", System.Diagnostics.EventLogEntryType.Error, 101, 1); } //MessageBox.Show("Please pass a valid file as the parameter!", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); return; } Application.Run(new UI.Forms.frmScriptEngine(filePath, null)); } else { Application.Run(new UI.Forms.frmScriptBuilder()); } }
internal static Udbus.Core.Logging.ILog CreateWCFServiceLogger(System.Diagnostics.EventLog eventLog) { return(Udbus.Core.Logging.LogCreation.CreateFormatLogger(WCFServiceName , new Udbus.Core.Logging.LogCreation.LogCreationDatum(defaultWCFServiceLevel, defaultWCFServiceFormat, new System.Diagnostics.ConsoleTraceListener()) , new Udbus.Core.Logging.LogCreation.LogCreationDatum(defaultWCFServiceLevel, defaultWCFServiceFormat, new System.Diagnostics.EventLogTraceListener(eventLog)) )); }
private string GrabarLog(string mensaje, System.Diagnostics.EventLogEntryType type) { try { Int32 eventID; using (System.Diagnostics.EventLog obLogEntry = new System.Diagnostics.EventLog()) { obLogEntry.Source = Constantes.NOMBREEVENTLOG; if (mensaje.Length >= short.MaxValue) { mensaje = mensaje.Remove(short.MaxValue - 1); } Random obRnd = new Random(); eventID = obRnd.Next(65535); obLogEntry.WriteEntry(mensaje, type, eventID); } return(eventID.ToString()); } catch (Exception ex) { throw new Exception("Sucedio un error al momento de ingresar el event log", ex); } }
/// <summary> /// Write to the application log in windows event logs /// </summary> /// <param name="title"></param> /// <param name="description"></param> private static void WriteTo_WindowsApplicaitonEventLog(string title, string description) { try { DateTime now = DateTime.Now; System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog(); // Set the source name for writing log entries. eventLog.Source = "BlobIM"; // Create an event ID to add to the event log int eventID = 111; // Write an entry to the event log. eventLog.WriteEntry(title + " - " + now + " \r\n" + description, System.Diagnostics.EventLogEntryType.Error, eventID); // Close the Event Log eventLog.Close(); } catch (Exception e) { Alerting.ErrorLogging.WriteTo_Log("Failed To Write to EventLog", e.ToString()); } }
public void InsertarChofer(E_ChoferCompleto ChoferCompleto) { try { conexion.Open(); OracleCommand cmd = conexion.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "SP_INSERTARCHOFER"; OracleParameter par1 = new OracleParameter("v_cedula", ChoferCompleto.Cedula); cmd.Parameters.Add(par1); OracleParameter par2 = new OracleParameter("v_nombre", ChoferCompleto.Nombre); cmd.Parameters.Add(par2); OracleParameter par3 = new OracleParameter("v_apellido", ChoferCompleto.Apellido); cmd.Parameters.Add(par3); OracleParameter par4 = new OracleParameter("v_fecha_nacimiento", ChoferCompleto.Fecha_nacimiento); cmd.Parameters.Add(par4); cmd.ExecuteNonQuery(); } catch (OracleException e) { string errorMessage = "Code " + e.ErrorCode + ", Message " + e.Message; System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(); log.Source = "My application"; log.WriteEntry(errorMessage); } conexion.Close(); }
public bool LoadConfig(System.Diagnostics.EventLog eventLog1) { try { dataSource = System.Configuration.ConfigurationManager.AppSettings["dataSource"]; dataSource1 = System.Configuration.ConfigurationManager.AppSettings["dataSource1"]; dataSource2 = System.Configuration.ConfigurationManager.AppSettings["dataSource2"]; catalog = System.Configuration.ConfigurationManager.AppSettings["catalog"]; emailAddress = System.Configuration.ConfigurationManager.AppSettings["emailAddress"]; emailFrom = System.Configuration.ConfigurationManager.AppSettings["emailFrom"]; emailTo = System.Configuration.ConfigurationManager.AppSettings["emailTo"]; backlogcatalog = System.Configuration.ConfigurationManager.AppSettings["backlogcatalog"]; backlogsubscriber = System.Configuration.ConfigurationManager.AppSettings["backlogsubscriber"]; logfile = System.Configuration.ConfigurationManager.AppSettings["logfile"]; String tmp = System.Configuration.ConfigurationManager.AppSettings["backlogthreshold"]; backlogthreshold = Int32.Parse(tmp); trantarget = System.Configuration.ConfigurationManager.AppSettings["trantarget"]; tmp = System.Configuration.ConfigurationManager.AppSettings["tranthreshold"]; tranthreshold = float.Parse(tmp); tmp = System.Configuration.ConfigurationManager.AppSettings["querytimeout"]; querytimeout = Int32.Parse(tmp); tmp = System.Configuration.ConfigurationManager.AppSettings["hourtosend"]; hourtosend = Int32.Parse(tmp); } catch (Exception e) { eventLog1.WriteEntry(e.Message); return(false); } return(true); }
static void Main(string[] args) { System.Diagnostics.EventLog eventLog1; eventLog1 = new System.Diagnostics.EventLog(); if (!System.Diagnostics.EventLog.SourceExists("DomainConnectDDNSUpdate")) { System.Diagnostics.EventLog.CreateEventSource("DomainConnectDDNSUpdate", ""); } eventLog1.Source = "DomainConnectDDNSUpdate"; eventLog1.Log = ""; DomainConnectDDNSUpdate.DomainConnectDDNSWorker worker = new DomainConnectDDNSUpdate.DomainConnectDDNSWorker(eventLog1); worker.InitService(); if (worker.Initialized) { if (worker.Monitoring) { worker.CheckToken(true); } if (worker.Monitoring) { worker.CheckIP(true); } } }
public static bool _ctor_System_Diagnostics_EventLogTraceListener_System_Diagnostics_EventLog( ) { //Parameters System.Diagnostics.EventLog eventLog = null; //Exception Exception exception_Real = null; Exception exception_Intercepted = null; InterceptionMaintenance.disableInterception( ); try { returnValue_Real = System.Diagnostics.EventLogTraceListener.ctor(eventLog); } catch (Exception e) { exception_Real = e; } InterceptionMaintenance.enableInterception( ); try { returnValue_Intercepted = System.Diagnostics.EventLogTraceListener.ctor(eventLog); } catch (Exception e) { exception_Intercepted = e; } }
void items_ItemAdd(object Item) { Outlook.MailItem mail = (Outlook.MailItem)Item; try { MailServiceReference.MailServiceClient mailServiceObj = new MailServiceReference.MailServiceClient(); if (Item != null) { string filterSenderMailID = mailServiceObj.GetTargetMailId(); const string PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"; Outlook.Recipients recips = mail.Recipients; foreach (Outlook.Recipient recip in recips) { Outlook.PropertyAccessor pa = recip.PropertyAccessor; string smtpAddress = pa.GetProperty(PR_SMTP_ADDRESS).ToString(); if (smtpAddress.ToLower() == filterSenderMailID.ToLower()) { mailServiceObj.InsertMailBody(mail.SenderEmailAddress, mail.ReceivedByName, mail.Subject, mail.Body); break; } } } } catch (Exception ex) { System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog(); appLog.Source = "Claysys UCU Outlook plugging"; appLog.WriteEntry("Exception : " + ex); throw ex; } }
//TOMBOL PRINT AKAN MEMANGGIL KE METHOD INI, berguna untuk memanggil method print public void coba_print() { LinkApi link = new LinkApi(); try { PrintDialog printDialog = new PrintDialog(); PrintDocument printDocument = new PrintDocument(); printDialog.Document = printDocument; //add the document to the dialog box... printDocument.PrinterSettings.PrinterName = link.printer_name; //try_bi.Properties.Settings.Default.mPrinter;//seting nama printer printDocument.PrintPage += new PrintPageEventHandler(CreateReceipt); //add an event handler that will do the printing printDocument.Print(); } catch (Exception ex) { //MessageBox.Show("Your Printer Name Is Unavailable", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error); //MessageBox.Show("Can't connect to the printer: " + try_bi.Properties.Settings.Default.mPrinter); MessageBox.Show("Can't connect to the printer #{" + link.printer_name /*try_bi.Properties.Settings.Default.mPrinter*/ + "}#" + ex.ToString()); var appLog = new System.Diagnostics.EventLog("Pos Biensi"); appLog.Source = "Printer"; appLog.WriteEntry(ex.Message); //MessageBox.Show(ex.ToString()); } }
static void write(EventLog model) { try { Service s = new Service(); string url = System.Configuration.ConfigurationManager.AppSettings["LogService"]; if (string.IsNullOrEmpty(url)) { return; } s.Url = url; model.AppId = new Guid(System.Configuration.ConfigurationManager.AppSettings["AppGuid"]); s.Credentials = System.Net.CredentialCache.DefaultCredentials; s.Write(model); } catch (Exception exc) { try { string desc = string.Format("ServiceError:{3}\n\nClientIP:{0}\nAppID:{1}\nMessage:{2}", model.Ip, model.AppId, model.Message, exc.ToString()); System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog(); eventLog.Log = "Application"; eventLog.Source = "LogService"; eventLog.WriteEntry(desc.Substring(0, desc.Length > 5000 ? 5000 : desc.Length), System.Diagnostics.EventLogEntryType.Error); } catch { } } }
//------------------------------------------------------------------------------------ protected void btnMatchRoutine_Click(object sender, EventArgs e) { const string EVENT_LOG_SOURCE = "ImportedPods"; const string EVENT_LOG_NAME = "Application"; if (!System.Diagnostics.EventLog.SourceExists(EVENT_LOG_SOURCE)) { System.Diagnostics.EventLog.CreateEventSource(EVENT_LOG_SOURCE, EVENT_LOG_NAME); } System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(EVENT_LOG_NAME, ".", EVENT_LOG_SOURCE); Facade.ImportedPod facImportedPod = new Facade.ImportedPod(); if (this.dteImportFromDate.SelectedDate.HasValue && this.dteImportToDate.SelectedDate.HasValue) { DateTime toDate = this.dteImportToDate.SelectedDate.Value; toDate = toDate.AddHours(23); toDate = toDate.AddMinutes(59); toDate = toDate.AddSeconds(59); facImportedPod.MatchImportedPods(log, Page.User.Identity.Name, this.dteImportFromDate.SelectedDate.Value, toDate); } else { facImportedPod.MatchImportedPods(log, Page.User.Identity.Name); } this.RebindGrid(); }
public void Relist(ApiContext apiContext, System.Diagnostics.EventLog eventLog = null) { ItemType itemType = ToItemType(); RelistItemCall apiCall = new RelistItemCall(apiContext); if (eventLog != null) { eventLog.WriteEntry(string.Format("Start relisting an item... ItemID={0}, Quantity={1}, Price={2}", itemType.ItemID, itemType.Quantity, itemType.StartPrice.Value)); } try { apiCall.RelistItem(itemType); RelistedItemID = itemType.ItemID; IsApiCallSuccess = true; } catch (Exception e) { if (eventLog != null) { eventLog.WriteEntry(string.Format("An error occured while relisting an item... ItemID={0}, Quantity={1}, Price={2}, Message={3}", itemType.ItemID, itemType.Quantity, itemType.StartPrice.Value, e.Message)); } IsApiCallSuccess = false; ApiCallErrorMessage = e.Message; } Console.WriteLine("item was relisted, result={0}", IsApiCallSuccess); }
public void InsertarAutobus(E_Autobus Autobus) { try { conexion.Open(); OracleCommand cmd = conexion.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "SP_INSERTARAUTOBUS"; OracleParameter par1 = new OracleParameter("v_marca", Autobus.Marca); cmd.Parameters.Add(par1); OracleParameter par2 = new OracleParameter("v_modelo", Autobus.Modelo); cmd.Parameters.Add(par2); OracleParameter par3 = new OracleParameter("v_placa", Autobus.Placa); cmd.Parameters.Add(par3); OracleParameter par4 = new OracleParameter("v_color", Autobus.Color); cmd.Parameters.Add(par4); OracleParameter par5 = new OracleParameter("v_año", Autobus.Año); cmd.Parameters.Add(par5); cmd.ExecuteNonQuery(); } catch (OracleException e) { string errorMessage = "Code " + e.ErrorCode + ", Message " + e.Message; System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(); log.Source = "My application"; log.WriteEntry(errorMessage); } conexion.Close(); }
public ISecurityProvider CreateSecurityProviderByLookup() { try { //This only runs once so no reason to cache assemblies var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes()).Where(type => type.IsClass && !type.IsAbstract && type.GetInterfaces().Where(iface => typeof(ISecurityProvider).IsAssignableFrom(iface)).Count() > 0); if (types.Count() == 1 && Security._provider == null) return SecurityProviderFactory.Instance.CreateSecurityProvider(types.Single()); } catch (Exception ex) { try { System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog(); appLog.Source = "Joe.Security"; appLog.WriteEntry("Could not set Security Object: " + ex.Message); } catch { //Do Nothing } } return null; }
/// <summary> /// Write to the application log in windows event logs /// </summary> /// <param name="title"></param> /// <param name="description"></param> public static void WriteTo_WindowsApplicaitonEventLog(string title, string description) { try { DateTime now = DateTime.Now; System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog(); // Set the source name for writing log entries. eventLog.Source = "BlobIM"; // Create an event ID to add to the event log int eventID = 011; // Write an entry to the event log. eventLog.WriteEntry(title + " - " + now + " \r\n" + description, System.Diagnostics.EventLogEntryType.Information, eventID); // Close the Event Log eventLog.Close(); } catch (Exception e) { Alerting.ErrorLogging.WriteTo_Log("Failed To Write to EventLog", e.ToString()); } }
private static void LogFatalError(string msg) { bool ok = false; if (consoleMode) { Console.WriteLine(msg); ok = true; } try { if (logger != null) { logger.Log(msg); ok = true; } } catch (Exception) {} if (!ok) { try { EventLog.WriteEntry(applName, msg); } catch (Exception) {} } }
public static void WriteEventLogEntry(string message, string appName) { // Create an instance of EventLog System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog(); // Check if the event source exists. If not create it. if (!System.Diagnostics.EventLog.SourceExists(appName)) { System.Diagnostics.EventLog.CreateEventSource(appName, "Application"); } // Set the source name for writing log entries. eventLog.Source = appName; // Create an event ID to add to the event log int eventID = 8; // Write an entry to the event log. eventLog.WriteEntry(message, System.Diagnostics.EventLogEntryType.Error, eventID); // Close the Event Log eventLog.Close(); }
private void WriteEvent(Exception ex, string action) { try { System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(); log.Source = eventSource; log.Log = eventLog; if (!System.Diagnostics.EventLog.SourceExists(eventSource)) { System.Diagnostics.EventLog.CreateEventSource(eventSource, eventLog); } string msg = "An exception occured communicating with the data source.\n\n"; msg += "Action: " + action + "\n\n"; msg += "Exception: " + ex.ToString(); log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error); } catch (Exception ex2) { throw new ApplicationException("Unable to write to event log.", new ProviderException(ex2.Message, ex)); } }
public Window1() { InitializeComponent(); try { el = new System.Diagnostics.EventLog("Application", Environment.MachineName, "Audio_Vista"); this.Closing += new System.ComponentModel.CancelEventHandler(Window1_Closing); npsVistaAudio = new VMuktiService.NetPeerServer("net.tcp://localhost:6060/NetP2PRTCVista"); npsVistaAudio.AddEndPoint("net.tcp://localhost:6060/NetP2PRTCVista"); npsVistaAudio.OpenServer(); npcRTCVistaClient = new VMuktiService.NetPeerClient(); objNetP2PRTCVista = new clsNetTcpRTCVistaService(); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcJoin += new clsNetTcpRTCVistaService.DelsvcJoin(Window1_entsvcJoin); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcCreateRTCClient += new clsNetTcpRTCVistaService.DelsvcCreateRTCClient(Window1_entsvcCreateRTCClient); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcRegisterSIPPhone += new clsNetTcpRTCVistaService.DelsvcRegisterSIPPhone(Window1_entsvcRegisterSIPPhone); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcAnswer += new clsNetTcpRTCVistaService.DelsvcAnswer(Window1_entsvcAnswer); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcDial += new clsNetTcpRTCVistaService.DelsvcDial(Window1_entsvcDial); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcHangup += new clsNetTcpRTCVistaService.DelsvcHangup(Window1_entsvcHangup); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcHold += new clsNetTcpRTCVistaService.DelsvcHold(Window1_entsvcHold); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcSendDTMF += new clsNetTcpRTCVistaService.DelsvcSendDTMF(Window1_entsvcSendDTMF); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcTransfer += new clsNetTcpRTCVistaService.DelsvcTransfer(Window1_entsvcTransfer); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcRTCEvent += new clsNetTcpRTCVistaService.DelsvcRTCEvent(Window1_entsvcRTCEvent); ((clsNetTcpRTCVistaService)objNetP2PRTCVista).entsvcUnJoin += new clsNetTcpRTCVistaService.DelsvcUnJoin(Window1_entsvcUnJoin); ClientNetP2PRTCVistaChannel = (INetTcpRTCVistaServiceChannel)npcRTCVistaClient.OpenClient<INetTcpRTCVistaServiceChannel>("net.tcp://localhost:6060/NetP2PRTCVista", "NetP2PRTCVistaMesh", ref objNetP2PRTCVista); ClientNetP2PRTCVistaChannel.svcJoin(); } catch (Exception ex) { el.WriteEntry("Window1:" + ex.Message); el.Close(); } }
public m0Logger(m0LogDestination dest) { m_logdest = dest; m_debuglevel = 0; if (m_logdest == m0LogDestination.LOG_EVENTLOG) { try { m_eventLog = new System.Diagnostics.EventLog(); if (!System.Diagnostics.EventLog.SourceExists("modzero")) { System.Diagnostics.EventLog.CreateEventSource( "modzero", "Application"); } m_eventLog.Source = "modzero"; m_eventLog.Log = "Application"; } catch (Exception e) { m_logdest = m0LogDestination.LOG_CONSOLE; Console.WriteLine("[e] m0Logger: failed to initialize eventlog: " + e.Message); } } else if (m_logdest == m0LogDestination.LOG_FILE) { init_filelogging("modzero_debug.log"); } else { } }
/// <summary> /// Runs a SELECT statement in database /// </summary> /// <param name="sqlcmd">SQL command to execute in database</param> /// <returns>On error null is returned else a OleDbDataReader is returned</returns> private OleDbDataReader executeSql(String sqlcmd) { // Create/get database connection OleDbConnection localconn = getConnection(); OleDbCommand cmd = new OleDbCommand(sqlcmd, localconn); OleDbDataReader reader; // Try to run the SQL-statement try { reader = cmd.ExecuteReader(); } catch (OleDbException e) { // If there is a error write data in programlog for later debugging string errorMessages = ""; for (int i = 0; i < e.Errors.Count; i++) { errorMessages += "Index #" + i + "\n" + "Message: " + e.Errors[i].Message + "\n" + "NativeError: " + e.Errors[i].NativeError + "\n" + "Source: " + e.Errors[i].Source + "\n" + "SQLState: " + e.Errors[i].SQLState + "\n"; } errorMessages += "SQL: " + sqlcmd; System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(); log.Source = "SchemaLite"; log.WriteEntry(errorMessages); return(null); } return(reader); }
private static void BindListener(string ipAddressForBinding) { IPAddress ip; if (!IPAddress.TryParse(ipAddressForBinding, out ip)) { return; } if (Servers.ContainsKey(ipAddressForBinding)) { return; } var dnsServer = new DnsServer(ip, 10, 10); dnsServer.QueryReceived += OnQueryReceived; Servers.Add(ipAddressForBinding, dnsServer); dnsServer.Start(); var appLog = new System.Diagnostics.EventLog { Source = "Hyper-V Dns Proxy" }; appLog.WriteEntry($"Started DNS Service on {ipAddressForBinding}"); }
static void HandleUnhandledException(Exception e, string title, string msgtext) { try { System.Text.StringBuilder sb = new System.Text.StringBuilder(); while (e != null) { sb.AppendFormat("{0}\r\n\r\n{1}\r\n\r\n", e.Message, e.StackTrace); e = e.InnerException; } string logtext = sb.ToString(); Utility.WriteDebugInfo(msgtext); Utility.WriteDebugInfo(logtext); string source = "Growl"; if (!System.Diagnostics.EventLog.SourceExists(source)) { System.Diagnostics.EventLog.CreateEventSource(source, "Application"); } System.Diagnostics.EventLog elog = new System.Diagnostics.EventLog(); elog.Source = source; elog.WriteEntry(logtext, System.Diagnostics.EventLogEntryType.Error); MessageBox.Show(msgtext, title, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); } catch { // dont fail on our global unhandled exception handler - that would just not be right } finally { Environment.Exit(0); } }
private void SendBossSMS(string sms, Enterprise empresa, System.Diagnostics.EventLog eventLog) { foreach (Director boss in empresa.Directors) { byeSMS(boss.CellPhone, sms, userName, password, eventLog); } }
private static void WriteMyEventLog(string iMyMsg, string iErrorMsg, string iConnString) { try { if (!System.Diagnostics.EventLog.SourceExists("CWIFtpApp")) { System.Diagnostics.EventLog.CreateEventSource("CWIFtpApp", "CWIFtpAppLog"); } System.Diagnostics.EventLog myLog = new System.Diagnostics.EventLog(); myLog.Source = "CWIFtpApp"; if (iErrorMsg != "") { myLog.WriteEntry(iMyMsg + " for db: " + iConnString + " Error:" + iErrorMsg); } else { myLog.WriteEntry(iMyMsg + " for db: " + iConnString); } } catch (Exception Ex) { WriteMyEventLog("Error: Cannot Write to the Event Log! ", Ex.Message.ToString(), iConnString); throw Ex; } }
// Método que realiza o monitoramento e executa as tarefas pendentes autorizadas public void monitorAndExecute(System.Diagnostics.EventLog log) { //string authToken = "uQLhVpS2kx2%2b95sRUwiq1uh8iRycp%2bWro6efT7eNTFM%3d"; string authToken = "T%2bVgaQPEbcfz%2bMbQPMd38d2pU7wL678T4nHb%2b%2fQjNI8WeISiIPYYh%2f62AqV3Uo0%2b"; List <AutomaticTask> tarefasAutorizadas = new Business.AutomaticTaskExecution().automaticTaskExecutionList(); // Se tem tarefas autorizadas if (tarefasAutorizadas.Count > 0) { foreach (AutomaticTask at in tarefasAutorizadas) { // Para cada tarefa autorizada por um usuário, verificar a existência destas tarefas em pendência de // execução sob a responsabilidade do usuário que autorizou // Chama query que consulta tarefas pendentes com o codTask e na responsabilidade do usuário em questão List <Data.Task> pendingTasks = new Business.Task().getPendingTasks(at.CodUser, at.CodTask); // Tem dessa tarefa em andamento? // Se sim, // Chamar o apoio à decisão para a tarefa, assim chama uma vez só para várias // Se não tem tarefa pendente, não há por que chamar trecho de apoio à decisão e nem de finalizar if (pendingTasks.Count > 0) { // Número total de execuções da tarefa int totalExecutions = getTotalExecutions(at.CodTask); // Lista de resultados da tarefa List <string> DsFlowResults = getTaskResults(at.CodTask); // Número de possíveis resultados para a tarefa sendo analisada int classCount = DsFlowResults.Count; // Chama a árvore de decisão // TODO: Usar árvore serializada Data.DecisionTree dTree = runDecisionSupport(at.CodTask, totalExecutions, classCount); // Para cada tarefa autorizada e pendente com o usuário, chama o apoio a decisão e depois finaliza a tarefa foreach (Data.Task t in pendingTasks) { // Pegar a sugestão de ação para a tarefa string action = getActionSuggestion(dTree, t.CodFlowExecute); // Cria o objeto de referência ao webservice Instance.Instance inst = new Instance.Instance(); //FinalizeTask02 - Finaliza a tarefa XmlNode xml = inst.FinalizeTask02(authToken, t.CodFlowExecuteTask, action, ""); if (log != null && xml.Name == "success") { log.WriteEntry("A Tarefa " + t.DsTask + " do processo " + t.CodFlowExecute.ToString() + " foi finalizada automaticamente com a opção " + action + "."); } if (xml.Name == "success") { // Notificar o usuário sobre a conclusão da tarefa new Business.AutomaticTaskExecution().notifyAutomaticExecution(at.CodTask, at.CodUser, t.CodFlowExecute); } } } } } }
//=============================================================== // Function: ErrorLog() //=============================================================== public void WriteLog(string moduleName, string functionName, string logText, logMessageLevel logLevel) { DateTime now = DateTime.Now; string strDate = now.Year + "/" + now.Month + "/" + now.Day + " "; if (now.Minute > 9) { strDate += now.Hour + ":" + now.Minute; } else { strDate += now.Hour + ":0" + now.Minute; } string logContents = strDate + " - " + moduleName + ":" + functionName + " - " + logText; // All error messages are written to the event log if (logLevel == logMessageLevel.errorMessage) { System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog(); appLog.Source = "Sedogo"; appLog.WriteEntry(logContents); } StreamWriter sw; if (logLevel <= GlobalSettings.errorLogLevel) { sw = new StreamWriter(GlobalSettings.errorLogFile, true); sw.WriteLine(logContents); sw.Flush(); sw.Close(); } }
public void End(ApiContext apiContext, System.Diagnostics.EventLog eventLog = null) { ItemType itemType = ToItemType(); EndItemCall apiCall = new EndItemCall(apiContext); if (eventLog != null) { eventLog.WriteEntry(string.Format("Start relisting an item... ItemID={0}, Quantity={1}, Price={2}", itemType.ItemID, itemType.Quantity, itemType.StartPrice.Value)); } try { apiCall.EndItem(itemType.ItemID, EndReasonCodeType.NotAvailable); IsApiCallSuccess = true; } catch (Exception e) { if (eventLog != null) { eventLog.WriteEntry(string.Format("An error occured while ending an item... ItemID={0}, Quantity={1}, Price={2}, Message={3}", itemType.ItemID, itemType.Quantity, itemType.StartPrice.Value, e.Message)); } IsApiCallSuccess = false; ApiCallErrorMessage = e.Message; } }
public static void WriteErrorLog(string sLog) { // Create an instance of EventLog System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog(); // Check if the event source exists. If not create it. if (!System.Diagnostics.EventLog.SourceExists(AppDomain.CurrentDomain.FriendlyName)) { System.Diagnostics.EventLog.CreateEventSource(AppDomain.CurrentDomain.FriendlyName, "Application"); } // Set the source name for writing log entries. eventLog.Source = AppDomain.CurrentDomain.FriendlyName; // Create an event ID to add to the event log int eventID = 8; // Write an entry to the event log. eventLog.WriteEntry(sLog, System.Diagnostics.EventLogEntryType.Error, eventID); // Close the Event Log eventLog.Close(); }
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { var ex = e.Exception; System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog(); appLog.Source = ex.Source; appLog.WriteEntry(!string.IsNullOrEmpty(ex.Message) ? ex.Message : ex.InnerException.Message); }
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { var ex = (e.ExceptionObject as Exception); System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog(); appLog.Source = ex.Source; appLog.WriteEntry(!string.IsNullOrEmpty(ex.Message) ? ex.Message : ex.InnerException.Message); }
public static void WriteLog(string strSourceName, string strMessage, System.Diagnostics.EventLogEntryType enEventLogEntryType) { System.Diagnostics.EventLog ArchFxLog = new System.Diagnostics.EventLog("ArchFx"); ArchFxLog.Source = strSourceName; ArchFxLog.WriteEntry(strMessage, enEventLogEntryType, 0); ArchFxLog.Close(); }
protected static void LogEntry(string entry) { if (!System.Diagnostics.EventLog.SourceExists("FileCastService")) System.Diagnostics.EventLog.CreateEventSource( "FileCastService", "Application"); using (System.Diagnostics.EventLog EventLog1 = new System.Diagnostics.EventLog { Source = "FileCastService" }) { EventLog1.WriteEntry(entry); } }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.ServiceEventLog = new System.Diagnostics.EventLog(); ((System.ComponentModel.ISupportInitialize)(this.ServiceEventLog)).BeginInit(); // // CallProxy // this.ServiceName = "GOS Proxy"; ((System.ComponentModel.ISupportInitialize)(this.ServiceEventLog)).EndInit(); }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.serviceLog = new System.Diagnostics.EventLog(); ((System.ComponentModel.ISupportInitialize)(this.serviceLog)).BeginInit(); // IntelliTwitterService components = new System.ComponentModel.Container(); this.ServiceName = "Intelli Twitter Service"; ((System.ComponentModel.ISupportInitialize)(this.serviceLog)).EndInit(); }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.sigConfigClientServiceLog = new System.Diagnostics.EventLog(); ((System.ComponentModel.ISupportInitialize)(this.sigConfigClientServiceLog)).BeginInit(); // // SigConfigClient // this.ServiceName = "SigConfig"; ((System.ComponentModel.ISupportInitialize)(this.sigConfigClientServiceLog)).EndInit(); }
public void InitLog() { mEventLog = new System.Diagnostics.EventLog(); if (!System.Diagnostics.EventLog.SourceExists("Karaoke")) { System.Diagnostics.EventLog.CreateEventSource( "Karaoke", "Web Service"); } mEventLog.Source = "Karaoke"; mEventLog.Log = "Web Service"; }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); eventLog1 = new System.Diagnostics.EventLog(); ((System.ComponentModel.ISupportInitialize)(eventLog1)).BeginInit(); // // DMCFileCacheService // this.ServiceName = "DMCFileCacheService"; ((System.ComponentModel.ISupportInitialize)(eventLog1)).EndInit(); }
public ServiceControl(string[] args) { this.ServiceName = SERVICE_NAME; m_eventLog = new System.Diagnostics.EventLog(); if (!System.Diagnostics.EventLog.SourceExists(LOG_SOURCE)) System.Diagnostics.EventLog.CreateEventSource(LOG_SOURCE, LOG_NAME); m_eventLog.Source = LOG_SOURCE; m_eventLog.Log = LOG_NAME; m_cmdargs = args; m_verbose_messages = m_cmdargs != null && m_cmdargs.Where(x => string.Equals("--debug-service", x, StringComparison.OrdinalIgnoreCase)).Any(); }
public RegistryPersistService() { InitializeComponent(); const string eventSourceName = "RegistryPersistSource"; const string logName = "RegistryPersistLog"; eventLog1 = new System.Diagnostics.EventLog(); if (!System.Diagnostics.EventLog.SourceExists(eventSourceName)) { System.Diagnostics.EventLog.CreateEventSource(eventSourceName, logName); } eventLog1.Source = eventSourceName; eventLog1.Log = logName; }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.eventLog1 = new System.Diagnostics.EventLog(); ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit(); // // eventLog1 // this.eventLog1.Log = "Application"; this.eventLog1.Source = "StateService"; // // StateService // this.ServiceName = "DKLStateService"; ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit(); }
public LidService() { InitializeComponent(); eventlog1 = new System.Diagnostics.EventLog(); if (!System.Diagnostics.EventLog.SourceExists("LidService")) { System.Diagnostics.EventLog.CreateEventSource("LidService", "NewLog"); } else { System.Diagnostics.EventLog.DeleteEventSource("LidService"); } eventlog1.Source = "LidService"; eventlog1.Log = "NewLog"; this.ServiceName = "LidService"; this.CanStop = true; this.CanPauseAndContinue = true; this.AutoLog = true; }
public void EventLogChannelTest() { var sourceName = Guid.NewGuid().ToString(); if (!System.Diagnostics.EventLog.SourceExists(sourceName)) { System.Diagnostics.EventLog.CreateEventSource(sourceName, "Application"); } var el = new DEAD.Logging.EventLog.EventLogStandardChannel(sourceName, StandardLevels.Debug); el?.Log("hahaha"); Thread.Sleep(100); var elcore = new System.Diagnostics.EventLog("Application","."); var e = elcore.Entries[elcore.Entries.Count-1]; Assert.AreEqual(sourceName, e.Source); if (System.Diagnostics.EventLog.SourceExists(sourceName)) { System.Diagnostics.EventLog.DeleteEventSource(sourceName); } }
// Handle the UI exceptions by showing a dialog box, and asking the user whether // or not they wish to abort execution. // NOTE: This exception cannot be kept from terminating the application - it can only // log the event, and inform the user about it. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { try { Exception ex = (Exception)e.ExceptionObject; string errorMsg = "An application error occurred. Please contact the adminstrator " + "with the following information:\n\n"; // Since we can't prevent the app from terminating, log this to the event log. if (!System.Diagnostics.EventLog.SourceExists("ThreadException")) { System.Diagnostics.EventLog.CreateEventSource("ThreadException", "Application"); } // Create an EventLog instance and assign its source. System.Diagnostics.EventLog myLog = new System.Diagnostics.EventLog(); myLog.Source = "ThreadException"; myLog.WriteEntry(errorMsg + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace); Log(ex.Message); } catch (Exception exc) { try { MessageBox.Show("Fatal Non-UI Error", "Fatal Non-UI Error. Could not write the error to the event log. Reason: " + exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop); Log(exc.Message); } finally { System.Environment.Exit(0); } } }
public static void SetupEventLog(System.Diagnostics.EventLog eventLog) { _eventLog = eventLog; }
private void Log(string msg) { if(msg == null) msg = string.Empty; try { if(!System.Diagnostics.EventLog.SourceExists(ServiceName)) { System.Diagnostics.EventLog.CreateEventSource(ServiceName, "NetzServiceLog"); } System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog(); eventLog.Source = ServiceName; eventLog.WriteEntry(msg); eventLog = null; } catch { System.Diagnostics.Debug.WriteLine("Netz: " + ServiceName + " Error: " + msg); } }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.eventLogQuote = new System.Diagnostics.EventLog(); this.buttonExit = new System.Windows.Forms.Button(); this.listBoxEvents = new System.Windows.Forms.ListBox(); ((System.ComponentModel.ISupportInitialize)(this.eventLogQuote)).BeginInit(); this.SuspendLayout(); // // eventLogQuote // this.eventLogQuote.EnableRaisingEvents = true; this.eventLogQuote.Log = "Application"; this.eventLogQuote.Source = "QuoteService"; this.eventLogQuote.SynchronizingObject = this; this.eventLogQuote.EntryWritten += new System.Diagnostics.EntryWrittenEventHandler(this.OnEntryWritten); // // buttonExit // this.buttonExit.Location = new System.Drawing.Point(160, 232); this.buttonExit.Name = "buttonExit"; this.buttonExit.Size = new System.Drawing.Size(88, 24); this.buttonExit.TabIndex = 1; this.buttonExit.Text = "Exit"; this.buttonExit.Click += new System.EventHandler(this.buttonExit_Click); // // listBoxEvents // this.listBoxEvents.Location = new System.Drawing.Point(16, 8); this.listBoxEvents.Name = "listBoxEvents"; this.listBoxEvents.Size = new System.Drawing.Size(368, 212); this.listBoxEvents.TabIndex = 0; // // EventListener // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(400, 273); this.Controls.AddRange(new System.Windows.Forms.Control[] {this.buttonExit, this.listBoxEvents}); this.Name = "EventListener"; this.Text = "Quote Service Event Listener"; ((System.ComponentModel.ISupportInitialize)(this.eventLogQuote)).EndInit(); this.ResumeLayout(false); }
/// <summary> /// takes an exception as input and logs it to file and potentially to the System EventLog /// </summary> /// <param name="oException">the exception</param> /// <param name="errPath">the path you would like to log it to</param> /// <param name="bSysEventLog">log it to the system event log?</param> public static void WriteExceptionLog(Exception oException, string errPath, bool bSysEventLog) { try { FileTools.SForceFileCreation(errPath); StreamWriter sw = new StreamWriter(errPath, true); sw.WriteLine("===================================================================="); sw.WriteLine("Source : " + oException.Source.ToString().Trim()); sw.WriteLine("Method : " + oException.TargetSite.Name.ToString()); sw.WriteLine("Date : " + DateTime.Now.ToLongTimeString()); sw.WriteLine("Time : " + DateTime.Now.ToShortDateString()); sw.WriteLine("Computer : " + Dns.GetHostName().ToString()); sw.WriteLine("Error : " + oException.Message.ToString().Trim()); sw.WriteLine("Stack Trace : " + oException.StackTrace.ToString().Trim()); sw.Flush(); sw.Close(); } catch (Exception ex) { } if (bSysEventLog) { try { string message = oException.GetBaseException().Message; System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(); log.Source = oException.Source.ToString().Trim(); log.WriteEntry(message); } catch (Exception) { } } }
public static void SendEmail(string subject, string msg, string sender, string to, bool overrideInterval) { try { if ((DateTime.Now.Subtract(lastemail).Ticks > acceptableInterval || overrideInterval)) { var kfdEmail = new Email(smtpserver); kfdEmail.SetEmail(subject.ToString(), msg.ToString()); kfdEmail.AddToAddress(to); kfdEmail.SetSender(sender); kfdEmail.SetBodyIsHTML(false); kfdEmail.SetTimeoutInSeconds(30); kfdEmail.SendEmail(); lastemail = DateTime.Now; } } catch (Exception e) { var log = new System.Diagnostics.EventLog { Source = e.Source.Trim() }; log.WriteEntry(e.Message); } }
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { DialogResult result = DialogResult.Cancel; System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application", ".", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); rfidLogErrorException logError = e.Exception as rfidLogErrorException; if (logError == null) { rfidException rfid = e.Exception as rfidException; if (rfid == null) { log.WriteEntry(FormatEventMessage(e.Exception), System.Diagnostics.EventLogEntryType.Error); } else { log.WriteEntry(FormatEventMessage(rfid), System.Diagnostics.EventLogEntryType.Error, (int)rfid.ErrorCode.ErrorCode); } } else { if (!logError.HasBeenLogged) { rfidException rfid = logError.InnerException as rfidException; if (rfid == null) { log.WriteEntry(FormatEventMessage(logError.InnerException), System.Diagnostics.EventLogEntryType.Error); } else { log.WriteEntry(FormatEventMessage(rfid), System.Diagnostics.EventLogEntryType.Error, (int)rfid.ErrorCode.ErrorCode); } } Application.Exit(); } try { result = ShowThreadExceptionDialog(e.Exception); } catch { try { MessageBox.Show("Fatal Error", "Fatal Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop); } finally { Application.Exit(); } } // Exits the program when the user clicks Abort. if (result == DialogResult.Abort) try { Application.Exit(); } catch { Application.Exit(); } finally { Application.Exit(); } }
static void Main() { if ( true == isOpen() ) { MessageBox.Show("Already Opened"); return; } System.Threading.Thread.CurrentThread.Name = "UpdateToolMainGUIThread"; System.Diagnostics.Debug.WriteLine(String.Format("{0} is threadID {1}", System.Threading.Thread.CurrentThread.Name, System.Threading.Thread.CurrentThread.ManagedThreadId)); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.ThreadException +=new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); try { string dir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); //Check Linkage.dll string fileName = Path.Combine(dir, Properties.Settings.Default.fileNameLinkdage); if (!System.IO.File.Exists(fileName)) throw new Exception(String.Format("A critial dll file is missing.\n({0})", fileName)); //Check Transfer.dll fileName = Path.Combine(dir, Properties.Settings.Default.fileNameTransfer); if (!System.IO.File.Exists(fileName)) throw new Exception(String.Format("A critial dll file is missing.\n({0})", fileName)); Application.Run( new UpdateFW() ); } catch (TypeInitializationException exp) { MessageBox.Show(exp.Message); System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application", ".", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); log.WriteEntry(FormatEventMessage(exp), System.Diagnostics.EventLogEntryType.Error, 1); if (exp.InnerException != null) { log.WriteEntry(FormatEventMessage(exp.InnerException), System.Diagnostics.EventLogEntryType.Error, 2); } } catch (rfidException rfid) { System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application", ".", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); try { log.WriteEntry(rfid.Message, System.Diagnostics.EventLogEntryType.Error, (int)rfid.ErrorCode.ErrorCode); } catch (Exception) { } } catch (System.ComponentModel.Win32Exception win32) { switch (win32.NativeErrorCode) { // no point in trying to write the log case ERROR_EVENTLOG_FILE_CORRUPT: case ERROR_EVENTLOG_CANT_START: case ERROR_LOG_FILE_FULL: MessageBox.Show("Unable to write to Application Log.\n\n" + win32.Message); break; default: try { System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application", ".", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); log.WriteEntry(win32.Message, System.Diagnostics.EventLogEntryType.Error, 1); } catch (Exception) { } break; } } catch (Exception e) { try { System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application", ".", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); log.WriteEntry(e.Message, System.Diagnostics.EventLogEntryType.Error, 1); MessageBox.Show(e.Message); } catch (Exception) { MessageBox.Show("Unable to write to Application Log.\n\n" + e.Message); } throw; } }
/// <summary> /// This logs the message to the path provided /// </summary> /// <param name="mess">the message</param> /// <param name="errPath">the path</param> /// public static void WriteMessageLog(string mess, string errPath) { mess = DateTime.Now + " - " + mess; try { FileTools.SForceFileCreation(errPath); StreamWriter sw = new StreamWriter(errPath, true); sw.WriteLine(mess); sw.Flush(); sw.Close(); } catch (Exception ex) { var log = new System.Diagnostics.EventLog { Source = ex.Source.Trim() }; log.WriteEntry(ex.Message); } }
/// <summary> /// Is user allowed to use service. /// </summary> /// <param name="authService"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public override bool TryAuthenticate(IServiceBase authService, string userName, string password) { GXAmiUser user; OrmLiteConnectionFactory f = authService.TryResolve<IDbConnectionFactory>() as OrmLiteConnectionFactory; //Connection factory is null when we are configure server at first time. if (f == null || f.ConnectionString == null) { return true; } try { using (IDbConnection Db = f.OpenDbConnection()) { lock (Db) { if (!GuruxAMI.Service.GXManagementService.IsDatabaseCreated(Db)) { #if !SS4 string[] items = RestPath.GetPathPartsForMatching(authService.RequestContext.PathInfo); #else string[] items = RestPath.GetPathPartsForMatching(authService.Request.PathInfo); #endif string target = items[items.Length - 1]; if (string.Compare(target, typeof(GXIsDatabaseCreatedRequest).Name, true) == 0 || string.Compare(target, typeof(GXCreateTablesRequest).Name, true) == 0 || string.Compare(target, typeof(GXDropTablesRequest).Name, true) == 0) { user = new GXAmiUser("gurux", "gurux", UserAccessRights.SuperAdmin); user.Id = 1; InitUser(authService, user); return true; } return false; } List<GXAmiUser> users = Db.Select<GXAmiUser>(q => q.Name == userName && q.Password == password); if (users.Count != 1) { //If known DC try to get new tasks, add new task, mark task claimed or add device exception. Guid guid; #if !SS4 string[] items = RestPath.GetPathPartsForMatching(authService.RequestContext.PathInfo); #else string[] items = RestPath.GetPathPartsForMatching(authService.Request.PathInfo); #endif string target = items[items.Length - 1]; if (items != null && items.Length != 0) { if (string.Compare(target, typeof(GXEventsRequest).Name, true) == 0 || string.Compare(target, typeof(GXEventsRegisterRequest).Name, true) == 0 || string.Compare(target, typeof(GXEventsUnregisterRequest).Name, true) == 0 || string.Compare(target, typeof(GXTaskDeleteRequest).Name, true) == 0 || string.Compare(target, typeof(GXTasksRequest).Name, true) == 0 || string.Compare(target, typeof(GXTaskUpdateRequest).Name, true) == 0 || string.Compare(target, typeof(GXTasksClaimRequest).Name, true) == 0 || string.Compare(target, typeof(GXTraceLevelRequest).Name, true) == 0) { //If DC register first time and starts to listen events. if (IsGuid(userName, out guid)) { //If known DC wants to listen events. List<GXAmiDataCollector> list = Db.Select<GXAmiDataCollector>(p => p.Guid == guid); if (list.Count == 1) { IAuthSession s = authService.GetSession(false); s.Id = userName; s.UserAuthId = Guid.NewGuid().ToString(); s.UserName = userName; s.IsAuthenticated = true; s.Roles = new List<string>(); s.Roles.Add("0"); return true; } return false; } return false; } else if (string.Compare(target, typeof(GXDataCollectorUpdateRequest).Name, true) == 0 && IsGuid(userName, out guid)) { if (guid == Guid.Empty) { /* TODO: IAuthSession s = authService.GetSession(false); s.Id = userName; s.UserAuthId = Guid.NewGuid().ToString(); s.UserName = userName; s.IsAuthenticated = true; s.Roles = new List<string>(); s.Roles.Add("0"); * */ return true; } //If DC updates itself. List<GXAmiDataCollector> list = Db.Select<GXAmiDataCollector>(p => p.Guid == guid); if (list.Count == 1) { IAuthSession s = authService.GetSession(false); s.Id = userName; s.UserAuthId = Guid.NewGuid().ToString(); s.UserName = userName; s.IsAuthenticated = true; s.Roles = new List<string>(); s.Roles.Add("0"); return true; } return false; } //If data collector wants to get data from itself by Guid. else if (string.Compare(target, typeof(GXDataCollectorsRequest).Name, true) == 0 && IsGuid(userName, out guid)) { List<GXAmiDataCollector> list = Db.Select<GXAmiDataCollector>(p => p.Guid == guid); if (list.Count == 1) { IAuthSession s = authService.GetSession(false); s.Id = userName; s.UserAuthId = Guid.NewGuid().ToString(); s.UserName = userName; s.IsAuthenticated = true; s.Roles = new List<string>(); s.Roles.Add("0"); return true; } return false; } return false; } } user = users[0]; InitUser(authService, user); } } } catch (Exception ex) { GuruxAMI.Server.AppHost.ReportError(ex); try { if (!System.Diagnostics.EventLog.SourceExists("GuruxAMI")) { System.Diagnostics.EventLog.CreateEventSource("GuruxAMI", "Application"); } System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog(); appLog.Source = "GuruxAMI"; appLog.WriteEntry(ex.Message); } catch (System.Security.SecurityException) { //Security exception is thrown if GuruxAMI source is not exists and it's try to create without administrator privilege. //Just skip this, but errors are not write to eventlog. } throw ex; } return true; }
static void write(LogEvent log) { try { ILogProvider logger = new RefObjectCreator().Create<ILogProvider>(); if (logger == null) logger = new LogServiceProvider(); logger.Write(log); } catch (Exception exc) { try { string message = "ServiceError:{0}\n\nClientIP:{1}\nAppID:{2}\nMessage:{3}".FormatArgs( exc, log.IPAddress, log.AppId, log.Message); System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog(); eventLog.Log = "Application"; eventLog.Source = "LogService"; if (message.Length > 5000) message = message.Substring(0, 5000); eventLog.WriteEntry(message, System.Diagnostics.EventLogEntryType.Error); } catch { } } }