Ejemplo n.º 1
0
        private void InternalTrace([CallerMemberName] string aCallerMemberName = null)
        {
            if (aCallerMemberName == null)
            {
                return;
            }
            var callerMethod = GetType().GetMethod(aCallerMemberName);
            var logMessages  =
                callerMethod.GetCustomAttributes(typeof(LogAttribute), true)
                .Cast <LogAttribute>()
                .Select(attribute => attribute.Message);

            foreach (var logMessage in logMessages)
            {
                _logging.Log(string.Format("{0}: {1}", DateTime.Now, logMessage));
            }
        }
Ejemplo n.º 2
0
        private void ReportMetrics(ILifetimeScope container)
        {
            Console.WriteLine("Metric Report...");
            ITestMetricManager manager = container.Resolve <ITestMetricManager>();
            ILogging           logging = container.Resolve <ILogging>();

            var maxRecord = manager
                            .Select((x, i) => new { r = x, index = i })
                            .OrderBy(x => x.r.Tps).Last();

            foreach (TestMetric metric in manager.OrderBy(x => x.Name).ThenBy(x => x.Tps))
            {
                logging.Log(() => $"{metric}, {(maxRecord.r.Tps == metric.Tps ? "Max" : string.Empty)}");
            }

            ByTestName(manager, logging);
            ByBatchSize(manager, logging);
        }
        public void ImplementTaskWithDirectories()
        {
            writeReadOfData.Write("\n\n=============Additional Task with Directories and file==============");

            SearchFile      fileFromDirectories     = new SearchFile(writeReadOfData, logger);
            List <FileInfo> allFiles                = new List <FileInfo>();
            List <string>   allFilesFromDirectories = new List <string>();
            List <string>   identicalFiles          = new List <string>();
            List <string>   distinctFiles           = new List <string>();

            string path;

            DirectoryInfo dirInfo;

            try
            {
                path    = ConfigurationManager.AppSettings.Get("TaskWithDirectories"); // path from App.config
                dirInfo = new DirectoryInfo(path);

                writeReadOfData.Write("All file in your directory and subdirectories: \n");
                allFiles = fileFromDirectories.GetFilesFromDirectory(dirInfo);

                foreach (FileInfo fi in allFiles)
                {
                    allFilesFromDirectories.Add(Path.GetFileName(fi.ToString()));
                }

                fileFromDirectories.OutputFile(allFilesFromDirectories);

                identicalFiles = fileFromDirectories.GetIdenticalFiles(allFilesFromDirectories);
                writeReadOfData.Write("\nIdentical files: ");
                fileFromDirectories.OutputFile(identicalFiles);
                writeReadOfData.Write($"\nCount of Identical files: {identicalFiles.Count}");

                writeReadOfData.Write("\nDistinct files: \n");
                distinctFiles = fileFromDirectories.GetDistinctFiles(allFilesFromDirectories);
                fileFromDirectories.OutputFile(distinctFiles);
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Error, ex.Message);
            }
        }
Ejemplo n.º 4
0
        public async Task <HtmlDocument> GetPage(HttpClient httpClient, string sourceLink, ILogging logging)
        {
            var pageResponse = await httpClient.GetAsync(sourceLink);

            string pageResponseBody = pageResponse.Content == null ? string.Empty : await pageResponse.Content.ReadAsStringAsync();

            if (!pageResponse.IsSuccessStatusCode && pageResponse.StatusCode != HttpStatusCode.NotFound)
            {
                logging.Log($"Failed to GET {sourceLink}. Received {pageResponse.StatusCode}: {pageResponseBody}");
            }
            if (pageResponse.StatusCode == HttpStatusCode.NotFound)
            {
                return(null);                       // Exit gracefully so the message isn't retried.
            }
            pageResponse.EnsureSuccessStatusCode(); // Fail hard so the message is retried.
            var htmlDoc = new HtmlDocument();

            htmlDoc.LoadHtml(pageResponseBody);
            return(htmlDoc);
        }
