Exemplo n.º 1
0
        public void RunStartActions()
        {
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "Windows service OnStart");
            try
            {
                FeederHandler.Instance.Connector = new RedisConnector(ConfigurationManager.AppSettings["redisserver"]);
                using (RedisStressContext ctx = new RedisStressContext())
                {
                    FeederHandler.Instance.ImeiList = ctx.Products.Select(p => p.Imei).ToList();
                }
                Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, $"Loaded {FeederHandler.Instance.ImeiList.Count} IMEIs from SQL Server database into memory.");

                #region Quartz

                _schedulerFactory = new StdSchedulerFactory();
                _scheduler        = _schedulerFactory.GetScheduler();
                IJobDetail job     = JobBuilder.Create <HeartbeatFeeder>().WithIdentity("StatusFeederJob", "StatusFeederGroup").Build();
                ITrigger   trigger = TriggerBuilder.Create().WithIdentity("StatusFeederTrigger", "StatusFeederGroup").WithCronSchedule(ConfigurationManager.AppSettings["StatusFeederCron"], x => x.InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("UTC"))).Build();
                _scheduler.ScheduleJob(job, trigger);
                _scheduler.Start();

                #endregion
            }
            catch (Exception ex)
            {
                Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, ex);
            }
        }
Exemplo n.º 2
0
 public void Execute(IJobExecutionContext context)
 {
     Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, $"{nameof(HeartbeatFeeder)}: {DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff")} UTC");
     for (int i = 0; i < FeederHandler.Instance.ImeiList.Count; i++)
     {
         try
         {
             string   currentImei  = FeederHandler.Instance.ImeiList[i];
             string   LastHbUtcStr = FeederHandler.Instance.Connector.StringGet($"Product_{currentImei}_Heartbeat");
             DateTime LastHbUtc;
             if (DateTime.TryParse(LastHbUtcStr, out LastHbUtc))
             {
                 using (RedisStressContext ctx = new RedisStressContext())
                 {
                     var prod = ctx.Products.Where(p => p.Imei == currentImei).FirstOrDefault();
                     if (prod != null)
                     {
                         prod.LastHbUtc = LastHbUtc;
                         ctx.SaveChanges();
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, $"Exception in loop #{i}: {ex}");
         }
     }
 }
Exemplo n.º 3
0
        private static void Main(string[] args)
        {
            JwtHeader    head    = new JwtHeader();
            TokenPayload payload = new TokenPayload()
            {
                Username            = "******",
                IssuedAt            = 1422979638,
                BusinessUserID      = 1,
                BusinessID          = 2,
                AssignedBusinessIDs = new List <int>()
                {
                    3, 4, 6
                }
            };
            JwtUtility <JwtHeader, TokenPayload> jwtUtil = new JwtUtility <JwtHeader, TokenPayload>(head, payload);
            string token = jwtUtil.ToString();

            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, token);

            Console.WriteLine();

            Log4netLogger.Warn(MethodBase.GetCurrentMethod().DeclaringType, Validate(token));

            Console.ReadLine();
        }
Exemplo n.º 4
0
        public void DataReceived(object sender, PacketDataReceivedEventArgs e)
        {
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, $"Get {e.TotalBytesRead} byte(s): 0x{e.DataRead} from {e.DestinationTuple.RemoteEndPoint}");
            if (e.TotalBytesRead == 8 && e.DataRead.Substring(0, 6) == "AB0106" && e.DataRead.Substring(14, 2) == "00")
            {
                try
                {
                    byte[] ImeiStream = e.BytesRead.Skip(3).Take(4).ToArray();
                    int    ImeiInt    = BitConverter.ToInt32(ImeiStream.Reverse().ToArray(), 0);
                    string ImeiWithLeadingZerosLength20 = ImeiInt.ToString("00000000000000000000");
                    Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, $"Imei: {ImeiInt}. With leading zeros: {ImeiWithLeadingZerosLength20}");
                    string key   = $"Product_{ImeiWithLeadingZerosLength20}_Heartbeat";
                    string value = _connector.StringGet(key);

                    //if found the key (value == null)
                    if (value != null)
                    {
                        _connector.StringSet(key, DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                        PacketConnection.Send(new byte[] { 0xAB, 0xFF, 0x06, e.BytesRead[3], e.BytesRead[4], e.BytesRead[5], e.BytesRead[6], 0x01, 0x01 }, e.DestinationTuple);
                    }
                }
                catch (Exception ex)
                {
                    LogUtil.Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, $"Error during DataReceived (UDP)", ex);
                }
            }
        }
