public void is_warn_enabled_honors_threshold()
 {
     var sut = new LoggerService();
     sut.Threshold = LogLevel.Warn;
     Assert.True(sut.IsWarnEnabled);
     sut.Threshold = LogLevel.Error;
     Assert.False(sut.IsWarnEnabled);
 }
Пример #2
0
        public Form1(IRepository repository)
        {
            //Привязываемся к хранилищу
            _repository = repository;

            //Инициализация компонентов формы
            InitializeComponent();

            //класс отвечающий за представление
            _calculView = new CalculView
            {
                ComboBoxOperators = this.comboBox1,
                TextBoxArg1 = this.textBox1,
                TextBoxArg2 = this.textBox2,
                TextBoxResult = this.textBox3,
                ListBox = this.listBox1
            };

            //Заполняем форму данными
            _calculView.Init();

            //Класс, отвечающий за вычисления
            _calculService = new CalculService();
            
            //класс отвечающий за запись лога в хранилище
            _loggerService = new LoggerService(_repository);
        }
 public void is_debug_enabled_honors_threshold()
 {
     var sut = new LoggerService();
     sut.Threshold = LogLevel.Debug;
     Assert.True(sut.IsDebugEnabled);
     sut.Threshold = LogLevel.Info;
     Assert.False(sut.IsDebugEnabled);
 }
 public void is_info_enabled_honors_threshold()
 {
     var sut = new LoggerService();
     sut.Threshold = LogLevel.Info;
     Assert.True(sut.IsInfoEnabled);
     sut.Threshold = LogLevel.Warn;
     Assert.False(sut.IsInfoEnabled);
 }
 public void is_error_enabled_is_always_true()
 {
     var sut = new LoggerService();
     sut.Threshold = LogLevel.Info;
     Assert.True(sut.IsErrorEnabled);
     sut.Threshold = LogLevel.Error;
     Assert.True(sut.IsErrorEnabled);
 }
 public void is_perf_enabled_honors_threshold()
 {
     var sut = new LoggerService();
     sut.Threshold = LogLevel.Perf;
     Assert.True(sut.IsPerfEnabled);
     sut.Threshold = LogLevel.Warn;
     Assert.False(sut.IsPerfEnabled);
 }
        public void logging_perf_adds_extra_performance_information_to_the_log_message()
        {
            var sut = new LoggerService();
            var logger = sut.GetLogger("test");
            var entry = sut
                .Entries
                .CreateCollection();

            using (logger.Perf("Some performance {0}", "entry"))
            {
            }

            Assert.Equal(1, entry.Count);
            // Some performance entry [00:00:00.0045605 (4ms)]
            Assert.True(Regex.IsMatch(entry[0].Message, @"Some performance entry \[\d\d:\d\d:\d\d\.\d*? \(\d*?ms\)\]"));
        }
