/// <summary> /// Yields every minute between start and end range. /// </summary> /// <returns></returns> public static IEnumerable <DateTime?> MinutesBetween(this DateTime?start, DateTime?end, MinutesBetweenMode mode = MinutesBetweenMode.Inclusive) { if (end == start || start > end) { return(Enumerable.Empty <DateTime?>()); } int adjustment = 1; if (mode == MinutesBetweenMode.Inclusive) { adjustment = 1; } if (mode == MinutesBetweenMode.EndExclusive) { adjustment = 0; } if (mode == MinutesBetweenMode.StartExclusive) { start = start?.AddMinutes(1); } if (mode == MinutesBetweenMode.StartAndEndExclusive) { adjustment = 0; start = start?.AddMinutes(1); } if (end == start || start > end) { return(Enumerable.Empty <DateTime?>()); } return(Enumerable.Range(0, (int)((end - start).GetValueOrDefault().TotalMinutes) + adjustment).Select(d => start?.AddMinutes(d))); }
private static Task WriteLiveShowDetailsToResponseBody(DateTime?nextShowDateUtc, HttpResponse response) { // Internet Calendaring and Scheduling Core Object Specification (iCalendar): https://tools.ietf.org/html/rfc5545 /* BEGIN:VCALENDAR * VERSION:2.0 * BEGIN:VEVENT * UID:[email protected] * DESCRIPTION:A live stream broadcast with the Visual Studio Tools for Apache Cordova team, answering your questions. * DTSTART:20150804T170000Z * DTEND:20150804T035959Z * LOCATION:http://taco.visualstudio.com/live * SUMMARY:Visual Studio Tools for Apache Cordova, Live Q&A * END:VEVENT * END:VCALENDAR */ return(response.WriteAsync( "BEGIN:VCALENDAR\r\n" + "VERSION:2.0\r\n" + "BEGIN:VEVENT\r\n" + "UID:[email protected]\r\n" + "DTSTART:" + nextShowDateUtc?.ToString(_dateTimeFormat) + "\r\n" + "DTEND:" + nextShowDateUtc?.AddMinutes(30).ToString(_dateTimeFormat) + "\r\n" + "SUMMARY:Visual Studio Tools for Apache Cordova, Live Q&A\r\n" + "DESCRIPTION:A live stream broadcast with the Visual Studio Tools for Apache Cordova team, answering your questions.\r\n" + "LOCATION:http://taco.visualstudio.com/live/\r\n" + "END:VEVENT\r\n" + "END:VCALENDAR\r\n")); }
public static DateTime InstantToDateTime(double instant, DateTime start, TimeUnits units = TimeUnits.SECONDS) { DateTime instantAsDate = start; switch (units) { case TimeUnits.YEARS: instantAsDate = start.AddYears((int)instant); break; case TimeUnits.MONTHS: instantAsDate = start.AddMonths((int)instant); break; case TimeUnits.DAYS: instantAsDate = start.AddDays(instant); break; case TimeUnits.HOURS: instantAsDate = start.AddHours(instant); break; case TimeUnits.MINUTES: instantAsDate = start.AddMinutes(instant); break; case TimeUnits.SECONDS: instantAsDate = start.AddSeconds(instant); break; } return instantAsDate; }
private static Task WriteLiveShowDetailsToResponseBody(DateTime?nextShowDateUtc, HttpResponse response) { // Internet Calendaring and Scheduling Core Object Specification (iCalendar): https://tools.ietf.org/html/rfc5545 /* BEGIN:VCALENDAR * VERSION:2.0 * BEGIN:VEVENT * UID:[email protected] * DESCRIPTION:ASP.NET Community Standup * DTSTART:20150804T170000Z * DTEND:20150804T035959Z * LOCATION:https://live.asp.net/ * SUMMARY:ASP.NET Community Standup * END:VEVENT * END:VCALENDAR */ return(response.WriteAsync( "BEGIN:VCALENDAR\r\n" + "VERSION:2.0\r\n" + "BEGIN:VEVENT\r\n" + "UID:[email protected]\r\n" + "DTSTART:" + nextShowDateUtc?.ToString(_dateTimeFormat) + "\r\n" + "DTEND:" + nextShowDateUtc?.AddMinutes(30).ToString(_dateTimeFormat) + "\r\n" + "SUMMARY:ASP.NET Community Standup\r\n" + "DESCRIPTION:\r\n" + "LOCATION:https://live.asp.net/\r\n" + "END:VEVENT\r\n" + "END:VCALENDAR\r\n")); }
public OnPostSave() { now = DateTime.UtcNow; sagaStore = new Mock<IStoreSagas>(); eventPublisher = new Mock<IPublishEvents>(); timeoutDispatcher = new TimeoutDispatcher(new Lazy<IStoreSagas>(() => sagaStore.Object), new Lazy<IPublishEvents>(() => eventPublisher.Object), callback => timer = new FakeTimer(callback)); sagaTimeout = new SagaTimeout(typeof(FakeSaga), GuidStrategy.NewGuid(), now.AddMinutes(5)); SystemTime.OverrideWith(() => now); sagaStore.Setup(mock => mock.GetScheduledTimeouts(It.IsAny<DateTime>())).Returns(new[] { sagaTimeout }); timer.InvokeCallback(); timer.Reset(); }
private async Task UpdateCacheIfExpired() { bool isCacheExpired = _lastUpdatedDateTime is null || DateTime.UtcNow >= _lastUpdatedDateTime?.AddMinutes(REFRESH_INTERVAL_MINUTES); if (isCacheExpired) { List <ConfigurationEntity> entities = await _cloudStorageTable.GetAllTableEntitiesAsync <ConfigurationEntity>(); _configurationCache = entities.ToDictionary(_ => _.RowKey, _ => _.ConfigurationValue); _lastUpdatedDateTime = DateTime.UtcNow; } }
public PeriodicBackupRunner(DocumentDatabase database, ServerStore serverStore, DateTime?wakeup = null) { _database = database; _serverStore = serverStore; _logger = LoggingSource.Instance.GetLogger <PeriodicBackupRunner>(_database.Name); _cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(_database.DatabaseShutdown); _tempBackupPath = (_database.Configuration.Storage.TempPath ?? _database.Configuration.Core.DataDirectory).Combine("PeriodicBackupTemp"); // we pass wakeup-1 to ensure the backup will run right after DB woke up on wakeup time, and not on the next occurrence. // relevant only if it's the first backup after waking up _databaseWakeUpTimeUtc = wakeup?.AddMinutes(-1); _database.TombstoneCleaner.Subscribe(this); IOExtensions.DeleteDirectory(_tempBackupPath.FullPath); Directory.CreateDirectory(_tempBackupPath.FullPath); }
public static bool IsIfTokenExpired (DateTime?tokenTime, string TokenGiven = null) { if (string.IsNullOrEmpty(TokenGiven) || tokenTime == null) { return(true); } var expiryDate = tokenTime?.AddMinutes(60); if (expiryDate <= DateTime.Now) { return(true); } return(false); }
private static Task WriteLiveShowDetailsToResponseBody(DateTime?nextShowDateUtc, HttpResponse response) { // Internet Calendaring and Scheduling Core Object Specification (iCalendar): https://tools.ietf.org/html/rfc5545 /* BEGIN:VCALENDAR * VERSION:2.0 * BEGIN:VEVENT * UID:[email protected] * DESCRIPTION:ASP.NET Community Standup * DTSTART:20150804T170000Z * DTEND:20150804T035959Z * SUMMARY:ASP.NET Community Standup * LOCATION:https://live.asp.net/ * BEGIN:VALARM * TRIGGER:-PT15M * ACTION:DISPLAY * END:VALARM * END:VEVENT * END:VCALENDAR */ var calendarString = new StringBuilder() .AppendLine("BEGIN:VCALENDAR") .AppendLine("VERSION:2.0") .AppendLine("BEGIN:VEVENT") .AppendLine("UID:[email protected]") .AppendLine("DESCRIPTION:ASP.NET Community Standup") .AppendLine("DTSTART:" + nextShowDateUtc?.ToString(_dateTimeFormat)) .AppendLine("DTEND:" + nextShowDateUtc?.AddMinutes(30).ToString(_dateTimeFormat)) .AppendLine("SUMMARY:ASP.NET Community Standup") .AppendLine("LOCATION:https://live.asp.net/") .AppendLine("BEGIN:VALARM") .AppendLine("TRIGGER:-PT15M") .AppendLine("ACTION:DISPLAY") .AppendLine("END:VALARM") .AppendLine("END:VEVENT") .AppendLine("END:VCALENDAR") .ToString(); return(response.WriteAsync(calendarString)); }
public static DateTime?NAddMinutes(this DateTime?self, double?value) => value.HasValue ? self?.AddMinutes(value.Value) : null;
/// <devdoc> /// <para> This constructor creates /// a FormsAuthenticationTicket instance with the specified name and cookie durability, /// and default values for the other settings.</para> /// </devdoc> public FormsAuthenticationTicket(String name, bool isPersistent, Int32 timeout) { _Version = 2; _Name = name; _IssueDateUtcHasValue = true; _IssueDateUtc = DateTime.UtcNow; _IssueDate = DateTime.Now; _IsPersistent = isPersistent; _UserData = ""; _ExpirationUtcHasValue = true; _ExpirationUtc = _IssueDateUtc.AddMinutes(timeout); _Expiration = _IssueDate.AddMinutes(timeout); _CookiePath = FormsAuthentication.FormsCookiePath; }
private void OnEnable() { #if !UNITY_EDITOR try { #endif //EventDispatcher.Instance.AddEventListener(MieShiDisappearModelRoot_Event.EVENT_TYPE, DisappearModelRoot); EventDispatcher.Instance.AddEventListener(MieShiRefreshTowers_Event.EVENT_TYPE, RefreshTowers); EventDispatcher.Instance.AddEventListener(MieShiAddActvityTime_Event.EVENT_TYPE, UpdateMieshiActivtyTimeList); EventDispatcher.Instance.AddEventListener(MieShiUiToggle_Event.EVENT_TYPE, UIToggleClick); EventDispatcher.Instance.AddEventListener(MieShiRefreshBoss_Event.EVENT_TYPE, CreateFakeObj); if (mRemoveBind) { EventDispatcher.Instance.AddEventListener(CloseUiBindRemove.EVENT_TYPE, OnCloseUiBindRemove); mController = UIManager.Instance.GetController(UIConfig.MonsterSiegeUI); if (mController == null) { return; } MonsterModel = mController.GetDataModel("") as MonsterDataModel; MonsterModel.PropertyChanged += OnMonsterPropertyChangedEvent; Binding.SetBindDataSource(MonsterModel); Binding.SetBindDataSource(PlayerDataManager.Instance.PlayerDataModel); } mRemoveBind = true; var main = UIManager.Instance.MainUIFrame.GetComponent <MainScreenFrame>(); RefreshBtnState(); //报名时间 // MonsterDataModel ad = DataModel.CurMonsterFuben.activity; if (MieShiActivityTimeList.Count > 0) { DateTime time = MieShiActivityTimeList[0]; if (time != null) { DateTime tm = time.AddMinutes(-(double)(Table.GetMieShiPublic(1).CanApplyTime)); DateTime tm2 = time; BaoMingTime.text = string.Format("{0}--{1}", string.Format("{0:yyyy/MM/dd HH:mm}", tm), string.Format("{0:yyyy/MM/dd HH:mm}", tm2));// tm + "--" + tm2; } } int FubenId = MonsterModel.MonsterFubens[0].Fuben.FubenId; //MonsterModel.MonsterFubens[0].activity.NeedLevel = Table.GetScene(FubenId).LevelLimit; // MonsterModel.UseDiamond = Table.GetMieShiPublic(1).CostNum; // MonsterModel.UseProp = Table.GetMieShiPublic(1).ItemNum; #if !UNITY_EDITOR } catch (Exception ex) { Logger.Error(ex.ToString()); } #endif }
void ProcessOrder() { if (!inUse) { inUse = true; if (cmd.COMMANDE_QUANTITE == 0) { return; } int qte_cond; DateTime startProcessDate = end_date_last_order; using (var context = new PalaisDuBonbonEntities()) { qte_cond = (int)context.CONDITIONNEMENTs.Where(c => c.CONDITIONNEMENT_ID == cmd.CONDITIONNEMENT_ID).FirstOrDefault().CONDITIONNEMENT_QUANTITE_MAX; int quantite_bonbon = (int)(cmd.COMMANDE_QUANTITE * qte_cond); string bonbon_type = context.BONBONs.Where(c => c.BONBON_ID == cmd.BONBON_ID).FirstOrDefault().BONBON_TYPE; string bonbon_variante = context.BONBONs.Where(c => c.BONBON_ID == cmd.BONBON_ID).FirstOrDefault().VARIANTE.VARIANTE_NOM; int varianteIndex = variantes.IndexOf(bonbon_variante); if (last_used_candy_type != bonbon_type) { last_used_candy_type = bonbon_type; end_date_last_order = end_date_last_order.AddMinutes(this.changements_outil[varianteIndex]); } double tps_traitement = (float)quantite_bonbon / (float)(cadences[varianteIndex] / 60); // Tps en minutes end_date_last_order = end_date_last_order.AddMinutes(tps_traitement); cmd.COMMANDE_DATE_FABRICATION = end_date_last_order; processedOrders.Add(cmd); PERF_COMMANDES perfCmd = new PERF_COMMANDES(); perfCmd.COMMANDE_ID = cmd.COMMANDE_ID; perfCmd.TEMPS_FABRICATION_LOT = (decimal)end_date_last_order.Subtract(startProcessDate).TotalMinutes; perfCmd.BONBON_FABRIQUE_COUNT = quantite_bonbon; perfCmd.PERF_MACHINE_FABRICATION_ID = _id; savedPerformances.Add(perfCmd); /******************************* * DEBUG ********************************/ /* * dynamic jsonCmd = new System.Dynamic.ExpandoObject(); * jsonCmd.machine = _id; * jsonCmd.date = cmd.COMMANDE_DATE_FABRICATION; * jsonCmd.id = cmd.COMMANDE_ID; * jsonCmd.numCmd = cmd.COMMANDE_NUM_COMMANDE; * jsonCmd.qte_bonbon = quantite_bonbon; * jsonCmd.temps_fab_lot = tps_traitement; * * string jsonData = JsonConvert.SerializeObject(jsonCmd); * Utils.GenerateFabricationData_Test(jsonData); */ /******************************* * END DEBUG ********************************/ } inUse = false; } //Console.ReadLine(); }
private void clickyclicky_Tick(object sender, EventArgs e) { Stopwatch t = new Stopwatch(); t.Start(); double money = GameEngine.GetMoney(); ParsedHeroes ph = GameEngine.GetHeroes(); if (ph != null) { if (Properties.Settings.Default.useTaskList) { label14.Text = PlayerEngine.TryNextTask(ph, money); } else { label14.Text = "None, tasks turned off"; } StringBuilder sb = new StringBuilder(); if (ph.HeroStats != null) { foreach (HeroStats ss in ph.HeroStats) { sb.AppendLine(string.Format("{0}: Lvl {1} Upgrades {2}", ss.Hero.Name, ss.Level, Convert.ToString(ss.UpgradeBitfield, 2))); } } curHeroesTxt.Text = sb.ToString(); } else { curHeroesTxt.Text = string.Empty; } label9.Text = money.ToString(); if (Properties.Settings.Default.logging && DateTime.Now > TimeToNextLog) { Stopwatch imgsw = new Stopwatch(); imgsw.Start(); sw.WriteLine(string.Format("{0},{1}", DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"), money)); Rectangle playableArea = GameEngine.GetPlayableArea(); using (Bitmap bitmap = new Bitmap(playableArea.Width, playableArea.Height)) { using (Graphics g = Graphics.FromImage(bitmap)) { g.CopyFromScreen(new Point(playableArea.Left, playableArea.Top), Point.Empty, playableArea.Size); } bitmap.Save(string.Format("{0}\\{1}\\screenshots\\{2}.png", loggingDirectory, currentLoggingString, DateTime.Now.ToString("MM-dd-yyyy HH mm ss"))); } TimeToNextLog = TimeToNextLog.AddMinutes(1); imgsw.Stop(); label15.Text = string.Format("Image captured at {0} in {1} ms", DateTime.Now.ToString("hh:mm:ss"), imgsw.ElapsedMilliseconds); } else if (!Properties.Settings.Default.logging) { label15.Text = "Logging turned off"; } t.Stop(); label8.Text = string.Format("{0} ms", t.ElapsedMilliseconds); }
private DateTime?ProcessMonthlyPattern(RecurrenceRule recurrence, RecurrenceRuleException[] exceptions, int timeZoneShift) { try { log.LogFunctionStart(); var startDate = recurrence.StartDate ?? DateTime.UtcNow; var userLocalNow = DateTime.UtcNow.AddMinutes(timeZoneShift); var nextMonthlyBase = startDate.AddMinutes(timeZoneShift); DateTime?targetDate = nextMonthlyBase; var occurrenceCount = recurrence.OccurrenceCount; if (occurrenceCount == null) { if (targetDate < userLocalNow) { targetDate = targetDate?.AddDays((int)(userLocalNow - nextMonthlyBase).TotalDays); log.Log($"New target date after jump range: {targetDate}.", LogLevel.Debug); } } else { log.Log($"Remaining occurrences: {occurrenceCount}"); } var months = recurrence.Months.Split(','); var daysOfTheMonth = recurrence.DaysOfTheMonth.Split(','); var occurrences = recurrence.DayOccurrences?.Split(',') .Select(e => (RecurrenceRule.MonthlyDayOccurrenceEnum) RecurrenceRule.Enums.GetValue(RecurrenceRule.Fields.MonthlyDayOccurrence, e.ToTitleCase())).ToArray(); var daysOfWeek = recurrence.WeekDays?.Split(',') .Select(e => (RecurrenceRule.WeekDayEnum) RecurrenceRule.Enums.GetValue(RecurrenceRule.Fields.WeekDay, e.ToTitleCase())) .ToArray(); var isFound = false; var exceptionRetryCount = 5000; while (true) { if (occurrenceCount != null && occurrenceCount <= 0) { log.Log("Occurrences exceeded.", LogLevel.Warning); targetDate = null; break; } if (targetDate > recurrence.EndDate?.AddMinutes(timeZoneShift)) { log.Log("Generated date exceeds the end date.", LogLevel.Warning); targetDate = null; break; } // must be in the future, and month selected if (months.Contains(nextMonthlyBase.ToString("MMMM").ToLower()) && nextMonthlyBase >= userLocalNow) { switch (recurrence.MonthlyPattern) { case RecurrenceRule.MonthlyPatternEnum.SpecificDays: if (daysOfTheMonth.Contains(nextMonthlyBase.Day.ToString())) { isFound = true; } break; case RecurrenceRule.MonthlyPatternEnum.DayOccurrence: if (daysOfWeek == null && occurrences != null) { if (occurrences.Contains(RecurrenceRule.MonthlyDayOccurrenceEnum.Last)) { isFound = nextMonthlyBase.Day == DateTime.DaysInMonth(nextMonthlyBase.Year, nextMonthlyBase.Month); } } for (var j = 0; j < daysOfWeek?.Length && !isFound; j++) { for (var k = 0; k < occurrences?.Length && !isFound; k++) { var isLastOccurrence = occurrences[j] == RecurrenceRule.MonthlyDayOccurrenceEnum.Last; var dateTimeDayOfWeek = GetDayOfWeek(daysOfWeek[j]); var occurrenceDate = DateTimeHelpers.GetDayOccurrenceOfMonth(nextMonthlyBase, dateTimeDayOfWeek, (int)occurrences[j], isLastOccurrence); if (occurrenceDate != null && occurrenceDate == nextMonthlyBase) { isFound = true; } } } break; default: throw new ArgumentOutOfRangeException("MonthlyPattern", $"{recurrence.MonthlyPattern} : {(int) recurrence.MonthlyPattern}", "Pattern value not recognised."); } } if (isFound) { // must not be excluded if (!IsExcluded(nextMonthlyBase, exceptions)) { targetDate = nextMonthlyBase; log.Log("Found!", LogLevel.Debug); break; } // too many exclusion retries could lead to an infinite loop if (--exceptionRetryCount <= 0) { throw new InvalidPluginExecutionException("Couldn't find a target date." + " Please relax the exclusion rules."); } } occurrenceCount--; isFound = false; nextMonthlyBase = nextMonthlyBase.AddDays(1); } log.Log($"Target date: {targetDate}"); return(targetDate?.AddMinutes(-timeZoneShift)); } catch (Exception ex) { log.Log(ex); throw; } finally { log.LogFunctionEnd(); } }
/// <summary> /// Get the time. /// </summary> protected override void ProcessRecord() { DateTime dateToUse = DateTime.Now; int offset; // use passed date object if specified if (_dateSpecified) { if (FromUnixTime.IsPresent) { dateToUse = DateTimeOffset.FromUnixTimeSeconds(Date.Ticks).UtcDateTime; } else { dateToUse = Date; } } // use passed year if specified if (_yearSpecified) { offset = Year - dateToUse.Year; dateToUse = dateToUse.AddYears(offset); } // use passed month if specified if (_monthSpecified) { offset = Month - dateToUse.Month; dateToUse = dateToUse.AddMonths(offset); } // use passed day if specified if (_daySpecified) { offset = Day - dateToUse.Day; dateToUse = dateToUse.AddDays(offset); } // use passed hour if specified if (_hourSpecified) { offset = Hour - dateToUse.Hour; dateToUse = dateToUse.AddHours(offset); } // use passed minute if specified if (_minuteSpecified) { offset = Minute - dateToUse.Minute; dateToUse = dateToUse.AddMinutes(offset); } // use passed second if specified if (_secondSpecified) { offset = Second - dateToUse.Second; dateToUse = dateToUse.AddSeconds(offset); } // use passed millisecond if specified if (_millisecondSpecified) { offset = Millisecond - dateToUse.Millisecond; dateToUse = dateToUse.AddMilliseconds(offset); dateToUse = dateToUse.Subtract(TimeSpan.FromTicks(dateToUse.Ticks % 10000)); } if (AsUTC) { dateToUse = dateToUse.ToUniversalTime(); } if (UFormat != null) { // format according to UFormat string WriteObject(UFormatDateString(dateToUse)); } else if (Format != null) { // format according to Format string // Special case built-in primitives: FileDate, FileDateTime. // These are the ISO 8601 "basic" formats, dropping dashes and colons // so that they can be used in file names if (string.Equals("FileDate", Format, StringComparison.OrdinalIgnoreCase)) { Format = "yyyyMMdd"; } else if (string.Equals("FileDateUniversal", Format, StringComparison.OrdinalIgnoreCase)) { dateToUse = dateToUse.ToUniversalTime(); Format = "yyyyMMddZ"; } else if (string.Equals("FileDateTime", Format, StringComparison.OrdinalIgnoreCase)) { Format = "yyyyMMddTHHmmssffff"; } else if (string.Equals("FileDateTimeUniversal", Format, StringComparison.OrdinalIgnoreCase)) { dateToUse = dateToUse.ToUniversalTime(); Format = "yyyyMMddTHHmmssffffZ"; } WriteObject(dateToUse.ToString(Format, CultureInfo.CurrentCulture)); } else { // output DateTime object wrapped in an PSObject with DisplayHint attached PSObject outputObj = new PSObject(dateToUse); PSNoteProperty note = new PSNoteProperty("DisplayHint", DisplayHint); outputObj.Properties.Add(note); WriteObject(outputObj); } }
public void Mailing() { while (mailingBreak != false) { DateTime now = DateTime.Now; Console.WriteLine("sending email"); Console.WriteLine(now + " " + nextEmail); m_dbConnection.Open(); string sql = "select * from public_datas order by ID desc"; SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection); SQLiteDataReader reader = command.ExecuteReader(); while (reader.Read()) { try { var mail = new MailMessage(); var SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress(_textBox_login.Text + "@gmail.com"); mail.To.Add(reader["email"].ToString()); string message = _textBox_MailText.Text; message = Regex.Replace(message, "NAME", reader["name"].ToString()); //Console.WriteLine(message); message = Regex.Replace(message, "ID", reader["id"].ToString()); //Console.WriteLine(message); message = Regex.Replace(message, "PHONE", reader["phone"].ToString()); //Console.WriteLine(message); message = Regex.Replace(message, "DATE", DateTime.Now.ToString()); string subject = _textBox_Subject.Text; subject = Regex.Replace(subject, "NAME", reader["name"].ToString()); subject = Regex.Replace(subject, "ID", reader["id"].ToString()); subject = Regex.Replace(subject, "PHONE", reader["phone"].ToString()); subject = Regex.Replace(subject, "DATE", DateTime.Now.ToString()); mail.Subject = subject; mail.Body = message; if (_textLabel_path.Text != "path") { Attachment atc = new Attachment(_textLabel_path.Text); mail.Attachments.Add(atc); } SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential(_textBox_login.Text, _textBox_password.Text); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } m_dbConnection.Close(); nextEmail = now; nextEmail = nextEmail.AddMinutes(double.Parse(_textBox_Time.Text)); Console.WriteLine(now + " " + nextEmail); while (nextEmail >= now) { now = DateTime.Now; } } }
public static object Answer(string[] inputs) { List <(DateTime TimeStamp, string Information)> guards_records = new List <(DateTime TimeStamp, string Information)>(); foreach (var timestamp in inputs) { string ts_str = timestamp.Substring(1, 16); string infos = timestamp.Substring(19, timestamp.Length - 19); DateTime ts = DateTime.ParseExact(ts_str, "yyyy-MM-dd HH:mm", System.Globalization.CultureInfo.InvariantCulture); guards_records.Add((ts, infos)); } guards_records = guards_records.OrderBy(x => x.TimeStamp).ToList(); int guard = 0; DateTime asleepStart = new DateTime(); Dictionary <int, List <DateTime> > SleepyGuards = new Dictionary <int, List <DateTime> >(); foreach (var(TimeStamp, Information) in guards_records) { if (IsWakingUp(Information)) { TimeSpan span = TimeStamp.Subtract(asleepStart); for (int i = 0; i < span.TotalMinutes; i++) { if (SleepyGuards.ContainsKey(guard)) { SleepyGuards[guard].Add(asleepStart.AddMinutes(i)); } else { SleepyGuards.Add(guard, new List <DateTime>() { asleepStart.AddMinutes(i) }); } } continue; } if (IsFallingAsleep(Information)) { asleepStart = TimeStamp; continue; } if (IsBeginningShift(Information)) { guard = GetGuardID(Information); continue; } } var sleepiestGuard = SleepyGuards.OrderByDescending(i => i.Value.Count()).FirstOrDefault(); var sleepiestGuardGrouped = sleepiestGuard.Value.GroupBy(x => x.Minute).ToList() .OrderByDescending(x => x.Count()) .FirstOrDefault(); var partTwoAnswer = PartTwo(SleepyGuards); return($"Part 1 : Guard #{sleepiestGuard.Key} likes to sleep at {sleepiestGuardGrouped.Key} min " + $": {sleepiestGuard.Key} x {sleepiestGuardGrouped.Key} = {sleepiestGuard.Key * sleepiestGuardGrouped.Key} \n{partTwoAnswer}"); }
public ActionResult Search() { //Server Side Parameter int start = Convert.ToInt32(Request["start"]); int length = Convert.ToInt32(Request["length"]); string sortColumnName = Request["columns[" + Request["order[0][column]"] + "][name]"]; string sortDirection = Request["order[0][dir]"]; string departid = Session["departID"].ToString(); string documentary_id = Request["documentary_id"]; string type = Request["type"]; string department = Request["department"]; string reason = Request["reason"]; string dateStart = Request["dateStart"]; string dateEnd = Request["dateEnd"]; string status = Request["status"]; QuangHanhManufacturingEntities DBContext = new QuangHanhManufacturingEntities(); List <DocumentaryDB> incidents; string query = "SELECT docu.*, docu.[out/in_come] as out_in_come, depa.department_name FROM Documentary docu inner join Department depa on docu.department_id_to = depa.department_id" + " where docu.documentary_code IS NOT NULL AND docu.documentary_type != 8 AND docu.documentary_status != 3 AND docu.department_id_to = @departid AND "; if (!documentary_id.Equals("") || !type.Equals("0") || !department.Equals("") || !reason.Equals("") || !status.Equals("0") || !(dateStart.Equals("") || dateEnd.Equals(""))) { if (!dateStart.Equals("") && !dateEnd.Equals("")) { DateTime dtStart = DateTime.ParseExact(dateStart, "dd/MM/yyyy", CultureInfo.InvariantCulture); DateTime dtEnd = DateTime.ParseExact(dateEnd, "dd/MM/yyyy", CultureInfo.InvariantCulture); dtEnd = dtEnd.AddHours(23); dtEnd = dtEnd.AddMinutes(59); query += "docu.date_created BETWEEN '" + dtStart + "' AND '" + dtEnd + "' AND "; } if (!documentary_id.Equals("")) { query += "docu.documentary_code LIKE @documentary_id AND "; } if (!type.Equals("0")) { query += "docu.documentary_type LIKE @documentary_type AND "; } if (!department.Equals("")) { query += "depa.department_name LIKE @department_name AND "; } if (!reason.Equals("")) { query += "docu.reason LIKE @reason AND "; } if (!status.Equals("0")) { query += "docu.documentary_status = @documentary_status AND "; } } query = query.Substring(0, query.Length - 5); incidents = DBContext.Database.SqlQuery <DocumentaryDB>(query, new SqlParameter("departid", departid), new SqlParameter("documentary_id", '%' + documentary_id + '%'), new SqlParameter("documentary_type", '%' + type + '%'), new SqlParameter("department_name", '%' + department + '%'), new SqlParameter("reason", '%' + reason + '%'), new SqlParameter("documentary_status", status) ).ToList(); int totalrows = incidents.Count; int totalrowsafterfiltering = incidents.Count; //sorting incidents = incidents.OrderBy(sortColumnName + " " + sortDirection).ToList <DocumentaryDB>(); //paging incidents = incidents.Skip(start).Take(length).ToList <DocumentaryDB>(); foreach (DocumentaryDB item in incidents) { item.linkIdCode = new LinkIdCode(); switch (item.documentary_type) { case 1: item.stringtype = "Sửa chữa"; item.linkIdCode.link = "sua-chua"; break; case 2: item.stringtype = "Bảo dưỡng"; item.linkIdCode.link = "bao-duong"; break; case 3: item.stringtype = "Điều động"; item.linkIdCode.link = "dieu-dong"; break; case 4: item.stringtype = "Thu hồi"; item.linkIdCode.link = "thu-hoi"; break; case 5: item.stringtype = "Thanh lý"; item.linkIdCode.link = "thanh-ly"; break; case 6: item.stringtype = "Trung đại tu"; item.linkIdCode.link = "trung-dai-tu"; break; case 7: item.stringtype = "Điều chỉnh"; item.linkIdCode.link = "cai-tien"; break; } switch (item.documentary_status) { case 1: item.stringstatus = "Đang xử lý"; break; case 2: item.stringstatus = "Đã xử lý chưa nghiệm thu"; break; case 3: item.stringstatus = "Đã nghiệm thu"; break; } item.stringdate = item.date_created.ToString("dd/MM/yyyy"); item.linkIdCode.code = item.documentary_code; item.linkIdCode.id = item.documentary_id; } return(Json(new { success = true, data = incidents, draw = Request["draw"], recordsTotal = totalrows, recordsFiltered = totalrowsafterfiltering }, JsonRequestBehavior.AllowGet)); }
public static void Method() { IQuery <User> q = context.Query <User>(); var space = new char[] { ' ' }; DateTime startTime = DateTime.Now; DateTime endTime = DateTime.Now.AddDays(1); q.Select(a => new { Id = a.Id, String_Length = (int?)a.Name.Length, //LEN([Users].[Name]) Substring = a.Name.Substring(0), //SUBSTRING([Users].[Name],0 + 1,LEN([Users].[Name])) Substring1 = a.Name.Substring(1), //SUBSTRING([Users].[Name],1 + 1,LEN([Users].[Name])) Substring1_2 = a.Name.Substring(1, 2), //SUBSTRING([Users].[Name],1 + 1,2) ToLower = a.Name.ToLower(), //LOWER([Users].[Name]) ToUpper = a.Name.ToUpper(), //UPPER([Users].[Name]) IsNullOrEmpty = string.IsNullOrEmpty(a.Name), //too long Contains = (bool?)a.Name.Contains("s"), // Trim = a.Name.Trim(), //RTRIM(LTRIM([Users].[Name])) TrimStart = a.Name.TrimStart(space), //LTRIM([Users].[Name]) TrimEnd = a.Name.TrimEnd(space), //RTRIM([Users].[Name]) StartsWith = (bool?)a.Name.StartsWith("s"), // EndsWith = (bool?)a.Name.EndsWith("s"), // DiffYears = DbFunctions.DiffYears(startTime, endTime), //DATEDIFF(YEAR,@P_0,@P_1) DiffMonths = DbFunctions.DiffMonths(startTime, endTime), //DATEDIFF(MONTH,@P_0,@P_1) DiffDays = DbFunctions.DiffDays(startTime, endTime), //DATEDIFF(DAY,@P_0,@P_1) DiffHours = DbFunctions.DiffHours(startTime, endTime), //DATEDIFF(HOUR,@P_0,@P_1) DiffMinutes = DbFunctions.DiffMinutes(startTime, endTime), //DATEDIFF(MINUTE,@P_0,@P_1) DiffSeconds = DbFunctions.DiffSeconds(startTime, endTime), //DATEDIFF(SECOND,@P_0,@P_1) DiffMilliseconds = DbFunctions.DiffMilliseconds(startTime, endTime), //DATEDIFF(MILLISECOND,@P_0,@P_1) //DiffMicroseconds = DbFunctions.DiffMicroseconds(startTime, endTime),//DATEDIFF(MICROSECOND,@P_0,@P_1) Exception /* No longer support method 'DateTime.Subtract(DateTime d)', instead of using 'DbFunctions.DiffXX' */ //SubtractTotalDays = endTime.Subtract(startTime).TotalDays,//CAST(DATEDIFF(DAY,@P_0,@P_1) //SubtractTotalHours = endTime.Subtract(startTime).TotalHours,//CAST(DATEDIFF(HOUR,@P_0,@P_1) //SubtractTotalMinutes = endTime.Subtract(startTime).TotalMinutes,//CAST(DATEDIFF(MINUTE,@P_0,@P_1) //SubtractTotalSeconds = endTime.Subtract(startTime).TotalSeconds,//CAST(DATEDIFF(SECOND,@P_0,@P_1) //SubtractTotalMilliseconds = endTime.Subtract(startTime).TotalMilliseconds,//CAST(DATEDIFF(MILLISECOND,@P_0,@P_1) AddYears = startTime.AddYears(1), //DATEADD(YEAR,1,@P_0) AddMonths = startTime.AddMonths(1), //DATEADD(MONTH,1,@P_0) AddDays = startTime.AddDays(1), //DATEADD(DAY,1,@P_0) AddHours = startTime.AddHours(1), //DATEADD(HOUR,1,@P_0) AddMinutes = startTime.AddMinutes(2), //DATEADD(MINUTE,2,@P_0) AddSeconds = startTime.AddSeconds(120), //DATEADD(SECOND,120,@P_0) AddMilliseconds = startTime.AddMilliseconds(20000), //DATEADD(MILLISECOND,20000,@P_0) Now = DateTime.Now, //GETDATE() UtcNow = DateTime.UtcNow, //GETUTCDATE() Today = DateTime.Today, //CAST(GETDATE() AS DATE) Date = DateTime.Now.Date, //CAST(GETDATE() AS DATE) Year = DateTime.Now.Year, //DATEPART(YEAR,GETDATE()) Month = DateTime.Now.Month, //DATEPART(MONTH,GETDATE()) Day = DateTime.Now.Day, //DATEPART(DAY,GETDATE()) Hour = DateTime.Now.Hour, //DATEPART(HOUR,GETDATE()) Minute = DateTime.Now.Minute, //DATEPART(MINUTE,GETDATE()) Second = DateTime.Now.Second, //DATEPART(SECOND,GETDATE()) Millisecond = DateTime.Now.Millisecond, //DATEPART(MILLISECOND,GETDATE()) DayOfWeek = DateTime.Now.DayOfWeek, //(DATEPART(WEEKDAY,GETDATE()) - 1) Int_Parse = int.Parse("1"), //CAST(N'1' AS INT) Int16_Parse = Int16.Parse("11"), //CAST(N'11' AS SMALLINT) Long_Parse = long.Parse("2"), //CAST(N'2' AS BIGINT) Double_Parse = double.Parse("3"), //CAST(N'3' AS FLOAT) Float_Parse = float.Parse("4"), //CAST(N'4' AS REAL) //Decimal_Parse = decimal.Parse("5"),//CAST(N'5' AS DECIMAL) ps: 'Decimal.Parse(string s)' is not supported now,because we don't know the precision and scale information. Guid_Parse = Guid.Parse("D544BC4C-739E-4CD3-A3D3-7BF803FCE179"), //CAST(N'D544BC4C-739E-4CD3-A3D3-7BF803FCE179' AS UNIQUEIDENTIFIER) AS [Guid_Parse] Bool_Parse = bool.Parse("1"), //CASE WHEN CAST(N'1' AS BIT) = CAST(1 AS BIT) THEN CAST(1 AS BIT) WHEN NOT (CAST(N'1' AS BIT) = CAST(1 AS BIT)) THEN CAST(0 AS BIT) ELSE NULL END AS [Bool_Parse] DateTime_Parse = DateTime.Parse("1992-1-16"), //CAST(N'1992-1-16' AS DATETIME) AS [DateTime_Parse] B = a.Age == null ? false : a.Age > 1, }).ToList(); ConsoleHelper.WriteLineAndReadKey(); }
static DateTime Before(DateTime t) { return(t.AddMinutes(-1)); }
static DateTime After(DateTime t) { return(t.AddMinutes(1)); }
private DateTime?ProcessEveryMinutePattern(RecurrenceRule recurrence, RecurrenceRuleException[] exceptions, int timeZoneShift) { try { log.LogFunctionStart(); var startDate = recurrence.StartDate ?? DateTime.UtcNow; DateTime?targetDate = startDate; var spanSinceStart = (int)(DateTime.UtcNow - startDate).TotalMinutes; var occurrenceCount = recurrence.OccurrenceCount; if (targetDate < DateTime.UtcNow) { if (occurrenceCount != null) { occurrenceCount -= spanSinceStart / recurrence.MinuteFrequency + 1; log.Log($"Remaining occurrences: {occurrenceCount}"); } targetDate = targetDate?.AddMinutes(spanSinceStart - (spanSinceStart % recurrence.MinuteFrequency ?? 1)); log.Log($"New target date after jump range: {targetDate}.", LogLevel.Debug); } var exceptionRetryCount = 500000; while (true) { if (occurrenceCount != null && occurrenceCount <= 0) { log.Log("Occurrences exceeded.", LogLevel.Warning); targetDate = null; break; } if (targetDate > recurrence.EndDate) { log.Log("Generated date exceeds the end date.", LogLevel.Warning); targetDate = null; break; } targetDate = targetDate.Value.AddMinutes(recurrence.MinuteFrequency ?? 1); // must be in the future if (targetDate >= DateTime.UtcNow) { // not excluded if (IsExcluded(targetDate.Value, exceptions, timeZoneShift)) { // too many exclusion retries could lead to an infinite loop if (--exceptionRetryCount <= 0) { throw new InvalidPluginExecutionException("Couldn't find a target date." + " Please relax the exclusion rules."); } continue; } break; } occurrenceCount--; } log.Log($"Target date: {targetDate}"); return(targetDate); } catch (Exception ex) { log.Log(ex); throw; } finally { log.LogFunctionEnd(); } }
async static Task <int> ProcessMetricAsync(IAzure subApi, ISubscription subscription, IResourceGroup group, IGenericResource res, IMetricDefinition metric) { int m = 0; DateTime? last = null; MetricLastDate record = null; lock (_ctx) { record = _ctx.MetricLastDates.Where(d => d.Key == metric.Id).SingleOrDefault(); } last = record?.LastDate; try { await _sem.WaitAsync(); var from = last?.AddMinutes(1.0) ?? DateTime.UtcNow.RoundMinutes().AddHours(-1.0); var to = DateTime.UtcNow.RoundMinutes().AddMinutes(10.0); var maxDataToGet = TimeSpan.FromHours(2.0); if (to - from > maxDataToGet) { to = from + maxDataToGet; } if (metric.Inner.IsDimensionRequired == true) { var dims = metric.Inner.Dimensions; // can ignore.. return(0); } var data = await metric.DefineQuery() .StartingFrom(from) .EndsBefore(to) // as much as possible .WithAggregation("Average,Minimum,Maximum,Count,Total") .WithResultType(ResultType.Data) .WithInterval(TimeSpan.FromMinutes(1)) .ExecuteAsync(); if (data.Metrics.Count != 1 || data.Metrics[0].Timeseries.Count != 1) { return(0); } /* * Console.WriteLine($"query from {from} to {to}: {data.Metrics[0].Timeseries[0].Data.Count()} results"); * Console.WriteLine($" min: {data.Metrics[0].Timeseries[0].Data.Min(d => d.Minimum)}"); * Console.WriteLine($" max: {data.Metrics[0].Timeseries[0].Data.Max(d => d.Maximum)}"); * Console.WriteLine($" avg: {data.Metrics[0].Timeseries[0].Data.Average(d => d.Average)}"); */ var dubiousCutoffUtc = DateTime.UtcNow.AddMinutes(-30.0); var pts = data.Metrics[0].Timeseries[0].Data // from future to past .OrderByDescending(d => d.TimeStamp) // skip anything with no data yet .SkipWhile(d => d.TimeStamp > dubiousCutoffUtc && (d.Average ?? 0) == 0 && (d.Maximum ?? 0) == 0 && (d.Minimum ?? 0) == 0 && (d.Total ?? 0) == 0 && ( (d.Count ?? 0) == 0 || d.TimeStamp > dubiousCutoffUtc ) ) // and the first one with data (probably the current slice) .Skip(1); /* * if (pts.Any()) * Console.WriteLine($"actual data points: {pts.Count()}, from {pts.Min(p => p.TimeStamp)} to {pts.Max(p => p.TimeStamp)}"); * else * Console.WriteLine($"all data points dismissed"); */ if (pts.Any()) { lock (_logger) { foreach (var pt in pts.Reverse()) { var entry = new Dictionary <string, object>(13) { { "@timestamp", pt.TimeStamp.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFZ") }, { "lib", "Saffron" }, { "type", "cloud" }, { "cloud", "Azure" }, { "sub", subscription.DisplayName }, { "group", group.Name }, { "resource", new Dictionary <string, object>(3) { { "name", res.Name }, { "type", res.Type }, { "tags", res.Tags } } }, { "metric", new Dictionary <string, object>(2) { { "name", metric.Name.Value }, { "unit", metric.Unit } } }, }; if (pt.Average != null) { entry["avg"] = pt.Average; } if (pt.Count != null) { entry["num"] = pt.Count; } if (pt.Maximum != null) { entry["max"] = pt.Maximum; } if (pt.Minimum != null) { entry["min"] = pt.Minimum; } if (pt.Total != null) { entry["sum"] = pt.Total; } _logger.LogAsJson(entry); m++; } } lock (_ctx) { if (record == null) { record = new MetricLastDate { Key = metric.Id }; _ctx.MetricLastDates.Add(record); } record.LastDate = pts.First().TimeStamp; _ctx.SaveChanges(); numStats++; long ageMs = (long)(DateTime.UtcNow - record.LastDate).TotalMilliseconds; totalAgeMs += ageMs; if (ageMs > oldestAgeMs) { oldestAgeMs = ageMs; } } } } catch (ErrorResponseException ex) { // ignored //Console.WriteLine($"Error reading {metric.Name.LocalizedValue} from {res.Name} ({res.Type}): {ex.Message} - {ex.Body.Code} {ex.Body.Message}"); } catch (HttpRequestException ex) { Console.WriteLine($"HTTP error reading {metric.Name.LocalizedValue} from {res.Name} ({res.Type}): {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"Error reading {metric.Name.LocalizedValue} from {res.Name} ({res.Type}): {ex.Message}"); } finally { _sem.Release(); } return(m); }
private DateTime?ProcessWeeklyPattern(RecurrenceRule recurrence, RecurrenceRuleException[] exceptions, int timeZoneShift) { try { log.LogFunctionStart(); var startDate = recurrence.StartDate ?? DateTime.UtcNow; var userLocalNow = DateTime.UtcNow.AddMinutes(timeZoneShift); var nextWeeklyBase = startDate.AddMinutes(timeZoneShift); DateTime?targetDate = nextWeeklyBase; var spanSinceStart = (int)((userLocalNow - nextWeeklyBase).TotalDays / 7); var occurrenceCount = recurrence.OccurrenceCount; if (targetDate < userLocalNow) { if (occurrenceCount != null) { occurrenceCount -= spanSinceStart / recurrence.WeeklyFrequency + 1; log.Log($"Remaining occurrences: {occurrenceCount}"); } targetDate = targetDate?.AddDays((spanSinceStart - (spanSinceStart % recurrence.WeeklyFrequency ?? 1)) * 7); log.Log($"New target date after jump range: {targetDate}.", LogLevel.Debug); } var weeklyDays = recurrence.WeekDays.Split(','); var isFound = false; var exceptionRetryCount = 5000; while (!isFound) { if (occurrenceCount != null && occurrenceCount <= 0) { log.Log("Occurrences exceeded.", LogLevel.Warning); targetDate = null; break; } if (targetDate > recurrence.EndDate?.AddMinutes(timeZoneShift)) { log.Log("Generated date exceeds the end date.", LogLevel.Warning); targetDate = null; break; } for (var i = 0; i <= 7; i++) { var nextDay = nextWeeklyBase.AddDays(i); if (weeklyDays.Contains(nextDay.ToString("dddd").ToLower())) { // must be in the future if (nextDay >= userLocalNow) { // not excluded if (IsExcluded(nextDay, exceptions)) { // too many exclusion retries could lead to an infinite loop if (--exceptionRetryCount <= 0) { throw new InvalidPluginExecutionException("Couldn't find a target date." + " Please relax the exclusion rules."); } continue; } } else { occurrenceCount--; continue; } targetDate = nextDay; isFound = true; log.Log("Found!", LogLevel.Debug); break; } } nextWeeklyBase = nextWeeklyBase.AddDays(7 * (recurrence.WeeklyFrequency ?? 1)); } log.Log($"Target date: {targetDate}"); return(targetDate?.AddMinutes(-timeZoneShift)); } catch (Exception ex) { log.Log(ex); throw; } finally { log.LogFunctionEnd(); } }
private void OnCheck(object sender, ElapsedEventArgs e) { IEstateModule mod = m_scene.RequestModuleInterface <IEstateModule>(); if (AllowDisableScripts && m_statsReporter.LastReportedSimFPS < BaseRateFramesPerSecond * (PercentToBeginShutDownOfServices / 100) && m_statsReporter.LastReportedSimFPS != 0) { //Less than the percent to start shutting things down... Lets kill some stuff if (mod != null) { mod.SetSceneCoreDebug(false, m_scene.RegionInfo.RegionSettings.DisableCollisions, m_scene.RegionInfo.RegionSettings.DisablePhysics); } //These are opposite of what you want the value to be... go figure DisabledScriptStartTime = DateTime.Now; } if (m_scene.RegionInfo.RegionSettings.DisableScripts && AllowDisableScripts && SimZeroFPSStartTime != DateTime.MinValue && //This makes sure we don't screw up the setting if the user disabled physics manually SimZeroFPSStartTime.AddSeconds(TimeAfterToReenableScripts) > DateTime.Now) { DisabledScriptStartTime = DateTime.MinValue; if (mod != null) { mod.SetSceneCoreDebug(true, m_scene.RegionInfo.RegionSettings.DisableCollisions, m_scene.RegionInfo.RegionSettings.DisablePhysics); } //These are opposite of what you want the value to be... go figure } if (m_statsReporter.LastReportedSimFPS == 0 && KillSimOnZeroFPS) { if (SimZeroFPSStartTime == DateTime.MinValue) { SimZeroFPSStartTime = DateTime.Now; } if (SimZeroFPSStartTime.AddMinutes(MinutesBeforeZeroFPSKills) > SimZeroFPSStartTime) { MainConsole.Instance.RunCommand("shutdown"); } } else if (SimZeroFPSStartTime != DateTime.MinValue) { SimZeroFPSStartTime = DateTime.MinValue; } float[] stats = m_scene.RequestModuleInterface <IMonitorModule>().GetRegionStats(m_scene); if (stats[2] < BaseRateFramesPerSecond * (PercentToBeginShutDownOfServices / 100) && stats[2] != 0 && AllowDisablePhysics && !m_scene.RegionInfo.RegionSettings.DisablePhysics) //Don't redisable physics again, physics will be frozen at the last FPS { DisabledPhysicsStartTime = DateTime.Now; if (mod != null) { mod.SetSceneCoreDebug(m_scene.RegionInfo.RegionSettings.DisableScripts, m_scene.RegionInfo.RegionSettings.DisableCollisions, false); } //These are opposite of what you want the value to be... go figure } if (m_scene.RegionInfo.RegionSettings.DisablePhysics && AllowDisablePhysics && DisabledPhysicsStartTime != DateTime.MinValue && //This makes sure we don't screw up the setting if the user disabled physics manually DisabledPhysicsStartTime.AddSeconds(TimeAfterToReenablePhysics) > DateTime.Now) { DisabledPhysicsStartTime = DateTime.MinValue; if (mod != null) { mod.SetSceneCoreDebug(m_scene.RegionInfo.RegionSettings.DisableScripts, m_scene.RegionInfo.RegionSettings.DisableCollisions, true); } //These are opposite of what you want the value to be... go figure } }
public FormsAuthenticationTicket (string name, bool isPersistent, int timeout) { this.version = 1; this.name = name; this.issue_date = DateTime.Now; this.persistent = isPersistent; if (persistent) expiration = issue_date.AddYears (50); else expiration = issue_date.AddMinutes ((double) timeout); this.user_data = ""; this.cookie_path = "/"; }
static void Main(string[] args) { // Here program opens file containing last run time and checks how many minutes elapsed since last run. // Program than is going to collect orders that were placed since the last check. time_in_minutes = checklastrun(); // Infinite loop for program to check orders and migrate them from dinar to insert while (true) { // Debugging and testing purposes Console.WriteLine("Start check " + DateTime.Now); // getting needed data from Dinar Dictionary <string, Dictionary <string, List <string> > > pozycje = getListPozycje(); Dictionary <string, string> LinkiZamowienieKlient = PolaczZBazaLinkZamowienieKlient(); Dictionary <string, Dictionary <string, string> > ZamowienieDane = PolaczZBazaSatZamowienieDane(); Dictionary <string, Dictionary <string, string> > KlientAdres = PolaczZBazaSatZamowienieKlientAdres(); Dictionary <string, Dictionary <string, string> > KlientDane = PolaczZBazaSatZamowienieKlientDane(); Dictionary <string, Dictionary <string, string> > KlientFirma = PolaczZBazaSatZamowienieKlientDaneFirmy(); string NIP = default(string); string nazwa_firma = default(string); string uwagi = default(string); string dostawa = default(string); string source = default(string); string kosztDostawy = default(string); string platnosc = default(string); Dictionary <string, string> Firma = new Dictionary <string, string>(); Dictionary <string, string> Adres = new Dictionary <string, string>(); Dictionary <string, string> Dane = new Dictionary <string, string>(); Dictionary <string, List <string> > Pozycje = new Dictionary <string, List <string> >(); // Loops through the order variables and gathers data from all tables foreach (KeyValuePair <string, Dictionary <string, List <string> > > entry in pozycje) { Pozycje = entry.Value; Console.WriteLine(entry.Key); foreach (KeyValuePair <string, List <string> > entryin in entry.Value) { Console.WriteLine("\t" + entryin.Key); foreach (var val in entryin.Value) { Console.WriteLine("\t\t" + val); } } try { string KlientId = LinkiZamowienieKlient[entry.Key.ToString()]; Console.WriteLine("\tAdres:"); Adres = KlientAdres[entry.Key]; foreach (KeyValuePair <string, string> adres in KlientAdres[entry.Key]) { Console.WriteLine("\t\t" + adres.Key + ": " + adres.Value); } }catch (Exception ex) { Console.WriteLine("Adres exception"); Console.WriteLine(ex); } Console.WriteLine("\n"); try { Console.WriteLine("\tDane:"); Dane = KlientDane[entry.Key]; foreach (KeyValuePair <string, string> dane in KlientDane[entry.Key]) { Console.WriteLine("\t\t" + dane.Key + ": " + dane.Value); } } catch (Exception ex) { Console.WriteLine(ex); } if (KlientFirma.ContainsKey(entry.Key) && KlientFirma[entry.Key].ContainsKey("NIP"))// && KlientFirma[entry.Key]["NIP"] != "" && KlientFirma[entry.Key]["NIP"].Length > 5) { if (KlientFirma[entry.Key]["NIP"] != "") { try { Console.WriteLine("\n"); Firma = KlientFirma[entry.Key]; NIP = KlientFirma[entry.Key]["NIP"].Replace("-", "").Replace(" ", ""); nazwa_firma = KlientFirma[entry.Key]["firma_nazwa"]; } catch (Exception ex) { Console.WriteLine(ex); } try { Console.WriteLine("\tFirma Dane:"); foreach (KeyValuePair <string, string> dane in KlientFirma[entry.Key]) { Console.WriteLine("\t\t" + dane.Key + ": " + dane.Value); } } catch (Exception ex) { Console.WriteLine("Firma exception"); Console.WriteLine(ex); } } } else { } Console.WriteLine("\tUwagi: "); if (ZamowienieDane.ContainsKey(entry.Key)) { Console.WriteLine("no uwagi"); if (ZamowienieDane[entry.Key].ContainsKey("uwagi")) { Console.WriteLine(ZamowienieDane[entry.Key]["uwagi"]); uwagi = ZamowienieDane[entry.Key]["uwagi"]; } if (ZamowienieDane[entry.Key].ContainsKey("dostawa")) { dostawa = ZamowienieDane[entry.Key]["dostawa"]; } if (ZamowienieDane[entry.Key].ContainsKey("koszt_przesylki")) { kosztDostawy = ZamowienieDane[entry.Key]["koszt_przesylki"]; } if (ZamowienieDane[entry.Key].ContainsKey("RecordSource")) { source = ZamowienieDane[entry.Key]["RecordSource"]; } if (ZamowienieDane[entry.Key].ContainsKey("platnosc")) { platnosc = ZamowienieDane[entry.Key]["platnosc"]; uwagi += "\n" + platnosc; } } // Console.WriteLine(ZamowienieDane[entry.Key]["uwagi"]); try { if (KlientAdres.Count > 0) { uwagi += "Źródło: " + getZamowienieSourceId(entry.Key); if (KlientFirma.ContainsKey(entry.Key) && KlientFirma[entry.Key]["NIP"] != "") { DodajZamowienie(Pozycje: Pozycje, Adres: Adres, Dane: Dane, uwagi: uwagi, NIP: NIP, firma_nazwa: nazwa_firma, Firma: Firma, dostawa: dostawa, kosztDostawy: kosztDostawy, source: source); } else { DodajZamowienie(Pozycje: Pozycje, Adres: Adres, Dane: Dane, uwagi: uwagi, dostawa: dostawa, kosztDostawy: kosztDostawy, source: source); } } }catch (Exception ex) { Console.WriteLine("Uwagi exception"); Console.WriteLine(ex); } } DateTime dateVal = DateTime.Now; Console.WriteLine(dateVal + " Następny sync o: " + dateVal.AddMinutes(15)); StreamWriter sw = new StreamWriter("lastsync.txt"); sw.WriteLine(dateVal); sw.Flush(); sw.Close(); time_in_minutes = "15"; //Console.WriteLine(time_in_minutes); Thread.Sleep(900000); } }
public async void UpdateChart(bool isSelectedChanged = false) { if (!IsSelected) { if (ForecastContainer != null) { ForecastContainer.Height = 0; } _animationPlayed = false; return; } if (!_initialized) { FindName(nameof(ForecastContainer)); ForecastContainer.Height = 0; ValueAxis.Minimum = 0; ValueAxis.Maximum = 100; ValueAxis.Interval = 10; SelectionComboBox.ItemsSource = ComboBoxValues; SelectionComboBox.SelectedItem = ComboBoxValues[0]; SelectionComboBox.SelectionChanged += (sender, args) => UpdateChart(); ForecastContainer.Loaded += (sender, args) => { if (!_containerDesiredHeight.HasValue) { _containerDesiredHeight = ForecastChart.DesiredSize.Height + SelectionComboBox.DesiredSize.Height; if (isSelectedChanged) { BeginSlideOutAnimation(); } } }; } BeginSlideOutAnimation(); var vm = ServiceLocator.Current.GetInstance <MainViewModel>(); if (!vm.InternetAvailable) { return; } var parkingLot = DataContext as ParkingLot; if (parkingLot != null && parkingLot.HasForecast) { if (_initialized) { ForecastChart.Series.Clear(); } var timeSpanSelection = SelectionComboBox.SelectedItem as ParkingLotForecastTimespanSelection; var timeSpan = timeSpanSelection?.TimeSpan; if (timeSpan.HasValue) { ForecastChart.Opacity = 0.2; LoadingProgressRing.Visibility = Visibility.Visible; await Task.Run(async() => { var api = ServiceLocator.Current.GetInstance <IParkenDdClient>(); var mainVm = ServiceLocator.Current.GetInstance <MainViewModel>(); var now = DateTime.Now; var startDate = _cachedForecastEndDate?.AddMinutes(30) ?? now; var endDate = now.Add(timeSpan.Value); if (endDate > startDate) { Forecast forecast; try { forecast = await api.GetForecastAsync(mainVm.SelectedCity.Id, parkingLot.Id, startDate, endDate); } catch (ApiException e) { ServiceLocator.Current.GetInstance <ExceptionService>().HandleApiExceptionForForecastData(e, mainVm.SelectedCity, parkingLot); return; } _cachedForecast.AddRange(forecast.Data.Select( item => new ParkingLotForecastDataPoint(item.Value, item.Key))); if (_cachedForecastEndDate.HasValue) { if (_cachedForecastEndDate.Value < endDate) { _cachedForecastEndDate = endDate; } } else { _cachedForecastEndDate = endDate; } } var points = _cachedForecast.Where(x => x.Time >= now && x.Time <= now.Add(timeSpan.Value)); DispatcherHelper.CheckBeginInvokeOnUI(() => { var series = new AreaSeries { ItemsSource = points, IndependentValuePath = "Time", DependentValuePath = "Value", Style = Application.Current.Resources["ParkingLotForecastChartAreaSeriesStyle"] as Style }; ForecastChart.Series.Add(series); ForecastChart.Opacity = 1; LoadingProgressRing.Visibility = Visibility.Collapsed; }); if (!_initialized) { ServiceLocator.Current.GetInstance <TrackingService>()? .TrackForecastRangeEvent(parkingLot, timeSpanSelection?.Mode); } _initialized = true; }); } } }
private static void S4U2Proxy(KRB_CRED kirbi, string targetUser, string targetSPN, string outfile, bool ptt, string domainController = "", string altService = "", KRB_CRED tgs = null, bool opsec = false) { Console.WriteLine("[*] Impersonating user '{0}' to target SPN '{1}'", targetUser, targetSPN); if (!String.IsNullOrEmpty(altService)) { string[] altSnames = altService.Split(','); if (altSnames.Length == 1) { Console.WriteLine("[*] Final ticket will be for the alternate service '{0}'", altService); } else { Console.WriteLine("[*] Final tickets will be for the alternate services '{0}'", altService); } } // extract out the info needed for the TGS-REQ/S4U2Proxy execution string userName = kirbi.enc_part.ticket_info[0].pname.name_string[0]; string domain = kirbi.enc_part.ticket_info[0].prealm; Ticket ticket = kirbi.tickets[0]; byte[] clientKey = kirbi.enc_part.ticket_info[0].key.keyvalue; Interop.KERB_ETYPE etype = (Interop.KERB_ETYPE)kirbi.enc_part.ticket_info[0].key.keytype; string dcIP = Networking.GetDCIP(domainController); if (String.IsNullOrEmpty(dcIP)) { return; } Console.WriteLine("[*] Building S4U2proxy request for service: '{0}'", targetSPN); TGS_REQ s4u2proxyReq = new TGS_REQ(!opsec); s4u2proxyReq.req_body.kdcOptions = s4u2proxyReq.req_body.kdcOptions | Interop.KdcOptions.CONSTRAINED_DELEGATION; s4u2proxyReq.req_body.realm = domain; string[] parts = targetSPN.Split('/'); string serverName = parts[parts.Length - 1]; s4u2proxyReq.req_body.sname.name_type = Interop.PRINCIPAL_TYPE.NT_SRV_INST; foreach (string part in parts) { s4u2proxyReq.req_body.sname.name_string.Add(part); } // supported encryption types s4u2proxyReq.req_body.etypes.Add(Interop.KERB_ETYPE.aes128_cts_hmac_sha1); s4u2proxyReq.req_body.etypes.Add(Interop.KERB_ETYPE.aes256_cts_hmac_sha1); s4u2proxyReq.req_body.etypes.Add(Interop.KERB_ETYPE.rc4_hmac); // add in the ticket from the S4U2self response s4u2proxyReq.req_body.additional_tickets.Add(tgs.tickets[0]); // needed for authenticator checksum byte[] cksum_Bytes = null; // the rest of the opsec changes if (opsec) { // remove renewableok and add canonicalize s4u2proxyReq.req_body.kdcOptions = s4u2proxyReq.req_body.kdcOptions & ~Interop.KdcOptions.RENEWABLEOK; s4u2proxyReq.req_body.kdcOptions = s4u2proxyReq.req_body.kdcOptions | Interop.KdcOptions.CANONICALIZE; // 15 minutes in the future like genuine requests DateTime till = DateTime.Now; till = till.AddMinutes(15); s4u2proxyReq.req_body.till = till; // extra etypes s4u2proxyReq.req_body.etypes.Add(Interop.KERB_ETYPE.rc4_hmac_exp); s4u2proxyReq.req_body.etypes.Add(Interop.KERB_ETYPE.old_exp); // get hostname and hostname of SPN string hostName = Dns.GetHostName().ToUpper(); string targetHostName; if (parts.Length > 1) { targetHostName = parts[1].Substring(0, parts[1].IndexOf('.')).ToUpper(); } else { targetHostName = hostName; } // create enc-authorization-data if target host is not the local machine if (hostName != targetHostName) { // authdata requires key and etype from tgs byte[] tgsKey = tgs.enc_part.ticket_info[0].key.keyvalue; Interop.KERB_ETYPE tgsEtype = (Interop.KERB_ETYPE)tgs.enc_part.ticket_info[0].key.keytype; ADIfRelevant ifrelevant = new ADIfRelevant(); ADRestrictionEntry restrictions = new ADRestrictionEntry(); ADKerbLocal kerbLocal = new ADKerbLocal(); ifrelevant.ADData.Add(restrictions); ifrelevant.ADData.Add(kerbLocal); AsnElt authDataSeq = ifrelevant.Encode(); authDataSeq = AsnElt.Make(AsnElt.SEQUENCE, authDataSeq); byte[] authorizationDataBytes = authDataSeq.Encode(); byte[] enc_authorization_data = Crypto.KerberosEncrypt(tgsEtype, Interop.KRB_KEY_USAGE_TGS_REQ_ENC_AUTHOIRZATION_DATA, tgsKey, authorizationDataBytes); s4u2proxyReq.req_body.enc_authorization_data = new EncryptedData((Int32)tgsEtype, enc_authorization_data); } // encode req_body for authenticator cksum AsnElt req_Body_ASN = s4u2proxyReq.req_body.Encode(); AsnElt req_Body_ASNSeq = AsnElt.Make(AsnElt.SEQUENCE, new[] { req_Body_ASN }); req_Body_ASNSeq = AsnElt.MakeImplicit(AsnElt.CONTEXT, 4, req_Body_ASNSeq); byte[] req_Body_Bytes = req_Body_ASNSeq.CopyValue(); cksum_Bytes = Crypto.KerberosChecksum(clientKey, req_Body_Bytes, Interop.KERB_CHECKSUM_ALGORITHM.KERB_CHECKSUM_RSA_MD5); } // moved to end so we can have the checksum in the authenticator PA_DATA padata = new PA_DATA(domain, userName, ticket, clientKey, etype, opsec, cksum_Bytes); s4u2proxyReq.padata.Add(padata); PA_DATA pac_options = new PA_DATA(false, false, false, true); s4u2proxyReq.padata.Add(pac_options); byte[] s4ubytes = s4u2proxyReq.Encode().Encode(); Console.WriteLine("[*] Sending S4U2proxy request"); byte[] response2 = Networking.SendBytes(dcIP, 88, s4ubytes); if (response2 == null) { return; } // decode the supplied bytes to an AsnElt object // false == ignore trailing garbage AsnElt responseAsn = AsnElt.Decode(response2, false); // check the response value int responseTag = responseAsn.TagValue; if (responseTag == (int)Interop.KERB_MESSAGE_TYPE.TGS_REP) { Console.WriteLine("[+] S4U2proxy success!"); // parse the response to an TGS-REP TGS_REP rep2 = new TGS_REP(responseAsn); // https://github.com/gentilkiwi/kekeo/blob/master/modules/asn1/kull_m_kerberos_asn1.h#L62 byte[] outBytes2 = Crypto.KerberosDecrypt(etype, 8, clientKey, rep2.enc_part.cipher); AsnElt ae2 = AsnElt.Decode(outBytes2, false); EncKDCRepPart encRepPart2 = new EncKDCRepPart(ae2.Sub[0]); if (!String.IsNullOrEmpty(altService)) { string[] altSnames = altService.Split(','); foreach (string altSname in altSnames) { // now build the final KRB-CRED structure with one or more alternate snames KRB_CRED cred = new KRB_CRED(); // since we want an alternate sname, first substitute it into the ticket structure rep2.ticket.sname.name_string[0] = altSname; // add the ticket cred.tickets.Add(rep2.ticket); // build the EncKrbCredPart/KrbCredInfo parts from the ticket and the data in the encRepPart KrbCredInfo info = new KrbCredInfo(); // [0] add in the session key info.key.keytype = encRepPart2.key.keytype; info.key.keyvalue = encRepPart2.key.keyvalue; // [1] prealm (domain) info.prealm = encRepPart2.realm; // [2] pname (user) info.pname.name_type = rep2.cname.name_type; info.pname.name_string = rep2.cname.name_string; // [3] flags info.flags = encRepPart2.flags; // [4] authtime (not required) // [5] starttime info.starttime = encRepPart2.starttime; // [6] endtime info.endtime = encRepPart2.endtime; // [7] renew-till info.renew_till = encRepPart2.renew_till; // [8] srealm info.srealm = encRepPart2.realm; // [9] sname info.sname.name_type = encRepPart2.sname.name_type; info.sname.name_string = encRepPart2.sname.name_string; // if we want an alternate sname, substitute it into the encrypted portion of the KRB_CRED Console.WriteLine("[*] Substituting alternative service name '{0}'", altSname); info.sname.name_string[0] = altSname; // add the ticket_info into the cred object cred.enc_part.ticket_info.Add(info); byte[] kirbiBytes = cred.Encode().Encode(); string kirbiString = Convert.ToBase64String(kirbiBytes); Console.WriteLine("[*] base64(ticket.kirbi) for SPN '{0}/{1}':\r\n", altSname, serverName); if (Rubeus.Program.wrapTickets) { // display the .kirbi base64, columns of 80 chararacters foreach (string line in Helpers.Split(kirbiString, 80)) { Console.WriteLine(" {0}", line); } } else { Console.WriteLine(" {0}", kirbiString); } if (!String.IsNullOrEmpty(outfile)) { string filename = $"{Helpers.GetBaseFromFilename(outfile)}_{altSname}-{serverName}{Helpers.GetExtensionFromFilename(outfile)}"; filename = Helpers.MakeValidFileName(filename); if (Helpers.WriteBytesToFile(filename, kirbiBytes)) { Console.WriteLine("\r\n[*] Ticket written to {0}\r\n", filename); } } if (ptt) { // pass-the-ticket -> import into LSASS LSA.ImportTicket(kirbiBytes, new LUID()); } } } else { // now build the final KRB-CRED structure, no alternate snames KRB_CRED cred = new KRB_CRED(); // if we want an alternate sname, first substitute it into the ticket structure if (!String.IsNullOrEmpty(altService)) { rep2.ticket.sname.name_string[0] = altService; } // add the ticket cred.tickets.Add(rep2.ticket); // build the EncKrbCredPart/KrbCredInfo parts from the ticket and the data in the encRepPart KrbCredInfo info = new KrbCredInfo(); // [0] add in the session key info.key.keytype = encRepPart2.key.keytype; info.key.keyvalue = encRepPart2.key.keyvalue; // [1] prealm (domain) info.prealm = encRepPart2.realm; // [2] pname (user) info.pname.name_type = rep2.cname.name_type; info.pname.name_string = rep2.cname.name_string; // [3] flags info.flags = encRepPart2.flags; // [4] authtime (not required) // [5] starttime info.starttime = encRepPart2.starttime; // [6] endtime info.endtime = encRepPart2.endtime; // [7] renew-till info.renew_till = encRepPart2.renew_till; // [8] srealm info.srealm = encRepPart2.realm; // [9] sname info.sname.name_type = encRepPart2.sname.name_type; info.sname.name_string = encRepPart2.sname.name_string; // add the ticket_info into the cred object cred.enc_part.ticket_info.Add(info); byte[] kirbiBytes = cred.Encode().Encode(); string kirbiString = Convert.ToBase64String(kirbiBytes); Console.WriteLine("[*] base64(ticket.kirbi) for SPN '{0}':\r\n", targetSPN); if (Rubeus.Program.wrapTickets) { // display the .kirbi base64, columns of 80 chararacters foreach (string line in Helpers.Split(kirbiString, 80)) { Console.WriteLine(" {0}", line); } } else { Console.WriteLine(" {0}", kirbiString); } if (!String.IsNullOrEmpty(outfile)) { string filename = $"{Helpers.GetBaseFromFilename(outfile)}_{targetSPN}{Helpers.GetExtensionFromFilename(outfile)}"; filename = Helpers.MakeValidFileName(filename); if (Helpers.WriteBytesToFile(filename, kirbiBytes)) { Console.WriteLine("\r\n[*] Ticket written to {0}\r\n", filename); } } if (ptt) { // pass-the-ticket -> import into LSASS LSA.ImportTicket(kirbiBytes, new LUID()); } } } else if (responseTag == (int)Interop.KERB_MESSAGE_TYPE.ERROR) { // parse the response to an KRB-ERROR KRB_ERROR error = new KRB_ERROR(responseAsn.Sub[0]); Console.WriteLine("\r\n[X] KRB-ERROR ({0}) : {1}\r\n", error.error_code, (Interop.KERBEROS_ERROR)error.error_code); } else { Console.WriteLine("\r\n[X] Unknown application tag: {0}", responseTag); } }
public async Task Arrange() { // Arrange _fixture = new CertificatePrintStatusUpdateHandlerTestsFixture() .WithCertificate(CertificateReference, CertificateStatus.Printed, PrintedAt, BatchNumber, PrintedAt.AddMinutes(-5)) .WithCertificateBatchLog(BatchNumber, CertificateReference, CertificateStatus.Printed, PrintedAt, null, PrintedAt.AddMinutes(5)) .WithBatchLog(BatchNumber); var request = new CertificatePrintStatusUpdateRequest { BatchNumber = BatchNumber, CertificateReference = CertificateReference, Status = CertificateStatus.Delivered, StatusAt = DeliveredAt }; // Act _response = await _fixture.Handle(request); }
private bool doRun(string runtime, DateTime lastRunTime) { bool bRet = false; int pos = 0; string literal = ""; int diff = 0; DateTime now = DateTime.Now; DateTime toRunTime; runtime = runtime.Replace(" ", ""); //get toRunTime int month, day, hour, min, sec; if (runtime.Substring(pos, 1).Equals("*")) { month = now.Month; pos++; } else { literal = runtime.Substring(pos, 2); month = literal.ToInt(); diff = 100000; pos += 2; } if (runtime.Substring(pos, 1).Equals("*")) { day = now.Day; pos++; } else { literal = runtime.Substring(pos, 2); day = literal.ToInt(); diff = diff == 0 ? 10000 : diff; pos += 2; } if (runtime.Substring(pos, 1).Equals("*")) { hour = now.Hour; pos++; } else { literal = runtime.Substring(pos, 2); hour = literal.ToInt(); diff = diff == 0 ? 1000 : diff; pos += 2; } if (runtime.Substring(pos, 1).Equals("*")) { min = now.Minute; pos++; } else { literal = runtime.Substring(pos, 2); min = literal.ToInt(); diff = diff == 0 ? 100 : diff; pos += 2; } if (runtime.Substring(pos, 1).Equals("*")) { sec = now.Second; diff = 1; pos++; } else { literal = runtime.Substring(pos, 2); sec = literal.ToInt(); diff = diff == 0 ? 10 : diff; pos += 2; } toRunTime = new DateTime(now.Year, month, day, hour, min, sec); if (lastRunTime == null) { lastRunTime = now.AddYears(-1); } TimeSpan span1 = toRunTime.Subtract(lastRunTime); //check if lastRunTime indicates that it already launched if (span1.TotalSeconds > 0) { DateTime prevRunTime; switch (diff) { case 100000: prevRunTime = toRunTime.AddYears(-1); break; case 10000: prevRunTime = toRunTime.AddMonths(-1); break; case 1000: prevRunTime = toRunTime.AddDays(-1); break; case 100: prevRunTime = toRunTime.AddHours(-1); break; case 10: prevRunTime = toRunTime.AddMinutes(-1); break; case 1: default: prevRunTime = toRunTime.AddSeconds(-1); break; } TimeSpan span2 = prevRunTime.Subtract(lastRunTime); if (span2.TotalSeconds <= 0) { bRet = true; } } return(bRet); }
public void Start() { var dateTime = new DateTime(); dateTime.AddMinutes(1); }
private static bool CheckSnipeConditions(ISession session) { if (session.SaveBallForByPassCatchFlee) { return(false); } //if (waitNextPokestop) return false; if (session.LoggedTime > DateTime.Now.AddMinutes(1)) { return(false); //only snipe after login 1 min. } if (snipeFailedCount >= 3) { return(false); } if (session.Stats.CatchThresholdExceeds(session)) { return(false); } if (inProgress || OutOffBallBlock > DateTime.Now) { return(false); } if (!session.LogicSettings.UseSnipeLimit) { return(true); } if (lastPrintMessageTime.AddMinutes(1) > DateTime.Now) { session.EventDispatcher.Send(new SnipeEvent { Message = session.Translation.GetTranslation(TranslationString.SniperCount, session.Stats.SnipeCount) }); } if (session.Stats.LastSnipeTime.AddMilliseconds(session.LogicSettings.MinDelayBetweenSnipes) > DateTime.Now) { return(false); } if (session.Stats.SnipeCount < session.LogicSettings.SnipeCountLimit) { return(true); } if ((DateTime.Now - session.Stats.LastSnipeTime).TotalSeconds > session.LogicSettings.SnipeRestSeconds) { session.Stats.SnipeCount = 0; } else { if (lastPrintMessageTime.AddMinutes(1) > DateTime.Now) { lastPrintMessageTime = DateTime.Now; session.EventDispatcher.Send(new SnipeEvent { Message = session.Translation.GetTranslation(TranslationString.SnipeExceeds) }); } return(false); } return(true); }
public void CanAddMinutesAcrossDstTransition() { var tz = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); var dt = new DateTime(2015, 3, 8, 1, 59, 0); var result = dt.AddMinutes(1, tz); var expected = new DateTimeOffset(2015, 3, 8, 3, 0, 0, TimeSpan.FromHours(-7)); Assert.Equal(expected, result); Assert.Equal(expected.Offset, result.Offset); }
public DateTime UpdateDateTime(DateTime dateTime) => dateTime.AddMinutes(-1);