Exemplo n.º 5
0
 public static void AddTokenIssued(string username, string token, DateTime IssuedAtUtc, DateTime ExpireAtUtc)
 {
     try
     {
         using (AuthorizeEntities ctx = new AuthorizeEntities())
         {
             Account account = ctx.Accounts.Where(a => a.Uname == username).SingleOrDefault();
             if (account != null)
             {
                 account.TokenIssueds.Add(new TokenIssued()
                 {
                     Val         = token,
                     IssuedAtUtc = IssuedAtUtc,
                     ExpireAtUtc = ExpireAtUtc
                 });
                 ctx.SaveChanges();
             }
             else
             {
             }
         }
     }
     catch (Exception ex)
     {
         Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, "Error during adding TokenIssued", ex);
     }
 }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            //若提示log4net.config找不到,需将其属性改始终复制
            ILogger logger = new Log4netLogger();

            WriteTestLog(logger);
            logger = new FileLogger("Logs\\FileLogs\\");//bin下。
            WriteTestLog(logger);
            logger = new NLogger();
            WriteTestLog(logger);
        }
Exemplo n.º 7
0
 // GET: Test
 public ActionResult Index()
 {
     #region 日志记录测试
     ILogger logger = new Log4netLogger();
     WriteTestLog(logger);
     logger = new FileLogger();//bin下。
     WriteTestLog(logger);
     logger = new NLogger();
     WriteTestLog(logger);
     #endregion
     return(View());
 }
Exemplo n.º 8
0
 protected override void OnStart(string[] args)
 {
     Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "Windows service OnStart");
     try
     {
         RunStartActions();
     }
     catch (Exception e)
     {
         Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, "Error when starting Windows service", e);
     }
 }
Exemplo n.º 9
0
 public void Execute(IJobExecutionContext context)
 {
     Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, $"Quartz: {nameof(TokenCleaningJob)} was executed at {DateTime.UtcNow.ToString()} UTC");
     try
     {
         AuthorizeService.CleanExpiredTokens();
     }
     catch (Exception ex)
     {
         Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, "cannot cleanup tokens.", ex);
     }
 }
Exemplo n.º 10
0
        public void RunStartActions()
        {
            HbListener.Instance.Connector = new RedisConnector(ConfigurationManager.AppSettings["redisserver"]);
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "Connected to Redis server.");
            List <Product> products = null;

            using (RedisStressContext ctx = new RedisStressContext())
            {
                products = ctx.Products.ToList();
                Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, $"Get {products.Count} products.");
            }
            var start = DateTime.UtcNow;
            int count = 0;
            int countNull = 0, countHasValue = 0;

            foreach (Product prod in products)
            {
                try
                {
                    if (prod.LastHbUtc != null)
                    {
                        countHasValue++;
                        HbListener.Instance.Connector.StringSet($"Product_{prod.Imei}_Heartbeat", prod.LastHbUtc.Value.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                        count++;
                    }
                    else
                    {
                        countNull++;
                        HbListener.Instance.Connector.StringSet($"Product_{prod.Imei}_Heartbeat", "");
                        count++;
                    }
                }
                catch (Exception ex)
                {
                    Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, ex);
                }
            }
            var end = DateTime.UtcNow;

            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, $"{countHasValue} products (in database) do have {nameof(Product.LastHbUtc)} value and {countNull} products (in database) don't. Successfully set {count} Redis keys in {(end - start).TotalMilliseconds} millisecs.");
            HbListener.Instance.PacketConnection = new UdpConnection();
            HbListener.Instance.PacketConnection.DataReceived += evtHandlerReceived;
            HbListener.Instance.PacketConnection.DataSent     += evtHandlerSent;
            HbListener.Instance.PacketConnection.StartUdpListening(int.Parse(ConfigurationManager.AppSettings["listenport"]));
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "Heartbeat listener is running...");

            InternalNetworkListener.Instance.TcpConnection = new TcpConnection();
            InternalNetworkListener.Instance.TcpConnection.StartListening(int.Parse(ConfigurationManager.AppSettings["tcpport"]));
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "Listen TCP...");
        }
