public void Save() { if (Stats != null) { try { string dir = Path.Combine(MainApp.dirs[1], CurrentUri.Host + "_" + CurrentUri.Port); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } string file = Path.Combine(dir, "uptime_" + TimeChron.GetRealTime().ToString("dd.MM.yyyy") + ".txt"); bool fileNew = !File.Exists(file); var fs = File.Open(file, FileMode.Append); string all = (fs.Length > 0 ? "\n" : "") + string.Join('\n', Stats); var buff = Encoding.UTF8.GetBytes(all); fs.Write(buff, 0, buff.Length); fs.Close(); if (!fileNew) { Stats.Clear(); } } catch (Exception ex) { Logger.Errors.Add(ex); } } }
/// <summary> /// Writes user state and request to log /// </summary> /// <param name="logger"></param> /// <param name="stats"></param> /// <param name="address">IP adress of user</param> /// <param name="request">Request string</param> /// <param name="user">UserAgent</param> /// <param name="xid">header x-id as email or unique user id</param> public static bool LogWrite(this ILogger logger, UserStats stats, string address, string request, string user, string xid) { string usrx; address = address ?? ""; if (!string.IsNullOrEmpty(xid)) { var t = UserStats.Parse(xid); usrx = "\nLoginedAs: " + t.UserType + " [" + (int)t.UserType + "]" + " ID: " + t.UserId; stats.CheckUser(user, xid, t.UserId); } else { usrx = " No user ID found"; } if (address.Contains(':')) { address = address.Substring(0, address.IndexOf(':')); } var d = TimeChron.GetRealTime().ToString("hh:mm:ss - dd.MM.yyyy", CultureInfo.CreateSpecificCulture("en-US")); if (!request.Contains("ulog") && !request.Contains("trace") && !user.Contains("MaxRev")) { logger.Notify(LogArea.Http, LogType.Main, "\n" + d + "\nip: " + address + usrx + "\nfrom: " + user + "\nreq=" + request + "\n"); } return(true); }
public void Save() { var st = TimeChron.GetRealTime().ToLongDateString(); File.AppendAllText(Path.Combine(App.Get.Core.DirectoryManager[App.Dirs.Feedback], "users_reviews" + st + ".txt"), GetAll(true)); for (int i = 0; i < Feed.Count; i++) { Feed[Feed.ElementAt(i).Key] = ""; } }
public void Manage() { var time = TimeChron.GetRealTime().ToString("hh:mm:ss"); System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch(); st.Start(); bool isopen = Tools.IsPortOpen(CurrentUri.Host, CurrentUri.Port, new TimeSpan(0, 0, 5)); st.Stop(); Stats.Add(string.Format("{0} | {1} | {2}ms", time, (isopen ? "OK" : "DOWN"), st.ElapsedMilliseconds)); }
public bool Checker(string key) { var g = Feed.Where(x => x.Key != null && x.Key.Contains(key)).ToArray(); if (g.Any()) { if (TimeChron.GetRealTime() - DateTime.ParseExact(g.Last().Key.Split("=>")[1].Trim(' '), "hh:mm:ss - dd.MM.yyyy", null) > new TimeSpan(0, 5, 0)) { return(true); } return(false); } return(true); }
private string Tracer() { this.Server.State.OnApiResponse(); this.Server.State.DecApiResponseUser(); var m = App.Get.ReparseScheduler.ScheduledTime - TimeChron.GetRealTime(); StringBuilder resp = new StringBuilder(); resp.Append(Tools.GetBaseTrace(Server)); resp.Append("\n\nSpecialties count: " + App.Get.SpecialtyParser.SpecialtyList.Count + "\nSpecialty parser encounter: " + $"{m.Days}d {m.Hours}h {m.Minutes}m {m.Seconds}s"); return(resp.ToString()); }
private bool FeedbackHandler(IRequestData Content) { try { var qur = Content.Form; if (!qur.TryGetValue("mail", out var c1) || !App.Get.FeedbackbHelper.Checker(c1)) { return(false); } qur.TryGetValue("text", out var c2); App.Get.FeedbackbHelper.Feed.Add(c1 + " => " + TimeChron.GetRealTime().ToString("hh:mm:ss - dd.MM.yyyy"), c2); } catch { return(false); } return(true); }
private async Task UpdateParser(Parser obj) { try { foreach (var u in obj.Newslist) { if ((TimeChron.GetRealTime() - new DateTime(long.Parse(u.CachedOnStr))) .Hours > App.Get.Config.CacheAlive) { await NewsItemDetailed.Process(u); } } } catch (Exception) { // ignored } }
public StatsInfo GetStatus(string key, string port = null) { var f = MainApp.dirs[1] + "/" + key + "_" + port + "/uptime_" + TimeChron.GetRealTime().ToString("dd.MM.yyyy") + ".txt"; StatsInfo list = new StatsInfo(); if (File.Exists(f)) { var r = File.OpenText(f); while (!r.EndOfStream) { var line = r.ReadLine(); list.StatList.Add(StatsInfo.Parse(line)); } } foreach (var i in POOL.Where(x => x.Key.Contains(key) && x.Key.Contains(port)).First().Stats) { list.StatList.Add(StatsInfo.Parse(i)); } return(list); }
public static bool IsPortOpen(string host, int port, TimeSpan timeout) { try { using (var client = new TcpClient()) { var result = client.BeginConnect(host, port, null, null); if (!result.AsyncWaitHandle.WaitOne(timeout)) { return(false); } client.EndConnect(result); } } catch (SocketException) { Logger.Errors.Add(new Exception( string.Format("No internet connection on {0}", TimeChron.GetRealTime().ToString("hh:mm:ss - dd.MM.yyyy")))); return(false); } catch { return(false); } return(true); }
/// <summary> /// Writes user state and request to log /// </summary> /// <param name="logger"></param> /// <param name="stats"></param> /// <param name="address">IP adress of user</param> /// <param name="request">Request string</param> /// <param name="useragent">UserAgent</param> /// <param name="xid">header x-id as email or unique user id</param> public static bool LogWrite(this ILogger logger, UserStats stats, string address, string request, string useragent, string xid) { string usrx; address ??= ""; if (!string.IsNullOrEmpty(xid)) { var t = UserStats.Parse(xid); usrx = $"\nLoginedAs: {t.UserType} [{(int)t.UserType}] ID: {t.UserId}"; stats.CheckUser(useragent, xid, t.UserId); } else { usrx = " No user ID found"; } if (address.Contains(':')) { address = address.Substring(0, address.IndexOf(':')); } var d = TimeChron.GetRealTime().ToString("hh:mm:ss - dd.MM.yyyy", CultureInfo.CreateSpecificCulture("en-US")); if (request != null) { if (!request.Contains("ulog") && !request.Contains("trace")) { if (useragent != null && !useragent.Contains("MaxRev") || useragent == null) { logger.Notify(LogArea.Http, LogType.Main, $"\n{d}\nip: {address}{usrx}\nfrom: {useragent ?? "Unknown client"}\nreq={request}\n"); } } } return(true); }
public async Task <string> Schedule() { var query = Info.Query; try { var auto = AutoReplaceHelper.Current?.Now ?? false; if (query.HasKey("auto")) { var autox = query["auto"]; auto = autox == "true" || autox == "1"; } if (query.HasKey("group") || query.HasKey("name")) { var group = Uri.UnescapeDataString(query["group"] ?? ""); var name = Uri.UnescapeDataString(query["name"] ?? ""); var year = TimeChron.GetRealTime().Year; if (query.HasKey("year")) { var ryear = query["year"]; year = int.Parse(ryear); } var type = ScheduleKitchen.RetType.days; if (query.HasKey("type")) { var rtype = query["type"]; if (rtype == "weeks") { type = ScheduleKitchen.RetType.weeks; } else if (rtype == "days") { type = ScheduleKitchen.RetType.days; } else { throw new InvalidOperationException("InvalidKey: type can be only 'days' or 'weeks'"); } } if (query.HasKey("sdate")) { var sdate = query["sdate"]; if (query.HasKey("edate")) { var edate = query["edate"]; var isLecturer = !string.IsNullOrEmpty(name); var data = new ScheduleKitchen(isLecturer ? name : group, sdate, edate, isLecturer, type); var rp = await data.GetDaysAsync(auto).ConfigureAwait(false); if (data.R != null) { return(JsonConvert.SerializeObject(ResponseTyper(data.R, new ScheduleVisualiser { Data = rp }))); } return(JsonConvert.SerializeObject(new Response { Code = StatusCode.Success, Content = new ScheduleVisualiser { Data = rp }, Error = null })); } return(CreateErrorResp(new InvalidOperationException("InvalidKey: edate expected - format dd.MM.yyyy"))); } if (query.HasKey("week")) { var rweek = query["week"]; var week = int.Parse(rweek); CheckWeekRange(week); var isLecturer = !string.IsNullOrEmpty(name); var cury = TimeChron.GetRealTime().Year; if (year > cury + 1 || year < cury - 1) { throw new InvalidOperationException("InvalidKey: year must be in bounds (current year+-1)"); } var data = new ScheduleKitchen(isLecturer ? name : group, week, year, isLecturer, type); var rp = await data.GetDaysAsync(auto).ConfigureAwait(false); if (data.R != null) { return(JsonConvert.SerializeObject(ResponseTyper(data.R, new ScheduleVisualiser { Data = rp }))); } return(JsonConvert.SerializeObject(new Response { Code = StatusCode.Success, Content = new ScheduleVisualiser { Data = rp }, Error = null })); } if (query.HasKey("weeks")) { var rweek = query["weeks"]; string[] weeks = null; if (rweek.Contains(',')) { weeks = rweek.Split(','); } var t1 = int.Parse((weeks ?? throw new BadRequestException("weeks must contain , separator")).First()); var t2 = int.Parse(weeks.Last()); CheckWeekRange(t1, t2); foreach (var weekq in weeks) { var week = int.Parse(weekq); if (week > 52) { week = 52; } if (/*week > 52 ||*/ week < 1) { throw new InvalidOperationException("InvalidKey: week is not valid"); } } var isLecturer = !string.IsNullOrEmpty(name); var cury = TimeChron.GetRealTime().Year; if (year > cury + 1 || year < cury - 1) { throw new InvalidOperationException("InvalidKey: year must be in bounds (current year+-1)"); } var data = new ScheduleKitchen(isLecturer ? name : group, t1, t2, year, isLecturer, type); var rp = await data.GetDaysAsync(auto).ConfigureAwait(false); if (data.R != null) { return(JsonConvert.SerializeObject(ResponseTyper(data.R, new ScheduleVisualiser { Data = rp }))); } return(JsonConvert.SerializeObject(new Response { Code = StatusCode.Success, Content = new ScheduleVisualiser { Data = rp }, Error = null })); } return(CreateErrorResp(new InvalidOperationException("InvalidKey: sdate expected - format dd.MM.yyyy"))); } return(CreateErrorResp(new InvalidOperationException("InvalidKey: group expected"))); } catch (OperationCanceledException) { return(JsonConvert.SerializeObject(new Response { Code = StatusCode.GatewayTimeout, Cache = false, Content = null, Error = "GatewayTimeout" })); } catch (Exception ex) { Server.Logger.Notify(LogArea.Other, LogType.Info, $"{ex.GetType()}:{ex.Message}\n{WebUtility.UrlDecode(ModuleContext.Request)}"); return(JsonConvert.SerializeObject(ResponseTyper(ex))); } }
public NewsItem() { CachedOn = TimeChron.GetRealTime(); }