/// <summary>
 /// Load configuration from string. Used by automated tests.
 /// </summary>
 /// <param name="content">Configuration data to parse</param>
 /// <param name="logger">Logging object</param>
 /// <returns>An instance of <see cref="TFSAggregatorSettings"/> or null</returns>
 public static TFSAggregatorSettings LoadXml(string content, ILogEvents logger)
 {
     // conventional point in time reference
     DateTime staticTimestamp = new DateTime(0, DateTimeKind.Utc);
     var parser = new AggregatorSettingsXmlParser(logger);
     return parser.Parse(staticTimestamp, (xmlLoadOptions) => XDocument.Parse(content, xmlLoadOptions));
 }
        /// <summary>
        /// Parse the specified <see cref="XDocument"/> to build a <see cref="TFSAggregatorSettings"/> instance.
        /// </summary>
        /// <param name="lastWriteTime">Last teime the document has been changed.</param>
        /// <param name="load">A lambda returning the <see cref="XDocument"/> to parse.</param>
        /// <returns></returns>
        public static TFSAggregatorSettings Load(DateTime lastWriteTime, Func<LoadOptions, XDocument> load, ILogEvents logger)
        {
            var instance = new TFSAggregatorSettings();

            LoadOptions xmlLoadOptions = LoadOptions.PreserveWhitespace | LoadOptions.SetBaseUri | LoadOptions.SetLineInfo;
            XDocument doc = load(xmlLoadOptions);

            instance.Hash = ComputeHash(doc, lastWriteTime);

            if (!ValidateDocAgainstSchema(doc, logger))
            {
                // HACK we must handle this scenario with clean exit
                return null;
            }

            // XML Schema has done lot of checking and set defaults, no need to recheck later, just manage missing pieces
            ParseRuntimeSection(instance, doc);

            Dictionary<string, Rule> rules = ParseRulesSection(instance, doc);

            var ruleInUse = rules.Keys.ToDictionary(ruleName => ruleName, ruleName => false);

            List<Policy> policies = ParsePoliciesSection(doc, rules, ruleInUse);

            instance.Policies = policies;

            // checks
            foreach (var unusedRule in ruleInUse.Where(kv => kv.Value == false))
            {
                logger.UnreferencedRule(unusedRule.Key);
            }

            return instance;
        }
        public FilteredLogger(ILogEvents logger, IEnumerable <LogLevel> allowedLogLevels, ErrorBehaviourOptions individualLogEntryErrorBehaviour)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (allowedLogLevels == null)
            {
                throw new ArgumentNullException(nameof(allowedLogLevels));
            }
            if ((individualLogEntryErrorBehaviour != ErrorBehaviourOptions.Ignore) && (individualLogEntryErrorBehaviour != ErrorBehaviourOptions.ThrowException))
            {
                // Note: Explicitly check for all valid values rather than using Enum.IsDefined since IsDefined uses reflection and logging should be as cheap as possible
                // (so reflection is best avoided)
                throw new ArgumentOutOfRangeException(nameof(individualLogEntryErrorBehaviour));
            }

            IndividualLogEntryErrorBehaviour = individualLogEntryErrorBehaviour;

            _logger          = logger;
            AllowedLogLevels = allowedLogLevels.ToList().AsReadOnly();
            foreach (var allowedLogLevel in AllowedLogLevels)
            {
                if ((allowedLogLevel != LogLevel.Debug) && (allowedLogLevel != LogLevel.Info) && (allowedLogLevel != LogLevel.Warning) && (allowedLogLevel != LogLevel.Error))
                {
                    throw new ArgumentException("Invalid LogLevel value specified");
                }
            }
        }
Exemple #4
0
 public WorkItemRepository(Uri tfsCollectionUri, IdentityDescriptor toImpersonate, IRuntimeContext context)
 {
     this.logger        = context.Logger;
     this.context       = context;
     this.tfs           = new TfsTeamProjectCollection(tfsCollectionUri, toImpersonate);
     this.workItemStore = this.tfs.GetService <WorkItemStore>();
 }
Exemple #5
0
        public static TFSAggregatorSettings LoadXml(string content, ILogEvents logger)
        {
            // conventional point in time reference
            DateTime staticTime = new DateTime(0, DateTimeKind.Utc);

            return(LoadXml(content, staticTime, logger));
        }
