public string Registration(string name, string pass) { try { SetSettings(); userRepository = new SimpleChatRepository <Users>(databaseSettings); userRepository.CreatDatabase(); user = new Users(); user.Name = name; user.Pass = Convert.ToInt32(pass); userRepository.Add(user); userRepository.Save(); otvet = "Пользователь зарегистрирован"; log.Info($"Пользователь {name} зарегистрирован"); } catch (Exception e) { otvet = "Ошибка регистрации"; log.Error(otvet, e); } return(otvet); }
public long Renew() { var loggingParams = ApplicationCookieUtilities.GetLoggingParams(HttpContext.Current.User, CommonStrings.Login_Renew); var numberOfMinutes = this.loginService.Renew(new LoginRequestModel { Oper = loggingParams.oper, Tenant = loggingParams.tenant, Cono = loggingParams.cono }, this.ActionContext.Request.Headers.Host, loggingParams.sessionid); _nLogLogger.Info(CommonStrings.Logging_Success + "Renew"); return(numberOfMinutes); }
public void CallingMethods() { NLogLogMock logMock = new NLogLogMock(); NLogLogger logger = new NLogLogger(logMock); bool b = logger.IsDebugEnabled; b = logger.IsErrorEnabled; b = logger.IsFatalEnabled; b = logger.IsInfoEnabled; b = logger.IsWarnEnabled; logger.Debug(null); logger.Debug(null, null); logger.DebugFormat(null, null); logger.Error(null); logger.Error(null, null); logger.ErrorFormat(null, null); logger.Warn(null); logger.Warn(null, null); logger.WarnFormat(null, null); logger.Info(null); logger.Info(null, null); logger.InfoFormat(null, null); logger.Fatal(null); logger.Fatal(null, null); logMock.debug.Should().Be(1); logMock.debugException.Should().Be(1); logMock.debugFormat.Should().Be(1); logMock.info.Should().Be(1); logMock.infoException.Should().Be(1); logMock.infoFormat.Should().Be(1); logMock.warn.Should().Be(1); logMock.warnException.Should().Be(1); logMock.warnFormat.Should().Be(1); logMock.error.Should().Be(1); logMock.errorException.Should().Be(1); logMock.errorFormat.Should().Be(1); logMock.fatal.Should().Be(1); logMock.fatalException.Should().Be(1); logMock.isDebugEnabled.Should().Be(1); logMock.isInfoEnabled.Should().Be(1); logMock.isWarnEnabled.Should().Be(1); logMock.isErrorEnabled.Should().Be(1); logMock.isFatalEnabled.Should().Be(1); }
static void Main(string[] args) { var repo = new InMemoryRepository <Game>(); var logger = new NLogLogger("ConsoleGameRunner"); // TODO: move to IOC Container if this gets more complicated var gameApi = new GameApi(new SimpleGameFactory(), repo, new PublicGameAuthorizer(repo), logger); Console.WriteLine("Welcome to Battleship"); logger.Info("Welcome to Battleship"); var player1Name = args.Length == 2 ? args[0] : "Player 1"; var player2Name = args.Length == 2 ? args[1] : "Player 2"; var gameId = gameApi.Create(player1Name, player2Name, GameCreatorUserId); CaptureShipLocation(gameApi, gameId, player1Name); CaptureShipLocation(gameApi, gameId, player2Name); var game = gameApi.Read(gameId, GameCreatorUserId); while (game.Status != GameStatus.Completed) { Console.WriteLine(); Console.WriteLine(GameDisplayer.Display(game)); Console.WriteLine(); CaptureAttack(gameApi, gameId); } Console.WriteLine(); Console.WriteLine(GameDisplayer.Display(game)); Console.ReadLine(); }
public override void OnActionExecuted(HttpActionExecutedContext actionContext) { var nLogLogger = new NLogLogger("ApiLog", "Harvest"); if (nLogLogger.Logger.IsInfoEnabled) { MappedDiagnosticsContext.Set("method", actionContext.Request.Method.Method); MappedDiagnosticsContext.Set("url", actionContext.Request.RequestUri.LocalPath); MappedDiagnosticsContext.Set("query", actionContext.Request.RequestUri.Query); if (nLogLogger.Logger.IsTraceEnabled) { string data; using (var stream = actionContext.Request.Content.ReadAsStreamAsync().Result) { if (stream.CanSeek) { stream.Position = 0; } data = actionContext.Request.Content.ReadAsStringAsync().Result; } MappedDiagnosticsContext.Set("request", data); } nLogLogger.Info(string.Empty); } base.OnActionExecuted(actionContext); }
protected override void apply(Type pluginType, IConfiguredInstance instance) { var subscriberFactory = GetMessageSubscriberFactoryParameter(instance); if (subscriberFactory == null) { return; } var environment = GetEnvironmentName(); var connectionStringName = GetConnectionStringName(instance); var messageQueueConnectionString = GetMessageQueueConnectionString(environment, connectionStringName); if (string.IsNullOrEmpty(messageQueueConnectionString)) { var groupFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/EAS_Queues/"; var factory = new FileSystemMessageSubscriberFactory(groupFolder); instance.Dependencies.AddForConstructorParameter(subscriberFactory, factory); } else { var subscriptionName = TopicSubscriptionHelper.GetMessageGroupName(instance.Constructor.DeclaringType); var logger = new NLogLogger(typeof(TopicSubscriberFactory)); logger.Info($"Creating TopicSubscriberFactory for {subscriptionName} connection {connectionStringName}"); var factory = new TopicSubscriberFactory(messageQueueConnectionString, subscriptionName, logger); instance.Dependencies.AddForConstructorParameter(subscriberFactory, factory); } }
public AdminModel Login(string UserName, string Password, ref int ResponseStatus) { try { var pars = new SqlParameter[] { new SqlParameter("@_ResponseStatus", SqlDbType.Int) { Direction = ParameterDirection.Output }, new SqlParameter("@_UserName", UserName), new SqlParameter("@_Password", Password), }; var data = db.GetInstanceSP <AdminModel>("SP_Users_CheckLogin", pars); ResponseStatus = Convert.ToInt32(pars[0].Value); NLogLogger.Info(string.Format("Login Out: {0} {1} ", ResponseStatus, data)); return(data); } catch (Exception e) { NLogLogger.Exception(e); ResponseStatus = -99; return(new AdminModel()); } }
public void Logger_GetLogger_ChangesCategory() { var target = GetLogMemoryTarget(); ILogger log = new NLogLogger(LogManager.GetLogger("category1")); log.Info("msg"); Assert.Equal("category1|Info|msg||", target.Logs.Last()); log = log.GetLogger("cat2"); log.Info("msg"); Assert.Equal("cat2|Info|msg||", target.Logs.Last()); log = log.GetLogger(GetType()); log.Info("msg"); Assert.Equal($"{GetType().FullName}|Info|msg||", target.Logs.Last()); }
// This function is used to check signature. // xml is string data. that's serialized. // signture is string signature. public static bool VerifyData(string xml, string signture, string certpath) { try { bool result = true; ContentInfo content = new ContentInfo(Encoding.Default.GetBytes(xml)); SignedCms signatureVerifier = new SignedCms(content, true); X509Certificate2 cert = new X509Certificate2(certpath); signatureVerifier.Decode(Convert.FromBase64String(signture)); X509Certificate2Collection certCollection = new X509Certificate2Collection(cert); signatureVerifier.CheckSignature(certCollection, true); if (signatureVerifier.Certificates.Count > 0) { if (!signatureVerifier.Certificates[0].Equals(cert)) { result = false; } } return(result); } catch (Exception ex) { NLogLogger.Info("" + ex); return(false); } }
public static async Task <T> GetAsync <T>(string uri) { try { using (var httpClient = new HttpClient()) { NLogLogger.Info(string.Format("Input {0}: ", uri)); httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json"); // httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Partner-Key", partnerCode); var response = await httpClient.GetAsync(uri).ConfigureAwait(false); var content = await response.Content.ReadAsStringAsync(); if (string.IsNullOrWhiteSpace(content)) { throw new Exception(); } NLogLogger.Info("Output: " + content); return(JsonConvert.DeserializeObject <T>(content)); } } catch (TaskCanceledException ex) { NLogLogger.Exception(ex); return(default(T)); } catch (Exception ex) { NLogLogger.Exception(ex); return(default(T)); } }
public void Logger_Log_DelegatesToNLog() { var target = GetLogMemoryTarget(); ILogger log = new NLogLogger(LogManager.GetLogger("cat")); log.Info("msg"); Assert.Equal("cat|Info|msg||", target.Logs.Last()); log.Log(LogLevel.Info, "msg"); Assert.Equal("cat|Info|msg||", target.Logs.Last()); log.Debug("msg"); Assert.Equal("cat|Debug|msg||", target.Logs.Last()); log.Log(LogLevel.Debug, "msg"); Assert.Equal("cat|Debug|msg||", target.Logs.Last()); log.Warn("msg"); Assert.Equal("cat|Warn|msg||", target.Logs.Last()); log.Log(LogLevel.Warning, "msg"); Assert.Equal("cat|Warn|msg||", target.Logs.Last()); log.Error("msg", new Exception("ex")); Assert.Equal("cat|Error|msg|ex|", target.Logs.Last()); log.Log(LogLevel.Error, "msg", new Exception("ex")); Assert.Equal("cat|Error|msg|ex|", target.Logs.Last()); log.Fatal("msg"); Assert.Equal("cat|Fatal|msg||", target.Logs.Last()); log.Fatal("msg", new Exception("ex")); Assert.Equal("cat|Fatal|msg|ex|", target.Logs.Last()); log.Log(LogLevel.Fatal, "msg", new Exception("ex")); Assert.Equal("cat|Fatal|msg|ex|", target.Logs.Last()); }
public void Add_File_Target() { string tmpFile = Path.GetTempFileName(); ILog log = new NLogLogger("Test_Logger"); log.AddFileTarget("Test_Target", tmpFile); log.Debug("DEBUG MESSAGE"); log.Info("INFO MESSAGE"); log.Error("ERROR MESSAGE"); log.Warn("WARN MESSAGE"); log.Fatal("FATAL MESSAGE"); log.Flush(); string logContents = File.ReadAllText(tmpFile); Console.Write(logContents); Assert.True(logContents.Contains("DEBUG MESSAGE")); Assert.True(logContents.Contains("INFO MESSAGE")); Assert.True(logContents.Contains("ERROR MESSAGE")); Assert.True(logContents.Contains("WARN MESSAGE")); Assert.True(logContents.Contains("FATAL MESSAGE")); File.Delete(tmpFile); }
public List <MenuModel> SP_Menu_GetList(string MenuIDs, Int16 GetChild, Int16 Status, out int TotalRow) { TotalRow = 0; try { var pars = new SqlParameter[4]; pars[0] = new SqlParameter("@MenuIDs", MenuIDs); pars[1] = new SqlParameter("@GetChild", GetChild); pars[2] = new SqlParameter("@Status", Status); pars[3] = new SqlParameter("@TotalRow", SqlDbType.Int) { Direction = ParameterDirection.Output }; var list = db.GetListSP <MenuModel>("SP_Menu_GetList", pars); if (list != null && list.Count >= 0) { TotalRow = Convert.ToInt32(pars[3].Value); } NLogLogger.Info(JsonConvert.SerializeObject(list)); return(list); } catch (Exception ex) { NLogLogger.Exception(ex); return(new List <MenuModel>()); } }
public int SP_GifCodeData_Transaction(int GiftCodeID, string GiftCode, long Value, int SourceID, int Type, DateTime EndTime, string ClientIP) { try { var pars = new SqlParameter[] { new SqlParameter("@_ResponseStatus", SqlDbType.Int) { Direction = ParameterDirection.Output }, new SqlParameter("@_GifCodeID", GiftCodeID), new SqlParameter("@_GifCode", GiftCode), new SqlParameter("@_Value", Value), new SqlParameter("@_SourceID", SourceID), new SqlParameter("@_Type", Type), new SqlParameter("@_EndDate", EndTime), new SqlParameter("@_MerchantID", _appSetting.MerchantIdGiftCodeInsert), new SqlParameter("@_MerchantKey", _appSetting.MerchantKeyGiftCodeInsert.ToString()), new SqlParameter("@_ClientIP", ClientIP), }; db.ExecuteNonQuerySP("SP_GifCodeData_Transaction", pars); NLogLogger.Info(string.Format("SP_GifCodeData_Transaction Output _ResponseStatus: {0}", pars[0].Value)); return(int.Parse(pars[0].Value.ToString())); } catch (Exception e) { NLogLogger.Exception(e); return(-99); } }
public string WriteMessage(string UserMessage, int userId) { try { messageRepository.CreatDatabase(); message = new Messages(); message.Text = UserMessage; message.UserId = userId; messageRepository.Add(message); messageRepository.Save(); Get(); otvet = "Сообщение доставлено"; log.Info($"Доставлено сообщение от {userId}"); } catch (Exception e) { otvet = "Сообщение не доставлено"; log.Error(otvet, e); } return(otvet); }
public Assembly Load(string script) { string scriptFile = Path.Combine(_sharedAsemblyDir, script); try { var configDir = _options.ConfigDir.Substring(0, _options.ConfigDir.LastIndexOf("\\", StringComparison.Ordinal)); var compiledScriptsDir = Path.Combine(configDir, @"Scripts\compiled"); if (!Directory.Exists(compiledScriptsDir)) { Directory.CreateDirectory(compiledScriptsDir); } var finalName = $@"{Path.GetFileNameWithoutExtension(scriptFile)}.dll"; finalName = Path.Combine(compiledScriptsDir, finalName); // The script file could have been deleted while already executing the progrsm if (!File.Exists(scriptFile) && !File.Exists(finalName)) { log.Info($"Script does not exist {finalName}"); return(null); } var lastwriteSourceFile = File.GetLastWriteTime(scriptFile); // Load the compiled Assembly only, if it is newer than the source file, to get changes done on the file if (File.Exists(finalName) && File.GetLastWriteTime(finalName) > lastwriteSourceFile) { _assembly = Assembly.LoadFile(finalName); } else { log.Info($"Compiling script {scriptFile}"); _assembly = CSScript.LoadFile(scriptFile, finalName, true); // And reload the assembly from the compiled dir, so that we may execute it Assembly.LoadFile(finalName); } return(_assembly); } catch (Exception ex) { log.Error("Error loading script: {0} {1}", scriptFile, ex.Message); return(null); } }
public void WhenCallingInfoShouldRecordOneError() { // act _logger.Info("Test String"); // assert _memoryTarget.Logs.Count.Should().Be(1, "because we only called the method once"); _memoryTarget.Logs.All(log => log.Contains("Info")).Should().BeTrue("Because we only logged a Info"); }
internal static void Main(string[] args) { var logger = new NLogLogger(null, null, null); try { logger.Info("WebJob starting"); var container = IoC.Initialize(); var updater = container.GetInstance <IEducationalOrgsUpdater>(); updater.RunUpdate().Wait(); logger.Info("WebJob finished"); } catch (Exception ex) { logger.Fatal(ex, "Unhandled Exception"); } }
public override int Run(string[] remainingArguments) { System.Console.WriteLine(DateTime.UtcNow); var nlog = new NLogLogger(); nlog.Info("Testing Logger"); return(0); }
private static void LogTest() { var logger = new NLogLogger(new ApplicationSettings()); logger.Debug("Just testing debug", "Debug"); logger.Info("Just testing info", "Info"); logger.Warn("Just testing warning", "Warning"); logger.Error("Just testing error", "Error"); logger.Fatal("Testing with exception", new Exception("TestException"), "Some details again"); }
public void TestInfo() { string msg = "info message"; logger.Info(msg); StreamReader sr = new StreamReader(LogFullPath); Assert.IsTrue(sr.ReadToEnd().Contains(msg)); sr.Close(); }
public ActionResult Edit(LocHours locHours) { /***** Logging initial settings *****/ DbChangeLog log = new DbChangeLog(); log.UserName = User.Identity.Name; log.Controller = "LocHours"; log.Action = (locHours.Id != 0) ? "Edit" : "Create"; if (log.Action == "Edit") { LocHours oldHours = context.LocHours.FirstOrDefault(m => m.Id == locHours.Id); log.BeforeChange = Domain.Extensions.DbLogExtensions.LocHoursToString(oldHours); } log.AfterChange = Domain.Extensions.DbLogExtensions.LocHoursToString(locHours); /***** end Logging initial settings *****/ if (ModelState.IsValid) { try { context.SaveLocHours(locHours); log.ItemId = locHours.Id; log.Success = true; TempData["message"] = string.Format("{0} : {1} has been saved", locHours.Days, locHours.Hours); } catch (Exception e) { log.Error = e.ToString(); log.Success = false; TempData["alert"] = string.Format("There has been an error. {0} : {1} has not been saved", locHours.Days, locHours.Hours); } } else { log.Error = "Errors: "; NLogLogger logger = new NLogLogger(); logger.Info("There has been a validation error, this record has not been saved"); foreach (ModelState modelState in ViewData.ModelState.Values) { foreach (ModelError error in modelState.Errors) { log.Error += error + "<br />"; } } TempData["alert"] = "There has been a validation error, this record has not been saved"; } log.AfterChange = Domain.Extensions.DbLogExtensions.LocHoursToString(locHours); context.SaveLog(log); return(RedirectToAction("Edit", new { id = locHours.Id })); }
new public void Run(string[] args) { var(app, buildConfigProvider, getDbBasePath) = BuildCommandLineApp(); ManualResetEventSlim appClosed = new ManualResetEventSlim(false); app.OnExecute(async() => { var configProvider = buildConfigProvider(); var initConfig = configProvider.GetConfig <IInitConfig>(); if (initConfig.RemovingLogFilesEnabled) { RemoveLogFiles(initConfig.LogDirectory); } Logger = new NLogLogger(initConfig.LogFileName, initConfig.LogDirectory); LogMemoryConfiguration(); var pathDbPath = getDbBasePath(); if (!string.IsNullOrWhiteSpace(pathDbPath)) { var newDbPath = Path.Combine(pathDbPath, initConfig.BaseDbPath); if (Logger.IsDebug) { Logger.Debug($"Adding prefix to baseDbPath, new value: {newDbPath}, old value: {initConfig.BaseDbPath}"); } initConfig.BaseDbPath = newDbPath ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "db"); } Console.Title = initConfig.LogFileName; var serializer = new UnforgivingJsonSerializer(); if (Logger.IsInfo) { Logger.Info($"Nethermind config:\n{serializer.Serialize(initConfig, true)}\n"); } await StartRunners(configProvider); Console.WriteLine("All done, goodbye!"); appClosed.Set(); return(0); }); app.Execute(args); appClosed.Wait(); }
public void CallMethods() { logger.Error("error message"); logger.Info("info message"); logger.Warn("warn message"); StreamReader sr = new StreamReader(LogFullPath); var line = sr.ReadLine(); while (line != null) { } }
public static bool CheckSignRSA(string data, string sign, string publicKey) { try { RSACryptoServiceProvider rsacp = new RSACryptoServiceProvider(); rsacp.FromXmlString(publicKey); return(rsacp.VerifyData(Encoding.UTF8.GetBytes(data), "SHA1", Convert.FromBase64String(sign))); } catch (Exception ex) { NLogLogger.Info(ex.ToString()); return(false); } }
public int SP_GifCode_Event_Insert(string GiftCodeName, long GiftCodeValue, int EventID, int Quantity, int SourceID, string ClientIP, int NumberInput, ref long Balance, ref DateTime EndDate) { try { var pars = new SqlParameter[] { new SqlParameter("@_Balance", SqlDbType.BigInt) { Direction = ParameterDirection.Output }, new SqlParameter("@_ResponseStatus", SqlDbType.Int) { Direction = ParameterDirection.Output }, new SqlParameter("@_EndDate", SqlDbType.DateTime) { Direction = ParameterDirection.Output }, new SqlParameter("@_GifCodeName", GiftCodeName), new SqlParameter("@_GifCodeValue", GiftCodeValue), new SqlParameter("@_EventID", EventID), //new SqlParameter("@_EventName", DBNull.Value), new SqlParameter("@_Quantity", Convert.ToInt64(Quantity)), new SqlParameter("@_Staff", _accountJwt.AccountName), new SqlParameter("@_SourceID", SourceID), new SqlParameter("@_MerchantID", _appSetting.MerchantIdGiftCodeInsert), new SqlParameter("@_MerchantKey", _appSetting.MerchantKeyGiftCodeInsert.ToString()), new SqlParameter("@_ClientIP", ClientIP), new SqlParameter("@_NumberInput", NumberInput), //new SqlParameter("@_Note", DBNull.Value), }; db.ExecuteNonQuerySP("SP_GifCode_Event_Insert", pars); NLogLogger.Info(string.Format("SP_GifCode_Event_Insert Output _Balance: {0} | _ResponseStatus: {1} | _EndDate : {2}", pars[0].Value, pars[1].Value, pars[2].Value)); Balance = Convert.ToInt64(pars[0].Value.ToString()); EndDate = DateTime.Parse(pars[2].Value.ToString()); return(int.Parse(pars[1].Value.ToString())); } catch (Exception e) { NLogLogger.Exception(e); Balance = 0; EndDate = new DateTime(); return(-99); } }
public static void ReportErrors(string errorMessage, int returnCode) { if (string.IsNullOrWhiteSpace(errorMessage)) { return; } var nLogLogger = new NLogLogger("ReportErrors"); if (errorMessage.Equals(SessionIdNotFound, StringComparison.InvariantCultureIgnoreCase) || errorMessage.Equals(ClientPrincipalExired, StringComparison.InvariantCultureIgnoreCase)) { nLogLogger.Warn(errorMessage); throw new HttpResponseException(CreateReponse(HttpStatusCode.Unauthorized, CommonStrings.Token_Invalid)); } nLogLogger.Info($"{returnCode}-{errorMessage}"); throw new HttpResponseException(CreateReponse((HttpStatusCode)returnCode, errorMessage, returnCode != 401 ? CommonStrings.Error_FromSxe : CommonStrings.Token_Invalid)); }
public List<AdvertPosModel> SP_AdvertPosition_Get() { try { var pars = new SqlParameter[] { }; var list = db.GetListSP<AdvertPosModel>("SP_AdvertPosition_Get", pars); NLogLogger.Info(JsonConvert.SerializeObject(list)); return list; } catch (Exception ex) { NLogLogger.Exception(ex); return new List<AdvertPosModel>(); } }
public List <ArticleModel> SP_Article_GetList_Web(int TopRow, int ArticleID, string Title, int MenuID, string UrlRedirect, string Tags, int isHot, int Page, int PageSize, out int TotalRow) { TotalRow = 0; try { var pars = new SqlParameter[10]; pars[0] = new SqlParameter("@TopRow", TopRow); pars[1] = new SqlParameter("@ArticleID", ArticleID); pars[2] = new SqlParameter("@Title", Title); pars[3] = new SqlParameter("@MenuID", MenuID); pars[4] = new SqlParameter("@UrlRedirect", UrlRedirect); pars[5] = new SqlParameter("@Tags", Tags); if (isHot == -1) { pars[6] = new SqlParameter("@isHot", DBNull.Value); } else if (isHot == 1) { pars[6] = new SqlParameter("@isHot", true); } else if (isHot == 0) { pars[6] = new SqlParameter("@isHot", false); } pars[7] = new SqlParameter("@Page", Page); pars[8] = new SqlParameter("@PageSize", PageSize); pars[9] = new SqlParameter("@TotalRow", SqlDbType.Int) { Direction = ParameterDirection.Output }; var list = db.GetListSP <ArticleModel>("SP_Article_GetList_Web", pars); if (list != null || list.Count >= 0) { TotalRow = Convert.ToInt32(pars[9].Value); } NLogLogger.Info(JsonConvert.SerializeObject(list)); return(list); } catch (Exception ex) { NLogLogger.Exception(ex); return(new List <ArticleModel>()); } }
// This function is used signature // Data is data. that's serialize public static string SignData(string Data, string privateKey, string passKey) { try { CmsCryptography objSign = new CmsCryptography(); //objSign.CharacterEncoding = Encoding.Default.BodyName; //objSign.CharacterEncoding = "UTF-8"; objSign.LoadSignerCredential(privateKey, passKey); return(objSign.Sign(Data)); } catch (Exception ex) { NLogLogger.Info("data: " + Data + "\n url key: " + privateKey + "\n passkey: " + passKey); NLogLogger.Info("" + ex); throw ex; } }