예제 #1
0
        /// <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));
        }
예제 #2
0
        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);
        }
예제 #3
0
        /// <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));
                }
            }
        }
예제 #4
0
        /// <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);
        }
예제 #5
0
        /// <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);
                }
            }
        }
예제 #6
0
        public TreeNodeBase(TNode item)
        {
            if (item == null)
            {
                ThrowException.ThrowArgumentNullException("item");
            }

            _item = item;
        }
예제 #7
0
            public GenericPropertyDescriptor(string name, Func <TComponent, TProperty> getter)
                : base(typeof(TComponent), name, typeof(TProperty))
            {
                if (getter == null)
                {
                    ThrowException.ThrowArgumentNullException("getter");
                }

                _getter = getter;
            }
        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);
        }
예제 #9
0
        /// <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);
            }
        }
예제 #10
0
        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))));
        }
예제 #11
0
        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));
        }
예제 #12
0
        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);
        }
예제 #13
0
        /// <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());
                }
            }
        }
예제 #14
0
        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);
        }
예제 #15
0
        /// <summary>
        /// Returns the mime type of the specified file.
        /// </summary>
        ///
        /// <param name="file">
        /// File path.
        /// </param>
        ///
        /// <returns>
        /// The mime type of the file path (the return value can be null).
        /// </returns>
        public static string GetMimeType(string file)
        {
            if (string.IsNullOrWhiteSpace(file))
            {
                ThrowException.ThrowArgumentNullException("file");
            }

            string filePath  = Path.GetFullPath(file);
            string extension = Path.GetExtension(filePath);

            if (extension == null || extension.Length == 0)
            {
                ThrowException.ThrowArgumentException(
                    "file",
                    string.Format("The '{0}' file must have an extension", filePath));
            }

            string registryPath = string.Format(@"HKEY_CLASSES_ROOT\{0}", extension);

            string mimeType = null;

            try
            {
                object value = Registry.GetValue(registryPath, "Content Type", null);

                if (value != null)
                {
                    mimeType = value.ToString();
                }
            }
            catch
            {
            }

            return(mimeType);
        }