Exemple #6
0
        public DotLessCssCssLoader(
            ITextFileLoader contentLoader,
            InsertedMarkerRetriever markerIdRetriever,
            string optionalTagNameToRemove,
            ErrorBehaviourOptions reportedErrorBehaviour,
            ILogEvents logger)
        {
            if (contentLoader == null)
            {
                throw new ArgumentNullException("contentLoader");
            }
            if (markerIdRetriever == null)
            {
                throw new ArgumentNullException("markerIdRetriever");
            }
            if (!Enum.IsDefined(typeof(ErrorBehaviourOptions), reportedErrorBehaviour))
            {
                throw new ArgumentOutOfRangeException("reportedErrorBehaviour");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            _contentLoader           = contentLoader;
            _markerIdRetriever       = markerIdRetriever;
            _optionalTagNameToRemove = optionalTagNameToRemove;
            _reportedErrorBehaviour  = reportedErrorBehaviour;
            _logger = logger;
        }
Exemple #7
0
 public ScriptLibrary(IRuntimeContext context)
 {
     this.connectionInfo = context.GetConnectionInfo();
     this.requestContext = context.RequestContext;
     this.logger         = context.Logger;
     this.mailer         = new Mailer(context.RequestContext.VssContext);
 }
Exemple #8
0
        public static TFSAggregatorSettings LoadFromFile(string settingsPath, ILogEvents logger)
        {
            DateTime lastWriteTime
                = System.IO.File.GetLastWriteTimeUtc(settingsPath);

            return(Load(lastWriteTime, (xmlLoadOptions) => XDocument.Load(settingsPath, xmlLoadOptions), logger));
        }
Exemple #9
0
 public WorkItemLinkCollectionWrapper(WorkItemLinkCollection workItemLinkCollection, IRuntimeContext context)
 {
     this.logger = context.Logger;
     this.workItemLinkCollection = workItemLinkCollection;
     this.store   = context.WorkItemRepository;
     this.context = context;
 }
        public DefaultNonCachedLessCssLoaderFactory(
            ITextFileLoader contentLoader,
            SourceMappingMarkerInjectionOptions sourceMappingMarkerInjection,
            ErrorBehaviourOptions errorBehaviour,
            ILogEvents logger)
        {
            if (contentLoader == null)
            {
                throw new ArgumentNullException("contentLoader");
            }
            if (!Enum.IsDefined(typeof(SourceMappingMarkerInjectionOptions), sourceMappingMarkerInjection))
            {
                throw new ArgumentOutOfRangeException("sourceMappingMarkerInjection");
            }
            if (!Enum.IsDefined(typeof(ErrorBehaviourOptions), errorBehaviour))
            {
                throw new ArgumentOutOfRangeException("lineNumberInjectionBehaviour");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            _contentLoader = contentLoader;
            _sourceMappingMarkerInjection = sourceMappingMarkerInjection;
            _errorBehaviour = errorBehaviour;
            _logger         = logger;
        }
 /// <summary>
 /// Load configuration from file. Main scenario.
 /// </summary>
 /// <param name="settingsPath">Path to policies file</param>
 /// <param name="logger">Logging object</param>
 /// <returns>An instance of <see cref="TFSAggregatorSettings"/> or null</returns>
 public static TFSAggregatorSettings LoadFromFile(string settingsPath, ILogEvents logger)
 {
     DateTime lastWriteTime
         = System.IO.File.GetLastWriteTimeUtc(settingsPath);
     var parser = new AggregatorSettingsXmlParser(logger);
     return parser.Parse(lastWriteTime, (xmlLoadOptions) => XDocument.Load(settingsPath, xmlLoadOptions));
 }
        public SameFolderImportFlatteningCssLoader(
            ITextFileLoader contentLoader,
            ContentLoaderCommentRemovalBehaviourOptions contentLoaderCommentRemovalBehaviour,
            ErrorBehaviourOptions circularReferenceImportBehaviour,
            ErrorBehaviourOptions unsupportedImportBehaviour,
            ILogEvents logger)
        {
            if (contentLoader == null)
            {
                throw new ArgumentNullException("contentLoader");
            }
            if (!Enum.IsDefined(typeof(ContentLoaderCommentRemovalBehaviourOptions), contentLoaderCommentRemovalBehaviour))
            {
                throw new ArgumentOutOfRangeException("contentLoaderCommentRemovalBehaviour");
            }
            if (!Enum.IsDefined(typeof(ErrorBehaviourOptions), circularReferenceImportBehaviour))
            {
                throw new ArgumentOutOfRangeException("circularReferenceImportBehaviour");
            }
            if (!Enum.IsDefined(typeof(ErrorBehaviourOptions), unsupportedImportBehaviour))
            {
                throw new ArgumentOutOfRangeException("unsupportedImportBehaviour");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            _contentLoader = contentLoader;
            _contentLoaderCommentRemovalBehaviour = contentLoaderCommentRemovalBehaviour;
            _circularReferenceImportBehaviour     = circularReferenceImportBehaviour;
            _unsupportedImportBehaviour           = unsupportedImportBehaviour;
            _logger = logger;
        }
Exemple #13
0
 public ErrorWithBackTrackLogger(ILogEvents logger) : this(
         logger,
         Defaults.MaximumNumberOfHistoricalMessagesToMaintain,
         Defaults.MaximumNumberOfHistoricalMessagesToIncludeWithAnErrorEntry,
         Defaults.HistoryLoggingBehaviourOptions,
         Defaults.IndividualLogEntryErrorBehaviour)
 {
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="EventProcessor"/> class.
        /// </summary>
        public EventProcessor(IWorkItemRepository workItemStore, IRuntimeContext runtime)
        {
            this.logger = runtime.Logger;
            this.store = workItemStore;
            this.settings = runtime.Settings;

            this.engine = runtime.GetEngine(workItemStore);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EventProcessor"/> class.
        /// </summary>
        public EventProcessor(IWorkItemRepository workItemStore, IRuntimeContext runtime)
        {
            this.logger   = runtime.Logger;
            this.store    = workItemStore;
            this.settings = runtime.Settings;

            this.engine = runtime.GetEngine(workItemStore);
        }
 /// <summary>
 /// Wrap logging request in a try..catch and swallow any exception - this is an extension method that guarantees the exception will be caught, regardless
 /// of the logger implementation
 /// </summary>
 public static void LogIgnoringAnyError(this ILogEvents logger, LogLevel logLevel, Func <string> contentGenerator, Exception exception)
 {
     try
     {
         logger.Log(logLevel, DateTime.Now, contentGenerator, exception);
     }
     catch { }
 }
 public DefaultNonCachedLessCssLoaderFactory(
     IRelativePathMapper pathMapper,
     SourceMappingMarkerInjectionOptions sourceMappingMarkerInjection,
     ErrorBehaviourOptions errorBehaviour,
     ILogEvents logger)
     : this(new SimpleTextFileContentLoader(pathMapper), sourceMappingMarkerInjection, errorBehaviour, logger)
 {
 }
 public ThrottlingLogger(ILogEvents logger) : this(
         logger,
         Defaults.MimimumFrequency,
         Defaults.MaximumNumberOfBufferedItems,
         Defaults.MessageEvaluationBehaviour,
         Defaults.IndividualLogEntryErrorBehaviour)
 {
 }
 internal static ScriptEngine MakeEngine(string scriptLanguage, IWorkItemRepository workItemRepository, ILogEvents logger, bool debug)
 {
     logger.BuildingScriptEngine(scriptLanguage);
     Type t = GetScriptEngineType(scriptLanguage);
     var ctor = t.GetConstructor(new Type[] { typeof(IWorkItemRepository), typeof(ILogEvents), typeof(bool) });
     ScriptEngine engine = ctor.Invoke(new object[] { workItemRepository, logger, debug }) as ScriptEngine;
     return engine;
 }
        /// <summary>
        /// Load configuration from file. Main scenario.
        /// </summary>
        /// <param name="settingsPath">Path to policies file</param>
        /// <param name="logger">Logging object</param>
        /// <returns>An instance of <see cref="TFSAggregatorSettings"/> or null</returns>
        public static TFSAggregatorSettings LoadFromFile(string settingsPath, ILogEvents logger)
        {
            DateTime lastWriteTime
                = System.IO.File.GetLastWriteTimeUtc(settingsPath);
            var parser = new AggregatorSettingsXmlParser(logger);

            return(parser.Parse(lastWriteTime, (xmlLoadOptions) => XDocument.Load(settingsPath, xmlLoadOptions)));
        }
        /// <summary>
        /// Load configuration from string. Used by automated tests.
        /// </summary>
        /// <param name="content">Configuration data to parse</param>
        /// <param name="logger">Logging object</param>
        /// <returns>An instance of <see cref="TFSAggregatorSettings"/> or null</returns>
        public static TFSAggregatorSettings LoadXml(string content, ILogEvents logger)
        {
            // conventional point in time reference
            DateTime staticTimestamp = new DateTime(0, DateTimeKind.Utc);
            var      parser          = new AggregatorSettingsXmlParser(logger);

            return(parser.Parse(staticTimestamp, (xmlLoadOptions) => XDocument.Parse(content, xmlLoadOptions)));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EventProcessor"/> class.
        /// </summary>
        public EventProcessor(IRuntimeContext runtime)
        {
            this.logger = runtime.Logger;
            this.settings = runtime.Settings;
            this.limiter = runtime.RateLimiter;

            this.store = runtime.GetWorkItemRepository();
            this.engine = runtime.GetEngine();
        }
Exemple #23
0
        internal static ScriptEngine MakeEngine(string scriptLanguage, ILogEvents logger, bool debug)
        {
            logger.BuildingScriptEngine(scriptLanguage);
            Type         t      = GetScriptEngineType(scriptLanguage);
            var          ctor   = t.GetConstructor(new Type[] { typeof(ILogEvents), typeof(bool) });
            ScriptEngine engine = ctor.Invoke(new object[] { logger, debug }) as ScriptEngine;

            return(engine);
        }
        public static void Log(this ILogEvents logger, LogLevel logLevel, DateTime logDate, int managedThreadId, Func <string> contentGenerator, Exception exception)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            logger.Log(new LogEventDetails(logLevel, logDate, managedThreadId, contentGenerator, exception));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EventProcessor"/> class.
        /// </summary>
        public EventProcessor(IRuntimeContext runtime)
        {
            this.logger   = runtime.Logger;
            this.settings = runtime.Settings;
            this.limiter  = runtime.RateLimiter;

            this.store  = runtime.WorkItemRepository;
            this.engine = runtime.GetEngine();
        }
        public static void TransitionToState(IWorkItem workItem, string state, string commentPrefix, ILogEvents logger)
        {
            // Set the sourceWorkItem's state so that it is clear that it has been moved.
            string originalState = (string)workItem.Fields["State"].Value;

            // Try to set the state of the source work item to the "Deleted/Moved" state (whatever is defined in the file).

            // We need an open work item to set the state
            workItem.TryOpen();

            // See if we can go directly to the planned state.
            workItem.Fields["State"].Value = state;

            if (workItem.Fields["State"].Status != FieldStatus.Valid)
            {
                // Revert back to the original value and start searching for a way to our "MovedState"
                workItem.Fields["State"].Value = workItem.Fields["State"].OriginalValue;

                // If we can't then try to go from the current state to another state.  Saving each time till we get to where we are going.
                foreach (string curState in FindNextState(workItem.Type, (string)workItem.Fields["State"].Value, state))
                {
                    string comment;
                    if (curState == state)
                    {
                        comment = string.Format(
                            "{0}{1}  State changed to {2}",
                            commentPrefix,
                            Environment.NewLine,
                            state);
                    }
                    else
                    {
                        comment = string.Format(
                            "{0}{1}  State changed to {2} as part of move toward a state of {3}",
                            commentPrefix,
                            Environment.NewLine,
                            curState,
                            state);
                    }

                    bool success = ChangeWorkItemState(workItem, originalState, curState, comment, logger);

                    // If we could not do the incremental state change then we are done.  We will have to go back to the original...
                    if (!success)
                    {
                        break;
                    }
                }
            }
            else
            {
                // Just save it off if we can.
                string comment = commentPrefix + "\n   State changed to " + state;
                ChangeWorkItemState(workItem, originalState, state, comment, logger);
            }
        }
        public WorkItemRepository(IRuntimeContext context)
        {
            this.logger  = context.Logger;
            this.context = context;
            var ci = context.GetConnectionInfo();

            this.logger.Connecting(ci);
            this.tfs           = new TfsTeamProjectCollection(ci.ProjectCollectionUri, ci.Impersonate);
            this.workItemStore = this.tfs.GetService <WorkItemStore>();
        }
 public MailPicker(ILogEvents logger, string hostname, int port, bool useSsl, string username, string password, string tempFolder)
 {
     this.logger     = logger;
     this.hostname   = hostname;
     this.port       = port;
     this.useSsl     = useSsl;
     this.username   = username;
     this.password   = password;
     this.tempFolder = tempFolder;
 }
Exemple #29
0
 public AsyncLogger(ILogEvents logger)
     : base(
         logger,
         TimeSpan.FromMilliseconds(500), // Minimum off-loading frequency
         5,                              // Maximum buffer size
         ThrottlingLogger.Defaults.MessageEvaluationBehaviour,
         ThrottlingLogger.Defaults.IndividualLogEntryErrorBehaviour
         )
 {
 }
Exemple #30
0
        public WorkItemRepository(IRuntimeContext context)
        {
            this.logger  = context.Logger;
            this.context = context;
            var ci = context.GetConnectionInfo();

            this.logger.Connecting(ci);
            this.tfs = ci.Token.GetCollection(ci.ProjectCollectionUri);
            this.tfs.Authenticate();
            this.workItemStore = this.tfs.GetService <WorkItemStore>();
        }
        /// <summary>
        /// Wrap logging request in a try..catch and swallow any exception - this is an extension method that guarantees the exception will be caught, regardless
        /// of the logger implementation
        /// </summary>
        public static void LogIgnoringAnyError(this ILogEvents logger, LogLevel logLevel, string content, Exception exception = null)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            try
            {
                logger.Log(new LogEventDetails(logLevel, DateTime.Now, Thread.CurrentThread.ManagedThreadId, content, exception));
            }
            catch { }
        }
Exemple #32
0
            public DotLessCssPassThroughLogger(ILogEvents logger, ErrorBehaviourOptions reportedErrorBehaviour)
            {
                if (logger == null)
                {
                    throw new ArgumentNullException("logger");
                }
                if (!Enum.IsDefined(typeof(ErrorBehaviourOptions), reportedErrorBehaviour))
                {
                    throw new ArgumentOutOfRangeException("reportedErrorBehaviour");
                }

                _logger = logger;
                _reportedErrorBehaviour = reportedErrorBehaviour;
            }
Exemple #33
0
        private static bool ValidateDocAgainstSchema(XDocument doc, ILogEvents logger)
        {
            XmlSchemaSet schemas      = new XmlSchemaSet();
            var          thisAssembly = Assembly.GetAssembly(typeof(TFSAggregatorSettings));
            var          stream       = thisAssembly.GetManifestResourceStream("Aggregator.Core.Configuration.AggregatorConfiguration.xsd");

            schemas.Add(string.Empty, XmlReader.Create(stream));
            bool valid = true;

            doc.Validate(schemas, (o, e) =>
            {
                logger.InvalidConfiguration(e.Severity, e.Message, e.Exception.LineNumber, e.Exception.LinePosition);
                valid = false;
            }, true);
            return(valid);
        }
        public ThrottlingLogger(
            ILogEvents logger,
            TimeSpan mimimumFrequency,
            int maximumNumberOfBufferedItems,
            MessageEvaluationBehaviourOptions messageEvaluationBehaviour,
            ErrorBehaviourOptions individualLogEntryErrorBehaviour)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (mimimumFrequency.Ticks <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(mimimumFrequency), "must be a positive duration");
            }
            if (maximumNumberOfBufferedItems <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(maximumNumberOfBufferedItems), "must be a positive value");
            }
            if ((messageEvaluationBehaviour != MessageEvaluationBehaviourOptions.EvaluateWhenLogged) && (messageEvaluationBehaviour != MessageEvaluationBehaviourOptions.EvaluateWhenQueued))
            {
                // Note: Explicitly check for all valid values rather than using Enum.IsDefined since IsDefined uses reflection and logging should be as cheap as possible
                // (so reflection is best avoided)
                throw new ArgumentOutOfRangeException(nameof(messageEvaluationBehaviour));
            }
            if ((individualLogEntryErrorBehaviour != ErrorBehaviourOptions.Ignore) && (individualLogEntryErrorBehaviour != ErrorBehaviourOptions.ThrowException))
            {
                // Note: Explicitly check for all valid values rather than using Enum.IsDefined since IsDefined uses reflection and logging should be as cheap as possible
                // (so reflection is best avoided)
                throw new ArgumentOutOfRangeException(nameof(individualLogEntryErrorBehaviour));
            }

            MaximumNumberOfBufferedItems     = maximumNumberOfBufferedItems;
            MinimumFrequency                 = mimimumFrequency;
            MessageEvaluationBehaviour       = messageEvaluationBehaviour;
            IndividualLogEntryErrorBehaviour = individualLogEntryErrorBehaviour;

            _logger   = logger;
            _messages = new ConcurrentQueue <LogEventDetails>();
            _timer    = new PauseableTimer(
                mimimumFrequency,
                FlushQueueIfNotAlreadyDoingSo
                );
            _lastFlushedAt            = null;
            _flushInProgressIndicator = 0;
        }
        /// <summary>
        /// Return a proper context
        /// </summary>
        /// <returns></returns>
        public static RuntimeContext GetContext(
            Func <string> settingsPathGetter,
            IRequestContext requestContext,
            ILogEvents logger,
            Func <IRuntimeContext, IWorkItemRepository> repoBuilder,
            Func <IRuntimeContext, IScriptLibrary> scriptLibraryBuilder)
        {
            string settingsPath = settingsPathGetter();
            string cacheKey     = CacheKey + settingsPath;
            var    runtime      = (RuntimeContext)Cache.Get(cacheKey);

            if (runtime == null)
            {
                logger.HelloWorld();

                logger.LoadingConfiguration(settingsPath);

                var settings = TFSAggregatorSettings.LoadFromFile(settingsPath, logger);
                runtime = MakeRuntimeContext(settingsPath, settings, requestContext, logger, repoBuilder, scriptLibraryBuilder);

                if (!runtime.HasErrors)
                {
                    var itemPolicy = new CacheItemPolicy();
                    itemPolicy.Priority = CacheItemPriority.NotRemovable;
                    itemPolicy.ChangeMonitors.Add(new HostFileChangeMonitor(new List <string>()
                    {
                        settingsPath
                    }));

                    Cache.Set(cacheKey, runtime, itemPolicy);
                }

                logger.ConfigurationLoaded(settingsPath);
            }
            else
            {
                logger.UsingCachedConfiguration(settingsPath);
            }

            runtime = runtime.Clone() as RuntimeContext;

            // as it changes at each invocation, must be set again here
            runtime.RequestContext     = requestContext;
            runtime.workItemRepository = null;
            return(runtime);
        }
Exemple #36
0
        public static RuntimeContext MakeRuntimeContext(
            string settingsPath,
            TFSAggregatorSettings settings,
            IRequestContext requestContext,
            ILogEvents logger,
            Func <Uri, Microsoft.TeamFoundation.Framework.Client.IdentityDescriptor, IRuntimeContext, IWorkItemRepository> repoBuilder)
        {
            var runtime = new RuntimeContext();

            runtime.Logger         = logger;
            runtime.RequestContext = requestContext;
            runtime.SettingsPath   = settingsPath;
            runtime.Settings       = settings;
            runtime.RateLimiter    = new RateLimiter(runtime);
            logger.MinimumLogLevel = runtime.Settings?.LogLevel ?? LogLevel.Normal;
            runtime.repoBuilder    = repoBuilder;

            runtime.HasErrors = settings == null;
            return(runtime);
        }
        /// <summary>
        /// Wrap logging request in a try..catch and swallow any exception - this is an extension method that guarantees the exception will be caught, regardless
        /// of the logger implementation.
        /// </summary>
        public static void LogIgnoringAnyError(this ILogEvents logger, Exception error)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            // If there's no error then there's nothing to log, but this method is not supposed to throw an error when operating against a logger
            // implementation (which is why the ArgumentNullException above is acceptable) so if error is null then do nothing
            if (error == null)
            {
                return;
            }

            try
            {
                logger.Log(new LogEventDetails(LogLevel.Error, DateTime.Now, Thread.CurrentThread.ManagedThreadId, "", error));
            }
            catch { }
        }
        public static RuntimeContext MakeRuntimeContext(
            string settingsPath,
            TFSAggregatorSettings settings,
            IRequestContext requestContext,
            ILogEvents logger,
            Func<Uri, Microsoft.TeamFoundation.Framework.Client.IdentityDescriptor, ILogEvents, IWorkItemRepository> repoBuilder)
        {
            var runtime = new RuntimeContext();

            runtime.Logger = logger;
            runtime.RequestContext = requestContext;
            runtime.SettingsPath = settingsPath;
            runtime.Settings = settings;
            runtime.RateLimiter = new RateLimiter(runtime);
            logger.MinimumLogLevel = runtime.Settings?.LogLevel ?? LogLevel.Normal;
            runtime.repoBuilder = repoBuilder;

            runtime.HasErrors = settings == null;
            return runtime;
        }
        /// <summary>
        /// Return a proper context
        /// </summary>
        /// <returns></returns>
        public static RuntimeContext GetContext(
            Func<string> settingsPathGetter,
            IRequestContext requestContext,
            ILogEvents logger,
            Func<Uri, Microsoft.TeamFoundation.Framework.Client.IdentityDescriptor, ILogEvents, IWorkItemRepository> repoBuilder)
        {
            string settingsPath = settingsPathGetter();
            string cacheKey = CacheKey + settingsPath;
            var runtime = (RuntimeContext)Cache.Get(cacheKey);
            if (runtime == null)
            {
                logger.HelloWorld();

                logger.LoadingConfiguration(settingsPath);

                var settings = TFSAggregatorSettings.LoadFromFile(settingsPath, logger);
                runtime = MakeRuntimeContext(settingsPath, settings, requestContext, logger, repoBuilder);

                if (!runtime.HasErrors)
                {
                    var itemPolicy = new CacheItemPolicy();
                    itemPolicy.Priority = CacheItemPriority.NotRemovable;
                    itemPolicy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string>() { settingsPath }));

                    Cache.Set(cacheKey, runtime, itemPolicy);
                }

                logger.ConfigurationLoaded(settingsPath);
            }
            else
            {
                logger.UsingCachedConfiguration(settingsPath);

                // as it changes at each invocation, must be set again here
                runtime.RequestContext = requestContext;
            }

            return runtime.Clone() as RuntimeContext;
        }
 public ScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug)
 {
     this.Logger = logger;
     this.Store = store;
     this.Debug = debug;
 }
 public WorkItemRepository(string tfsCollectionUrl, IdentityDescriptor toImpersonate, ILogEvents logger)
 {
     this.logger = logger;
     this.tfsCollectionUrl = tfsCollectionUrl;
     this.toImpersonate = toImpersonate;
 }
 public WorkItemLinkCollectionWrapper(WorkItemLinkCollection workItemLinkCollection, IWorkItemRepository store, ILogEvents logger)
 {
     this.logger = logger;
     this.workItemLinkCollection = workItemLinkCollection;
     this.store = store;
 }
 private static bool ValidateDocAgainstSchema(XDocument doc, ILogEvents logger)
 {
     XmlSchemaSet schemas = new XmlSchemaSet();
     var thisAssembly = Assembly.GetAssembly(typeof(TFSAggregatorSettings));
     var stream = thisAssembly.GetManifestResourceStream("Aggregator.Core.Configuration.AggregatorConfiguration.xsd");
     schemas.Add(string.Empty, XmlReader.Create(stream));
     bool valid = true;
     doc.Validate(schemas, (o, e) =>
     {
         logger.InvalidConfiguration(e.Severity, e.Message, e.Exception.LineNumber, e.Exception.LinePosition);
         valid = false;
     }, true);
     return valid;
 }
        public static RuntimeContext MakeRuntimeContext(string settingsPath, TFSAggregatorSettings settings, IRequestContext requestContext, ILogEvents logger)
        {
            var runtime = new RuntimeContext();

            runtime.Logger = logger;
            runtime.RequestContext = requestContext;
            runtime.SettingsPath = settingsPath;
            runtime.Settings = settings;
            logger.MinimumLogLevel = runtime.Settings.LogLevel;

            runtime.HasErrors = false;
            return runtime;
        }
 public PsScriptEngine(ILogEvents logger, bool debug)
     : base(logger, debug)
 {
 }
 public AggregatorSettingsXmlParser(ILogEvents logger)
 {
     this.logger = logger;
 }
 public WorkItemLinkWrapper(WorkItemLink link, IWorkItemRepository store, ILogEvents logger)
 {
     this.logger = logger;
     this.link = link;
     this.store = store;
 }
 public WorkItemWrapper(WorkItem workItem, IWorkItemRepository store, ILogEvents logger)
     : base(store, logger)
 {
     this.workItem = workItem;
 }
 public ScriptEngine(ILogEvents logger, bool debug)
 {
     this.Logger = logger;
     this.Debug = debug;
 }
 public static TFSAggregatorSettings LoadXml(string content, DateTime timestamp, ILogEvents logger)
 {
     return Load(timestamp, (xmlLoadOptions) => XDocument.Parse(content, xmlLoadOptions), logger);
 }
 public RuleLogger(ILogEvents logger)
 {
     this.logger = logger;
 }
 public static TFSAggregatorSettings LoadXml(string content, ILogEvents logger)
 {
     // conventional point in time reference
     DateTime staticTime = new DateTime(0, DateTimeKind.Utc);
     return LoadXml(content, staticTime, logger);
 }
        /// <summary>
        /// Return a proper context
        /// </summary>
        /// <returns></returns>
        public static RuntimeContext GetContext(Func<string> settingsPathGetter, IRequestContext requestContext, ILogEvents logger)
        {
            var runtime = (RuntimeContext)Cache.Get(CacheKey);
            if (runtime == null)
            {
                string settingsPath = settingsPathGetter();
                var settings = TFSAggregatorSettings.LoadFromFile(settingsPath, logger);
                runtime = MakeRuntimeContext(settingsPath, settings, requestContext, logger);

                var itemPolicy = new CacheItemPolicy();
                itemPolicy.Priority = CacheItemPriority.NotRemovable;
                itemPolicy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string>() { settingsPath }));

                Cache.Set(CacheKey, runtime, itemPolicy);
            }
            else
            {
                runtime.RequestContext = requestContext;
            }

            return runtime.Clone() as RuntimeContext;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="WorkItemImplementationBase"/> class.
 /// </summary>
 public WorkItemImplementationBase(IWorkItemRepository store, ILogEvents logger)
 {
     this.Store = store;
     this.Logger = logger;
 }
 public static TFSAggregatorSettings LoadConfigFromResourceFile(string fileName, ILogEvents logger)
 {
     var configXml = LoadTextFromEmbeddedResource(fileName);
     return TFSAggregatorSettings.LoadXml(configXml, logger);
 }
 public WorkItemRepository(Uri tfsCollectionUri, IdentityDescriptor toImpersonate, ILogEvents logger)
 {
     this.logger = logger;
     this.tfs = new TfsTeamProjectCollection(tfsCollectionUri, toImpersonate);
     this.workItemStore = (WorkItemStore)this.tfs.GetService(typeof(WorkItemStore));
 }
        private static bool ChangeWorkItemState(IWorkItem workItem, string orginalSourceState, string destState, string comment, ILogEvents logger)
        {
            // Try to save the new state.  If that fails then we also go back to the original state.
            try
            {
                workItem.TryOpen();
                workItem.Fields["State"].Value = destState;
                workItem.History = comment;

                logger.AttemptingToMoveWorkItemToState(workItem, orginalSourceState, destState);
                if (workItem.IsValid())
                {
                    logger.WorkItemIsValidToSave(workItem);
                }
                else
                {
                    logger.WorkItemIsInvalidInState(workItem, destState);
                }

                workItem.Save();
                return true;
            }
            catch (Exception)
            {
                // Revert back to the original value.
                workItem.Fields["State"].Value = orginalSourceState;
                return false;
            }
        }
 public PsScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug)
     : base(store, logger, debug)
 {
 }