예제 #1
0
        protected ObjectHandleSerializer(SerializationInfo info, StreamingContext context)
        {
            Type type = null;

            try
            {
                type     = (Type)info.GetValue("wrappedtype", typeof(Type));
                _wrapped = info.GetValue("wrappedvalue", type);
            }
            catch (Exception ex)
            {
                _wrapped = string.Empty;    // Type cannot be resolved in this AppDomain
                InternalLogger.Debug(ex, "ObjectHandleSerializer failed to deserialize object: {0}", type);
            }
        }
        private static bool TryCreatePropertyInfoDictionary(Type t, out Dictionary <string, PropertyInfo> result)
        {
            result = null;

            try
            {
                if (!t.IsDefined(typeof(NLogConfigurationItemAttribute), true))
                {
                    return(false);
                }

                result = new Dictionary <string, PropertyInfo>(StringComparer.OrdinalIgnoreCase);
                foreach (PropertyInfo propInfo in t.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    try
                    {
                        var parameterName = LookupPropertySymbolName(propInfo);
                        if (string.IsNullOrEmpty(parameterName))
                        {
                            continue;
                        }

                        result[parameterName] = propInfo;

                        if (propInfo.IsDefined(_defaultParameterAttribute.GetType(), false))
                        {
                            // define a property with empty name (Default property name)
                            result[string.Empty] = propInfo;
                        }
                    }
                    catch (Exception ex)
                    {
                        InternalLogger.Debug(ex, "Type reflection not possible for property {0} on type {1}. Maybe because of .NET Native.", propInfo.Name, t);
                    }
                }
            }
            catch (Exception ex)
            {
                InternalLogger.Debug(ex, "Type reflection not possible for type {0}. Maybe because of .NET Native.", t);
            }

            return(result != null);
        }
예제 #3
0
 private void StopWatching(FileSystemWatcher watcher)
 {
     try
     {
         InternalLogger.Debug("Stopping file watching for path '{0}' filter '{1}'", watcher.Path, watcher.Filter);
         watcher.EnableRaisingEvents = false;
         watcher.Created            -= OnFileChanged;
         watcher.Changed            -= OnFileChanged;
         watcher.Deleted            -= OnFileChanged;
         watcher.Renamed            -= OnFileChanged;
         watcher.Error -= OnWatcherError;
         watcher.Dispose();
     }
     catch (Exception ex)
     {
         InternalLogger.Error(ex, "Failed to stop file watcher for path '{0}' filter '{1}'", watcher.Path, watcher.Filter);
         if (ex.MustBeRethrown())
         {
             throw;
         }
     }
 }
예제 #4
0
        /// <summary>
        /// Copy to output stream and skip BOM if encoding is UTF8
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        /// <param name="encoding"></param>
        public static void CopyAndSkipBom(this Stream input, Stream output, Encoding encoding)
        {
            var bomSize   = EncodingHelpers.Utf8BOM.Length;
            var bomBuffer = new byte[bomSize];
            var posBefore = input.Position;
            int bytesRead = input.Read(bomBuffer, 0, bomSize);

            //TODO support other BOMs, like UTF16
            if (bytesRead == bomSize && bomBuffer.SequenceEqual(EncodingHelpers.Utf8BOM))
            {
                InternalLogger.Debug("input has UTF8 BOM");
                //already skipped due to read
            }
            else
            {
                InternalLogger.Debug("input hasn't a UTF8 BOM");
                //reset position
                input.Position = posBefore;
            }

            Copy(input, output);
        }
예제 #5
0
        public static bool SetPropertyFromString(object o, string name, string value0, NameValueCollection variables)
        {
            string value = ExpandVariables(value0, variables);

            InternalLogger.Debug("Setting '{0}.{1}' to '{2}'", o.GetType().Name, name, value);

            try
            {
                PropertyInfo propInfo = GetPropertyInfo(o, name);
                if (propInfo == null)
                {
                    throw new NotSupportedException("Parameter " + name + " not supported on " + o.GetType().Name);
                }

                if (propInfo.IsDefined(typeof(ArrayParameterAttribute), false))
                {
                    throw new NotSupportedException("Parameter " + name + " of " + o.GetType().Name + " is an array and cannot be assigned a scalar value.");
                }

                object newValue;

                if (propInfo.PropertyType.IsEnum)
                {
                    newValue = GetEnumValue(propInfo.PropertyType, value);
                }
                else
                {
                    newValue = Convert.ChangeType(value, propInfo.PropertyType, CultureInfo.InvariantCulture);
                }
                propInfo.SetValue(o, newValue, null);
                return(true);
            }
            catch (Exception ex)
            {
                InternalLogger.Error(ex.ToString());
                return(false);
            }
        }
