Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
        public List <CustomerBean> getAllCustomer(string sql, Dictionary <string, string> parameters)
        {
            List <CustomerBean> customerDataSource = new List <CustomerBean>();

            try
            {
                DataTable customerResult = new ConnectionManager().select(sql, parameters);
                for (int i = 0; i < customerResult.Rows.Count; i++)
                {
                    CustomerBean custBean = new CustomerBean();
                    custBean.ID        = int.Parse(customerResult.Rows[i]["ID"].ToString());
                    custBean.COMP_ID   = int.Parse(customerResult.Rows[i]["COMP_ID"].ToString());
                    custBean.GRP_ID    = int.Parse(customerResult.Rows[i]["GRP_ID"].ToString());
                    custBean.NAME      = customerResult.Rows[i]["NAME"].ToString();
                    custBean.LONG_NAME = customerResult.Rows[i]["LONG_NAME"].ToString();
                    custBean.DESC      = customerResult.Rows[i]["DESC"].ToString();
                    custBean.COUNTERY  = int.Parse(customerResult.Rows[i]["COUNTERY"].ToString());
                    custBean.ADDRESS   = customerResult.Rows[i]["ADDRESS"].ToString();
                    custBean.OWNER     = customerResult.Rows[i]["OWNER"].ToString();
                    custBean.PHONE     = customerResult.Rows[i]["PHONE"].ToString();
                    custBean.STATUS    = int.Parse(customerResult.Rows[i]["STATUS"].ToString());
                    customerDataSource.Add(custBean);
                }
            }
            catch (Exception ex)
            {
                myLog.Error(ex);
            }
            return(customerDataSource);
        }
Exemplo n.º 3
0
        public List <MaterialBean> getAllMaterial(string sql, Dictionary <string, string> parameters)
        {
            List <MaterialBean> materialDataSource = new List <MaterialBean>();

            try
            {
                DataTable currencyResult = new ConnectionManager().select(sql, parameters);
                for (int i = 0; i < currencyResult.Rows.Count; i++)
                {
                    MaterialBean matrBean = new MaterialBean();
                    matrBean.ID        = int.Parse(currencyResult.Rows[i]["ID"].ToString());
                    matrBean.NAME      = currencyResult.Rows[i]["NAME"].ToString();
                    matrBean.LONG_NAME = currencyResult.Rows[i]["LONG_NAME"].ToString();
                    matrBean.MEASURE   = int.Parse(currencyResult.Rows[i]["MEASURE"].ToString());
                    matrBean.MRP_LOW   = int.Parse(currencyResult.Rows[i]["MRP_LOW"].ToString());
                    matrBean.MRP_HIGH  = int.Parse(currencyResult.Rows[i]["MRP_HIGH"].ToString());
                    matrBean.GRP_ID    = int.Parse(currencyResult.Rows[i]["GRP_ID"].ToString());
                    materialDataSource.Add(matrBean);
                }
            }
            catch (Exception ex)
            {
                myLog.Error(ex);
            }
            return(materialDataSource);
        }
Exemplo n.º 4
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
            {
                ILogger logger = new NLogLogger("logs.txt");
                if (eventArgs.ExceptionObject is Exception e)
                {
                    logger.Error(FailureString, e);
                }
                else
                {
                    logger.Error(FailureString + eventArgs.ExceptionObject);
                }
            };

            try
            {
                Run(args);
            }
            catch (AggregateException e)
            {
                ILogger logger = new NLogLogger("logs.txt");
                logger.Error(FailureString, e.InnerException);
            }
            catch (Exception e)
            {
                ILogger logger = new NLogLogger("logs.txt");
                logger.Error(FailureString, e);
            }
            finally
            {
                NLogLogger.Shutdown();
            }
        }