Exemplo n.º 11
0
        public void RunStopActions()
        {
            HbListener.Instance.PacketConnection.DataReceived -= evtHandlerReceived;
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "DataReceived event Unsubscribed.");
            HbListener.Instance.PacketConnection.DataSent -= evtHandlerSent;
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "DataSent event Unsubscribed.");
            HbListener.Instance.PacketConnection.Dispose();
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "Connection disposed.");
            HbListener.Instance.Connector = null;
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "Redis connection set to null.");

            InternalNetworkListener.Instance.TcpConnection.Dispose();
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "Dispose TCP connection");
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string token;

            try
            {
                token = httpContext.GetAuthToken();
            }
            catch (Exception ex)
            {
                Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, $"AuthorizeCore error", ex);
                return(false);
            }
            return(AuthUtility.IsAuthorized(token, true));
        }
Exemplo n.º 13
0
 private void Disconnect()
 {
     try
     {
         if (this.ConnectionSocket == null)
         {
             return;
         }
         this.StopServer();
     }
     catch (Exception exception)
     {
         Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, exception);
     }
 }
Exemplo n.º 14
0
        public void log4net日志测试()
        {
            ILogger logger = new Log4netLogger();

            logger.Info("log4net测试日志");
            try
            {
                int i = 1, j = 0;
                i = i / j;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
Exemplo n.º 15
0
 public static IDictionary <int, string> FetchHashTypes()
 {
     try
     {
         using (AuthorizeEntities ctx = new AuthorizeEntities())
         {
             return(ctx.HashTypes.OrderBy(x => x.Id).ToDictionary(kvp => kvp.Id, kvp => kvp.Name));
         }
     }
     catch (Exception ex)
     {
         Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, "Cannot fetch hash types", ex);
         return(null);
     }
 }
Exemplo n.º 16
0
        public bool Start()
        {
            bool isSuccessful = true;

            try
            {
                scheduler.ScheduleJob(job, trigger);
            }
            catch (Exception ex)
            {
                isSuccessful = false;
                Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, $"cannot start", ex);
            }
            return(isSuccessful);
        }
Exemplo n.º 17
0
        public bool Shutdown()
        {
            bool isSuccessful = true;

            try
            {
                scheduler.Shutdown(true);
            }
            catch (Exception ex)
            {
                isSuccessful = false;
                Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, $"cannot shutdown", ex);
            }
            return(isSuccessful);
        }
Exemplo n.º 18
0
        public bool Resume()
        {
            bool isSuccessful = true;

            try
            {
                scheduler.ResumeAll();
            }
            catch (Exception ex)
            {
                isSuccessful = false;
                Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, $"cannot resume", ex);
            }
            return(isSuccessful);
        }
