static IEnumerable <MetricDefinition> GetMetricDefinitions(TokenCredentials credentials, string resourceUri)
 {
     using (var client = new InsightsClient(credentials))
     {
         return(client.MetricDefinitions.List(resourceUri).ToList());
     }
 }
        private const double days = -10; //max = -90  (90 days of logs is stored by audit logs)

        static void Main(string[] args)
        {
            Console.WriteLine("Starting operations log export.");

            string token = GetAuthorizationHeader();

            TokenCloudCredentials credentials = new TokenCloudCredentials(SubscriptionID, token);
            InsightsClient        client      = new InsightsClient(credentials);

            DateTime endDateTime   = DateTime.Now;
            DateTime startDateTime = endDateTime.AddDays(days);

            string filterString = FilterString.Generate <ListEventsForResourceProviderParameters>(eventData => (eventData.EventTimestamp >= startDateTime) && (eventData.EventTimestamp <= endDateTime));

            EventDataListResponse response = client.EventOperations.ListEvents(filterString, selectedProperties: null);
            List <EventData>      logList  = new List <EventData>(response.EventDataCollection.Value);

            while (!string.IsNullOrEmpty(response.EventDataCollection.NextLink))
            {
                Console.WriteLine($"Retrieving page {response.EventDataCollection.NextLink}");

                response = client.EventOperations.ListEventsNext(response.EventDataCollection.NextLink);
                logList.AddRange(response.EventDataCollection.Value);
            }

            ResourceManagementClient resClient = new ResourceManagementClient(credentials);

            Console.WriteLine($"Page retrieval completed, preparing to write to a file {CSVExportNamePath}.");

            ExportOpsLogToCSV(logList, resClient);

            Console.WriteLine("Export completed.");
            Console.WriteLine("Press any key to exit");
            Console.ReadLine();
        }
        private const double days = -10; //max = -90  (90 days of logs is stored by audit logs)

        static void Main(string[] args)
        {
            Console.WriteLine("Starting operations log export.");

            string token = GetAuthorizationHeader();

            TokenCloudCredentials credentials = new TokenCloudCredentials(SubscriptionID, token);
            InsightsClient client = new InsightsClient(credentials);

            DateTime endDateTime = DateTime.Now;
            DateTime startDateTime = endDateTime.AddDays(days);
            
            string filterString = FilterString.Generate<ListEventsForResourceProviderParameters>(eventData => (eventData.EventTimestamp >= startDateTime) && (eventData.EventTimestamp <= endDateTime));
                     
            EventDataListResponse response = client.EventOperations.ListEvents(filterString, selectedProperties: null);
            List<EventData> logList = new List<EventData>(response.EventDataCollection.Value);

            while (!string.IsNullOrEmpty(response.EventDataCollection.NextLink))
            {
                Console.WriteLine($"Retrieving page {response.EventDataCollection.NextLink}");

                response = client.EventOperations.ListEventsNext(response.EventDataCollection.NextLink);
                logList.AddRange(response.EventDataCollection.Value);
            }

            ResourceManagementClient resClient = new ResourceManagementClient(credentials);
          
            Console.WriteLine($"Page retrieval completed, preparing to write to a file {CSVExportNamePath}.");

            ExportOpsLogToCSV(logList, resClient);

            Console.WriteLine("Export completed.");
            Console.WriteLine("Press any key to exit");
            Console.ReadLine();
        }
 static IEnumerable <Metric> GetMetrics(TokenCredentials credentials, string resourceUri, string filter)
 {
     using (var client = new InsightsClient(credentials))
     {
         return(client.Metrics.List(resourceUri, filter).ToList());
     }
 }
 private static MetricDefinitionListResponse GetAvailableMetricDefinitions(TokenCloudCredentials credentials, string resourceUri)
 {
     using (var client = new InsightsClient(credentials))
     {
         return(client.MetricDefinitionOperations.GetMetricDefinitions(resourceUri, null));
     }
 }
