private static void ProcessCoverage(PublisherConfiguration config, CancellationToken cancellationToken)
        {
            // Currently the publisher only works for azure pipelines, so we simply instansiate for Azure Pipelines
            AzurePipelinesPublisher publisher = null;
            IExecutionContext       context   = null;

            try
            {
                publisher = new AzurePipelinesPublisher(/*enableTelemetry*/ !config.DisableTelemetry);
                context   = publisher.ExecutionContext;
                TraceLogger.Initialize(context.Logger);
            }
            catch (Exception ex)
            {
                Console.Error.Write(string.Format(Resources.CouldNotConnectToAzurePipelines, ex));
                return;
            }


            var processor = new CoverageProcessor(publisher, context.TelemetryDataCollector);

            // By default wait for 2 minutes for coverage to publish
            var publishTimedout = processor.ParseAndPublishCoverage(config, cancellationToken, new Parser(config, context.TelemetryDataCollector))
                                  .Wait(config.TimeoutInSeconds * 1000, cancellationToken);

            if (publishTimedout)
            {
                _cancellationTokenSource.Cancel();
            }
            else
            {
                publishSuccess = true;
            }
        }
Exemplo n.º 2
0
        public void WillSafelyLogException()
        {
            var tempDir  = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var mockTool = new Mock <ICoverageParserTool>();

            Directory.CreateDirectory(tempDir);

            mockTool.Setup(x => x.GenerateHTMLReport()).Throws(new Exception("error"));

            var config = new PublisherConfiguration()
            {
                CoverageFiles = new List <string>()
                {
                    "SampleCoverage/Clover.xml", "SampleCoverage/Cobertura.xml", "SampleCoverage/Jacoco.xml"
                },
                ReportDirectory = tempDir
            };

            var parser = new TestParser(config, _mockTelemetry.Object);

            parser.GenerateReport(mockTool.Object);

            //cleanup
            Directory.Delete(tempDir, true);

            Assert.IsTrue(_logger.Log.Contains($"error: {string.Format(Resources.HTMLReportError, "error")}".Trim()));
        }
Exemplo n.º 3
0
        protected virtual void UpdateExchangeConfig(PublisherConfiguration config, Type messageType)
        {
            var attribute = GetAttribute <ExchangeAttribute>(messageType);

            if (attribute == null)
            {
                return;
            }

            if (!string.IsNullOrWhiteSpace(attribute.Name))
            {
                config.ExchangeName = attribute.Name;
                if (config.Exchange != null)
                {
                    config.Exchange.Name = attribute.Name;
                }
            }
            if (config.Exchange == null)
            {
                return;
            }
            if (attribute.NullableDurability.HasValue)
            {
                config.Exchange.Durable = attribute.NullableDurability.Value;
            }
            if (attribute.NullableAutoDelete.HasValue)
            {
                config.Exchange.AutoDelete = attribute.NullableAutoDelete.Value;
            }
            if (attribute.Type != ExchangeType.Unknown)
            {
                config.Exchange.ExchangeType = attribute.Type.ToString().ToLowerInvariant();
            }
        }
Exemplo n.º 4
0
        public void RunBeforeAnyTests()
        {
            Log.Initializing += Log_Initializing;
            m_Configuration   = new AgentConfiguration();
            PublisherConfiguration publisher = m_Configuration.Publisher;

            publisher.ProductName     = "NUnit";
            publisher.ApplicationName = "Loupe.PerformanceCounters.Tests";

            //and now try to get the file version.  This is risky.
            var fileVersionAttributes = this.GetType().GetTypeInfo().Assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute));

            if (fileVersionAttributes != null)
            {
                AssemblyFileVersionAttribute leadAttribute = fileVersionAttributes.FirstOrDefault() as AssemblyFileVersionAttribute;

                if (leadAttribute != null)
                {
                    publisher.ApplicationVersion = new Version(leadAttribute.Version);
                }
            }

            publisher.ApplicationDescription = "NUnit tests of the Loupe Agent PerformanceCounter Library";

            m_Configuration.SessionFile.EnableFilePruning = false;

            Monitor.Subscribe(new PerformanceMonitor(new PerformanceConfiguration()));

            //force us to initialize logging
            Log.StartSession(m_Configuration);
            Trace.TraceInformation("Starting testing at {0} on computer {1}", DateTimeOffset.UtcNow, Log.SessionSummary.HostName);
        }
