/// <summary> /// Creates and initializes the RequiredPropertyController instance. /// </summary> /// /// <param name="parent"> /// Object to manage. /// </param> /// /// <param name="func"> /// Function indicating whether the property is required (optional). /// </param> public RequiredPropertyController(object parent, Func <PropertyInfo, bool> func = null) { if (parent == null) { ThrowException.ThrowArgumentNullException("parent"); } _parent = parent; _requiredProperties = new Dictionary <string, PropertyInfo>(); var props = _parent.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); if (func != null) { foreach (var prop in props) { if (func(prop)) { _requiredProperties.Add(prop.Name, prop); } } } else { foreach (var prop in props.Where(p => RequiredPropertyController.HasRequiredAttribute(p))) { _requiredProperties.Add(prop.Name, prop); } } }
/// <summary> /// Maps the target's properties using a Dictionary that contains {Name, Value} properties. /// </summary> /// /// <param name="target"> /// Target object. /// </param> /// /// <param name="properties"> /// Dictionary that contains {Name, Value} properties. /// </param> /// /// <param name="throwMappingException"> /// Value indicating whether exception is thrown when a property cannot be mapped. /// </param> public static void MapProperties(object target, IDictionary <string, object> properties, bool throwMappingException = true) { if (properties != null && properties.Count != 0) { Type targetType = target.GetType(); PropertyInfo[] props = targetType.GetProperties().Where(p => p.CanWrite).ToArray(); foreach (var property in properties) { PropertyInfo pi = props.FirstOrDefault(p => p.Name == property.Key); if (pi != null) { pi.SetValue(target, property.Value); continue; } if (throwMappingException) { ThrowException.Throw( "The '{0}' property (from '{1}.{2}' class) cannot be found or setted", property.Key, targetType.Namespace, targetType.Name); } } } }
/// <summary> /// Registers an instance in the container using a unique name. /// </summary> /// /// <typeparam name="T"> /// Type of the instance. Should be an interface. /// </typeparam> /// /// <param name="name"> /// Unique name to identicate the instance. /// </param> /// /// <param name="instance"> /// Instance to register. /// </param> /// /// <param name="throwExceptionIfAlreadyRegistered"> /// Indicates whether an exception is raised on name already used. /// </param> /// /// <returns> /// The registered instance. /// </returns> public T RegisterInstance <T>(string name, T instance, bool throwExceptionIfAlreadyRegistered = true) { if (string.IsNullOrEmpty(name)) { ThrowException.ThrowArgumentNullException("name"); } T registeredInstance; if (this.HasInstance <T>(name, out registeredInstance)) { if (throwExceptionIfAlreadyRegistered) { ThrowException.ThrowInvalidOperationException(string.Format( "The instance associated to the '{0}' name is already registered", name)); } return(registeredInstance); } else { _container.TryAdd(name, instance); } return(instance); }
public static bool IsValidityDateRangeValid <T>(this IObjectValidityDateRange source, IEnumerable <T> sequence, Func <T, DateTime?> beginDateSelector, Func <T, DateTime?> endDateSelector) { if (source == null) { ThrowException.ThrowArgumentNullException("source"); } if (!sequence.Any()) { return(false); } if (source.ValidityBeginDate == null && source.ValidityEndDate == null) { return(true); } DateTimeRange range = new DateTimeRange(source.ValidityBeginDate, source.ValidityEndDate); if (sequence.Any(i => new DateTimeRange(beginDateSelector(i), endDateSelector(i)).Overlaps(range))) { return(true); } return(false); }
/// <summary> /// Converts an object to the given type. /// </summary> /// /// <typeparam name="T"> /// Convertion type. /// </typeparam> /// /// <param name="value"> /// Object to convert. /// </param> /// /// <returns> /// Converted object. /// </returns> public static T To <T>(object value) { if (value == DBNull.Value || value == null) { return(default(T)); } var conversionType = typeof(T); if (conversionType == null) { ThrowException.ThrowArgumentNullException("conversionType"); } if (TypeHelper.IsNullable(conversionType)) { var nullableConverter = new NullableConverter(conversionType); conversionType = nullableConverter.UnderlyingType; } if (typeof(T).Equals(typeof(Guid))) { return((T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(value.ToString())); } return((T)Convert.ChangeType(value, conversionType)); }
/// <summary> /// Loads the loggerServiceConfiguration Xml section. /// </summary> /// <param name="sectionNode">The loggerServiceConfiguration root node.</param> internal void Load(XmlNode sectionNode) { if (sectionNode.Attributes["isEnabled"] == null) { ThrowException.ThrowConfigurationErrorsException( "Cannot find the 'isEnabled' attribute on loggerServiceConfiguration section"); } if (sectionNode.Attributes["logSource"] == null) { ThrowException.ThrowConfigurationErrorsException( "Cannot find the 'logSource' attribute on loggerServiceConfiguration section"); } string sIsEnabled = sectionNode.Attributes["isEnabled"].Value; if (string.IsNullOrEmpty(sIsEnabled)) { ThrowException.ThrowConfigurationErrorsException( "Cannot find the 'isEnabled' attribute value on loggerServiceConfiguration section"); } string sLogSource = sectionNode.Attributes["logSource"].Value; if (string.IsNullOrEmpty(sIsEnabled)) { ThrowException.ThrowConfigurationErrorsException( "Cannot find the 'logSource' attribute value on loggerServiceConfiguration section"); } this.IsEnabled = Convert.ToBoolean(sIsEnabled); this.LogSource = sLogSource; }
/// <summary> /// Deserialize a xml representation to an object using XmlSerializerType.Xml or XmlSerializerType.DataContract. /// </summary> /// /// <typeparam name="T"> /// Type of the object returned. /// </typeparam> /// /// <param name="serializerType"> /// Serializer to use. /// </param> /// /// <param name="content"> /// String representation to deserialize. /// </param> /// /// <returns> /// The object. /// </returns> public static T ToObject <T>(SerializerType serializerType, string content) { if (string.IsNullOrEmpty(content)) { ThrowException.ThrowArgumentNullException("content"); } if (serializerType == SerializerType.DataContract) { using (var stream = new MemoryStream()) { byte[] data = Encoding.UTF8.GetBytes(content); stream.Write(data, 0, data.Length); stream.Position = 0; var dcSerializer = new DataContractSerializer(typeof(T)); return((T)dcSerializer.ReadObject(stream)); } } else if (serializerType == SerializerType.Json) { return(_jsonSerializer.Deserialize <T>(content.Trim())); } else { var xmlSerializer = new XmlSerializer(typeof(T)); using (var reader = new StringReader(content)) { return((T)xmlSerializer.Deserialize(reader)); } } }
/// <summary> /// Default constructor. /// Uses <smtpServiceConfiguration> section from application configuration file. /// </summary> public SmtpService() { if (_config == null) { ThrowException.ThrowConfigurationErrorsException( "Cannot find the smtpServiceConfiguration section from the configuration file"); } }
public TreeNodeBase(TNode item) { if (item == null) { ThrowException.ThrowArgumentNullException("item"); } _item = item; }
/// <summary> /// Creates a new instance of PropertyEqualityComparer. /// </summary> /// /// <param name="propertyName"> /// The name of the property on type T to perform the comparison on. /// </param> public PropertyEqualityComparer(string propertyName) { _propertyInfo = typeof(T).GetProperty(propertyName, BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public); if (_propertyInfo == null) { ThrowException.ThrowArgumentException( string.Format("{0} is not a property of type {1}.", propertyName, typeof(T))); } }
public GenericPropertyDescriptor(string name, Func <TComponent, TProperty> getter) : base(typeof(TComponent), name, typeof(TProperty)) { if (getter == null) { ThrowException.ThrowArgumentNullException("getter"); } _getter = getter; }
/// <summary> /// Default constructor. Uses <loggerServiceConfiguration> section from application configuration file. /// </summary> public LoggerService() { if (_config == null) { ThrowException.ThrowConfigurationErrorsException("Cannot find the loggerServiceConfiguration section from the configuration file"); } this.LogSource = _config.LogSource; this.IsEnabled = _config.IsEnabled; }
/// <summary> /// Loads the queueExecutionTracerServiceConfiguration Xml section. /// </summary> /// /// <param name="sectionNode"> /// The queueExecutionTracerServiceConfiguration root node. /// </param> internal void Load(XmlNode sectionNode) { if (sectionNode.Attributes["isEnabled"] == null) { ThrowException.ThrowConfigurationErrorsException( "Cannot find the 'isEnabled' attribute on queueExecutionTracerServiceConfiguration section"); } if (sectionNode.Attributes["withDebugTrace"] == null) { ThrowException.ThrowConfigurationErrorsException( "Cannot find the 'withDebugTrace' attribute on queueExecutionTracerServiceConfiguration section"); } if (sectionNode.Attributes["outputPath"] == null) { ThrowException.ThrowConfigurationErrorsException( "Cannot find the 'outputPath' attribute on queueExecutionTracerServiceConfiguration section"); } string sIsEnabled = sectionNode.Attributes["isEnabled"].Value; if (string.IsNullOrEmpty(sIsEnabled)) { ThrowException.ThrowConfigurationErrorsException( "Cannot find the 'isEnabled' attribute value on queueExecutionTracerServiceConfiguration section"); } string sWithDebugTrace = sectionNode.Attributes["withDebugTrace"].Value; if (string.IsNullOrEmpty(sIsEnabled)) { ThrowException.ThrowConfigurationErrorsException( "Cannot find the 'withDebugTrace' attribute value on queueExecutionTracerServiceConfiguration section"); } string sOutputPath = sectionNode.Attributes["outputPath"].Value; if (string.IsNullOrEmpty(sOutputPath)) { ThrowException.ThrowConfigurationErrorsException( "Cannot find the 'outputPath' attribute value on queueExecutionTracerServiceConfiguration section"); } this.IsEnabled = Convert.ToBoolean(sIsEnabled); this.OutputPath = sOutputPath; #if DEBUG this.WithDebugTrace = Convert.ToBoolean(sWithDebugTrace); #else this.WithDebugTrace = false; #endif }
/// <summary> /// Adds an object instance in the multiton stored instances. /// </summary> /// /// <param name="key"> /// Instance key. /// </param> /// /// <param name="instance"> /// Object instance. /// </param> public void Add(string key, object instance) { lock (_locker) { if (_container.ContainsKey(key)) { ThrowException.ThrowArgumentException("There is already an instance registered using key = '{0}'", key); } _container.TryAdd(key, instance); } }
/// <summary> /// Gets the fullname of the queue (".\private$\nameQueue"). /// </summary> /// /// <param name="queueName"> /// Name of the queue (".\private$\nameQueue" or "nameQueue"). /// </param> /// /// <returns> /// The fullname of the queue. /// </returns> public static string GetQueueFullName(string queueName) { if (string.IsNullOrEmpty(queueName)) { ThrowException.ThrowArgumentException("queueName"); } if (!queueName.ToLowerInvariant().Contains(@"\private$\")) { queueName = string.Format(@".\private$\{0}", queueName); } return(queueName); }
public static void PropertyChangingRemoveHandler(this INotifyPropertyChanging source, EventHandler <PropertyChangingEventArgs> handler) { if (source == null) { ThrowException.ThrowArgumentNullException("source"); } if (handler == null) { ThrowException.ThrowArgumentNullException("handler"); } WeakEventManager <INotifyPropertyChanging, PropertyChangingEventArgs> .RemoveHandler(source, "PropertyChanging", handler); }
public static Stream GetEmbeddedStream(string assemblyFullName, string assemblyName, string file) { Assembly assembly = Assembly.Load(assemblyFullName); Stream stream = assembly.GetManifestResourceStream(string.Format("{0}.{1}", assemblyName, file)); if (stream == null) { ThrowException.Throw( @"Could not locate embedded resource '{0}' in assembly '{1}'", file, assemblyName); } return(stream); }
/// <summary> /// Creates and initializes the TrackedPropertyController instance. /// </summary> /// /// <param name="parent"> /// Object to manage. /// </param> public TrackedPropertyController(object parent) { if (parent == null) { ThrowException.ThrowArgumentNullException("parent"); } _trackedProperties = new Dictionary <string, PropertyInfo>(); foreach (var prop in parent.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => TrackedPropertyController.HasTrackedPropertyAttribute(p))) { _trackedProperties.Add(prop.Name, prop); } }
public static IEnumerable <T> GetValues <T>(string keyName, params char[] separators) { if (string.IsNullOrEmpty(keyName)) { ThrowException.ThrowArgumentNullException("keyName"); } if (separators.IsNullOrEmpty()) { ThrowException.ThrowArgumentNullException("separators"); } string values = ConfigurationManagerHelper.GetValue <string>(keyName); return(new List <T>(values.Split(separators, StringSplitOptions.RemoveEmptyEntries).Select(i => TypeHelper.To <T>(i)))); }
public static T GetValue <T>(string keyName) { if (string.IsNullOrEmpty(keyName)) { ThrowException.ThrowArgumentNullException("keyName"); } string value = ConfigurationManager.AppSettings[keyName]; if (value == null) { ThrowException.ThrowConfigurationErrorsException(string.Format("Cannot find the '{0}' configuration key from the AppSettings section", keyName)); } return(TypeHelper.To <T>(value)); }
/// <summary> /// Creates the new queue if not exists. /// </summary> /// /// <param name="queueName"> /// Name of the queue (".\private$\mailQueue" or "nameQueue"). /// </param> /// /// <param name="isTransactional"> /// Value indicating whether the queue is transactional. /// </param> /// /// <returns> /// The MessageQueue instance. /// </returns> public static MessageQueue CreateQueue(string queueName, bool isTransactional = false) { if (string.IsNullOrEmpty(queueName)) { ThrowException.ThrowArgumentException("queueName"); } queueName = GetQueueFullName(queueName); if (MessageQueue.Exists(queueName)) { return(new MessageQueue(queueName)); } return(MessageQueue.Create(queueName, isTransactional)); }
/// <summary> /// Parse a value to a enum. /// </summary> /// /// <typeparam name="T"> /// Type of enum. /// </typeparam> /// /// <param name="value"> /// Value to parse. /// </param> /// /// <param name="defaultValue"> /// Default value if the value is null. /// </param> /// /// <returns> /// The enum. /// </returns> public static T ParseByValue <T>(int?value, T defaultValue) where T : struct { if (value == null) { return(defaultValue); } if (!Enum.IsDefined(typeof(T), value)) { ThrowException.ThrowInvalidOperationException(string.Format( "The '{0}' enum does not define '{1}' value", typeof(T).ToString(), value)); } return((T)Enum.ToObject(typeof(T), value)); }
public static T GetValue <T>(string keyName, T defaultValue = default(T)) { if (string.IsNullOrEmpty(keyName)) { ThrowException.ThrowArgumentNullException("keyName"); } T value = defaultValue; string sValue = ConfigurationManager.AppSettings[keyName]; if (sValue != null) { value = TypeHelper.To <T>(sValue); } return(value); }
/// <summary> /// Executes an action with many retries. /// </summary> /// /// <typeparam name="T1"> /// Type of the first argument. /// </typeparam> /// /// <typeparam name="T2"> /// Type of the second argument. /// </typeparam> /// /// <typeparam name="T3"> /// Type of the third argument. /// </typeparam> /// /// <typeparam name="T4"> /// Type of the fourth argument. /// </typeparam> /// /// <param name="action"> /// Action to execute. /// </param> /// /// <param name="arg1"> /// First action argument. /// </param> /// /// <param name="arg2"> /// Second action argument. /// </param> /// /// <param name="arg3"> /// Third action argument. /// </param> /// /// <param name="arg4"> /// Fourth action argument. /// </param> /// /// <param name="options"> /// Execution options. /// </param> /// /// <returns> /// True if the action has been executed; otherwise, false. /// </returns> /// /// <exception cref="AggregateException"> /// AggregateException if the action is not complete. /// </exception> public static bool ExecuteWithRetry <T1, T2, T3, T4>(this Action <T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4, ExecuteWithRetryOptions options = null) { if (options == null) { options = new ExecuteWithRetryOptions(); } int counter = 0; IList <Exception> exceptions = new List <Exception>(); do { try { action(arg1, arg2, arg3, arg4); options.IsComplete = true; } catch (Exception x) { DebugTraceException(x, counter); exceptions.Add(x); } finally { counter++; } if (!options.IsComplete && counter < options.RetryCounter) { Thread.Sleep(options.RetryDelay); } }while (!options.IsComplete && counter < options.RetryCounter); if (!exceptions.IsNullOrEmpty()) { ThrowException.ThrowAggregateException(exceptions); } return(options.IsComplete); }
/// <summary> /// Transforms a flat collection to a hierarchy object. /// Elements must implements TreeNodeBase abstract class. /// </summary> /// /// <typeparam name="TNode"> /// Type of the items. /// </typeparam> /// /// <param name="flatCollection"> /// The collection that contains all the elements of a hierarchy. /// Elements must implements TreeNodeBase abstract class. /// </param> /// /// <param name="idSelector"> /// Func that returns the Id property of an item. /// </param> /// /// <param name="idParentSelector"> /// Func that returns the Parent Id property of an item. /// </param> /// /// <param name="orderBySelector"> /// Func that sorts items on same parent node. /// </param> /// /// <returns> /// The hierarchy. /// </returns> public static IEnumerable <ITreeNode <TNode> > Hierarchize <TNode, TOrderKey>( IEnumerable <ITreeNode <TNode> > flatCollection, Func <TNode, long> idSelector, Func <TNode, long?> idParentSelector, Func <TNode, TOrderKey> orderBySelector = null) where TNode : class { if (flatCollection.IsNullOrEmpty()) { return(flatCollection); } var orderByFunc = new Func <IEnumerable <ITreeNode <TNode> >, IEnumerable <ITreeNode <TNode> > >(collection => { return((orderBySelector != null) ? collection = collection.OrderBy(o => orderBySelector(o.Item)) : collection); }); var dirtyFlatCollection = flatCollection.DeepCopy(); // not to modify flatCollection input foreach (var item in dirtyFlatCollection) { long?idParent = idParentSelector(item.Item); if (idParent != null) { var parent = dirtyFlatCollection.FirstOrDefault(i => idSelector(i.Item) == idParent); if (parent == null) { ThrowException.Throw("Cannot hierarchize the flatcollection because it is not complete (missing parent item with Id = {0}", idParent); } item.Parent = parent; } item.Children = orderByFunc(dirtyFlatCollection.Where(i => i != item && idParentSelector(i.Item) != null && idParentSelector(i.Item) == idSelector(item.Item))); } return(orderByFunc(dirtyFlatCollection.Where(i => idParentSelector(i.Item) == null))); }
public static ExceptionInfo Create(Exception exception) { if (exception == null) { ThrowException.ThrowArgumentNullException("exception"); } var info = new ExceptionInfo { Exception = exception }; if (exception is FileNotFoundException) { info.Message = string.Format("{0} (file: {1})", exception.Message, ((FileNotFoundException)exception).FileName); } else { info.Message = exception.Message.Replace(Environment.NewLine, " "); } return(info); }
/// <summary> /// Unregisters an action. /// </summary> /// /// <typeparam name="T"> /// Type of the object. /// </typeparam> /// /// <param name="key"> /// Key of the messenger. /// </param> /// /// <param name="throwExceptionOnError"> /// Value indicating whether an exception is thrown when an unregistration error occurred. /// </param> public void Unregister <T>(string key, bool throwExceptionOnError = true) { var t = typeof(T); var messengerEntry = _actions.Where(kvp => kvp.Key.Type == t && kvp.Key.Key == key).FirstOrDefault(); if (messengerEntry.Key == null) { if (throwExceptionOnError) { ThrowException.Throw( "Cannot unregister (key = '{0}', Type = {1}) because it does not exist", key, t.FullName); } } object removedObj; _actions.TryRemove(messengerEntry.Key, out removedObj); removedObj = null; }
/// <summary> /// Serialize an object to a Xml representation using SerializerType.Xml (DOES NOT SUPPORT CIRCULAR REFERENCES) or SerializerType.DataContract (supports circular references). /// </summary> /// /// <param name="serializerType"> /// Serializer to use. /// </param> /// /// <param name="source"> /// Object to serialize. /// </param> /// /// <returns> /// The Xml representation. /// </returns> public static string ToXml(SerializerType serializerType, object source) { if (source == null) { ThrowException.ThrowArgumentNullException("source"); } if (serializerType != SerializerType.Xml && serializerType != SerializerType.DataContract) { ThrowException.ThrowArgumentException(string.Format("The '{0}' serializer is not supported in this context", serializerType)); } if (serializerType == SerializerType.DataContract) { var mStream = new MemoryStream(); // no using -> CA2202 Do not dispose objects multiple times Object 'mStream' can be disposed more than once in method 'SerializerHelper.ToXml(XmlSerializerType, object)'. using (var reader = new StreamReader(mStream)) { var dcSerializer = new DataContractSerializer(source.GetType()); dcSerializer.WriteObject(mStream, source); mStream.Position = 0; return(reader.ReadToEnd()); } } else { var xmlSerializer = new XmlSerializer(source.GetType()); using (var writer = new StringWriter()) { // NOTE: if you get "A circular reference was detected while serializing an object of type 'Entity'" // then use XmlSerializerType.DataContract instead. xmlSerializer.Serialize(writer, source); return(writer.ToString()); } } }
private static string GetAccessModifier(MethodInfo method) { if (method.IsPublic) { return("public"); } else if (method.IsPrivate) { return("private"); } else if (method.IsAssembly) { return("internal"); } else if (method.IsFamily) { return("protected"); } ThrowException.ThrowFormatException("Unable to define the accessor modifier!"); return(string.Empty); // for compilation only }
private static int VisibilityValue(MethodInfo method) { if (method.IsPublic) { return(1); } else if (method.IsFamily) { return(2); } else if (method.IsAssembly) { return(3); } else if (method.IsPrivate) { return(4); } ThrowException.ThrowFormatException("Unable to define the visibility!"); return(-1); // for compilation only }