/// <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);
        }
Example #2
0
        public void AdvanceTo(DateTimeOffset when)
        {
            if (when < _now)
                throw new InvalidOperationException("You can't reverse time...");

            Advance(when.Subtract(_now));
        }
Example #3
0
 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 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;
        }
Example #5
0
        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 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 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));
 }
Example #11
0
 public static void Subtract_DateTimeOffset(DateTimeOffset dt1, DateTimeOffset dt2, TimeSpan expected)
 {
     Assert.Equal(expected, dt1 - dt2);
     Assert.Equal(expected, dt1.Subtract(dt2));
 }
Example #12
0
 public static void Subtract_TimeSpan(DateTimeOffset dt, TimeSpan ts, DateTimeOffset expected)
 {
     Assert.Equal(expected, dt - ts);
     Assert.Equal(expected, dt.Subtract(ts));
 }
 public static long ToUnixTimeStamp(DateTimeOffset dateTime)
 {
     var ts = dateTime.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
     return (long)ts;
 }
 private DateTimeOffset CleanOffset(DateTimeOffset offset)
 {
     offset = offset.Subtract(TimeSpan.FromMilliseconds(offset.Millisecond));
     return offset.Subtract(TimeSpan.FromSeconds(offset.Second));
 }
Example #15
0
    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);
    }
Example #16
0
		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 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
        }
Example #18
0
        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);
        }
 /// <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);
 }
Example #20
0
        /// <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;
        }
        public static void ForwardTimeUntil(DateTimeOffset startTime, DateTimeOffset dateTime, TimeSpan timeout)
        {
            var dueTime = GetDueTime(dateTime.Subtract(startTime));

            WaitOnTimer(dueTime, timeout);
        }
Example #23
0
 public static void IsNear(DateTimeOffset expected, DateTimeOffset actual, TimeSpan threshold)
 {
     IsWithinThreshold(expected.Subtract(actual), threshold);
 }
Example #24
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));
		}
Example #25
0
 /// <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);
 }
Example #26
0
		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());
		}
Example #27
0
        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);
        }
Example #28
0
 //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);
 }
Example #29
0
 public static void IsAfter(DateTimeOffset expected, DateTimeOffset actual)
 {
     TimeSpan difference = actual.Subtract(expected);
     Assert.IsTrue(difference.Ticks > 0);
 }
Example #30
-1
        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;
        }