Beispiel #6
0
        /// <summary>
        /// Initialize a new instance of the AppInsight class.
        /// </summary>
        /// <param name="subscriptionId">SubscriptionId where the resource resides on.</param>
        /// <param name="tenantId">Guid of the tenant.</param>
        /// <param name="clientId">ClientId or Username to authenticate.</param>
        /// <param name="clientSecret">ClientSecret or Password to authenticate.</param>
        public AppInsight(string subscriptionId, string tenantId, string clientId, string clientSecret)
        {
            _token = GetAuthorizationHeader(tenantId, clientId, clientSecret);
            SubscriptionCloudCredentials credentials = new TokenCloudCredentials(subscriptionId, _token);

            _client         = new InsightsClient(credentials);
            _subscriptionId = subscriptionId;
        }
Beispiel #7
0
        public void TestInsights()
        {
            InsightsClient insightsClient = new InsightsClient(TestHelper.ApplicationId1, TestHelper.AdminKey1);
            var            insights       = insightsClient.User("test");

            // click
            insights.ClickedFilters("clickedFilters", _indexName, new List <string> {
                "brand:apple"
            });
            insights.ClickedObjectIDs("clickedObjectEvent", _indexName, new List <string> {
                "1", "2"
            });

            // Conversion
            insights.ConvertedObjectIDs("convertedObjectIDs", _indexName, new List <string> {
                "1", "2"
            });
            insights.ConvertedFilters("converterdFilters", _indexName, new List <string> {
                "brand:apple"
            });

            // View
            insights.ViewedFilters("viewedFilters", _indexName, new List <string> {
                "brand:apple", "brand:google"
            });
            insights.ViewedObjectIDs("viewedObjectIDs", _indexName, new List <string> {
                "1", "2"
            });

            _index.SaveObject(new AlgoliaStub {
                ObjectID = "one"
            }).Wait();

            var query = new Query()
            {
                EnablePersonalization = true,
                ClickAnalytics        = true
            };

            var search1 = _index.Search <AlgoliaStub>(query);

            insights.ClickedObjectIDsAfterSearch("clickedObjectIDsAfterSearch", _indexName, new List <string> {
                "1", "2"
            },
                                                 new List <uint> {
                17, 19
            }, search1.QueryID);

            var search2 = _index.Search <AlgoliaStub>(query);

            insights.ConvertedObjectIDsAfterSearch("convertedObjectIDsAfterSearch", _indexName,
                                                   new List <string> {
                "1", "2"
            }, search2.QueryID);
        }
 private static void OnNextEvent(BBEvent bbEvent)
 {
     try
     {
         InsightsClient.TrackEvent((EventTelemetry)bbEvent.ToTelemetry());
     }
     catch (Exception ex)
     {
         InsightsClient.TrackException(
             (ExceptionTelemetry) new BBInternalEvent("Error senting the telemetry event through AppInsights", ex).ToTelemetry());
     }
 }
        static Program()
        {
            var accessToken           = GetAccessToken();
            var tokenCredentials      = new TokenCredentials(accessToken);
            var tokenCloudCredentials = new TokenCloudCredentials(SubscriptionId, accessToken);

            resourceManagementClient = new ResourceManagementClient(tokenCredentials)
            {
                SubscriptionId = SubscriptionId
            };
            insightsClient = new InsightsClient(tokenCloudCredentials);
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            // Define the base URI for management operations
            Uri baseUri = new Uri("https://management.azure.com");

            string token           = GetAuthorizationHeader();
            var    startTime       = DateTime.Now;
            var    endTime         = startTime.ToUniversalTime().AddHours(1.0).ToLocalTime();
            var    redisConnection = "";

            ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(redisConnection);
            IDatabase             cachedb    = connection.GetDatabase();

            for (int i = 0; i < 10; i++)
            {
                cachedb.StringIncrement(i.ToString());
                Console.WriteLine("value=" + cachedb.StringGet(i.ToString()));
            }


            // Get the credentials
            // You can find instructions on how to get the token here:
            // http://msdn.microsoft.com/en-us/library/azure/dn790557.aspx
            SubscriptionCloudCredentials credentials = new TokenCloudCredentials(subscriptionId, token);

            // Create an instance of the InsightsClient from Microsoft.Azure.Insights
            InsightsClient client = new InsightsClient(credentials, baseUri);

            // Get the events for an Azure Resource (e.g. Website) (as described by the Azure Resource Manager APIs here:http://msdn.microsoft.com/en-us/library/azure/dn790569.aspx)
            // A resource URI looks like the following string:
            //"/subscriptions/########-####-####-####-############/resourceGroups/resourcegroupname1/providers/resourceprovider1/resourcename1"
            string resourceUri = string.Format("subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Cache/redis/{2}", subscriptionId, resourceGroupName, cacheName);

            //Define a FilterString
            string filterString = FilterString.Generate <ListEventsForResourceParameters>(eventData => (eventData.EventTimestamp >= startTime) && (eventData.EventTimestamp <= endTime) && (eventData.ResourceUri == resourceUri));

            //Get the events logs
            EventDataListResponse response = client.EventOperations.ListEvents(filterString, selectedProperties: null);


            //Check the status code of the response
            Console.WriteLine("HTTP Status Code returned for the call:" + response.StatusCode);

            var response2 = client.MetricDefinitionOperations.GetMetricDefinitions(resourceUri, "");
            var metrics   = client.MetricOperations.GetMetrics(resourceUri, "startTime eq 2015-01-14T02:19:03.0712821Z and endTime eq 2015-01-14T03:19:03.0712821Z and timeGrain eq duration'PT5M'", response2.MetricDefinitionCollection.Value);

            Console.WriteLine("Print out the metrics logs");
            foreach (var item in metrics.MetricCollection.Value)
            {
                Console.WriteLine(item.Name.Value + "--" + item.MetricValues.Count);
            }
        }
        protected InsightsClient GetInsightsClient(RecordedDelegatingHandler handler)
        {
            handler.IsPassThrough = false;
            var tokenProvider = new StringTokenProvider("granted", "SimpleString");
            var id            = Guid.NewGuid().ToString();
            var token         = new TokenCredentials(tokenProvider: tokenProvider, tenantId: id, callerId: id);
            var client        = new InsightsClient(token, handler);

            token.InitializeServiceClient(client);
            client.SubscriptionId = id;

            return(client);
        }
