Exemple #1
0
        public async Task WhenCreatingQueryRunInfoForTooManyResourcesThenAnExceptionIsThrown()
        {
            const int             TooManyResourcesCount = 11;
            IQueryRunInfoProvider provider = new QueryRunInfoProvider(this.azureResourceManagerClientMock.Object);

            try
            {
                List <ResourceIdentifier> resources = Enumerable.Range(1, TooManyResourcesCount)
                                                      .Select(i => new ResourceIdentifier(ResourceType.ApplicationInsights, SubscriptionId + i, ResourceGroupName + i, ResourceName + i)).ToList();
                await provider.GetQueryRunInfoAsync(resources, default(CancellationToken));

                Assert.Fail("An exception should be thrown");
            }
            catch (QueryClientInfoProviderException)
            {
            }

            try
            {
                List <ResourceIdentifier> resources = Enumerable.Range(1, TooManyResourcesCount)
                                                      .Select(i => new ResourceIdentifier(ResourceType.LogAnalytics, SubscriptionId + i, ResourceGroupName + i, ResourceName + i)).ToList();
                await provider.GetQueryRunInfoAsync(resources, default(CancellationToken));

                Assert.Fail("An exception should be thrown");
            }
            catch (QueryClientInfoProviderException)
            {
            }
        }
Exemple #2
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Application.Startup" /> event.
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.</param>
        protected override void OnStartup(StartupEventArgs e)
        {
            ITracer stringTracer        = new StringTracer(string.Empty);
            ITracer consoleTracer       = new ConsoleTracer(string.Empty);
            var     smartDetectorLoader = new SmartDetectorLoader(consoleTracer);

            // *Temporary*: if package file path wasn't accepted, raise file selection window to allow package file selection.
            // This option should be removed before launching version for customers (bug for tracking: 1177247)
            string smartDetectorPackagePath = e.Args.Length != 1 ?
                                              this.GetSmartDetectorPackagePath() :
                                              Diagnostics.EnsureStringNotNullOrWhiteSpace(() => e.Args[0]);

            SmartDetectorPackage smartDetectorPackage;

            using (var fileStream = new FileStream(smartDetectorPackagePath, FileMode.Open))
            {
                smartDetectorPackage = SmartDetectorPackage.CreateFromStream(fileStream, consoleTracer);
            }

            SmartDetectorManifest smartDetectorManifest = smartDetectorPackage.Manifest;
            ISmartDetector        detector = smartDetectorLoader.LoadSmartDetector(smartDetectorPackage);

            // Authenticate the user to Active Directory
            var authenticationServices = new AuthenticationServices();

            authenticationServices.AuthenticateUser();
            ICredentialsFactory credentialsFactory = new ActiveDirectoryCredentialsFactory(authenticationServices);

            IAzureResourceManagerClient azureResourceManagerClient = new AzureResourceManagerClient(credentialsFactory, consoleTracer);

            // Create analysis service factory
            var queryRunInroProvider = new QueryRunInfoProvider(azureResourceManagerClient);
            var httpClientWrapper    = new HttpClientWrapper();
            IAnalysisServicesFactory analysisServicesFactory = new AnalysisServicesFactory(consoleTracer, httpClientWrapper, credentialsFactory, azureResourceManagerClient, queryRunInroProvider);

            // Create state repository factory
            IStateRepositoryFactory stateRepositoryFactory = new InMemoryStateRepositoryFactory();

            var smartDetectorRunner = new SmartDetectorRunner(detector, analysisServicesFactory, queryRunInroProvider, smartDetectorManifest, stateRepositoryFactory, smartDetectorManifest.Id, stringTracer);

            // Create a Unity container with all the required models and view models registrations
            Container = new UnityContainer();
            Container
            .RegisterInstance(stringTracer)
            .RegisterInstance(new AlertsRepository())
            .RegisterInstance(authenticationServices)
            .RegisterInstance(azureResourceManagerClient)
            .RegisterInstance(detector)
            .RegisterInstance(smartDetectorManifest)
            .RegisterInstance(analysisServicesFactory)
            .RegisterInstance(smartDetectorRunner)
            .RegisterInstance(stateRepositoryFactory);
        }
Exemple #3
0
        public async Task WhenCreatingQueryRunInfoForApplicationInsightsResourcesThenTheCorrectInfoIsCreated()
        {
            var resources = new List <ResourceIdentifier>()
            {
                new ResourceIdentifier(ResourceType.ApplicationInsights, SubscriptionId, ResourceGroupName, ResourceName)
            };

            IQueryRunInfoProvider provider = new QueryRunInfoProvider(this.azureResourceManagerClientMock.Object);

            QueryRunInfo queryRunInfo = await provider.GetQueryRunInfoAsync(resources, default(CancellationToken));

            Assert.IsNotNull(queryRunInfo, "Query run information is null");
            Assert.AreEqual(TelemetryDbType.ApplicationInsights, queryRunInfo.Type, "Wrong telemetry DB type");
            CollectionAssert.AreEqual(new[] { resources.First().ToResourceId() }, queryRunInfo.ResourceIds.ToArray(), "Wrong resource IDs");
        }