Ejemplo n.º 5
0
        public IActionResult TestLongRunning([FromServices] IDataClient dataClient, [FromServices] IIAM iam, string customerShortName, string projectShortName, int timeout)
        {
            var parameters = new List <NpgsqlParameter>
            {
                new NpgsqlParameter("v_timeout", NpgsqlDbType.Integer)
                {
                    Value = timeout
                },
            };

            var projectConfig = iam.GetProjectConfig(customerShortName, projectShortName);
            var request       = new GreenplumStoredProcedureRequest(projectConfig.GreenplumConfig.RawConnectionString, "usp_timeout_test", parameters);

            var stopWatch = Stopwatch.StartNew();

            dataClient.ExecuteScalar <object>(request);

            _logging.Log($"Long-running-test ran for: { stopWatch.Elapsed }");
            return(Ok());
        }
Ejemplo n.º 6
0
        private void DisplayDetail(RateDetail detail)
        {
            int count = detail.NewCount + detail.BatchCount;

            var fields = new List <string>
            {
                $"{Name,-10}",
                $"Service={detail.Name,-20}",
                $"Count=({count,8:D} / {detail.TpsRate:00000000.00})",
                $"Batches=({detail.BatchCount, 5:D} / {detail.TpsReadRate:00000.00})",
                $"New=({detail.NewCount, 5:D} / {detail.TpsNewRate:00000.00})",
                $"Error Count={detail.ErrorCount, 5:D}",
                $"Retry={detail.RetryCount, 5:D}",
            };

            if (!string.IsNullOrWhiteSpace(detail.LastErrorMessage))
            {
                fields.Add($"LastError: {detail.LastErrorMessage}");
            }

            _logging.Log(() => string.Join(", ", fields));
        }
