/// <summary> /// Asserts that a <see cref="DateTimeOffset"/> occurs a specified amount of time before another <see cref="DateTimeOffset"/>. /// </summary> /// <param name="target"> /// The <see cref="DateTimeOffset"/> to compare the subject with. /// </param> /// <param name="because"> /// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not /// start with the word <i>because</i>, it is prepended to the message. /// </param> /// <param name="reasonArgs"> /// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders. /// </param> public AndConstraint<DateTimeOffsetAssertions> Before(DateTimeOffset target, string because = "", params object[] reasonArgs) { bool success = Execute.Assertion .ForCondition(subject.HasValue) .BecauseOf(because, reasonArgs) .FailWith("Expected date and/or time {0} to be " + predicate.DisplayText + " {1} before {2}{reason}, but found a <null> DateTime.", subject, timeSpan, target); if (success) { var actual = target.Subtract(subject.Value); if (!predicate.IsMatchedBy(actual, timeSpan)) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith( "Expected date and/or time {0} to be " + predicate.DisplayText + " {1} before {2}{reason}, but it differs {3}.", subject, timeSpan, target, actual); } } return new AndConstraint<DateTimeOffsetAssertions>(parentAssertions); }
public void AdvanceTo(DateTimeOffset when) { if (when < _now) throw new InvalidOperationException("You can't reverse time..."); Advance(when.Subtract(_now)); }
/// <summary> /// Implements the interface method by invoking the related delegate method. /// </summary> /// <param name="context"></param> /// <returns></returns> public override async Task ValidatePrincipal(CookieValidatePrincipalContext context) { IEnumerable <AuthenticationToken> tokens = context.Properties.GetTokens(); if (tokens == null || !tokens.Any()) { this.Logger.LogDebug("No tokens found in cookie properties. SaveTokens must be enabled for automatic token refresh."); return; } AuthenticationToken refreshToken = tokens.SingleOrDefault(t => t.Name == OpenIdConnectParameterNames.RefreshToken); if (refreshToken == null) { this.Logger.LogWarning("No refresh token found in cookie properties. A refresh token must be requested and SaveTokens must be enabled."); return; } AuthenticationToken expiresAt = tokens.SingleOrDefault(t => t.Name == "expires_at"); if (expiresAt == null) { this.Logger.LogWarning("No expires_at value found in cookie properties."); return; } DateTimeOffset dtExpires = DateTimeOffset.Parse(expiresAt.Value, CultureInfo.InvariantCulture); DateTimeOffset dtRefresh = dtExpires.Subtract(this.AutomaticTokenManagementOptions.RefreshBeforeExpiration); if (dtRefresh < this.SystemClock.UtcNow) { Boolean shouldRefresh = AutomaticTokenManagementCookieEvents.PendingRefreshTokenRequests.TryAdd(refreshToken.Value, true); if (shouldRefresh) { try { TokenResponse response = await this.TokenEndpointService.RefreshTokenAsync(refreshToken.Value); if (response.IsError) { this.Logger.LogWarning("Error refreshing token: {error}", response.Error); return; } context.Properties.UpdateTokenValue("access_token", response.AccessToken); context.Properties.UpdateTokenValue("refresh_token", response.RefreshToken); DateTime newExpiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(response.ExpiresIn); context.Properties.UpdateTokenValue("expires_at", newExpiresAt.ToString("o", CultureInfo.InvariantCulture)); await context.HttpContext.SignInAsync(context.Principal, context.Properties); } finally { AutomaticTokenManagementCookieEvents.PendingRefreshTokenRequests.TryRemove(refreshToken.Value, out _); } } } }
static void GenerateData(GenConfig config) { Queue <LogRecord> futureLogQ = new Queue <LogRecord>(); DateTimeOffset currentTime = DateTimeOffset.UtcNow; DateTimeOffset endTime = currentTime.AddHours(config.nDurationHours); int totalSession = 0; Random coin = new Random(); PlayerPool players = new PlayerPool(config.numPlayers); LocationPool locations = new LocationPool(config.cityFile); while (endTime.Subtract(currentTime) >= TimeSpan.Zero) { Session curSession = new Session(coin, players, locations); //start curSession.setEvent(Session.eventTypeList.gameStart, currentTime); LogRecord rec = new LogRecord(curSession); outputLog(rec, config); //reachLevel int seconds2Level = coin.Next(5, 20); curSession.setEvent(Session.eventTypeList.levelReached, currentTime.AddSeconds(seconds2Level)); rec = new LogRecord(curSession); futureLogQ.Enqueue(rec); //purchase int seconds2Purchase = coin.Next(2, 10); curSession.setEvent(Session.eventTypeList.itemPurchased, currentTime.AddSeconds(seconds2Purchase)); rec = new LogRecord(curSession); futureLogQ.Enqueue(rec); //end int seconds2End = Math.Max(seconds2Level, seconds2Purchase) + coin.Next(3, 7); curSession.setEvent(Session.eventTypeList.gameEnd, currentTime.AddSeconds(seconds2End)); rec = new LogRecord(curSession); futureLogQ.Enqueue(rec); //output those session end records that happened in the past not future while (futureLogQ.Count > 0) { LogRecord drec, prec; prec = (LogRecord)futureLogQ.Peek(); DateTimeOffset oldest = DateTimeOffset.Parse(prec.eventTime, null, System.Globalization.DateTimeStyles.AssumeUniversal); if (currentTime.Subtract(oldest) >= TimeSpan.Zero) { drec = (LogRecord)futureLogQ.Dequeue(); outputLog(drec, config); } else { break; } } System.Threading.Thread.Sleep(config.msPerSession); Console.WriteLine("Total:" + totalSession++ + ", In queue:" + futureLogQ.Count); currentTime = DateTimeOffset.UtcNow; } // while - within duration }
public async Task ScheduleNewMeeting(IRoom room, string title, DateTimeOffset startTime, DateTimeOffset endTime, bool inviteMe) { if (string.IsNullOrEmpty(_contextService.UserId)) { throw new ApplicationException("User required to create future meeting"); } var meetings = await GetUpcomingAppointmentsForRoom(room); var conflict = meetings.Where(i => !i.IsCancelled && !i.IsEndedEarly).FirstOrDefault(i => (i.Start <= startTime && startTime < i.End) || (i.Start < endTime && endTime <= i.End) || (startTime <= i.Start && i.Start < endTime) || (startTime < i.End && i.End <= endTime)); if (null != conflict) { throw new ApplicationException($"Conflicts with existing meeting"); } if (endTime.Subtract(startTime).TotalHours > 2) { throw new ApplicationException("Cannot create a meeting for more than 2 hours"); } var item = await _exchange.CreateEvent(room.RoomAddress, new CalendarEntry { Attendees = inviteMe ? new [] { new Attendee() { EmailAddress = new EmailAddress() { Address = _contextService.UserId } } } : new Attendee[0], Start = new DateTimeReference() { DateTime = startTime.ToUniversalTime().ToString("o"), TimeZone = "UTC" }, End = new DateTimeReference() { DateTime = endTime.ToUniversalTime().ToString("o"), TimeZone = "UTC" }, Subject = title ?? $"Scheduled via conference room management system by {_contextService.UserId}", Body = new BodyContent() { Content = $"Scheduled via conference room management system by {_contextService.UserId}", ContentType = "Text" }, Importance = Importance.Normal, ShowAs = ShowAs.Busy, Sensitivity = Sensitivity.Normal, }); // autostart if within the next 10 minutes var now = _dateTimeService.Now; if (startTime <= now.AddMinutes(10)) { _meetingRepository.StartMeeting(room.OrganizationId, item.Id); } await BroadcastUpdate(room); }
private DateTimeOffset getRandomDate() { DateTimeOffset start = DateTimeOffset.ParseExact("01/01/1900", "dd/MM/yyyy", null); DateTimeOffset end = DateTimeOffset.Now; start.AddMinutes(random.Next(0, end.Subtract(start).Minutes - 1)); return(start); }
public static bool Add <T>(this StackExchangeRedisCacheClient cacheClient, string key, T value, DateTimeOffset?expiresAt, TimeSpan?expiresIn, bool fireAndForget) { var numArray = cacheClient.Serializer.Serialize(value); expiresIn = expiresIn ?? expiresAt?.Subtract(DateTimeOffset.Now); return(cacheClient.Database.StringSet(key, numArray, expiresIn, When.Always, fireAndForget ? CommandFlags.FireAndForget : CommandFlags.None)); }
/// <summary> /// Adds the specified instance to the Redis database. /// </summary> /// <typeparam name="T">The type of the class to add to Redis</typeparam> /// <param name="key">The cache key.</param> /// <param name="value">The instance of T.</param> /// <param name="expiresAt">Expiration time.</param> /// <returns> /// True if the object has been added. Otherwise false /// </returns> public async Task <bool> AddAsync <T>(string key, T value, DateTimeOffset expiresAt) where T : class { var entryBytes = await serializer.SerializeAsync(value); var expiration = expiresAt.Subtract(DateTimeOffset.Now); return(await db.StringSetAsync(key, entryBytes, expiration)); }
/// <summary> /// Calculates the currently unix timestamp in millis since epoch. /// </summary> /// <returns>The Unix timstamp.</returns> internal static long GetTimestamp() { // TODO when not supporting net35 just use DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() DateTimeOffset epoch = new DateTimeOffset(1970, 01, 01, 00, 00, 00, TimeSpan.Zero); DateTimeOffset now = DateTimeOffset.UtcNow; return((long)now.Subtract(epoch).TotalMilliseconds); }
long getUnixTimeEnd(DateTimeOffset old) { //UNIXエポック時刻 DateTimeOffset dto = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); //oldのDateTimeOffsetからUNIXエポック時刻のDateTimeOffsetを引いて、その結果を秒数で表す return((long)old.Subtract(dto).TotalSeconds); }
public void Add(string key, object o, DateTimeOffset expiration, string dependsOnKey = null) { var timeSpan = expiration.Subtract(new DateTimeOffset(DateTime.Now)); var value = Newtonsoft.Json.JsonConvert.SerializeObject(o); _db.StringSet(key, value, timeSpan); }
/// <summary> /// 设置string键值 /// </summary> /// <typeparam name="T">值的类型</typeparam> /// <param name="key">key</param> /// <param name="value">值</param> /// <param name="expiresAt">过期时间</param> /// <returns>成功返回true</returns> public async Task <bool> StringSetAsync <T>(string key, T value, DateTimeOffset expiresAt) { var objBytes = await Serializer.SerializeAsync(value); var expiration = expiresAt.Subtract(DateTimeOffset.Now); return(await Database.StringSetAsync(SetPrefix(key), objBytes, expiration)); }
public override void OnNext(T value) { DateTimeOffset now = parent.scheduler.Now; TimeSpan interval = now.Subtract(lastTime); lastTime = now; observer.OnNext(new TimeInterval <T>(value, interval)); }
private bool IsDateNotRecent(DateTimeOffset dateTime) { DateTimeOffset now = this.dateTimeBroker.GetCurrentDateTime(); int oneMinute = 1; TimeSpan difference = now.Subtract(dateTime); return(Math.Abs(difference.TotalMinutes) > oneMinute); }
public bool Add <T>(string key, T value, DateTimeOffset expiresAt) { string serializedObject = JsonConvert.SerializeObject(value); var expiration = expiresAt.Subtract(DateTimeOffset.Now); var db = GetDb(); return(db.StringSet(key, serializedObject, expiration)); }
public static void IsWithin(DateTimeOffset expected, DateTimeOffset actual, long timeDiff) { Assert.IsNotNull(expected); Assert.IsNotNull(actual); var actualDiff = expected.Subtract(actual).TotalMilliseconds; Assert.IsTrue(Math.Abs(actualDiff) < timeDiff); }
public static DateTimeOffset UtcToCest(this DateTimeOffset original) { var cetTime = TimeZoneInfo.ConvertTime(original, CstZone); return(original .Subtract(cetTime.Offset) .ToOffset(cetTime.Offset)); }
private static string BuildExpiresOn(TimeSpan timeToLive) { DateTimeOffset expiresOn = DateTimeOffset.UtcNow.Add(timeToLive); TimeSpan secondsFromBaseTime = expiresOn.Subtract(SharedAccessSignatureConstants.s_epochTime); long seconds = Convert.ToInt64(secondsFromBaseTime.TotalSeconds, CultureInfo.InvariantCulture); return(Convert.ToString(seconds, CultureInfo.InvariantCulture)); }
public static void TestTimeSpan() { DateTimeOffset dt = new DateTimeOffset(new DateTime(2012, 6, 18, 10, 5, 1, 0)); TimeSpan ts = dt.TimeOfDay; DateTimeOffset newDate = dt.Subtract(ts); Assert.Equal(new DateTimeOffset(new DateTime(2012, 6, 18, 0, 0, 0, 0)).Ticks, newDate.Ticks); Assert.Equal(dt.Ticks, newDate.Add(ts).Ticks); }
public async Task Daily() { EmbedBuilder eb = new EmbedBuilder(); //Create player folder if it doesn't exist Directory.CreateDirectory(Setup.PlayerSavesPath + "/" + Context.User.Id); //Loaded data BinaryMoneyNormal entry = new BinaryMoneyNormal(0, 0, Context.Message.Timestamp.Ticks, Context.Message.Timestamp.Offset.Ticks); //Load bool fileExists = MoneyNormal.Load(Setup.PlayerSavesPath + "/" + Context.User.Id + "/" + "Money", ref entry); DateTimeOffset lastLoadedTimestamp = new DateTimeOffset(entry.DateTimeTicks, new TimeSpan(entry.DateTimeOffsetTicks)); DateTimeOffset nextUpdateTimestamp = lastLoadedTimestamp.AddHours(Setup.HoursTillReset); TimeSpan nextUpdateTime = nextUpdateTimestamp.Subtract(Context.Message.Timestamp); //Check if time threshold has passed to execute again if (nextUpdateTime.TotalHours <= 0 || !fileExists) { //Modify entry.CurrentBonusDay += 1; if (entry.CurrentBonusDay > 5) { entry.CurrentBonusDay = 1; } entry.Money += Setup.DailyBaseWorth * entry.CurrentBonusDay; entry.DateTimeTicks = Context.Message.Timestamp.Ticks; entry.DateTimeOffsetTicks = Context.Message.Timestamp.Offset.Ticks; //Save MoneyNormal.Save(Setup.PlayerSavesPath + "/" + Context.User.Id + "/" + "Money", entry); string[] streakSymbols = new string[5]; streakSymbols[0] = "🇨 "; streakSymbols[1] = "🇭 "; streakSymbols[2] = "🇮 "; streakSymbols[3] = "🇲 "; streakSymbols[4] = "🇵 "; string streak = ""; for (int i = 0; i < entry.CurrentBonusDay; i++) { streak += streakSymbols[i]; } eb.Title = "**💰 Daily! " + Tools.GetNickname(Context, Context.User.Id) + "**"; string text = "You got **$" + Setup.DailyBaseWorth * entry.CurrentBonusDay + "** daily credits!" + "\n" + "**Streak: " + streak + "**"; eb.WithDescription(text); eb.WithColor(Color.Gold); } else { eb.Title = "**🚫 " + Tools.GetNickname(Context, Context.User.Id) + " please wait " + (nextUpdateTime.Hours) + " hours, " + (nextUpdateTime.Minutes) + " minutes, and " + (nextUpdateTime.Seconds) + " seconds for daily! 💰**"; eb.WithColor(Color.Red); } await Context.Channel.SendMessageAsync("", false, eb.Build()); await Context.Message.DeleteAsync(); }
private static Image DrawStripHeader(DateTimeOffset now, TheFieldInfo pInfo) { bool drawRightToLeft = (TheCommonUtils.CBool(pInfo?.PropBagGetValue("DrawRightToLeft"))); int pixelWidth = 78 * TheCommonUtils.CInt(pInfo?.PropBagGetValue("TileWidth")); if (pixelWidth == 0) { pixelWidth = 78; } int Hours = TheCommonUtils.CInt(pInfo?.PropBagGetValue("Hours")); if (Hours == 0) { Hours = 1; } int pixelHeight = 39; Bitmap bmp = new Bitmap(pixelWidth, pixelHeight, PixelFormat.Format32bppArgb); DateTimeOffset start = now.Subtract(new TimeSpan(drawRightToLeft ? Hours : 0, now.Minute, now.Second)); TimeSpan step = new TimeSpan(0, Hours * 5, 0); double scaling = (float)pixelWidth / (Hours * 60 * 60); using (Graphics g = Graphics.FromImage(bmp)) { Font drawFont = new Font("Arial", 10); SolidBrush drawBrush = new SolidBrush(Color.Black); // Color.FromArgb(179, 255, 255, 255)); DateTimeOffset currentTime = start; g.TextRenderingHint = TextRenderingHint.AntiAlias; for (int i = 0; i <= 12; i++) { string pattern = CultureInfo.CurrentCulture.DateTimeFormat.MonthDayPattern; pattern = pattern.Replace("MMMM", "MMM"); string timeValue = currentTime.DateTime.ToString(pattern) + "\n"; timeValue += currentTime.DateTime.ToShortTimeString(); SizeF size = g.MeasureString(timeValue, drawFont); double x = now.Subtract(currentTime).TotalSeconds *scaling - size.Width / 2; if (drawRightToLeft) { x = pixelWidth - x; } if (x >= -3 && x <= pixelWidth - size.Width + 3) { g.DrawString(timeValue, drawFont, drawBrush, new PointF((float)x, pixelHeight - size.Height - 5)); } if (drawRightToLeft) { currentTime = currentTime.Add(step); } else { currentTime = currentTime.Subtract(step); } } } return(bmp); }
public async Task OnValidateIdentity(CookieValidateIdentityContext cookieValidateIdentityContext) { DateTimeOffset currentDateUtc = DateTimeOffset.UtcNow; if (cookieValidateIdentityContext.Options?.SystemClock != null) { currentDateUtc = cookieValidateIdentityContext.Options.SystemClock.UtcNow; } DateTimeOffset?authenticationTickedIssuedDataUtc = cookieValidateIdentityContext.Properties.IssuedUtc; bool authenticationTickedIsValid = !authenticationTickedIssuedDataUtc.HasValue; if (authenticationTickedIssuedDataUtc.HasValue) { authenticationTickedIsValid = currentDateUtc.Subtract(authenticationTickedIssuedDataUtc.Value) > this.ValidationInterval; } if (authenticationTickedIsValid) { var userId = this.identityProvider.GetUserId(cookieValidateIdentityContext.Identity); if (userId != null) { bool userIdentityIsValid = false; using (this.dbContextScopeFactory.CreateReadOnly()) { User user = await this.userRepository.FindByIdAsync(userId); if (user != null) { string securityStamp = cookieValidateIdentityContext.Identity.FindFirst("AspNet.Identity.SecurityStamp")?.Value; if (securityStamp == user.SecurityStamp) { var userRoles = await this.userRepository.GetRolesAsync(user); var userClaims = await this.userRepository.GetClaimsAsync(user); var claimsIdentity = await this.claimsIdentityFactory.CreateAsync(user, AuthenticationType.ApplicationCookie, userRoles, userClaims); // Add custom user claims here. cookieValidateIdentityContext.Properties.IssuedUtc = new DateTimeOffset?(); cookieValidateIdentityContext.Properties.ExpiresUtc = new DateTimeOffset?(); cookieValidateIdentityContext.OwinContext.Authentication.SignIn(cookieValidateIdentityContext.Properties, claimsIdentity); userIdentityIsValid = true; } } } if (!userIdentityIsValid) { cookieValidateIdentityContext.RejectIdentity(); cookieValidateIdentityContext.OwinContext.Authentication.SignOut(cookieValidateIdentityContext.Options.AuthenticationType); } } } }
/// <summary> /// メッセージを通知する /// </summary> /// <param name="tileId">アプリタイルのID</param> /// <param name="title">タイトル</param> /// <param name="body">本文</param> /// <param name="timestamp">日時</param> /// <param name="flags">フラグ</param> /// <returns>Task</returns> public Task SendMessageAsync(Guid tileId, string title, string body, DateTimeOffset timestamp, MessageFlags flags = MessageFlags.None) { var nativeFlag = flags == MessageFlags.None ? Native.Notifications.MessageFlags.None : Native.Notifications.MessageFlags.ShowDialog; var timespan = timestamp.Subtract(new DateTime(2001, 1, 1, 0, 0, 0)).TotalSeconds; return(Native.Notifications.BandNotificationManagerExtensions.SendMessageTaskAsync( this.manager, new NSUuid(tileId.ToString("D")), title, body, NSDate.FromTimeIntervalSinceReferenceDate(timespan), nativeFlag)); }
public static string GetDifferenceTillNow(this DateTimeOffset?datetimeoffset) { DateTimeOffset?creationTime = datetimeoffset; DateTimeOffset rightnow = DateTimeOffset.Now; DateTimeOffset somewhen = creationTime ?? rightnow; TimeSpan difference = rightnow.Subtract(somewhen); return(difference.Days.ToString() + " days & " + difference.Hours.ToString() + " hours ago"); }
private async Task <bool> MeetsRecurrenceCriteria(ScheduleTask reminderTask, DateTimeOffset now) { var lastRun = await _scheduleTaskRepo.GetLastRunTime(reminderTask.ScheduleTaskId); var taskHasNeverRan = !lastRun.HasValue; var hasNotRanWithin_N_Weeks = !taskHasNeverRan && now.Subtract(lastRun.Value).TotalDays > (reminderTask.RecurEveryNWeeks * 7); return(taskHasNeverRan || hasNotRanWithin_N_Weeks); }
static void Main(string[] args) { // read JSON directly from a file using (StreamReader file = File.OpenText(@"./burrow_lag.json")) using (JsonTextReader reader = new JsonTextReader(file)) { JObject o = (JObject)JToken.ReadFrom(reader); long startOffset = (long)o.SelectToken("status.partitions[0].start.offset"); long startTimestamp = (long)o.SelectToken("status.partitions[0].start.timestamp"); long endOffset = (long)o.SelectToken("status.partitions[0].end.offset"); long endTimestamp = (long)o.SelectToken("status.partitions[0].end.timestamp"); DateTimeOffset startDateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(startTimestamp); DateTimeOffset endDateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(endTimestamp); TimeSpan starTimeDifference = startDateTimeOffset.Subtract(appStart); TimeSpan endTimeDifference = endDateTimeOffset.Subtract(appStart); long startRate = DataRate(startOffset, starTimeDifference); long endRate = DataRate(endOffset, endTimeDifference); var filePath = @"./performancedata.json"; if (!File.Exists(filePath)) { try { // Create the file CreateFile(filePath); } catch (Exception e) { Console.WriteLine(e.ToString()); } } // Read existing json data var jsonData = System.IO.File.ReadAllText(filePath); // De-serialize to object or create new list var dataList = JsonConvert.DeserializeObject <List <PerformanceData> >(jsonData) ?? new List <PerformanceData>(); // Add any new employees dataList.Add(new PerformanceData() { StartTime = appStart.ToString("MM/dd/yyyy H:mm:ss tt"), EndTime = endDateTimeOffset.ToString("MM/dd/yyyy H:mm:ss tt"), Difference = (long)endTimeDifference.TotalSeconds, StartOffset = startOffset, EndOffset = endOffset, StartRate = startRate, EndRate = endRate }); // Update json data string jsonData = JsonConvert.SerializeObject(dataList, Formatting.Indented); System.IO.File.WriteAllText(filePath, jsonData); } }
public void AdvanceTo(DateTimeOffset when) { if (when < _now) { throw new InvalidOperationException("You can't reverse time..."); } Advance(when.Subtract(_now)); }
/// <summary> /// Runs a test on two times, with a tolerance of 200ms. /// </summary> /// <param name="expectedTime"></param> /// <param name="actualTime"></param> /// <param name="millisecondTolerance"></param> private void TimeTest(DateTimeOffset expectedTime, DateTimeOffset actualTime, int millisecondTolerance = 200) { var tolerance = new TimeSpan(0, 0, 0, 0, millisecondTolerance); var expectedLowTime = expectedTime.Subtract(tolerance); var expectedHighTime = expectedTime.Add(tolerance); Assert.True(actualTime > expectedLowTime, $"The actual time {actualTime} is less than the expected time {expectedLowTime}."); Assert.True(actualTime < expectedHighTime, $"The actual time {actualTime} is greater than the expected time {expectedHighTime}."); }
// from calc_res.cpp public void UpdateDeclaredPuMass(DateTimeOffset meas_date, ref double decl_pu_mass, bool INCCParity) { double ref_days; double pu_days; double pu238_iso_mass; double pu239_iso_mass; double pu240_iso_mass; double pu241_iso_mass; double pu242_iso_mass; double pu238_decay_fract_pu_to_now; double pu239_decay_fract_pu_to_now; double pu240_decay_fract_pu_to_now; double pu241_decay_fract_pu_to_now; double pu242_decay_fract_pu_to_now; double cur_mass_pu238; double cur_mass_pu239; double cur_mass_pu240; double cur_mass_pu241; double cur_mass_pu242; if (decl_pu_mass > 0) { /* update declared Pu mass based upon original isotopic composition */ // INCC literally truncates the fractional date here, so it is always at time of the full day // gen_date_time_str_to_seconds (&seconds, results.meas_date, "00:00:00", GEN_DTF_IAEA); // ref_days = (double) seconds / SECONDS_PER_DAY; // if (INCCParity) { pu_days = (pu_date.Date.Subtract(ZeroIAEATime)).TotalDays; ref_days = (meas_date.Date.Subtract(ZeroIAEATime)).TotalDays; } else { pu_days = (pu_date.Subtract(ZeroIAEATime)).TotalDays; ref_days = (meas_date.Subtract(ZeroIAEATime)).TotalDays; } pu238_iso_mass = this[Isotope.pu238].v * (decl_pu_mass) / 100.0; pu239_iso_mass = this[Isotope.pu239].v * (decl_pu_mass) / 100.0; pu240_iso_mass = this[Isotope.pu240].v * (decl_pu_mass) / 100.0; pu241_iso_mass = this[Isotope.pu241].v * (decl_pu_mass) / 100.0; pu242_iso_mass = this[Isotope.pu242].v * (decl_pu_mass) / 100.0; pu238_decay_fract_pu_to_now = Math.Exp((-LN2 / PU238HL) * (ref_days - pu_days)); pu239_decay_fract_pu_to_now = Math.Exp((-LN2 / PU239HL) * (ref_days - pu_days)); pu240_decay_fract_pu_to_now = Math.Exp((-LN2 / PU240HL) * (ref_days - pu_days)); pu241_decay_fract_pu_to_now = Math.Exp((-LN2 / PU241HL) * (ref_days - pu_days)); pu242_decay_fract_pu_to_now = Math.Exp((-LN2 / PU242HL) * (ref_days - pu_days)); cur_mass_pu238 = pu238_iso_mass * pu238_decay_fract_pu_to_now; cur_mass_pu239 = pu239_iso_mass * pu239_decay_fract_pu_to_now; cur_mass_pu240 = pu240_iso_mass * pu240_decay_fract_pu_to_now; cur_mass_pu241 = pu241_iso_mass * pu241_decay_fract_pu_to_now; cur_mass_pu242 = pu242_iso_mass * pu242_decay_fract_pu_to_now; decl_pu_mass = cur_mass_pu238 + cur_mass_pu239 + cur_mass_pu240 + cur_mass_pu241 + cur_mass_pu242; } }
public async Task <ActionResult <List <ShiftAvailabilityDto> > > GetDistributeScheduleForLocation(int locationId, DateTimeOffset start, DateTimeOffset end, bool includeWorkSection) { if (start >= end) { return(BadRequest("Start date was on or after end date.")); } if (end.Subtract(start).TotalDays > 30) { return(BadRequest("End date and start date are more than 30 days apart.")); } if (!PermissionDataFiltersExtensions.HasAccessToLocation(User, Db, locationId)) { return(Forbid()); } if (!User.HasPermission(Permission.ViewDutyRoster)) { includeWorkSection = false; } var shiftAvailability = await ShiftService.GetShiftAvailability(start, end, locationId : locationId); var shiftsWithDuties = await DistributeScheduleService.GetDistributeSchedule(shiftAvailability, includeWorkSection, start, end, locationId); if (!User.HasPermission(Permission.ViewAllFutureShifts) || !User.HasPermission(Permission.ViewDutyRosterInFuture)) { var location = await Db.Location.AsNoTracking().FirstOrDefaultAsync(l => l.Id == locationId); var timezone = location.Timezone; var currentDate = DateTimeOffset.UtcNow.ConvertToTimezone(timezone).DateOnly(); if (!User.HasPermission(Permission.ViewAllFutureShifts)) { var shiftRestrictionDays = int.Parse(Configuration.GetNonEmptyValue("ViewShiftRestrictionDays")); var endDateShift = currentDate.TranslateDateForDaylightSavings(timezone, shiftRestrictionDays + 1); foreach (var sa in shiftsWithDuties) { sa.Conflicts = sa.Conflicts.WhereToList(c => c.Start < endDateShift); } } if (!User.HasPermission(Permission.ViewDutyRosterInFuture)) { var dutyRestrictionHours = float.Parse(Configuration.GetNonEmptyValue("ViewDutyRosterRestrictionHours")); var endDateDuties = currentDate.TranslateDateForDaylightSavings(timezone, hoursToShift: dutyRestrictionHours); foreach (var sa in shiftsWithDuties) { sa.Conflicts.WhereToList(c => c.Start > endDateDuties) .ForEach(c => c.WorkSection = null); } } } return(Ok(shiftsWithDuties.Adapt <List <ShiftAvailabilityDto> >())); }
public override void OnNext(T value) { DateTimeOffset now = parent.scheduler.Now; TimeSpan span = now.Subtract(lastTime); lastTime = now; base.observer.OnNext(new UniRx.TimeInterval <T>(value, span)); }
//return how much time passed from plane takeoff relative to date private TimeSpan ReturnTakeoffTimePassedFromDate(string date, FlightPlan flightPlan) { DateTimeOffset dateTimeFromUser = DateTimeOffset.Parse(date); DateTimeOffset dateTimeOfTakeoff = flightPlan.initial_Location.Date_Time; //substract flight initial time from the date. give the space between them. if its minus,means date is before plane takeoff. TimeSpan timeBetweenDates = dateTimeFromUser.Subtract(dateTimeOfTakeoff); return(timeBetweenDates); }
public DateTimeOffset ScheduleNextTime(DateTimeOffset currentTime, JobExecutionRecord lastExecution) { var next = currentTime.Subtract(new TimeSpan(0, 0, 0, currentTime.Second, currentTime.Millisecond)); while (next < currentTime) { next = next.Add(_seconds.Seconds()); } return next; }
static void Main(string[] args) { //var offset = DateTimeOffset.Now; //Debug.WriteLine(offset); //Debug.WriteLine(DateTimeOffset.UtcNow); //String s = "10/1/2014 6:17 PM"; //DateTime dt = DateTime.ParseExact(s, "MM/dd/yyyy h:mm tt", CultureInfo.InvariantCulture); //DateTimeOffset dto = new DateTimeOffset(dt); DateTimeOffset dto1 = new DateTimeOffset(); dto1 = DateTimeOffset.Now; dto1 = dto1.AddHours(2); dto1 = dto1.AddMinutes(30); Debug.WriteLine(DateTimeOffset.Now); Debug.WriteLine(dto1); TimeSpan diff = dto1.Subtract(DateTimeOffset.Now); Debug.WriteLine(diff); Debug.WriteLine(diff.TotalHours); Debug.WriteLine(diff.TotalSeconds); var diffsec = (DateTimeOffset.Now - dto1).TotalSeconds; Debug.WriteLine(diffsec); //dtoff.Value.ToLocalTime().ToString("dddd, MMM dd yyyy HH:mm", new CultureInfo("en-US")); //Debug.WriteLine(dto1); //Debug.WriteLine(dto2); //Debug.WriteLine(DateTimeOffset.Now); //Debug.WriteLine(dto1 - DateTimeOffset.Now); //Debug.WriteLine(DateTimeOffset.Now - dto1); //Debug.WriteLine(dto1.CompareTo(DateTimeOffset.Now)); //Debug.WriteLine(DateTimeOffset.Now.CompareTo(dto1)); //Debug.WriteLine(" "); //Debug.WriteLine(dto1.Hour); double temp = -26; double res = 0; for (int i = 0; i < 40; i++) { temp++; res = 0.5 - (temp * 0.1); Debug.WriteLine("Temp: " + temp + " Result: " + res); } //Debug.WriteLine(s); //Debug.WriteLine(dt.ToString()); //Debug.WriteLine(dt.ToUniversalTime().ToString()); //Debug.WriteLine(dto.ToString()); }
public Task DeliverAfter(NimbusMessage message, DateTimeOffset deliveryTime) { // Deliberately not awaiting this task. We want it to run in the background. Task.Run(async () => { var delay = deliveryTime.Subtract(_clock.UtcNow); if (delay < TimeSpan.Zero) delay = TimeSpan.Zero; await Task.Delay(delay); AsyncBlockingCollection<NimbusMessage> queue; if (!_messageStore.TryGetExistingMessageQueue(message.DeliverTo, out queue)) return; await queue.Add(message); }).ConfigureAwaitFalse(); return Task.Delay(0); }
public Task DeliverAfter(NimbusMessage message, DateTimeOffset deliveryTime) { _logger.Debug("Enqueuing {MessageId} for re-delivery at {DeliverAt}", message.MessageId, deliveryTime); // Deliberately not awaiting this task. We want it to run in the background. Task.Run(async () => { var delay = deliveryTime.Subtract(_clock.UtcNow); if (delay < TimeSpan.Zero) delay = TimeSpan.Zero; await Task.Delay(delay); _logger.Debug("Re-delivering {MessageId} (attempt {Attempt})", message.MessageId, message.DeliveryAttempts.Length); var sender = _transport.GetQueueSender(message.DeliverTo); await sender.Send(message); }).ConfigureAwaitFalse(); return Task.Delay(0); }
public async Task ExecuteWithCache_WhenValueIsCachedAndAgeEntryIsTooOld_ShouldRemoveOldEntry( [Frozen] Mock<ICacheEntryRepository> cacheEntryRepo, CacheService sut, string key, TestCacheReturnValue expected, TestCacheReturnValue notExpected, DateTimeOffset now, Guid id) { //arrange cacheEntryRepo.Setup(c => c.Get<TestCacheReturnValue>(It.IsAny<CancellationToken>(), key, It.Is<IDictionary<string, string>>(d => d.Count == 0))) .ReturnsTask(new CacheEntry<TestCacheReturnValue>( id, key, new Dictionary<string, string>(), now.Subtract(TimeSpan.FromMinutes(10)), notExpected)); //act await sut.ExecuteWithCache(CancellationToken.None, key, () => Task.FromResult(expected), TimeSpan.FromMinutes(5)); //assert cacheEntryRepo.Verify(c => c.Remove<TestCacheReturnValue>(CancellationToken.None, key, id)); }
public static void IsAfter(DateTimeOffset expected, DateTimeOffset actual) { TimeSpan difference = actual.Subtract(expected); Assert.IsTrue(difference.Ticks > 0); }
public static void ForwardTimeUntil(DateTimeOffset startTime, DateTimeOffset dateTime, TimeSpan timeout) { var dueTime = GetDueTime(dateTime.Subtract(startTime)); WaitOnTimer(dueTime, timeout); }
/// <summary> /// (Re)sets the process delayed actions timer to trigger based on the given due time. /// </summary> /// <param name="nextDueTime">Time when the timer should timeout.</param> private void ResetProcessDelayedActionsTimer(DateTimeOffset nextDueTime) { if (_processDelayedActionsTimer != null) { _processDelayedActionsTimer.Dispose(); } int millisecondsToNextProcessingOfDelayedActions = (int)nextDueTime.Subtract(DateTimeOffset.Now).TotalMilliseconds; System.Diagnostics.Debug.WriteLine("SDKManager.ResetProcessDelayedActionsTimer(): " + Math.Round((double)millisecondsToNextProcessingOfDelayedActions / 1000, 0) + " second(s) to next processing of delayed actions"); _processDelayedActionsTimer = new Timer(OnProcessDelayedActionsTimerTimeoutAsync, null, millisecondsToNextProcessingOfDelayedActions, Timeout.Infinite); }
/// <summary> /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteExpiration"></param> /// <returns> /// <c>true</c> if insertion succeeded, or <c>false</c> if there is an already an entry in the cache that has the same key as key. /// </returns> /// <exception cref="NotImplementedException"></exception> public bool Add(string key, ICacheItem value, DateTimeOffset absoluteExpiration) { if (key == null) throw new ArgumentNullException("key"); try { if (IsCacheInitilized()) { TimeSpan expiration = absoluteExpiration.Subtract(DateTimeOffset.UtcNow); this.cache.SetAsync(key, value, expiration); double expirationInSeconds = Math.Ceiling(expiration.TotalSeconds); Trace.TraceInformation("Redis Cache Provider: Requested to add asyn key {0} for {1} secounds. Correlation Id = {2}", key, expirationInSeconds, Trace.CorrelationManager.ActivityId); return true; } else { Trace.TraceWarning("Redis Cache Provider: Cache still not initilized when trying to add the key {0}. Correlation Id = {1}", key, Trace.CorrelationManager.ActivityId); } } catch (Exception ex) { Trace.TraceError("Redis Cache Provider: Error inserting cache item. Key={0}, Correlation Id = {2}.\n Exception Message {3}\n{4}", key, Trace.CorrelationManager.ActivityId, ex.Message, ex.StackTrace); } return false; }
/// <summary> /// Returns a <see cref="DateTimeOffset"/> which subtract current <see cref="TimeSpan"/> ago from the <paramref name="time"/>. /// </summary> /// <param name="source">A <see cref="TimeSpan"/> instance.</param> /// <param name="time">A <see cref="DateTimeOffset"/> ago from.</param> /// <returns>Returns a <see cref="DateTimeOffset"/> which subtract current <see cref="TimeSpan"/> ago from the <paramref name="time"/>.</returns> public static DateTimeOffset Until(this TimeSpan source, DateTimeOffset time) { return time.Subtract(source); }
public void SendSession(DateTimeOffset start, DateTimeOffset end, int sessionId, Guid version) { //TODO: errors at this level should be treated as critical DateTime utcActualStart = start.Subtract(Settings.SessionWarmUp).UtcDateTime; _logger.InfoFormat("Sending StartSessionRequest with SessionId: {0} Version: {1} Start(UTC): {2}", version, sessionId, utcActualStart); StartSessionRequest startRequest = new StartSessionRequest { Version = version, SessionId = sessionId}; Send(startRequest, utcActualStart); DateTime utcActualEnd = end.Add(Settings.SessionCoolDown).UtcDateTime; _logger.InfoFormat("Sending EndSessionRequest with SessionId: {0} Version: {1} End(UTC): {2}", version, sessionId, utcActualEnd); EndSessionRequest endRequest = new EndSessionRequest { Version = version, SessionId = sessionId }; Send(endRequest, utcActualEnd); }
/// <summary> /// Gets the statistical information /// </summary> /// <param name="totalCasesNum">The number of total cases</param> /// <param name="passedNum">The number of passed cases</param> /// <param name="failedNum">The number of failed cases</param> /// <param name="testRunStartTime">The start time of the run</param> /// <param name="testRunEndTime">The end time of the run</param> /// <returns>Return statistical information about this test</returns> public string SummaryTable(long totalCasesNum, long passedNum, long failedNum, DateTimeOffset testRunStartTime, DateTimeOffset testRunEndTime) { DataType.RunSummary sry = new DataType.RunSummary() { TotalCount = totalCasesNum, FailedCount = failedNum, PassedCount = passedNum, InconclusiveCount = totalCasesNum - passedNum - failedNum, PassRate = totalCasesNum == 0 ? 0 : (float)passedNum * 100 / totalCasesNum, StartTime = testRunStartTime.ToLocalTime().ToString("MM/dd/yyyy HH:mm:ss"), EndTime = testRunEndTime.ToLocalTime().ToString("MM/dd/yyyy HH:mm:ss"), Duration = testRunEndTime.Subtract(testRunStartTime).ToString(@"hh\:mm\:ss") }; return (serializer.Serialize(sry)); }
public static void Subtract_DateTimeOffset(DateTimeOffset dt1, DateTimeOffset dt2, TimeSpan expected) { Assert.Equal(expected, dt1 - dt2); Assert.Equal(expected, dt1.Subtract(dt2)); }
public static void Subtract_TimeSpan(DateTimeOffset dt, TimeSpan ts, DateTimeOffset expected) { Assert.Equal(expected, dt - ts); Assert.Equal(expected, dt.Subtract(ts)); }
public static void AddSubtract_TimeSpan() { var dateTimeOffset = new DateTimeOffset(new DateTime(2012, 6, 18, 10, 5, 1, 0, DateTimeKind.Utc)); TimeSpan timeSpan = dateTimeOffset.TimeOfDay; DateTimeOffset newDate = dateTimeOffset.Subtract(timeSpan); Assert.Equal(new DateTimeOffset(new DateTime(2012, 6, 18, 0, 0, 0, 0, DateTimeKind.Utc)).Ticks, newDate.Ticks); Assert.Equal(dateTimeOffset.Ticks, newDate.Add(timeSpan).Ticks); }
public async Task ExecuteWithCache_WhenValueIsCachedAndAgeEntryIsTooOldWithAttributes_ShouldAddNewEntry( [Frozen] Mock<ICacheEntryRepository> cacheEntryRepo, CacheService sut, string key, TestCacheReturnValue expected, TestCacheReturnValue notExpected, DateTimeOffset now, Guid id, Dictionary<string, string> attributes) { //arrange cacheEntryRepo.Setup(c => c.Get<TestCacheReturnValue>(It.IsAny<CancellationToken>(), key, attributes)) .ReturnsTask(new CacheEntry<TestCacheReturnValue>( id, key, new Dictionary<string, string>(), now.Subtract(TimeSpan.FromMinutes(10)), notExpected)); cacheEntryRepo.Setup(c => c.AddOrUpdate(CancellationToken.None, It.Is<CacheEntry<TestCacheReturnValue>>(entry => entry.CacheKey == key && entry.Value == expected && entry.Attributes == attributes))) .ReturnsDefaultTask() .Verifiable(); //act await sut.ExecuteWithCache(CancellationToken.None, key, () => Task.FromResult(expected), TimeSpan.FromMinutes(5), attributes); //assert cacheEntryRepo.Verify(); }
public async Task Invalidate_WithIsYoungerThanMinAge_ShouldNotRemoveCacheEntry( [Frozen] Mock<ICacheEntryRepository> cacheEntryRepo, CacheService sut, string key, TestCacheReturnValue value, DateTimeOffset now) { //arrange var entry = new CacheEntry<TestCacheReturnValue>(Guid.NewGuid(), key, new Dictionary<string, string>(), now.Subtract(TimeSpan.FromMinutes(2)), value); cacheEntryRepo.Setup(c => c.Get<TestCacheReturnValue>(It.IsAny<CancellationToken>(), key, It.Is<IDictionary<string, string>>(d => d.Count == 0))) .ReturnsTask(entry); //act await sut.Invalidate<TestCacheReturnValue>(CancellationToken.None, key, TimeSpan.FromMinutes(2)); //assert cacheEntryRepo.Verify(c => c.Remove<TestCacheReturnValue>(It.IsAny<CancellationToken>(), key, entry.Id), Times.Never()); }
public static void TestOperators() { DateTimeOffset date1 = new DateTimeOffset(new DateTime(1996, 6, 3, 22, 15, 0, DateTimeKind.Utc)); DateTimeOffset date2 = new DateTimeOffset(new DateTime(1996, 12, 6, 13, 2, 0, DateTimeKind.Utc)); DateTimeOffset date3 = new DateTimeOffset(new DateTime(1996, 10, 12, 8, 42, 0, DateTimeKind.Utc)); // diff1 gets 185 days, 14 hours, and 47 minutes. TimeSpan diff1 = date2.Subtract(date1); Assert.Equal(new TimeSpan(185, 14, 47, 0), diff1); // date4 gets 4/9/1996 5:55:00 PM. DateTimeOffset date4 = date3.Subtract(diff1); Assert.Equal(new DateTimeOffset(new DateTime(1996, 4, 9, 17, 55, 0, DateTimeKind.Utc)), date4); // diff2 gets 55 days 4 hours and 20 minutes. TimeSpan diff2 = date2 - date3; Assert.Equal(new TimeSpan(55, 4, 20, 0), diff2); // date5 gets 4/9/1996 5:55:00 PM. DateTimeOffset date5 = date1 - diff2; Assert.Equal(new DateTimeOffset(new DateTime(1996, 4, 9, 17, 55, 0, DateTimeKind.Utc)), date5); }
public static long ToUnixTimeStamp(DateTimeOffset dateTime) { var ts = dateTime.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; return (long)ts; }
//Use this method in LINQ queries when using constant DateTimeOffset value, when your target database is SQL CE public static DateTimeOffset AdjustDateTimeOffsetForLinq(DateTimeOffset value) { AdjustDefaultDateTimeFormatForSqlCe(); return value.Subtract(value.Offset); }
/// <summary> /// Gets the difference between the given <see cref="DateTimeOffset"/> object /// defined by <paramref name="dateTimeOffset"/> and <see cref="UtcNow"/>. /// </summary> /// <param name="dateTimeOffset"> /// The date time offset to be compared with. /// </param> /// <returns> /// The number of seconds difference between the <see cref="DateTimeOffset"/> object and /// <see cref="UtcNow"/>. Zero, if they reference the same point of time; /// greater than zero if the <see cref="DateTimeOffset"/> object in the future, /// or less than zero if the <see cref="DateTimeOffset"/> object is in the past. /// </returns> public int GetDiffereceInSeconds(DateTimeOffset dateTimeOffset) { return Convert.ToInt32(dateTimeOffset.Subtract(this.UtcNow).TotalSeconds); }
private DateTimeOffset CleanOffset(DateTimeOffset offset) { offset = offset.Subtract(TimeSpan.FromMilliseconds(offset.Millisecond)); return offset.Subtract(TimeSpan.FromSeconds(offset.Second)); }
public async Task UserLockedOutWithDateTimeNowPlus30() { var db = UnitTestHelper.CreateDefaultDb(); var mgr = TestUtil.CreateManager(db); mgr.UserLockoutEnabledByDefault = true; var user = new IdentityUser("LockoutTest"); UnitTestHelper.IsSuccess(mgr.Create(user)); Assert.True(mgr.GetLockoutEnabled(user.Id)); Assert.True(user.LockoutEnabled); var lockoutEnd = new DateTimeOffset(DateTime.Now.AddMinutes(30)); UnitTestHelper.IsSuccess(await mgr.SetLockoutEndDateAsync(user.Id, lockoutEnd)); // Create a new db to ensure the user entities are recreated db = new IdentityDbContext(); mgr = TestUtil.CreateManager(db); Assert.True(await mgr.IsLockedOutAsync(user.Id)); var end = await mgr.GetLockoutEndDateAsync(user.Id); Assert.True(lockoutEnd.Subtract(end) < TimeSpan.FromSeconds(1)); // Conversions are slightly lossy }
public static void IsNear(DateTimeOffset expected, DateTimeOffset actual, TimeSpan threshold) { IsWithinThreshold(expected.Subtract(actual), threshold); }
private bool CanRemoveMessage(IMessageViewModel message) { if (message == null) return false; var currentDate = new DateTimeOffset(_mainViewModel.CurrentDateTime); double minutesLeft = currentDate.Subtract(message.SentDate).TotalMinutes; return (message.User.Id == _mainViewModel.CurrentUser.Id && minutesLeft < 10); }
//public void RequestHistoricalData(Security security, DateTime endDateTime, TimeSpan duration, // BarSize barSizeSetting, HistoricalDataType whatToShow, int useRth) //{ // DateTime beginDateTime = endDateTime.Subtract(duration); // string dur = ConvertPeriodtoIb(beginDateTime, endDateTime); // RequestHistoricalData(tickerId, contract, endDateTime, dur, barSizeSetting, whatToShow, useRth); //} /// <summary> /// used for reqHistoricalData /// </summary> private static string ConvertPeriodtoIb(DateTimeOffset startTime, DateTimeOffset endTime) { var period = endTime.Subtract(startTime); var secs = period.TotalSeconds; long unit; if (secs < 1) throw new ArgumentOutOfRangeException("endTime", "Period cannot be less than 1 second."); if (secs < 86400) { unit = (long)Math.Ceiling(secs); return unit + " S"; } var days = secs / 86400; unit = (long)Math.Ceiling(days); if (unit <= 34) return unit + " D"; var weeks = days / 7; unit = (long)Math.Ceiling(weeks); if (unit > 52) throw new ArgumentOutOfRangeException("endTime", "Period cannot be bigger than 52 weeks."); return unit + " W"; }
public int CheckForAvailableResources(int subscriptionId, DateTimeOffset sessionStart, DateTimeOffset sessionEnd) { int availableCPUs; using (ApplicationDbContext context = new ApplicationDbContext()) { //TODO: move warmUP and coolDown into the config TimeSpan warmUp = new TimeSpan(0, 20, 0); //there is an extra +5 as this is a safe assumption as how long will it take for azure to //delete the VMs TimeSpan coolDown = new TimeSpan(0, 30 + 5, 0); DateTimeOffset start = sessionStart.Subtract(warmUp); DateTimeOffset end = sessionEnd.Add(coolDown); var sameWindowSessions = context.Sessions.Where(x => x.SubscriptionId == subscriptionId && x.StartDate <= end && x.EndDate >= start && !x.Removed).ToList(); //int projectedCPUs = sameWindowSessions.Sum(x => Sessions.CalculateSessionCPUs(x)); int projectedCPUs = MaxOverlappingCPUs(sameWindowSessions); //now check how many VMs programmed are running at the moment List<VmSizeEnum> runningVMs = context.VirtualMachines .Where(x => !x.Deleted && !x.Stopped && x.Session.SubscriptionId == subscriptionId) .Select(x => x.Session.VmSize).ToList() .Select(x => (VmSizeEnum)Enum.Parse(typeof(VmSizeEnum), x)).ToList(); int currentPlannedCPUs = runningVMs.Sum(x => (int)x); Subscription subscription = context.Subscriptions .Single(x => x.SubscriptionId == subscriptionId); IVMManagement management = AzureFacadeFactory.VMManagement(subscription.AzureSubscriptionId, subscription.Certificate, subscription.CertificateKey, subscription.BlobStorageName, subscription.BlobStorageKey); SubscriptionDetails subscriptionDetails = management.GetSubscriptionDetails(); int unknownCPUs = subscriptionDetails.MaxCoreCount - subscriptionDetails.AvailableCoreCount - currentPlannedCPUs; unknownCPUs = Math.Max(unknownCPUs, 0); availableCPUs = subscriptionDetails.MaxCoreCount - unknownCPUs - projectedCPUs; } return availableCPUs; }