Exemplo n.º 5
0
        void Log_Initializing(object sender, LogInitializingEventArgs e)
        {
            if (m_HaveCanceled == false)
            {
                //we haven't done our first cancel test.
                e.Cancel       = true;
                m_HaveCanceled = true;
            }
            else
            {
                //set up our logging.
                PublisherConfiguration publisher = e.Configuration.Publisher;
                publisher.ProductName     = "NUnit";
                publisher.ApplicationName = "Gibraltar.Test";

                //and now try to get the file version.  This is risky.
                var fileVersionAttributes = this.GetType().GetTypeInfo().Assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute));

                if (fileVersionAttributes != null)
                {
                    AssemblyFileVersionAttribute leadAttribute = fileVersionAttributes.FirstOrDefault() as AssemblyFileVersionAttribute;

                    if (leadAttribute != null)
                    {
                        publisher.ApplicationVersion = new Version(leadAttribute.Version);
                    }
                }

                publisher.ApplicationDescription = "NUnit tests of the Gibraltar Core Library";

                e.Configuration.SessionFile.EnableFilePruning = false;
            }
        }
Exemplo n.º 6
0
        public void RunBeforeAnyTests()
        {
            //delete the existing local logs folder for us...
            try
            {
                var path = Path.Combine(Environment.GetEnvironmentVariable(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "ProgramData" : "Home"), @"Gibraltar\Local Logs\NUnit");
                Directory.Delete(path, true);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Unable to clean out local logs directory due to " + ex.GetType());
            }

            Log.Initializing += Log_Initializing;
            m_Configuration   = new AgentConfiguration();
            PublisherConfiguration publisher = m_Configuration.Publisher;

            publisher.ProductName     = "NUnit";
            publisher.ApplicationName = "Gibraltar.Agent.Test";

            //and now try to get the file version.  This is risky.
            var fileVersionAttributes = this.GetType().GetTypeInfo().Assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute));

            if (fileVersionAttributes != null)
            {
                AssemblyFileVersionAttribute leadAttribute = fileVersionAttributes.FirstOrDefault() as AssemblyFileVersionAttribute;

                if (leadAttribute != null)
                {
                    publisher.ApplicationVersion = new Version(leadAttribute.Version);
                }
            }

            publisher.ApplicationDescription = "NUnit tests of the Loupe Agent Library";

            m_Configuration.SessionFile.EnableFilePruning = false;

            //if we need email server information set that
#if CONFIGURE_EMAIL
            EmailConfiguration email = e.Configuration.Email;
            email.Server   = EmailServer;
            email.Port     = EmailServerPort;
            email.User     = EmailServerUser;
            email.Password = EmailServerPassword;
            email.UseSsl   = EmailUseSsl;

            PackagerConfiguration packager = e.Configuration.Packager;
            packager.DestinationEmailAddress = EmailToAddress;
            packager.FromEmailAddress        = EmailFromAddress;
#endif

            //force us to initialize logging
            Log.StartSession(m_Configuration);
            Trace.TraceInformation("Starting testing at {0} on computer {1}", DateTimeOffset.UtcNow, Log.SessionSummary.HostName);

            //we have to test this before we get into the application user tests and start manipulating the properties.
            Assert.That(Gibraltar.Monitor.Log.PrincipalResolver, Is.InstanceOf(typeof(DefaultPrincipalResolver)));
            Assert.That(Log.PrincipalResolver, Is.InstanceOf(typeof(DefaultPrincipalResolver)));
        }
Exemplo n.º 7
0
        public IPublisher <TMessage> CreatePublisher <TMessage>(Action <IPublisherBuilder <TMessage> > builder)
        {
            var configuration = new PublisherConfiguration <TMessage>();

            builder(configuration);

            return(CreatePublisher(configuration));
        }
Exemplo n.º 8
0
        protected virtual void UpdateRoutingConfig(PublisherConfiguration config, Type messageType)
        {
            var routingAttr = GetAttribute <RoutingAttribute>(messageType);

            if (routingAttr?.RoutingKey != null)
            {
                config.RoutingKey = routingAttr.RoutingKey;
            }
        }
        protected override ICoverageParserTool GetCoverageParserTool(PublisherConfiguration config)
        {
            if (_tool != null)
            {
                return(_tool);
            }

            return(base.GetCoverageParserTool(config));
        }
        public Parser(PublisherConfiguration config, ITelemetryDataCollector telemetry)
        {
            _configuration = config;
            _telemetry     = telemetry;

            using (new SimpleTimer("Parser", "Parsing", _telemetry))
            {
                _coverageParserTool = new Lazy <ICoverageParserTool>(() => this.GetCoverageParserTool(_configuration));
            }
        }
