public async Task WhenCreatingApplicationInsightsClientWithTooManyResourcesThenAnExceptionIsThrown() { List <ResourceIdentifier> resources = Enumerable.Range(1, TooManyResourcesCount) .Select(i => new ResourceIdentifier(ResourceType.ApplicationInsights, SubscriptionId + i, ResourceGroupName + i, ResourceName + i)).ToList(); IAnalysisServicesFactory factory = new AnalysisServicesFactory(this.tracerMock.Object, this.httpClientWrapperMock.Object, this.credentialsFactoryMock.Object, this.azureResourceManagerClientMock.Object); await factory.CreateApplicationInsightsTelemetryDataClientAsync(resources, default(CancellationToken)); }
public async Task WhenCreatingMetricClientThenItIsCreatedSuccessfully() { IAnalysisServicesFactory factory = new AnalysisServicesFactory(this.tracerMock.Object, this.httpClientWrapperMock.Object, this.credentialsFactoryMock.Object, this.azureResourceManagerClientMock.Object); IMetricClient client = await factory.CreateMetricClientAsync(SubscriptionId, default(CancellationToken)); Assert.IsNotNull(client); Assert.IsTrue(client is MetricClient); }
public async Task WhenCreatingArmClientThenItIsCreatedSuccessfully() { IAnalysisServicesFactory factory = new AnalysisServicesFactory(this.tracerMock.Object, this.httpClientWrapperMock.Object, this.credentialsFactoryMock.Object, this.azureResourceManagerClientMock.Object, this.queryRunInfoProviderMock.Object); IAzureResourceManagerClient client = await factory.CreateArmClientAsync(default(CancellationToken)); Assert.IsNotNull(client); Assert.IsTrue(client == this.azureResourceManagerClientMock.Object); }
public async Task WhenCreatingApplicationInsightsClientWithEmptyResourcesListThenAnExceptionIsThrown() { var resources = new List <ResourceIdentifier>(); this.SetupTest(resources); IAnalysisServicesFactory factory = new AnalysisServicesFactory(this.tracerMock.Object, this.httpClientWrapperMock.Object, this.credentialsFactoryMock.Object, this.azureResourceManagerClientMock.Object); await factory.CreateApplicationInsightsTelemetryDataClientAsync(resources, default(CancellationToken)); }
public async Task WhenCreatingLogAnalyticsClientWithMixedResourcesOfLogAnalyticsAndApplicationInsightsThenAnExceptionIsThrown() { var resources = new List <ResourceIdentifier>() { new ResourceIdentifier(ResourceType.LogAnalytics, SubscriptionId, ResourceGroupName, WorkSpaceName), new ResourceIdentifier(ResourceType.ApplicationInsights, SubscriptionId, ResourceGroupName, ResourceName) }; IAnalysisServicesFactory factory = new AnalysisServicesFactory(this.tracerMock.Object, this.httpClientWrapperMock.Object, this.credentialsFactoryMock.Object, this.azureResourceManagerClientMock.Object); await factory.CreateLogAnalyticsTelemetryDataClientAsync(resources, default(CancellationToken)); }
public async Task WhenCreatingApplicationInsightsClientForRunInfoWithWrongTypeThenAnExceptionIsThrown() { var resources = new List <ResourceIdentifier>() { new ResourceIdentifier(ResourceType.VirtualMachine, SubscriptionId, ResourceGroupName, ResourceName) }; this.SetupTest(resources, TelemetryDbType.LogAnalytics, WorkspaceId); IAnalysisServicesFactory factory = new AnalysisServicesFactory(this.tracerMock.Object, this.httpClientWrapperMock.Object, this.credentialsFactoryMock.Object, this.azureResourceManagerClientMock.Object, this.queryRunInfoProviderMock.Object); await factory.CreateApplicationInsightsTelemetryDataClientAsync(resources, default(CancellationToken)); }
/// <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); }
public async Task WhenCreatingLogAnalyticsClientForSomeResourceThenTheCorrectClientIsCreated() { var resource = new ResourceIdentifier(ResourceType.VirtualMachine, SubscriptionId, ResourceGroupName, ResourceName); IAnalysisServicesFactory factory = new AnalysisServicesFactory(this.tracerMock.Object, this.httpClientWrapperMock.Object, this.credentialsFactoryMock.Object, this.azureResourceManagerClientMock.Object); LogAnalyticsClient client = await factory.CreateLogAnalyticsClientAsync(resource, default(CancellationToken)) as LogAnalyticsClient; Assert.IsNotNull(client); Assert.AreEqual( new Uri($"https://api.loganalytics.io/v1/subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.Compute/virtualMachines/{ResourceName}/query"), client.QueryUri, "Wrong query URI"); }
public async Task WhenCallingActivityLogClientWithMultiplePagesThenTheCorrectResponseIsReturned() { IAnalysisServicesFactory factory = new AnalysisServicesFactory(this.tracerMock.Object, this.httpClientWrapperMock.Object, this.credentialsFactoryMock.Object, this.azureResourceManagerClient, this.queryRunInfoProviderMock.Object); var resource = new ResourceIdentifier(ResourceType.Subscription, "subscriptionId", string.Empty, string.Empty); IActivityLogClient client = await factory.CreateActivityLogClientAsync(default(CancellationToken)); string nextLink = "https://management.azure.com/"; Uri nextLinkUri = new Uri(nextLink); JObject returnValue = new JObject { ["value"] = new JArray { new JObject { ["subscriptionId"] = "subId" } }, ["nextLink"] = nextLink }; JObject nextLinkReturnValue = new JObject { ["value"] = new JArray { new JObject { ["subscriptionId"] = "subId2" } } }; Uri requestUri = new Uri("https://management.azure.com/subscriptions/subscriptionId/providers/microsoft.insights/eventtypes/management/values?api-version=2015-04-01&$filter=eventTimestamp ge '2018-04-30 17:00:00Z' and eventTimestamp le '2018-04-30 23:00:00Z'"); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(returnValue.ToString()) }; HttpResponseMessage nextLinkResponse = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(nextLinkReturnValue.ToString()) }; this.httpClientWrapperMock.Setup(m => m.SendAsync(It.Is <HttpRequestMessage>(r => r.RequestUri == requestUri), It.IsAny <TimeSpan?>(), It.IsAny <CancellationToken>())).ReturnsAsync(response); this.httpClientWrapperMock.Setup(m => m.SendAsync(It.Is <HttpRequestMessage>(r => r.RequestUri == nextLinkUri), It.IsAny <TimeSpan?>(), It.IsAny <CancellationToken>())).ReturnsAsync(nextLinkResponse); await client.GetActivityLogAsync(resource, new DateTime(2018, 04, 30, 17, 0, 0, DateTimeKind.Utc), new DateTime(2018, 04, 30, 23, 0, 0), CancellationToken.None); this.httpClientWrapperMock.Verify(x => x.SendAsync(It.Is <HttpRequestMessage>(r => r.RequestUri == requestUri), It.IsAny <TimeSpan?>(), It.IsAny <CancellationToken>()), Times.Once); this.httpClientWrapperMock.Verify(x => x.SendAsync(It.Is <HttpRequestMessage>(r => r.RequestUri == nextLinkUri), It.IsAny <TimeSpan?>(), It.IsAny <CancellationToken>()), Times.Once); }
public async Task WhenCreatingLogAnalyticsClientForLogAnalyticsWorkspaceResourceThenTheCorrectClientIsCreated() { var resource = new ResourceIdentifier(ResourceType.LogAnalytics, SubscriptionId, ResourceGroupName, ResourceName); this.azureResourceManagerClientMock .Setup(m => m.GetLogAnalyticsWorkspaceIdAsync(resource, default(CancellationToken))) .ReturnsAsync("testWorkspaceId"); IAnalysisServicesFactory factory = new AnalysisServicesFactory(this.tracerMock.Object, this.httpClientWrapperMock.Object, this.credentialsFactoryMock.Object, this.azureResourceManagerClientMock.Object); LogAnalyticsClient client = await factory.CreateLogAnalyticsClientAsync(resource, default(CancellationToken)) as LogAnalyticsClient; Assert.IsNotNull(client); Assert.AreEqual(new Uri("https://api.loganalytics.io/v1/workspaces/testWorkspaceId/query"), client.QueryUri, "Wrong query URI"); }
public async Task WhenCreatingLogAnalyticsClientWithoutLogAnalyticsResourcesThenAnExceptionIsThrown() { var resources = new List <ResourceIdentifier>() { new ResourceIdentifier(ResourceType.VirtualMachine, SubscriptionId, ResourceGroupName, ResourceName) }; this.azureResourceManagerClientMock .Setup(x => x.GetAllResourcesInSubscriptionAsync(It.Is <string>(y => string.Equals(y, "subscriptionId", StringComparison.InvariantCulture)), It.IsAny <IEnumerable <ResourceType> >(), It.IsAny <CancellationToken>())) .ReturnsAsync(new List <ResourceIdentifier>()); IAnalysisServicesFactory factory = new AnalysisServicesFactory(this.tracerMock.Object, this.httpClientWrapperMock.Object, this.credentialsFactoryMock.Object, this.azureResourceManagerClientMock.Object); await factory.CreateLogAnalyticsTelemetryDataClientAsync(resources, default(CancellationToken)); }
public async Task WhenCreatingLogAnalyticsClientForTheCorrectRunInfoThenTheCorrectClientIsCreated() { var resources = new List <ResourceIdentifier>() { new ResourceIdentifier(ResourceType.VirtualMachine, SubscriptionId, ResourceGroupName, ResourceName) }; this.SetupTest(resources, TelemetryDbType.LogAnalytics, WorkspaceId); IAnalysisServicesFactory factory = new AnalysisServicesFactory(this.tracerMock.Object, this.httpClientWrapperMock.Object, this.credentialsFactoryMock.Object, this.azureResourceManagerClientMock.Object, this.queryRunInfoProviderMock.Object); TelemetryDataClientBase client = await factory.CreateLogAnalyticsTelemetryDataClientAsync(resources, default(CancellationToken)) as TelemetryDataClientBase; Assert.IsNotNull(client); Assert.AreEqual(typeof(LogAnalyticsTelemetryDataClient), client.GetType(), "Wrong telemetry data client type created"); CollectionAssert.AreEqual(new[] { resources.First().ToResourceId() }, client.TelemetryResourceIds.ToArray(), "Wrong resource Ids"); }
public async Task WhenCallingActivityLogClientWithVmResourceTypeThenTheCorrectUriIsCreated() { IAnalysisServicesFactory factory = new AnalysisServicesFactory(this.tracerMock.Object, this.httpClientWrapperMock.Object, this.credentialsFactoryMock.Object, this.azureResourceManagerClient, this.queryRunInfoProviderMock.Object); var resource = new ResourceIdentifier(ResourceType.VirtualMachine, "subscriptionId", "resourceGroupName", "resourceName"); IActivityLogClient client = await factory.CreateActivityLogClientAsync(default(CancellationToken)); JObject returnValue = new JObject() { ["value"] = new JArray() }; Uri requestUri = new Uri("https://management.azure.com/subscriptions/subscriptionId/providers/microsoft.insights/eventtypes/management/values?api-version=2015-04-01&$filter=eventTimestamp ge '2018-04-30 17:00:00Z' and eventTimestamp le '2018-04-30 23:00:00Z' and resourceUri eq '/subscriptions/subscriptionId/resourceGroups/resourceGroupName/providers/Microsoft.Compute/virtualMachines/resourceName"); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(returnValue.ToString()) }; this.httpClientWrapperMock.Setup(m => m.SendAsync(It.Is <HttpRequestMessage>(r => r.RequestUri == requestUri), It.IsAny <TimeSpan?>(), It.IsAny <CancellationToken>())).ReturnsAsync(response); await client.GetActivityLogAsync(resource, new DateTime(2018, 04, 30, 17, 0, 0, DateTimeKind.Utc), new DateTime(2018, 04, 30, 23, 0, 0), CancellationToken.None); this.httpClientWrapperMock.Verify(x => x.SendAsync(It.Is <HttpRequestMessage>(r => r.RequestUri == requestUri), It.IsAny <TimeSpan?>(), It.IsAny <CancellationToken>()), Times.Once); }
/// <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(); ITracer 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); } try { SmartDetectorManifest smartDetectorManifest = smartDetectorPackage.Manifest; ISmartDetector detector = smartDetectorLoader.LoadSmartDetector(smartDetectorPackage); // Authenticate the user to Active Directory IAuthenticationServices authenticationServices = new AuthenticationServices(); authenticationServices.AuthenticateUserAsync().Wait(); ICredentialsFactory credentialsFactory = new ActiveDirectoryCredentialsFactory(authenticationServices); IHttpClientWrapper httpClientWrapper = new HttpClientWrapper(); IExtendedAzureResourceManagerClient azureResourceManagerClient = new ExtendedAzureResourceManagerClient(httpClientWrapper, credentialsFactory, consoleTracer); // Create analysis service factory IInternalAnalysisServicesFactory analysisServicesFactory = new AnalysisServicesFactory(consoleTracer, httpClientWrapper, credentialsFactory, azureResourceManagerClient); // Create state repository factory IStateRepositoryFactory stateRepositoryFactory = new EmulationStateRepositoryFactory(); // Load user settings var userSettings = UserSettings.LoadUserSettings(); // Create the detector runner IPageableLogArchive logArchive = new PageableLogArchive(smartDetectorManifest.Name); IEmulationSmartDetectorRunner smartDetectorRunner = new SmartDetectorRunner( detector, analysisServicesFactory, smartDetectorManifest, stateRepositoryFactory, azureResourceManagerClient, logArchive); // Create a Unity container with all the required models and view models registrations Container = new UnityContainer(); Container .RegisterInstance(notificationService) .RegisterInstance <ITracer>(consoleTracer) .RegisterInstance(new AlertsRepository()) .RegisterInstance(authenticationServices) .RegisterInstance(azureResourceManagerClient) .RegisterInstance(detector) .RegisterInstance(smartDetectorManifest) .RegisterInstance(analysisServicesFactory) .RegisterInstance(logArchive) .RegisterInstance(smartDetectorRunner) .RegisterInstance(stateRepositoryFactory) .RegisterInstance(userSettings); } catch (Exception exception) { var message = $"{exception.Message}. {Environment.NewLine}{exception.InnerException?.Message}"; MessageBox.Show(message); System.Diagnostics.Trace.WriteLine(message); Environment.Exit(1); } }