Пример #8
0
        private async Task <string> CreateOpportunityAsync(SalesForceResponse salesForceResponse, CreateOpportunityFields createOpportunityFields)
        {
            string opportunityId        = string.Empty;
            string createOpportunityUrl = salesForceResponse.instance_url + "/services/data/v26.0/sobjects/Opportunity/";

            LoggerService.Debug("Entered CreateOpportunityAsync()", "INFO");
            try
            {
                LoggerService.Debug("Inside CreateOpportunityAsync() 2", "");
                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Add("Authorization", "OAuth " + salesForceResponse.access_token);

                    httpResponseMessage = await httpClient.PostAsJsonAsync(createOpportunityUrl, createOpportunityFields);

                    LoggerService.Debug("CreateOpportunityAsync()- Response for httpResponseMessage:", httpResponseMessage);

                    var opportunityUserResult = await httpResponseMessage.Content.ReadAsStringAsync();

                    LoggerService.Debug("CreateOpportunityAsync() - Response for opportunityUserResult :", opportunityUserResult);

                    if (httpResponseMessage != null && httpResponseMessage.IsSuccessStatusCode)
                    {
                        LoggerService.Debug("httpResponseMessage = SuccessStatusCode ", "");
                        var opportunityUserResultObject = (IDictionary <string, object>)javaScriptSerializer.DeserializeObject(opportunityUserResult);
                        opportunityId = Convert.ToString(opportunityUserResultObject["id"]);
                        LoggerService.Debug("opportunityId:", opportunityId);
                    }
                    else
                    {
                        LoggerService.Debug("httpResponseMessage = Error ", httpResponseMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerService.Error("", "SalesForceBL->CreateOpportunityAsync() 2: " + "\r\nError Message: " + ex.Message + "\r\nStackTrace: " + ex.StackTrace);
            }

            return(opportunityId);
        }
        private Task DiscordAppClientOnLog(DiscordAppClient discordAppClient, LogMessage logMessage)
        {
            Task.Run(async() =>
            {
                var botId   = discordAppClient.DiscordShardedClient?.CurrentUser?.Id;
                var botName = discordAppClient.DiscordShardedClient?.CurrentUser?.ToString();
                var message = discordAppClient.DiscordShardedClient?.CurrentUser == null ? $"[Bot] {logMessage.ToString()}" : $"[Bot {botId}] {botName}: {logMessage.ToString()}";

                switch (logMessage.Severity)
                {
                case LogSeverity.Critical:
                    await LoggerService.LogMessageAsync(message, ConsoleColor.Red).ConfigureAwait(false);
                    break;

                case LogSeverity.Error:
                    await LoggerService.LogMessageAsync(message, ConsoleColor.Red).ConfigureAwait(false);
                    break;

                case LogSeverity.Warning:
                    await LoggerService.LogMessageAsync(message, ConsoleColor.Yellow).ConfigureAwait(false);
                    break;

                case LogSeverity.Info:
                    await LoggerService.LogMessageAsync(message).ConfigureAwait(false);
                    break;

                case LogSeverity.Verbose:
                    await LoggerService.LogMessageAsync(message).ConfigureAwait(false);
                    break;

                case LogSeverity.Debug:
                    await LoggerService.LogMessageAsync(message, ConsoleColor.Cyan).ConfigureAwait(false);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }).ConfigureAwait(false);

            return(Task.CompletedTask);
        }
        /// <summary>
        /// Load object from the cache
        /// </summary>
        /// <param name="key">Identification of the object</param>
        /// <returns></returns>
        public object Load(string key)
        {
            // if there is no call back, we can do nothing but return the item
            if (this.GetLastPublishDateCallBack == null)
            {
                return(FindOrRemove(key));
            }


            //DateTime? insertionDateScheduledCallBack = Cache[string.Format("{0}_S", key)] as DateTime?;
            //if (insertionDateScheduledCallBack != null)
            //{
            //    // do not call back now, it is already scheduled to happen!
            //    return FindOrRemove(key);
            //}

            object objectToReturn = FindOrRemove(key);

            if (objectToReturn == null)
            {
                return(null);
            }
            DateTime?insertionDateDirectCallBack = Cache[string.Format("{0}_D", key)] as DateTime?;

            if (insertionDateDirectCallBack == null)
            {
                return(objectToReturn);
            }

            DateTime lastPublishDate = GetLastPublishDateCallBack(key, objectToReturn);

            if (insertionDateDirectCallBack.Value < lastPublishDate)
            {
                LoggerService.Debug("removing item with key '{0}' from cache because it has been re/unpublished", key);
                Cache.Remove(key);
                Cache.Remove(string.Format("{0}_D", key));
                return(null);
            }

            return(Cache[key]);
        }
        public void LoadRecords()
        {
            if (_loaded)
            {
                return;
            }

            _loaded = true;
            IsBusy  = true;
            ThreadInvoker.BackInvoke(() => {
                //通知进度;
                var opStream = new OperatebleStream(Stream);

                //释放中断处理;
                _dispoingActions.Add(opStream.Break);

                var percentage = 0;
                //通知进度;
                opStream.PositionChanged += (sender, e) => {
                    if (percentage == (int)(e * 100 / opStream.Length))
                    {
                        return;
                    }
                    percentage = (int)(e * 100 / opStream.Length);
                    BusyWord   = $"{percentage}%";
                };

                try {
                    Records = UsnRecordV2.ReadRecordsFromStream(opStream).ToList();
                    IsBusy  = false;
                }
                catch (Exception ex) {
                    LoggerService.WriteException(ex);
                    BusyWord = ex.Message;
                }


                //取消释放中断处理;
                _dispoingActions.Remove(opStream.Break);
            });
        }
        private static void OnPart_Disposing(object sender, EventArgs e)
        {
            if (!(sender is IPartition part))
            {
                return;
            }

            if (part.TypeGuid != Constants.PartitionType_Ext)
            {
                return;
            }

            PartitionStoken stoken = null;

            try {
                stoken = part.GetStoken(Constants.PartitionKey_Ext);
            }
            catch (Exception ex) {
                LoggerService.WriteCallerLine(ex.Message);
            }

            if (stoken == null)
            {
                return;
            }

            var partInfo = stoken.GetInstance <ExtPartInfo>(Constants.PartitionStokenTag_ExtPartInfo);

            if (partInfo == null)
            {
                return;
            }

            //释放非托管流;
            try {
                partInfo.ExtUnmanagedManager?.Dispose();
            }
            catch (Exception ex) {
                LoggerService.WriteCallerLine(ex.Message);
            }
        }
 /// <summary>
 /// Listen to the websocket
 /// </summary>
 /// <returns></returns>
 public async Task ListenAsync()
 {
     await Task.Factory.StartNew(async() =>
     {
         var buffer         = new Byte[1024 * 4];
         string messageJson = "";
         while (Client.State == WebSocketState.Open)
         {
             try
             {
                 Array.Clear(buffer, 0, buffer.Count());
                 var result  = await Client.ReceiveAsync(new ArraySegment <byte>(buffer), Cts.Token);
                 messageJson = Encoding.UTF8.GetString(buffer, 0, result.Count);
                 while (!result.EndOfMessage)
                 {
                     Array.Clear(buffer, 0, buffer.Count());
                     result       = await Client.ReceiveAsync(new ArraySegment <byte>(buffer), Cts.Token);
                     messageJson += Encoding.UTF8.GetString(buffer, 0, result.Count);
                 }
                 if (result.MessageType == WebSocketMessageType.Close)
                 {
                     await CloseAsync();
                 }
                 else if (result.MessageType == WebSocketMessageType.Binary)
                 {
                     await Client.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "Cannot accept binary frame", CancellationToken.None);
                 }
                 else
                 {
                     OnData?.Invoke(messageJson);
                 }
             }
             catch (Exception e)
             {
                 LoggerService.Log(
                     LogLevel.Error,
                     $"{e.Message}: While distributing websocket message: {messageJson}");
             }
         }
     }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
 }
Пример #14
0
        public static void BootstrapCommand(CommandLineApplication command)
        {
            command.Description = "Bootstraps folders structure for static website";

            command.HelpOption("-?|-h|--help");

            command.OnExecute(() =>
            {
                LoggerService.WriteLogMessage("Bootstraping folder strcuture").Wait();

                var configurationService = new ConfigurationService();
                var examplePath          = Path.Combine(Directory.GetCurrentDirectory(), configurationService.Configuration.Engine.Path, "Data", "src");
                var sourcePath           = Path.Combine(Directory.GetCurrentDirectory(), configurationService.Configuration.Source.Path);

                LoggerService.WriteLogMessage($"Example from: {examplePath}").Wait();
                LoggerService.WriteLogMessage($"Bootstraped to: {sourcePath}").Wait();

                var dataReader = new FileSystemBinaryContentReaderService <BinaryContentModel>(examplePath);
                var dataWriter = new FileSystemBinaryContentWriterService <BinaryContentModel>(sourcePath);

                var taskGetList = dataReader.LoadContentsIdsAsync(true);
                taskGetList.Wait();

                var files = taskGetList.Result;

                foreach (var file in files)
                {
                    var taskLoadContent = dataReader.LoadContentByIdAsync(file);
                    taskLoadContent.Wait();

                    var content = taskLoadContent.Result;
                    dataWriter.SaveContentAsync(file, content).Wait();

                    LoggerService.WriteLogMessage($"Bootstraped file: {file}").Wait();
                }

                LoggerService.WriteLogMessage("Bootstraping finished successfully").Wait();

                return(0);
            });
        }
Пример #15
0
        /// <summary>
        /// 查找文档区域是否已经添加了File相关文档;
        /// </summary>
        /// <param name="tag"></param>
        internal static IDocumentBase CheckTagAddedToDocument(IFile file)
        {
            var mainDocService = DocumentService.MainDocumentService;

            if (mainDocService == null)
            {
                LoggerService.WriteCallerLine($"{nameof(mainDocService)} can't be null.");
                return(null);
            }

            var doc = mainDocService.CurrentDocuments.FirstOrDefault(p =>
                                                                     p.GetInstance <IFile>(Contracts.FileExplorer.Constants.DocumentTag_File) == file);

            if (doc != null)
            {
                mainDocService.SelectedDocument = doc;
                return(doc);
            }

            return(null);
        }
Пример #16
0
        /// <summary>
        /// Executes the command.
        /// </summary>
        /// <param name="groupName">Name of the group.</param>
        public void ExecuteCommand(string groupName, double maxExecutionTime)
        {
            try
            {
                var settings = SettingsHelper.Get();

                string cmdProtractorRunner = string.Format(
                    command,
                    settings.BaseTestPath,
                    groupName);

                LoggerService.LogInformation("Executing: " + cmdProtractorRunner);

                var process = System.Diagnostics.Process.Start("CMD.exe", "/C " + cmdProtractorRunner);
                process.WaitForExit(Int32.Parse(maxExecutionTime.ToString()));
            }
            catch (Exception ex)
            {
                LoggerService.LogException(ex);
            }
        }
Пример #17
0
        protected override Point OnDeserialize(XElement xElem)
        {
            if (xElem.Name != XElemName_Point)
            {
                return(null);
            }

            try {
                var positionElem = xElem.Element(XElemName_Position);

                var x = double.Parse(positionElem.Attribute(XPropName_X).Value);
                var y = double.Parse(positionElem.Attribute(XPropName_Y).Value);

                return(new Point(new Vector2D(x, y)));
            }
            catch (Exception ex) {
                LoggerService.WriteException(ex);
            }

            return(null);
        }
Пример #18
0
        public IHttpActionResult Get(int id)
        {
            LoggerService.Info("Getting 'Exercise' by id = '{0}'", id);

            return(ExecuteRequest(() =>
            {
                var exerciseDTO = _service.Get(id);

                if (exerciseDTO != null)
                {
                    var exercise = _mapper.Map <Exercise>(exerciseDTO);

                    LogInfoObjectToJson(exercise);
                    return Ok <Exercise>(exercise);
                }

                LoggerService.Info("There is no 'Exercise' with Id = '{0}'", id);

                return NotFound();
            }));
        }
Пример #19
0
        public string BuildLogFolderStructure()
        {
            string strFolderName = DateTime.Today.Year.ToString() + @"\";

            try
            {
                strFolderName += DateTime.Now.ToString("MMMM") + @"\";
                string CurrDirectoryPath = strFolderName;
                if (!File.Exists(CurrDirectoryPath))
                {
                    Directory.CreateDirectory(CurrDirectoryPath);
                }
                strFolderName += DateTime.Today.ToShortDateString();
                strFolderName  = strFolderName.Replace(@"/", @"-");
            }
            catch (Exception ex)
            {
                LoggerService.Error("", "SFService-BuildLogFolderStructure: " + "\r\nError Message: " + ex.Message + "\r\nStackTrace: " + ex.StackTrace);
            }
            return(strFolderName);
        }
        public IFolderBrowserDataContext CreateFolderBrowserDataContext(IHaveFileCollection haveFileCollection)
        {
            var dataContext = new FolderBrowserDataContext(haveFileCollection);

            try {
                CommonEventHelper.PublishEventToHandlers(dataContext as IFolderBrowserDataContext, _folderBrowserViewModelCreatedEventHandlers);
                CommonEventHelper.GetEvent <FolderBrowserDataContextCreatedEvent>().Publish(dataContext);
            }
            catch (Exception ex) {
                LoggerService.WriteException(ex);
            }

            //try {
            //    dataContext.Initialize();
            //}
            //catch(Exception ex) {
            //    LoggerService.WriteException(ex);
            //}

            return(dataContext);
        }
Пример #21
0
        public static async Task Main(string[] args)
        {
            //Load Settings
            var loader = new FileLoader();

            _settings = loader.ReadSettings();
            try
            {
                ServiceProvider = buildServiceProvider().Result;
                var core = ServiceProvider.GetService <ICoreService>();
                await core.Run();
            }
            catch (Exception e)
            {
                var logger = new LoggerService(_settings);
                logger.LogFatal($"Initialization failed with exception: {e}");
                Console.ReadKey();
            }

            Console.ReadKey();
        }
        private void OnSetPos(long pos)
        {
#if DEBUG
            if (pos >= 13878934528 && OriStream.Length == 13878934528)
            {
            }
#endif
            if (pos > OriStream.Length)
            {
                LoggerService.WriteCallerLine($"{nameof(pos)} out of range.({nameof(pos)}:{pos},available length:{OriStream.Length}");
                OriStream.Position = pos;
                return;
            }
            else if (pos < 0)
            {
                LoggerService.WriteCallerLine($"{nameof(pos)} can't be less than zero.({nameof(pos)}:{pos},available length:{OriStream.Length}");
                return;
            }

            OriStream.Position = pos;
        }
Пример #23
0
        public ParsedInfo ParseStream(Stream stream)
        {
            if (!FatFileSystem.Detect(stream))
            {
                return(null);
            }

            try {
                using (var fileSystem = new FatFileSystem(stream)) {
                    var seagments  = GetSeagmentsByFatFileSystem(fileSystem);
                    var parsedInfo = new ParsedInfo(seagments);
                    parsedInfo.ParsedType = fileSystem.FatVariant.ToString();

                    return(parsedInfo);
                }
            }
            catch (Exception ex) {
                LoggerService.WriteException(ex);
                return(null);
            }
        }
Пример #24
0
        //public void Report(string text, string statusBarItemGUID = null) {

        //}

        public void RemoveStatusBarItem(IStatusBarItem item)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            if (!StatusBarItems.Contains(item))
            {
                LoggerService.WriteCallerLine($"{nameof(StatusBarItems)} doesn't contain the {nameof(item)}");
                return;
            }

            try {
                _items.Remove(item);
                _stackGrid.Remove(item);
            }
            catch (Exception ex) {
                LoggerService.WriteCallerLine(ex.Message);
            }
        }
Пример #25
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting MonoCMS...");

            // launch services
            Config.init();
            LoggerService.init();
            DBConnectionService.init();
            WebServerService.init();

            // bind controllers
            Console.WriteLine("\nBegin controllers initialization...");
            PostsController.init();
            UsersController.init();

            Console.WriteLine("\nControllers initialized successfully.!");

            Console.WriteLine("\nMonoCMS successfully started.");
            Console.WriteLine("\nPress any key for exit...");
            Console.ReadLine();
        }
        public void SetUnitHashValueStatus(string name, string hashValue, string hasherGUID, string hashValueStatusType)
        {
            if (_streamWriter == null)
            {
                throw new InvalidOperationException($"Please invoke {nameof(BeginEdit)} before invoking this method.");
            }

            try {
                //一行内写入名称,哈希值,哈希器GUID,哈希值状态类型;
                _streamWriter.WriteLine(
                    GetFormattedPropFromProp(name) +
                    GetFormattedPropFromProp(hashValue) +
                    GetFormattedPropFromProp(hasherGUID) +
                    GetFormattedPropFromProp(hashValueStatusType)
                    );
            }
            catch (Exception ex) {
                LoggerService.WriteException(ex);
                throw;
            }
        }
Пример #27
0
        // GET: api/Set/5
        public IHttpActionResult Get(int id)
        {
            LoggerService.Info("Getting 'Set' by id = '{0}'", id);

            return(ExecuteRequest(() =>
            {
                var setDTO = _service.Get(id);

                if (setDTO != null)
                {
                    var set = _mapper.Map <Set>(setDTO);

                    LogInfoObjectToJson(set);
                    return Ok <Set>(set);
                }

                LoggerService.Info("There is no 'Set' with Id = '{0}'", id);

                return NotFound();
            }));
        }
Пример #28
0
        protected override Line OnDeserialize(XElement xElem)
        {
            try {
                var startElem = xElem.Element(XElemName_Start);
                var endElem   = xElem.Element(XElemName_End);

                var startX = double.Parse(startElem.Attribute(XPropName_X).Value);
                var startY = double.Parse(startElem.Attribute(XPropName_Y).Value);
                var endX   = double.Parse(endElem.Attribute(XPropName_X).Value);
                var endY   = double.Parse(endElem.Attribute(XPropName_Y).Value);

                var line2D = new Line2D(new Vector2D(startX, startY), new Vector2D(endX, endY));

                return(new Line(line2D));
            }
            catch (Exception ex) {
                LoggerService.WriteException(ex);
            }

            return(null);
        }
Пример #29
0
        public void CalculateAverageSessionTime_Pass()
        {
            // Arrange
            LoggerService _loggerService = new LoggerService();
            bool          expected       = true;
            bool          actual         = false;

            // Read logs from this path
            string        path    = "C:\\Users\\Midnightdrop\\Documents\\GitHub\\GreetNGroup\\Backend\\UnitTest\\UADTest\\TestLogs\\ServiceLogs\\PassLogs_SessionTimes";
            List <GNGLog> logList = new List <GNGLog>();

            // Act
            logList = _loggerService.ReadLogsPath(path);
            var averageTime = _uadService.CalculateSessionInformation(logList);

            if (averageTime[0].CompareTo("60") == 0)
            {
                actual = true;
            }
            Assert.AreEqual(actual, expected);
        }
Пример #30
0
        //初始化核心;
        private void InitilizeCore()
        {
            IsLoading = true;

            ThreadInvoker.BackInvoke(() => {
                try {
                    _comObject = ComObject.Current;
                }
                catch (Exception ex) {
                    LoggerService.WriteCallerLine(ex.Message);
                    return;
                }

                var units = GetUnitsFromObject();

                ThreadInvoker.UIInvoke(() => {
                    DriveUnits.AddRange(units);
                });
                IsLoading = false;
            });
        }
        // region Workflow

        private async Task DeleteAllStreamingLocatorsForAssetAsync(string assetName)
        {
            ListStreamingLocatorsResponse locators = await Client.Assets.ListStreamingLocatorsAsync(
                resourceGroupName : Config.ResourceGroup,
                accountName : Config.AccountName,
                assetName : assetName
                );

            LoggerService.Info($"Deleting {locators.StreamingLocators.Count} streaming locator(s)", LoggerService.Stop);

            foreach (AssetStreamingLocator locator in locators.StreamingLocators)
            {
                await Client.StreamingLocators.DeleteAsync(
                    resourceGroupName : Config.ResourceGroup,
                    accountName : Config.AccountName,
                    streamingLocatorName : locator.Name
                    );
            }

            LoggerService.Info("Deleted all streaming locator(s)", LoggerService.Stop);
        }
Пример #32
0
        static void CreateDB(BussinesService bussinesService, LoggerService loggerService)
        {
            loggerService.Info("Create a database...");

            bussinesService.RegisterNewClient("Johann", "Bach", "839404983", 473637849);
            bussinesService.RegisterNewClient("Wolfgang", "Mozart", "6272893", 2638);
            bussinesService.RegisterNewClient("Giuseppe", "Verdi", "896232", 855790);
            bussinesService.RegisterNewClient("Sergei", "Rahmaninov", "213568", 5670);
            bussinesService.RegisterNewClient("Franz", "Schubert", "645689", 54680);

            foreach (var stock in allStocksType)
            {
                if ((stock.Key != "Tatneft") || (stock.Key != "NLMK"))
                {
                    bussinesService.RegisterNewStock(bussinesService.GetClient(1), stock);
                }

                if ((stock.Key != "KAMAZ") || (stock.Key != "Norilsk Nickel"))
                {
                    bussinesService.RegisterNewStock(bussinesService.GetClient(2), stock);
                }

                if ((stock.Key != "DIXY Group") || (stock.Key != "Severstal"))
                {
                    bussinesService.RegisterNewStock(bussinesService.GetClient(3), stock);
                }

                if ((stock.Key != "AvtoVAZ") || (stock.Key != "Yandex"))
                {
                    bussinesService.RegisterNewStock(bussinesService.GetClient(4), stock);
                }

                if ((stock.Key != "Rosneft Oil Company") || (stock.Key != "LUKOIL NK"))
                {
                    bussinesService.RegisterNewStock(bussinesService.GetClient(5), stock);
                }
            }

            loggerService.Info("The database is created. We can start to trading!");
        }
Пример #33
0
        public override DateTime GetLastPublishedDateCallBack(string key, object cachedItem)
        {
            LoggerService.Debug(">>GetLastPublishedDateCallBack {0}", LoggingCategory.Performance, key);
            if (cachedItem == null)
            {
                return(DateTime.Now); // this will force the item to be removed from the cache
            }
            if (cachedItem is IPage)
            {
                DateTime dt = GetLastPublishedDateByUri(((IPage)cachedItem).Id);
                LoggerService.Debug("<<GetLastPublishedDateCallBack {0}", LoggingCategory.Performance, key);
                return(dt);
            }

            Match m = rePageContentByUrl.Match(key);

            if (m.Success)
            {
                int publicationId = Convert.ToInt32(m.Groups[1].Value);
                if (publicationId == Int32.MinValue)
                {
                    publicationId = 0;
                }
                string   url = m.Groups[2].Value;
                DateTime dt  = GetLastPublishedDateByUrl(url);
                LoggerService.Debug("<<GetLastPublishedDateCallBack {0} -- regex", LoggingCategory.Performance, key);
                return(dt);
            }

            if (key.StartsWith("PageContentByUri_"))
            {
                string   uri = key.Substring("PageContentByUri_".Length);
                DateTime dt  = GetLastPublishedDateByUri(uri);
                LoggerService.Debug("<<GetLastPublishedDateCallBack {0} -- 'PageContentByUri_'", LoggingCategory.Performance, key);
                return(dt);
            }


            throw new Exception(string.Format("GetLastPublishedDateCallBack called for unexpected object type '{0}' or with unexpected key '{1}'", cachedItem.GetType(), key));
        }
Пример #34
0
        private SiteMapNode ReadSitemapFromXml(string sitemapUrl)
        {
            LoggerService.Debug(">>ReadSitemapFromXml", LoggingCategory.Performance);
            SiteMapNode rootNode = null;

            NodeDictionary = new Dictionary <string, SiteMapNode>();

            string sitemap;

            if (!PageFactory.TryFindPageContent(sitemapUrl, out sitemap))
            {
                sitemap = emptySiteMapString();
            }
            LoggerService.Debug(string.Format("loaded sitemap with url {0}, length {1}", sitemapUrl, sitemap.Length), LoggingCategory.Performance);

            XDocument xDoc = XDocument.Parse(sitemap);

            LoggerService.Debug("parsed sitemap into XDocument", LoggingCategory.Performance);

            //XElement siteMapRoot = xDoc.Element("siteMap");
            XElement siteMapRoot = xDoc.Root;


            try
            {
                rootNode = new TridionSiteMapNode(this, String.Empty, "root_" + PageFactory.PageProvider.PublicationId, String.Empty, String.Empty, String.Empty, new ArrayList(), new NameValueCollection(), new NameValueCollection(), String.Empty);
                LoggerService.Debug("created root node", LoggingCategory.Performance);
                AddNode(rootNode);
                LoggerService.Debug("added root node", LoggingCategory.Performance);

                //Fill down the hierarchy.
                AddChildren(rootNode, siteMapRoot.Elements(), 1);
            }
            catch (Exception e)
            {
                Exception e2 = e;
            }
            LoggerService.Debug("<<ReadSitemapFromXml", LoggingCategory.Performance);
            return(rootNode);
        }
Пример #35
0
        static void Main(string[] args)
        {
            XmlConfigurator.Configure();

            var logger = LogManager.GetLogger("SampleTextLogger");

            var loggerService = new LoggerService(logger);

            var taskManager = new TaskManager(loggerService);

            var tasksDictionary = new Dictionary <string, TaskManager.Functions>();

            tasksDictionary.Add("first thread", TaskManager.Functions.Linear);
            tasksDictionary.Add("second thread", TaskManager.Functions.Cube);

            Client client = new Client();

            taskManager.AddBadProducerWithConnectedClient(client);


            foreach (var task in tasksDictionary)
            {
                taskManager.AddThread(task.Value, task.Key);
            }

            taskManager.Run();

            while (true)
            {
                if (Console.ReadKey().Key == ConsoleKey.Escape)
                {
                    taskManager.Stop();
                    break;
                }
            }

            Console.WriteLine("\nPress any key to exit...");
            GC.Collect();
            Console.ReadKey();
        }
Пример #36
0
        internal DataSet ExecuteProcedureReturnDataSet(string connString, string proc)
        {
            const string methodName = "ExecuteProcedureReturnDataTable";

            LogCall(methodName, proc);

            SqlConnection conn    = new SqlConnection(connString);
            DataSet       dataSet = new DataSet();

            try
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = proc;

                    AddParameters(cmd.Parameters, parameters);

                    conn.Open();

                    using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd))
                    {
                        sqlDataAdapter.Fill(dataSet);
                    }

                    return(dataSet);
                }
            }
            catch (Exception ex)
            {
                conn.Close();
                LoggerService.LogException(requestId, className, methodName, new Exception(GetSqlWithParams(proc), ex));
                throw;
            }
            finally
            {
                ClearParams();
                LoggerService.LogMethodEnd(requestId, className, methodName);
            }
        }