Exemplo n.º 11
0
 /// <summary>
 ///   Initializes a new <see cref="Publisher" \> instance.
 /// </summary>
 ///
 /// <param name="testConfiguration">The <see cref="TestConfiguration" /> used to configure the processor test scenario run.</param>
 /// <param name="publisherConfiguration">The <see cref="PublisherConfiguration" /> instance used to configure this instance of <see cref="Publisher" />.</param>
 /// <param name="metrics">The <see cref="Metrics" /> instance used to send metrics to Application Insights.</param>
 /// <param name="testName">The name of the test being run in order to organize metrics being collected.</param>
 ///
 public Publisher(PublisherConfiguration publisherConfiguration,
                  TestConfiguration testConfiguration,
                  Metrics metrics,
                  string testName)
 {
     _testConfiguration      = testConfiguration;
     _publisherconfiguration = publisherConfiguration;
     _metrics  = metrics;
     _testName = testName;
 }
        public BlobPublisherRepository(PublisherConfiguration configuration, ILoggerWrapper logger)
        {
            _configuration = configuration;
            _logger        = logger;

            var storageAccount = CloudStorageAccount.Parse(configuration.StorageConnectionString);
            var blobClient     = storageAccount.CreateCloudBlobClient();

            _container = blobClient.GetContainerReference(configuration.StorageContainerName);
        }
