public override object this[string name] { get { ChoGuard.ArgumentNotNullOrEmpty(name, "Name"); if (!(ConfigData is NameValueCollection)) { throw new ChoConfigurationException("ConfigObject is not of NameValueCollection type."); } return(((NameValueCollection)ConfigData)[name]); } }
public static bool TryGetProfileBackingStore(string name, string startActions, string stopActions, ref IChoProfileBackingStore profileBackingStore) { ChoGuard.ArgumentNotNullOrEmpty(name, "Name"); if (_profilerCache.ContainsKey(name)) { profileBackingStore = _profilerCache[name]; return(true); } lock (_padLock) { if (!_profilerCache.ContainsKey(name)) { try { profileBackingStore = ConstructProfiler(name); if (profileBackingStore == null) { if (name == ChoProfile.GLOBAL_PROFILE_NAME || name == ChoProfile.NULL_PROFILE_NAME || name == ChoProfile.DEFAULT_PROFILE_NAME) { } else { Trace.TraceInformation("Failed to find profile backingstore for '{0}' logger, using default one.", name); } profileBackingStore = _defaultProfileBackingStore.Value; } if (_profilerCache.ContainsKey(name)) { Trace.TraceError("Duplicate '{0}' logger found. {1}", name, Environment.NewLine); } else { _profilerCache.Add(name, profileBackingStore); } } catch (Exception ex) { Trace.TraceError("Failed to create profile backingstore for '{0}' logger, using default one. {2}{1}", name, ex.ToString(), Environment.NewLine); _profilerCache.Add(name, _defaultProfileBackingStore.Value); } } profileBackingStore = _profilerCache[name]; } return(true); }
public ChoTimerService(string name, Action <T> timerServiceCallback, T state, int period, bool autoStart) { ChoGuard.ArgumentNotNullOrEmpty(name, "Name"); _name = name; _timerServiceCallback = timerServiceCallback; _state = state; _period = period; _timerThread = new Thread(OnTimerCallback); _timerThread.IsBackground = true; if (autoStart) { Start(); } }
public static void AddMissingAssembly(string assemblyFileName) { ChoGuard.ArgumentNotNullOrEmpty(assemblyFileName, "Assembly File Name"); lock (_assemblyCache.SyncRoot) { if (_missingAssemblyCache.Contains(assemblyFileName)) { return; } _missingAssemblyCache.Add(assemblyFileName); //ChoMissingAssemblies.Me.AppendLine(assemblyFileName); } }
public override object this[string name] { get { ChoGuard.ArgumentNotNullOrEmpty(name, "Name"); foreach (string key in Collection.AllKeys) { if (String.Compare(key, name, IgnoreCase) == 0) { return(Collection[key]); } } return(null); } }
public void SetMemberErrorMsg(string memberName, string errMsg) { ChoGuard.ArgumentNotNullOrEmpty(memberName, "MemberName"); if (!ObjectMemberErrMsgs.ContainsKey(memberName)) { ObjectMemberErrMsgs.Add(memberName, errMsg); } else { ObjectMemberErrMsgs[memberName] = errMsg; } // if (ObjectErrMsg.IsNullOrWhiteSpace()) // ObjectErrMsg = "Found error in configuration object member '{0}'.".FormatString(memberName); }
private void btnDonate_Click(object sender, RoutedEventArgs e) { ChoGuard.ArgumentNotNullOrEmpty(PaypalAccountEmail, "PaypalAccountEmail"); string url = ""; url += "https://www.paypal.com/cgi-bin/webscr" + "?cmd=" + "_donations" + "&business=" + PaypalAccountEmail + "&lc=" + Country + "&item_name=" + Description + "¤cy_code=" + Currency + "&bn=" + "PP%2dDonationsBF"; System.Diagnostics.Process.Start(url); }
public static object GetConfigFromConfigFile(Type type, string configFileName, bool initialize) { ChoGuard.ArgumentNotNullOrEmpty(configFileName, "ConfigFileName"); XmlDocument document = new XmlDocument(); document.Load(configFileName); if (initialize) { return(GetConfig(type, document.DocumentElement)); } else { return(GetConfigOnly(type, document.DocumentElement)); } }
public static TextWriter Add(string logFileName, TextWriter writer) { ChoGuard.ArgumentNotNullOrEmpty(logFileName, "LogFileName"); ChoGuard.ArgumentNotNull(writer, "TextWriter"); lock (SyncRoot) { if (_writers.ContainsKey(logFileName)) { Remove(logFileName); } _writers.Add(logFileName, writer); return(writer); } }
/// <summary> /// Get relative path for a given file path /// </summary> /// <param name="baseDirectory">Base directory</param> /// <param name="filePath">A file path</param> /// <returns>A relative path location</returns> public static string GetRelativePath(string baseDirectory, string filePath) { ChoGuard.ArgumentNotNullOrEmpty(baseDirectory, "BaseDirectory"); ChoGuard.ArgumentNotNullOrEmpty(filePath, "FilePath"); if (!baseDirectory.EndsWith("\\")) { baseDirectory += "\\"; } System.Uri uri1 = new Uri(filePath); System.Uri uri2 = new Uri(baseDirectory); Uri relativeUri = uri2.MakeRelativeUri(uri1); return(relativeUri.ToString()); }
public ChoRegistryKey(string registryKey, bool createKeyIfNotFound = false, bool silent = false) { ChoGuard.ArgumentNotNullOrEmpty(registryKey, "RegistryKey"); _createKeyIfNotFound = createKeyIfNotFound; _registryKey = registryKey; _silent = silent; string[] nameParts = registryKey.Split('\\'); if (nameParts.Length < 2) { throw new ArgumentException("Invalid registry key."); } switch (nameParts[0].ToUpper()) { case "HKEY_CLASSES_ROOT": case "HKCR": _registryHive = Registry.ClassesRoot; break; case "HKEY_CURRENT_USER": case "HKCU": _registryHive = Registry.CurrentUser; break; case "HKEY_LOCAL_MACHINE": case "HKLM": _registryHive = Registry.LocalMachine; break; case "HKEY_USERS": _registryHive = Registry.Users; break; case "HKEY_CURRENT_CONFIG": _registryHive = Registry.CurrentConfig; break; default: throw new ArgumentException("The registry hive '" + nameParts[0] + "' is not supported", "value"); } _registrySubKeyName = String.Join("\\", nameParts, 1, nameParts.Length - 1); }
public ChoNetworkShare(string networkShareName, NetworkCredential credentials) { ChoGuard.ArgumentNotNullOrEmpty(networkShareName, "NetworkShareName"); ChoGuard.ArgumentNotNull(credentials, "NetworkCredentials"); _networkShareName = networkShareName; var netResource = new NetResource() { Scope = ResourceScope.Context, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplaytype.Share, RemoteName = _networkShareName }; var result = ChoMpr.WNetAddConnection2(netResource, credentials.Password, @"{1}\{0}".FormatString(credentials.UserName, credentials.Domain), ChoMpr.CONNECT_UPDATE_PROFILE); if (result != 0) { throw new ChoWin32Exception(result, "Error connecting to '{0}' remote share".FormatString(_networkShareName)); } }
public ChoXmlFileConfigurationManager(string configFilePath) { ChoGuard.ArgumentNotNullOrEmpty(configFilePath, "ConfigFilePath"); _configFilePath = configFilePath; try { if (File.Exists(_configFilePath)) { _xmlDocument = (new ChoXmlDocument(_configFilePath)).XmlDocument; } } catch (Exception ex) { Trace.TraceError(ex.ToString()); } }
/// <summary> /// <para>Initialize a new <see cref="ChoConfigurationChangeCompositeWatcher"/> class with the path to the configuration file and the name of the section</para> /// </summary> /// <param name="_configFilePath"> /// <para>The full path to the configuration file.</para> /// </param> /// <param name="_configurationSectionName"> /// <para>The name of the configuration section to watch.</para> /// </param> public ChoConfigurationChangeCompositeWatcher(string configurationSectionName, IChoConfigurationChangeWatcher[] configurationChangeWatchers) { ChoGuard.ArgumentNotNullOrEmpty(configurationChangeWatchers, "ConfigurationChangeWatchers"); ChoGuard.ArgumentNotNullOrEmpty(configurationSectionName, "ConfigurationSectionName"); foreach (IChoConfigurationChangeWatcher configurationChangeWatcher in configurationChangeWatchers) { if (configurationChangeWatcher == null) { continue; } _configurationChangeWatchers.Add(configurationChangeWatcher); } _configurationSectionName = configurationSectionName; _threadName = "{0} : {1}".FormatString(typeof(ChoConfigurationChangeCompositeWatcher).Name, _configurationSectionName); }
public static void Remove(string logFileName) { ChoGuard.ArgumentNotNullOrEmpty(logFileName, "LogFileName"); lock (SyncRoot) { if (!_writers.ContainsKey(logFileName)) { return; } TextWriter writer = _writers[logFileName]; if (writer != null) { writer.Flush(); writer.Close(); } _writers.Remove(logFileName); } }
public static void Register(string name, Action timerServiceCallback, long period) { ChoGuard.ArgumentNotNullOrEmpty(name, "Name"); ChoGuard.ArgumentNotNull(timerServiceCallback, "TimerServiceCallback"); if (period != Timeout.Infinite && period <= 0) { throw new ChoTimerServiceException("Period should be > 0"); } lock (_padLock) { if (_callbacks.ContainsKey(name)) { //TODO: log the duplicate entries return; } _callbacks.Add(name, new ChoGlobalTimerServiceData(name, timerServiceCallback, period)); } }
private void AddCounters(Type[] reflectedTypes, bool silent) { ChoGuard.ArgumentNotNullOrEmpty(reflectedTypes, "reflectedTypes"); string performanceCounterCategoryName = null; foreach (Type type in reflectedTypes) { if (type == null) { continue; } ChoPerformanceCounterCategoryAttribute performanceCounterCategoryAttribute = type.GetCustomAttribute <ChoPerformanceCounterCategoryAttribute>(true); if (performanceCounterCategoryAttribute == null && !silent) { throw new ApplicationException("Missing performance counter category attribute."); } if (_performanceCounterCategoryAttribute == null) { _performanceCounterCategoryAttribute = performanceCounterCategoryAttribute; } if (performanceCounterCategoryName.IsNullOrEmpty()) { performanceCounterCategoryName = performanceCounterCategoryAttribute.CategoryName; } else if (performanceCounterCategoryName != performanceCounterCategoryAttribute.CategoryName) { continue; } if (performanceCounterCategoryAttribute != null) { AddCountersFromType(type); } } }
public static void CreateXmlFileIfEmpty(string appConfigPath, string rootElementName) { ChoGuard.ArgumentNotNullOrEmpty(rootElementName, "RootElementName"); if (!File.Exists(appConfigPath)) { ChoDirectory.CreateDirectoryFromFilePath(appConfigPath); using (StreamWriter sw = File.CreateText(appConfigPath)) { } } bool hasRoot = false; using (XmlReader xmlReader = XmlReader.Create(appConfigPath)) { try { if (xmlReader.MoveToContent() == XmlNodeType.Element) { hasRoot = true; } } catch (Exception ex) { if (ex.Message != "Root element is missing.") { throw; } } } //string allText = File.ReadAllText(appConfigPath); if (!hasRoot) //allText.IsNullOrWhiteSpace()) { File.WriteAllText(appConfigPath, @"<?xml version=""1.0"" encoding=""utf-8"" ?>{0}<{1}/>".FormatString(Environment.NewLine, rootElementName)); } }
public void WriteData(T target) { ChoGuard.ArgumentNotNullOrEmpty(target, "Target"); ChoGuard.NotDisposed(this); //using (Mutex mutex = new Mutex(false, ChoMutexHelper.GetName(_name))) //{ // mutex.WaitOne(); using (MemoryMappedViewStream stream = mf.CreateViewStream()) { if (_msgFormatter == ChoMsgFormatter.Binary) { ChoObject.Serialize(stream, target); } else { ChoObject.XmlSerialize(stream, target); } } _event.Set(); //} }
public static void Save(XmlNode xmlNode, string xmlFilePath, XmlWriterSettings xws) { ChoGuard.ArgumentNotNull(xmlNode, "XmlDocument"); ChoGuard.ArgumentNotNullOrEmpty(xmlFilePath, "XmlFilePath"); if (xmlNode is XmlDocumentFragment) { xws.OmitXmlDeclaration = true; xws.ConformanceLevel = ConformanceLevel.Auto; xws.Indent = false; } try { //using (FileStream fs = File.Create(xmlFilePath)) //using (FileStream fs = new FileStream(xmlFilePath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)) //{ using (StreamWriter sw = new StreamWriter(xmlFilePath, false)) { // Create a XMLTextWriter that will send its output to a memory stream (file) using (XmlWriter xtw = XmlTextWriter.Create(sw, xws)) { // Set the formatting property of the XML Text Writer to indented // the text writer is where the indenting will be performed //if (indentOutput) // xtw.Formatting = Formatting.Indented; // write dom xml to the xmltextwriter xmlNode.WriteContentTo(xtw); // Flush the contents of the text writer // to the memory stream, which is simply a memory file xtw.Flush(); } } } catch (Exception ex) { ChoTrace.Error(ex); } }
public ChoXmlDocument(string filePathOrXml) { ChoGuard.ArgumentNotNullOrEmpty(filePathOrXml, "FilePath or Xml"); filePathOrXml = filePathOrXml.Trim(); if (filePathOrXml.StartsWith("<")) { _xml = filePathOrXml; } else { _filePath = filePathOrXml; } if (IsXmlFile) { //_includeXmlFileRegEx = new Regex(String.Format(@"^\s*\[INCLUDE\(""(?<{0}>[A-Za-z0-9:\\\._\s*]+)""\)\]\s*[{1}](?<{2}>.*)$|^\s*\[INCLUDE\(""(?<{0}>[A-Za-z0-9:\\\._\s*]+)""\)\]\s*$", INI_INCLUDE_FILE_FILEPATH_TOKEN, _commentChars, INI_INCLUDE_FILE_COMMENTS_TOKEN), // RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline); _queuedMsgService = new ChoQueuedMsgService <ChoStandardQueuedMsg>(new ChoStandardQueuedMsgObject().QuitServiceMsg, false, new ChoQueuedMsgService <ChoStandardQueuedMsg> .ChoQMessageHandler(QueueMessageHandler)); _timerService = new ChoTimerService <string>(String.Format("{0}_Timer", System.IO.Path.GetFileNameWithoutExtension(_filePath)), new ChoTimerService <string> .ChoTimerServiceCallback(OnTimerServiceCallback), null, 1000, 5000, false); } }
public ChoUDPMulticastClient(IPAddress multicastAddress, int port, ChoNetMessageType?messageType = null, Encoding encoding = null) { ChoGuard.ArgumentNotNullOrEmpty(multicastAddress, "MulticastAddress"); if (encoding != null) { _encoding = encoding; } _messageType = messageType; _multicastAddress = multicastAddress; _localEP = new IPEndPoint(IPAddress.Any, port); _remoteEP = new IPEndPoint(_multicastAddress, port); _serverSocket = new UdpClient(); _serverSocket.DontFragment = true; //_serverSocket.MulticastLoopback = false; _serverSocket.ExclusiveAddressUse = false; _serverSocket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _serverSocket.Client.Bind(_localEP); _serverSocket.JoinMulticastGroup(_multicastAddress); _recieveResult = _serverSocket.BeginReceive(ReceiveCallback, _localEP); _pingServerTask = Task.Factory.StartNew(() => { while (true) { if (_lastPingMsgArrived != DateTime.MinValue) { IsServerAvailable = (DateTime.Now.Subtract(_lastPingMsgArrived).TotalMilliseconds <= PingMsgInterval * 2); } Thread.Sleep(PingMsgInterval); //TODO: Parameterize } }); }
public ChoXPathAttribute(string xpath) { ChoGuard.ArgumentNotNullOrEmpty(xpath, "XPath"); XPath = xpath; }
public void ResetToMemberDefaultValue(MemberInfo memberInfo) { ChoGuard.ArgumentNotNullOrEmpty(memberInfo, "MemberInfo"); ChoType.SetMemberValue(this, memberInfo, memberInfo.GetConvertedDefaultValue()); }
public static IChoConfigStorage GetConfigStorage(string configStorageName) { ChoGuard.ArgumentNotNullOrEmpty(configStorageName, "Config Storage Name"); return(null); }
//public ChoUDPServer(IPEndPoint serverEndPoint, ChoUDPMessageType messageType = ChoUDPMessageType.Binary, Encoding encoding = null) //{ // ChoGuard.ArgumentNotNullOrEmpty(serverEndPoint, "EndPoint"); // _serverEndPoint = serverEndPoint; // _messageType = messageType; // if (encoding != null) // _encoding = encoding; //} #endregion Constructors #region Send Overloads public int Send(string value) { ChoGuard.ArgumentNotNullOrEmpty(value, "value"); return Send(ConvertToBytes(new ChoScalarObject(value))); }
public ChoFileProfileBackingStore(string filePath) { ChoGuard.ArgumentNotNullOrEmpty(filePath, "FilePath"); _filePath = ChoString.ExpandPropertiesEx(filePath); }
public ChoIniSectionAttribute1(string iniSectionName) { ChoGuard.ArgumentNotNullOrEmpty(iniSectionName, "IniSectionName"); _iniSectionName = iniSectionName; }
/// <summary> /// Initializes a new instance of the <see cref="ChoCommandLineArgAttribute" /> class /// with the specified argument type. /// </summary> /// <param name="argumentType">Specifies the checking to be done on the argument.</param> public ChoCommandLineArgAttribute(string commandLineSwitch) { ChoGuard.ArgumentNotNullOrEmpty(commandLineSwitch, "CommandLine Switch"); CommandLineSwitch = commandLineSwitch; }
internal static object GetSection(string sectionName) { ChoGuard.ArgumentNotNullOrEmpty(sectionName, "SectionName"); return(ApplicationConfiguration.GetSection(sectionName)); }