Ejemplo n.º 1
0
 internal bool Override( IActivityMonitor monitor, IReadOnlyList<string> fullPath, ActionConfiguration a )
 {
     var e = fullPath.GetEnumerator();
     if( !e.MoveNext() ) throw new ArgumentException( "Must not be empty.", "fullPath" );
     if( e.Current != _action.Name ) throw new ArgumentException( "Must start with the action name.", "fullPath" );
     if( !e.MoveNext() )
     {
         _action = a;
         _isCloned = false;
         monitor.SendLine( LogLevel.Info, string.Format( "Action '{0}' has been overridden.", a.Name ), null );
         return true;
     }
     ActionCompositeConfiguration parent;
     int idx = FindInComposite( e, out parent );
     if( idx >= 0 )
     {
         Debug.Assert( _action is ActionCompositeConfiguration, "It is a composite." );
         Debug.Assert( _action.IsCloneable, "A composite is cloneable." );
         if( !_isCloned )
         {
             _action = ((ActionCompositeConfiguration)_action).CloneComposite( true );
             monitor.SendLine( LogLevel.Info, string.Format( "Action '{0}' has been cloned in order to override an inner action.", string.Join( "/", fullPath ) ), null );
             _isCloned = true;
             idx = FindInComposite( e, out parent );
         }
         Debug.Assert( parent.Children[idx].Name == fullPath.Last() );
         parent.Override( idx, a );
         monitor.SendLine( LogLevel.Info, string.Format( "Inner action '{0}' has been overridden.", string.Join( "/", fullPath ) ), null );
         return true;
     }
     monitor.SendLine( LogLevel.Error, string.Format( "Action '{0}' not found. Unable to override it.", string.Join( "/", fullPath ) ), null );
     return false;
 }
Ejemplo n.º 2
0
 /// <summary>
 /// Implements standard name checking for <see cref="ActionConfiguration.Name"/>. 
 /// The provided <paramref name="nameToCheck"/> must not be null or empty or contains only whitespaces nor '/' character.
 /// The '/' is reserved to structure the namespace.
 /// </summary>
 /// <param name="routeName">The name of the route that contains the action.</param>
 /// <param name="monitor">The monitor that will receive error descriptions.</param>
 /// <param name="nameToCheck">The name to check.</param>
 /// <returns>True if the name is valid. False otherwise.</returns>
 static public bool CheckActionNameValidity( string routeName, IActivityMonitor monitor, string nameToCheck )
 {
     if( String.IsNullOrWhiteSpace( nameToCheck ) ) monitor.SendLine( LogLevel.Error, string.Format( "Invalid name '{0}' in route '{1}'. Name must not be empty or contains only white space.", nameToCheck, routeName ), null );
     else if( nameToCheck.Contains( '/' ) ) monitor.SendLine( LogLevel.Error, string.Format( "Invalid name '{0}' in route '{1}'. Name must not contain '/'.", nameToCheck, routeName ), null );
     else return true;
     return false;
 }