Exemplo n.º 5
0
        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);
        }
        static void Main()
        {
            try
            {
                var container = IoC.Initialize();
                var logger    = container.GetInstance <ILog>();
                logger.Info("ContractAgreements job started");
                var timer = Stopwatch.StartNew();

                var service = container.GetInstance <ProviderAgreementStatusService>();
                service.UpdateProviderAgreementStatuses().Wait();

                timer.Stop();

                logger.Info($"ContractAgreements job done, Took: {timer.ElapsedMilliseconds} milliseconds");
            }
            catch (AggregateException exc)
            {
                ILog exLogger = new NLogLogger();
                exLogger.Error(exc, "Error running ContractAgreements WebJob");
                exc.Handle(ex =>
                {
                    exLogger.Error(ex, "Inner exception running ContractAgreements WebJob");
                    return(false);
                });
            }
            catch (Exception ex)
            {
                ILog exLogger = new NLogLogger();
                exLogger.Error(ex, "Error running ContractAgreements WebJob");
                throw;
            }
        }
Exemplo n.º 7
0
        public override void OnException(ExceptionContext filterContext)
        {
            Exception exp = filterContext.Exception;
            //获取ex的第一级内部异常
            Exception innerExp = exp.InnerException == null ? exp : exp.InnerException;

            //循环获取内部异常直到获取详细异常信息为止
            while (innerExp.InnerException != null)
            {
                innerExp = innerExp.InnerException;
            }
            NLogLogger nlog = new NLogLogger();

            //ajax请求
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                nlog.Error(innerExp.Message);
                JsonConvert.SerializeObject(new { status = 1, msg = "请求发生错误,请联系管理员" });
            }
            else //正常url请求
            {
                nlog.Error("Error", exp);
                ViewResult viewResult = new ViewResult();
                viewResult.ViewName  = "/Views/Shared/Error.cshtml";
                filterContext.Result = viewResult;
            }
            //告诉mvc框架异常被处理
            filterContext.ExceptionHandled = true;

            base.OnException(filterContext);
        }
Exemplo n.º 8
0
        public List <CompanyBeans> getAllCompany(string sql, Dictionary <string, string> parameters)
        {
            List <CompanyBeans> companyDataSource = new List <CompanyBeans>();

            try
            {
                DataTable companyResult = new ConnectionManager().select(sql, parameters);
                for (int i = 0; i < companyResult.Rows.Count; i++)
                {
                    CompanyBeans compBean = new CompanyBeans();
                    compBean.id          = int.Parse(companyResult.Rows[i]["id"].ToString());
                    compBean.cmp_code    = companyResult.Rows[i]["cmp_code"].ToString();
                    compBean.cmp_nme     = companyResult.Rows[i]["cmp_nme"].ToString();
                    compBean.cmp_lng_nme = companyResult.Rows[i]["cmp_lng_nme"].ToString();
                    compBean.address     = companyResult.Rows[i]["address"].ToString();
                    compBean.telephone   = companyResult.Rows[i]["telephone"].ToString();
                    compBean.mobile      = companyResult.Rows[i]["mobile"].ToString();
                    companyDataSource.Add(compBean);
                }
            }
            catch (Exception ex)
            {
                myLog.Error(ex);
            }
            return(companyDataSource);
        }