Beispiel #12
0
        public static List <AzureResourceUsageMetric> GetUsageMetrics(string token, string subscriptionId, string resourceUri, string filter)
        {
            var result = new List <AzureResourceUsageMetric>();

            var            credentials = CredentialManager.GetCredentials(token, subscriptionId);
            InsightsClient client      = new InsightsClient(credentials);

            var usageMetrics = client.UsageMetricOperations.List(resourceUri, filter);

            foreach (var usageMetric in usageMetrics.UsageMetricCollection.Value)
            {
                result.Add(new AzureResourceUsageMetric(usageMetric));
            }

            return(result);
        }
Beispiel #13
0
        public static List <AzureResourceMetricDefinition> GetMetricDefinitions(string token, string subscriptionId, string resourceUri)
        {
            var result = new List <AzureResourceMetricDefinition>();

            var            credentials = CredentialManager.GetCredentials(token, subscriptionId);
            InsightsClient client      = new InsightsClient(credentials);

            var metricDefinitions = client.MetricDefinitionOperations.GetMetricDefinitionsAsync(resourceUri, "").Result;

            foreach (var metricDefinition in metricDefinitions.MetricDefinitionCollection.Value)
            {
                result.Add(new AzureResourceMetricDefinition(metricDefinition));
            }

            return(result);
        }
Beispiel #14
0
        public static List <AzureResourceMetric> GetMetrics(string token, string subscriptionId, string resourceUri, string filter, List <MetricDefinition> metricDefinitions)
        {
            var result = new List <AzureResourceMetric>();

            var            credentials = CredentialManager.GetCredentials(token, subscriptionId);
            InsightsClient client      = new InsightsClient(credentials);

            var metrics = client.MetricOperations.GetMetrics(resourceUri, filter, metricDefinitions);

            foreach (var metric in metrics.MetricCollection.Value)
            {
                result.Add(new AzureResourceMetric(metric));
            }

            return(result);
        }
        public void Should_ReturnCompletedTask_When_InitIsNotCalled(bool enabled)
        {
            var cluster = Mock.Of <IInternalCluster>();
            var session = Mock.Of <IInternalSession>();
            var config  = new TestConfigurationBuilder
            {
                GraphOptions = new GraphOptions()
            }.Build();

            config.MonitorReportingOptions.SetMonitorReportingEnabled(enabled);
            Mock.Get(cluster).SetupGet(c => c.Configuration).Returns(config);

            var insightsClient = new InsightsClient(
                cluster, session, Mock.Of <IInsightsMessageFactory <InsightsStartupData> >(), Mock.Of <IInsightsMessageFactory <InsightsStatusData> >());
            var task = insightsClient.ShutdownAsync();

            Assert.AreSame(TaskHelper.Completed, task);
        }
