public static bool WriteError(Exception exception) { StringBuilder LogBuilder = new StringBuilder(); StreamWriter LogWriter; try { if (Directory.Exists(Application.StartupPath + "\\LogPath") == false) { Directory.CreateDirectory(Application.StartupPath + "\\LogPath"); } LogWriter = File.AppendText(Application.StartupPath + "\\LogPath\\Errors" + DateTime.Today.ToShortDateString().Replace("/", "-") + ".log"); LogBuilder.Append("<" + System.DateTime.Now.ToString() + ">"); LogBuilder.Append(" "); LogBuilder.Append(exception.Source); LogBuilder.Append(" "); LogBuilder.Append(exception.Message); LogBuilder.Append(" "); LogBuilder.Append(exception.StackTrace); LogBuilder.Append(" "); LogWriter.WriteLine(LogBuilder.ToString()); LogWriter.Close(); return(true); } catch (CustomException tbex) { return(false); } }
public void Log(Category eCat, string sMessage) { try { lock (Locker) { DateTime dt = DateTime.Now; if (Math.Abs(dt.DayOfYear - Ndt.DayOfYear) > 0) { if (LogWriter != null) { LogWriter.Close(); LogWriter.Dispose(); } LogWriter = CreateFileStreamWriter(); } if (LogWriter != null) { Ndt = dt; string s = dt.ToString("yyyy-MM-dd HH:mm:ss:fff") + " " + eCat + ": > " + sMessage; LogWriter.BaseStream.Seek(0, SeekOrigin.End); LogWriter.WriteLine(s); LogWriter.Flush(); } } } catch (Exception) { } }
private void CloseLogWriter() { if (_logWriter != null) { _logWriter.Close(); _logWriter = null; } }
public void Close() { if (LogWriter != null) { LogWriter.Close(); LogWriter.Dispose(); LogWriter = null; } }
private static void DumpQuadrant <T>(String label, Quadrant <T> q, LogWriter w) where T : class { if (q != null) { w.Open("Quadrant"); w.WriteAttribute("Name", label); q.Dump(w); w.Close(); } }
public static void Close() { Exists = false; try { LogWriter?.Close(); } catch (Exception) { // NOOP } }
public void StopLog() { if (!loggingEnabled) { return; } frameFile.Close(); // stop current logger loggingEnabled = false; frameDataLogModel = null; }
private void CloseLogger() { DetectLogCallback = null; if (LogWriter != null) { LogWriter.Close(); LogWriter.Dispose(); } if (detectLogs.ContainsKey(latestDetectorInstanceId)) { detectLogs.Remove(latestDetectorInstanceId); } }
public static void Dump <T>(this Quadrant <T> source, LogWriter w) where T : class { w.WriteAttribute("Bounds", source.Bounds.ToString()); if (source.Nodes != null) { QuadNode <T> n = source.Nodes; do { n = n.Next; // first node. w.Open("node"); w.WriteAttribute("Bounds", n.Bounds.ToString()); w.Close(); } while (n != source.Nodes); } DumpQuadrant("TopLeft", source.TopLeft, w); DumpQuadrant("TopRight", source.TopRight, w); DumpQuadrant("BottomLeft", source.BottomLeft, w); DumpQuadrant("BottomRight", source.BottomRight, w); }
public static void LogToFile(string message) { StreamWriter LogWriter; string sLogPath = Path.Combine(Environment.CurrentDirectory + @"\Log\");//System.Configuration.ConfigurationManager.AppSettings["LogFilePath"].ToString(); StringBuilder logfilename = new StringBuilder(); logfilename.Append(sLogPath); logfilename.Append(String.Format("{0:0000}", DateTime.Now.Year)); logfilename.Append("_"); logfilename.Append(String.Format("{0:00}", DateTime.Now.Month)); logfilename.Append("_"); logfilename.Append(String.Format("{0:00}", DateTime.Now.Day)); logfilename.Append(".txt"); try { if (!File.Exists(logfilename.ToString())) { if (!Directory.Exists(sLogPath)) { Directory.CreateDirectory(sLogPath); } LogWriter = new StreamWriter(logfilename.ToString()); } else { LogWriter = File.AppendText(logfilename.ToString()); } string msg = "<DATA>" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + " : " + message + "</DATA>"; LogWriter.WriteLine(msg); LogWriter.Flush(); LogWriter.Close(); } catch (Exception) { } }
private string CreateMessage(Exception exception, Guid handlingInstanceID) { StringWriter writer = null; StringBuilder stringBuilder = null; try { writer = CreateStringWriter(); writer.WriteLine("HandlingInstanceID: {0}", handlingInstanceID.ToString()); ExceptionFormatter formatter = CreateFormatter(writer, exception); formatter.Format(); stringBuilder = writer.GetStringBuilder(); } finally { if (writer != null) { writer.Close(); } } return(stringBuilder.ToString()); }
void OnDestroy() { _writer.Close(); _logWriter.Close(); }
/// <summary> /// Initialization of internal resources. /// Must be called at the start of the application execution. /// </summary> public static void Initialize(string AppName, string AppVersion, string AppDefinitions, string UserDataName) { if (Initialized) { Console.WriteLine("Reinitializing"); } General.ContractRequiresNotAbsent(AppName, AppVersion, UserDataName); General.ContractAssert(AppName.IsValidIdentifier()); General.ContractAssert(UserDataName.IsValidIdentifier()); ApplicationName = AppName; ApplicationVersion = AppVersion; // Very important. License version is check against this ApplicationDefinitions = AppDefinitions; UserDataNaming = UserDataName; string DetectedProblem = ""; Exception DetectedError = null; SessionStart = DateTime.Now; // MUST BE THE SAME FOLDERS AS IN InstallerCustomAction.Installer1.cs (Commit method) // This is: - "C:\ProgramData\" on Windows Vista and Windows 7 // - "C:\Documents and Settings\<User-Account>\Application Data\" on Windows XP ApplicationsCommonDataDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), General.TextToIdentifier(Company.NAME_SIMPLE)); ApplicationsClipartDirectory = Path.Combine(ApplicationsCommonDataDirectory, CLIPART_SUBDIR); // This is: "C:\Users\<User-Account>\AppData\Local\Instrumind" on Windows 7 ApplicationUserDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), General.TextToIdentifier(Company.NAME_SIMPLE)); // My Documents\My Compositions UserDataDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), USERDATA_DIR_PREFIX + UserDataNaming); try { // Create [Common]\Instrumind if (!Directory.Exists(ApplicationsCommonDataDirectory)) { Directory.CreateDirectory(ApplicationsCommonDataDirectory); } // Create [Common]\Instrumind\ThinkComposer (currently not used, as it cannot be saved without UAC/admin privileges) ApplicationSpecificDataDirectory = Path.Combine(ApplicationsCommonDataDirectory, AppExec.ApplicationName.TextToIdentifier()); if (!Directory.Exists(ApplicationSpecificDataDirectory)) { Directory.CreateDirectory(ApplicationSpecificDataDirectory); } // Create [Common]\Instrumind\Domains ApplicationSpecificDefinitionsDirectory = Path.Combine(ApplicationsCommonDataDirectory, AppExec.ApplicationDefinitions.TextToIdentifier()); if (!Directory.Exists(ApplicationSpecificDefinitionsDirectory)) { Directory.CreateDirectory(ApplicationSpecificDefinitionsDirectory); } // Create [User]\Instrumind if (!Directory.Exists(ApplicationUserDirectory)) { Directory.CreateDirectory(ApplicationUserDirectory); } // Create [User]\Instrumind\_temp ApplicationUserTemporalDirectory = Path.Combine(ApplicationUserDirectory, TEMPORAL_SUBDIR); if (!Directory.Exists(ApplicationUserTemporalDirectory)) { Directory.CreateDirectory(ApplicationUserTemporalDirectory); } // Create [User]\Instrumind\ThinkComposer ApplicationUserDirectory = Path.Combine(ApplicationUserDirectory, AppExec.ApplicationName.TextToIdentifier()); if (!Directory.Exists(ApplicationUserDirectory)) { Directory.CreateDirectory(ApplicationUserDirectory); } // Third: Create ...\MyCompositions if (!Directory.Exists(UserDataDirectory)) { Directory.CreateDirectory(UserDataDirectory); } } catch (Exception Anomaly) { DetectedProblem = "Cannot create Application Directory."; DetectedError = Anomaly; } if (DetectedError == null) { LicenseFilePath = ApplicationUserDirectory + "\\" + AppExec.ApplicationName.TextToIdentifier() + "." + LICENSE_EXTENSION; ConfigurationFilePath = ApplicationUserDirectory + "\\" + AppExec.ApplicationName.TextToIdentifier() + "." + CONFIG_EXTENSION; RecentDocumentsFilePath = ApplicationUserDirectory + "\\" + "RecentDocuments." + LISTS_EXTENSION; try { // new StreamWriter(new FileStream(LogFileName, FileMode.Append, FileAccess.Write, FileShare.Read)); LogWriter = TextWriter.Synchronized(new StreamWriter(ConfigurationFilePath, true)); } catch (Exception Anomaly) { DetectedProblem = "Cannot open or create Configuration file."; DetectedError = Anomaly; } } if (DetectedError == null) { if (LogWriter != null) { LogWriter.Close(); } LogFilePath = ApplicationUserDirectory + "\\" + AppExec.ApplicationName.TextToIdentifier() + "." + LOG_EXTENSION; try { // new StreamWriter(new FileStream(LogFileName, FileMode.Append, FileAccess.Write, FileShare.Read)); LogWriter = TextWriter.Synchronized(new StreamWriter(LogFilePath, true)); } catch (Exception Anomaly) { DetectedProblem = "Cannot open Log file."; DetectedError = Anomaly; } } if (DetectedError != null) { // At this point, there could not be an application unhandled exception event attached, // so this problem will just be logged to the console. var Here = System.Reflection.MethodBase.GetCurrentMethod(); LogException(new WarningAnomaly(new ExternalAnomaly(DetectedProblem, DetectedError)), Here.DeclaringType.FullName + "." + Here.Name); LogWriter = null; } Initialized = true; }
public void Dump(string filename) { using (StreamWriter w = new StreamWriter(filename)) { using (LogWriter log = new LogWriter(w)) { log.Open("QuadTree"); _index.Dump(log); log.Open("Other"); log.WriteAttribute("MaxDepth", log.MaxDepth.ToString()); log.Close(); log.Close(); } } }
/// <summary> /// Used to stop the gamecontroller. /// Here everything is closed down. /// </summary> public void StopGame() { IsRunning = false; _udpHost.Close(); _logWriter.Close(); }
/// <summary> /// Start a POP3 proxy instance. /// </summary> /// <param name="acceptedIPs">IP addresses to accept connections from.</param> /// <param name="localIPAddress">Local IP address to bind to.</param> /// <param name="localPort">Local port to listen on.</param> /// <param name="localEnableSsl">Whether the local server supports TLS/SSL.</param> /// <param name="remoteServerHostName">Remote server hostname to forward all POP3 messages to.</param> /// <param name="remoteServerPort">Remote server port to connect to.</param> /// <param name="remoteServerEnableSsl">Whether the remote POP3 server requires TLS/SSL.</param> /// <param name="remoteServerCredential">(Optional) Credentials to be used for all connections to the remote POP3 server. When set, this overrides any credentials passed locally.</param> /// <param name="exportDirectory">(Optional) Location where all incoming messages are saved as EML files.</param> /// <param name="logFile">File where event logs and exception information will be written.</param> /// <param name="logLevel">Proxy logging level, determining how much information is logged.</param> /// <param name="instanceId">The instance number of the proxy.</param> /// <param name="debugMode">Whether the proxy instance is running in DEBUG mode and should output full exception messages.</param> public void Start(string acceptedIPs, IPAddress localIPAddress, int localPort, bool localEnableSsl, string remoteServerHostName, int remoteServerPort, bool remoteServerEnableSsl, NetworkCredential remoteServerCredential, string exportDirectory, string logFile, LogLevel logLevel, int instanceId, bool debugMode) { // Create the log writer. string logFileName = ""; if (!string.IsNullOrEmpty(logFile)) { logFileName = ProxyFunctions.GetLogFileName(logFile, instanceId, localIPAddress.ToString(), remoteServerHostName, localPort, remoteServerPort); LogWriter = new StreamWriter(logFileName, true, Encoding.UTF8, Constants.SMALLBUFFERSIZE); LogWriter.AutoFlush = true; LogLevel = logLevel; } // Make sure the remote server isn't an infinite loop back to this server. string fqdn = Functions.GetLocalFQDN(); if (remoteServerHostName.ToUpper() == fqdn.ToUpper() && remoteServerPort == localPort) { ProxyFunctions.Log(LogWriter, SessionId, "Cannot start service because the remote server host name {" + remoteServerHostName + "} and port {" + remoteServerPort.ToString() + "} is the same as this proxy, which would cause an infinite loop.", Proxy.LogLevel.Critical, LogLevel); return; } IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress hostIP in hostEntry.AddressList) { if (remoteServerHostName == hostIP.ToString() && remoteServerPort == localPort) { ProxyFunctions.Log(LogWriter, SessionId, "Cannot start service because the remote server hostname {" + remoteServerHostName + "} and port {" + remoteServerPort.ToString() + "} is the same as this proxy, which would cause an infinite loop.", Proxy.LogLevel.Critical, LogLevel); return; } } ProxyFunctions.Log(LogWriter, SessionId, "Starting service.", Proxy.LogLevel.Information, LogLevel); // Attempt to start up to 3 times in case another service using the port is shutting down. int startAttempts = 0; while (startAttempts < 3) { startAttempts++; // If we've failed to start once, wait an extra 10 seconds. if (startAttempts > 1) { ProxyFunctions.Log(LogWriter, SessionId, "Attempting to start for the " + (startAttempts == 2 ? "2nd" : "3rd") + " time.", Proxy.LogLevel.Information, LogLevel); Thread.Sleep(10000 * startAttempts); } try { X509Certificate serverCertificate = null; // Generate a unique session ID for logging. SessionId = Guid.NewGuid().ToString(); ConnectionId = 0; // If local SSL is supported via STARTTLS, ensure we have a valid server certificate. if (localEnableSsl) { serverCertificate = CertHelper.GetCertificateBySubjectName(StoreLocation.LocalMachine, fqdn); // In case the service as running as the current user, check the Current User certificate store as well. if (serverCertificate == null) { serverCertificate = CertHelper.GetCertificateBySubjectName(StoreLocation.CurrentUser, fqdn); } // If no certificate was found, generate a self-signed certificate. if (serverCertificate == null) { ProxyFunctions.Log(LogWriter, SessionId, "No signing certificate found, so generating new certificate.", Proxy.LogLevel.Warning, LogLevel); List <string> oids = new List <string>(); oids.Add("1.3.6.1.5.5.7.3.1"); // Server Authentication. // Generate the certificate with a duration of 10 years, 4096-bits, and a key usage of server authentication. serverCertificate = CertHelper.CreateSelfSignedCertificate(fqdn, fqdn, StoreLocation.LocalMachine, true, 4096, 10, oids); ProxyFunctions.Log(LogWriter, SessionId, "Certificate generated with Serial Number {" + serverCertificate.GetSerialNumberString() + "}.", Proxy.LogLevel.Information, LogLevel); } } // Start listening on the specified port and IP address. Listener = new TcpListener(localIPAddress, localPort); Listener.Start(); ProxyFunctions.Log(LogWriter, SessionId, "Service started.", Proxy.LogLevel.Information, LogLevel); ProxyFunctions.Log(LogWriter, SessionId, "Listening on address {" + localIPAddress.ToString() + "}, port {" + localPort + "}.", Proxy.LogLevel.Information, LogLevel); Started = true; // Accept client requests, forking each into its own thread. while (Started) { TcpClient client = Listener.AcceptTcpClient(); string newLogFileName = ProxyFunctions.GetLogFileName(logFile, instanceId, localIPAddress.ToString(), remoteServerHostName, localPort, remoteServerPort); if (newLogFileName != logFileName) { if (LogWriter != null) { LogWriter.Close(); } LogWriter = new StreamWriter(newLogFileName, true, Encoding.UTF8, Constants.SMALLBUFFERSIZE); LogWriter.AutoFlush = true; } // Prepare the arguments for our new thread. Pop3ProxyConnectionArguments arguments = new Pop3ProxyConnectionArguments(); arguments.AcceptedIPs = acceptedIPs; arguments.TcpClient = client; arguments.Certificate = serverCertificate; arguments.ExportDirectory = exportDirectory; arguments.LocalIpAddress = localIPAddress; arguments.LocalPort = localPort; arguments.LocalEnableSsl = localEnableSsl; arguments.RemoteServerHostName = remoteServerHostName; arguments.RemoteServerPort = remoteServerPort; arguments.RemoteServerEnableSsl = remoteServerEnableSsl; arguments.RemoteServerCredential = remoteServerCredential; // Increment the connection counter; arguments.ConnectionId = (unchecked (++ConnectionId)).ToString(); arguments.InstanceId = instanceId; arguments.DebugMode = debugMode; // Fork the thread and continue listening for new connections. Thread processThread = new Thread(new ParameterizedThreadStart(ProcessConnection)); processThread.Name = "OpaqueMail POP3 Proxy Connection"; processThread.Start(arguments); } return; } catch (Exception ex) { if (debugMode || System.Diagnostics.Debugger.IsAttached) { ProxyFunctions.Log(LogWriter, SessionId, "Exception when starting proxy: " + ex.ToString(), Proxy.LogLevel.Critical, LogLevel); } else { ProxyFunctions.Log(LogWriter, SessionId, "Exception when starting proxy: " + ex.Message, Proxy.LogLevel.Critical, LogLevel); } } } }
public void Dispose() { LogWriter.Close(); }