Ejemplo n.º 7
0
        ApplySettingsAsync()
        {
            Task <JObject> settingsFromFileTask = _settings.ReadSettings();
            JObject        settingsFromFile     = await settingsFromFileTask;

            //TODO: Check to see if a file has been added to.Ignore it if it hasn't been.
            // TODO: Clean up logfile at various points.

            LotteryFile     = new List <string>();
            _lotteryJObject = new List <JObject>();

            // Checks for True/False for scraping websites on first run. If true, sets up Quartz timers to scrape new
            // winning numbers automatically.
            var scrapeWebsites = settingsFromFile["ScrapeLotteryWebsites"].ToObject <bool>();

            // Takes each item from the array of json lottery files and adds it to a list
            foreach (JToken itm in settingsFromFile["LotteryMasterFiles"])
            {
                LotteryFile.Add(itm.ToString());
            }

            // Descending for loop to allow for removing any files that are not present while logging such.
            for (int i = LotteryFile.Count - 1; i >= 0; i--)
            {
                try
                {
                    // tries to create list of json objects from the contents of the file from config
                    _lotteryJObject.Add(JObject.Parse(File.ReadAllText($"./Data Files/{LotteryFile[i]}")));
                }
                catch (Exception) when(!File.Exists($"./Data Files/{LotteryFile[i]}"))
                {
                    _logger.Log($"{DateTime.Now} : " +
                                $"File \"{LotteryFile[i]}\" Does Not Exist. Verify the folder location & is correctly named in the config.\n" +
                                "    * Check the config.json file for proper format.");

                    LotteryFile.Remove(LotteryFile[i]);
                }
            }
Ejemplo n.º 8
0
        public void ImplementTaskWithExcel()
        {
            writeReadOfData.Write("\n\n=============Additional Task with Excel File==============");
            try
            {
                ExcelData excelData = new ExcelData();

                string firstColumn  = ConfigurationManager.AppSettings.Get("FirstColumn");
                string secondColumn = ConfigurationManager.AppSettings.Get("SecondColumn");
                path = ConfigurationManager.AppSettings.Get("ExcelFilePath"); // path from App.config

                HashSet <string> uniqueElementsFromFirstColumn  = new HashSet <string>();
                HashSet <string> uniqueElementsFromSecondColumn = new HashSet <string>();

                uniqueElementsFromFirstColumn  = excelData.Read(path, firstColumn);
                uniqueElementsFromSecondColumn = excelData.Read(path, secondColumn);
                excelData.Output(writeReadOfData, uniqueElementsFromFirstColumn, uniqueElementsFromSecondColumn);
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Error, ex.Message);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// takes the FileSystemEventArgs and if the file is a picture, call the IController to
        /// handle it, and then report to the ILogging.
        /// </summary>
        /// <param name="source"> not used </param>
        /// <param name="e"> the arguments of the new file </param>
        private void OnCreated(object source, FileSystemEventArgs e)
        {
            // get the file's extension
            string strFileExt = Path.GetExtension(e.FullPath);

            // filter file types
            if (Regex.IsMatch(strFileExt, @"\.jpg|\.png|\.bmp|\.gif|\.jpeg", RegexOptions.IgnoreCase))
            {
                List <String> args = new List <String>();
                args.Add(e.FullPath.TrimEnd(e.Name.ToCharArray()));
                args.Add(e.Name);
                string message = controller.ExecuteCommand(CommandEnum.NewFileCommand, args, out bool result);
                if (result)
                {
                    logger.Log(message, MessageTypeEnum.INFO);
                }
                else
                {
                    logger.Log(message, MessageTypeEnum.FAIL);
                }
            }
        }
Ejemplo n.º 10
0
        private void PopulateXrefAll(IDataClient dataClient, string customer, string project)
        {
            var projectConfig = _iam.GetProjectConfig(customer, project);

            var parameters = new List <NpgsqlParameter>
            {
                new NpgsqlParameter("v_result_schema", NpgsqlDbType.Varchar)
                {
                    Value = projectConfig.GreenplumConfig.ResultSchema
                },
            };

            var request = new GreenplumStoredProcedureRequest(projectConfig.GreenplumConfig.RawConnectionString, "usp_populate_xref_all", parameters);

            dataClient.ExecuteScalar <object>(request);

            _logging.Log("usp_populate_xref_all proc executed");
        }
Ejemplo n.º 11
0
        public void OnGet()
        {
            this.Title = "RazorDemoModel";

            _Logging.Log("In RazorDemoModel");
        }
Ejemplo n.º 12
0
 public static void Info(this ILogging self, string message)
 {
     self.Log(MyLogSeverity.Info, message);
 }
Ejemplo n.º 13
0
 public static void Error(this ILogging self, string message, params object[] args)
 {
     self.Log(MyLogSeverity.Error, message, args);
 }
Ejemplo n.º 14
0
 public static void Warning(this ILogging self, string message, params object[] args)
 {
     self.Log(MyLogSeverity.Warning, message, args);
 }
Ejemplo n.º 15
0
 public static void Debug(this ILogging self, StringBuilder buillder)
 {
     self.Log(MyLogSeverity.Debug, buillder);
 }
Ejemplo n.º 16
0
 public static void Critical(this ILogging self, string message, params object[] args)
 {
     self.Log(MyLogSeverity.Critical, message, args);
 }
Ejemplo n.º 17
0
 public void Start()
 {
     _logger.Log("Engine is started...");
 }
Ejemplo n.º 18
0
 public void Save()
 {
     Console.WriteLine("Saved to db");
     _logging.Log("Ürün loglandı");
 }
Ejemplo n.º 19
0
 private void Log()
 {
     _logger.Log($"Entities tracked: {Table.Entries().Count()}");
 }
Ejemplo n.º 20
0
 public static void Log(string msg)
 {
     logger.Log(msg);
 }
Ejemplo n.º 21
0
 public void Move()
 {
     _engine.Start();
     _logger.Log("Car is moving");
 }
Ejemplo n.º 22
0
        public void SendToAccounting(DateTime date, ILogging logger)
        {
            var databaseClient = new DatabaseClient <QuickBooksOnlineConnection>(new AmazonDynamoDBClient(), logger);
            var qboClient      = new QuickBooksOnlineClient(PrivateAccounting.Constants.LakelandMiPuebloRealmId, databaseClient, logger);

            var originalMonth = date.Month;

            var client = new CloverClient(
                Environment.GetEnvironmentVariable("CLOVER_MI_PUEBLO_CHICKEN_ACCESS_TOKEN"),
                Environment.GetEnvironmentVariable("CLOVER_MI_PUEBLO_CHICKEN_MERCHANT_ID"),
                logger
                );

            var restaurantCustomer = qboClient
                                     .QueryAll <Customer>($"select * from Customer where Id = '{PrivateAccounting.Constants.LakelandMiPuebloAccountRestaurant}'")
                                     .First();

            var cashTenderType = client.QueryAll <Tender>($"tenders")
                                 .Single(x => string.Equals(x.LabelKey, "com.clover.tender.cash", StringComparison.OrdinalIgnoreCase));

            do
            {
                var salesReceipts = qboClient.QueryAll <SalesReceipt>(
                    $"select * from SalesReceipt where CustomerRef = '{PrivateAccounting.Constants.LakelandMiPuebloAccountRestaurant}' and TxnDate = '{date:yyyy-MM-dd}'");

                if (salesReceipts.Any())
                {
                    logger.Log($"Skipping {date:yyyy-MM-dd}, because a sales receipt already exists.");
                }
                else
                {
                    var today    = new DateTimeOffset(date).ToUnixTimeMilliseconds();
                    var tomorrow = new DateTimeOffset(date.AddDays(1)).ToUnixTimeMilliseconds();
                    var result   =
                        client.QueryAll <Payment>($"payments?filter=createdTime>={today}&filter=createdTime<{tomorrow}");

                    var cashPayments = result.Where(x => x.Tender.Id == cashTenderType.Id).ToList();
                    var cardPayments = result.Where(x => x.Tender.Id != cashTenderType.Id).ToList();
                    var cashTotal    = GetTotal(cashPayments);
                    var cardTotal    = GetTotal(cardPayments);
                    if (cashTotal > 0)
                    {
                        CreateSalesReceipt(
                            qboClient,
                            restaurantCustomer.Id,
                            restaurantCustomer.DefaultTaxCodeRef.Value,
                            PrivateAccounting.Constants.LakelandMiPuebloProductRestaurant,
                            date,
                            GetTotal(cashPayments),
                            "Restaurant sales using cash in Clover Register");
                    }

                    if (cardTotal > 0)
                    {
                        CreateSalesReceipt(
                            qboClient,
                            restaurantCustomer.Id,
                            restaurantCustomer.DefaultTaxCodeRef.Value,
                            PrivateAccounting.Constants.LakelandMiPuebloProductRestaurant,
                            date,
                            cardTotal,
                            "Restaurant sales using credit card in Clover Register");
                    }
                }
                date = date.AddDays(1);
            } while (date.Month == originalMonth);
        }
Ejemplo n.º 23
0
 public static void Critical(this ILogging self, StringBuilder buillder)
 {
     self.Log(MyLogSeverity.Critical, buillder);
 }
Ejemplo n.º 24
0
 public static void Warning(this ILogging self, string message)
 {
     self.Log(MyLogSeverity.Warning, message);
 }
Ejemplo n.º 25
0
 public static void Info(this ILogging self, StringBuilder buillder)
 {
     self.Log(MyLogSeverity.Info, buillder);
 }
Ejemplo n.º 26
0
 public static void Error(this ILogging self, string message)
 {
     self.Log(MyLogSeverity.Error, message);
 }
Ejemplo n.º 27
0
 public static void Warning(this ILogging self, StringBuilder buillder)
 {
     self.Log(MyLogSeverity.Warning, buillder);
 }
Ejemplo n.º 28
0
 public static void Critical(this ILogging self, string message)
 {
     self.Log(MyLogSeverity.Critical, message);
 }
Ejemplo n.º 29
0
 public static void Error(this ILogging self, StringBuilder buillder)
 {
     self.Log(MyLogSeverity.Error, buillder);
 }
Ejemplo n.º 30
0
 public static void Debug(this ILogging self, string message)
 {
     self.Log(MyLogSeverity.Debug, message);
 }