Exemplo n.º 19
0
 public static void CleanExpiredTokens()
 {
     try
     {
         using (AuthorizeEntities ctx = new AuthorizeEntities())
         {
             var tokenToDelete = ctx.TokenIssueds.Where(x => x.ExpireAtUtc <= DateTime.UtcNow);
             ctx.TokenIssueds.RemoveRange(tokenToDelete);
             ctx.SaveChanges();
         }
     }
     catch (Exception ex)
     {
         Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, "Error during token cleanup.", ex);
     }
 }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            EventHandler <PacketDataReceivedEventArgs> evtHandlerReceived = new EventHandler <PacketDataReceivedEventArgs>(HbSpammer.Instance.DataReceived);
            EventHandler <PacketDataSentEventArgs>     evtHandlerSent     = new EventHandler <PacketDataSentEventArgs>(HbSpammer.Instance.DataSent);

            HbSpammer.Instance.PacketConnection = new UdpConnection();
            HbSpammer.Instance.PacketConnection.DataReceived += evtHandlerReceived;
            HbSpammer.Instance.PacketConnection.DataSent     += evtHandlerSent;
            HbSpammer.Instance.PacketConnection.StartUdpListening(int.Parse(ConfigurationManager.AppSettings["localPort"]));
            IPEndPoint localEndPoint, remoteEndPoint;

            localEndPoint  = HbSpammer.Instance.PacketConnection.ConnectionSocket.LocalEndPoint as IPEndPoint;
            remoteEndPoint = new IPEndPoint(IPAddress.Parse(ConfigurationManager.AppSettings["remoteIP"]), int.Parse(ConfigurationManager.AppSettings["remotePort"]));
            HbSpammer.Instance.PacketConnection.destinationTuple = new DestinationTuple(localEndPoint, remoteEndPoint);
            Console.Write("How many Heartbeats do you want to send very second? ");
            bool success;

            do
            {
                success = int.TryParse(Console.ReadLine(), out HbSpammer.Instance.frequency);
            }while (!success);
            try
            {
                List <string> ImeiList = null;
                using (RedisStressContext ctx = new RedisStressContext())
                {
                    ImeiList = ctx.Products.Select(pr => pr.Imei).ToList();
                }
                for (int i = 0; i < ImeiList.Count; i++)
                {
                    int    ImeiInt = int.Parse(ImeiList[i]);
                    byte[] ImeiByteArray = BitConverter.GetBytes(ImeiInt).Reverse().ToArray();
                    byte[] HbByteArray = new byte[] { 0xAB, 0x01, 0x06 }.Concat(ImeiByteArray).Concat(new byte[] { 0x00 }).ToArray();
                    HbSpammer.Instance.HbByteStreamList.Add(HbByteArray);
                }
                HbSpammer.Instance._scheduler1 = HbSpammer.Instance._schedulerFactory1.GetScheduler();
                IJobDetail job        = JobBuilder.Create <HbBatchSend>().WithIdentity("HbBatchSend", "HbBatchSendGroup").Build();
                string     cronString = "* * * * * ? *";
                ITrigger   trigger    = TriggerBuilder.Create().WithIdentity("EverySecond", "HbBatchSendGroup").WithCronSchedule(cronString, x => x.InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("UTC"))).Build();
                HbSpammer.Instance._scheduler1.ScheduleJob(job, trigger);
                HbSpammer.Instance._scheduler1.Start();
            }
            catch (Exception ex)
            {
                Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, ex);
            }
        }
Exemplo n.º 21
0
 // GET: File
 public ActionResult Index()
 {
     try
     {
         string        RootDirectory = Server.MapPath("~/App_Data/");
         DirectoryInfo d             = new DirectoryInfo($"{RootDirectory}files\\");
         FileInfo[]    Files         = d.GetFiles("*.txt");
         ViewBag.Files = Files;
     }
     catch (Exception ex)
     {
         Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, $"Error in {nameof(FileController)}", ex);
         return(View("Error"));
     }
     ViewBag.Title = Resources.Resource.File;
     return(View());
 }