Beispiel #16
0
        public static List <AzureResourceEventData> GetEventData(string token, string subscriptionId, string resourceUri, DateTime startTime, DateTime endTime)
        {
            var result = new List <AzureResourceEventData>();

            string filterString = FilterString.Generate <ListEventsForResourceParameters>(eventData => (eventData.EventTimestamp >= startTime) && (eventData.EventTimestamp <= endTime) && (eventData.ResourceUri == resourceUri));

            var            credentials = CredentialManager.GetCredentials(token, subscriptionId);
            InsightsClient client      = new InsightsClient(credentials);

            EventDataListResponse response = client.EventOperations.ListEvents(filterString, selectedProperties: null);

            foreach (var eventEntry in response.EventDataCollection.Value)
            {
                result.Add(new AzureResourceEventData(eventEntry));
            }

            return(result);
        }
Beispiel #17
0
        public static string redirectUri = ""; // Your app name

        static void Main(string[] args)
        {
            // Define the base URI for management operations
            var azureUrl = "https://management.azure.com";  // or "https://management.chinacloudapi.cn/" for China
            Uri baseUri = new Uri(azureUrl);

            string token = GetAuthorizationHeader();
            var startTime = DateTime.Now;
            var endTime = startTime.ToUniversalTime().AddHours(1.0).ToLocalTime();
            var redisConnection = "";

            
            // Get the credentials
            // You can find instructions on how to get the token here:
            // http://msdn.microsoft.com/en-us/library/azure/dn790557.aspx
            SubscriptionCloudCredentials credentials = new TokenCloudCredentials(subscriptionId, token);

            // Create an instance of the InsightsClient from Microsoft.Azure.Insights
            InsightsClient client = new InsightsClient(credentials, baseUri);

            // Get the events for an Azure Resource (e.g. Website) (as described by the Azure Resource Manager APIs here:http://msdn.microsoft.com/en-us/library/azure/dn790569.aspx)
            // A resource URI looks like the following string: 
            //"/subscriptions/########-####-####-####-############/resourceGroups/resourcegroupname1/providers/resourceprovider1/resourcename1"
            string resourceUri = string.Format("subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Cache/redis/{2}", subscriptionId, resourceGroupName, cacheName);

            //Define a FilterString
            string filterString = FilterString.Generate<ListEventsForResourceParameters>(eventData => (eventData.EventTimestamp >= startTime) && (eventData.EventTimestamp <= endTime) && (eventData.ResourceId == resourceUri));

            //Get the events logs
            EventDataListResponse response = client.EventOperations.ListEvents(filterString, selectedProperties: null);


            //Check the status code of the response
            Console.WriteLine("HTTP Status Code returned for the call:" + response.StatusCode);

            var response2 = client.MetricDefinitionOperations.GetMetricDefinitions(resourceUri, "");
            var metrics = client.MetricOperations.GetMetrics(resourceUri, "startTime eq " + startTime.ToString("yyyy-MM-ddThh:mm:ss") + "and endTime eq " + endTime.ToString("yyyy-MM-ddThh:mm:ss") + " and timeGrain eq duration'PT5M'", response2.MetricDefinitionCollection.Value);
            Console.WriteLine("Print out the metrics logs");
            foreach (var item in metrics.MetricCollection.Value)
            {
                Console.WriteLine(item.Name.Value + "--" + item.MetricValues.Count);
            }

        }
        private static MetricListResponse GetResourceMetrics(TokenCloudCredentials credentials, string resourceUri, string filter, TimeSpan period, string duration)
        {
            var dateTimeFormat = "yyy-MM-ddTHH:mmZ";

            string start = DateTime.UtcNow.Subtract(period).ToString(dateTimeFormat);
            string end   = DateTime.UtcNow.ToString(dateTimeFormat);

            // TODO: Make this more robust.
            StringBuilder sb = new StringBuilder(filter);

            if (!string.IsNullOrEmpty(filter))
            {
                sb.Append(" and ");
            }
            sb.AppendFormat("startTime eq {0} and endTime eq {1}", start, end);
            sb.AppendFormat(" and timeGrain eq duration'{0}'", duration);

            using (var client = new InsightsClient(credentials))
            {
                return(client.MetricOperations.GetMetrics(resourceUri, sb.ToString()));
            }
        }