Ejemplo n.º 3
0
        SubRouteConfiguration FillSubRoute(IActivityMonitor monitor, XElement xml, SubRouteConfiguration sub)
        {
            using (monitor.OpenGroup(LogLevel.Trace, string.Format("Reading subordinated channel '{0}'.", sub.Name), null))
            {
                var matchOptions = (string)xml.Attribute("MatchOptions");
                var filter       = (string)xml.Attribute("TopicFilter");
                var regex        = (string)xml.Attribute("TopicRegex");
                if ((filter == null) == (regex == null))
                {
                    throw new XmlException("Subordinated Channel must define one TopicFilter or TopicRegex attribute (and not both)." + xml.GetLineColumnString());
                }
                RegexOptions opt = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.ExplicitCapture;
                if (!String.IsNullOrWhiteSpace(matchOptions))
                {
                    if (!Enum.TryParse(matchOptions, true, out opt))
                    {
                        var expected = String.Join(", ", Enum.GetNames(typeof(RegexOptions)).Where(n => n != "None"));
                        throw new XmlException("MatchOptions value must be a subset of: " + expected + xml.GetLineColumnString());
                    }
                    monitor.SendLine(LogLevel.Trace, string.Format("MatchOptions for Channel '{0}' is: {1}.", sub.Name, opt), null);
                }
                else
                {
                    monitor.SendLine(LogLevel.Trace, string.Format("MatchOptions for Channel '{0}' defaults to: IgnoreCase, CultureInvariant, Multiline, ExplicitCapture.", sub.Name), null);
                }

                sub.RoutePredicate = filter != null?CreatePredicateFromWildcards(filter, opt) : CreatePredicateRegex(regex, opt);

                FillRoute(monitor, xml, sub);
                return(sub);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Computes the root path.
        /// </summary>
        /// <param name="m">A monitor (must not be null).</param>
        /// <returns>The final path to use (ends with '\'). Null if unable to compute the path.</returns>
        string ComputeBasePath(IActivityMonitor m)
        {
            string rootPath = null;

            if (String.IsNullOrWhiteSpace(_configPath))
            {
                m.SendLine(LogLevel.Error, "The configured path is empty.", null);
            }
            else if (FileUtil.IndexOfInvalidPathChars(_configPath) >= 0)
            {
                m.SendLine(LogLevel.Error, string.Format("The configured path '{0}' is invalid.", _configPath), null);
            }
            else
            {
                rootPath = _configPath;
                if (!Path.IsPathRooted(rootPath))
                {
                    string rootLogPath = SystemActivityMonitor.RootLogPath;
                    if (String.IsNullOrWhiteSpace(rootLogPath))
                    {
                        m.SendLine(LogLevel.Error, string.Format("The relative path '{0}' requires that {1} be specified (typically in the AppSettings).", _configPath, SystemActivityMonitor.AppSettingsKey), null);
                    }
                    else
                    {
                        rootPath = Path.Combine(rootLogPath, _configPath);
                    }
                }
            }
            return(rootPath != null?FileUtil.NormalizePathSeparator(rootPath, true) : null);
        }
Ejemplo n.º 5
0
 bool IRouteConfigurationContext.RemoveAction(string name)
 {
     if (!_actionsByName.Remove(name))
     {
         _monitor.SendLine(LogLevel.Warn, string.Format("Action declaration '{0}' to remove is not found.", name), null);
         return(false);
     }
     return(true);
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Loads this configuration from a <see cref="XElement"/>.
        /// </summary>
        /// <param name="e">The xml element: its name must be GrandOutputConfiguration.</param>
        /// <param name="monitor">Monitor that will be used.</param>
        /// <returns>True on success, false if the configuration can not be read.</returns>
        public bool Load(XElement e, IActivityMonitor monitor)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }
            if (monitor == null)
            {
                throw new ArgumentNullException("monitor");
            }
            try
            {
                if (e.Name != "GrandOutputConfiguration")
                {
                    throw new XmlException("Element name must be <GrandOutputConfiguration>." + e.GetLineColumnString());
                }
                // AppDomainDefaultFilter was the name before.
                LogFilter?globalDefaultFilter = e.GetAttributeLogFilter("GlobalDefaultFilter", false)
                                                ?? e.GetAttributeLogFilter("AppDomainDefaultFilter", false);

                SourceFilterApplyMode          applyMode;
                Dictionary <string, LogFilter> sourceFilter = ReadSourceOverrideFilter(e, out applyMode, monitor);
                if (sourceFilter == null)
                {
                    return(false);
                }

                RouteConfiguration routeConfig;
                using (monitor.OpenGroup(LogLevel.Trace, "Reading root Channel.", null))
                {
                    XElement channelElement = e.Element("Channel");
                    if (channelElement == null)
                    {
                        monitor.SendLine(LogLevel.Error, "Missing <Channel /> element." + e.GetLineColumnString(), null);
                        return(false);
                    }
                    routeConfig = FillRoute(monitor, channelElement, new RouteConfiguration());
                }
                // No error: set the new values.
                _routeConfig           = routeConfig;
                _sourceFilter          = sourceFilter;
                _sourceFilterApplyMode = applyMode;
                _globalDefaultFilter   = globalDefaultFilter;
                return(true);
            }
            catch (Exception ex)
            {
                monitor.SendLine(LogLevel.Error, null, ex);
            }
            return(false);
        }
Ejemplo n.º 7
0
 public RouteResolver(IActivityMonitor monitor, RouteConfiguration c)
 {
     try
     {
         using (monitor.OpenGroup(LogLevel.Info, c.Name.Length > 0 ? string.Format("Resolving root configuration (name is '{0}').", c.Name) : "Resolving root configuration.", null))
         {
             ProtoResolver protoResolver = new ProtoResolver(monitor, c);
             NamedSubRoutes = new Dictionary <string, SubRouteConfigurationResolved>();
             using (monitor.OpenGroup(LogLevel.Info, "Building final routes.", null))
             {
                 var preRoot = new PreRoute(monitor, protoResolver.Root);
                 Root = new RouteConfigurationResolved(protoResolver.Root.FullName, c.ConfigData, preRoot.FinalizeActions());
                 foreach (IProtoSubRoute sub in protoResolver.NamedSubRoutes.Values)
                 {
                     var preRoute = new PreRoute(monitor, sub);
                     NamedSubRoutes.Add(sub.FullName, new SubRouteConfigurationResolved(sub, preRoute.FinalizeActions()));
                 }
                 Root.SubRoutes = protoResolver.Root.SubRoutes.Select(p => NamedSubRoutes[p.FullName]).ToArray();
                 foreach (IProtoSubRoute sub in protoResolver.NamedSubRoutes.Values)
                 {
                     NamedSubRoutes[sub.FullName].SubRoutes = sub.SubRoutes.Select(p => NamedSubRoutes[p.FullName]).ToArray();
                 }
             }
         }
     }
     catch (Exception ex)
     {
         monitor.SendLine(LogLevel.Fatal, null, ex);
     }
 }
Ejemplo n.º 8
0
 /// <summary>
 /// Implements standard name checking for <see cref="ActionConfiguration.Name"/>.
 /// The provided <paramref name="nameToCheck"/> must not be null or empty or contains only whitespaces nor '/' character.
 /// The '/' is reserved to structure the namespace.
 /// </summary>
 /// <param name="routeName">The name of the route that contains the action.</param>
 /// <param name="monitor">The monitor that will receive error descriptions.</param>
 /// <param name="nameToCheck">The name to check.</param>
 /// <returns>True if the name is valid. False otherwise.</returns>
 static public bool CheckActionNameValidity(string routeName, IActivityMonitor monitor, string nameToCheck)
 {
     if (String.IsNullOrWhiteSpace(nameToCheck))
     {
         monitor.SendLine(LogLevel.Error, string.Format("Invalid name '{0}' in route '{1}'. Name must not be empty or contains only white space.", nameToCheck, routeName), null);
     }
     else if (nameToCheck.Contains('/'))
     {
         monitor.SendLine(LogLevel.Error, string.Format("Invalid name '{0}' in route '{1}'. Name must not contain '/'.", nameToCheck, routeName), null);
     }
     else
     {
         return(true);
     }
     return(false);
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Checks whether this <see cref="MonitorFileOutputBase"/> is valid: its base path is successfully created.
        /// Can be called multiple times.
        /// </summary>
        /// <param name="monitor">Required monitor.</param>
        public bool Initialize(IActivityMonitor monitor)
        {
            if (_basePath != null)
            {
                return(true);
            }
            if (monitor == null)
            {
                throw new ArgumentNullException("monitor");
            }
            string b = ComputeBasePath(monitor);

            if (b != null)
            {
                try
                {
                    Directory.CreateDirectory(b);
                    _basePath = b;
                    return(true);
                }
                catch (Exception ex)
                {
                    monitor.SendLine(LogLevel.Error, null, ex);
                }
            }
            return(false);
        }
        /// <summary>
        /// Checks that children are valid (action's name must be unique).
        /// </summary>
        /// <param name="routeName">Name of the route that references this action.</param>
        /// <param name="monitor">Monitor to report errors.</param>
        /// <returns>True if valid, false otherwise.</returns>
        public override bool CheckValidity(string routeName, IActivityMonitor monitor)
        {
            if (monitor == null)
            {
                throw new ArgumentNullException("monitor");
            }
            bool result = true;

            for (int i = 0; i < _children.Count; ++i)
            {
                var  child      = _children[i];
                bool validChild = true;
                for (int j = ++i; j < _children.Count; ++j)
                {
                    if (_children[j].Name == child.Name)
                    {
                        monitor.SendLine(LogLevel.Error, string.Format("Duplicate action name '{0}' in {1} '{2}', route '{3}'.", child.Name, TypeDisplayName, Name, routeName), null);
                        validChild = false;
                    }
                }
                validChild &= child.CheckValidity(routeName, monitor);
                // Remove child to continue the process but avoid cascading errors.
                if (!validChild)
                {
                    _children.RemoveAt(i--);
                }
                result &= validChild;
            }
            return(result);
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Computes the root path.
 /// </summary>
 /// <param name="m">A monitor (must not be null).</param>
 /// <returns>The final path to use (ends with '\'). Null if unable to compute the path.</returns>
 string ComputeBasePath( IActivityMonitor m )
 {
     string rootPath = null;
     if( String.IsNullOrWhiteSpace( _configPath ) ) m.SendLine( LogLevel.Error, "The configured path is empty.", null );
     else if( FileUtil.IndexOfInvalidPathChars( _configPath ) >= 0 ) m.SendLine( LogLevel.Error, string.Format( "The configured path '{0}' is invalid.", _configPath ), null );
     else
     {
         rootPath = _configPath;
         if( !Path.IsPathRooted( rootPath ) )
         {
             string rootLogPath = SystemActivityMonitor.RootLogPath;
             if( String.IsNullOrWhiteSpace( rootLogPath ) ) m.SendLine( LogLevel.Error, string.Format( "The relative path '{0}' requires that {1} be specified (typically in the AppSettings).", _configPath, SystemActivityMonitor.AppSettingsKey ), null );
             else rootPath = Path.Combine( rootLogPath, _configPath );
         }
     }
     return rootPath != null ? FileUtil.NormalizePathSeparator( rootPath, true ) : null;
 }
        internal bool CheckAndOptimize(IActivityMonitor monitor)
        {
            bool             formalError = false;
            HashSet <string> formalNames = new HashSet <string>();

            formalNames.Add(Name);
            for (int i = 0; i < _children.Count; ++i)
            {
                ActionConfiguration a = _children[i];
                if (!formalNames.Add(a.Name))
                {
                    if (a.Name == Name)
                    {
                        monitor.SendLine(LogLevel.Warn, string.Format("Action n°{2} '{0}' has the name of its parent {1}.", a.Name, TypeDisplayName, i + 1), null);
                    }
                    else
                    {
                        if (_isParallel)
                        {
                            monitor.SendLine(LogLevel.Warn, string.Format("Duplicate name '{0}' found in {1} (action n°{2}).", a.Name, _parDisplayName, i + 1), null);
                        }
                        else
                        {
                            monitor.SendLine(LogLevel.Error, string.Format("Action n°{2}'s name '{0}' alreay appears in {1}. In a {1}, names must be unique.", a.Name, _seqDisplayName), null);
                            formalError = true;
                        }
                    }
                }
                ActionCompositeConfiguration composite = a as ActionCompositeConfiguration;
                if (composite != null)
                {
                    formalError |= composite.CheckAndOptimize(monitor);
                    if (composite.IsParallel == _isParallel)
                    {
                        _children.RemoveAt(i);
                        _children.InsertRange(i, composite.Children);
                        i += composite.Children.Count;
                    }
                }
            }
            return(!formalError);
        }
Ejemplo n.º 13
0
            bool IProtoRouteConfigurationContext.AddRoute(SubRouteConfiguration route)
            {
                if (route == null)
                {
                    throw new ArgumentNullException();
                }
                var newSub = new Route(_resolver, this, route);

                if (!_resolver.RegisterSubRoute(newSub))
                {
                    Monitor.SendLine(LogLevel.Error, string.Format("Route named '{0}' is already declared.", newSub._fullName), null);
                    return(false);
                }
                using (Monitor.OpenGroup(LogLevel.Info, string.Format("Preprocessing route '{0}'.", newSub._fullName), null))
                {
                    newSub.ExecuteMetaConfigurations();
                    _subRoutes.Add(newSub);
                }
                return(true);
            }
Ejemplo n.º 14
0
        internal bool Override(IActivityMonitor monitor, IReadOnlyList <string> fullPath, ActionConfiguration a)
        {
            var e = fullPath.GetEnumerator();

            if (!e.MoveNext())
            {
                throw new ArgumentException("Must not be empty.", "fullPath");
            }
            if (e.Current != _action.Name)
            {
                throw new ArgumentException("Must start with the action name.", "fullPath");
            }
            if (!e.MoveNext())
            {
                _action   = a;
                _isCloned = false;
                monitor.SendLine(LogLevel.Info, string.Format("Action '{0}' has been overridden.", a.Name), null);
                return(true);
            }
            ActionCompositeConfiguration parent;
            int idx = FindInComposite(e, out parent);

            if (idx >= 0)
            {
                Debug.Assert(_action is ActionCompositeConfiguration, "It is a composite.");
                Debug.Assert(_action.IsCloneable, "A composite is cloneable.");
                if (!_isCloned)
                {
                    _action = ((ActionCompositeConfiguration)_action).CloneComposite(true);
                    monitor.SendLine(LogLevel.Info, string.Format("Action '{0}' has been cloned in order to override an inner action.", string.Join("/", fullPath)), null);
                    _isCloned = true;
                    idx       = FindInComposite(e, out parent);
                }
                Debug.Assert(parent.Children[idx].Name == fullPath.Last());
                parent.Override(idx, a);
                monitor.SendLine(LogLevel.Info, string.Format("Inner action '{0}' has been overridden.", string.Join("/", fullPath)), null);
                return(true);
            }
            monitor.SendLine(LogLevel.Error, string.Format("Action '{0}' not found. Unable to override it.", string.Join("/", fullPath)), null);
            return(false);
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Loads this configuration from a <see cref="XElement"/>.
 /// </summary>
 /// <param name="path">Path to the configuration xml file.</param>
 /// <param name="monitor">Monitor that will be used.</param>
 /// <returns>True on success, false if the configuration can not be read.</returns>
 public bool LoadFromFile( string path, IActivityMonitor monitor )
 {
     if( path == null ) throw new ArgumentNullException( "path" );
     if( monitor == null ) throw new ArgumentNullException( "monitor" );
     try
     {
         var doc = XDocument.Load( path, LoadOptions.SetBaseUri|LoadOptions.SetLineInfo );
         return Load( doc.Root, monitor );
     }
     catch( Exception ex )
     {
         monitor.SendLine( LogLevel.Error, null, ex );
         return false;
     }
 }
Ejemplo n.º 16
0
        static Dictionary <string, LogFilter> ReadSourceOverrideFilter(XElement e, out SourceFilterApplyMode apply, IActivityMonitor monitor)
        {
            apply = SourceFilterApplyMode.None;
            using (monitor.OpenGroup(LogLevel.Trace, "Reading SourceOverrideFilter elements.", null))
            {
                try
                {
                    var s = e.Element("SourceOverrideFilter");
                    if (s == null)
                    {
                        monitor.CloseGroup("No source filtering (ApplyMode is None).");
                        return(new Dictionary <string, LogFilter>());
                    }
                    apply = s.AttributeEnum("ApplyMode", SourceFilterApplyMode.Apply);

                    var stranger = e.Elements("SourceOverrideFilter").Elements().FirstOrDefault(f => f.Name != "Add" && f.Name != "Remove");
                    if (stranger != null)
                    {
                        throw new XmlException("SourceOverrideFilter element must contain only Add and Remove elements." + stranger.GetLineColumnString());
                    }
                    var result = e.Elements("SourceOverrideFilter")
                                 .Elements()
                                 .Select(f => new
                    {
                        File   = f.AttributeRequired("File"),
                        Filter = f.Name == "Add"
                                                                    ? f.GetRequiredAttributeLogFilter("Filter")
                                                                    : (LogFilter?)LogFilter.Undefined
                    })
                                 .Where(f => !String.IsNullOrWhiteSpace(f.File.Value))
                                 .ToDictionary(f => f.File.Value, f => f.Filter.Value);
                    monitor.CloseGroup(String.Format("{0} source files, ApplyMode is {1}.", result.Count, apply));
                    return(result);
                }
                catch (Exception ex)
                {
                    monitor.SendLine(LogLevel.Error, "Error while reading SourceOverrideFilter element.", ex);
                    return(null);
                }
            }
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Loads this configuration from a <see cref="XElement"/>.
 /// </summary>
 /// <param name="path">Path to the configuration xml file.</param>
 /// <param name="monitor">Monitor that will be used.</param>
 /// <returns>True on success, false if the configuration can not be read.</returns>
 public bool LoadFromFile(string path, IActivityMonitor monitor)
 {
     if (path == null)
     {
         throw new ArgumentNullException("path");
     }
     if (monitor == null)
     {
         throw new ArgumentNullException("monitor");
     }
     try
     {
         var doc = XDocument.Load(path, LoadOptions.SetBaseUri | LoadOptions.SetLineInfo);
         return(Load(doc.Root, monitor));
     }
     catch (Exception ex)
     {
         monitor.SendLine(LogLevel.Error, null, ex);
         return(false);
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Loads this configuration from a <see cref="XElement"/>.
        /// </summary>
        /// <param name="e">The xml element: its name must be GrandOutputConfiguration.</param>
        /// <param name="monitor">Monitor that will be used.</param>
        /// <returns>True on success, false if the configuration can not be read.</returns>
        public bool Load( XElement e, IActivityMonitor monitor )
        {
            if( e == null ) throw new ArgumentNullException( "e" );
            if( monitor == null ) throw new ArgumentNullException( "monitor" );
            try
            {
                if( e.Name != "GrandOutputConfiguration" ) throw new XmlException( "Element name must be <GrandOutputConfiguration>." + e.GetLineColumnString() );
                // AppDomainDefaultFilter was the name before.
                LogFilter? globalDefaultFilter = e.GetAttributeLogFilter( "GlobalDefaultFilter", false ) 
                                                    ?? e.GetAttributeLogFilter( "AppDomainDefaultFilter", false );

                SourceFilterApplyMode applyMode;
                Dictionary<string, LogFilter> sourceFilter = ReadSourceOverrideFilter( e, out applyMode, monitor );
                if( sourceFilter == null ) return false;

                RouteConfiguration routeConfig;
                using( monitor.OpenGroup( LogLevel.Trace, "Reading root Channel.", null ) )
                {
                    XElement channelElement = e.Element( "Channel" );
                    if( channelElement == null )
                    {
                        monitor.SendLine( LogLevel.Error, "Missing <Channel /> element." + e.GetLineColumnString(), null );
                        return false;
                    }
                    routeConfig = FillRoute( monitor, channelElement, new RouteConfiguration() );
                }
                // No error: set the new values.
                _routeConfig = routeConfig;
                _sourceFilter = sourceFilter;
                _sourceFilterApplyMode = applyMode;
                _globalDefaultFilter = globalDefaultFilter;
                return true;
            }
            catch( Exception ex )
            {
                monitor.SendLine( LogLevel.Error, null, ex );
            }
            return false;
        }
 /// <summary>
 /// Checks that children are valid (action's name must be unique).
 /// </summary>
 /// <param name="routeName">Name of the route that references this action.</param>
 /// <param name="monitor">Monitor to report errors.</param>
 /// <returns>True if valid, false otherwise.</returns>
 public override bool CheckValidity( string routeName, IActivityMonitor monitor )
 {
     if( monitor == null ) throw new ArgumentNullException( "monitor" );
     bool result = true;
     for( int i = 0; i < _children.Count; ++i )
     {
         var child = _children[i];
         bool validChild = true;
         for( int j = ++i; j < _children.Count; ++j )
         {
             if( _children[j].Name == child.Name )
             {
                 monitor.SendLine( LogLevel.Error, string.Format( "Duplicate action name '{0}' in {1} '{2}', route '{3}'.", child.Name, TypeDisplayName, Name, routeName ), null );
                 validChild = false;
             }
         }
         validChild &= child.CheckValidity( routeName, monitor );
         // Remove child to continue the process but avoid cascading errors.
         if( !validChild ) _children.RemoveAt( i-- );
         result &= validChild;
     }
     return result;
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Checks whether this <see cref="MonitorFileOutputBase"/> is valid: its base path is successfully created.
 /// Can be called multiple times.
 /// </summary>
 /// <param name="monitor">Required monitor.</param>
 public bool Initialize( IActivityMonitor monitor )
 {
     if( _basePath != null ) return true;
     if( monitor == null ) throw new ArgumentNullException( "monitor" );
     string b = ComputeBasePath( monitor );
     if( b != null )
     {
         try
         {
             Directory.CreateDirectory( b );
             _basePath = b;
             return true;
         }
         catch( Exception ex )
         {
             monitor.SendLine( LogLevel.Error, null, ex );
         }
     }
     return false;
 }
Ejemplo n.º 21
0
 /// <summary>
 /// Closes the file if it is opened.
 /// </summary>
 /// <param name="m">The monitor to use to track activity.</param>
 public override void Close( IActivityMonitor m )
 {
     m.SendLine( LogLevel.Info, string.Format( "Closing file for BinaryFile handler '{0}'.", Name ), null );
     _file.Close();
 }
Ejemplo n.º 22
0
        SubRouteConfiguration FillSubRoute( IActivityMonitor monitor, XElement xml, SubRouteConfiguration sub )
        {
            using( monitor.OpenGroup( LogLevel.Trace, string.Format( "Reading subordinated channel '{0}'.", sub.Name ), null ) )
            {
                var matchOptions = (string)xml.Attribute( "MatchOptions" );
                var filter = (string)xml.Attribute( "TopicFilter" );
                var regex = (string)xml.Attribute( "TopicRegex" );
                if( (filter == null) == (regex == null) )
                {
                    throw new XmlException( "Subordinated Channel must define one TopicFilter or TopicRegex attribute (and not both)." + xml.GetLineColumnString() );
                }
                RegexOptions opt = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.ExplicitCapture;
                if( !String.IsNullOrWhiteSpace( matchOptions ) )
                {
                    if( !Enum.TryParse( matchOptions, true, out opt ) )
                    {
                        var expected = String.Join( ", ", Enum.GetNames( typeof( RegexOptions ) ).Where( n => n != "None" ) );
                        throw new XmlException( "MatchOptions value must be a subset of: " + expected + xml.GetLineColumnString() );
                    }
                    monitor.SendLine( LogLevel.Trace, string.Format( "MatchOptions for Channel '{0}' is: {1}.", sub.Name, opt ), null );
                }
                else monitor.SendLine( LogLevel.Trace, string.Format( "MatchOptions for Channel '{0}' defaults to: IgnoreCase, CultureInvariant, Multiline, ExplicitCapture.", sub.Name ), null );

                sub.RoutePredicate = filter != null ? CreatePredicateFromWildcards( filter, opt ) : CreatePredicateRegex( regex, opt );

                FillRoute( monitor, xml, sub );
                return sub;
            }
        }
Ejemplo n.º 23
0
        static Dictionary<string, LogFilter> ReadSourceOverrideFilter( XElement e, out SourceFilterApplyMode apply, IActivityMonitor monitor )
        {
            apply = SourceFilterApplyMode.None;
            using( monitor.OpenGroup( LogLevel.Trace, "Reading SourceOverrideFilter elements.", null ) )
            {
                try
                {
                    var s = e.Element( "SourceOverrideFilter" );
                    if( s == null )
                    {
                        monitor.CloseGroup( "No source filtering (ApplyMode is None)." );
                        return new Dictionary<string, LogFilter>();
                    }
                    apply = s.AttributeEnum( "ApplyMode", SourceFilterApplyMode.Apply );

                    var stranger =  e.Elements( "SourceOverrideFilter" ).Elements().FirstOrDefault( f => f.Name != "Add" && f.Name != "Remove" );
                    if( stranger != null )
                    {
                        throw new XmlException( "SourceOverrideFilter element must contain only Add and Remove elements." + stranger.GetLineColumnString() );
                    }
                    var result = e.Elements( "SourceOverrideFilter" )
                                    .Elements()
                                    .Select( f => new
                                                    {
                                                        File = f.AttributeRequired( "File" ),
                                                        Filter = f.Name == "Add"
                                                                    ? f.GetRequiredAttributeLogFilter( "Filter" )
                                                                    : (LogFilter?)LogFilter.Undefined
                                                    } )
                                    .Where( f => !String.IsNullOrWhiteSpace( f.File.Value ) )
                                    .ToDictionary( f => f.File.Value, f => f.Filter.Value );
                    monitor.CloseGroup( String.Format( "{0} source files, ApplyMode is {1}.", result.Count, apply ) );
                    return result;
                }
                catch( Exception ex )
                {
                    monitor.SendLine( LogLevel.Error, "Error while reading SourceOverrideFilter element.", ex );
                    return null;
                }
            }
        }
Ejemplo n.º 24
0
 public RouteResolver( IActivityMonitor monitor, RouteConfiguration c )
 {
     try
     {
         using( monitor.OpenGroup( LogLevel.Info, c.Name.Length > 0 ? string.Format( "Resolving root configuration (name is '{0}').", c.Name ) : "Resolving root configuration.", null ) )
         {
             ProtoResolver protoResolver = new ProtoResolver( monitor, c );
             NamedSubRoutes = new Dictionary<string, SubRouteConfigurationResolved>();
             using( monitor.OpenGroup( LogLevel.Info, "Building final routes.", null ) )
             {
                 var preRoot = new PreRoute( monitor, protoResolver.Root );
                 Root = new RouteConfigurationResolved( protoResolver.Root.FullName, c.ConfigData, preRoot.FinalizeActions() );
                 foreach( IProtoSubRoute sub in protoResolver.NamedSubRoutes.Values )
                 {
                     var preRoute = new PreRoute( monitor, sub );
                     NamedSubRoutes.Add( sub.FullName, new SubRouteConfigurationResolved( sub, preRoute.FinalizeActions() ) );
                 }
                 Root.SubRoutes = protoResolver.Root.SubRoutes.Select( p => NamedSubRoutes[p.FullName] ).ToArray();
                 foreach( IProtoSubRoute sub in protoResolver.NamedSubRoutes.Values )
                 {
                     NamedSubRoutes[sub.FullName].SubRoutes = sub.SubRoutes.Select( p => NamedSubRoutes[p.FullName] ).ToArray();
                 }
             }
         }
     }
     catch( Exception ex )
     {
         monitor.SendLine( LogLevel.Fatal, null, ex );
     }
 }
 internal bool CheckAndOptimize( IActivityMonitor monitor )
 {
     bool formalError = false;
     HashSet<string> formalNames = new HashSet<string>();
     formalNames.Add( Name );
     for( int i = 0; i < _children.Count; ++i )
     {
         ActionConfiguration a = _children[i];
         if( !formalNames.Add( a.Name ) )
         {
             if( a.Name == Name )
             {
                 monitor.SendLine( LogLevel.Warn, string.Format( "Action n°{2} '{0}' has the name of its parent {1}.", a.Name, TypeDisplayName, i+1 ), null );
             }
             else
             {
                 if( _isParallel )
                 {
                     monitor.SendLine( LogLevel.Warn, string.Format( "Duplicate name '{0}' found in {1} (action n°{2}).", a.Name, _parDisplayName, i + 1 ), null );
                 }
                 else
                 {
                     monitor.SendLine( LogLevel.Error, string.Format( "Action n°{2}'s name '{0}' alreay appears in {1}. In a {1}, names must be unique.", a.Name, _seqDisplayName ), null );
                     formalError = true;
                 }
             }
         }
         ActionCompositeConfiguration composite = a as ActionCompositeConfiguration;
         if( composite != null )
         {
             formalError |= composite.CheckAndOptimize( monitor );
             if( composite.IsParallel == _isParallel )
             {
                 _children.RemoveAt( i );
                 _children.InsertRange( i, composite.Children );
                 i += composite.Children.Count;
             }
         }
     }
     return !formalError;
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Closes the file if it is opened.
 /// </summary>
 /// <param name="m">The monitor to use to track activity.</param>
 public override void Close(IActivityMonitor m)
 {
     m.SendLine(LogLevel.Info, string.Format("Closing file for TextFile handler '{0}'.", Name), null);
     _file.Close();
 }