Exemplo n.º 9
0
        public static void Main(string[] args)
        {
            ILogger logger = new NLogLogger("logs.txt");

            AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
            {
                if (eventArgs.ExceptionObject is Exception e)
                {
                    logger.Error(FailureString, e);
                }
                else
                {
                    logger.Error(FailureString + eventArgs.ExceptionObject?.ToString());
                }
            };

            try
            {
                IRunnerApp runner = new RunnerApp(logger);
                runner.Run(args);
                return;
            }
            catch (AggregateException e)
            {
                logger.Error(FailureString, e.InnerException);
            }
            catch (Exception e)
            {
                logger.Error(FailureString, e);
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Exemplo n.º 10
0
        private List <InventoryBean> getAllInventory(string sql, Dictionary <string, string> parameters)
        {
            List <InventoryBean> inevntory_dataSource = new List <InventoryBean>();

            try
            {
                DataTable currencyResult = new ConnectionManager().select(sql, parameters);
                for (int i = 0; i < currencyResult.Rows.Count; i++)
                {
                    InventoryBean invent_Bean = new InventoryBean();
                    invent_Bean.id        = int.Parse(currencyResult.Rows[i]["id"].ToString());
                    invent_Bean.cmp_id    = int.Parse(currencyResult.Rows[i]["cmp_id"].ToString());
                    invent_Bean.strg_name = currencyResult.Rows[i]["strg_name"].ToString();
                    invent_Bean.long_nme  = currencyResult.Rows[i]["long_nme"].ToString();
                    invent_Bean.desc      = currencyResult.Rows[i]["desc"].ToString();
                    invent_Bean.address   = currencyResult.Rows[i]["address"].ToString();
                    inevntory_dataSource.Add(invent_Bean);
                }
            }
            catch (Exception ex)
            {
                myLog.Error(ex);
            }
            return(inevntory_dataSource);
        }
Exemplo n.º 11
0
        public List <MaterialCardBean> getMaterialsCard(string sql, Dictionary <string, string> parameters)
        {
            List <MaterialCardBean> material_card_dataSource = new List <MaterialCardBean>();

            try
            {
                string material_sql = " select * from pos.tmaterial where comp_id  = @cmp_id ";
                Dictionary <string, string> material_parameters = new Dictionary <string, string>();
                material_parameters.Add("@cmp_id", parameters["@cmp_id"]);
                List <MaterialBean> materialsResult    = new MaterialBean().getAllMaterial(material_sql, material_parameters);
                DataTable           materialCardResult = new ConnectionManager().select(sql, parameters);
                for (int i = 0; i < materialCardResult.Rows.Count; i++)
                {
                    MaterialCardBean matr_card_Bean = new MaterialCardBean();
                    matr_card_Bean.ID            = int.Parse(materialCardResult.Rows[i]["ID"].ToString());
                    matr_card_Bean.FISCAL_YEAR   = int.Parse(materialCardResult.Rows[i]["FISCAL_YEAR"].ToString());
                    matr_card_Bean.COMP_ID       = int.Parse(materialCardResult.Rows[i]["COMP_ID"].ToString());
                    matr_card_Bean.inventory_id  = int.Parse(materialCardResult.Rows[i]["inventory_id"].ToString());
                    matr_card_Bean.MATERIAL_ID   = int.Parse(materialCardResult.Rows[i]["MATERIAL_ID"].ToString());
                    matr_card_Bean.INITIAL_QNTY  = int.Parse(materialCardResult.Rows[i]["INITIAL_QNTY"].ToString());
                    matr_card_Bean.CURRENT_QNTY  = int.Parse(materialCardResult.Rows[i]["CURRENT_QNTY"].ToString());
                    matr_card_Bean.MATERIAL_name = materialsResult.Single(x => x.ID == matr_card_Bean.MATERIAL_ID).NAME;
                    matr_card_Bean.MRP_LOW       = materialsResult.Single(x => x.ID == matr_card_Bean.MATERIAL_ID).MRP_LOW;
                    matr_card_Bean.MRP_HIGH      = materialsResult.Single(x => x.ID == matr_card_Bean.MATERIAL_ID).MRP_HIGH;
                    matr_card_Bean.CREATE_DATE   = DateTime.Parse(materialCardResult.Rows[i]["CREATE_DATE"].ToString());
                    matr_card_Bean.lastupdate    = DateTime.Parse(materialCardResult.Rows[i]["lastupdate"].ToString());
                    material_card_dataSource.Add(matr_card_Bean);
                }
            }
            catch (Exception ex)
            {
                myLog.Error(ex);
            }
            return(material_card_dataSource);
        }
Exemplo n.º 12
0
        private static UserDTO claim2UserDto()
        {
            try
            {
                var claimId = GetClaim(ClaimTypes.NameIdentifier);

                if (claimId == null)
                {
                    return(null);
                }

                var userId = Convert.ToInt32(claimId.Value);

                var claimFirst = GetClaim(ClaimTypesHelper.CLAIM_FIRSTNAME);

                var firstName = claimFirst != null ? claimFirst.Value : string.Empty;

                var claimLast = GetClaim(ClaimTypes.Surname);

                var lastName = claimLast != null ? claimLast.Value : string.Empty;

                var claimFull = GetClaim(ClaimTypesHelper.CLAIM_FULLNAME);

                var fullName = claimFull != null ? claimFull.Value : string.Empty;

                var claimNick = GetClaim(ClaimTypesHelper.CLAIM_FIRSTNAME);

                var nick = claimNick != null ? claimNick.Value : string.Empty;

                var claimPayout = GetClaim(ClaimTypesHelper.CLAIM_PAYOUT_SETTINGS);

                var isPayoutDefinded = false;

                if (claimPayout != null)
                {
                    Boolean.TryParse(claimPayout.Value, out isPayoutDefinded);
                }

                return(new UserDTO
                {
                    UserId = userId            //Convert.ToInt32(GetClaim(ClaimTypes.NameIdentifier).Value)
                    , Email = WebSecurity.CurrentUserName
                    , FirstName = firstName    // GetClaim(ClaimTypesHelper.CLAIM_FIRSTNAME).Value
                    , LastName = lastName      //GetClaim(ClaimTypes.Surname).Value
                    , FullName = fullName      //GetClaim(ClaimTypesHelper.CLAIM_FULLNAME).Value
                    , Nickname = nick          // GetClaim(ClaimTypesHelper.CLAIM_NICKNAME).Value
                    , IsPayoutOptionsDefined = isPayoutDefinded
                                               //,UserProfileId = WebSecurity.CurrentUserId
                });
            }
            catch (Exception ex)
            {
                _logger.Error("claim2UserDto::" + WebSecurity.CurrentUserName, ex, CommonEnums.LoggerObjectTypes.UserAccount);
                return(null);
            }
        }
Exemplo n.º 13
0
        public void TestError()
        {
            string msg = "error message";

            logger.Error(msg);
            StreamReader sr = new StreamReader(LogFullPath);

            Assert.IsTrue(sr.ReadToEnd().Contains(msg));
            sr.Close();
        }
Exemplo n.º 14
0
 private MySqlConnection getConnection()
 {
     try
     {
         currentConnection = new MySqlConnection(connStr);
         currentConnection.Open();
     }
     catch (Exception ex)
     {
         myLog.Error(ex);
     }
     return(currentConnection);
 }
Exemplo n.º 15
0
        public LoginInternalResult Login(string username, string password, int companyNumber, string languageID, bool firstLogin, bool singleTenant)
        {
            _nLogLogger.Debug($"username {username}", "Login");
            _nLogLogger.Debug($"password {password}", "Login");
            _nLogLogger.Debug($"companyNumber {companyNumber}", "Login");
            _nLogLogger.Debug($"languageID {languageID}", "Login");
            _nLogLogger.Debug($"firstLogin {firstLogin}", "Login");
            _nLogLogger.Debug($"singleTenant {singleTenant}", "Login");
            var pdsUserLoginDataSet = new pdsUserLoginDataSet();

            pdsUserLoginDataSet.ttblUserLogin.AddttblUserLoginRow(username, password, companyNumber, languageID, firstLogin, singleTenant);
            var cErrorMessage = string.Empty;

            StopwatchUtil.Time(
                () =>
            {
                this._poLoginproxy.Login(ref this._pdsContext, ref pdsUserLoginDataSet, out cErrorMessage);
            });
            _nLogLoggerP.Trace("Login");
            if (!string.IsNullOrEmpty(cErrorMessage))
            {
                if (cErrorMessage.Contains(OperInUse))
                {
                    _nLogLogger.Warn($"Error returned - {cErrorMessage}", "PopulateLoginModel");
                }
                else
                {
                    _nLogLogger.Error($"Error returned - {cErrorMessage}", "PopulateLoginModel");
                }
            }
            if (pdsUserLoginDataSet.HasErrors)
            {
                _nLogLogger.Error("pdsUserContext is showing errors", "Login");
            }
            var result = new UserLogin();

            if (pdsUserLoginDataSet.ttblUserLogin.Count > 0)
            {
                result = UserLogin.BuildUserLoginFromRow(pdsUserLoginDataSet.ttblUserLogin[0]);
            }
            var loginInternalResult = this.PopulateLoginModel(pdsUserLoginDataSet.HasErrors, cErrorMessage, result, firstLogin);

            loginInternalResult.availUsers = new List <AvailUsers>();
            foreach (DataRow row in pdsUserLoginDataSet.ttblAvailUsers)
            {
                _nLogLogger.Debug($"Building Avail Users", "Login");
                loginInternalResult.availUsers.Add(AvailUsers.BuildAvailUsersFromRow(row));
            }
            _nLogLogger.Debug($"Finished Login", "Login");
            return(loginInternalResult);
        }
Exemplo n.º 16
0
        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);
        }