Beispiel #19
0
        private static async Task <EventData[]> GetCreationLogs(String startTime, String endTime, String resourceId, InsightsClient client)
        {
            ODataQuery <EventData> query = new ODataQuery <EventData>($"eventTimestamp ge '{startTime}' and eventTimestamp le '{endTime}' and resourceUri eq '{resourceId}'");
            var logs = await client.Events.ListAsync(query);

            return(logs.ToArray());
        }
        private static async Task <EventData[]> GetCreationLogs(String startTime, String endTime, String resourceId, String operation, InsightsClient client)
        {
            ODataQuery <EventData> query = new ODataQuery <EventData>($"eventTimestamp ge '{startTime}' and eventTimestamp le '{endTime}' and resourceUri eq '{resourceId}'");
            var logs = await client.Events.ListAsync(query);

            return(logs.Where(log => log.OperationName.Value.Equals(operation, StringComparison.CurrentCultureIgnoreCase)).ToArray());
        }
        private static InsightsClient GetInsightsClient(IInternalCluster cluster, IInternalSession session)
        {
            var hostnameInfoMock       = Mock.Of <IInsightsInfoProvider <string> >();
            var driverInfoMock         = Mock.Of <IInsightsInfoProvider <DriverInfo> >();
            var timestampGeneratorMock = Mock.Of <IInsightsMetadataTimestampGenerator>();
            var platformInfoMock       = Mock.Of <IInsightsInfoProvider <InsightsPlatformInfo> >();

            Mock.Get(hostnameInfoMock).Setup(m => m.GetInformation(cluster, session)).Returns("awesome_hostname");
            Mock.Get(driverInfoMock).Setup(m => m.GetInformation(cluster, session)).Returns(new DriverInfo
            {
                DriverVersion = "1.1.2",
                DriverName    = "Driver Name"
            });
            Mock.Get(timestampGeneratorMock).Setup(m => m.GenerateTimestamp()).Returns(124219041);
            Mock.Get(platformInfoMock).Setup(m => m.GetInformation(cluster, session)).Returns(new InsightsPlatformInfo
            {
                CentralProcessingUnits = new CentralProcessingUnitsInfo
                {
                    Length = 2,
                    Model  = "Awesome CPU"
                },
                Runtime = new RuntimeInfo
                {
                    Dependencies = new Dictionary <string, AssemblyInfo>
                    {
                        { "Assembly1", new AssemblyInfo {
                              Version = "1.2.0", Name = "Assembly1", FullName = "Assembly1FullName"
                          } }
                    },
                    RuntimeFramework = "runtime-framework",
                    TargetFramework  = "target-framework"
                },
                OperatingSystem = new OperatingSystemInfo
                {
                    Version = "os version",
                    Name    = "os name",
                    Arch    = "os arch"
                }
            });

            var target = new InsightsClient(
                cluster,
                session,
                new InsightsStartupMessageFactory(
                    new InsightsMetadataFactory(timestampGeneratorMock),
                    new InsightsInfoProvidersCollection(
                        platformInfoMock,
                        new ExecutionProfileInfoProvider(
                            new LoadBalancingPolicyInfoProvider(new ReconnectionPolicyInfoProvider()),
                            new SpeculativeExecutionPolicyInfoProvider(),
                            new RetryPolicyInfoProvider()),
                        new PoolSizeByHostDistanceInfoProvider(),
                        new AuthProviderInfoProvider(),
                        new DataCentersInfoProvider(),
                        new OtherOptionsInfoProvider(),
                        new ConfigAntiPatternsInfoProvider(),
                        new ReconnectionPolicyInfoProvider(),
                        driverInfoMock,
                        hostnameInfoMock)),
                new InsightsStatusMessageFactory(
                    new InsightsMetadataFactory(timestampGeneratorMock),
                    new NodeStatusInfoProvider()));

            return(target);
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            // The file with the Azure Service Principal Credentials.
            var authFile = "my.azureauth";

            // Parse the credentials from the file.
            var credentials = SdkContext.AzureCredentialsFactory.FromFile(authFile);

            // Authenticate with Azure
            var azure = Azure
                        .Configure()
                        .Authenticate(credentials)
                        .WithDefaultSubscription();

            // Create an InsightsClient instance.
            var client = new InsightsClient(credentials);

            // If we subscription is not set the API call will fail.
            client.SubscriptionId = credentials.DefaultSubscriptionId;

            // Create the OData filter for a time interval and the Azure.Health Provider.
            // Search back one day.
            var    days          = -1;
            var    endDateTime   = DateTime.Now;
            var    startDateTime = endDateTime.AddDays(days);
            string filterString  = FilterString.Generate <EventDataForFilter>(eventData =>
                                                                              (eventData.EventTimestamp >= startDateTime) &&
                                                                              (eventData.EventTimestamp <= endDateTime) &&
                                                                              (eventData.ResourceProvider == "Azure.Health"));

            // Get the Events from Azure.
            var response = client.Events.List(filterString);

            while (response != null && response.Any())
            {
                foreach (var eventData in response)
                {
                    // Set the Console Color according to the Event Status.
                    if (eventData.Status.Value != "Resolved" &&
                        eventData.Level <= EventLevel.Warning)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                    }
                    else if (eventData.Status.Value == "Resolved")
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.White;
                    }

                    // Write event data to the console
                    Console.WriteLine($"{eventData.EventTimestamp.ToLocalTime()} - {eventData.ResourceProviderName.Value} - {eventData.OperationName.Value}");
                    Console.WriteLine($"Status:\t {eventData.Status.Value}");
                    Console.WriteLine($"Level:\t {eventData.Level.ToString()}");
                    Console.WriteLine($"CorrelationId:\t {eventData.CorrelationId}");
                    Console.WriteLine($"Resource Type:\t {eventData.ResourceType.Value}");
                    Console.WriteLine($"Description:\t {eventData.Description}");
                }

                // Get more events if available.
                if (!string.IsNullOrEmpty(response.NextPageLink))
                {
                    response = client.Events.ListNext(response.NextPageLink);
                }
                else
                {
                    response = null;
                }
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("No more events...");
            Console.ForegroundColor = ConsoleColor.White;
        }