Exemplo n.º 13
0
        public ReportGeneratorTool(PublisherConfiguration configuration)
        {
            Configuration = configuration;

            if (Configuration.CoverageFiles == null)
            {
                TraceLogger.Debug("ReportGeneratorTool: No input coverage files to parse.");
                return;
            }

            _parserResult = ParseCoverageFiles(new List <string>(Configuration.CoverageFiles));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Create a publisher config.
        /// </summary>
        /// <param name="id">Id of the publisher</param>
        /// <param name="endpointId">Id of the end point</param>
        /// <param name="transformerId">Id of the transformer</param>
        /// <returns>A new config</returns>
        public static PublisherConfiguration CreatePublisherConfig(string id, string endpointId, string transformerId)
        {
            var config = new PublisherConfiguration()
            {
                Id            = id,
                Type          = TYPE_PUBLISHER,
                EndpointId    = endpointId,
                TransformerId = transformerId
            };

            return(config);
        }
Exemplo n.º 15
0
        public void WillGenerateReportWhenParsingFileCoverage()
        {
            var config = new PublisherConfiguration();
            var parser = new Mock <TestParser>(config, _mockTelemetry.Object);

            parser.Setup(x => x.GenerateReport(It.IsAny <ICoverageParserTool>()));

            parser.CallBase = true;
            parser.Object.GetFileCoverageInfos();

            parser.Verify(x => x.GenerateReport(It.IsAny <ICoverageParserTool>()));
        }
Exemplo n.º 16
0
        public PublisherConfiguration ProcessCommandLineArgs(string[] args)
        {
            var promise = new TaskCompletionSource <PublisherConfiguration>();
            PublisherConfiguration config = null;

            Parser.Default.ParseArguments <Options>(args)
            .WithParsed <Options>(opts =>
            {
                config = opts;
            });

            return(config);
        }
Exemplo n.º 17
0
 /// <summary>
 /// Create a publisher.
 /// </summary>
 /// <param name="type">Fully qualified name of the publisher class</param>
 /// <param name="id">Id of the publisher</param>
 /// <param name="config">The config parameters for connecting to the data end point</param>
 /// <returns>A new publisher</returns>
 public static IPublisher CreatePublisher(PublisherConfiguration config, EndPointConfiguration endpointConfig)
 {
     try
     {
         var publisher = ComponentRegistration.CreateInstance <IPublisher>(config.Type);
         publisher.Configure(config.Id, endpointConfig);
         return(publisher);
     }
     catch (Exception e)
     {
         _logger.Error(e);
     }
     return(null);
 }
Exemplo n.º 18
0
        public void CollectorFactory_CreatePublisher_Succeeds()
        {
            var endpointConfig = CreateEndPointConfig("10", "URI", "http://acme.com/ivanti/uno/discovery");
            var config         = new PublisherConfiguration()
            {
                Id            = "4",
                Type          = TYPE_PUBLISHER,
                EndpointId    = "1",
                TransformerId = "4"
            };
            var handler   = new MockTransformationHandler();
            var publisher = CollectorFactory.CreatePublisher(config, endpointConfig);

            publisher.Should().NotBeNull();
        }
Exemplo n.º 19
0
        public void ParsingException()
        {
            var mockTool = new Mock <ICoverageParserTool>();

            var config = new PublisherConfiguration()
            {
            };
            var parser = new Mock <TestParser>(config, _mockTelemetry.Object, mockTool.Object);

            mockTool.Setup(x => x.GetCoverageSummary()).Throws(new Exception("error"));
            mockTool.Setup(x => x.GetFileCoverageInfos()).Throws(new Exception("error"));

            parser.Setup(x => x.GenerateReport(It.IsAny <ICoverageParserTool>()));

            parser.CallBase = true;
            Assert.ThrowsException <ParsingException>(() => parser.Object.GetFileCoverageInfos());
            Assert.ThrowsException <ParsingException>(() => parser.Object.GetCoverageSummary());
        }
Exemplo n.º 20
0
    /// <summary>
    ///   Starts a background task for each test that needs to be run, and waits for all
    ///   test runs to completed before returning.
    /// </summary>
    ///
    /// <param name="roleList">The list of roles needed for the scenario being run.</param>
    /// <param name="testConfiguration">The <see cref="TestConfiguration" /> instance used to configure this test scenario run.</param>
    /// <param name="roleConfiguration">The <see cref="RoleConfiguration" /> instance used to configure the role being run.</param>
    /// <param name="metrics">The <see cref="Metrics" /> instance used by this role to send metrics to application insights.</param>
    /// <param name="testName">The name of the test scenario that is being run, for metrics purposes.</param>
    /// <param name="cancellationToken">The <see cref="CancellationToke"/> instance to signal the request to cancel the operation.</param>
    ///
    private static async Task RunRole(string role,
                                      TestConfiguration testConfiguration,
                                      RoleConfiguration roleConfiguration,
                                      Metrics metrics,
                                      string testName,
                                      CancellationToken cancellationToken)
    {
        if (role == RoleConfiguration.Publisher)
        {
            var publisherConfiguration = new PublisherConfiguration();
            var publisher = new Publisher(publisherConfiguration, testConfiguration, metrics, testName);
            await publisher.Start(cancellationToken);
        }

        if (role == RoleConfiguration.BufferedPublisher)
        {
            var publisherConfiguration = new BufferedPublisherConfiguration();
            var publisher = new BufferedPublisher(testConfiguration, publisherConfiguration, metrics, testName);
            await publisher.Start(cancellationToken);
        }

        if (role == RoleConfiguration.Processor)
        {
            var partitionCount = _getPartitionCount(testConfiguration.EventHubsConnectionString, testConfiguration.EventHub);
            await partitionCount.ConfigureAwait(false);

            var processConfiguration = new ProcessorConfiguration();
            var processor            = new Processor(testConfiguration, processConfiguration, metrics, partitionCount.Result, testName);
            await processor.Start(cancellationToken);
        }

        if (role == RoleConfiguration.BurstBufferedPublisher)
        {
            var publisherConfiguration = new BufferedPublisherConfiguration();
            publisherConfiguration.ProducerPublishingDelay = TimeSpan.FromMinutes(25);
            var publisher = new BufferedPublisher(testConfiguration, publisherConfiguration, metrics, testName);
            await publisher.Start(cancellationToken);
        }

        //return Task.CompletedTask;
        await Task.Delay(TimeSpan.FromSeconds(1));
    }
Exemplo n.º 21
0
        public void WillGenerateHTMLReportWithSummaryFilesCopied()
        {
            var tempDir  = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var mockTool = new Mock <ICoverageParserTool>();

            Directory.CreateDirectory(tempDir);

            mockTool.Setup(x => x.GenerateHTMLReport());

            var config = new PublisherConfiguration()
            {
                CoverageFiles = new List <string>()
                {
                    "SampleCoverage/Clover.xml", "SampleCoverage/Cobertura.xml", "SampleCoverage/Jacoco.xml"
                },
                ReportDirectory = tempDir
            };

            var parser = new TestParser(config, _mockTelemetry.Object);

            parser.GenerateReport(mockTool.Object);

            var tempDirSummary = Directory.EnumerateDirectories(tempDir, "Summary_*").ToList()[0];

            foreach (var summaryFile in config.CoverageFiles)
            {
                var fileName = Path.GetFileName(summaryFile);
                Assert.IsTrue(File.Exists(Path.Combine(tempDirSummary, fileName)));
            }

            //cleanup
            Directory.Delete(tempDir, true);

            Assert.IsTrue(_logger.Log.Contains("debug: Parser.GenerateHTMLReport: Creating summary file directory:"));

            Assert.IsTrue(_logger.Log.Contains(@"
debug: Parser.GenerateHTMLReport: Copying summary file SampleCoverage/Clover.xml
debug: Parser.GenerateHTMLReport: Copying summary file SampleCoverage/Cobertura.xml
debug: Parser.GenerateHTMLReport: Copying summary file SampleCoverage/Jacoco.xml
".Trim()));
        }
Exemplo n.º 22
0
        public void WillLogIfReportDirectoryDoesntExist()
        {
            var tempDir  = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var mockTool = new Mock <ICoverageParserTool>();

            mockTool.Setup(x => x.GenerateHTMLReport());

            var config = new PublisherConfiguration()
            {
                CoverageFiles = new List <string>()
                {
                    "SampleCoverage/Clover.xml", "SampleCoverage/Cobertura.xml", "SampleCoverage/Jacoco.xml"
                },
                ReportDirectory = tempDir
            };

            var parser = new TestParser(config, _mockTelemetry.Object);

            parser.GenerateReport(mockTool.Object);

            Assert.IsTrue(_logger.Log.Contains("debug: Parser.GenerateHTMLReport: Directory".Trim()));
            Assert.IsTrue(_logger.Log.Contains("doesn't exist, skipping copying of coverage input files.".Trim()));
        }
Exemplo n.º 23
0
        public Task PublishAsync <T>(T message = default(T), Guid globalMessageId = new Guid(), Action <IPublishConfigurationBuilder> configuration = null)
        {
            var config      = _configEval.GetConfiguration <T>(configuration);
            var exchangeCfg = config.Exchange.AssumeInitialized
                                ? null
                                : new ExchangeDeclaration
            {
                AutoDelete   = config.Exchange.AutoDelete,
                Durable      = config.Exchange.Durable,
                ExchangeType = config.Exchange.ExchangeType,
                Name         = config.Exchange.ExchangeName,
                Arguments    = config.Exchange.Arguments
            };

            var publisherCfg = new PublisherConfiguration
            {
                Exchange        = exchangeCfg,
                ExchangeName    = config.Exchange.ExchangeName,
                RoutingKey      = config.RoutingKey,
                BasicProperties = new BasicProperties(),
                Mandatory       = config.BasicReturn != null,
                ReturnCallback  = config.BasicReturn
            };

            config.PropertyModifier?.Invoke(publisherCfg.BasicProperties);

            Action <IPipeContext> ctxAction = context =>
            {
                context.Properties.TryAdd(PipeKey.PublisherConfiguration, publisherCfg);
                context.Properties.TryAdd(PipeKey.BasicPublishConfiguration, publisherCfg);
                context.Properties.TryAdd(PipeKey.ExchangeDeclaration, exchangeCfg);
                context.Properties.TryAdd(PipeKey.ReturnCallback, publisherCfg.ReturnCallback);
            };

            return(_client.PublishAsync(message: message, context: ctxAction));
        }
        public async Task ParseAndPublishCoverage(PublisherConfiguration config, CancellationToken token, Parser parser)
        {
            if (_publisher != null)
            {
                try
                {
                    _telemetry.AddOrUpdate("PublisherConfig", () =>
                    {
                        return("{" +
                               $"\"InputFilesCount\": {config.CoverageFiles.Count}," +
                               $"\"SourceDirectoryProvided\": {config.SourceDirectory != ""}," +
                               $"\"GenerateHtmlReport\": {config.GenerateHTMLReport}," +
                               $"\"GenerateHtmlReport\": {config.TimeoutInSeconds}" +
                               "}");
                    });

                    var supportsFileCoverageJson = _publisher.IsFileCoverageJsonSupported();

                    if (supportsFileCoverageJson)
                    {
                        TraceLogger.Debug("Publishing file json coverage is supported.");
                        var fileCoverage = parser.GetFileCoverageInfos();

                        _telemetry.AddOrUpdate("UniqueFilesCovered", fileCoverage.Count);

                        if (fileCoverage.Count == 0)
                        {
                            TraceLogger.Warning(Resources.NoCoverageFilesGenerated);
                        }
                        else
                        {
                            using (new SimpleTimer("CoverageProcesser", "PublishFileCoverage", _telemetry))
                            {
                                await _publisher.PublishFileCoverage(fileCoverage, token);
                            }
                        }
                    }
                    else
                    {
                        TraceLogger.Debug("Publishing file json coverage is not supported.");
                        var summary = parser.GetCoverageSummary();

                        if (summary == null || summary.CodeCoverageData.CoverageStats.Count == 0)
                        {
                            TraceLogger.Warning(Resources.NoSummaryStatisticsGenerated);
                        }
                        else
                        {
                            using (new SimpleTimer("CoverageProcesser", "PublishCoverageSummary", _telemetry))
                            {
                                await _publisher.PublishCoverageSummary(summary, token);
                            }
                        }
                    }

                    if (config.GenerateHTMLReport)
                    {
                        if (!Directory.Exists(config.ReportDirectory))
                        {
                            TraceLogger.Warning(Resources.NoReportDirectoryGenerated);
                        }
                        else
                        {
                            using (new SimpleTimer("CoverageProcesser", "PublishHTMLReport", _telemetry))
                            {
                                await _publisher.PublishHTMLReport(config.ReportDirectory, token);
                            }
                        }
                    }
                }
                // Only catastrophic failures should trickle down to these catch blocks
                catch (ParsingException ex)
                {
                    _telemetry.AddFailure(ex);
                    TraceLogger.Error($"{ex.Message} {ex.InnerException}");
                }
                catch (Exception ex)
                {
                    _telemetry.AddFailure(ex);
                    TraceLogger.Error(string.Format(Resources.ErrorOccuredWhilePublishing, ex));
                }
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Create an entire stack.
        /// </summary>
        /// <param name="readerId"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        public static IStack CreateStack(string readerId, CollectorConfiguration config)
        {
            var stack = ComponentRegistration.CreateInstance <IStack>(config.StackType);

            foreach (var readerConfig in config.Readers)
            {
                if (readerConfig.Id == readerId)
                {
                    var newReaderId = Guid.NewGuid().ToString();

                    List <IPublisher>   publishers   = new List <IPublisher>();
                    List <ITransformer> transformers = new List <ITransformer>();
                    foreach (var transformerConfig in config.Transformers)
                    {
                        if (transformerConfig.ReaderId == readerId)
                        {
                            var newTransformerId = Guid.NewGuid().ToString();
                            foreach (var publisherConfig in config.Publishers)
                            {
                                if (publisherConfig.TransformerId == transformerConfig.Id)
                                {
                                    foreach (var endpoint in config.EndPoints)
                                    {
                                        if (endpoint.Id == publisherConfig.EndpointId)
                                        {
                                            var newEndpoint = new EndPointConfiguration()
                                            {
                                                Id       = Guid.NewGuid().ToString(),
                                                Password = endpoint.Password,
                                                User     = endpoint.User
                                            };
                                            foreach (var key in endpoint.Properties.Keys)
                                            {
                                                newEndpoint.Properties.Add(key, endpoint.Properties[key]);
                                            }

                                            var newPublisherConfig = new PublisherConfiguration()
                                            {
                                                Id            = Guid.NewGuid().ToString(),
                                                EndpointId    = newEndpoint.Id,
                                                TransformerId = newTransformerId,
                                                Type          = publisherConfig.Type
                                            };
                                            var publisher = CreatePublisher(newPublisherConfig, endpoint);
                                            publishers.Add(publisher);
                                        }
                                    }
                                }
                            }
                            var newTransformerConfig = new TransformerConfiguration()
                            {
                                Id       = newTransformerId,
                                Type     = transformerConfig.Type,
                                ReaderId = newReaderId,
                            };
                            foreach (var mapper in transformerConfig.Mappers)
                            {
                                var newMapperConfig = new MapperConfiguration()
                                {
                                    Id                   = mapper.Id,
                                    DataType             = mapper.DataType,
                                    TransformerId        = newTransformerId,
                                    Type                 = mapper.Type,
                                    SourceTargetMappings = mapper.SourceTargetMappings
                                };
                                foreach (var converter in mapper.PipedConverters)
                                {
                                    var newConverter = CopyConfig(converter);
                                    newMapperConfig.PipedConverters.Add(converter);
                                }
                                foreach (var converter in mapper.Converters)
                                {
                                    var newConverter = CopyConfig(converter);
                                    newMapperConfig.Converters.Add(converter);
                                }
                                newTransformerConfig.Mappers.Add(newMapperConfig);
                            }
                            var transformer = CreateTransformer(newTransformerConfig, stack);
                            transformers.Add(transformer);
                        }
                    }
                    foreach (var endpoint in config.EndPoints)
                    {
                        if (readerConfig.EndpointId.Equals(endpoint.Id))
                        {
                            var newEndpoint = new EndPointConfiguration()
                            {
                                Id       = Guid.NewGuid().ToString(),
                                Password = endpoint.Password,
                                User     = endpoint.User
                            };
                            foreach (var key in endpoint.Properties.Keys)
                            {
                                newEndpoint.Properties.Add(key, endpoint.Properties[key]);
                            }
                            var reader = CreateReader(readerConfig.Type, newReaderId, newEndpoint, stack);
                            stack.Configure(reader, transformers, publishers);
                            break;
                        }
                    }
                    break;
                }
            }
            return(stack);
        }
 public TestParser(PublisherConfiguration config, ITelemetryDataCollector telemetryDataCollector, ICoverageParserTool tool) : base(config, telemetryDataCollector)
 {
     _tool = tool;
 }
 public TestParser(PublisherConfiguration config, ITelemetryDataCollector telemetryDataCollector) : base(config, telemetryDataCollector)
 {
 }
Exemplo n.º 28
0
        public IQueuePublisher GetPublisher(PublisherConfiguration configuration)
        {
            string queueName = configuration.Queue.Name;

            return(new QueuePublisher(queueName, PublishMessageAsync));
        }
 protected virtual ICoverageParserTool GetCoverageParserTool(PublisherConfiguration config)
 {
     // Currently there's only one parser tool, so simply return that instead of having a factory
     return(new ReportGeneratorTool(config));
 }
        /// <summary>
        /// Create a new session summary as the live collection session for the current process
        /// </summary>
        /// <remarks>This constructor figures out all of the summary information when invoked, which can take a moment.</remarks>
        internal SessionSummary(AgentConfiguration configuration)
        {
            m_IsLive        = true;
            m_Packet        = new SessionSummaryPacket();
            m_SessionStatus = SessionStatus.Running;

            m_PrivacyEnabled = configuration.Publisher.EnableAnonymousMode;

            try
            {
                m_Packet.ID      = Guid.NewGuid();
                m_Packet.Caption = null;

                //this stuff all tends to succeed
                if (m_PrivacyEnabled)
                {
                    m_Packet.UserName       = string.Empty;
                    m_Packet.UserDomainName = string.Empty;
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    m_Packet.UserName       = System.Environment.GetEnvironmentVariable("USERNAME") ?? string.Empty;
                    m_Packet.UserDomainName = System.Environment.GetEnvironmentVariable("USERDOMAIN") ?? string.Empty;
                }
                else
                {
                    m_Packet.UserName       = System.Environment.GetEnvironmentVariable("USER") ?? string.Empty;
                    m_Packet.UserDomainName = System.Environment.GetEnvironmentVariable("HOSTNAME") ?? string.Empty;
                }

                m_Packet.TimeZoneCaption = TimeZoneInfo.Local.StandardName;
                m_Packet.EndDateTime     = StartDateTime; //we want to ALWAYS have an end time, and since we just created our start time we need to move that over to end time

                //this stuff, on the other hand, doesn't always succeed

                //Lets see if the user has already picked some things for us...
                PublisherConfiguration publisherConfig = configuration.Publisher;
                string  productName = null, applicationName = null, applicationDescription = null;
                Version applicationVersion = null;

                //what kind of process are we?
                if (publisherConfig.ApplicationType != ApplicationType.Unknown)
                {
                    // They specified an application type, so just use that.
                    m_AgentAppType = publisherConfig.ApplicationType; // Start with the type they specified.
                }

                m_Packet.ApplicationType = m_AgentAppType; // Finally, set the application type from our determined type.
                if (m_AgentAppType != ApplicationType.AspNet)
                {
                    //we want to find our entry assembly and get default product/app info from it.
                    GetApplicationNameSafe(out productName, out applicationName, out applicationVersion, out applicationDescription);
                }

                //OK, now apply configuration overrides or what we discovered...
                m_Packet.ProductName            = string.IsNullOrEmpty(publisherConfig.ProductName) ? productName : publisherConfig.ProductName;
                m_Packet.ApplicationName        = string.IsNullOrEmpty(publisherConfig.ApplicationName) ? applicationName : publisherConfig.ApplicationName;
                m_Packet.ApplicationVersion     = publisherConfig.ApplicationVersion ?? applicationVersion;
                m_Packet.ApplicationDescription = string.IsNullOrEmpty(publisherConfig.ApplicationDescription) ? applicationDescription : publisherConfig.ApplicationDescription;
                m_Packet.EnvironmentName        = publisherConfig.EnvironmentName;
                m_Packet.PromotionLevelName     = publisherConfig.PromotionLevelName;

                //Finally, no nulls allowed! Fix any...
                m_Packet.ProductName            = string.IsNullOrEmpty(m_Packet.ProductName) ? "Unknown" : m_Packet.ProductName;
                m_Packet.ApplicationName        = string.IsNullOrEmpty(m_Packet.ApplicationName) ? "Unknown" : m_Packet.ApplicationName;
                m_Packet.ApplicationVersion     = m_Packet.ApplicationVersion ?? new Version(0, 0);
                m_Packet.ApplicationDescription = m_Packet.ApplicationDescription ?? string.Empty;
                m_Packet.EnvironmentName        = m_Packet.EnvironmentName ?? string.Empty;
                m_Packet.PromotionLevelName     = m_Packet.PromotionLevelName ?? string.Empty;

                m_Packet.ComputerId   = GetComputerIdSafe(m_Packet.ProductName, configuration);
                m_Packet.AgentVersion = GetAgentVersionSafe();
            }
            catch (Exception ex)
            {
                //we really don't want an init error to fail us, not here!
                GC.KeepAlive(ex);
            }

            if (m_PrivacyEnabled == false)
            {
                try
                {
                    IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
                    m_Packet.HostName      = ipGlobalProperties.HostName;
                    m_Packet.DnsDomainName = ipGlobalProperties.DomainName ?? string.Empty;
                }
                catch
                {
                    //fallback to environment names
                    try
                    {
                        m_Packet.HostName = System.Environment.MachineName;
                    }
                    catch (Exception ex)
                    {
                        //we really don't want an init error to fail us, not here!
                        GC.KeepAlive(ex);

                        m_Packet.HostName = "unknown";
                    }
                    m_Packet.DnsDomainName = string.Empty;
                }
            }
            else
            {
                // Privacy mode.  Don't store "personally-identifying information".
                m_Packet.HostName      = "anonymous";
                m_Packet.DnsDomainName = string.Empty;
            }

            var os = System.Environment.OSVersion;

            m_Packet.OSPlatformCode = (int)os.Platform;  //we copied this enum for our value.
            m_Packet.OSVersion      = os.Version;
            m_Packet.OSServicePack  = os.ServicePack;

            try
            {
                m_Packet.OSArchitecture      = RuntimeInformation.OSArchitecture.ToProcessorArchitecture();
                m_Packet.RuntimeArchitecture = RuntimeInformation.ProcessArchitecture.ToProcessorArchitecture();

                m_Packet.OSCultureName        = CultureInfo.CurrentUICulture.ToString();
                m_Packet.CurrentCultureName   = CultureInfo.CurrentCulture.ToString();
                m_Packet.CurrentUICultureName = CultureInfo.CurrentUICulture.ToString();

                m_Packet.OSBootMode = OSBootMode.Normal;

                m_Packet.Processors     = System.Environment.ProcessorCount;
                m_Packet.ProcessorCores = m_Packet.Processors; //BUG

                try
                {
                    var frameworkDescription = RuntimeInformation.FrameworkDescription;

                    //hopefully this has a version number in it...
                    //Thanks to SO.. https://stackoverflow.com/questions/6618868/regular-expression-for-version-numbers
                    var versionMatch = Regex.Match(frameworkDescription, @"\d+(?:\.\d+)+");
                    if (versionMatch.Success)
                    {
                        if (Version.TryParse(versionMatch.Value, out var version))
                        {
                            m_Packet.RuntimeVersion = version;
                        }
                        else
                        {
                            m_Packet.RuntimeVersion = new Version(0, 0);
                        }
                    }
                }
                catch (Exception ex)
                {
                    GC.KeepAlive(ex);
                    m_Packet.RuntimeVersion = new Version(0, 0);
                }


                m_Packet.MemoryMB        = 0; // BUG
                m_Packet.UserInteractive = System.Environment.UserInteractive;

                //find the active screen resolution
                if (m_AgentAppType == ApplicationType.Windows)
                {
                    //We don't know if we can reliably get these on .NET Core.
                    m_Packet.TerminalServer = false;
                    m_Packet.ColorDepth     = 0;
                    m_Packet.ScreenHeight   = 0;
                    m_Packet.ScreenWidth    = 0;
                }

                if (m_PrivacyEnabled)
                {
                    m_Packet.CommandLine = string.Empty;
                }
                else
                {
                    //.NET Core doesn't expose the command line because of concerns over how it is handled cross-platform.
                    var commandArgs = System.Environment.GetCommandLineArgs();
                    m_Packet.CommandLine = string.Join(" ", commandArgs); //the first arg is the executable name
                }
            }
            catch (Exception ex)
            {
                //we really don't want an init error to fail us, not here!
                GC.KeepAlive(ex);
            }

            //now do user defined properties
            try
            {
                foreach (KeyValuePair <string, string> keyValuePair in configuration.Properties)
                {
                    m_Packet.Properties.Add(keyValuePair.Key, keyValuePair.Value);
                }
            }
            catch (Exception ex)
            {
                //we aren't expecting any errors, but best be safe.
                GC.KeepAlive(ex);
            }

            m_Packet.Caption = m_Packet.ApplicationName;
        }