Exemplo n.º 17
0
        protected void Application_Error(object sender, EventArgs e)
        {
            var ex = Server.GetLastError();

            _logger.Error("application error::" + Utils.FormatError(ex), ex, CommonEnums.LoggerObjectTypes.Application);
            try
            {
                _logger.Fatal("application error::" + HttpContext.Current.Request.RawUrl + "::" + HttpContext.Current.Request.QueryString, ex);
            }
            catch (Exception x)
            {
                _logger.Error("application error::", x, CommonEnums.LoggerObjectTypes.Application);
            }

            var exception = ex as HttpException;

            if (exception != null && exception.GetHttpCode() == 404)
            {
                try
                {
                    Response.StatusCode = 404;
                    var ctx = HttpContext.Current;

                    //var error = new KeyValuePair<string, object>("ErrorMessage", ctx.Server.GetLastError().ToString());

                    ctx.Response.Clear();

                    var rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;

                    var factory = ControllerBuilder.Current.GetControllerFactory();

                    var controller = (HomeController)factory.CreateController(rc, "home");
                    var cc         = new ControllerContext(rc, controller);

                    controller.ControllerContext = cc;

                    var s = controller.RenderRazorViewToString("Error404", null);

                    Response.Write(s);
                    ctx.Response.End();
                }
                catch (Exception) { }
            }
            else
            {
                var ee = Utils.FormatError(ex).OptimizedUrl();
                Response.Redirect("/Home/Error/");
            }
        }