Beispiel #23
0
        public static async Task Run()
        {
            string tag_owner           = GetConfigItem("tag_owner");
            string tag_deallocate      = GetConfigItem("tag_deallocate");
            int    tag_deallocate_days = int.Parse(GetConfigItem("tag_deallocate_days"));
            string tag_deletevm        = GetConfigItem("tag_deletevm");
            int    tag_deletevm_days   = int.Parse(GetConfigItem("tag_deletevm_days"));
            string tag_deleterg        = GetConfigItem("tag_deleterg");
            int    tag_deleterg_days   = int.Parse(GetConfigItem("tag_deleterg_days"));
            string subscriptionIds     = GetConfigItem("subscriptionIds");
            string clientId            = GetConfigItem("clientId");
            string clientSecret        = GetConfigItem("clientSecret");
            string tenantId            = GetConfigItem("tenantId");

            AzureCredentialsFactory factory    = new AzureCredentialsFactory();
            AzureCredentials        azureCreds = factory.FromServicePrincipal(clientId, clientSecret, tenantId,
                                                                              AzureEnvironment.AzureGlobalCloud);

            Azure.IAuthenticated azure = Azure.Configure().Authenticate(azureCreds);

            foreach (var subscriptionId in subscriptionIds.Split(",", StringSplitOptions.RemoveEmptyEntries))
            {
                Console.WriteLine($"Looking for new resources without an owner tag in subscription {subscriptionId}");

                var azureSub       = azure.WithSubscription(subscriptionId);
                var insightsClient = new InsightsClient(azureCreds);
                insightsClient.SubscriptionId = subscriptionId;

                var resourceGroups = azureSub.ResourceGroups.List();
                foreach (var group in resourceGroups)
                {
                    try
                    {
                        var defaultKeyValuePair = default(KeyValuePair <String, String>);
                        var ownerTag            = defaultKeyValuePair;
                        if (group.Tags != null)
                        {
                            ownerTag = group.Tags.Where(tag => tag.Key.Equals(tag_owner, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                        }

                        String endTime    = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
                        String resourceId = group.Id;
                        if (ownerTag.Equals(defaultKeyValuePair))
                        {
                            //Console.WriteLine($"Resource group {group.Name} does not contain owner tag...looking in activity log");
                            String startTime = DateTime.Now.ToUniversalTime().AddHours(-25).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");

                            string newOwner = UNKNOWN_OWNER;
                            var    resourceGroupCreateLogs = await GetCreationLogs(startTime, endTime, resourceId, OPERATION_RESOURCEGROUP_WRITE, insightsClient);

                            if (resourceGroupCreateLogs.Length == 0)
                            {
                                startTime = DateTime.Now.ToUniversalTime().AddDays(-90).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
                                resourceGroupCreateLogs = await GetCreationLogs(startTime, endTime, resourceId, OPERATION_RESOURCEGROUP_WRITE, insightsClient);
                            }
                            if (resourceGroupCreateLogs.Length != 0)
                            {
                                newOwner = resourceGroupCreateLogs[0].Caller;
                            }
                            if (!UNKNOWN_OWNER.Equals(newOwner))
                            {
                                await group.Update().WithTag(tag_owner, newOwner).ApplyAsync();

                                Console.WriteLine($"Resource group {group.Name} tagged with owner {newOwner}");
                            }
                        }
                        else if (UNKNOWN_OWNER.Equals(ownerTag.Value))
                        {
                            bool needsUpdate = false;
                            var  updateGroup = group.Update();
                            if (group.Tags.Where(tag => tag.Key.Equals(tag_deallocate, StringComparison.InvariantCultureIgnoreCase)).Count() == 0)
                            {
                                needsUpdate = true;
                                updateGroup.WithTag(tag_deallocate, DateTime.Now.ToUniversalTime().AddDays(tag_deallocate_days).ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
                            }
                            if (group.Tags.Where(tag => tag.Key.Equals(tag_deletevm, StringComparison.InvariantCultureIgnoreCase)).Count() == 0)
                            {
                                needsUpdate = true;
                                updateGroup.WithTag(tag_deletevm, DateTime.Now.ToUniversalTime().AddDays(tag_deletevm_days).ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
                            }
                            if (group.Tags.Where(tag => tag.Key.Equals(tag_deleterg, StringComparison.InvariantCultureIgnoreCase)).Count() == 0)
                            {
                                needsUpdate = true;
                                updateGroup.WithTag(tag_deleterg, DateTime.Now.ToUniversalTime().AddDays(tag_deleterg_days).ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
                            }

                            if (needsUpdate)
                            {
                                await updateGroup.ApplyAsync();
                            }
                        }
                        else
                        {
                            //Console.WriteLine($"Resource group {group.Name} is already owned by {ownerTag.Value}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception: " + ex);
                    }
                }
            }

            Console.WriteLine("Done Tagging");
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Starting operations log export.");

            string token = GetAuthorizationHeader();

            TokenCloudCredentials credentials = new TokenCloudCredentials(SubscriptionID, token);

            InsightsClient client = new InsightsClient(credentials);

            DateTime endDateTime = DateTime.Now;

            DateTime startDateTime = endDateTime.AddDays(-90);

            string filterString = FilterString.Generate<ListEventsForResourceProviderParameters>(eventData => (eventData.EventTimestamp >= startDateTime) && (eventData.EventTimestamp <= endDateTime));

            EventDataListResponse response = client.EventOperations.ListEvents(filterString, selectedProperties: null);

            ResourceManagementClient resClient = new ResourceManagementClient(credentials);

            IList<EventData> logList = response.EventDataCollection.Value;

            ExportOpsLogToCSV(logList, resClient);

            Console.WriteLine("Export completed.");
            Console.WriteLine("Press any key to exit");
            Console.ReadLine();
        }
Beispiel #25
0
        private static async Task <EventData[]> GetCreationLogs(String startTime, String endTime, String resourceId, String operation, InsightsClient client)
        {
            var logs = await GetCreationLogs(startTime, endTime, resourceId, client);

            return(logs.Where(log => log.OperationName.Value.Equals(operation, StringComparison.InvariantCultureIgnoreCase)).ToArray());
        }
Beispiel #26
0
 public PollingService(IPoolingProvider poolingProvider)
 {
     _poolingProvider = poolingProvider;
     _insightsClient  = GetInsightsClient();
 }