Exemplo n.º 22
0
        public void Constructor_AllServicesManually_CartsController()
        {
            // arrange
            var              httpRequest  = new HttpRequest("", "https://www.vml.com", "");
            var              stringWriter = new StringWriter();
            var              httpResponse = new HttpResponse(stringWriter);
            var              httpContext  = new HttpContext(httpRequest, httpResponse);
            HttpContextBase  contextBase  = new HttpContextWrapper(httpContext);
            ICommerceService service      = new DefaultCommerceService(new CommerceDatabaseContext());
            ILogger          logger       = new Log4netLogger(new RootLogger(Level.Alert), new Log4netFactory());

            // act
            var sut = new CartsController(service, logger, contextBase);

            // assert
            Assert.IsNotNull(sut);
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            // Display the number of command line arguments.
            IZdbLogger logger = new ConsoleLogger();

            logger.Debug("11 Debug print");
            logger.Info("11 Info level log print");
            logger.Error("11 Error level log print");

            IZdbLogger logger2 = new Log4netLogger(logger.GetType());

            logger2.Debug("2 Debug print");
            logger2.Info("2 Info level log print");
            logger2.Error("2 Error level log print");

            IZdbLogger logger3 = LoggerFactory.GetLogger(LogType.CONSOLE, typeof(Program));

            logger3.Debug("3 Debug print");
            logger3.Info("3 Info level log print");
            logger3.Error("3 Error level log print");

            IZdbLogger logger4 = LoggerFactory.GetLogger(LogType.LOG4NET, typeof(Program));

            logger4.Debug("4 Debug print");
            logger4.Info("4 Info level log print");
            logger4.Error("4 Error level log print");


            IZdbLogger logger5 = LoggerFactory.GetLogger(LogType.UNITY_DEBUG, typeof(Program));

            try
            {
                logger5.Debug("5 Debug print");
                logger5.Info("5 Info level log print");
                logger5.Error("5 Error level log print");
            }catch (Exception e)
            {
                Console.WriteLine(e);
            }

            IZdbLogger logger6 = LoggerFactory.GetLogger();

            logger6.Debug("6 Debug print");
            logger6.Info("6 Info level log print");
            logger6.Error("6 Error level log print");
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "Running Windows service as a Console...");
            var service1 = new AppService();

            try
            {
                service1.RunStartActions();
            }
            catch (Exception e)
            {
                LogUtil.Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, "Error when trying to start Windows service as a Console.", e);
            }
            Console.Write("Press Enter to terminate this Console...");
            Console.ReadLine();
            service1.RunStopActions();
        }
Exemplo n.º 25
0
        private void StartConversation()
        {
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, $"{_clientSocketAddress} Start");
            DateTime utcNow = DateTime.UtcNow;

            _lastReceiveDateTime    = utcNow;
            _currentReceiveDateTime = utcNow;
            Timer t        = new Timer(new TimerCallback(CheckClientCommInterval), null, 15000, 15000);
            int   bytesRec = 0;

            byte[] dataBytes = new byte[4096];

            // An incoming connection needs to be processed.
            while (!_stopClient)
            {
                try
                {
                    if (!IsConnected())
                    {
                        break;
                    }
                    bytesRec = _clientSocket.Receive(dataBytes);
                    _currentReceiveDateTime = DateTime.UtcNow;
                    if (bytesRec > 0)
                    {
                        byte[] shrinkDataBytes = new byte[bytesRec];
                        Array.Copy(dataBytes, shrinkDataBytes, bytesRec);
                        Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, $"{_clientSocketAddress} received {bytesRec} bytes: {ByteStreamUtil.ByteToHexBit(shrinkDataBytes)}");
                        byte[] answer = Encoding.ASCII.GetBytes("<Ack>").Concat(shrinkDataBytes).Concat(Encoding.ASCII.GetBytes("<\\Ack>")).ToArray();
                        SendMessage(answer);
                        Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, $"{_clientSocketAddress} sent {answer.Count()} bytes: {ByteStreamUtil.ByteToHexBit(answer)}");
                    }
                }
                catch (Exception exception)
                {
                    Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, $"{_clientSocketAddress} exception {exception}");
                    _stopClient        = true;
                    _markedForDeletion = true;
                }
            }
            _stopClient        = true;
            _markedForDeletion = true;
            t.Change(Timeout.Infinite, Timeout.Infinite);
            t = null;
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, $"{_clientSocketAddress} End");
        }