예제 #6
0
        /// <summary>
        /// Render the event info as parse as <c>bool</c>
        /// </summary>
        /// <param name="layout">current layout</param>
        /// <param name="logEvent"></param>
        /// <param name="defaultValue">default value when the render </param>
        /// <param name="layoutName">layout name for log message to internal log when logging fails</param>
        /// <returns></returns>
        public static bool RenderBool(this Layout layout, LogEventInfo logEvent, bool defaultValue, string layoutName)
        {
            if (layout == null)
            {
                InternalLogger.Debug(layoutName + " is null so default value of " + defaultValue);
                return(defaultValue);
            }
            if (logEvent == null)
            {
                InternalLogger.Debug(layoutName + ": logEvent is null so default value of " + defaultValue);
                return(defaultValue);
            }

            var  rendered = layout.Render(logEvent);
            bool result;

            if (!bool.TryParse(rendered, out result))
            {
                InternalLogger.Warn(layoutName + ": parse of value '" + rendered + "' failed, return " + defaultValue);
                return(defaultValue);
            }
            return(result);
        }
예제 #7
0
        internal void Watch(string fileName)
        {
            var directory = Path.GetDirectoryName(fileName);

            if (!Directory.Exists(directory))
            {
                InternalLogger.Warn("Cannot watch {0} for changes as it doesn't exist", directory);
                return;
            }

            lock (this)
            {
                if (_watcherMap.ContainsKey(fileName))
                {
                    return;
                }

                var watcher = new FileSystemWatcher
                {
                    Path         = directory,
                    Filter       = Path.GetFileName(fileName),
                    NotifyFilter = NotifyFilters
                };

                watcher.Created            += OnFileChanged;
                watcher.Changed            += OnFileChanged;
                watcher.Deleted            += OnFileChanged;
                watcher.Renamed            += OnFileChanged;
                watcher.Error              += OnWatcherError;
                watcher.EnableRaisingEvents = true;

                InternalLogger.Debug("Watching path '{0}' filter '{1}' for changes.", watcher.Path, watcher.Filter);

                _watcherMap.Add(fileName, watcher);
            }
        }
예제 #8
0
 private void StopWatching(FileSystemWatcher watcher)
 {
     InternalLogger.Debug("Stopping file watching for path '{0}' filter '{1}'", watcher.Path, watcher.Filter);
     watcher.EnableRaisingEvents = false;
     watcher.Dispose();
 }
예제 #9
0
        public static string GetAssemblyFileLocation(Assembly assembly)
        {
            string fullName = string.Empty;

            try
            {
                if (assembly == null)
                {
                    return(string.Empty);
                }

                fullName = assembly.FullName;

#if NETSTANDARD
                if (string.IsNullOrEmpty(assembly.Location))
                {
                    // Assembly with no actual location should be skipped (Avoid PlatformNotSupportedException)
                    InternalLogger.Warn("Ignoring assembly location because location is empty: {0}", fullName);
                    return(string.Empty);
                }
#endif

                Uri assemblyCodeBase;
                if (!Uri.TryCreate(assembly.CodeBase, UriKind.RelativeOrAbsolute, out assemblyCodeBase))
                {
                    InternalLogger.Warn("Ignoring assembly location because code base is unknown: '{0}' ({1})", assembly.CodeBase, fullName);
                    return(string.Empty);
                }

                var assemblyLocation = Path.GetDirectoryName(assemblyCodeBase.LocalPath);
                if (string.IsNullOrEmpty(assemblyLocation))
                {
                    InternalLogger.Warn("Ignoring assembly location because it is not a valid directory: '{0}' ({1})", assemblyCodeBase.LocalPath, fullName);
                    return(string.Empty);
                }

                DirectoryInfo directoryInfo = new DirectoryInfo(assemblyLocation);
                if (!directoryInfo.Exists)
                {
                    InternalLogger.Warn("Ignoring assembly location because directory doesn't exists: '{0}' ({1})", assemblyLocation, fullName);
                    return(string.Empty);
                }

                InternalLogger.Debug("Found assembly location directory: '{0}' ({1})", directoryInfo.FullName, fullName);
                return(directoryInfo.FullName);
            }
            catch (System.PlatformNotSupportedException ex)
            {
                InternalLogger.Warn(ex, "Ignoring assembly location because assembly lookup is not supported: {0}", fullName);
                if (ex.MustBeRethrown())
                {
                    throw;
                }
                return(string.Empty);
            }
            catch (System.Security.SecurityException ex)
            {
                InternalLogger.Warn(ex, "Ignoring assembly location because assembly lookup is not allowed: {0}", fullName);
                if (ex.MustBeRethrown())
                {
                    throw;
                }
                return(string.Empty);
            }
            catch (UnauthorizedAccessException ex)
            {
                InternalLogger.Warn(ex, "Ignoring assembly location because assembly lookup is not allowed: {0}", fullName);
                if (ex.MustBeRethrown())
                {
                    throw;
                }
                return(string.Empty);
            }
        }