Exemple #4
0
        public async Task WhenCreatingQueryRunInfoForLogAnalyticsResourcesThenTheCorrectInfoIsCreated()
        {
            var resources = new List <ResourceIdentifier>()
            {
                new ResourceIdentifier(ResourceType.LogAnalytics, SubscriptionId, ResourceGroupName, WorkspaceNames[0]),
                new ResourceIdentifier(ResourceType.LogAnalytics, SubscriptionId, ResourceGroupName, WorkspaceNames[1])
            };

            string[] resourceIds               = resources.Select(r => r.ToResourceId()).ToArray();
            IQueryRunInfoProvider provider     = new QueryRunInfoProvider(this.azureResourceManagerClientMock.Object);
            QueryRunInfo          queryRunInfo = await provider.GetQueryRunInfoAsync(resources, default(CancellationToken));

            Assert.IsNotNull(queryRunInfo, "Query run information is null");
            Assert.AreEqual(TelemetryDbType.LogAnalytics, queryRunInfo.Type, "Wrong telemetry DB type");
            CollectionAssert.AreEqual(resourceIds, queryRunInfo.ResourceIds.ToArray(), "Wrong resource IDs");
        }
Exemple #5
0
        public async Task WhenCreatingQueryRunInfoForResourcesWithMultipleSubscriptionsThenAllWorkspacesAreReturned()
        {
            var resources = new List <ResourceIdentifier>()
            {
                new ResourceIdentifier(ResourceType.VirtualMachine, SubscriptionId + "1", ResourceGroupName + "1", ResourceName + "1"),
                new ResourceIdentifier(ResourceType.VirtualMachine, SubscriptionId + "2", ResourceGroupName + "2", ResourceName + "2")
            };

            var workspaces = new List <ResourceIdentifier>()
            {
                new ResourceIdentifier(ResourceType.LogAnalytics, SubscriptionId + "1", ResourceGroupName + "1", ResourceName + "1"),
                new ResourceIdentifier(ResourceType.LogAnalytics, SubscriptionId + "2", ResourceGroupName + "2", ResourceName + "2"),
                new ResourceIdentifier(ResourceType.LogAnalytics, SubscriptionId + "2", ResourceGroupName + "2", ResourceName + "3")
            };

            this.azureResourceManagerClientMock
            .Setup(x => x.GetAllResourcesInSubscriptionAsync(SubscriptionId + "1", It.IsAny <IEnumerable <ResourceType> >(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new List <ResourceIdentifier>()
            {
                workspaces[0]
            });
            this.azureResourceManagerClientMock
            .Setup(x => x.GetAllResourcesInSubscriptionAsync(SubscriptionId + "2", It.IsAny <IEnumerable <ResourceType> >(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new List <ResourceIdentifier>()
            {
                workspaces[1], workspaces[2]
            });
            this.azureResourceManagerClientMock
            .Setup(x => x.GetLogAnalyticsWorkspaceIdAsync(It.Is <ResourceIdentifier>(identifier => identifier.ResourceType == ResourceType.LogAnalytics), It.IsAny <CancellationToken>()))
            .ReturnsAsync("workspaceId");

            IQueryRunInfoProvider provider     = new QueryRunInfoProvider(this.azureResourceManagerClientMock.Object);
            QueryRunInfo          queryRunInfo = await provider.GetQueryRunInfoAsync(resources, default(CancellationToken));

            Assert.IsNotNull(queryRunInfo, "Query run information is null");
            this.azureResourceManagerClientMock.Verify(x => x.GetAllResourcesInSubscriptionAsync(SubscriptionId + "1", It.IsAny <IEnumerable <ResourceType> >(), It.IsAny <CancellationToken>()), Times.Once);
            this.azureResourceManagerClientMock.Verify(x => x.GetAllResourcesInSubscriptionAsync(SubscriptionId + "2", It.IsAny <IEnumerable <ResourceType> >(), It.IsAny <CancellationToken>()), Times.Once);
            CollectionAssert.AreEqual(workspaces.Select(w => w.ToResourceId()).ToArray(), queryRunInfo.ResourceIds.ToArray());
        }
Exemple #6
0
        public async Task WhenCreatingQueryRunInfoForMixedResourcesThenAnExceptionIsThrown()
        {
            IQueryRunInfoProvider provider = new QueryRunInfoProvider(this.azureResourceManagerClientMock.Object);

            try
            {
                var resources = new List <ResourceIdentifier>()
                {
                    new ResourceIdentifier(ResourceType.ApplicationInsights, SubscriptionId, ResourceGroupName, ResourceName + "111"),
                    new ResourceIdentifier(ResourceType.VirtualMachine, SubscriptionId, ResourceGroupName, ResourceName)
                };

                await provider.GetQueryRunInfoAsync(resources, default(CancellationToken));

                Assert.Fail("An exception should be thrown");
            }
            catch (QueryClientInfoProviderException)
            {
            }

            try
            {
                var resources = new List <ResourceIdentifier>()
                {
                    new ResourceIdentifier(ResourceType.LogAnalytics, SubscriptionId, ResourceGroupName, WorkspaceNames[0]),
                    new ResourceIdentifier(ResourceType.ApplicationInsights, SubscriptionId, ResourceGroupName, ResourceName)
                };

                await provider.GetQueryRunInfoAsync(resources, default(CancellationToken));

                Assert.Fail("An exception should be thrown");
            }
            catch (QueryClientInfoProviderException)
            {
            }
        }
Exemple #7
0
 public async Task WhenCreatingQueryRunInfoForEmptyResourcesThenAnExceptionIsThrown()
 {
     IQueryRunInfoProvider provider = new QueryRunInfoProvider(this.azureResourceManagerClientMock.Object);
     await provider.GetQueryRunInfoAsync(new List <ResourceIdentifier>(), default(CancellationToken));
 }
        /// <summary>
        /// Raises the <see cref="Application.Startup" /> event.
        /// </summary>
        /// <param name="e">A <see cref="StartupEventArgs" /> that contains the event data.</param>
        protected override void OnStartup(StartupEventArgs e)
        {
            // Cleanup previous temp folders (that are at least 2 days old), and create a new temp folder
            FileSystemExtensions.CleanupTempFolders(TempSubFolderName, 48);
            tempFolder = FileSystemExtensions.CreateTempFolder(TempSubFolderName);

            NotificationService notificationService = new NotificationService();
            IObservableTracer   stringTracer        = new StringTracer(string.Empty);
            IExtendedTracer     consoleTracer       = new ConsoleTracer(string.Empty);
            var smartDetectorLoader = new SmartDetectorLoader(tempFolder, consoleTracer);

            // *Temporary*: if package file path wasn't accepted, raise file selection window to allow package file selection.
            // This option should be removed before launching version for customers (bug for tracking: 1177247)
            string smartDetectorPackagePath = e.Args.Length != 1 ?
                                              GetSmartDetectorPackagePath() :
                                              Diagnostics.EnsureStringNotNullOrWhiteSpace(() => e.Args[0]);

            SmartDetectorPackage smartDetectorPackage;

            using (var fileStream = new FileStream(smartDetectorPackagePath, FileMode.Open))
            {
                smartDetectorPackage = SmartDetectorPackage.CreateFromStream(fileStream, consoleTracer);
            }

            try
            {
                SmartDetectorManifest smartDetectorManifest = smartDetectorPackage.Manifest;
                ISmartDetector        detector = smartDetectorLoader.LoadSmartDetector(smartDetectorPackage);

                // Authenticate the user to Active Directory
                IAuthenticationServices authenticationServices = new AuthenticationServices();
                authenticationServices.AuthenticateUser();
                ICredentialsFactory credentialsFactory = new ActiveDirectoryCredentialsFactory(authenticationServices);
                IHttpClientWrapper  httpClientWrapper  = new HttpClientWrapper();
                IExtendedAzureResourceManagerClient azureResourceManagerClient = new ExtendedAzureResourceManagerClient(credentialsFactory, consoleTracer);

                // Create analysis service factory
                var queryRunInfoProvider = new QueryRunInfoProvider(azureResourceManagerClient);
                IInternalAnalysisServicesFactory analysisServicesFactory = new AnalysisServicesFactory(consoleTracer, httpClientWrapper, credentialsFactory, azureResourceManagerClient, queryRunInfoProvider);

                // Create state repository factory
                IStateRepositoryFactory stateRepositoryFactory = new EmulationStateRepositoryFactory();

                // Create a system process client
                ISystemProcessClient systemProcessClient = new SystemProcessClient();

                // Load user settings
                var userSettings = UserSettings.LoadUserSettings();

                IEmulationSmartDetectorRunner smartDetectorRunner = new SmartDetectorRunner(
                    detector,
                    analysisServicesFactory,
                    queryRunInfoProvider,
                    smartDetectorManifest,
                    stateRepositoryFactory,
                    azureResourceManagerClient,
                    stringTracer);

                // Create a Unity container with all the required models and view models registrations
                Container = new UnityContainer();
                Container
                .RegisterInstance(notificationService)
                .RegisterInstance(stringTracer)
                .RegisterInstance(new AlertsRepository())
                .RegisterInstance(authenticationServices)
                .RegisterInstance(azureResourceManagerClient)
                .RegisterInstance(detector)
                .RegisterInstance(smartDetectorManifest)
                .RegisterInstance(analysisServicesFactory)
                .RegisterInstance(smartDetectorRunner)
                .RegisterInstance(stateRepositoryFactory)
                .RegisterInstance(systemProcessClient)
                .RegisterInstance(userSettings);
            }
            catch (Exception exception)
            {
                var message = $"{exception.Message}. {Environment.NewLine}{exception.InnerException?.Message}";
                MessageBox.Show(message);
                Trace.WriteLine(message);
                Environment.Exit(1);
            }
        }