Пример #37
0
        public IEnumerable <IUnitHashSetStatus> GetAllHashSetStatus()
        {
            if (_streamReader == null)
            {
                throw new InvalidOperationException($"Please invoke {nameof(BeginOpen)} before invoking this method.");
            }

            _streamReader.BaseStream.Position = 0;

            UnitHashSetStatus status = null;

            while (true)
            {
                try {
                    if (_streamReader.EndOfStream)
                    {
                        yield break;
                    }
                    if (_streamReader.BaseStream.Position == _streamReader.BaseStream.Length - 1)
                    {
                        continue;
                    }
                    status = (UnitHashSetStatus)_formatter.Deserialize(_streamReader.BaseStream);
                }
                catch (Exception ex) {
                    LoggerService.WriteException(ex);
                }

                if (status != null)
                {
                    yield return(status);
                }
                else
                {
                    yield break;
                }

                status = null;
            }
        }
        public void log_entries_can_be_formatted()
        {
            var sut = new LoggerService();
            var logger = sut.GetLogger("test");
            var entry = sut
                .Entries
                .CreateCollection();

            logger.Debug("A message with a parameter: {0}", 42);

            Assert.Equal(1, entry.Count);
            Assert.Equal("A message with a parameter: 42", entry[0].Message);
        }
        public void logging_perf_is_a_noop_if_perf_level_is_disabled()
        {
            var sut = new LoggerService();
            var logger = sut.GetLogger("test");
            sut.Threshold = LogLevel.Warn;
            var entry = sut
                .Entries
                .CreateCollection();

            using (logger.Perf("This shouldn't be logged"))
            {
            }

            logger.Warn("This should be logged");

            Assert.Equal(1, entry.Count);
            Assert.Equal("This should be logged", entry[0].Message);
        }
        public void log_entries_can_contain_exception_details()
        {
            var sut = new LoggerService();
            var logger = sut.GetLogger("test");
            var entry = sut
                .Entries
                .CreateCollection();

            logger.Debug(new InvalidOperationException("foo"), "A message with an exception and a parameter ({0}): ", 42);

            Assert.Equal(1, entry.Count);
            Assert.Equal("A message with an exception and a parameter (42): System.InvalidOperationException: foo",
                entry[0].Message);
        }
 public void get_logger_for_type_returns_a_logger_with_the_full_name_of_the_type_as_its_name()
 {
     var sut = new LoggerService();
     var logger = sut.GetLogger(GetType());
     Assert.Equal(GetType().FullName, logger.Name);
 }
        public void log_entries_ticks_for_log_calls_within_the_configured_threshold()
        {
            var sut = new LoggerService();
            var logger = sut.GetLogger("test");
            var entries = sut
                .Entries
                .CreateCollection();

            sut.Threshold = LogLevel.Info;
            logger.Debug("Whatever");
            logger.Debug("foo");
            logger.Debug("bar");
            logger.Info("An informational message");
            logger.Debug("foo");
            logger.Warn("A warning message");
            logger.Debug("foo");
            logger.Debug("foo");
            logger.Error("An error message");

            Assert.Equal(3, entries.Count);
            Assert.Equal("An informational message", entries[0].Message);
            Assert.Equal(LogLevel.Info, entries[0].Level);
            Assert.Equal("A warning message", entries[1].Message);
            Assert.Equal(LogLevel.Warn, entries[1].Level);
            Assert.Equal("An error message", entries[2].Message);
            Assert.Equal(LogLevel.Error, entries[2].Level);
        }