Exemplo n.º 18
0
        public static WixInstanceDTO DecodeInstance2WixInstanceDTO(this string instance, out string error)
        {
            try
            {
                var instanceParts = instance.Split('.');
                var sig           = ConvertBase64ToString(instanceParts[0].Replace("_", "/").Replace("-", "+") + "=", out error);

                if (String.IsNullOrEmpty(sig))
                {
                    return(null);
                }

                var encodedJson = instanceParts[1];

                //validate signature
                var hash                = new HMACSHA256(Encoding.ASCII.GetBytes(appSecretkey));
                var computeHash         = hash.ComputeHash(Encoding.ASCII.GetBytes(encodedJson));
                var s                   = Encoding.ASCII.GetString(computeHash);
                var isSignatureVerified = sig == s;

                //decode instance
                if (isSignatureVerified)
                {
                    var decodedJson = ConvertBase64ToString(instanceParts[1], out error);

                    if (String.IsNullOrEmpty(decodedJson))
                    {
                        return(null);
                    }

                    var token = JSSerializer.Deserialize <WixInstanceDTO>(decodedJson);

                    token.instanceToken = instance;

                    return(token);
                    //return String.IsNullOrEmpty(decodedJson) ? null : JSSerializer.Deserialize<WixInstanceDTO>(decodedJson);
                }

                error = "Signature not valid";

                return(null);
            }
            catch (Exception ex)
            {
                error = Utils.FormatError(ex);
                _logger.Error("DecodeInstance2WixInstanceDTO::" + instance, ex, CommonEnums.LoggerObjectTypes.Wix);
                return(null);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        ///   Executes commandline processes and parses their output
        /// </summary>
        /// <param name = "aArguments">The arguments to supply for the given process</param>
        /// <param name = "aExpectedTimeoutMs">How long the function will wait until the tool's execution will be aborted</param>
        /// <returns>A list containing the redirected StdOut line by line</returns>
        public static List <string> ExecuteProcReturnStdOut(string aArguments, int aExpectedTimeoutMs)
        {
            StdOutList.Clear();

            var MP3ValProc  = new Process();
            var ProcOptions = new ProcessStartInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Bin\mp3val.exe"))
            {
                Arguments              = aArguments,
                UseShellExecute        = false,
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                StandardOutputEncoding = Encoding.GetEncoding("ISO-8859-1"),
                StandardErrorEncoding  = Encoding.GetEncoding("ISO-8859-1"),
                CreateNoWindow         = true,
                ErrorDialog            = false
            };

            MP3ValProc.OutputDataReceived += StdOutDataReceived;
            MP3ValProc.ErrorDataReceived  += StdErrDataReceived;
            MP3ValProc.EnableRaisingEvents = true; // We want to know when and why the process died
            MP3ValProc.StartInfo           = ProcOptions;
            if (File.Exists(ProcOptions.FileName))
            {
                try
                {
                    MP3ValProc.Start();
                    MP3ValProc.BeginErrorReadLine();
                    MP3ValProc.BeginOutputReadLine();

                    // wait this many seconds until mp3val has to be finished
                    MP3ValProc.WaitForExit(aExpectedTimeoutMs);
                    if (MP3ValProc.HasExited && MP3ValProc.ExitCode != 0)
                    {
                        log.Warn($"MP3Val: Did not exit properly with arguments: {aArguments}, exitcode: {MP3ValProc.ExitCode}");
                    }
                }
                catch (Exception ex)
                {
                    log.Error("MP3Val: Error executing mp3val: {0}", ex.Message);
                }
            }
            else
            {
                log.Warn($"MP3VAL: Could not start {ProcOptions.FileName} because it doesn't exist!");
            }

            return(StdOutList);
        }
Exemplo n.º 20
0
        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());
        }
