public void TransmissionProcessorIsAddedDefaultWhenNoOtherTelemetryProcessorsAreConfigured()
 {
     var config = new TelemetryConfiguration();
     var builder = new TelemetryProcessorChainBuilder(config);            
     builder.Build();
     Assert.IsType<TransmissionProcessor>(config.TelemetryProcessorChain.FirstTelemetryProcessor);
 }
 public void UsesTelemetryProcessorGivenInUseToBuild()
 {
     var config = new TelemetryConfiguration();
     var builder = new TelemetryProcessorChainBuilder(config);
     builder.Use((next) => new StubTelemetryProcessor(next));                    
     builder.Build();
     Assert.IsType<StubTelemetryProcessor>(config.TelemetryProcessorChain.FirstTelemetryProcessor);
 }
        public virtual void Initialize(TelemetryConfiguration configuration)
        {
            configuration.ContextInitializers.Add(new SdkVersionPropertyContextInitializer());
            configuration.TelemetryInitializers.Add(new TimestampPropertyInitializer());

            // Creating the default channel if no channel configuration supplied
            configuration.TelemetryChannel = configuration.TelemetryChannel ?? new InMemoryChannel();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TransmissionProcessor"/> class.
        /// </summary>        
        /// <param name="configuration">The <see cref="TelemetryConfiguration"/> to get the channel from.</param>
        internal TransmissionProcessor(TelemetryConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            this.configuration = configuration;
        }
 public SessionTelemetryModuleTest()
 {
     this.platform = new StubPlatform { OnGetApplicationSettings = () => this.settings };
     this.channel = new StubTelemetryChannel { OnSend = t => this.sentTelemetry.Add(t) };
     this.configuration = new TelemetryConfiguration { TelemetryChannel = this.channel, InstrumentationKey = "Test Key" };
     ServiceLocator.AddService<IApplicationService>(new ApplicationService());
     TelemetryConfiguration.Active = configuration;
     HockeyClient.Current.AsInternal().IsTelemetryInitialized = true;
 }
        /// <summary>
        /// Initialize method is called after all configuration properties have been loaded from the configuration.
        /// </summary>
        public void Initialize(TelemetryConfiguration configuration)
        {
            /*
            The configuration that is being passed into this method is the configuration that is the reason
            why this instance of telemetry processor was created. Regardless of which instrumentation key is passed in,
            this telemetry processor will only collect for whichever instrumentation key is specified by the module in StartCollection call.
            */

            this.Register();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TelemetryProcessorChainBuilder" /> class.
        /// </summary>
        /// <param name="configuration"> The <see cref="TelemetryConfiguration"/> instance to which the constructed processing chain should be set to. </param>        
        public TelemetryProcessorChainBuilder(TelemetryConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            this.configuration = configuration;
            this.factories = new List<Func<ITelemetryProcessor, ITelemetryProcessor>>();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TransmissionProcessor"/> class.
        /// </summary>        
        /// <param name="configuration">The <see cref="TelemetryConfiguration"/> to get the channel from.</param>
        internal TransmissionProcessor(TelemetryConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            this.configuration = configuration;
            this.debugOutput = PlatformSingleton.Current.GetDebugOutput();
        }
        public void NoExceptionOnReturningNullFromUse()
        {
            var configuration = new TelemetryConfiguration();

            var builder = new TelemetryProcessorChainBuilder(configuration);
            builder.Use(next => null);

            builder.Build();

            Assert.Equal(1, configuration.TelemetryProcessors.Count); // Transmission is added by default
        }
        public void BuildOrdersTelemetryChannelsInOrderOfUseCalls()
        {
           var config = new TelemetryConfiguration() {TelemetryChannel = new StubTelemetryChannel()};
           StringBuilder outputCollector = new StringBuilder();
           var builder = new TelemetryProcessorChainBuilder(config);
           builder.Use((next) => new StubTelemetryProcessor(next) { OnProcess = (item) => { outputCollector.Append("processor1"); } });
           builder.Use((next) => new StubTelemetryProcessor(next) { OnProcess = (item) => { outputCollector.Append("processor2"); } });
           builder.Build();
           config.TelemetryProcessorChain.Process(new StubTelemetry());            

           Assert.Equal("processor1processor2", outputCollector.ToString());
        }
        void IQuickPulseTelemetryProcessor.StartCollection(IQuickPulseDataAccumulatorManager accumulatorManager, Uri serviceEndpoint, TelemetryConfiguration configuration)
        {
            if (this.isCollecting)
            {
                throw new InvalidOperationException("Can't start collection while it is already running.");
            }

            this.dataAccumulatorManager = accumulatorManager;
            this.serviceEndpoint = serviceEndpoint;
            this.config = configuration;
            this.isCollecting = true;
        }
        public void NullProcessorsAreSkipped()
        {
            var configuration = new TelemetryConfiguration();

            var builder = new TelemetryProcessorChainBuilder(configuration);
            builder.Use(next => new StubTelemetryProcessor(next));
            builder.Use(next => null);
            builder.Use(next => new StubTelemetryProcessor(next));

            builder.Build();

            Assert.Equal(3, configuration.TelemetryProcessors.Count); // Transmission is added by default
            Assert.Same(((StubTelemetryProcessor)configuration.TelemetryProcessors[0]).next, ((StubTelemetryProcessor)configuration.TelemetryProcessors[1]));
        }
        public void BuildUsesTelemetryProcesorFactoryOnEachCall()
        {
            var tc1 = new TelemetryConfiguration();
            var tc2 = new TelemetryConfiguration();
            var builder1 = new TelemetryProcessorChainBuilder(tc1);
            builder1.Use((next) => new StubTelemetryProcessor(next));
            builder1.Build();

            var builder2 = new TelemetryProcessorChainBuilder(tc2);
            builder2.Use((next) => new StubTelemetryProcessor(next));
            builder2.Build();
            
            Assert.NotSame(tc1.TelemetryProcessors, tc2.TelemetryProcessors);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpProcessingFramework"/> class.
        /// </summary>
        internal HttpProcessingFramework(TelemetryClient client, TelemetryConfiguration configuration, ISamplingPolicy samplingPolicy = null)
            : base(samplingPolicy)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            this.telemetryClient = client;
            this.telemetryConfiguration = configuration;
        }
        public PortalDiagnosticsSenderTest()
        {
            var configuration =
                new TelemetryConfiguration
                {
                    TelemetryChannel = new StubTelemetryChannel { OnSend = item => this.sendItems.Add(item) },
                    InstrumentationKey = Guid.NewGuid().ToString()
                };

            this.nonThrottlingPortalSender = new PortalDiagnosticsSender(
                configuration, 
                this.dontThrottleManager);

            this.throttlingPortalSender = new PortalDiagnosticsSender(
                configuration,
                this.throttleAllManager); 
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PortalDiagnosticsSender"/> class. 
        /// </summary>
        public PortalDiagnosticsSender(
            TelemetryConfiguration configuration,
            IDiagnoisticsEventThrottlingManager throttlingManager)
        {
            if (null == configuration)
            {
                throw new ArgumentNullException("configuration");
            }

            if (null == throttlingManager)
            {
                throw new ArgumentNullException("throttlingManager");
            }

            this.telemetryClient = new TelemetryClient(configuration);

            this.throttlingManager = throttlingManager;
        }
        public void SendNotFailIfChannelNotInitialized()
        {
            var configuration = new TelemetryConfiguration();
            var portalSenderWithDefaultCOnfiguration = new PortalDiagnosticsSender(
                configuration,
                this.dontThrottleManager);

            var evt = new TraceEvent
            {
                MetaData = new EventMetaData
                {
                    EventId = 10,
                    Keywords = 0x20,
                    Level = EventLevel.Warning,
                    MessageFormat = "Something failed"
                },
                Payload = null
            };

            portalSenderWithDefaultCOnfiguration.Send(evt);
        }
示例#18
0
        /// <summary>
        /// Initializes static members of the <see cref="ApplicationInsightsTelemetry"/> class.
        /// Static constructor determines whether telemetry is to be sent, and then
        /// sets the telemetry key and set the telemetry delivery mode.
        /// Creates the session ID and initializes the HashSet of known module names.
        /// Gets or constructs the unique identifier.
        /// </summary>
        static ApplicationInsightsTelemetry()
        {
            // If we can't send telemetry, there's no reason to do any of this
            CanSendTelemetry = !GetEnvironmentVariableAsBool(name: _telemetryOptoutEnvVar, defaultValue: false);
            if (CanSendTelemetry)
            {
                TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
                configuration.InstrumentationKey = _psCoreTelemetryKey;

                // Set this to true to reduce latency during development
                configuration.TelemetryChannel.DeveloperMode = false;

                s_telemetryClient = new TelemetryClient(configuration);
                // Be sure to obscure any information about the client node.
                s_telemetryClient.Context.Cloud.RoleInstance = string.Empty;
                s_telemetryClient.Context.GetInternalContext().NodeName = string.Empty;
                s_sessionId = Guid.NewGuid().ToString();

                // use a hashset when looking for module names, it should be quicker than a string comparison
                s_knownModules = new HashSet <string>(StringComparer.OrdinalIgnoreCase)
                {
                    "AADRM",
                    "activedirectory",
                    "adcsadministration",
                    "adcsdeployment",
                    "addsadministration",
                    "addsdeployment",
                    "adfs",
                    "adrms",
                    "adrmsadmin",
                    "agpm",
                    "appbackgroundtask",
                    "applocker",
                    "appv",
                    "appvclient",
                    "appvsequencer",
                    "appvserver",
                    "appx",
                    "assignedaccess",
                    "Az",
                    "Az.Accounts",
                    "Az.Advisor",
                    "Az.Aks",
                    "Az.AlertsManagement",
                    "Az.AnalysisServices",
                    "Az.ApiManagement",
                    "Az.ApplicationInsights",
                    "Az.Attestation",
                    "Az.Automation",
                    "Az.Batch",
                    "Az.Billing",
                    "Az.Blueprint",
                    "Az.Cdn",
                    "Az.CognitiveServices",
                    "Az.Compute",
                    "Az.ContainerInstance",
                    "Az.ContainerRegistry",
                    "Az.DataBox",
                    "Az.DataFactory",
                    "Az.DataLakeAnalytics",
                    "Az.DataLakeStore",
                    "Az.DataMigration",
                    "Az.DataShare",
                    "Az.DeploymentManager",
                    "Az.DeviceProvisioningServices",
                    "Az.DevSpaces",
                    "Az.DevTestLabs",
                    "Az.Dns",
                    "Az.EventGrid",
                    "Az.EventHub",
                    "Az.FrontDoor",
                    "Az.GuestConfiguration",
                    "Az.HDInsight",
                    "Az.HealthcareApis",
                    "Az.IotCentral",
                    "Az.IotHub",
                    "Az.KeyVault",
                    "Az.Kusto",
                    "Az.LogicApp",
                    "Az.MachineLearning",
                    "Az.ManagedServiceIdentity",
                    "Az.ManagedServices",
                    "Az.ManagementPartner",
                    "Az.Maps",
                    "Az.MarketplaceOrdering",
                    "Az.Media",
                    "Az.MixedReality",
                    "Az.Monitor",
                    "Az.NetAppFiles",
                    "Az.Network",
                    "Az.NotificationHubs",
                    "Az.OperationalInsights",
                    "Az.Peering",
                    "Az.PolicyInsights",
                    "Az.PowerBIEmbedded",
                    "Az.PrivateDns",
                    "Az.RecoveryServices",
                    "Az.RedisCache",
                    "Az.Relay",
                    "Az.Reservations",
                    "Az.ResourceGraph",
                    "Az.Resources",
                    "Az.Search",
                    "Az.Security",
                    "Az.ServiceBus",
                    "Az.ServiceFabric",
                    "Az.SignalR",
                    "Az.Sql",
                    "Az.Storage",
                    "Az.StorageSync",
                    "Az.StorageTable",
                    "Az.StreamAnalytics",
                    "Az.Subscription",
                    "Az.TrafficManager",
                    "Az.Websites",
                    "Azs.Azurebridge.Admin",
                    "Azs.Backup.Admin",
                    "Azs.Commerce.Admin",
                    "Azs.Compute.Admin",
                    "Azs.Fabric.Admin",
                    "Azs.Gallery.Admin",
                    "Azs.Infrastructureinsights.Admin",
                    "Azs.Keyvault.Admin",
                    "Azs.Network.Admin",
                    "Azs.Storage.Admin",
                    "Azs.Subscriptions",
                    "Azs.Subscriptions.Admin",
                    "Azs.Update.Admin",
                    "AzStorageTable",
                    "Azure",
                    "Azure.AnalysisServices",
                    "Azure.Storage",
                    "AzureAD",
                    "AzureInformationProtection",
                    "AzureRM.Aks",
                    "AzureRM.AnalysisServices",
                    "AzureRM.ApiManagement",
                    "AzureRM.ApplicationInsights",
                    "AzureRM.Automation",
                    "AzureRM.Backup",
                    "AzureRM.Batch",
                    "AzureRM.Billing",
                    "AzureRM.Cdn",
                    "AzureRM.CognitiveServices",
                    "AzureRm.Compute",
                    "AzureRM.Compute.ManagedService",
                    "AzureRM.Consumption",
                    "AzureRM.ContainerInstance",
                    "AzureRM.ContainerRegistry",
                    "AzureRM.DataFactories",
                    "AzureRM.DataFactoryV2",
                    "AzureRM.DataLakeAnalytics",
                    "AzureRM.DataLakeStore",
                    "AzureRM.DataMigration",
                    "AzureRM.DeploymentManager",
                    "AzureRM.DeviceProvisioningServices",
                    "AzureRM.DevSpaces",
                    "AzureRM.DevTestLabs",
                    "AzureRm.Dns",
                    "AzureRM.EventGrid",
                    "AzureRM.EventHub",
                    "AzureRM.FrontDoor",
                    "AzureRM.HDInsight",
                    "AzureRm.Insights",
                    "AzureRM.IotCentral",
                    "AzureRM.IotHub",
                    "AzureRm.Keyvault",
                    "AzureRM.LocationBasedServices",
                    "AzureRM.LogicApp",
                    "AzureRM.MachineLearning",
                    "AzureRM.MachineLearningCompute",
                    "AzureRM.ManagedServiceIdentity",
                    "AzureRM.ManagementPartner",
                    "AzureRM.Maps",
                    "AzureRM.MarketplaceOrdering",
                    "AzureRM.Media",
                    "AzureRM.Network",
                    "AzureRM.NotificationHubs",
                    "AzureRM.OperationalInsights",
                    "AzureRM.PolicyInsights",
                    "AzureRM.PowerBIEmbedded",
                    "AzureRM.Profile",
                    "AzureRM.RecoveryServices",
                    "AzureRM.RecoveryServices.Backup",
                    "AzureRM.RecoveryServices.SiteRecovery",
                    "AzureRM.RedisCache",
                    "AzureRM.Relay",
                    "AzureRM.Reservations",
                    "AzureRM.ResourceGraph",
                    "AzureRM.Resources",
                    "AzureRM.Scheduler",
                    "AzureRM.Search",
                    "AzureRM.Security",
                    "AzureRM.ServerManagement",
                    "AzureRM.ServiceBus",
                    "AzureRM.ServiceFabric",
                    "AzureRM.SignalR",
                    "AzureRM.SiteRecovery",
                    "AzureRM.Sql",
                    "AzureRm.Storage",
                    "AzureRM.StorageSync",
                    "AzureRM.StreamAnalytics",
                    "AzureRM.Subscription",
                    "AzureRM.Subscription.Preview",
                    "AzureRM.Tags",
                    "AzureRM.TrafficManager",
                    "AzureRm.UsageAggregates",
                    "AzureRm.Websites",
                    "AzureRmStorageTable",
                    "bestpractices",
                    "bitlocker",
                    "bitstransfer",
                    "booteventcollector",
                    "branchcache",
                    "CimCmdlets",
                    "clusterawareupdating",
                    "CompatPowerShellGet",
                    "configci",
                    "ConfigurationManager",
                    "DataProtectionManager",
                    "dcbqos",
                    "deduplication",
                    "defender",
                    "devicehealthattestation",
                    "dfsn",
                    "dfsr",
                    "dhcpserver",
                    "directaccessclient",
                    "directaccessclientcomponent",
                    "directaccessclientcomponents",
                    "dism",
                    "dnsclient",
                    "dnsserver",
                    "ElasticDatabaseJobs",
                    "EventTracingManagement",
                    "failoverclusters",
                    "fileserverresourcemanager",
                    "FIMAutomation",
                    "GPRegistryPolicy",
                    "grouppolicy",
                    "hardwarecertification",
                    "hcs",
                    "hgsattestation",
                    "hgsclient",
                    "hgsdiagnostics",
                    "hgskeyprotection",
                    "hgsserver",
                    "hnvdiagnostics",
                    "hostcomputeservice",
                    "hpc",
                    "HPC.ACM",
                    "HPC.ACM.API.PS",
                    "HPCPack2016",
                    "hyper-v",
                    "IISAdministration",
                    "international",
                    "ipamserver",
                    "iscsi",
                    "iscsitarget",
                    "ISE",
                    "kds",
                    "Microsoft.MBAM",
                    "Microsoft.MEDV",
                    "MgmtSvcAdmin",
                    "MgmtSvcConfig",
                    "MgmtSvcMySql",
                    "MgmtSvcSqlServer",
                    "Microsoft.AzureStack.ReadinessChecker",
                    "Microsoft.Crm.PowerShell",
                    "Microsoft.DiagnosticDataViewer",
                    "Microsoft.DirectoryServices.MetadirectoryServices.Config",
                    "Microsoft.Dynamics.Nav.Apps.Management",
                    "Microsoft.Dynamics.Nav.Apps.Tools",
                    "Microsoft.Dynamics.Nav.Ide",
                    "Microsoft.Dynamics.Nav.Management",
                    "Microsoft.Dynamics.Nav.Model.Tools",
                    "Microsoft.Dynamics.Nav.Model.Tools.Crm",
                    "Microsoft.EnterpriseManagement.Warehouse.Cmdlets",
                    "Microsoft.Medv.Administration.Commands.WorkspacePackager",
                    "Microsoft.PowerApps.Checker.PowerShell",
                    "Microsoft.PowerShell.Archive",
                    "Microsoft.PowerShell.Core",
                    "Microsoft.PowerShell.Crescendo",
                    "Microsoft.PowerShell.Diagnostics",
                    "Microsoft.PowerShell.Host",
                    "Microsoft.PowerShell.LocalAccounts",
                    "Microsoft.PowerShell.Management",
                    "Microsoft.PowerShell.ODataUtils",
                    "Microsoft.PowerShell.Operation.Validation",
                    "Microsoft.PowerShell.RemotingTools",
                    "Microsoft.PowerShell.SecretManagement",
                    "Microsoft.PowerShell.SecretStore",
                    "Microsoft.PowerShell.Security",
                    "Microsoft.PowerShell.TextUtility",
                    "Microsoft.PowerShell.Utility",
                    "Microsoft.SharePoint.Powershell",
                    "Microsoft.SystemCenter.ServiceManagementAutomation",
                    "Microsoft.Windows.ServerManager.Migration",
                    "Microsoft.WSMan.Management",
                    "Microsoft.Xrm.OnlineManagementAPI",
                    "Microsoft.Xrm.Tooling.CrmConnector.PowerShell",
                    "Microsoft.Xrm.Tooling.PackageDeployment",
                    "Microsoft.Xrm.Tooling.PackageDeployment.Powershell",
                    "Microsoft.Xrm.Tooling.Testing",
                    "MicrosoftPowerBIMgmt",
                    "MicrosoftPowerBIMgmt.Data",
                    "MicrosoftPowerBIMgmt.Profile",
                    "MicrosoftPowerBIMgmt.Reports",
                    "MicrosoftPowerBIMgmt.Workspaces",
                    "MicrosoftStaffHub",
                    "MicrosoftTeams",
                    "MIMPAM",
                    "mlSqlPs",
                    "MMAgent",
                    "MPIO",
                    "MsDtc",
                    "MSMQ",
                    "MSOnline",
                    "MSOnlineBackup",
                    "WmsCmdlets",
                    "WmsCmdlets3",
                    "NanoServerImageGenerator",
                    "NAVWebClientManagement",
                    "NetAdapter",
                    "NetConnection",
                    "NetEventPacketCapture",
                    "Netlbfo",
                    "Netldpagent",
                    "NetNat",
                    "Netqos",
                    "NetSecurity",
                    "NetSwitchtTeam",
                    "Nettcpip",
                    "Netwnv",
                    "NetworkConnectivity",
                    "NetworkConnectivityStatus",
                    "NetworkController",
                    "NetworkControllerDiagnostics",
                    "NetworkloadBalancingClusters",
                    "NetworkSwitchManager",
                    "NetworkTransition",
                    "NFS",
                    "NPS",
                    "OfficeWebapps",
                    "OperationsManager",
                    "PackageManagement",
                    "PartnerCenter",
                    "pcsvdevice",
                    "pef",
                    "Pester",
                    "pkiclient",
                    "platformidentifier",
                    "pnpdevice",
                    "PowerShellEditorServices",
                    "PowerShellGet",
                    "powershellwebaccess",
                    "printmanagement",
                    "ProcessMitigations",
                    "provisioning",
                    "PSDesiredStateConfiguration",
                    "PSDiagnostics",
                    "PSReadLine",
                    "PSScheduledJob",
                    "PSScriptAnalyzer",
                    "PSWorkflow",
                    "PSWorkflowUtility",
                    "RemoteAccess",
                    "RemoteDesktop",
                    "RemoteDesktopServices",
                    "ScheduledTasks",
                    "Secureboot",
                    "ServerCore",
                    "ServerManager",
                    "ServerManagerTasks",
                    "ServerMigrationcmdlets",
                    "ServiceFabric",
                    "Microsoft.Online.SharePoint.PowerShell",
                    "shieldedvmdatafile",
                    "shieldedvmprovisioning",
                    "shieldedvmtemplate",
                    "SkypeOnlineConnector",
                    "SkypeForBusinessHybridHealth",
                    "smbshare",
                    "smbwitness",
                    "smisconfig",
                    "softwareinventorylogging",
                    "SPFAdmin",
                    "Microsoft.SharePoint.MigrationTool.PowerShell",
                    "sqlps",
                    "SqlServer",
                    "StartLayout",
                    "StartScreen",
                    "Storage",
                    "StorageDsc",
                    "storageqos",
                    "Storagereplica",
                    "Storagespaces",
                    "Syncshare",
                    "System.Center.Service.Manager",
                    "TLS",
                    "TroubleshootingPack",
                    "TrustedPlatformModule",
                    "UEV",
                    "UpdateServices",
                    "UserAccessLogging",
                    "vamt",
                    "VirtualMachineManager",
                    "vpnclient",
                    "WasPSExt",
                    "WDAC",
                    "WDS",
                    "WebAdministration",
                    "WebAdministrationDsc",
                    "WebApplicationProxy",
                    "WebSites",
                    "Whea",
                    "WhiteboardAdmin",
                    "WindowsDefender",
                    "WindowsDefenderDsc",
                    "WindowsDeveloperLicense",
                    "WindowsDiagnosticData",
                    "WindowsErrorReporting",
                    "WindowServerRackup",
                    "WindowsSearch",
                    "WindowsServerBackup",
                    "WindowsUpdate",
                    "wsscmdlets",
                    "wsssetup",
                    "wsus",
                    "xActiveDirectory",
                    "xBitLocker",
                    "xDefender",
                    "xDhcpServer",
                    "xDismFeature",
                    "xDnsServer",
                    "xHyper-V",
                    "xHyper-VBackup",
                    "xPSDesiredStateConfiguration",
                    "xSmbShare",
                    "xSqlPs",
                    "xStorage",
                    "xWebAdministration",
                    "xWindowsUpdate",
                };

                s_uniqueUserIdentifier = GetUniqueIdentifier().ToString();
            }
        }
示例#19
0
        public void Configure(
            IApplicationBuilder app,
            ILogger <Startup> logger,
            IHostApplicationLifetime appLifetime,
            TelemetryConfiguration configuration)
        {
            _logger = logger;

            appLifetime.ApplicationStarted.Register(() =>
            {
                _logger.LogInformation("Moonglade started.");
            });
            appLifetime.ApplicationStopping.Register(() =>
            {
                _logger.LogInformation("Moonglade is stopping...");
            });
            appLifetime.ApplicationStopped.Register(() =>
            {
                _logger.LogInformation("Moonglade stopped.");
            });

            PrepareRuntimePathDependencies(app, _environment);

            var enforceHttps = bool.Parse(_appSettingsSection["EnforceHttps"]);

            app.UseSecurityHeaders(new HeaderPolicyCollection()
                                   .AddFrameOptionsSameOrigin()
                                   .AddXssProtectionEnabled()
                                   .AddContentTypeOptionsNoSniff()
                                   .AddContentSecurityPolicy(csp =>
            {
                if (enforceHttps)
                {
                    csp.AddUpgradeInsecureRequests();
                }
                csp.AddFormAction()
                .Self();
                csp.AddScriptSrc()
                .Self()
                .UnsafeInline()
                .UnsafeEval()
                // Whitelist Azure Application Insights
                .From("https://*.vo.msecnd.net")
                .From("https://*.services.visualstudio.com");
            })
                                   // Microsoft believes privacy is a fundamental human right
                                   // So should I
                                   .AddFeaturePolicy(builder =>
            {
                builder.AddCamera().None();
                builder.AddMicrophone().None();
                builder.AddPayment().None();
                builder.AddUsb().None();
            })
                                   .RemoveServerHeader()
                                   );
            app.UseMiddleware <PoweredByMiddleware>();

            if (!_environment.IsProduction())
            {
                _logger.LogWarning($"Running in environment: {_environment.EnvironmentName}. Application Insights disabled.");

                configuration.DisableTelemetry         = true;
                TelemetryDebugWriter.IsTracingDisabled = true;
            }

            if (_environment.IsDevelopment())
            {
                _logger.LogWarning($"Running in environment: {_environment.EnvironmentName}. Detailed error page enabled.");
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/error");
                app.UseStatusCodePagesWithReExecute("/error", "?statusCode={0}");
            }

            if (enforceHttps)
            {
                _logger.LogInformation("HTTPS is enforced.");
                app.UseHttpsRedirection();
                app.UseHsts();
            }

            // Support Chinese contents
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            app.UseStaticFiles();
            app.UseSession();

            var conn        = _configuration.GetConnectionString(Constants.DbConnectionName);
            var setupHelper = new SetupHelper(conn);

            if (!setupHelper.TestDatabaseConnection(exception =>
            {
                _logger.LogCritical(exception, $"Error {nameof(SetupHelper.TestDatabaseConnection)}, connection string: {conn}");
            }))
            {
                app.Run(async context =>
                {
                    context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                    await context.Response.WriteAsync("Database connection failed. Please see error log. Application has been stopped.");
                    appLifetime.StopApplication();
                });
            }
            else
            {
                if (setupHelper.IsFirstRun())
                {
                    try
                    {
                        _logger.LogInformation("Initializing first run configuration...");
                        setupHelper.InitFirstRun();
                        _logger.LogInformation("Database setup successfully.");
                    }
                    catch (Exception e)
                    {
                        _logger.LogCritical(e, e.Message);
                        app.Run(async context =>
                        {
                            context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                            await context.Response.WriteAsync("Error initializing first run, please check error log.");
                            appLifetime.StopApplication();
                        });
                    }
                }

                app.UseIpRateLimiting();
                app.MapWhen(context => context.Request.Path == "/ping", builder =>
                {
                    builder.Run(async context =>
                    {
                        context.Response.Headers.Add("X-Moonglade-Version", Utils.AppVersion);
                        await context.Response.WriteAsync($"Moonglade Version: {Utils.AppVersion}, .NET Core {Environment.Version}", Encoding.UTF8);
                    });
                });

                app.UseRouting();
                app.UseAuthentication();
                app.UseAuthorization();

                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        "default",
                        "{controller=Home}/{action=Index}/{id?}");
                    endpoints.MapRazorPages();
                });
            }
        }
示例#20
0
        public static async Task RunAsync(CancellationToken token)
        {
            // set Instrumentation Key
            var configuration = new TelemetryConfiguration();

            configuration.InstrumentationKey = "fb8a0b03-235a-4b52-b491-307e9fd6b209";

            // automatically track dependency calls
            var dependencies = new DependencyTrackingTelemetryModule();

            dependencies.Initialize(configuration);

            // automatically correlate all telemetry data with request
            configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());

            QuickPulseTelemetryProcessor processor = null;

            // enable Live Metrics
            configuration.TelemetryProcessorChainBuilder

            // adding LiveMetrics telemetry processor
            .Use((next) =>
            {
                processor = new QuickPulseTelemetryProcessor(next);
                return(processor);
            })

            .Build();

            var quickPulse = new QuickPulseTelemetryModule();

            quickPulse.Initialize(configuration);
            quickPulse.RegisterTelemetryProcessor(processor);

            var client = new TelemetryClient(configuration);

            var iteration = 0;
            var http      = new HttpClient();
            var rnd       = new Random();

            while (!token.IsCancellationRequested)
            {
                iteration++;

                using (var operation = client.StartOperation <RequestTelemetry>("Process item"))
                {
                    client.TrackEvent("test", new Dictionary <string, string>()
                    {
                        { "iteration", iteration.ToString() }
                    });
                    client.TrackTrace($"Iteration {iteration} happened", SeverityLevel.Information);

                    var status = rnd.Next() < rnd.Next();
                    try
                    {
                        if (status)
                        {
                            throw new Exception($"Failure during processing of iteration #{iteration}");
                        }

                        await http.GetStringAsync("http://bing.com");
                    }
                    catch (Exception exc)
                    {
                        client.TrackException(exc);
                    }
                    finally
                    {
                        client.StopOperation <RequestTelemetry>(operation);
                        operation.Telemetry.Success = status;

                        Console.WriteLine($"Iteration {iteration}. Elapsed time: {operation.Telemetry.Duration}. Success: {operation.Telemetry.Success}");
                    }
                }
            }
        }
 public TelemetryClient CreateTelemetryClient(TelemetryConfiguration configuration)
 {
     return(new TelemetryClient(configuration));
 }
 public AzureSdkDiagnosticsEventHandler(TelemetryConfiguration configuration) : base(configuration)
 {
 }
        public SentimentInstrumentationMiddlewareTests()
        {
            var telemetryConfiguration = new TelemetryConfiguration(FakeInstrumentationKey, this.mockTelemetryChannel.Object);

            this.telemetryClient = new TelemetryClient(telemetryConfiguration);
        }
