public void LogText(LogLevel logLevel, String strInText, params object[] parms) { String output = String.Format(strInText, parms); BufferedOutput cached; try { _outputListLock.Lock(); if (_outputByText.TryGetValue(output, out cached) == false) { cached = new BufferedOutput(logLevel, DateTime.UtcNow, output); _outputByText.Add(output, cached); } cached.AddInstance(); int count; if (cached.TryGetOutput(_minumumOutputInterval, out count)) { _log.LogText(logLevel, String.Format("{0} - ({1} times)", output, count)); _outputByText.Remove(output); } } finally { _outputListLock.Unlock(); } CheckCache(); }
public void AddInstance() { try { _listLock.Lock(); _outputList.Add(new BufferedLine()); } finally { _listLock.Unlock(); } }
public static int Main(string[] args) { Thread.Sleep(2000); MutexLock.Lock(); try { ExternalFunctionalityManager.Init(new UtLibFunctions()); RootCommand rootCommand = new RootCommand(); Command install = new Command("install", "Install UpTool") { new Option <bool>(new[] { "--noPrep", "-p" }, "Doesn't initialize repos. Use with caution!") }; install.AddAlias("-i"); install.AddAlias("i"); install.Handler = CommandHandler.Create <bool>(Install); rootCommand.AddCommand(install); return(rootCommand.InvokeAsync(args).Result); } catch (Exception e) { Console.WriteLine($"FAILED: {e}"); return(1); } finally { MutexLock.Unlock(); } }
public static int Main(string[] args) { MutexLock.Lock(); try { XmlTool.FixXml(); ExternalFunctionalityManager.Init(Functions); RootCommand rootCommand = new RootCommand(); PackageManagement.RegisterCommands(rootCommand); CacheManagement.RegisterCommands(rootCommand); ReposManagement.RegisterCommands(rootCommand); Other.RegisterCommands(rootCommand); return(rootCommand.InvokeAsync(args).Result); } catch (Exception e) { Console.WriteLine($"FAILED: {e}"); return(1); } finally { MutexLock.Unlock(); } }
public QUEUETYPE Dequeue() { QUEUETYPE ret = default(QUEUETYPE); try { _listLock.Lock(); ret = PopHead(); } finally { _listLock.Unlock(); } return(ret); }
public void ReceivedEvents(int count) { try { _lock.Lock(); while (count-- > 0) { _eventList.Add(CreateEvent()); } } finally { _lock.Unlock(); } RemoveSurplusEvents(); }
public void Close() { if (_logging) { _logging = false; _lock.Lock(); if (this == _systemLog) { _systemLog = null; } CloseLogFile(); CloseLogConsole(); _lock.Unlock(); } }
public static DBResult GetDatabaseVersion(SqlDBCredentials credentials, out SoftwareVersion version, out InternalDatabaseType databaseType) { DBResult retVal = new DBResult(DBResult.Result.Success); try { _databaseVersionLock.Lock(); version = null; databaseType = InternalDatabaseType.Unknown; String indexKey = credentials.ToParsableString(); if (!_databaseVersionLookup.TryGetValue(indexKey, out version)) { ISqlDataSource ds = SqlConnectionPool.Instance(credentials).GetDataSource(); DatabaseDataReader reader; QueryString sql = ds.FormatTrusted("SELECT * FROM I.seq where name in ('{0}', '{1}')", KEY_DB_TYPE, KEY_SCHEMA_VER); retVal = ds.Query(sql, out reader); if (retVal.ResultCode == DBResult.Result.Success && reader.HasRows) { while (reader.Read()) { String key = DBUtil.GetString(reader[COL_KEY]); if (key == KEY_SCHEMA_VER) { version = DBUtil.GetSoftwareVersion(reader[COL_VALUE]); } else if (key == KEY_DB_TYPE) { databaseType = (InternalDatabaseType)DBUtil.GetInt32(reader[COL_VALUE]); } } _databaseVersionLookup.Add(indexKey, version); } } } finally { _databaseVersionLock.Unlock(); } return(retVal); }
// Called by the tcp client public virtual void OnConnectionClosed(TcpConnectedClient client) { TcpConnectedClient existingClient; try { _clientLock.Lock(); // Make sure it is the corresponding client if (_clientList.TryGetValue(client.RemoteAddress.Address, out existingClient) && existingClient.GetHashCode() == client.GetHashCode()) { Log.LogText(LogLevel.DEBUG, "OnConnectionClosed Found it"); _clientList.Remove(client.RemoteAddress.Address); if (_connectionDebugLogging) { Log.LogText(LogLevel.DEBUG, "{0} Client {1} Removed", Name, client); } } else { Log.LogText(LogLevel.DEBUG, "OnConnectionClosed Did not found it"); existingClient = null; } } finally { _clientLock.Unlock(); } // Notify Consumer Of Event if (existingClient != null && ConnectionClosed != null) { ConnectionClosed(client); } }
public virtual void Update(_KEY_TYPE key, _OBJECT_TYPE updated) { if (ObjectCaching.Enabled) { try { _lock.Lock(); if (!_cache.ContainsKey(key)) { _cache.Add(key, new CacheEntry <_OBJECT_TYPE>(updated)); } else { if (updated is ICopyable <_OBJECT_TYPE> ) { ((ICopyable <_OBJECT_TYPE>)_cache[key].CachedObject).CopyFrom(updated); _cache[key].EntryTime = DateTime.UtcNow; } else { _cache[key] = new CacheEntry <_OBJECT_TYPE>(updated); } } if (ObjectCaching.TrackYoungestEntry) { _youngestEntry = _cache[key]; } } finally { _lock.Unlock(); } } }
private static void Main() { try { MutexLock.Lock(); Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new InstallerForm()); } finally { MutexLock.Unlock(); } }
public void LogText(String format, params object[] args) { try { m_Lock.Lock(); String text = args == null || args.Length == 0 ? format : String.Format(format, args); m_TextWriter.WriteLine(text); m_TextWriter.Flush(); } catch (Exception) { } finally { m_Lock.Unlock(); } }
void RotateLogFile() { #if (!PocketPC) try { _fileLock.Lock(); String strDestFileName = ""; /** write a line out to signal rotation */ if (_fileWriter != null) { _fileWriter.WriteLine(String.Format("Rotating Log File {0}", DateTime.Now.ToString("HH:mm:ss.fff "))); _fileWriter.Flush(); } /** * Copy our current log file to a filename including the * date and time it was rotated */ if (File.Exists(_logToRotate.FileName)) { strDestFileName = String.Format("{0}-{1}.log", _logToRotate.FileName, DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")); File.Copy(_logToRotate.FileName, strDestFileName); _fileWriter.BaseStream.SetLength(0); } } catch (Exception e) { _fileWriter.WriteLine(String.Format("EXCEPTION - LOG ROTATION FAILED: {0}", e.Message)); } finally { _fileLock.Unlock(); } /** * we have to do this because of a bug in GetCreationTime where it returns * the old creation time of a newly deleted file */ #endif }
private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); BuildSplash(); Splash.Show(); //new Thread(() => { Splash.ShowDialog(); }).Start(); try { MutexLock.Lock(); } catch (MutexLockLockedException) { Console.WriteLine("Mutex property of other process, quitting"); Process[] processes = Process.GetProcessesByName("UpTool2"); if (processes.Length > 0) { WindowHelper.BringProcessToFront(Process.GetProcessesByName("UpTool2")[0]); } return; } #if !DEBUG try { #endif ExternalFunctionalityManager.Init(new UtLibFunctions()); SetSplash(1, "Initializing paths"); if (!Directory.Exists(PathTool.Dir)) { Directory.CreateDirectory(PathTool.Dir); } FixXml(); SetSplash(2, "Performing checks"); try { UpToolLib.UpdateCheck.Reload(); Online = true; } catch { Online = false; } if (Application.ExecutablePath != PathTool.GetRelative("Install", "UpTool2.dll")) { Splash.Invoke((Action)(() => MessageBox.Show(Splash, $"WARNING!{Environment.NewLine}Running from outside the install directory is not recommended!") )); } if (!Directory.Exists(PathTool.GetRelative("Apps"))) { Directory.CreateDirectory(PathTool.GetRelative("Apps")); } if (!Online) { SetSplash(7, "Opening"); } if (!Online || UpdateCheck()) { Application.Run(new MainForm()); } #if !DEBUG } catch (Exception e1) { try { Splash.Invoke((Action)Splash.Hide); } catch { Console.WriteLine("Failed to hide splash"); } MessageBox.Show(e1.ToString()); } finally { MutexLock.Unlock(); } #endif }
public Type GetByType(Type type, SoftwareVersion version) { Type returnType = null; // Type type = typeof(T); VersionLookup versionLookup; try { if (!_TypeLookup.TryGetValue(type, out versionLookup)) { _typeLock.Lock(); versionLookup = new VersionLookup(); _TypeLookup.Add(type, versionLookup); List <Type> types = new List <Type>(type.Assembly.GetTypes().Where(asmType => asmType.IsClass && !asmType.IsAbstract && (asmType.IsSubclassOf(type) || asmType == type))); // Find all descendants // TODO: Add functionality to add additional assemblies where datasources may be found, // outside of the assembly containing the base, which is where all searches are currently conducted foreach (Type subType in types) { DatabaseVersionAttribute[] attribs = (DatabaseVersionAttribute[])subType.GetCustomAttributes(typeof(DatabaseVersionAttribute), false); if (attribs.Length > 0) { foreach (DatabaseVersionAttribute attr in attribs) { foreach (SoftwareVersion attributeVersion in attr.Versions) { if (versionLookup.ContainsKey(attributeVersion)) { versionLookup[attributeVersion] = subType; } else { versionLookup.Add(attributeVersion, subType); } } } } } } } finally { _typeLock.Unlock(); } // At this point, all versioned types realted to the requested type are indexed by version number in the lookup for this type if (!versionLookup.TryGetValue(version, out returnType)) { // Couldn't find an exact match of the datasource requested. Look for the most recent one prior to this database version SoftwareVersion lastVersion = null; List <SoftwareVersion> keys = new List <SoftwareVersion>(versionLookup.Keys); keys.Sort(); keys.Reverse(); foreach (SoftwareVersion key in keys) { if (key > version) { continue; } lastVersion = key; break; } if (lastVersion != null) { returnType = versionLookup[lastVersion]; versionLookup.Add(version, returnType); // Warn if our datasource is not marked for the current version? } } return(returnType); }
public static T Create <T>(SqlDBCredentials credentials, bool checkVersion = false, bool checkDeclarations = false, SoftwareVersion version = null, Type defaultDSType = null, bool readOnly = false) { /** make a copy of these */ credentials = credentials.Clone(); InternalDatabaseType databaseType = InternalDatabaseType.Unknown; /** ensure version is valid */ if (version == null) { version = new SoftwareVersion(); } T retVal = default(T); try { _instanceLock.Lock(); SoftwareVersion initialVersion = version; _InstanceLookup.Get <T>(credentials, version); // No cached instance of the proper datasource for these credentials about. Try and find one. if (retVal == null) { if (checkVersion == false) { version = new SoftwareVersion("9.9"); databaseType = InternalDatabaseType.Unknown; } else { // Now we get the database version from the lookup or database if (version == SoftwareVersion.Empty && GetDatabaseVersion(credentials, out version, out databaseType).ResultCode != DBResult.Result.Success) { throw new DataSourceException("DataSource Factory unable to obtain version from Database: {0} (1)", credentials.Host); } } //1. Get specified version of T. Routine will Start at T and look at descendants, caching results. Type type = _TypeLookup.Get <T>(version); //1a. Throw exception if T has no version decorations if (type == null) { if (defaultDSType == null) { throw new DataSourceException("Unable to find version {0} of DataSource {1}", version, typeof(T)); } else { type = defaultDSType; } } bool saveDeclarationCheck = false; /** save global declaration check flag */ if (type.IsSubclassOf(typeof(DataSourceBase))) { saveDeclarationCheck = DataSourceBase.CheckDeclarations; DataSourceBase.CheckDeclarations = checkDeclarations; } /** Create instance with proper parameters */ retVal = (T)Activator.CreateInstance(type, credentials); _InstanceLookup.Set <T>(credentials, version, retVal); if (initialVersion != version) { _InstanceLookup.Set <T>(credentials, initialVersion, retVal); } /** restore global declaration check flag */ if (type.IsSubclassOf(typeof(DataSourceBase))) { DataSourceBase.CheckDeclarations = saveDeclarationCheck; } if (retVal is DataSourceBase) { ((DataSourceBase)(Object)retVal).ReadOnly = readOnly; ((DataSourceBase)(Object)retVal).Version = version; ((DataSourceBase)(Object)retVal).DatabaseType = databaseType; } } } catch (Exception e) { Log.SysLogText(LogLevel.ERROR, "DataSourceFactory Exception: {0}", e.Message); if (e.InnerException != null) { Log.SysLogText(LogLevel.ERROR, " Inner Exception: {0}", e.InnerException.Message); } /** rethrow */ throw e; } finally { _instanceLock.Unlock(); } return(retVal); }
public void AddLogLine(String strLine) { _logLineListLock.Lock(); _logLines.Add(strLine); _logLineListLock.Unlock(); }