Exemplo n.º 21
0
        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);
        }
Exemplo n.º 22
0
 public string GenerateToken(AdminModel user)
 {
     try
     {
         var tokenHandler    = new JwtSecurityTokenHandler();
         var key             = Encoding.ASCII.GetBytes(appSetting.JwtKey);
         var tokenDescriptor = new SecurityTokenDescriptor
         {
             Subject = new ClaimsIdentity(new Claim[]
             {
                 new Claim(appSetting.jwtAccountId, user.UserId.ToString()),
                 new Claim(appSetting.jwtAccountName, user.UserName),
                 new Claim(appSetting.jwtFullName, user.FullName),
                 new Claim(appSetting.jwtEmail, user.Email.ToString()),
                 //new Claim("isAdmin", user.isAdmin.ToString()),
                 //new Claim("Avatar", user.Avatar)
                 //new Claim("isAdminOrigin", user.isAdminOrigin.ToString())
             }),
             Expires            = DateTime.Now.AddHours(appSetting.TokenExpire),
             SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
         };
         var token = tokenHandler.CreateToken(tokenDescriptor);
         return(tokenHandler.WriteToken(token));
     }
     catch (Exception ex)
     {
         NLogLogger.Error(ex.ToString());
         return(null);
     }
 }
Exemplo n.º 23
0
 private void  fillInventory()
 {
     try
     {
         string selectedCompVal = lst_company.SelectedItem.Value;
         List <InventoryBean> inventoryDataSource = new InventoryBean().getAllInventoryUnderCompany(selectedCompVal);
         lst_inventory.DataSource     = inventoryDataSource;
         lst_inventory.DataTextField  = "strg_name";
         lst_inventory.DataValueField = "id";
         lst_inventory.DataBind();
     }
     catch (Exception ex)
     {
         myLog.Error(ex);
     }
 }
Exemplo n.º 24
0
 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
     // PMC 07/14/2016 - IBM AppScan - This has been manually reviewed and passed as being safe Manipulating the response that we are composing
     if (actionExecutedContext.Response != null)
     {
         actionExecutedContext.Response.Content.Headers.Remove(ApplicationCookieUtilities.TokenName);
         if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
         {
             return;
         }
         var myprincipal = System.Web.HttpContext.Current.User as ServiceInterfacePrincipal;
         if (myprincipal?.TokenObject == null || myprincipal?.TokenObject.SessionidGuid == Guid.Empty)
         {
             return;
         }
         var progressSettings = DependencyResolver.Current.GetService <IProgressConfiguration>();
         if (string.IsNullOrEmpty(progressSettings.ApplicationEncryptKey) ||
             string.IsNullOrEmpty(progressSettings.ApplicationEncryptIv))
         {
             var nLogLogger = new NLogLogger(TokenHeaderAddExceptionText);
             nLogLogger.Error("Encrypt Key and/or Encrypt IV are empty, the application will not operate.  Ensure they are set in the web.config");
             return;
         }
         var token = ApplicationCookieUtilities.ObjectToToken(myprincipal.TokenObject, progressSettings.ApplicationEncryptKey, progressSettings.ApplicationEncryptIv);
         actionExecutedContext.Response.Content.Headers.Add(ApplicationCookieUtilities.TokenName, token);
     }
 }