示例#24
0
        private static async Task Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .CreateLogger();

            var builder = new HostBuilder()
                          .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json", true);
                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
                          .ConfigureServices((hostContext, services) =>
            {
                _module = new DependencyTrackingTelemetryModule();
                _module.IncludeDiagnosticSourceActivities.Add("MassTransit");

                TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();
                configuration.InstrumentationKey     = "6b4c6c82-3250-4170-97d3-245ee1449278";
                configuration.TelemetryInitializers.Add(new HttpDependenciesParsingTelemetryInitializer());

                _telemetryClient = new TelemetryClient(configuration);

                _module.Initialize(configuration);

                services.TryAddSingleton(KebabCaseEndpointNameFormatter.Instance);
                services.AddMassTransit(cfg =>
                {
                    cfg.AddConsumersFromNamespaceContaining <SubmitFileInfoConsumer>();

                    cfg.AddSagaStateMachine <FileHandlerStateMachine, FileHandlerState>(typeof(FileHandlerStateMachineDefinition))
                    .MongoDbRepository(r =>
                    {
                        r.Connection     = "mongodb://localhost";
                        r.DatabaseName   = "filedb";
                        r.CollectionName = "states";
                    });

                    cfg.UsingRabbitMq(ConfigureBus);
                });

                services.AddHostedService <MassTransitConsoleHostedService>();
            })
                          .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddSerilog(dispose: true);
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
            });

            if (isService)
            {
                await builder.UseWindowsService().Build().RunAsync();
            }
            else
            {
                await builder.RunConsoleAsync();
            }

            _module?.Dispose();
            _telemetryClient?.Flush();

            Log.CloseAndFlush();
        }
