public bool RunLAQuery(string tableName)
        {
            try
            {
                // Get credentials fron config.json
                var appConfig   = new AppConfig();
                var credentials = appConfig.GetCredentials();
                customerId   = credentials["workspaceId"];
                clientId     = credentials["clientId"];
                clientSecret = credentials["clientSecret"];
                domain       = credentials["domain"];

                var authEndpoint  = "https://login.microsoftonline.com";
                var tokenAudience = "https://api.loganalytics.io/";

                var adSettings = new ActiveDirectoryServiceSettings
                {
                    AuthenticationEndpoint = new Uri(authEndpoint),
                    TokenAudience          = new Uri(tokenAudience),
                    ValidateAuthority      = true
                };

                var creds = ApplicationTokenProvider.LoginSilentAsync(domain, clientId, clientSecret, adSettings).GetAwaiter().GetResult();

                var laClient = new OperationalInsightsDataClient(creds);
                laClient.WorkspaceId = customerId;

                var path    = new SampleDataPath();
                var dirPath = path.GetDirPath();
                tableName = tableName.Replace(dirPath, "").Replace(".json", "");

                string query = tableName
                               + @"| where TimeGenerated > ago(10d)
                             | limit 100";
                var results    = laClient.Query(query);
                var tableCount = results.Tables.Count;
                if (tableCount > 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Calling Log Analytics Error " + ex.Message);
            }
        }
Ejemplo n.º 2
0
        static async Task Main()
        {
            // Get a list of Custom Log file names with their paths
            var files = GetFiles();

            if (files.Length > 0)
            {
                // Get credentials
                var appConfig = new AppConfig();
                var creds     = appConfig.GetCredentials();
                customerId = creds["workspaceId"];
                sharedKey  = creds["sharedKey"];

                var laCheck = new LogAnalyticsCheck();
                var path    = new SampleDataPath();
                var dirPath = path.GetDirPath();

                // Loop through files
                foreach (var file in files)
                {
                    var fileName = file.Replace(dirPath, "");

                    // Check if the file has been pushed to the Log Analytics workspace
                    bool result = await laCheck.RunLAQuery(fileName);

                    if (result == true)
                    {
                        // Prompt user to choose to repush data
                        Console.WriteLine("{0} has been posted. Would you like to post it again?", fileName);
                        var res = Console.ReadLine();
                        if (res.ToLower() == "y" || res.ToLower() == "yes")
                        {
                            PushDataToLog(file);
                        }
                        else
                        {
                            Console.WriteLine("Check Log Analytics for existing data");
                        }
                    }
                    else
                    {
                        PushDataToLog(file);
                    }
                }
            }
            else
            {
                Console.WriteLine("No Custom files in Sample Data");
            }
        }
Ejemplo n.º 3
0
        //Get Custom Log files from Sample Data
        private static string[] GetFiles()
        {
            try
            {
                var      path     = new SampleDataPath();
                var      filePath = path.GetDirPath();
                string[] files    = System.IO.Directory.GetFiles(filePath, "*.json*", SearchOption.AllDirectories);

                return(files);
            }
            catch (Exception excep)
            {
                Console.WriteLine("Get Files Error: " + excep.Message);
                throw new Exception("Get Files Error: " + excep.Message);
            }
        }
Ejemplo n.º 4
0
        //Send a request to the POST API endpoint for Custom Log
        public static void PostData(string signature, string date, string json, string filePath)
        {
            try
            {
                string url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");

                var path    = new SampleDataPath();
                var dirPath = path.GetDirPath();

                logName = filePath.Replace(dirPath, "").Replace("_CL.json", "").Replace(".json", "");
                client.DefaultRequestHeaders.Add("Log-Type", logName);
                client.DefaultRequestHeaders.Add("Authorization", signature);
                client.DefaultRequestHeaders.Add("x-ms-date", date);
                client.DefaultRequestHeaders.Add("time-generated-field", timeStampField);

                HttpContent httpContent = new StringContent(json, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                Task <HttpResponseMessage> response = client.PostAsync(new Uri(url), httpContent);
                HttpContent responseContent         = response.Result.Content;
                string      result = responseContent.ReadAsStringAsync().Result;

                var fileName = logName + "_CL.json";

                if (response.Result.StatusCode.ToString().Contains("OK"))
                {
                    Console.WriteLine("{0} is successfully pushed", fileName);
                }
                else
                {
                    Console.WriteLine("Failed to push {0}", fileName);
                }
            }
            catch (Exception excep)
            {
                Console.WriteLine("API Post Exception: " + excep.Message);
            }
        }
Ejemplo n.º 5
0
        public bool RunLAQuery(string tableName)
        {
            try
            {
                // Get credentials fron config.json
                var appConfig   = new AppConfig();
                var credentials = appConfig.GetCredentials();
                customerId   = credentials["workspaceId"];
                clientId     = credentials["clientId"];
                clientSecret = credentials["clientSecret"];
                domain       = credentials["domain"];

                var authEndpoint  = "https://login.microsoftonline.com";
                var tokenAudience = "https://api.loganalytics.io/";

                var adSettings = new ActiveDirectoryServiceSettings
                {
                    AuthenticationEndpoint = new Uri(authEndpoint),
                    TokenAudience          = new Uri(tokenAudience),
                    ValidateAuthority      = true
                };

                var creds = ApplicationTokenProvider.LoginSilentAsync(domain, clientId, clientSecret, adSettings).GetAwaiter().GetResult();

                var laClient = new OperationalInsightsDataClient(creds);
                laClient.WorkspaceId = customerId;

                //get custom table name
                var path    = new SampleDataPath();
                var dirPath = path.GetDirPath();
                tableName = tableName.Replace(dirPath, "").Replace(".json", "");

                //get a list of table names in your workspace
                var    tableNameList = new List <string>();
                string query         = @"search * | distinct $table";
                var    result        = laClient.Query(query).Tables;
                foreach (var table in result)
                {
                    var rows = table.Rows;
                    foreach (var r in rows)
                    {
                        var customFileName = r[0];
                        if (customFileName.EndsWith("_CL"))
                        {
                            tableNameList.Add(customFileName);
                        }
                    }
                }

                //check if the custom table name exists in the list
                if (tableNameList.Contains(tableName) == false)
                {
                    return(false);
                }
                else
                {
                    //check if there's any data in the table for last 7 days
                    string query1 = tableName
                                    + @"| where TimeGenerated > ago(7d)
                             | limit 10";
                    var results    = laClient.Query(query1);
                    var tableCount = results.Tables.Count;
                    if (tableCount > 0)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Calling Log Analytics Error " + ex.Message);
            }
        }