Exemplo n.º 25
0
        public void WhenCallingErrorShouldRecordOneError()
        {
            // act
            _logger.Error("Test String", new NotImplementedException());

            // assert
            _memoryTarget.Logs.Count.Should().Be(1, "because we only called the method once");
            _memoryTarget.Logs.All(log => log.Contains("Error")).Should().BeTrue("Because we only logged an Error");
        }
Exemplo n.º 26
0
        public static void Main(string[] args)
        {
            ILogger logger = new NLogLogger("logs.txt");

            AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
            {
                if (eventArgs.ExceptionObject is Exception e)
                {
                    logger.Error(FailureString, e);
                }
                else
                {
                    logger.Error(FailureString + eventArgs.ExceptionObject?.ToString());
                }
            };

            try
            {
                IRunnerApp runner = new RunnerApp(logger);
                runner.Run(args);
                return;
            }
            catch (AggregateException e)
            {
                logger.Error(FailureString, e.InnerException);
            }
            catch (Exception e)
            {
                logger.Error(FailureString, e);
            }

            var detached = Environment.GetEnvironmentVariable("NETHERMIND_DETACHED_MODE")?.ToLowerInvariant() == "true";

            if (detached)
            {
                Console.WriteLine("Press RETURN to exit.");
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
        }
Exemplo n.º 27
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");
        }
Exemplo n.º 28
0
 private void fillScreen(object userProfile)
 {
     try
     {
         UserProfile         curentUser            = (UserProfile)userProfile;
         List <CompanyBeans> userCompanyDataSource = curentUser.userCompany;
         lst_company.DataSource     = userCompanyDataSource;
         lst_company.DataTextField  = "cmp_code";
         lst_company.DataValueField = "id";
         lst_company.DataBind();
         fillMaterialGroup();
         fillMeasures();
         txt_mrp_low.Text  = "0";
         txt_mrp_high.Text = "100";
     }
     catch (Exception ex)
     {
         mylog.Error(ex);
     }
 }
Exemplo n.º 29
0
 public bool CommitAndRefreshChanges(out string error)
 {
     error = string.Empty;
     try
     {
         base.SaveChanges();
     }
     catch (DbUpdateConcurrencyException ex)
     {
         ex.Entries.ToList().ForEach(entry => entry.OriginalValues.SetValues(entry.GetDatabaseValues()));
         error = Utils.FormatError(ex);
         Logger.Error("UoW :" + error, ex, CommonEnums.LoggerObjectTypes.UnitOfWork);
         return(false);
     }
     catch (DbEntityValidationException e)
     {
         var sb = new StringBuilder();
         foreach (var eve in e.EntityValidationErrors)
         {
             sb.AppendLine(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                         eve.Entry.Entity.GetType().Name,
                                         eve.Entry.State));
             foreach (var ve in eve.ValidationErrors)
             {
                 sb.AppendLine(string.Format("- Property: \"{0}\", Error: \"{1}\"",
                                             ve.PropertyName,
                                             ve.ErrorMessage));
             }
         }
         error = sb.ToString();
         Logger.Error("UoW DbEntityValidationException exception: " + sb, e, CommonEnums.LoggerObjectTypes.UnitOfWork);
         return(false);
     }
     catch (Exception ex)
     {
         error = Utils.FormatError(ex);
         Logger.Error("UoW :" + Utils.FormatError(ex), ex, CommonEnums.LoggerObjectTypes.UnitOfWork);
         return(false);
     }
     return(true);
 }
Exemplo n.º 30
0
        public static void Main(string[] args)
        {
            ILogger logger = new NLogLogger("logs.txt");

            AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
            {
                logger.Error("Unhandled exception " + eventArgs.ExceptionObject?.ToString());
                Console.ReadLine(); // TODO: remove later
            };

            try
            {
                IRunnerApp runner = new RunnerApp(logger);
                runner.Run(args);
            }
            catch (Exception e)
            {
                logger.Error("Runner exception", e);
                Console.ReadLine(); // TODO: remove later
            }
        }