示例#25
0
 public TelemetryDiagnosticSourceListener(TelemetryConfiguration configuration, ICollection <string> includeDiagnosticSourceActivities)
     : base(configuration)
 {
     this.Client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("rdd" + RddSource.DiagnosticSourceListener + ":");
     this.PrepareInclusionLists(includeDiagnosticSourceActivities);
 }
示例#26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TelemetryLoggerMiddleware"/> class.
 /// </summary>
 /// <param name="telemetryClient">The IBotTelemetryClient implementation used for registering telemetry events.</param>
 /// <param name="logPersonalInformation"> (Optional) TRUE to include personally indentifiable information.</param>
 /// <param name="config"> (Optional) TelemetryConfiguration to use for Application Insights.</param>
 public TelemetryLoggerMiddleware(IBotTelemetryClient telemetryClient, bool logPersonalInformation = false, TelemetryConfiguration config = null)
 {
     _telemetryClient       = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
     LogPersonalInformation = logPersonalInformation;
 }
        public void DisableTelemetryIsFalseByDefault()
        {
            var configuration = new TelemetryConfiguration();

            Assert.False(configuration.DisableTelemetry);
        }
示例#28
0
        /// <summary>
        /// Copy Paste Job
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns></returns>
        private static DependencyTrackingTelemetryModule InitializeDependencyTracking(TelemetryConfiguration configuration)
        {
            var module = new DependencyTrackingTelemetryModule();

            // prevent Correlation Id to be sent to certain endpoints. You may add other domains as needed.
            //module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.chinacloudapi.cn");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.cloudapi.de");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.usgovcloudapi.net");
            //module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("localhost");
            //module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("127.0.0.1");

            // enable known dependency tracking, note that in future versions, we will extend this list.
            // please check default settings in https://github.com/Microsoft/ApplicationInsights-dotnet-server/blob/develop/Src/DependencyCollector/NuGet/ApplicationInsights.config.install.xdt#L20
            module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.ServiceBus");
            module.IncludeDiagnosticSourceActivities.Add("Microsoft.Azure.EventHubs");

            // initialize the module
            module.Initialize(configuration);

            return(module);
        }
