/// <summary>
 /// Create or update a workspace.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.OperationalInsights.IWorkspaceOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The resource group name of the workspace.
 /// </param>
 /// <param name='parameters'>
 /// Required. The parameters required to create or update a workspace.
 /// </param>
 /// <returns>
 /// The create or update workspace operation response.
 /// </returns>
 public static WorkspaceCreateOrUpdateResponse BeginCreateOrUpdate(this IWorkspaceOperations operations, string resourceGroupName, WorkspaceCreateOrUpdateParameters parameters)
 {
     return Task.Factory.StartNew((object s) => 
     {
         return ((IWorkspaceOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, parameters);
     }
     , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }
        public void CanCreateListDeleteWorkspace()
        {
            BasicDelegatingHandler handler = new BasicDelegatingHandler();

            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();

                var resourceClient = TestHelper.GetResourceClient(handler);
                var client = TestHelper.GetOperationalInsightsManagementClient(handler);

                string resourceGroupName = TestUtilities.GenerateName("OIHyak");
                var resourceGroup = TestHelper.CreateResourceGroup(resourceGroupName, resourceClient);

                // Create a workspace
                string workspaceName = TestUtilities.GenerateName("AzTest");
                var workspaceCreateParameters = new WorkspaceCreateOrUpdateParameters
                {
                    Workspace =
                        new Workspace
                        {
                            Name = workspaceName,
                            Location = resourceGroup.Location,
                            Tags = new Dictionary<string, string> { { "tag1", "val1" } },
                            Properties = new WorkspaceProperties { Sku = new Sku(SkuNameEnum.Free) }
                        }
                };

                var createResponse = client.Workspaces.CreateOrUpdate(resourceGroupName, workspaceCreateParameters);
                Assert.True(HttpStatusCode.Created == createResponse.StatusCode || HttpStatusCode.OK == createResponse.StatusCode);
                TestHelper.ValidateWorkspace(workspaceCreateParameters.Workspace, createResponse.Workspace);

                // Get the workspace
                var getResponse = client.Workspaces.Get(resourceGroupName, workspaceName);
                Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
                TestHelper.ValidateWorkspace(workspaceCreateParameters.Workspace, getResponse.Workspace);

                // Create a second workspace for list testing
                var workspaceNameTwo = TestUtilities.GenerateName("AzTest");
                workspaceCreateParameters.Workspace.Name = workspaceNameTwo;
                createResponse = client.Workspaces.CreateOrUpdate(resourceGroupName, workspaceCreateParameters);
                Assert.True(HttpStatusCode.Created == createResponse.StatusCode || HttpStatusCode.OK == createResponse.StatusCode);
                TestHelper.ValidateWorkspace(workspaceCreateParameters.Workspace, createResponse.Workspace);

                // List the workspace in the subscription
                var listResponse = client.Workspaces.ListInSubscription();
                Assert.True(HttpStatusCode.OK == listResponse.StatusCode);
                Assert.Equal(2, listResponse.Workspaces.Count);
                Assert.Null(listResponse.NextLink);
                Assert.Single(listResponse.Workspaces.Where(w => w.Name.Equals(workspaceName, StringComparison.OrdinalIgnoreCase)));
                Assert.Single(listResponse.Workspaces.Where(w => w.Name.Equals(workspaceNameTwo, StringComparison.OrdinalIgnoreCase)));

                // List the workspace in the resource group
                listResponse = client.Workspaces.ListInResourceGroup(resourceGroupName);
                Assert.True(HttpStatusCode.OK == listResponse.StatusCode);
                Assert.Equal(2, listResponse.Workspaces.Count);
                Assert.Null(listResponse.NextLink);
                Assert.Single(listResponse.Workspaces.Where(w => w.Name.Equals(workspaceName, StringComparison.OrdinalIgnoreCase)));
                Assert.Single(listResponse.Workspaces.Where(w => w.Name.Equals(workspaceNameTwo, StringComparison.OrdinalIgnoreCase)));

                // Perform an update on one of the workspaces
                createResponse.Workspace.Properties.Sku.Name = SkuNameEnum.Premium;
                var workspaceUpdateParameters = new WorkspaceCreateOrUpdateParameters { Workspace = createResponse.Workspace };
                var updateResponse = client.Workspaces.CreateOrUpdate(resourceGroupName, workspaceUpdateParameters);
                Assert.True(HttpStatusCode.OK == updateResponse.StatusCode);
                TestHelper.ValidateWorkspace(workspaceUpdateParameters.Workspace, updateResponse.Workspace);

                // Delete a workspace
                var deleteResponse = client.Workspaces.Delete(resourceGroupName, workspaceName);
                Assert.Equal(HttpStatusCode.OK, deleteResponse.StatusCode);

                // Verify the workspace is gone
                TestHelper.VerifyCloudException(HttpStatusCode.NotFound, () => client.Workspaces.Get(resourceGroupName, workspaceName));
            }
        }
        public void CanEnableDisableListIntelligencePacks()
        {
            BasicDelegatingHandler handler = new BasicDelegatingHandler();

            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();

                var resourceClient = TestHelper.GetResourceClient(handler);
                var client = TestHelper.GetOperationalInsightsManagementClient(handler);

                string resourceGroupName = TestUtilities.GenerateName("OIHyak");
                var resourceGroup = TestHelper.CreateResourceGroup(resourceGroupName, resourceClient);

                // Create a workspace
                string workspaceName = TestUtilities.GenerateName("AzTest");
                var workspaceCreateParameters = new WorkspaceCreateOrUpdateParameters
                {
                    Workspace =
                        new Workspace
                        {
                            Name = workspaceName,
                            Location = resourceGroup.Location,
                            Tags = new Dictionary<string, string> { { "tag1", "val1" } },
                            Properties = new WorkspaceProperties { Sku = new Sku(SkuNameEnum.Free) }
                        }
                };

                var createResponse = client.Workspaces.CreateOrUpdate(resourceGroupName, workspaceCreateParameters);
                Assert.True(
                    HttpStatusCode.Created == createResponse.StatusCode
                    || HttpStatusCode.OK == createResponse.StatusCode);
                TestHelper.ValidateWorkspace(workspaceCreateParameters.Workspace, createResponse.Workspace);

                // Enable an intelligence pack
                var enableResponse = client.Workspaces.EnableIntelligencePackAsync(
                    resourceGroupName,
                    workspaceName,
                    "ChangeTracking");
                Assert.True(enableResponse != null && HttpStatusCode.OK == enableResponse.Result.StatusCode);

                enableResponse = client.Workspaces.EnableIntelligencePackAsync(
                    resourceGroupName,
                    workspaceName,
                    "SiteRecovery");
                Assert.True(enableResponse != null && HttpStatusCode.OK == enableResponse.Result.StatusCode);

                var listResponse = client.Workspaces.ListIntelligencePacks(resourceGroupName, workspaceName);
                Assert.NotNull(listResponse);
                Assert.NotNull(listResponse.IntelligencePacks);

                foreach (var ip in listResponse.IntelligencePacks)
                {

                    if (ip.Name.Equals("ChangeTracking"))
                    {
                        Assert.True(ip.Enabled);
                    }
                    else if (ip.Name.Equals("SiteRecovery"))
                    {
                        Assert.True(ip.Enabled);
                    }
                    else if (ip.Name.Equals("LogManagement"))
                    {
                        Assert.True(ip.Enabled);
                    }
                    else
                    {
                        Assert.False(ip.Enabled);
                    }
                }

                var disableResponse = client.Workspaces.DisableIntelligencePackAsync(
                    resourceGroupName,
                    workspaceName,
                    "ChangeTracking");
                Assert.True(disableResponse != null && HttpStatusCode.OK == disableResponse.Result.StatusCode);

                disableResponse = client.Workspaces.DisableIntelligencePackAsync(
                    resourceGroupName,
                    workspaceName,
                    "SiteRecovery");
                Assert.True(disableResponse != null && HttpStatusCode.OK == disableResponse.Result.StatusCode);

                listResponse = client.Workspaces.ListIntelligencePacks(resourceGroupName, workspaceName);
                Assert.NotNull(listResponse);
                Assert.NotNull(listResponse.IntelligencePacks);

                foreach (var ip in listResponse.IntelligencePacks)
                {
                    if (ip.Name.Equals("ChangeTracking"))
                    {
                        Assert.False(ip.Enabled);
                    }
                    else if (ip.Name.Equals("SiteRecovery"))
                    {
                        Assert.False(ip.Enabled);
                    }
                    else if (ip.Name.Equals("LogManagement"))
                    {
                        Assert.True(ip.Enabled);
                    }
                    else
                    {
                        Assert.False(ip.Enabled);
                    }
                }
                // Delete a workspace
                var deleteResponse = client.Workspaces.Delete(resourceGroupName, workspaceName);
                Assert.Equal(HttpStatusCode.OK, deleteResponse.StatusCode);

                // Verify the workspace is gone
                TestHelper.VerifyCloudException(HttpStatusCode.NotFound, () => client.Workspaces.Get(resourceGroupName, workspaceName));
            }
        }
        public void CanPerformWorkspaceActions()
        {
            BasicDelegatingHandler handler = new BasicDelegatingHandler();

            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();

                var resourceClient = TestHelper.GetResourceClient(handler);
                var client = TestHelper.GetOperationalInsightsManagementClient(handler);

                string resourceGroupName = TestUtilities.GenerateName("OIHyak");
                var resourceGroup = TestHelper.CreateResourceGroup(resourceGroupName, resourceClient);

                // Query link targets for an identity
                var linkTargetsResponse = client.Workspaces.ListLinkTargets();
                Assert.True(HttpStatusCode.OK == linkTargetsResponse.StatusCode);
                Assert.Equal(0, linkTargetsResponse.Accounts.Count);

                // Attempt to link a workspace to an invalid account
                string workspaceName = TestUtilities.GenerateName("AzTest");
                var workspaceCreateParameters = new WorkspaceCreateOrUpdateParameters
                {
                    Workspace =
                        new Workspace
                        {
                            Name = workspaceName,
                            Location = resourceGroup.Location,
                            Properties = new WorkspaceProperties {  CustomerId = Guid.NewGuid() }
                        }
                };

                TestHelper.VerifyCloudException(HttpStatusCode.BadRequest, () => client.Workspaces.CreateOrUpdate(resourceGroupName, workspaceCreateParameters));

                // Create a real workspace
                workspaceCreateParameters.Workspace.Properties = null;
                var createResponse = client.Workspaces.CreateOrUpdate(resourceGroupName, workspaceCreateParameters);
                Assert.True(HttpStatusCode.Created == createResponse.StatusCode || HttpStatusCode.OK == createResponse.StatusCode);
                TestHelper.ValidateWorkspace(workspaceCreateParameters.Workspace, createResponse.Workspace);

                // Get the shared keys for a workspace
                var getKeysResponse = client.Workspaces.GetSharedKeys(resourceGroupName, workspaceName);
                Assert.True(HttpStatusCode.OK == getKeysResponse.StatusCode);
                Assert.NotNull(getKeysResponse.Keys.PrimarySharedKey);
                Assert.NotNull(getKeysResponse.Keys.SecondarySharedKey);

                // List the management groups connected to the workspace
                var managementGroupsResponse = client.Workspaces.ListManagementGroups(resourceGroupName, workspaceName);
                Assert.True(HttpStatusCode.OK == managementGroupsResponse.StatusCode);
                Assert.Null(managementGroupsResponse.NextLink);
                Assert.Equal(0, managementGroupsResponse.ManagementGroups.Count);

                // List the usage for a workspace
                var usagesResponse = client.Workspaces.ListUsages(resourceGroupName, workspaceName);
                Assert.True(HttpStatusCode.OK == usagesResponse.StatusCode);
                Assert.Equal(1, usagesResponse.UsageMetrics.Count);
                
                var metric = usagesResponse.UsageMetrics.Single();
                Assert.Equal("DataAnalyzed", metric.Name.Value);
                Assert.NotNull(metric.NextResetTime);
                Assert.Equal("Bytes", metric.Unit);
                Assert.Equal("P1D", metric.QuotaPeriod);
            }
        }
 /// <summary>
 /// Create or update a workspace.
 /// </summary>
 /// <param name='operations'>
 /// Reference to the
 /// Microsoft.Azure.Management.OperationalInsights.IWorkspaceOperations.
 /// </param>
 /// <param name='resourceGroupName'>
 /// Required. The resource group name of the workspace.
 /// </param>
 /// <param name='parameters'>
 /// Required. The parameters required to create or update a workspace.
 /// </param>
 /// <returns>
 /// The create or update workspace operation response.
 /// </returns>
 public static Task<WorkspaceCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this IWorkspaceOperations operations, string resourceGroupName, WorkspaceCreateOrUpdateParameters parameters)
 {
     return operations.BeginCreateOrUpdateAsync(resourceGroupName, parameters, CancellationToken.None);
 }
        public void CanCreateUpdateDeleteDataSource()
        {
            BasicDelegatingHandler handler = new BasicDelegatingHandler();

            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();

                var resourceClient = TestHelper.GetResourceClient(handler);
                var client = TestHelper.GetOperationalInsightsManagementClient(handler);

                string resourceGroupName = TestUtilities.GenerateName("OIHyak");
                var resourceGroup = TestHelper.CreateResourceGroup(resourceGroupName, resourceClient);

                // Create a workspace that will house the data source
                string workspaceName = TestUtilities.GenerateName("AzTest");
                var workspaceCreateParameters = new WorkspaceCreateOrUpdateParameters
                {
                    Workspace =
                        new Workspace
                        {
                            Name = workspaceName,
                            Location = resourceGroup.Location
                        }
                };

                var workspaceCreateResponse = client.Workspaces.CreateOrUpdate(resourceGroupName, workspaceCreateParameters);
                Assert.True(HttpStatusCode.Created == workspaceCreateResponse.StatusCode || HttpStatusCode.OK == workspaceCreateResponse.StatusCode);

                // Create a dataSource
                string dataSourceName = TestUtilities.GenerateName("AzTestDS");
                var createParameters = new DataSourceCreateOrUpdateParameters
                {
                    DataSource = new DataSource
                    {
                        Name = dataSourceName,
                        Kind = "AzureAuditLog",
                        Properties = "{'LinkedResourceId':'/subscriptions/0b88dfdb-55b3-4fb0-b474-5b6dcbe6b2ef/providers/microsoft.insights/eventtypes/management'}"
                    }
                };
                var createResponse = client.DataSources.CreateOrUpdate(resourceGroupName, workspaceName, createParameters);
                Assert.True(HttpStatusCode.Created == createResponse.StatusCode || HttpStatusCode.OK == createResponse.StatusCode);
                TestHelper.ValidateDatasource(createParameters.DataSource, createResponse.DataSource);

                // Get the data source
                var getResponse = client.DataSources.Get(resourceGroupName, workspaceName, dataSourceName);
                Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
                TestHelper.ValidateDatasource(createParameters.DataSource, getResponse.DataSource);

                // Create a second data source for list testing
                var dataSourceNameTwo = TestUtilities.GenerateName("AzTestDS");
                createParameters.DataSource.Name = dataSourceNameTwo;
                createParameters.DataSource.Properties = "{'LinkedResourceId':'/subscriptions/a6383be3-f0e8-4968-93d5-10f2625f5bb5/providers/microsoft.insights/eventtypes/management'}";
                createResponse = client.DataSources.CreateOrUpdate(resourceGroupName, workspaceName, createParameters);
                Assert.True(HttpStatusCode.Created == createResponse.StatusCode || HttpStatusCode.OK == createResponse.StatusCode);
                TestHelper.ValidateDatasource(createParameters.DataSource, createResponse.DataSource);

                // List the data sources in the workspace
                var listResponse = client.DataSources.ListInWorkspace(resourceGroupName, workspaceName, "AzureAuditLog", string.Empty);
                Assert.True(HttpStatusCode.OK == listResponse.StatusCode);
                Assert.Equal(2, listResponse.DataSources.Count);
                Assert.Null(listResponse.NextLink);
                Assert.Single(listResponse.DataSources.Where(w => w.Name.Equals(dataSourceName, StringComparison.OrdinalIgnoreCase)));
                Assert.Single(listResponse.DataSources.Where(w => w.Name.Equals(dataSourceNameTwo, StringComparison.OrdinalIgnoreCase)));

                // Perform an update on one of the data sources
                createResponse.DataSource.Properties= "{'LinkedResourceId':'/subscriptions/bc8edd8f-a09f-499d-978d-6b5ed2f84852/providers/microsoft.insights/eventtypes/management'}";
                createResponse.DataSource.Name = dataSourceNameTwo;
                var updateParameters = new DataSourceCreateOrUpdateParameters { DataSource= createResponse.DataSource };
                var updateResponse = client.DataSources.CreateOrUpdate(resourceGroupName, workspaceName, updateParameters);
                Assert.True(HttpStatusCode.OK == updateResponse.StatusCode);
                TestHelper.ValidateDatasource(updateParameters.DataSource, updateResponse.DataSource);

                // Delete a data source
                var deleteResponse = client.DataSources.Delete(resourceGroupName, workspaceName, dataSourceName);
                Assert.Equal(HttpStatusCode.OK, deleteResponse.StatusCode);

                // Verify the data source is gone
                TestHelper.VerifyCloudException(HttpStatusCode.NotFound, () => client.DataSources.Get(resourceGroupName, workspaceName, dataSourceName));
            }
        }
        public void CanCreateUpdateDeleteStorageInsight()
        {
            BasicDelegatingHandler handler = new BasicDelegatingHandler();

            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();

                var resourceClient = TestHelper.GetResourceClient(handler);
                var client = TestHelper.GetOperationalInsightsManagementClient(handler);

                string resourceGroupName = TestUtilities.GenerateName("OIHyak");
                var resourceGroup = TestHelper.CreateResourceGroup(resourceGroupName, resourceClient);

                // Create a workspace that will house the storage insights
                string workspaceName = TestUtilities.GenerateName("AzTest");
                var workspaceCreateParameters = new WorkspaceCreateOrUpdateParameters
                {
                    Workspace =
                        new Workspace
                        {
                            Name = workspaceName,
                            Location = resourceGroup.Location
                        }
                };

                var workspaceCreateResponse = client.Workspaces.CreateOrUpdate(resourceGroupName, workspaceCreateParameters);
                Assert.True(HttpStatusCode.Created == workspaceCreateResponse.StatusCode || HttpStatusCode.OK == workspaceCreateResponse.StatusCode);

                // Create a storage insight
                string storageInsightName = TestUtilities.GenerateName("AzTestSI");
                string storageAccountName = TestUtilities.GenerateName("AzTestFakeSA");
                var createParameters = new StorageInsightCreateOrUpdateParameters
                {
                    StorageInsight = new StorageInsight
                    {
                        Location = resourceGroup.Location,
                        Name = storageInsightName,
                        Properties = new StorageInsightProperties
                        {
                            Tables = new[] { "WADWindowsEventLogsTable", "LinuxSyslogVer2v0" },
                            Containers = new[] { "wad-iis-logfiles" },
                            StorageAccount =
                                new StorageAccount
                                {
                                    Id = string.Format(StorageAccountIdFormat, client.Credentials.SubscriptionId, resourceGroupName, storageAccountName),
                                    Key = "1234"
                                }
                        }
                    }
                };
                var createResponse = client.StorageInsights.CreateOrUpdate(resourceGroupName, workspaceName, createParameters);
                Assert.True(HttpStatusCode.Created == createResponse.StatusCode || HttpStatusCode.OK == createResponse.StatusCode);
                TestHelper.ValidateStorageInsight(createParameters.StorageInsight, createResponse.StorageInsight);

                // Get the storage insight
                var getResponse = client.StorageInsights.Get(resourceGroupName, workspaceName, storageInsightName);
                Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
                TestHelper.ValidateStorageInsight(createParameters.StorageInsight, getResponse.StorageInsight);

                // Create a second storage insight for list testing
                var storageInsightNameTwo = TestUtilities.GenerateName("AzTestSI");
                createParameters.StorageInsight.Name = storageInsightNameTwo;
                createParameters.StorageInsight.Properties.Containers = null;
                createResponse = client.StorageInsights.CreateOrUpdate(resourceGroupName, workspaceName, createParameters);
                Assert.True(HttpStatusCode.Created == createResponse.StatusCode || HttpStatusCode.OK == createResponse.StatusCode);
                TestHelper.ValidateStorageInsight(createParameters.StorageInsight, createResponse.StorageInsight);

                // List the storage insights in the workspace
                var listResponse = client.StorageInsights.ListInWorkspace(resourceGroupName, workspaceName);
                Assert.True(HttpStatusCode.OK == listResponse.StatusCode);
                Assert.Equal(2, listResponse.StorageInsights.Count);
                Assert.Null(listResponse.NextLink);
                Assert.Single(listResponse.StorageInsights.Where(w => w.Name.Equals(storageInsightName, StringComparison.OrdinalIgnoreCase)));
                Assert.Single(listResponse.StorageInsights.Where(w => w.Name.Equals(storageInsightNameTwo, StringComparison.OrdinalIgnoreCase)));

                // Perform an update on one of the storage insights
                createResponse.StorageInsight.Properties.StorageAccount.Key = "9876";
                createResponse.StorageInsight.Properties.Tables = new[] { "WADWindowsEventLogsTable" };
                createResponse.StorageInsight.Properties.Containers = new[] { "wad-iis-logfiles" };
                var updateParameters = new StorageInsightCreateOrUpdateParameters { StorageInsight= createResponse.StorageInsight };
                var updateResponse = client.StorageInsights.CreateOrUpdate(resourceGroupName, workspaceName, updateParameters);
                Assert.True(HttpStatusCode.OK == updateResponse.StatusCode);
                TestHelper.ValidateStorageInsight(updateParameters.StorageInsight, updateResponse.StorageInsight);

                // Delete a storage insight
                var deleteResponse = client.StorageInsights.Delete(resourceGroupName, workspaceName, storageInsightName);
                Assert.Equal(HttpStatusCode.OK, deleteResponse.StatusCode);

                // Verify the storageinsight is gone
                TestHelper.VerifyCloudException(HttpStatusCode.NotFound, () => client.StorageInsights.Get(resourceGroupName, workspaceName, storageInsightName));
            }
        }