/// <summary> /// Entry point to start scheduler's execution /// </summary> /// <returns></returns> public virtual Task Run() { if (execTask != null) { return(execTask); } log.Debug("Scheduler starting ..."); running = true; paused = false; execTask = Task.Run(() => { log.Debug("Scheduler started"); while (running) { lock (pauseLock) { while (paused && running) { try { // wait until scheduler resumes Monitor.Wait(pauseLock, PauseWaitMs); } catch { } } if (!running) { break; } } DateTimeOffset now = Time.Now(); DateTimeOffset endTime = now.Add(timeDelta); nextJobs.Clear(); lock (jobsQueue) { while (true) { JobHolder jh = jobsQueue.FirstOrDefault(); if (jh == null) { break; } DateTimeOffset?nextFireTime = jh.Schedule.GetNextFireTime(); if (!nextFireTime.HasValue) { jobsQueue.Remove(jh); continue; } if (nextFireTime < now) { jobsQueue.Remove(jh); // check for misfire TimeSpan diff = now - nextFireTime.Value; jh.Schedule.HandleMisfire(now, diff); if (jh.Schedule.GetNextFireTime() != null) { jobsQueue.Add(jh); } continue; } if (nextFireTime > endTime) { break; } nextJobs.Add(jh); jobsQueue.Remove(jh); } } // end LOCK if (nextJobs.Count > 0) { // check if pause requested // just after jobs fetched bool pauseReq; lock (pauseLock) pauseReq = paused; if (pauseReq) { // save jobs until next resume lock (jobsQueue) { foreach (JobHolder jh in nextJobs) { jobsQueue.Add(jh); } continue; } } foreach (JobHolder jh in nextJobs) { Task.Run(async() => { try { await jh.Schedule.WaitUntilFire(); await jh.Job.Execute(jh.Context); jh.Context.OnJobExecuted(jh); lock (jobsQueue) jobsQueue.Add(jh); } catch (Exception ex) { Exception lastError = ex; int maxReTry = jh.Schedule.ReTryAttempts; if (maxReTry > 0) { while (maxReTry-- > 0) { try { jh.Context.IncrementReTryAttempt(); await jh.Job.Execute(jh.Context); jh.Context.OnJobExecuted(jh); lock (jobsQueue) jobsQueue.Add(jh); return; } catch (Exception exOnReTry) { lastError = exOnReTry; jh.Context.SetLastError(lastError); continue; } } } jh.Context.OnJobFaulted(lastError, jh); } }); } } } log.Debug("Scheduler shutting down ..."); }); return(execTask); }
public Interval(DateTimeOffset start, TimeSpan duration, bool startIncluded, bool endIncluded) : this(start, start.Add(duration), startIncluded, endIncluded) { }
public void Advance(DateTimeOffset actualLastRuntime) { LastRunTime = actualLastRuntime; NextRunTime = actualLastRuntime.Add(Request.RunTime); }
public ImmutableTimeRange(DateTimeOffset start, TimeSpan span) : this(start, start.Add(span.Ticks >= 0 ? span : TimeSpan.Zero)) { }
public async Task <IEnumerable <FlightModel> > FindFlights(string departingFrom, string arrivingAt, DateTimeOffset desiredTime, TimeSpan offset, CancellationToken cancellationToken) { return((await _flightModels).Where(f => f.DepartingFrom.Equals(departingFrom) && f.ArrivingAt.Equals(arrivingAt) && f.DepartureTime > desiredTime.Subtract(offset) && f.DepartureTime < desiredTime.Add(offset)).OrderBy(f => f.DepartureTime)); }
protected override async Task ApplyResponseGrantAsync() { AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType); bool shouldSignin = signin != null; AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode); bool shouldSignout = signout != null; if (shouldSignin || shouldSignout || _shouldRenew) { var cookieOptions = new CookieOptions { Domain = Options.CookieDomain, HttpOnly = Options.CookieHttpOnly, Path = Options.CookiePath ?? "/", }; if (Options.CookieSecure == CookieSecureOption.SameAsRequest) { cookieOptions.Secure = Request.IsSecure; } else { cookieOptions.Secure = Options.CookieSecure == CookieSecureOption.Always; } if (shouldSignin) { var context = new CookieResponseSignInContext( Context, Options, Options.AuthenticationType, signin.Identity, signin.Properties); DateTimeOffset issuedUtc = Options.SystemClock.UtcNow; DateTimeOffset expiresUtc = issuedUtc.Add(Options.ExpireTimeSpan); context.Properties.IssuedUtc = issuedUtc; context.Properties.ExpiresUtc = expiresUtc; Options.Provider.ResponseSignIn(context); if (context.Properties.IsPersistent) { cookieOptions.Expires = expiresUtc.ToUniversalTime().DateTime; } var model = new AuthenticationTicket(context.Identity, context.Properties); string cookieValue = Options.TicketDataFormat.Protect(model); Response.Cookies.Append( Options.CookieName, cookieValue, cookieOptions); } else if (shouldSignout) { Response.Cookies.Delete( Options.CookieName, cookieOptions); } else if (_shouldRenew) { AuthenticationTicket model = await AuthenticateAsync(); model.Properties.IssuedUtc = _renewIssuedUtc; model.Properties.ExpiresUtc = _renewExpiresUtc; string cookieValue = Options.TicketDataFormat.Protect(model); if (model.Properties.IsPersistent) { cookieOptions.Expires = _renewExpiresUtc.ToUniversalTime().DateTime; } Response.Cookies.Append( Options.CookieName, cookieValue, cookieOptions); } Response.Headers.Set( HeaderNameCacheControl, HeaderValueNoCache); Response.Headers.Set( HeaderNamePragma, HeaderValueNoCache); Response.Headers.Set( HeaderNameExpires, HeaderValueMinusOne); bool shouldLoginRedirect = shouldSignin && Options.LoginPath.HasValue && Request.Path == Options.LoginPath; bool shouldLogoutRedirect = shouldSignout && Options.LogoutPath.HasValue && Request.Path == Options.LogoutPath; if ((shouldLoginRedirect || shouldLogoutRedirect) && Response.StatusCode == 200) { IReadableStringCollection query = Request.Query; string redirectUri = query.Get(Options.ReturnUrlParameter); if (!string.IsNullOrWhiteSpace(redirectUri) && IsHostRelative(redirectUri)) { var redirectContext = new CookieApplyRedirectContext(Context, Options, redirectUri); Options.Provider.ApplyRedirect(redirectContext); } } } }
/// /// <summary> * add a given offset to this multiple calls stack /// * </summary> /// * <param name="seconds"> seconds to add to this </param> /// * <param name="minutes"> minutes to add to this </param> /// * <param name="hours"> hours to add to this </param> /// * <param name="days"> days to add to this </param> /// public virtual void addOffset(int seconds, int minutes, int hours, int days) { m_DateTimeOffset = m_DateTimeOffset.Add(new TimeSpan(days, hours, minutes, seconds)); }
public static DateTimeOffset AddMilliseconds(this DateTimeOffset dateTimeOffset, double milliseconds, TimeZoneInfo timeZone) { return(dateTimeOffset.Add(TimeSpan.FromMilliseconds(milliseconds), timeZone)); }
public static DateTimeOffset AddTicks(this DateTimeOffset dateTimeOffset, long ticks, TimeZoneInfo timeZone) { return(dateTimeOffset.Add(TimeSpan.FromTicks(ticks), timeZone)); }
public static DateTimeOffset Add(this DateTimeOffset dateTimeOffset, TimeSpan timeSpan, TimeZoneInfo timeZone) { var t = dateTimeOffset.Add(timeSpan); return(TimeZoneInfo.ConvertTime(t, timeZone)); }
public static DateTimeOffset AddHours(this DateTimeOffset dateTimeOffset, double hours, TimeZoneInfo timeZone) { return(dateTimeOffset.Add(TimeSpan.FromHours(hours), timeZone)); }
public static DateTimeOffset Subtract(this DateTimeOffset dateTimeOffset, TimeSpan timeSpan, TimeZoneInfo timeZone) { return(dateTimeOffset.Add(timeSpan.Negate(), timeZone)); }
private async Task InvokeTokenEndpointAsync() { DateTimeOffset currentUtc = Options.SystemClock.UtcNow; // remove milliseconds in case they don't round-trip currentUtc = currentUtc.Subtract(TimeSpan.FromMilliseconds(currentUtc.Millisecond)); IFormCollection form = await Request.ReadFormAsync(); var clientContext = new OAuthValidateClientAuthenticationContext( Context, Options, form); await Options.Provider.ValidateClientAuthentication(clientContext); if (!clientContext.IsValidated) { _logger.WriteError("clientID is not valid."); if (!clientContext.HasError) { clientContext.SetError(Constants.Errors.InvalidClient); } await SendErrorAsJsonAsync(clientContext); return; } var tokenEndpointRequest = new TokenEndpointRequest(form); var validatingContext = new OAuthValidateTokenRequestContext(Context, Options, tokenEndpointRequest, clientContext); AuthenticationTicket ticket = null; if (tokenEndpointRequest.IsAuthorizationCodeGrantType) { // Authorization Code Grant http://tools.ietf.org/html/rfc6749#section-4.1 // Access Token Request http://tools.ietf.org/html/rfc6749#section-4.1.3 ticket = await InvokeTokenEndpointAuthorizationCodeGrantAsync(validatingContext, currentUtc); } else if (tokenEndpointRequest.IsResourceOwnerPasswordCredentialsGrantType) { // Resource Owner Password Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.3 // Access Token Request http://tools.ietf.org/html/rfc6749#section-4.3.2 ticket = await InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync(validatingContext, currentUtc); } else if (tokenEndpointRequest.IsClientCredentialsGrantType) { // Client Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.4 // Access Token Request http://tools.ietf.org/html/rfc6749#section-4.4.2 ticket = await InvokeTokenEndpointClientCredentialsGrantAsync(validatingContext, currentUtc); } else if (tokenEndpointRequest.IsRefreshTokenGrantType) { // Refreshing an Access Token // http://tools.ietf.org/html/rfc6749#section-6 ticket = await InvokeTokenEndpointRefreshTokenGrantAsync(validatingContext, currentUtc); } else if (tokenEndpointRequest.IsCustomExtensionGrantType) { // Defining New Authorization Grant Types // http://tools.ietf.org/html/rfc6749#section-8.3 ticket = await InvokeTokenEndpointCustomGrantAsync(validatingContext, currentUtc); } else { // Error Response http://tools.ietf.org/html/rfc6749#section-5.2 // The authorization grant type is not supported by the // authorization server. _logger.WriteError("grant type is not recognized"); validatingContext.SetError(Constants.Errors.UnsupportedGrantType); } if (ticket == null) { await SendErrorAsJsonAsync(validatingContext); return; } ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(Options.AccessTokenExpireTimeSpan); var tokenEndpointContext = new OAuthTokenEndpointContext( Context, Options, ticket, tokenEndpointRequest); await Options.Provider.TokenEndpoint(tokenEndpointContext); if (tokenEndpointContext.TokenIssued) { ticket = new AuthenticationTicket( tokenEndpointContext.Identity, tokenEndpointContext.Properties); } else { _logger.WriteError("Token was not issued to tokenEndpointContext"); validatingContext.SetError(Constants.Errors.InvalidGrant); await SendErrorAsJsonAsync(validatingContext); return; } var accessTokenContext = new AuthenticationTokenCreateContext( Context, Options.AccessTokenFormat, ticket); await Options.AccessTokenProvider.CreateAsync(accessTokenContext); string accessToken = accessTokenContext.Token; if (string.IsNullOrEmpty(accessToken)) { accessToken = accessTokenContext.SerializeTicket(); } DateTimeOffset?accessTokenExpiresUtc = ticket.Properties.ExpiresUtc; var refreshTokenCreateContext = new AuthenticationTokenCreateContext( Context, Options.RefreshTokenFormat, accessTokenContext.Ticket); await Options.RefreshTokenProvider.CreateAsync(refreshTokenCreateContext); string refreshToken = refreshTokenCreateContext.Token; var tokenEndpointResponseContext = new OAuthTokenEndpointResponseContext( Context, Options, ticket, tokenEndpointRequest, accessToken, tokenEndpointContext.AdditionalResponseParameters); await Options.Provider.TokenEndpointResponse(tokenEndpointResponseContext); var memory = new MemoryStream(); byte[] body; using (var writer = new JsonTextWriter(new StreamWriter(memory))) { writer.WriteStartObject(); writer.WritePropertyName(Constants.Parameters.AccessToken); writer.WriteValue(accessToken); writer.WritePropertyName(Constants.Parameters.TokenType); writer.WriteValue(Constants.TokenTypes.Bearer); if (accessTokenExpiresUtc.HasValue) { TimeSpan?expiresTimeSpan = accessTokenExpiresUtc - currentUtc; var expiresIn = (long)expiresTimeSpan.Value.TotalSeconds; if (expiresIn > 0) { writer.WritePropertyName(Constants.Parameters.ExpiresIn); writer.WriteValue(expiresIn); } } if (!String.IsNullOrEmpty(refreshToken)) { writer.WritePropertyName(Constants.Parameters.RefreshToken); writer.WriteValue(refreshToken); } foreach (var additionalResponseParameter in tokenEndpointResponseContext.AdditionalResponseParameters) { writer.WritePropertyName(additionalResponseParameter.Key); writer.WriteValue(additionalResponseParameter.Value); } writer.WriteEndObject(); writer.Flush(); body = memory.ToArray(); } Response.ContentType = "application/json;charset=UTF-8"; Response.Headers.Set("Cache-Control", "no-cache"); Response.Headers.Set("Pragma", "no-cache"); Response.Headers.Set("Expires", "-1"); Response.ContentLength = body.Length; await Response.WriteAsync(body, Request.CallCancelled); }
protected override async Task ApplyResponseGrantAsync() { // only successful results of an authorize request are altered if (_clientContext == null || _authorizeEndpointRequest == null || Response.StatusCode != 200) { return; } // only apply with signin of matching authentication type AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType); if (signin == null) { return; } var returnParameter = new Dictionary <string, string>(); if (_authorizeEndpointRequest.IsAuthorizationCodeGrantType) { DateTimeOffset currentUtc = Options.SystemClock.UtcNow; signin.Properties.IssuedUtc = currentUtc; signin.Properties.ExpiresUtc = currentUtc.Add(Options.AuthorizationCodeExpireTimeSpan); // associate client_id with all subsequent tickets signin.Properties.Dictionary[Constants.Extra.ClientId] = _authorizeEndpointRequest.ClientId; if (!string.IsNullOrEmpty(_authorizeEndpointRequest.RedirectUri)) { // keep original request parameter for later comparison signin.Properties.Dictionary[Constants.Extra.RedirectUri] = _authorizeEndpointRequest.RedirectUri; } var context = new AuthenticationTokenCreateContext( Context, Options.AuthorizationCodeFormat, new AuthenticationTicket(signin.Identity, signin.Properties)); await Options.AuthorizationCodeProvider.CreateAsync(context); string code = context.Token; if (string.IsNullOrEmpty(code)) { _logger.WriteError("response_type code requires an Options.AuthorizationCodeProvider implementing a single-use token."); var errorContext = new OAuthValidateAuthorizeRequestContext(Context, Options, _authorizeEndpointRequest, _clientContext); errorContext.SetError(Constants.Errors.UnsupportedResponseType); await SendErrorRedirectAsync(_clientContext, errorContext); return; } var authResponseContext = new OAuthAuthorizationEndpointResponseContext( Context, Options, new AuthenticationTicket(signin.Identity, signin.Properties), _authorizeEndpointRequest, null, code); await Options.Provider.AuthorizationEndpointResponse(authResponseContext); foreach (var parameter in authResponseContext.AdditionalResponseParameters) { returnParameter[parameter.Key] = parameter.Value.ToString(); } returnParameter[Constants.Parameters.Code] = code; if (!String.IsNullOrEmpty(_authorizeEndpointRequest.State)) { returnParameter[Constants.Parameters.State] = _authorizeEndpointRequest.State; } string location = string.Empty; if (_authorizeEndpointRequest.IsFormPostResponseMode) { location = Options.FormPostEndpoint.ToString(); returnParameter[Constants.Parameters.RedirectUri] = _clientContext.RedirectUri; } else { location = _clientContext.RedirectUri; } foreach (var key in returnParameter.Keys) { location = WebUtilities.AddQueryString(location, key, returnParameter[key]); } Response.Redirect(location); } else if (_authorizeEndpointRequest.IsImplicitGrantType) { string location = _clientContext.RedirectUri; DateTimeOffset currentUtc = Options.SystemClock.UtcNow; signin.Properties.IssuedUtc = currentUtc; signin.Properties.ExpiresUtc = currentUtc.Add(Options.AccessTokenExpireTimeSpan); // associate client_id with access token signin.Properties.Dictionary[Constants.Extra.ClientId] = _authorizeEndpointRequest.ClientId; var accessTokenContext = new AuthenticationTokenCreateContext( Context, Options.AccessTokenFormat, new AuthenticationTicket(signin.Identity, signin.Properties)); await Options.AccessTokenProvider.CreateAsync(accessTokenContext); string accessToken = accessTokenContext.Token; if (string.IsNullOrEmpty(accessToken)) { accessToken = accessTokenContext.SerializeTicket(); } DateTimeOffset?accessTokenExpiresUtc = accessTokenContext.Ticket.Properties.ExpiresUtc; var appender = new Appender(location, '#'); appender .Append(Constants.Parameters.AccessToken, accessToken) .Append(Constants.Parameters.TokenType, Constants.TokenTypes.Bearer); if (accessTokenExpiresUtc.HasValue) { TimeSpan?expiresTimeSpan = accessTokenExpiresUtc - currentUtc; var expiresIn = (long)(expiresTimeSpan.Value.TotalSeconds + .5); appender.Append(Constants.Parameters.ExpiresIn, expiresIn.ToString(CultureInfo.InvariantCulture)); } if (!String.IsNullOrEmpty(_authorizeEndpointRequest.State)) { appender.Append(Constants.Parameters.State, _authorizeEndpointRequest.State); } var authResponseContext = new OAuthAuthorizationEndpointResponseContext( Context, Options, new AuthenticationTicket(signin.Identity, signin.Properties), _authorizeEndpointRequest, accessToken, null); await Options.Provider.AuthorizationEndpointResponse(authResponseContext); foreach (var parameter in authResponseContext.AdditionalResponseParameters) { appender.Append(parameter.Key, parameter.Value.ToString()); } Response.Redirect(appender.ToString()); } }
/// <inheritdoc /> public IEnumerable <string> ExportToFiles(Summary summary, ILogger consoleLogger) { CIVisibility.Initialize(); DateTimeOffset startTime = DateTimeOffset.UtcNow; Exception exception = null; try { Tracer tracer = Tracer.Instance; foreach (var report in summary.Reports) { Span span = tracer.StartSpan("benchmarkdotnet.test", startTime: startTime); double durationNanoseconds = 0; span.SetTraceSamplingPriority(SamplingPriority.AutoKeep); span.Type = SpanTypes.Test; span.ResourceName = $"{report.BenchmarkCase.Descriptor.Type.FullName}.{report.BenchmarkCase.Descriptor.WorkloadMethod.Name}"; CIEnvironmentValues.Instance.DecorateSpan(span); span.SetTag(Tags.Origin, TestTags.CIAppTestOriginName); span.SetTag(TestTags.Name, report.BenchmarkCase.Descriptor.WorkloadMethodDisplayInfo); span.SetTag(TestTags.Type, TestTags.TypeBenchmark); span.SetTag(TestTags.Suite, report.BenchmarkCase.Descriptor.Type.FullName); span.SetTag(TestTags.Bundle, report.BenchmarkCase.Descriptor.Type.Assembly?.GetName().Name); span.SetTag(TestTags.Framework, $"BenchmarkDotNet {summary.HostEnvironmentInfo.BenchmarkDotNetVersion}"); span.SetTag(TestTags.Status, report.Success ? TestTags.StatusPass : TestTags.StatusFail); span.SetTag(CommonTags.LibraryVersion, TracerConstants.AssemblyVersion); if (summary.HostEnvironmentInfo != null) { span.SetTag("benchmark.host.processor.name", ProcessorBrandStringHelper.Prettify(summary.HostEnvironmentInfo.CpuInfo.Value)); span.SetMetric("benchmark.host.processor.physical_processor_count", summary.HostEnvironmentInfo.CpuInfo.Value.PhysicalProcessorCount); span.SetMetric("benchmark.host.processor.physical_core_count", summary.HostEnvironmentInfo.CpuInfo.Value.PhysicalCoreCount); span.SetMetric("benchmark.host.processor.logical_core_count", summary.HostEnvironmentInfo.CpuInfo.Value.LogicalCoreCount); span.SetMetric("benchmark.host.processor.max_frequency_hertz", summary.HostEnvironmentInfo.CpuInfo.Value.MaxFrequency?.Hertz); span.SetTag("benchmark.host.os_version", summary.HostEnvironmentInfo.OsVersion.Value); span.SetTag("benchmark.host.runtime_version", summary.HostEnvironmentInfo.RuntimeVersion); span.SetMetric("benchmark.host.chronometer.frequency_hertz", summary.HostEnvironmentInfo.ChronometerFrequency.Hertz); span.SetMetric("benchmark.host.chronometer.resolution", summary.HostEnvironmentInfo.ChronometerResolution.Nanoseconds); } if (report.BenchmarkCase.Job != null) { var job = report.BenchmarkCase.Job; span.SetTag("benchmark.job.description", job.DisplayInfo); if (job.Environment != null) { var jobEnv = job.Environment; span.SetTag("benchmark.job.environment.platform", jobEnv.Platform.ToString()); if (jobEnv.Runtime != null) { span.SetTag("benchmark.job.runtime.name", jobEnv.Runtime.Name); span.SetTag("benchmark.job.runtime.moniker", jobEnv.Runtime.MsBuildMoniker); } } } if (report.ResultStatistics != null) { var stats = report.ResultStatistics; span.SetMetric("benchmark.runs", stats.N); span.SetMetric("benchmark.duration.mean", stats.Mean); span.SetMetric("benchmark.statistics.n", stats.N); span.SetMetric("benchmark.statistics.max", stats.Max); span.SetMetric("benchmark.statistics.min", stats.Min); span.SetMetric("benchmark.statistics.mean", stats.Mean); span.SetMetric("benchmark.statistics.median", stats.Median); span.SetMetric("benchmark.statistics.std_dev", stats.StandardDeviation); span.SetMetric("benchmark.statistics.std_err", stats.StandardError); span.SetMetric("benchmark.statistics.kurtosis", stats.Kurtosis); span.SetMetric("benchmark.statistics.skewness", stats.Skewness); if (stats.Percentiles != null) { span.SetMetric("benchmark.statistics.p90", stats.Percentiles.P90); span.SetMetric("benchmark.statistics.p95", stats.Percentiles.P95); span.SetMetric("benchmark.statistics.p99", stats.Percentiles.Percentile(99)); } durationNanoseconds = stats.Mean; } if (report.Metrics != null) { foreach (var keyValue in report.Metrics) { if (keyValue.Value is null || keyValue.Value.Descriptor is null) { continue; } span.SetTag($"benchmark.metrics.{keyValue.Key}.displayName", keyValue.Value.Descriptor.DisplayName); span.SetTag($"benchmark.metrics.{keyValue.Key}.legend", keyValue.Value.Descriptor.Legend); span.SetTag($"benchmark.metrics.{keyValue.Key}.unit", keyValue.Value.Descriptor.Unit); span.SetMetric($"benchmark.metrics.{keyValue.Key}.value", keyValue.Value.Value); } } if (report.BenchmarkCase.Config?.HasMemoryDiagnoser() == true) { span.SetMetric("benchmark.memory.gen0Collections", report.GcStats.Gen0Collections); span.SetMetric("benchmark.memory.gen1Collections", report.GcStats.Gen1Collections); span.SetMetric("benchmark.memory.gen2Collections", report.GcStats.Gen2Collections); span.SetMetric("benchmark.memory.total_operations", report.GcStats.TotalOperations); span.SetMetric("benchmark.memory.mean_bytes_allocations", report.GcStats.BytesAllocatedPerOperation); span.SetMetric("benchmark.memory.total_bytes_allocations", report.GcStats.GetTotalAllocatedBytes(false)); } var duration = TimeSpan.FromTicks((long)(durationNanoseconds / TimeConstants.NanoSecondsPerTick)); span.Finish(startTime.Add(duration)); } // Ensure all the spans gets flushed before we report the success. // In some cases the process finishes without sending the traces in the buffer. CIVisibility.FlushSpans(); } catch (Exception ex) { exception = ex; consoleLogger.WriteLine(LogKind.Error, ex.ToString()); } if (exception is null) { return(new string[] { "Datadog Exporter ran successfully." }); } else { return(new string[] { "Datadog Exporter error: " + exception.ToString() }); } }
protected TimeoutSpecsBase() { // Override the SystemClock, to return time stored in variables we manipulate. SystemClock.DateTimeOffsetUtcNow = () => _offsetUtcNow; SystemClock.UtcNow = () => _utcNow; // Override SystemClock.CancelTokenAfter to record when the policy wants the token to cancel. SystemClock.CancelTokenAfter = (tokenSource, timespan) => { if (_trackedTokenSource != null && tokenSource != _trackedTokenSource) { throw new InvalidOperationException("Timeout tests cannot track more than one timing out token at a time."); } _trackedTokenSource = tokenSource; DateTimeOffset newCancelAt = _offsetUtcNow.Add(timespan); _cancelAt = newCancelAt < _cancelAt ? newCancelAt : _cancelAt; SystemClock.Sleep(TimeSpan.Zero, CancellationToken.None); // Invoke our custom definition of sleep, to check for immediate cancellation. }; // Override SysteClock.Sleep, to manipulate our artificial clock. And - if it means sleeping beyond the time when a tracked token should cancel - cancel it! SystemClock.Sleep = (sleepTimespan, sleepCancellationtoken) => { if (sleepCancellationtoken.IsCancellationRequested) { return; } if (_trackedTokenSource == null || _trackedTokenSource.IsCancellationRequested) { // Not tracking any CancellationToken (or already cancelled) - just advance time. _utcNow += sleepTimespan; _offsetUtcNow += sleepTimespan; } else { // Tracking something to cancel - does this sleep hit time to cancel? TimeSpan timeToCancellation = _cancelAt - _offsetUtcNow; if (sleepTimespan >= timeToCancellation) { // Cancel! (And advance time only to the instant of cancellation) _offsetUtcNow += timeToCancellation; _utcNow += timeToCancellation; // (and stop tracking it after cancelling; it can't be cancelled twice, so there is no need, and the owner may dispose it) CancellationTokenSource copySource = _trackedTokenSource; _trackedTokenSource = null; copySource.Cancel(); copySource.Token.ThrowIfCancellationRequested(); } else { // (not yet time to cancel - just advance time) _utcNow += sleepTimespan; _offsetUtcNow += sleepTimespan; } } }; SystemClock.SleepAsync = (sleepTimespan, cancellationtoken) => { SystemClock.Sleep(sleepTimespan, cancellationtoken); return(Task.FromResult(true)); }; }
private static SessionMetadata CreateMetadataForSession(int sessionId, DateTimeOffset startTime, TimeSpan duration) { var metadata = new SessionMetadata { SessionID = sessionId, BitFlags = 59 }; metadata.PipeInfo = new PipeInfo { Streamed = true, Reused = false, CltReuse = false }; const string format = @"yyyy-MM-ddTHH\:mm\:ss.fffffffzzz"; metadata.SessionTimers = new SessionTimers { ClientConnected = startTime.ToString(format), ClientBeginRequest = startTime.ToString(format), GotRequestHeaders = startTime.ToString(format), ClientDoneRequest = startTime.ToString(format), ServerConnected = startTime.ToString(format), FiddlerBeginRequest = startTime.ToString(format), ServerGotRequest = startTime.ToString(format), ServerBeginResponse = startTime.Add(duration).ToString(format), GotResponseHeaders = startTime.Add(duration).ToString(format), ServerDoneResponse = startTime.Add(duration).ToString(format), ClientBeginResponse = startTime.Add(duration).ToString(format), ClientDoneResponse = startTime.Add(duration).ToString(format) }; metadata.SessionFlags.Add(new SessionFlag { Name = SessionFlag.ClientIP, Value = "127.0.0.1" }); metadata.SessionFlags.Add(new SessionFlag { Name = SessionFlag.ProcessInfo, Value = "apidocs.exe:1234" }); return metadata; }
public static DateTimeOffset FromLong(long offsetInMicrosecsSinceEpoch) { var valInMs = offsetInMicrosecsSinceEpoch / 1000.0; return(NixEpoch.Add(TimeSpan.FromMilliseconds(valInMs))); }
protected DateTimeOffset? GetAbsoluteExpiration(DateTimeOffset utcNow, DistributedCacheEntryOptions options) { // calculate absolute expiration DateTimeOffset? absoluteExpiration = null; if (options.AbsoluteExpirationRelativeToNow.HasValue) { absoluteExpiration = utcNow.Add(options.AbsoluteExpirationRelativeToNow.Value); } else if (options.AbsoluteExpiration.HasValue) { if (options.AbsoluteExpiration.Value <= utcNow) { throw new InvalidOperationException("The absolute expiration value must be in the future."); } absoluteExpiration = options.AbsoluteExpiration.Value; } return absoluteExpiration; }
/// <summary> /// Creates the week range. /// </summary> /// <param name="current">The current</param> /// <param name="cultureInfo">The culture info</param> /// <returns>Set of days</returns> public static DateRange CreateWeekRange(DateTimeOffset current, CultureInfo cultureInfo) { DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek; int diff = (7 + ((int)current.DayOfWeek - (int)firstDay)) % 7; DateTimeOffset start = new DateTimeOffset(current.Year, current.Month, current.Day - diff, 0, 0, 0, 0, TimeSpan.Zero); DateTimeOffset end = start.Add(new TimeSpan(7, 0, 0, 0, -1)); return new DateRange(start, end); }
/// <summary> /// Returns a <see cref="DateTimeOffset"/> which add current <see cref="TimeSpan"/> since from the <paramref name="time"/>. /// </summary> /// <param name="source">A <see cref="TimeSpan"/> instance.</param> /// <param name="time">A <see cref="DateTimeOffset"/> since from.</param> /// <returns>Returns a <see cref="DateTimeOffset"/> which add current <see cref="TimeSpan"/> since from the <paramref name="time"/>.</returns> public static DateTimeOffset Since(this TimeSpan source, DateTimeOffset time) { return time.Add(source); }
/// <summary> /// reserveN is a helper method for AllowN, ReserveN, and WaitN. /// maxFutureReserve specifies the maximum reservation wait duration allowed. /// reserveN returns Reservation, not *Reservation, to avoid allocation in AllowN and WaitN. /// </summary> /// <param name="now">The now.</param> /// <param name="number">The number.</param> /// <param name="maxFutureReserve">The maximum future reserve.</param> /// <returns>Reservation.</returns> private Reservation ReserveImpl(DateTimeOffset now, int number, TimeSpan maxFutureReserve) { lock (_sync) { if (_limit == Limit.Max) { return(new Reservation( clock: _clock, limiter: this, ok: true, tokens: number, timeToAct: now)); } var(newNow, last, tokens) = Advance(now); now = newNow; // Calculate the remaining number of tokens resulting from the request. tokens -= number; // Calculate the wait duration TimeSpan waitDuration = default; if (tokens < 0) { waitDuration = _limit.DurationFromTokens(-tokens); } // Decide result var ok = number <= _burst && waitDuration <= maxFutureReserve; // Prepare reservation if (ok) { var reservation = new Reservation( clock: _clock, limiter: this, ok: true, tokens: number, limit: _limit, timeToAct: now.Add(waitDuration)); _last = newNow; _tokens = tokens; _lastEvent = reservation.TimeToAct; return(reservation); } else { var reservation = new Reservation( clock: _clock, limiter: this, ok: false, limit: _limit); _last = last; return(reservation); } } }
/// <summary> /// The main processing loop of the <see cref="QuartzSchedulerThread" />. /// </summary> public override void Run() { bool lastAcquireFailed = false; while (!halted) { try { // check if we're supposed to pause... lock (sigLock) { while (paused && !halted) { try { // wait until togglePause(false) is called... Monitor.Wait(sigLock, 1000); } catch (ThreadInterruptedException) { } } if (halted) { break; } } int availThreadCount = qsRsrcs.ThreadPool.BlockForAvailableThreads(); if (availThreadCount > 0) // will always be true, due to semantics of blockForAvailableThreads... { IList <IOperableTrigger> triggers = null; DateTimeOffset now = SystemTime.UtcNow(); ClearSignaledSchedulingChange(); try { triggers = qsRsrcs.JobStore.AcquireNextTriggers( now + idleWaitTime, Math.Min(availThreadCount, qsRsrcs.MaxBatchSize), qsRsrcs.BatchTimeWindow); lastAcquireFailed = false; if (log.IsDebugEnabled) { log.DebugFormat("Batch acquisition of {0} triggers", (triggers == null ? 0 : triggers.Count)); } } catch (JobPersistenceException jpe) { if (!lastAcquireFailed) { qs.NotifySchedulerListenersError("An error occurred while scanning for the next trigger to fire.", jpe); } lastAcquireFailed = true; continue; } catch (Exception e) { if (!lastAcquireFailed) { Log.Error("quartzSchedulerThreadLoop: RuntimeException " + e.Message, e); } lastAcquireFailed = true; continue; } if (triggers != null && triggers.Count > 0) { now = SystemTime.UtcNow(); DateTimeOffset triggerTime = triggers[0].GetNextFireTimeUtc().Value; TimeSpan timeUntilTrigger = triggerTime - now; while (timeUntilTrigger > TimeSpan.FromMilliseconds(2)) { if (ReleaseIfScheduleChangedSignificantly(triggers, triggerTime)) { break; } lock (sigLock) { if (halted) { break; } if (!IsCandidateNewTimeEarlierWithinReason(triggerTime, false)) { try { // we could have blocked a long while // on 'synchronize', so we must recompute now = SystemTime.UtcNow(); timeUntilTrigger = triggerTime - now; if (timeUntilTrigger > TimeSpan.Zero) { Monitor.Wait(sigLock, timeUntilTrigger); } } catch (ThreadInterruptedException) { } } } if (ReleaseIfScheduleChangedSignificantly(triggers, triggerTime)) { break; } now = SystemTime.UtcNow(); timeUntilTrigger = triggerTime - now; } // this happens if releaseIfScheduleChangedSignificantly decided to release triggers if (triggers.Count == 0) { continue; } // set triggers to 'executing' IList <TriggerFiredResult> bndles = new List <TriggerFiredResult>(); bool goAhead = true; lock (sigLock) { goAhead = !halted; } if (goAhead) { try { IList <TriggerFiredResult> res = qsRsrcs.JobStore.TriggersFired(triggers); if (res != null) { bndles = res; } } catch (SchedulerException se) { qs.NotifySchedulerListenersError("An error occurred while firing triggers '" + triggers + "'", se); // QTZ-179 : a problem occurred interacting with the triggers from the db // we release them and loop again foreach (IOperableTrigger t in triggers) { qsRsrcs.JobStore.ReleaseAcquiredTrigger(t); } continue; } } for (int i = 0; i < bndles.Count; i++) { TriggerFiredResult result = bndles[i]; TriggerFiredBundle bndle = result.TriggerFiredBundle; Exception exception = result.Exception; IOperableTrigger trigger = triggers[i]; // TODO SQL exception? if (exception != null && (exception is DbException || exception.InnerException is DbException)) { Log.Error("DbException while firing trigger " + trigger, exception); qsRsrcs.JobStore.ReleaseAcquiredTrigger(trigger); continue; } // it's possible to get 'null' if the triggers was paused, // blocked, or other similar occurrences that prevent it being // fired at this time... or if the scheduler was shutdown (halted) if (bndle == null) { qsRsrcs.JobStore.ReleaseAcquiredTrigger(trigger); continue; } // TODO: improvements: // // 2- make sure we can get a job runshell before firing trigger, or // don't let that throw an exception (right now it never does, // but the signature says it can). // 3- acquire more triggers at a time (based on num threads available?) JobRunShell shell = null; try { shell = qsRsrcs.JobRunShellFactory.CreateJobRunShell(bndle); shell.Initialize(qs); } catch (SchedulerException) { qsRsrcs.JobStore.TriggeredJobComplete(trigger, bndle.JobDetail, SchedulerInstruction.SetAllJobTriggersError); continue; } if (qsRsrcs.ThreadPool.RunInThread(shell) == false) { // this case should never happen, as it is indicative of the // scheduler being shutdown or a bug in the thread pool or // a thread pool being used concurrently - which the docs // say not to do... Log.Error("ThreadPool.runInThread() return false!"); qsRsrcs.JobStore.TriggeredJobComplete(trigger, bndle.JobDetail, SchedulerInstruction.SetAllJobTriggersError); } } continue; // while (!halted) } } else // if(availThreadCount > 0) { // should never happen, if threadPool.blockForAvailableThreads() follows contract continue; // while (!halted) } DateTimeOffset utcNow = SystemTime.UtcNow(); DateTimeOffset waitTime = utcNow.Add(GetRandomizedIdleWaitTime()); TimeSpan timeUntilContinue = waitTime - utcNow; lock (sigLock) { if (!halted) { try { // QTZ-336 A job might have been completed in the mean time and we might have // missed the scheduled changed signal by not waiting for the notify() yet // Check that before waiting for too long in case this very job needs to be // scheduled very soon if (!IsScheduleChanged()) { Monitor.Wait(sigLock, timeUntilContinue); } } catch (ThreadInterruptedException) { } } } } catch (Exception re) { if (Log != null) { Log.Error("Runtime error occurred in main trigger firing loop.", re); } } } // while (!halted) // drop references to scheduler stuff to aid garbage collection... qs = null; qsRsrcs = null; }
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> /// Return a date with time of day reset to this object values. The millisecond value will be zero. /// </summary> /// <param name="dateTime"></param> public DateTimeOffset? GetTimeOfDayForDate(DateTimeOffset? dateTime) { if (dateTime == null) { return null; } DateTimeOffset cal = new DateTimeOffset(dateTime.Value.Date, dateTime.Value.Offset); TimeSpan t = new TimeSpan(0, hour, minute, second); return cal.Add(t); }
/// <summary> /// Calculate and set the EndTimeOfDay using count, interval and StarTimeOfDay. This means /// that these must be set before this method is call. /// </summary> /// <param name="count"></param> /// <returns>the updated DailyTimeIntervalScheduleBuilder</returns> public DailyTimeIntervalScheduleBuilder EndingDailyAfterCount(int count) { if (count <= 0) { throw new ArgumentException("Ending daily after count must be a positive number!"); } if (startTimeOfDayUtc == null) { throw new ArgumentException("You must set the StartDailyAt() before calling this EndingDailyAfterCount()!"); } DateTimeOffset today = SystemTime.UtcNow(); DateTimeOffset startTimeOfDayDate = startTimeOfDayUtc.GetTimeOfDayForDate(today).Value; DateTimeOffset maxEndTimeOfDayDate = TimeOfDay.HourMinuteAndSecondOfDay(23, 59, 59).GetTimeOfDayForDate(today).Value; //apply proper offsets according to timezone TimeZoneInfo targetTimeZone = timeZone ?? TimeZoneInfo.Local; startTimeOfDayDate = new DateTimeOffset(startTimeOfDayDate.DateTime, TimeZoneUtil.GetUtcOffset(startTimeOfDayDate.DateTime, targetTimeZone)); maxEndTimeOfDayDate = new DateTimeOffset(maxEndTimeOfDayDate.DateTime, TimeZoneUtil.GetUtcOffset(maxEndTimeOfDayDate.DateTime, targetTimeZone)); TimeSpan remainingMillisInDay = maxEndTimeOfDayDate - startTimeOfDayDate; TimeSpan intervalInMillis; if (intervalUnit == IntervalUnit.Second) { intervalInMillis = TimeSpan.FromSeconds(interval); } else if (intervalUnit == IntervalUnit.Minute) { intervalInMillis = TimeSpan.FromMinutes(interval); } else if (intervalUnit == IntervalUnit.Hour) { intervalInMillis = TimeSpan.FromHours(interval); } else { throw new ArgumentException("The IntervalUnit: " + intervalUnit + " is invalid for this trigger."); } if (remainingMillisInDay < intervalInMillis) { throw new ArgumentException("The startTimeOfDay is too late with given Interval and IntervalUnit values."); } long maxNumOfCount = (remainingMillisInDay.Ticks / intervalInMillis.Ticks); if (count > maxNumOfCount) { throw new ArgumentException("The given count " + count + " is too large! The max you can set is " + maxNumOfCount); } TimeSpan incrementInMillis = TimeSpan.FromTicks((count - 1) * intervalInMillis.Ticks); DateTimeOffset endTimeOfDayDate = startTimeOfDayDate.Add(incrementInMillis); if (endTimeOfDayDate > maxEndTimeOfDayDate) { throw new ArgumentException("The given count " + count + " is too large! The max you can set is " + maxNumOfCount); } DateTime cal = SystemTime.UtcNow().Date; cal = cal.Add(endTimeOfDayDate.TimeOfDay); endTimeOfDayUtc = TimeOfDay.HourMinuteAndSecondOfDay(cal.Hour, cal.Minute, cal.Second); return(this); }
public static DateTimeOffset ToLocalTime(DateTimeOffset date) { TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now); return date.Add(offset).AddHours(BlogSettings.Instance.Timezone); }
public static DateTimeOffset DateTimeNear(DateTimeOffset value, TimeSpan?tolerance) { var actualTolerance = tolerance ?? DefaultDateTimeTolerance; return(ValueInRange(value.Subtract(actualTolerance), value.Add(actualTolerance))); }
public DateTimeOffsetRange(DateTimeOffset start, TimeSpan duration) : this(start, start.Add(duration)) { }
private void TimerEventAsync(object target) { //remove previously created timers var ret = ConversationStarter.Timers[me.conversationId + me.channelId]; if (ret != tAlert.GetHashCode()) { tAlert.Dispose(); return; } if (StartAlert.Add(alert.MaxTime) <= DateTimeOffset.Now) { tAlert.Dispose(); ConversationStarter.EndAlerts(me.conversationId, me.channelId); } if (NumberAlerts > AlertMaxNumber) { tAlert.Dispose(); ConversationStarter.EndAlertsMax(me.conversationId, me.channelId); } Electricity res = null; float consumption = 0; if (alert.IsInstant) { var t = myWivaldy.GetMeasures(DateTimeOffset.Now.Add(-alert.Interval), DateTimeOffset.Now); t.Wait(); res = t.Result; if (res != null) { foreach (var wat in res.Consumptions) { if (wat.watts >= alert.Threshold) { if (consumption < wat.watts) { consumption = wat.watts; } } } } } else { DateTimeOffset today = new DateTimeOffset(DateTimeOffset.Now.Year, DateTimeOffset.Now.Month, DateTimeOffset.Now.Day, 0, 0, 0, DateTimeOffset.Now.Offset); var t = myWivaldy.GetDayMeasures(today); t.Wait(); res = t.Result; if (res != null) { var cons = GetKiloWattHour(res); if (cons >= alert.Threshold) { consumption = (float)cons; } } } if (consumption > 0) { NumberAlerts++; ConversationStarter.Resume(me.conversationId, me.channelId, consumption, alert); } }
/// <summary> /// The main processing loop of the <see cref="QuartzSchedulerThread" />. /// </summary> public async Task Run() { int acquiresFailed = 0; Context.CallerId.Value = Guid.NewGuid(); while (!halted) { cancellationTokenSource.Token.ThrowIfCancellationRequested(); try { // check if we're supposed to pause... lock (sigLock) { while (paused && !halted) { try { // wait until togglePause(false) is called... Monitor.Wait(sigLock, 1000); } catch (ThreadInterruptedException) { } // reset failure counter when paused, so that we don't // wait again after unpausing acquiresFailed = 0; } if (halted) { break; } } // wait a bit, if reading from job store is consistently // failing (e.g. DB is down or restarting).. if (acquiresFailed > 1) { try { var delay = ComputeDelayForRepeatedErrors(qsRsrcs.JobStore, acquiresFailed); await Task.Delay(delay).ConfigureAwait(false); } catch { } } cancellationTokenSource.Token.ThrowIfCancellationRequested(); int availThreadCount = qsRsrcs.ThreadPool.BlockForAvailableThreads(); if (availThreadCount > 0) { List <IOperableTrigger> triggers; DateTimeOffset now = SystemTime.UtcNow(); ClearSignaledSchedulingChange(); try { var noLaterThan = now + idleWaitTime; var maxCount = Math.Min(availThreadCount, qsRsrcs.MaxBatchSize); triggers = new List <IOperableTrigger>(await qsRsrcs.JobStore.AcquireNextTriggers(noLaterThan, maxCount, qsRsrcs.BatchTimeWindow, CancellationToken.None).ConfigureAwait(false)); acquiresFailed = 0; if (Log.IsDebugEnabled()) { Log.DebugFormat("Batch acquisition of {0} triggers", triggers?.Count ?? 0); } } catch (JobPersistenceException jpe) { if (acquiresFailed == 0) { var msg = "An error occurred while scanning for the next trigger to fire."; await qs.NotifySchedulerListenersError(msg, jpe, CancellationToken.None).ConfigureAwait(false); } if (acquiresFailed < int.MaxValue) { acquiresFailed++; } continue; } catch (Exception e) { if (acquiresFailed == 0) { Log.ErrorException("quartzSchedulerThreadLoop: RuntimeException " + e.Message, e); } if (acquiresFailed < int.MaxValue) { acquiresFailed++; } continue; } if (triggers != null && triggers.Count > 0) { now = SystemTime.UtcNow(); DateTimeOffset triggerTime = triggers[0].GetNextFireTimeUtc() !.Value; TimeSpan timeUntilTrigger = triggerTime - now; while (timeUntilTrigger > TimeSpan.Zero) { if (await ReleaseIfScheduleChangedSignificantly(triggers, triggerTime).ConfigureAwait(false)) { break; } lock (sigLock) { if (halted) { break; } if (!IsCandidateNewTimeEarlierWithinReason(triggerTime, false)) { try { // we could have blocked a long while // on 'synchronize', so we must recompute now = SystemTime.UtcNow(); timeUntilTrigger = triggerTime - now; if (timeUntilTrigger > TimeSpan.Zero) { Monitor.Wait(sigLock, timeUntilTrigger); } } catch (ThreadInterruptedException) { } } } if (await ReleaseIfScheduleChangedSignificantly(triggers, triggerTime).ConfigureAwait(false)) { break; } now = SystemTime.UtcNow(); timeUntilTrigger = triggerTime - now; } // this happens if releaseIfScheduleChangedSignificantly decided to release triggers if (triggers.Count == 0) { continue; } // set triggers to 'executing' List <TriggerFiredResult> bndles = new List <TriggerFiredResult>(); bool goAhead; lock (sigLock) { goAhead = !halted; } if (goAhead) { try { var res = await qsRsrcs.JobStore.TriggersFired(triggers, CancellationToken.None).ConfigureAwait(false); if (res != null) { bndles = res.ToList(); } } catch (SchedulerException se) { var msg = "An error occurred while firing triggers '" + triggers + "'"; await qs.NotifySchedulerListenersError(msg, se, CancellationToken.None).ConfigureAwait(false); // QTZ-179 : a problem occurred interacting with the triggers from the db // we release them and loop again foreach (IOperableTrigger t in triggers) { await qsRsrcs.JobStore.ReleaseAcquiredTrigger(t, CancellationToken.None).ConfigureAwait(false); } continue; } } for (int i = 0; i < bndles.Count; i++) { TriggerFiredResult result = bndles[i]; var bndle = result.TriggerFiredBundle; var exception = result.Exception; IOperableTrigger trigger = triggers[i]; // TODO SQL exception? if (exception != null && (exception is DbException || exception.InnerException is DbException)) { Log.ErrorException("DbException while firing trigger " + trigger, exception); await qsRsrcs.JobStore.ReleaseAcquiredTrigger(trigger, CancellationToken.None).ConfigureAwait(false); continue; } // it's possible to get 'null' if the triggers was paused, // blocked, or other similar occurrences that prevent it being // fired at this time... or if the scheduler was shutdown (halted) if (bndle == null) { await qsRsrcs.JobStore.ReleaseAcquiredTrigger(trigger, CancellationToken.None).ConfigureAwait(false); continue; } // TODO: improvements: // // 2- make sure we can get a job runshell before firing trigger, or // don't let that throw an exception (right now it never does, // but the signature says it can). // 3- acquire more triggers at a time (based on num threads available?) JobRunShell shell; try { shell = qsRsrcs.JobRunShellFactory.CreateJobRunShell(bndle); await shell.Initialize(qs, CancellationToken.None).ConfigureAwait(false); } catch (SchedulerException) { await qsRsrcs.JobStore.TriggeredJobComplete(trigger, bndle.JobDetail, SchedulerInstruction.SetAllJobTriggersError, CancellationToken.None).ConfigureAwait(false); continue; } var threadPoolRunResult = qsRsrcs.ThreadPool.RunInThread(() => shell.Run(CancellationToken.None)); if (threadPoolRunResult == false) { // this case should never happen, as it is indicative of the // scheduler being shutdown or a bug in the thread pool or // a thread pool being used concurrently - which the docs // say not to do... Log.Error("ThreadPool.RunInThread() returned false!"); await qsRsrcs.JobStore.TriggeredJobComplete(trigger, bndle.JobDetail, SchedulerInstruction.SetAllJobTriggersError, CancellationToken.None).ConfigureAwait(false); } } continue; // while (!halted) } } else // if(availThreadCount > 0) { continue; // while (!halted) } DateTimeOffset utcNow = SystemTime.UtcNow(); DateTimeOffset waitTime = utcNow.Add(GetRandomizedIdleWaitTime()); TimeSpan timeUntilContinue = waitTime - utcNow; lock (sigLock) { if (!halted) { try { // QTZ-336 A job might have been completed in the mean time and we might have // missed the scheduled changed signal by not waiting for the notify() yet // Check that before waiting for too long in case this very job needs to be // scheduled very soon if (!IsScheduleChanged()) { Monitor.Wait(sigLock, timeUntilContinue); } } catch (ThreadInterruptedException) { } } } } catch (Exception re) { Log.ErrorException("Runtime error occurred in main trigger firing loop.", re); } } // while (!halted) }
/// <summary> /// The main processing loop of the <see cref="QuartzSchedulerThread" />. /// </summary> public async Task Run() { Log.LogInformation("QuartzSchedulerThread Run"); int acquiresFailed = 0; //Context.CallerId.Value = Guid.NewGuid(); while (!halted) { cancellationTokenSource.Token.ThrowIfCancellationRequested(); try { // check if we're supposed to pause... lock (sigLock) { var fst = true; while (paused && !halted) { if (fst) { Log.LogInformation("QuartzSchedulerThread Run is paused"); fst = false; } try { // wait until togglePause(false) is called... Monitor.Wait(sigLock, 1000); } catch (ThreadInterruptedException) { } // reset failure counter when paused, so that we don't // wait again after unpausing acquiresFailed = 0; } if (!fst && !halted) { Log.LogInformation("QuartzSchedulerThread Run is unpaused"); } if (halted) { Log.LogInformation("QuartzSchedulerThread Run is halted"); break; } } cancellationTokenSource.Token.ThrowIfCancellationRequested(); bool goAhead; lock (sigLock) { goAhead = !halted; } if (goAhead) { try { await Core.Instance.TriggerAsync(); //Fire triggers here } catch (Exception se) { Log.LogError(se, se.ToString()); } } DateTimeOffset utcNow = DateTime.Now; DateTimeOffset waitTime = utcNow.Add(GetRandomizedIdleWaitTime()); TimeSpan timeUntilContinue = waitTime - utcNow; lock (sigLock) { if (!halted) { try { Monitor.Wait(sigLock, timeUntilContinue); } catch (ThreadInterruptedException) { } } } } catch (Exception re) { Log.LogError(re, "Runtime error occurred in main trigger firing loop."); } } // while (!halted) }
private async Task WaitForLeaseAsync(CancellationToken cancellationToken) { await _semaphore?.WaitAsync(cancellationToken); do { TimeSpan?waitTime = null; lock (SyncLock) { DateTimeOffset now = DateTimeOffset.Now; if (Settings.WaitTimeBetweenLease != null) { DateTimeOffset?nextAllowedTime = null; switch (Settings.WaitStrategy) { case ThrottleWaitStrategy.FromStartOfLastRequest: if (_lastStartTime > 0) { nextAllowedTime = DateTimeOffset.FromUnixTimeMilliseconds(_lastStartTime); } break; case ThrottleWaitStrategy.FromEndOfLastRequest: if (_lastFinishTime > 0) { nextAllowedTime = DateTimeOffset.FromUnixTimeMilliseconds(_lastFinishTime); } break; case ThrottleWaitStrategy.SlidingWindow: case ThrottleWaitStrategy.TumblingWindow: int requestCount = SyncCountAndWindowUnsafe(out DateTimeOffset periodWindow); if (requestCount >= Settings.MaxRequests) { nextAllowedTime = periodWindow; } break; default: throw new NotSupportedException($"{Settings.WaitStrategy} is not supported."); } if (nextAllowedTime != null) { nextAllowedTime = nextAllowedTime?.Add(Settings.WaitTimeBetweenLease.Value); if (nextAllowedTime > now) { waitTime = nextAllowedTime.Value - now; } } } if (waitTime == null) { _activeThreads++; _lastStartTime = now.ToUnixTimeMilliseconds(); if (_requests != null) { _requests.Add(_lastStartTime); } break; } } try { await Task.Delay(waitTime.Value, cancellationToken); } catch { cancellationToken.ThrowIfCancellationRequested(); } }while (!cancellationToken.IsCancellationRequested); }
protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationTicket ticket = null; try { string cookie = Options.CookieManager.GetRequestCookie(Context, Options.CookieName); if (string.IsNullOrWhiteSpace(cookie)) { return(null); } ticket = Options.TicketDataFormat.Unprotect(cookie); if (ticket == null) { _logger.WriteWarning(@"Unprotect ticket failed"); return(null); } if (Options.SessionStore != null) { Claim claim = ticket.Identity.Claims.FirstOrDefault(c => c.Type.Equals(SessionIdClaim)); if (claim == null) { _logger.WriteWarning(@"SessionId missing"); return(null); } _sessionKey = claim.Value; ticket = await Options.SessionStore.RetrieveAsync(_sessionKey); if (ticket == null) { _logger.WriteWarning(@"Identity missing in session store"); return(null); } } DateTimeOffset currentUtc = Options.SystemClock.UtcNow; DateTimeOffset?issuedUtc = ticket.Properties.IssuedUtc; DateTimeOffset?expiresUtc = ticket.Properties.ExpiresUtc; if (expiresUtc != null && expiresUtc.Value < currentUtc) { if (Options.SessionStore != null) { await Options.SessionStore.RemoveAsync(_sessionKey); } return(null); } bool?allowRefresh = ticket.Properties.AllowRefresh; if (issuedUtc != null && expiresUtc != null && Options.SlidingExpiration && (!allowRefresh.HasValue || allowRefresh.Value)) { TimeSpan timeElapsed = currentUtc.Subtract(issuedUtc.Value); TimeSpan timeRemaining = expiresUtc.Value.Subtract(currentUtc); if (timeRemaining < timeElapsed) { _shouldRenew = true; _renewIssuedUtc = currentUtc; TimeSpan timeSpan = expiresUtc.Value.Subtract(issuedUtc.Value); _renewExpiresUtc = currentUtc.Add(timeSpan); } } var context = new CookieValidateIdentityContext(Context, ticket, Options); await Options.Provider.ValidateIdentity(context); if (context.Identity == null) { // Rejected _shouldRenew = false; return(null); } return(new AuthenticationTicket(context.Identity, context.Properties)); } catch (Exception exception) { CookieExceptionContext exceptionContext = new CookieExceptionContext(Context, Options, CookieExceptionContext.ExceptionLocation.AuthenticateAsync, exception, ticket); Options.Provider.Exception(exceptionContext); if (exceptionContext.Rethrow) { throw; } return(exceptionContext.Ticket); } }
/// <summary> /// Get a handle to the next trigger to be fired, and mark it as 'reserved' /// by the calling scheduler. /// </summary> /// <param name="noLaterThan">If > 0, the JobStore should only return a Trigger /// that will fire no later than the time represented in this value as /// milliseconds.</param><param name="maxCount"/><param name="timeWindow"/> /// <returns/> /// <seealso cref="T:Quartz.ITrigger"/> public IList<IOperableTrigger> AcquireNextTriggers(DateTimeOffset noLaterThan, int maxCount, TimeSpan timeWindow) { ReleaseTriggers(); var triggers = new List<IOperableTrigger>(); bool retry = false; do { var acquiredJobHashKeysForNoConcurrentExec = new global::Quartz.Collection.HashSet<string>(); var score = ToUnixTimeMilliseconds(noLaterThan.Add(timeWindow)); var waitingStateTriggers = Db.SortedSetRangeByScoreWithScores( RedisJobStoreSchema.TriggerStateSetKey(RedisTriggerState.Waiting), 0, score, Exclude.None, Order.Ascending, 0, maxCount); foreach (var sortedSetEntry in waitingStateTriggers) { var trigger = RetrieveTrigger(RedisJobStoreSchema.TriggerKey(sortedSetEntry.Element)); if (ApplyMisfire(trigger)) { retry = true; break; } if (trigger.GetNextFireTimeUtc() == null) { this.UnsetTriggerState(sortedSetEntry.Element); continue; } var jobHashKey = RedisJobStoreSchema.JobHashKey(trigger.JobKey); var job = RetrieveJob(trigger.JobKey); if (job != null && job.ConcurrentExecutionDisallowed) { if (acquiredJobHashKeysForNoConcurrentExec.Contains(jobHashKey)) { continue; } acquiredJobHashKeysForNoConcurrentExec.Add(jobHashKey); } LockTrigger(trigger.Key); SetTriggerState(RedisTriggerState.Acquired, sortedSetEntry.Score, sortedSetEntry.Element); triggers.Add(trigger); } } while (retry); return triggers; }
public VirtuosoDateTimeOffset Add(TimeSpan ts) { return(new VirtuosoDateTimeOffset(value.Add(ts))); }
public static void Add_TimeSpan(DateTimeOffset dateTimeOffset, TimeSpan timeSpan, DateTimeOffset expected) { Assert.Equal(expected, dateTimeOffset.Add(timeSpan)); Assert.Equal(expected, dateTimeOffset + timeSpan); }
public static object ChangeType(object value, Type type) { if (value == null) { return(null); } MethodInfo mi; #warning [FB] REFACTOR: TYPE OBTAINED FROM SQLCLIENT. WILL CAUSE CONFLICTS WHEN OTHER DBs ARE ADDED. Type toType = TypeSystem.GetNonNullableType(type); Type fromType = value.GetType(); if (toType.IsAssignableFrom(fromType)) { return(value); } if (toType == typeof(Binary)) { if (fromType == typeof(byte[])) { return(new Binary((byte[])value)); } else if (fromType == typeof(Guid)) { return(new Binary(((Guid)value).ToByteArray())); } else { BinaryFormatter formatter = new BinaryFormatter(); byte[] streamArray; using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, value); streamArray = stream.ToArray(); } return(new Binary(streamArray)); } } else if (toType == typeof(byte[])) { if (fromType == typeof(Binary)) { return(((Binary)value).ToArray()); } else if (fromType == typeof(Guid)) { return(((Guid)value).ToByteArray()); } else { BinaryFormatter formatter = new BinaryFormatter(); byte[] returnValue; using (MemoryStream stream = new MemoryStream()) { formatter.Serialize(stream, value); returnValue = stream.ToArray(); } return(returnValue); } } else if (fromType == typeof(byte[])) { if (toType == typeof(Guid)) { return(new Guid((byte[])value)); } else { BinaryFormatter formatter = new BinaryFormatter(); object returnValue; using (MemoryStream stream = new MemoryStream((byte[])value)) { returnValue = ChangeType(formatter.Deserialize(stream), toType); } return(returnValue); } } else if (fromType == typeof(Binary)) { if (toType == typeof(Guid)) { return(new Guid(((Binary)value).ToArray())); } else { BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream stream = new MemoryStream(((Binary)value).ToArray(), false)) { return(ChangeType(formatter.Deserialize(stream), toType)); } } } else if (toType.IsEnum) { if (fromType == typeof(string)) { string text = ((string)value).Trim(); return(Enum.Parse(toType, text)); } else { return(Enum.ToObject(toType, Convert.ChangeType(value, Enum.GetUnderlyingType(toType), Globalization.CultureInfo.InvariantCulture))); } } else if (fromType.IsEnum) { if (toType == typeof(string)) { return(Enum.GetName(fromType, value)); } else { return(Convert.ChangeType(Convert.ChangeType(value, Enum.GetUnderlyingType(fromType), Globalization.CultureInfo.InvariantCulture), toType, Globalization.CultureInfo.InvariantCulture)); } } else if (toType == typeof(TimeSpan)) { if (fromType == typeof(string)) { return(TimeSpan.Parse(value.ToString(), Globalization.CultureInfo.InvariantCulture)); } else if (fromType == typeof(DateTime)) { return(DateTime.Parse(value.ToString(), Globalization.CultureInfo.InvariantCulture).TimeOfDay); } else if (fromType == typeof(DateTimeOffset)) { return(DateTimeOffset.Parse(value.ToString(), Globalization.CultureInfo.InvariantCulture).TimeOfDay); } else { return(new TimeSpan((long)Convert.ChangeType(value, typeof(long), Globalization.CultureInfo.InvariantCulture))); } } else if (fromType == typeof(TimeSpan)) { if (toType == typeof(string)) { return(((TimeSpan)value).ToString("", Globalization.CultureInfo.InvariantCulture)); } else if (toType == typeof(DateTime)) { DateTime dt = new DateTime(); return(dt.Add((TimeSpan)value)); } else if (toType == typeof(DateTimeOffset)) { DateTimeOffset dto = new DateTimeOffset(); return(dto.Add((TimeSpan)value)); } else { return(Convert.ChangeType(((TimeSpan)value).Ticks, toType, Globalization.CultureInfo.InvariantCulture)); } } else if (toType == typeof(DateTime) && fromType == typeof(DateTimeOffset)) { return(((DateTimeOffset)value).DateTime); } else if (toType == typeof(DateTimeOffset) && fromType == typeof(DateTime)) { return(new DateTimeOffset((DateTime)value)); } else if (toType == typeof(string) && !(typeof(IConvertible).IsAssignableFrom(fromType))) { if (fromType == typeof(char[])) { return(new String((char[])value)); } else { return(value.ToString()); } } else if (fromType == typeof(string)) { if (toType == typeof(Guid)) { return(new Guid((string)value)); } else if (toType == typeof(char[])) { return(((String)value).ToCharArray()); } else if (toType == typeof(System.Xml.Linq.XDocument) && (string)value == string.Empty) { return(new System.Xml.Linq.XDocument()); } // [JA] - fixed bug where empty XML column throws an exception else if (toType == typeof(System.Xml.Linq.XElement) && (string)value == string.Empty) { return(null); } else if (!(typeof(IConvertible).IsAssignableFrom(toType)) && (mi = toType.GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, StringArg, null)) != null) { try { return(SecurityUtils.MethodInfoInvoke(mi, null, new object[] { value })); } catch (TargetInvocationException t) { throw t.GetBaseException(); } } else { return(Convert.ChangeType(value, toType, Globalization.CultureInfo.InvariantCulture)); } } else if (toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(IQueryable <>) && typeof(IEnumerable <>).MakeGenericType(toType.GetGenericArguments()[0]).IsAssignableFrom(fromType) ) { return(Queryable.AsQueryable((IEnumerable)value)); } else { try { return(Convert.ChangeType(value, toType, Globalization.CultureInfo.InvariantCulture)); } catch (InvalidCastException) { throw Error.CouldNotConvert(fromType, toType); } } }
public void GetUtcOffset_FromDateTimeOffset () { DateTimeOffset offset; offset = new DateTimeOffset(dst1Start, baseUtcOffset); Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, -1))), "dst1Start_with_baseUtcOffset#before"); Assert.AreEqual(dstUtcOffset, cairo.GetUtcOffset(offset), "dst1Start_with_baseUtcOffset#exact"); Assert.AreEqual(dstUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, 1))), "dst1Start_with_baseUtcOffset#after"); offset = new DateTimeOffset(dst1End, dstOffset + baseUtcOffset); Assert.AreEqual(dstUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, -1))), "dst1End_with_dstOffset+baseUtcOffset#before"); Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset(offset), "dst1End_with_dstOffset+baseUtcOffset#exact"); Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, 1))), "dst1End_with_dstOffset+baseUtcOffset#after"); offset = new DateTimeOffset(dst2Start, baseUtcOffset); Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, -1))), "dst2Start_with_baseUtcOffset#before"); Assert.AreEqual(dstUtcOffset, cairo.GetUtcOffset(offset), "dst2Start_with_baseUtcOffset#exact"); Assert.AreEqual(dstUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, 1))), "dst2Start_with_baseUtcOffset#after"); offset = new DateTimeOffset(dst2End, baseUtcOffset + dstOffset); Assert.AreEqual(dstUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, -1))), "dst2End_with_dstOffset+baseUtcOffset#before"); Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset(offset), "dst2End_with_dstOffset+baseUtcOffset#exact"); Assert.AreEqual(baseUtcOffset, cairo.GetUtcOffset(offset.Add(new TimeSpan(0, 0, 0, 1))), "dst2End_with_dstOffset+baseUtcOffset#after"); }
/// <summary> /// 日程調整 /// </summary> /// <param name="requestCountryDateTimeOffset">施設側タイムゾーンの日時</param> /// <param name="requestTimeSpan">予約時間</param> /// <returns></returns> private DateTimeOffset ScheduleAdjustment(DateTimeOffset requestCountryDateTimeOffset, TimeSpan requestTimeSpan) { //開業時間と曜日 List <OpeningDays> openingDays = new List <OpeningDays> { new OpeningDays(9, 17, DayOfWeek.Monday) , new OpeningDays(9, 17, DayOfWeek.Tuesday) , new OpeningDays(9, 12, DayOfWeek.Wednesday) , new OpeningDays(9, 17, DayOfWeek.Thursday) , new OpeningDays(13, 20, DayOfWeek.Friday) }; int whereCount; OpeningDays selectedDays = openingDays.FirstOrDefault(); bool addDayProcess = false; //リクエスト日より後の開業曜日を検索する。 do { List <OpeningDays> openings = openingDays.Where(d => d.OpeningWeek == requestCountryDateTimeOffset.DayOfWeek) .ToList <OpeningDays>(); whereCount = openings.Count(); if (whereCount == 0) { //開業曜日に含まれない場合、一日追加する。 requestCountryDateTimeOffset = requestCountryDateTimeOffset.AddDays(1.0); } else if (addDayProcess == true) { selectedDays = openings.FirstOrDefault(); //リクエスト日の終了時間が遅すぎる場合、営業時間の最も遅い時間に、時間を早める。 TimeSpan subtractionTime = new TimeSpan( selectedDays.ClosingTime - requestCountryDateTimeOffset.Hour - requestTimeSpan.Hours, (requestTimeSpan.Minutes + requestCountryDateTimeOffset.Minute) * (-1), 0); requestCountryDateTimeOffset = requestCountryDateTimeOffset.Add(subtractionTime); addDayProcess = false; } else { //開業曜日に含まれる場合、該当の開業時間と曜日を返す。 selectedDays = openings.FirstOrDefault(); //リクエスト日の終了時間が遅すぎる場合、時間を早めて、一日追加する。 double countryMinutes = (double)requestCountryDateTimeOffset.Minute / 60.0; double durationMinutes = ((double)requestTimeSpan.Hours * 60.0 + (double)requestTimeSpan.Minutes) / 60.0; if ((double)selectedDays.ClosingTime < ((double)requestCountryDateTimeOffset.Hour + countryMinutes + durationMinutes) ) { requestCountryDateTimeOffset = requestCountryDateTimeOffset.AddDays(1.0); addDayProcess = true; whereCount = 0; } } }while (whereCount == 0); //リクエスト日の開始時間が早すぎる場合、開始時間に変更する。 if (requestCountryDateTimeOffset.Hour < selectedDays.OpeningTime) { requestCountryDateTimeOffset = requestCountryDateTimeOffset.AddHours(selectedDays.OpeningTime - requestCountryDateTimeOffset.Hour); requestCountryDateTimeOffset = requestCountryDateTimeOffset.AddMinutes(requestCountryDateTimeOffset.Minute * -1); } return(requestCountryDateTimeOffset); }
private Epoch RunSingleEpoch(double sampleRate, int nChannels, IEpochPersistor epochPersistor) { Epoch e; IExternalDevice dev0; RenderedStimulus stim1; IExternalDevice dev1; RenderedStimulus stim2; IList<IMeasurement> stimData; var controller = SetupController(sampleRate, out e, out dev0, out stim1, out dev1, out stim2, out stimData, nChannels); var time = new DateTimeOffset(2011, 8, 22, 11, 12, 0, 0, TimeSpan.FromHours(-6)); var h5Persistor = epochPersistor as H5EpochPersistor; if (h5Persistor != null) { h5Persistor.BeginEpochBlock(e.ProtocolID, e.ProtocolParameters, time); } else { epochPersistor.BeginEpochBlock(e.ProtocolID, e.ProtocolParameters); } controller.RunEpoch(e, epochPersistor); if (h5Persistor != null) { h5Persistor.EndEpochBlock(time.Add(e.Duration)); } else { epochPersistor.EndEpochBlock(); } Assert.AreEqual((TimeSpan)stim1.Duration, e.Responses[dev0].Duration); if (nChannels > 1) Assert.AreEqual((TimeSpan)stim2.Duration, e.Responses[dev1].Duration); var inputData = e.Responses[dev0].Data; const double MAX_VOLTAGE_DIFF = 0.001; int failures = inputData.Select((t, i) => t.QuantityInBaseUnits - stimData[i].QuantityInBaseUnits) .Count(dif => Math.Abs(dif) > (decimal) MAX_VOLTAGE_DIFF); Assert.AreEqual(0, failures); return e; }
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; }