示例#29
0
 public HttpTelemetryHandler(TelemetryConfiguration telemetryConfiguration)
 => this.telemetryConfiguration = telemetryConfiguration ?? throw new ArgumentNullException(nameof(telemetryConfiguration));
示例#30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TelemetryLoggerMiddleware"/> class.
 /// </summary>
 /// <param name="telemetryClient">The IBotTelemetryClient implementation used for registering telemetry events.</param>
 /// <param name="logUserName"> (Optional) Enable/Disable logging user name within Application Insights.</param>
 /// <param name="logOriginalMessage"> (Optional) Enable/Disable logging original message name within Application Insights.</param>
 /// <param name="config"> (Optional) TelemetryConfiguration to use for Application Insights.</param>
 public TelemetryLoggerMiddleware(IBotTelemetryClient telemetryClient, bool logUserName = false, bool logOriginalMessage = false, TelemetryConfiguration config = null)
 {
     _telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
     LogUserName        = logUserName;
     LogOriginalMessage = logOriginalMessage;
 }
示例#31
0
        /// <summary>
        /// Initialize the bot's references to external services.
        /// For example, Application Insights and QnaMaker services
        /// are created here.  These external services are configured
        /// using the <see cref="BotConfiguration"/> class (based on the contents of your ".bot" file).
        /// </summary>
        /// <param name="config">The <see cref="BotConfiguration"/> object based on your ".bot" file.</param>
        /// <returns>A <see cref="BotConfiguration"/> representing client objects to access external services the bot uses.</returns>
        /// <seealso cref="BotConfiguration"/>
        /// <seealso cref="QnAMaker"/>
        /// <seealso cref="TelemetryClient"/>
        private static BotServices InitBotServices(BotConfiguration config)
        {
            TelemetryClient telemetryClient = null;
            var             qnaServices     = new Dictionary <string, QnAMaker>();

            foreach (var service in config.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.QnA:
                {
                    // Create a QnA Maker that is initialized and suitable for passing
                    // into the IBot-derived class (QnABot).
                    // In this case, we're creating a custom class (wrapping the original
                    // QnAMaker client) that logs the results of QnA Maker into Application
                    // Insights for future anaysis.
                    var qna = (QnAMakerService)service;
                    if (qna == null)
                    {
                        throw new InvalidOperationException("The QnA service is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(qna.KbId))
                    {
                        throw new InvalidOperationException("The QnA KnowledgeBaseId ('kbId') is required to run this sample.  Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(qna.EndpointKey))
                    {
                        throw new InvalidOperationException("The QnA EndpointKey ('endpointKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(qna.Hostname))
                    {
                        throw new InvalidOperationException("The QnA Host ('hostname') is required to run this sample.  Please update your '.bot' file.");
                    }

                    var qnaEndpoint = new QnAMakerEndpoint()
                    {
                        KnowledgeBaseId = qna.KbId,
                        EndpointKey     = qna.EndpointKey,
                        Host            = qna.Hostname,
                    };

                    var qnaMaker = new MyAppInsightsQnAMaker(qnaEndpoint, null, logUserName: false, logOriginalMessage: false);
                    qnaServices.Add(qna.Name, qnaMaker);

                    break;
                }

                case ServiceTypes.AppInsights:
                {
                    var appInsights = (AppInsightsService)service;
                    if (appInsights == null)
                    {
                        throw new InvalidOperationException("The Application Insights is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(appInsights.InstrumentationKey))
                    {
                        throw new InvalidOperationException("The Application Insights Instrumentation Key ('instrumentationKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey);
                    telemetryClient = new TelemetryClient(telemetryConfig);
                    telemetryClient.InstrumentationKey = appInsights.InstrumentationKey;
                    break;
                }
                }
            }

            var connectedServices = new BotServices(telemetryClient, qnaServices);

            return(connectedServices);
        }
示例#32
0
 public LiveStreamProvider(TelemetryConfiguration configuration)
 {
     this.configuration = configuration;
 }
 public void TelemetryInitializersReturnsThreadSafeList()
 {
     var configuration = new TelemetryConfiguration();
     Assert.Equal(typeof(SnapshottingList<ITelemetryInitializer>), configuration.TelemetryInitializers.GetType());
 }
示例#34
0
 private static int GetTelemetryProcessorsCountInConfiguration <T>(TelemetryConfiguration telemetryConfiguration)
 {
     return(telemetryConfiguration.TelemetryProcessors.Where(processor => processor.GetType() == typeof(T)).Count());
 }
 public FilterWithMetricsWorker(ILogger <FilteringWorker> logger)
 {
     _logger       = logger;
     configuration = TelemetryConfigurationExtensions.CreateConfiguration().ConfigureFilteringWithMetrics();
 }
示例#36
0
 public DocumentProcessor(IConfiguration config, TelemetryConfiguration telemetryConfig)
 {
     this.config          = config;
     this.telemetryClient = new TelemetryClient(telemetryConfig);
 }
        private void RecordNormalMetric(TelemetryConfiguration telemetryPipeline)
        {
            MetricSeries durationMeric = telemetryPipeline.GetMetricManager().CreateNewSeries(
                "Item Add duration",
                new MetricSeriesConfigurationForMeasurement(restrictToUInt32Values: false));

            MockContainerDataStructure dataStructure = new MockContainerDataStructure((c) => TimeSpan.FromSeconds(c));

            DateTimeOffset experimentStart = new DateTimeOffset(2017, 9, 14, 0, 0, 0, TimeSpan.Zero);

            // Stop the default minute-ly cycle so that it does not interfere with our virtual time debugging:
            Task fireAndForget = telemetryPipeline.GetMetricManager().StopDefaultAggregationCycleAsync();

            telemetryPipeline.GetMetricManager().StartOrCycleAggregators(CycleKind.Custom, experimentStart, futureFilter: null);

            const int ExperimentLengthSecs = 60 * 10;
            const int IntervalLengthSecs   = 60;

            int totalSecs    = 0;
            int intervalSecs = 0;

            int       itemsThisTime   = 0;
            const int maxItemsAtATime = 4;

            int operationsCount = 0;

            while (totalSecs < ExperimentLengthSecs)
            {
                itemsThisTime = (itemsThisTime + 1) % maxItemsAtATime;

                int addItemCount    = 1 + (itemsThisTime + 1) % maxItemsAtATime;
                int removeItemCount = 1 + itemsThisTime % maxItemsAtATime;

                Trace.WriteLine($"{totalSecs})");
                Trace.WriteLine(addItemCount);
                Trace.WriteLine(removeItemCount);
                Trace.WriteLine("");

                TimeSpan duration;

                dataStructure.AddItems(addItemCount, out duration);
                operationsCount++;

                int durationSecs = (int)duration.TotalSeconds;
                durationMeric.TrackValue(durationSecs);

                totalSecs    += durationSecs;
                intervalSecs += durationSecs;

                dataStructure.RemoveItems(removeItemCount, out duration);
                operationsCount++;

                durationSecs = (int)duration.TotalSeconds;
                durationMeric.TrackValue(durationSecs);

                totalSecs    += durationSecs;
                intervalSecs += durationSecs;

                if (intervalSecs >= IntervalLengthSecs)
                {
                    AggregationPeriodSummary aggregatedMetrics = telemetryPipeline.GetMetricManager().StartOrCycleAggregators(
                        CycleKind.Custom,
                        experimentStart.AddSeconds(totalSecs),
                        futureFilter: null);
                    Assert.IsNotNull(aggregatedMetrics);

                    IReadOnlyList <MetricAggregate> aggregates = aggregatedMetrics.NonpersistentAggregates;
                    Assert.IsNotNull(aggregates);
                    Assert.AreEqual(1, aggregates.Count);

                    MetricAggregate aggregate = aggregates[0];
                    Assert.IsNotNull(aggregates);

                    Assert.AreEqual(1.0, aggregate.Data["Min"]);
                    Assert.AreEqual(4.0, aggregate.Data["Max"]);
                    Assert.AreEqual(operationsCount, aggregate.Data["Count"]);
                    Assert.AreEqual("Item Add duration", aggregate.MetricId);
                    Assert.IsNotNull(aggregate.Dimensions);
                    Assert.AreEqual(0, aggregate.Dimensions.Count);
                    Assert.AreEqual((double)intervalSecs, aggregate.Data["Sum"]);
                    Assert.AreEqual(experimentStart.AddSeconds(totalSecs - intervalSecs), aggregate.AggregationPeriodStart);

                    intervalSecs   %= IntervalLengthSecs;
                    operationsCount = 0;

                    Assert.AreEqual(0, intervalSecs, "For the above to work, the number of wirtual secs must exactly fit into IntervalLengthSecs.");
                }
            }
            {
                AggregationPeriodSummary aggregatedMetrics = telemetryPipeline.GetMetricManager().StartOrCycleAggregators(
                    CycleKind.Custom,
                    experimentStart.AddSeconds(totalSecs),
                    futureFilter: null);
                Assert.IsNotNull(aggregatedMetrics);

                IReadOnlyList <MetricAggregate> aggregates = aggregatedMetrics.NonpersistentAggregates;
                Assert.IsNotNull(aggregates);
                Assert.AreEqual(0, aggregates.Count);
            }
            {
                durationMeric.TrackValue("7");
                durationMeric.TrackValue("8");
                durationMeric.TrackValue("9.0");
                totalSecs += 24;
            }
            {
                AggregationPeriodSummary aggregatedMetrics = telemetryPipeline.GetMetricManager().StopAggregators(
                    CycleKind.Custom,
                    experimentStart.AddSeconds(totalSecs));
                Assert.IsNotNull(aggregatedMetrics);

                IReadOnlyList <MetricAggregate> aggregates = aggregatedMetrics.NonpersistentAggregates;
                Assert.IsNotNull(aggregates);

                MetricAggregate aggregate = aggregates[0];
                Assert.IsNotNull(aggregates);

                Assert.AreEqual(7.0, aggregate.Data["Min"]);
                Assert.AreEqual(9.0, aggregate.Data["Max"]);
                Assert.AreEqual(3, aggregate.Data["Count"]);
                Assert.AreEqual("Item Add duration", aggregate.MetricId);
                Assert.IsNotNull(aggregate.Dimensions);
                Assert.AreEqual(0, aggregate.Dimensions.Count);
                Assert.AreEqual(24.0, aggregate.Data["Sum"]);
                Assert.AreEqual(experimentStart.AddSeconds(totalSecs - 24), aggregate.AggregationPeriodStart);
            }
        }
        public static async Task Run([TimerTrigger("0 */7 * * * *", RunOnStartup = false /* Only set to true to test locally! */)] TimerInfo myTimer,
                                     ILogger log,
                                     Microsoft.Azure.WebJobs.ExecutionContext context,
                                     CancellationToken cancellationToken)
        {
            log.LogInformation($"GenerateTelemetryJob Timer trigger function executed at: {DateTime.UtcNow.ToTelemetryString()}");

            // Read the configuration
            IConfigurationRoot config = new ConfigurationBuilder()
                                        .SetBasePath(context.FunctionAppDirectory)
                                        .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                        .AddEnvironmentVariables()
                                        .Build();

            // Setting the target application insight
            TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();

            configuration.InstrumentationKey = config["InstrumentationKey"];

            // Generating the list of telemetry events to emit
            SortedSet <TelemetryItem>   items    = new SortedSet <TelemetryItem>();
            List <TelemetryItemBuilder> builders = new List <TelemetryItemBuilder> {
                new TelemetryPageViewBuilder()
            };

            // Each tenants emits a random number of operations.
            // The number of users is TenantId * 2.
            // The telemetry item emitted is random as well.
            // A user hits always the same node.
            Random rand            = new Random();
            int    numberOfTenants = rand.Next(1, 10);
            int    maxDelay        = (int)FunctionRunDuration.TotalMilliseconds;

            for (int tenantId = 1; tenantId <= numberOfTenants; tenantId++)
            {
                int maxUserId       = tenantId * 2;
                int numOfOperations = rand.Next(1, 50);
                for (int j = 1; j < numOfOperations; j++)
                {
                    int userId = rand.Next(1, maxUserId + 1);
                    builders[rand.Next(0, builders.Count)].Build(
                        rand.Next(1, maxDelay),
                        rand.Next(1, 100),
                        tenantId,
                        userId,
                        userId % NumberOfNodes,
                        rand.Next(1, maxDelay)
                        ).ForEach(t => items.Add(t));
                }
            }

            log.LogInformation($"About to emit {items.Count} telemetry events for {numberOfTenants} tenants.");

            // Emitting telemetry
            var telemetryClient = new TelemetryClient(configuration);

            telemetryClient.Context.InstrumentationKey = configuration.InstrumentationKey;

            int delay = 0;

            foreach (TelemetryItem item in items)
            {
                await Task.Delay(item.Delay - delay, cancellationToken);

                delay = item.Delay;
                log.LogDebug(new EventId(1), item.ToString());
                item.Send(telemetryClient);
            }

            log.LogInformation($"GenerateTelemetryJob Timer trigger function completed at: {DateTime.UtcNow.ToTelemetryString()}");
        }
示例#39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ApplicationInsightsExporter"/> class.
 /// This exporter allows to send OpenTelemetry data to Azure Application Insights.
 /// </summary>
 /// <param name="exporter">Exporter to get traces and metrics from.</param>
 /// <param name="viewManager">View manager to get stats from.</param>
 /// <param name="telemetryConfiguration">Telemetry configuration to use to report telemetry.</param>
 public ApplicationInsightsExporter(ISpanExporter exporter, IViewManager viewManager, TelemetryConfiguration telemetryConfiguration)
 {
     this.exporter               = exporter;
     this.viewManager            = viewManager;
     this.telemetryConfiguration = telemetryConfiguration;
 }
示例#40
0
        public SkillConfiguration(BotConfiguration botConfiguration, string[] supportedProviders, string[] parameters, Dictionary <string, object> configuration)
        {
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.AppInsights:
                {
                    var appInsights     = service as AppInsightsService;
                    var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey);
                    TelemetryClient = new TelemetryClient(telemetryConfig);
                    break;
                }

                case ServiceTypes.Luis:
                {
                    var luis    = service as LuisService;
                    var luisApp = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                    LuisServices.Add(service.Id, new LuisRecognizer(luisApp));
                    break;
                }

                case ServiceTypes.Generic:
                {
                    if (service.Name == "Authentication")
                    {
                        var auth = service as GenericService;

                        foreach (var provider in supportedProviders)
                        {
                            auth.Configuration.TryGetValue(provider, out var connectionName);

                            if (connectionName != null)
                            {
                                AuthenticationConnections.Add(provider, connectionName);
                            }
                        }
                    }

                    break;
                }
                }
            }

            if (parameters != null)
            {
                // add the parameters the skill needs
                foreach (var parameter in parameters)
                {
                    // Initialize each parameter to null. Needs to be set later by the bot.
                    Properties.Add(parameter, null);
                }
            }

            if (configuration != null)
            {
                // add the additional keys the skill needs
                foreach (var set in configuration)
                {
                    Properties.Add(set.Key, set.Value);
                }
            }
        }
        public TelemetryService()
        {
            TelemetryConfiguration configuration = TelemetryConfiguration.CreateDefault();

            _telemetryClient = new TelemetryClient(configuration);
        }
 public void Initialize(TelemetryConfiguration configuration)
 {
 }
 public PilotsControllerTests()
 {
     _fakeBookings    = GenerateMockBookings();
     _telemetryClient = new TelemetryClient(TelemetryConfiguration.CreateDefault());
 }
 public void InstrumentationKeyCanBeSetToProgrammaticallyDefineInstrumentationKeyForAllContextsInApplication()
 {
     var configuration = new TelemetryConfiguration();
     configuration.InstrumentationKey = "99C6A712-B2B5-46E3-97F4-F83F69999324";
     Assert.Equal("99C6A712-B2B5-46E3-97F4-F83F69999324", configuration.InstrumentationKey);
 }
示例#45
0
 public SpaFallback(IHostingEnvironment env, ISpaPrerenderer spaPrerenderer, TelemetryConfiguration config)
 {
     _env            = env;
     _spaPrerenderer = spaPrerenderer;
     _htmlProps      = new HtmlProps(env.WebRootPath, config.InstrumentationKey);
 }
 public override void Initialize(TelemetryConfiguration configuration)
 {
     this.OnInitialize(configuration);
 }
        /// <summary>
        /// Initialize method is called after all configuration properties have been loaded from the configuration.
        /// </summary>
        public void Initialize()
        {
            if (configuration != null)
            {
                this.configuration = TelemetryConfiguration.Active;
            }

            // ToDo: Implement Initialize method
        }
 public PersistenceChannelTest()
 {
     this.configuration = new TelemetryConfiguration();            
 }
 public void InstrumentationKeyThrowsArgumentNullExceptionWhenNewValueIsNullToAvoidNullReferenceExceptionWhenAccessingPropertyValue()
 {
     var configuration = new TelemetryConfiguration();
     Xunit.Assert.Throws<ArgumentNullException>(() => configuration.InstrumentationKey = null);
 }
        public void TelemetryChannelCanBeSetByUserToReplaceDefaultChannelForTesting()
        {
            var configuration = new TelemetryConfiguration();

            var customChannel = new StubTelemetryChannel();
            configuration.TelemetryChannel = customChannel;

            Assert.Same(customChannel, configuration.TelemetryChannel);
        }
示例#51
0
        private static TelemetryClient CreateTelemetryClient()
        {
            var config = new TelemetryConfiguration(GetApplicationInsightsKey());

            return(new TelemetryClient(config));
        }
 public void TelemetryChannelIsNullByDefaultToAvoidLockEscalation()
 {
     var configuration = new TelemetryConfiguration();
     Assert.Null(configuration.TelemetryChannel);
 }
 private static List<ICounterValue> CreateEmptyDictionary(TelemetryConfiguration configuration)
 {
     return new List<ICounterValue>();
 }
 public ChangePassword(IHttpClientFactory httpClientFactory, IGremlinClient gremlinClient, IB2CGraphClient b2cGraphClient, TelemetryConfiguration telemetryConfiguration) : base(httpClientFactory, gremlinClient, b2cGraphClient, telemetryConfiguration)
 {
     // Calls base
 }
 public void InstrumentationKeyIsEmptyStringByDefaultToAvoidNullReferenceExceptionWhenAccessingPropertyValue()
 {
     var configuration = new TelemetryConfiguration();
     Assert.Equal(0, configuration.InstrumentationKey.Length);
 }
示例#56
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TelemetryLoggerMiddleware"/> class.
        /// </summary>
        /// <param name="instrumentationKey">The Application Insights instrumentation key.  See Application Insights for more information.</param>
        /// <param name="logUserName"> (Optional) Enable/Disable logging user name within Application Insights.</param>
        /// <param name="logOriginalMessage"> (Optional) Enable/Disable logging original message name within Application Insights.</param>
        /// <param name="config"> (Optional) TelemetryConfiguration to use for Application Insights.</param>
        public TelemetryLoggerMiddleware(string instrumentationKey, bool logUserName = false, bool logOriginalMessage = false, TelemetryConfiguration config = null)
        {
            if (string.IsNullOrWhiteSpace(instrumentationKey))
            {
                throw new ArgumentNullException(nameof(instrumentationKey));
            }

            _telemetryClient   = new TelemetryClient();
            LogUserName        = logUserName;
            LogOriginalMessage = logOriginalMessage;
        }
            public void AddsItselfToTelemetryInitializersToSetSessionIdForAllTelemetryTypes()
            {
                ServiceLocator.AddService<IApplicationService>(new ApplicationService());
                var module = new SessionTelemetryModule(new StubPlatform(), new StubClock());
                var configuration = new TelemetryConfiguration();
                configuration.TelemetryChannel = new InMemoryChannel();
                module.Initialize();

                Assert.Contains(module, TelemetryConfiguration.Active.TelemetryInitializers);
            }
 void ITelemetryModule.Initialize(TelemetryConfiguration configuration)
 {
     this.telemetryClient = new TelemetryClient(configuration);
     this.telemetryClient.Context.GetInternalContext().SdkVersion = "wcf: " + SdkVersionUtils.GetAssemblyVersion();
 }
示例#59
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotServices"/> class.
        /// </summary>
        /// <param name="botConfiguration">The <see cref="BotConfiguration"/> instance for the bot.</param>
        /// <param name="skills">List of <see cref="SkillDefinition"/> for loading skill configurations.</param>
        /// <param name="languageModels">The locale specifc language model configs for each supported language.</param>
        /// <param name="skillEventsConfig">The configuration for skill events.</param>
        public BotServices(BotConfiguration botConfiguration, Dictionary <string, Dictionary <string, string> > languageModels, List <SkillDefinition> skills, List <SkillEvent> skillEventsConfig)
        {
            // Create service clients for each service in the .bot file.
            foreach (var service in botConfiguration.Services)
            {
                switch (service.Type)
                {
                case ServiceTypes.AppInsights:
                {
                    var appInsights = (AppInsightsService)service;
                    if (appInsights == null)
                    {
                        throw new InvalidOperationException("The Application Insights is not configured correctly in your '.bot' file.");
                    }

                    if (string.IsNullOrWhiteSpace(appInsights.InstrumentationKey))
                    {
                        throw new InvalidOperationException("The Application Insights Instrumentation Key ('instrumentationKey') is required to run this sample.  Please update your '.bot' file.");
                    }

                    var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey);
                    TelemetryClient = new TelemetryClient(telemetryConfig)
                    {
                        InstrumentationKey = appInsights.InstrumentationKey,
                    };

                    break;
                }

                case ServiceTypes.CosmosDB:
                {
                    var cosmos = service as CosmosDbService;

                    CosmosDbOptions = new CosmosDbStorageOptions
                    {
                        AuthKey          = cosmos.Key,
                        CollectionId     = cosmos.Collection,
                        DatabaseId       = cosmos.Database,
                        CosmosDBEndpoint = new Uri(cosmos.Endpoint),
                    };

                    break;
                }

                case ServiceTypes.Generic:
                {
                    if (service.Name == "Authentication")
                    {
                        var authentication = service as GenericService;
                        AuthenticationConnections = authentication.Configuration;
                    }

                    break;
                }
                }
            }

            // Create locale configuration object for each language config in appsettings.json
            foreach (var language in languageModels)
            {
                if (language.Value.TryGetValue("botFilePath", out var botFilePath) && File.Exists(botFilePath))
                {
                    var botFileSecret = language.Value["botFileSecret"];
                    var config        = BotConfiguration.Load(botFilePath, !string.IsNullOrEmpty(botFileSecret) ? botFileSecret : null);

                    var localeConfig = new LocaleConfiguration
                    {
                        Locale = language.Key
                    };

                    foreach (var service in config.Services)
                    {
                        switch (service.Type)
                        {
                        case ServiceTypes.Dispatch:
                        {
                            var dispatch = service as DispatchService;
                            if (dispatch == null)
                            {
                                throw new InvalidOperationException("The Dispatch service is not configured correctly in your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(dispatch.AppId))
                            {
                                throw new InvalidOperationException("The Dispatch Luis Model Application Id ('appId') is required to run this sample.  Please update your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(dispatch.SubscriptionKey))
                            {
                                throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample.  Please update your '.bot' file.");
                            }

                            var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.SubscriptionKey, dispatch.GetEndpoint());
                            localeConfig.DispatchRecognizer = new TelemetryLuisRecognizer(dispatchApp);
                            break;
                        }

                        case ServiceTypes.Luis:
                        {
                            var luis = service as LuisService;
                            if (luis == null)
                            {
                                throw new InvalidOperationException("The Luis service is not configured correctly in your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(luis.AppId))
                            {
                                throw new InvalidOperationException("The Luis Model Application Id ('appId') is required to run this sample.  Please update your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(luis.AuthoringKey))
                            {
                                throw new InvalidOperationException("The Luis Authoring Key ('authoringKey') is required to run this sample.  Please update your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(luis.SubscriptionKey))
                            {
                                throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample.  Please update your '.bot' file.");
                            }

                            if (string.IsNullOrWhiteSpace(luis.Region))
                            {
                                throw new InvalidOperationException("The Region ('region') is required to run this sample.  Please update your '.bot' file.");
                            }

                            var luisApp    = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
                            var recognizer = new TelemetryLuisRecognizer(luisApp);
                            localeConfig.LuisServices.Add(service.Id, recognizer);
                            break;
                        }

                        case ServiceTypes.QnA:
                        {
                            var qna         = service as QnAMakerService;
                            var qnaEndpoint = new QnAMakerEndpoint()
                            {
                                KnowledgeBaseId = qna.KbId,
                                EndpointKey     = qna.EndpointKey,
                                Host            = qna.Hostname,
                            };
                            var qnaMaker = new TelemetryQnAMaker(qnaEndpoint);
                            localeConfig.QnAServices.Add(qna.Id, qnaMaker);
                            break;
                        }
                        }
                    }

                    LocaleConfigurations.Add(language.Key, localeConfig);
                }
            }

            // Create a skill configurations for each skill in appsettings.json
            foreach (var skill in skills)
            {
                var skillConfig = new SkillConfiguration()
                {
                    CosmosDbOptions = CosmosDbOptions
                };

                foreach (var localeConfig in LocaleConfigurations)
                {
                    skillConfig.LocaleConfigurations.Add(localeConfig.Key, new LocaleConfiguration
                    {
                        LuisServices = localeConfig.Value.LuisServices.Where(l => skill.LuisServiceIds.Contains(l.Key) == true).ToDictionary(l => l.Key, l => l.Value)
                    });
                }

                if (skill.SupportedProviders != null)
                {
                    foreach (var provider in skill.SupportedProviders)
                    {
                        var matches = AuthenticationConnections.Where(x => x.Value == provider);

                        foreach (var match in matches)
                        {
                            skillConfig.AuthenticationConnections.Add(match.Key, match.Value);
                        }
                    }
                }

                foreach (var set in skill.Configuration)
                {
                    skillConfig.Properties.Add(set.Key, set.Value);
                }

                SkillDefinitions.Add(skill);
                SkillConfigurations.Add(skill.Id, skillConfig);
                SkillEvents = skillEventsConfig != null?skillEventsConfig.ToDictionary(i => i.Event) : null;
            }
        }
 public void TelemetryInitializersReturnsAnEmptyListByDefaultToAvoidNullReferenceExceptionsInUserCode()
 {
     var configuration = new TelemetryConfiguration();
     Assert.Equal(0, configuration.TelemetryInitializers.Count);
 }