Exemplo n.º 26
0
        //
        // GET: /Home/

        public ActionResult Index()
        {
            ILogger logger = new Log4netLogger();

            logger.Info("记录信息");
            logger.Debug("测试");
            try
            {
                int i = 0, j = 0;
                i = i / j;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return(Content(""));
        }
Exemplo n.º 27
0
 public static void ExtendTokenIssued(string username, string token)
 {
     try
     {
         using (AuthorizeEntities ctx = new AuthorizeEntities())
         {
             TokenIssued tokenIssued = ctx.TokenIssueds.Where(t => t.Account.Uname == username && t.Val == token).SingleOrDefault();
             if (tokenIssued != null)
             {
                 tokenIssued.ExpireAtUtc = DateTime.UtcNow.AddSeconds(Settings.InitSetting.Instance.AuthorizationTokenLifeSpanInSecond);
                 ctx.SaveChanges();
             }
         }
     }
     catch (Exception ex)
     {
         Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, "Error during extending TokenIssued", ex);
     }
 }
Exemplo n.º 28
0
        public void RunStopActions()
        {
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "Windows service OnStop");
            try
            {
                #region Quartz

                _scheduler.Shutdown(true);
                Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "Quartz Shutdown.");

                #endregion
            }
            catch (Exception ex)
            {
                Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, ex);
            }
            FeederHandler.Instance.Connector = null;
            Log4netLogger.Info(MethodBase.GetCurrentMethod().DeclaringType, "Redis connection set to null.");
        }
Exemplo n.º 29
0
        public bool Initialize()
        {
            bool isSuccessful = true;

            try
            {
                schedulerFactory = new StdSchedulerFactory();
                scheduler        = schedulerFactory.GetScheduler();
                scheduler.Start();
                job = JobBuilder.Create <TokenCleaningJob>().WithIdentity("myJob", "group1").Build();
                string cronString = ConfigurationManager.AppSettings["TokenCleaningCron"];
                trigger = TriggerBuilder.Create().WithIdentity("myTrigger", "group1").WithCronSchedule(cronString, x => x.InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("UTC"))).Build();
            }
            catch (Exception ex)
            {
                isSuccessful = false;
                Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, $"cannot initialize", ex);
            }
            return(isSuccessful);
        }
Exemplo n.º 30
0
 public bool IsValid(string token)
 {
     try
     {
         string[]  parts             = token.Split('.');
         string    headerBase64Text  = parts[0];
         string    payloadBase64Text = parts[1];
         JwtHeader headerObj         = JsonConvert.DeserializeObject <JwtHeader>(Encoding.ASCII.GetString(Convert.FromBase64String(headerBase64Text)));
         int       mod4 = payloadBase64Text.Length % 4;
         if (mod4 > 0)
         {
             if (mod4 == 1)
             {
                 payloadBase64Text += "===";
             }
             else if (mod4 == 2)
             {
                 payloadBase64Text += "==";
             }
             else
             {
                 payloadBase64Text += "=";
             }
         }
         T2 payloadObj = JsonConvert.DeserializeObject <T2>(Encoding.ASCII.GetString(Convert.FromBase64String(payloadBase64Text)));
         if (headerObj.HashAlgorithm != "HS256" || headerObj.TokenType != "JWT")
         {
             Log4netLogger.Warn(MethodBase.GetCurrentMethod().DeclaringType, "Invalid token header");
             return(false);
         }
         return(token == (new JwtUtility <JwtHeader, T2>(headerObj, payloadObj)).ToString());
     }
     catch (Exception ex)
     {
         Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, "Cannot validate token", ex);
         return(false);
     }
 }