internal byte[] UnprotectCore([NotNull] byte[] protectedData, DateTimeOffset now, out DateTimeOffset expiration)
        {
            try
            {
                byte[] plaintextWithHeader = GetInnerProtectorWithTimeLimitedPurpose().Unprotect(protectedData);
                if (plaintextWithHeader.Length < 8)
                {
                    // header isn't present
                    throw new CryptographicException(Resources.TimeLimitedDataProtector_PayloadInvalid);
                }

                // Read expiration time back out of the payload
                ulong utcTicksExpiration = BitHelpers.ReadUInt64(plaintextWithHeader, 0);
                DateTimeOffset embeddedExpiration = new DateTimeOffset(checked((long)utcTicksExpiration), TimeSpan.Zero /* UTC */);

                // Are we expired?
                if (now > embeddedExpiration)
                {
                    throw new CryptographicException(Resources.FormatTimeLimitedDataProtector_PayloadExpired(embeddedExpiration));
                }

                // Not expired - split and return payload
                byte[] retVal = new byte[plaintextWithHeader.Length - 8];
                Buffer.BlockCopy(plaintextWithHeader, 8, retVal, 0, retVal.Length);
                expiration = new DateTimeOffset((long)utcTicksExpiration, TimeSpan.Zero);
                return retVal;
            }
            catch (Exception ex) when (ex.RequiresHomogenization())
            {
                // Homogenize all failures to CryptographicException
                throw new CryptographicException(Resources.CryptCommon_GenericError, ex);
            }
        }
Esempio n. 2
0
 public AccelerometerDatum(DateTimeOffset timestamp, double x, double y, double z)
     : base(timestamp)
 {
     _x = x;
     _y = y;
     _z = z;
 }
Esempio n. 3
0
        public ActivityViewModel(Activity activity)
        {
            Id = activity.Id;
            if (activity.Campaign != null)
            {
                CampaignId = activity.Campaign.Id;
                CampaignName = activity.Campaign.Name;
            }

            Title = activity.Name;
            Description = activity.Description;

            StartDateTime = new DateTimeOffset(activity.StartDateTimeUtc, TimeSpan.Zero);
            EndDateTime = new DateTimeOffset(activity.EndDateTimeUtc, TimeSpan.Zero);

            if (activity.Location != null)
            {
                Location = new LocationViewModel(activity.Location);
            }

            ImageUrl = activity.ImageUrl;

            //TODO Location
            Tasks = activity.Tasks != null
                 ? new List<TaskViewModel>(activity.Tasks.Select(data => new TaskViewModel(data)).OrderBy(task => task.StartDateTime))
                 : new List<TaskViewModel>();

            RequiredSkills = activity.RequiredSkills?.Select(acsk => acsk.Skill).ToList();
        }
        /// <summary>
        /// Determine the next time (in milliseconds) that is 'included' by the
        /// Calendar after the given time. Return the original value if timeStamp is
        /// included. Return DateTime.MinValue if all days are excluded.
        /// <para>
        /// Note that this Calendar is only has full-day precision.
        /// </para>
        /// </summary>
        /// <param name="timeUtc"></param>
        /// <returns></returns>
        public override DateTimeOffset GetNextIncludedTimeUtc(DateTimeOffset timeUtc)
        {
            if (base.AreAllDaysExcluded())
            {
                return DateTime.MinValue;
            }

            // Call base calendar implementation first
            DateTimeOffset baseTime = base.GetNextIncludedTimeUtc(timeUtc);
            if ((baseTime != DateTimeOffset.MinValue) && (baseTime > timeUtc))
            {
                timeUtc = baseTime;
            }

            // Get timestamp for 00:00:00
            //DateTime d = timeUtc.Date;   --commented out for local time impl
            DateTime d = timeUtc.ToLocalTime().Date;

            if (!IsDayExcluded(d.DayOfWeek))
            {
                return timeUtc;
            } // return the original value

            while (IsDayExcluded(d.DayOfWeek))
            {
                d = d.AddDays(1);
            }

            return d;
        }
        public void IndexDecider_EndsUpInTheOutput()
        {
            //DO NOTE that you cant send objects as scalar values through Logger.*("{Scalar}", {});
            var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
            const string messageTemplate = "{Song}++ @{Complex}";
            var template = new MessageTemplateParser().Parse(messageTemplate);
            _options.IndexDecider = (l, utcTime) => string.Format("logstash-{1}-{0:yyyy.MM.dd}", utcTime, l.Level.ToString().ToLowerInvariant());
            using (var sink = new ElasticsearchSink(_options))
            {
                var properties = new List<LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) };
                var e = new LogEvent(timestamp, LogEventLevel.Information, null, template, properties);
                sink.Emit(e);
                var exception = new ArgumentException("parameter");
                properties = new List<LogEventProperty>
                {
                    new LogEventProperty("Song", new ScalarValue("Old Macabre")),
                    new LogEventProperty("Complex", new ScalarValue(new { A  = 1, B = 2}))
                };
                e = new LogEvent(timestamp.AddYears(-2), LogEventLevel.Fatal, exception, template, properties);
                sink.Emit(e);
            }

            _seenHttpPosts.Should().NotBeEmpty().And.HaveCount(1);
            var json = _seenHttpPosts.First();
            var bulkJsonPieces = json.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            bulkJsonPieces.Should().HaveCount(4);
            bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-information-2013.05.28");
            bulkJsonPieces[1].Should().Contain("New Macabre");
            bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-fatal-2011.05.28");
            bulkJsonPieces[3].Should().Contain("Old Macabre");

            //serilog by default simpy .ToString()'s unknown objects
            bulkJsonPieces[3].Should().Contain("Complex\":\"{");

        }
 /// <summary>
 /// Sets an absolute expiration date for the cache entry.
 /// </summary>
 /// <param name="options"></param>
 /// <param name="absolute"></param>
 public static DistributedCacheEntryOptions SetAbsoluteExpiration(
     this DistributedCacheEntryOptions options,
     DateTimeOffset absolute)
 {
     options.AbsoluteExpiration = absolute;
     return options;
 }
Esempio n. 7
0
		// not virtual as is called from the ctor
		protected void OnClosing(DateTimeOffset closed)
		{
			DomainEventHandler<IssueClosed> handler = Closing;
			if (handler != null) handler(this, new DomainEventEventArgs<IssueClosed>(
				new IssueClosed(Id) {  Closed = closed },
				doClose));
		}
Esempio n. 8
0
 public static DateTimeOffset ToClientTimeZone(long ticks, int zona)
 {
     var dt = new DateTime(ticks, DateTimeKind.Utc);
     var tz = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(b => b.BaseUtcOffset.Hours == zona);
     var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);
     return utcOffset.ToOffset(tz.GetUtcOffset(utcOffset));
 }
 public async Task UsesCustomPropertyNames()
 {
     try
     {
         await new HttpClient().GetStringAsync("http://i.do.not.exist");
     }
     catch (Exception e)
     {
         var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
         var messageTemplate = "{Song}++";
         var template = new MessageTemplateParser().Parse(messageTemplate);
         using (var sink = new ElasticsearchSink(_options))
         {
             var properties = new List<LogEventProperty>
             {
                 new LogEventProperty("Song", new ScalarValue("New Macabre")), 
                 new LogEventProperty("Complex", new ScalarValue(new { A = 1, B = 2 }))
             };
             var logEvent = new LogEvent(timestamp, LogEventLevel.Information, e, template, properties);
             sink.Emit(logEvent);
             logEvent = new LogEvent(timestamp.AddDays(2), LogEventLevel.Information, e, template, properties);
             sink.Emit(logEvent);
         }
         _seenHttpPosts.Should().NotBeEmpty().And.HaveCount(1);
         var json = _seenHttpPosts.First();
         var bulkJsonPieces = json.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
         bulkJsonPieces.Should().HaveCount(4);
         bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-2013.05.28");
         bulkJsonPieces[1].Should().Contain("New Macabre");
         bulkJsonPieces[1].Should().NotContain("Properties\"");
         bulkJsonPieces[1].Should().Contain("fields\":{");
         bulkJsonPieces[1].Should().Contain("@timestamp");
         bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-2013.05.30");
     }
 }
        public Task SendJoinMail(
            string receipientAddress, string clusterAddress, int userPort, TimeSpan clusterTimeRemaining, DateTimeOffset clusterExpiration,
            IEnumerable<HyperlinkView> links)
        {
            string date = String.Format("{0:MMMM dd} at {1:H:mm:ss UTC}", clusterExpiration, clusterExpiration);
            string time = String.Format("{0} hour{1}, ", clusterTimeRemaining.Hours, clusterTimeRemaining.Hours == 1 ? "" : "s")
                          + String.Format("{0} minute{1}, ", clusterTimeRemaining.Minutes, clusterTimeRemaining.Minutes == 1 ? "" : "s")
                          + String.Format("and {0} second{1}", clusterTimeRemaining.Seconds, clusterTimeRemaining.Seconds == 1 ? "" : "s");

            string linkList = String.Join(
                "",
                links.Select(
                    x =>
                        String.Format("<li><a href=\"{0}\">{1}</a> - {2}</li>", x.Address, x.Text, x.Description)));

            return this.SendMessageAsync(
                new MailAddress(this.mailAddress, this.mailFrom),
                receipientAddress,
                this.mailSubject,
                this.joinMailTemplate
                    .Replace("__clusterAddress__", clusterAddress)
                    .Replace("__userPort__", userPort.ToString())
                    .Replace("__clusterExpiration__", date)
                    .Replace("__clusterTimeRemaining__", time)
                    .Replace("__links__", linkList));
        }
Esempio n. 11
0
 public ChainedHeader(BlockHeader blockHeader, int height, BigInteger totalWork, DateTimeOffset dateSeen)
 {
     BlockHeader = blockHeader;
     Height = height;
     TotalWork = totalWork;
     DateSeen = dateSeen;
 }
        private static void InitCustomers()
        {
            DateTimeOffset dto = new DateTimeOffset(2015, 1, 1, 1, 2, 3, 4, TimeSpan.Zero);
            _customers = Enumerable.Range(1, 5).Select(e =>
                new DCustomer
                {
                    Id = e,
                    DateTime = dto.AddYears(e).DateTime,
                    Offset = e % 2 == 0 ? dto.AddMonths(e) : dto.AddDays(e).AddMilliseconds(10),
                    Date = e % 2 == 0 ? dto.AddDays(e).Date : dto.AddDays(-e).Date,
                    TimeOfDay = e % 3 == 0 ? dto.AddHours(e).TimeOfDay : dto.AddHours(-e).AddMilliseconds(10).TimeOfDay,

                    NullableDateTime = e % 2 == 0 ? (DateTime?)null : dto.AddYears(e).DateTime,
                    NullableOffset = e % 3 == 0 ? (DateTimeOffset?)null : dto.AddMonths(e),
                    NullableDate = e % 2 == 0 ? (Date?)null : dto.AddDays(e).Date,
                    NullableTimeOfDay = e % 3 == 0 ? (TimeOfDay?)null : dto.AddHours(e).TimeOfDay,

                    DateTimes = new [] { dto.AddYears(e).DateTime, dto.AddMonths(e).DateTime },
                    Offsets = new [] { dto.AddMonths(e), dto.AddDays(e) },
                    Dates = new [] { (Date)dto.AddYears(e).Date, (Date)dto.AddMonths(e).Date },
                    TimeOfDays = new [] { (TimeOfDay)dto.AddHours(e).TimeOfDay, (TimeOfDay)dto.AddMinutes(e).TimeOfDay },

                    NullableDateTimes = new [] { dto.AddYears(e).DateTime, (DateTime?)null, dto.AddMonths(e).DateTime },
                    NullableOffsets = new [] { dto.AddMonths(e), (DateTimeOffset?)null, dto.AddDays(e) },
                    NullableDates = new [] { (Date)dto.AddYears(e).Date, (Date?)null, (Date)dto.AddMonths(e).Date },
                    NullableTimeOfDays = new [] { (TimeOfDay)dto.AddHours(e).TimeOfDay, (TimeOfDay?)null, (TimeOfDay)dto.AddMinutes(e).TimeOfDay },

                }).ToList();
        }
Esempio n. 13
0
		private void Syncronize()
		{
			lock (_stopwatch) {
				_baseTime = DateTimeOffset.UtcNow;
				_stopwatch.Restart();
			}
		}
Esempio n. 14
0
		/// <summary>
		/// Subscribe to receive new candles.
		/// </summary>
		/// <param name="series">Candles series.</param>
		/// <param name="from">The initial date from which you need to get data.</param>
		/// <param name="to">The final date by which you need to get data.</param>
		public void SubscribeCandles(CandleSeries series, DateTimeOffset from, DateTimeOffset to)
		{
			if (series == null)
				throw new ArgumentNullException("series");

			if (series.CandleType != typeof(TimeFrameCandle))
				throw new ArgumentException(LocalizedStrings.NotSupportCandle.Put("OANDA", series.CandleType), "series");

			if (!(series.Arg is TimeSpan))
				throw new ArgumentException(LocalizedStrings.WrongCandleArg.Put(series.Arg), "series");

			var transactionId = TransactionIdGenerator.GetNextId();

			_series.Add(transactionId, series);

			SendInMessage(new MarketDataMessage
			{
				TransactionId = transactionId,
				DataType = MarketDataTypes.CandleTimeFrame,
				//SecurityId = GetSecurityId(series.Security),
				Arg = series.Arg,
				IsSubscribe = true,
				From = from,
				To = to,
			}.FillSecurityInfo(this, series.Security));
		}
Esempio n. 15
0
        internal static string GetBuildDescription(Build build, bool includeRefDescription, DateTimeOffset now)
        {
            if (build == null) throw new ArgumentNullException("build");

            var @ref = "";
            if (includeRefDescription)
                @ref = String.Concat(" on ", GetRefDescription(build));

            if (!build.Started.HasValue)
            {
                if (!build.Queued.HasValue)
                    return String.Format("Build #{0}{1} queued.", build.Id, @ref);

                return String.Format("Build #{0}{1} queued {2} seconds ago.", build.Id, @ref, build.Queued.Value.Since(now));
            }

            if (!build.Finished.HasValue)
                return String.Format("Build #{0}{1} started {2} seconds ago.", build.Id, @ref, build.Started.Value.Since(now));

            if (!build.Succeeded.HasValue)
                return String.Format("Build #{0}{1} finished in {2} seconds.", build.Id, @ref, build.Started.Value.Until(build.Finished.Value));

            if (build.Succeeded.Value)
                return String.Format("Build #{0}{1} succeeded in {2} seconds.", build.Id, @ref, build.Started.Value.Until(build.Finished.Value));

            return String.Format("Build #{0}{1} failed in {2} seconds.", build.Id, @ref, build.Started.Value.Until(build.Finished.Value));
        }
Esempio n. 16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LogEntry"/> class.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="categories">The categories.</param>
 public LogEntry(Object message, IEnumerable<String> categories)
 {
     _Message = message;
     _Categories = categories;
     _OccurredOn = DateTimeOffset.UtcNow;
     _AuxiliaryProperties = new Dictionary<String, Object>();
 }
Esempio n. 17
0
 private LogEntry(Object message, IEnumerable<String> categories, DateTimeOffset occurredOn, IDictionary<String, Object> auxiliaryProperties)
 {
     _Message = message;
     _Categories = new ReadOnlyCollection<String>(categories.ToList());
     _OccurredOn = occurredOn;
     _AuxiliaryProperties = new ReadOnlyDictionary<String, Object>(auxiliaryProperties);
 }
Esempio n. 18
0
 public PullRequest(Uri url, Uri htmlUrl, Uri diffUrl, Uri patchUrl, Uri issueUrl, Uri statusesUrl, int number, ItemState state, string title, string body, DateTimeOffset createdAt, DateTimeOffset updatedAt, DateTimeOffset? closedAt, DateTimeOffset? mergedAt, GitReference head, GitReference @base, User user, User assignee, bool? mergeable, User mergedBy, int comments, int commits, int additions, int deletions, int changedFiles)
 {
     Url = url;
     HtmlUrl = htmlUrl;
     DiffUrl = diffUrl;
     PatchUrl = patchUrl;
     IssueUrl = issueUrl;
     StatusesUrl = statusesUrl;
     Number = number;
     State = state;
     Title = title;
     Body = body;
     CreatedAt = createdAt;
     UpdatedAt = updatedAt;
     ClosedAt = closedAt;
     MergedAt = mergedAt;
     Head = head;
     Base = @base;
     User = user;
     Assignee = assignee;
     Mergeable = mergeable;
     MergedBy = mergedBy;
     Comments = comments;
     Commits = commits;
     Additions = additions;
     Deletions = deletions;
     ChangedFiles = changedFiles;
 }
Esempio n. 19
0
        /// <summary>
        /// Returns a list of events given the start and end time, inclusive.
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public IEnumerable<ICalendarEvent> GetCalendarEvents(DateTimeOffset startDate, DateTimeOffset endDate)
        {
            // Initialize the calendar folder object with only the folder ID.
            var propertiesToGet = new PropertySet(PropertySet.IdOnly);
            propertiesToGet.RequestedBodyType = BodyType.Text;

            var calendar = CalendarFolder.Bind(_exchangeService, WellKnownFolderName.Calendar, propertiesToGet);
            
            // Set the start and end time and number of appointments to retrieve.
            var calendarView = new CalendarView(
                startDate.ToOffset(_exchangeService.TimeZone.BaseUtcOffset).DateTime,
                endDate.ToOffset(_exchangeService.TimeZone.BaseUtcOffset).DateTime,
                MAX_EVENTS_TO_RETRIEVE);

            // Retrieve a collection of appointments by using the calendar view.
            var appointments = calendar.FindAppointments(calendarView);

            // Get specific properties.
            var appointmentSpecificPropertiesToGet = new PropertySet(PropertySet.FirstClassProperties);
            appointmentSpecificPropertiesToGet.AddRange(NonFirstClassAppointmentProperties);
            appointmentSpecificPropertiesToGet.RequestedBodyType = BodyType.Text;
            _exchangeService.LoadPropertiesForItems(appointments, appointmentSpecificPropertiesToGet);

            return TransformExchangeAppointmentsToGenericEvents(appointments);
        }
Esempio n. 20
0
        /// <summary>
        /// Loads a list of meetings for a given date from the database
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        internal static List<Tuple<string, DateTime, int>> GetMeetingsFromDatabase(DateTimeOffset date)
        {
            var meetings = new List<Tuple<string, DateTime, int>>();
            try
            {
                var query = "SELECT subject, time, durationInMins FROM " + Settings.MeetingsTable + " "
                            + "WHERE " + Database.GetInstance().GetDateFilteringStringForQuery(VisType.Day, date) + " "
                            + "AND subject != '" + Dict.Anonymized + "';";

                var table = Database.GetInstance().ExecuteReadQuery(query);

                foreach (DataRow row in table.Rows)
                {
                    var subject = (string)row["subject"];
                    var time = DateTime.Parse((string)row["time"], CultureInfo.InvariantCulture);
                    var duration = Convert.ToInt32(row["durationInMins"], CultureInfo.InvariantCulture);

                    var t = new Tuple<string, DateTime, int>(subject, time, duration);
                    meetings.Add(t);
                }
            }
            catch (Exception e)
            {
                Logger.WriteToLogFile(e);
            }

            return meetings;
        }
Esempio n. 21
0
        protected override void TestFixtureSetUp()
        {
            base.TestFixtureSetUp();
            _session = Session;
            _session.CreateKeyspace(_uniqueKsName);
            _session.ChangeKeyspace(_uniqueKsName);

            // Create necessary tables
            MappingConfiguration config1 = new MappingConfiguration();
            config1.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(EntityWithTimeUuid),
                () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(EntityWithTimeUuid)));
            _tableEntityWithTimeUuid = new Table<EntityWithTimeUuid>(_session, config1);
            _tableEntityWithTimeUuid.Create();

            MappingConfiguration config2 = new MappingConfiguration();
            config2.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(EntityWithNullableTimeUuid),
                () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(EntityWithNullableTimeUuid)));
            _tableEntityWithNullableTimeUuid = new Table<EntityWithNullableTimeUuid>(_session, config2);
            _tableEntityWithNullableTimeUuid.Create();

            _expectedTimeUuidObjectList = EntityWithTimeUuid.GetDefaultObjectList();
            _expectedNullableTimeUuidObjectList = EntityWithNullableTimeUuid.GetDefaultObjectList();

            _dateBefore = DateTimeOffset.Parse("2014-2-1");
            _dateAfter = DateTimeOffset.Parse("2014-4-1");
        }
        /// <summary>
        /// Asserts that a <see cref="DateTime"/> occurs a specified amount of time after another <see cref="DateTime"/>.
        /// </summary>
        /// <param name="target">
        /// The <see cref="DateTime"/> to compare the subject with.
        /// </param>
        /// <param name="reason">
        /// 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> After(DateTimeOffset target, string reason = "", params object[] reasonArgs)
        {
            bool success = Execute.Assertion
                .ForCondition(subject.HasValue)
                .BecauseOf(reason, reasonArgs)
                .FailWith("Expected date and/or time {0} to be " + predicate.DisplayText +
                          " {1} after {2}{reason}, but found a <null> DateTime.",
                    subject, timeSpan, target);

            if (success)
            {
                var actual = subject.Value.Subtract(target);

                if (!predicate.IsMatchedBy(actual, timeSpan))
                {
                    Execute.Assertion
                        .BecauseOf(reason, reasonArgs)
                        .FailWith(
                            "Expected date and/or time {0} to be " + predicate.DisplayText +
                            " {1} after {2}{reason}, but it differs {3}.",
                            subject, timeSpan, target, actual);
                }
            }

            return new AndConstraint<DateTimeOffsetAssertions>(parentAssertions);
        }
        public static HeartbeatMeasurement GetHeartbeatMeasurementFromData(byte[] data, DateTimeOffset timeStamp)
        {
            // Heart Rate profile defined flag values
            const byte HEART_RATE_VALUE_FORMAT = 0x01;
            byte flags = data[0];

            ushort HeartbeatMeasurementValue = 0;

            if (((flags & HEART_RATE_VALUE_FORMAT) != 0))
            {
                HeartbeatMeasurementValue = (ushort)((data[2] << 8) + data[1]);
            }
            else
            {
                HeartbeatMeasurementValue = data[1];
            }

            DateTimeOffset tmpVal = timeStamp;
            if (tmpVal == null)
            {
                tmpVal = DateTimeOffset.Now;
            }
            return new HeartbeatMeasurement
            {
                HeartbeatValue = HeartbeatMeasurementValue,
                Timestamp = tmpVal
            };
        }
Esempio n. 24
0
 internal IssueCommentItemViewModel(string body, string login, string avatar, DateTimeOffset createdAt)
 {
     Comment = body;
     Actor = login;
     AvatarUrl = new GitHubAvatar(avatar);
     CreatedAt = createdAt;
 }
Esempio n. 25
0
 internal IssueCommentItemViewModel(GitHubSharp.Models.IssueCommentModel comment)
 {
     Comment = comment.BodyHtml;
     Actor = comment.With(x => x.User).With(x => x.Login);
     AvatarUrl = new GitHubAvatar(comment.With(x => x.User).With(x => x.AvatarUrl));
     CreatedAt = comment.CreatedAt;
 }
        public override void Complete(
            string completedComments,
            IEnumerable<CreateDocumentParameters> createDocumentParameterObjects,
            IEnumerable<long> documentLibraryIdsToRemove,
            UserForAuditing userForAuditing,
            User user,
            DateTimeOffset completedDate)
        {
            //Addition conditions for completeing a FurtherControlMeasureTask.
            if (TaskStatus == TaskStatus.NoLongerRequired)
            {
                throw new AttemptingToCompleteFurtherControlMeasureTaskThatIsNotRequiredException();
            }

            if (!CanUserComplete(user))
            {
                throw new AttemptingToCompleteFurtherControlMeasureTaskThatTheUserDoesNotHavePermissionToAccess(Id);
            }

            base.Complete(
                completedComments,
                createDocumentParameterObjects,
                documentLibraryIdsToRemove,
                userForAuditing,
                user,
                completedDate);
        }
        public AbsoluteTimerWaitHandle(DateTimeOffset dueTime)
        {
            _dueTime = dueTime;
            _eventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);

            SafeWaitHandle = _eventWaitHandle.SafeWaitHandle;

            var dueSpan = (_dueTime - DateTimeOffset.Now);
            var period = new TimeSpan(dueSpan.Ticks / 10);

            if (dueSpan < TimeSpan.Zero)
            {
                _eventWaitHandle.Set();
            }
            else
            {
                _timer = new Timer(period.TotalMilliseconds)
                {
                    AutoReset = false,
                };

                _timer.Elapsed += TimerOnElapsed;

                _timer.Start();
            }
        }
Esempio n. 28
0
        public void when_getting_now_as_datetimeoffset_should_return_the_mock_provider_now_as_datetimeoffset()
        {
            var expectedDate = new DateTimeOffset(20.July(2015));
            _mockProvider.NowAsDateTimeOffset.Returns(expectedDate);

            TimeProvider.Current.NowAsDateTimeOffset.Should().Be(expectedDate);
        }
 private bool TodayIsTheDayOfThe(DateTime itineraryDate, string eventsTimeZoneId)
 {
     var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(eventsTimeZoneId);
     var utcOffset = timeZoneInfo.GetUtcOffset(itineraryDate);
     var intineraryDateConvertedToEventsTimeZone = new DateTimeOffset(itineraryDate, utcOffset);
     return (intineraryDateConvertedToEventsTimeZone.Date - DateTimeUtcNow().Date).TotalDays == 0;
 }
 public async Task<ICollection<Appointment>> GetAsync(string userEmail, int year, int month, int day)
 {
     var date = new DateTimeOffset(new DateTime(year, month, day));
     var events = await _office365HttpApi.GetUserDayEvents(userEmail, date);
     var appointments = MapEventsToAppointments(events);
     return appointments;
 }
Esempio n. 31
0
        public void SetLastOpened(DateTimeOffset date)
        {
            var dateString = date.ToString();

            keyValueStorage.SetString(lastAccessDateKey, dateString);
        }
 public BaseEntity()
 {
     this.Id       = Guid.NewGuid().ToString();
     this.CreateAt = DateTime.Now;
 }
Esempio n. 33
0
 public void Add(TimeSpan timeSpan)
 {
     UtcNow = UtcNow + timeSpan;
 }
Esempio n. 34
0
 public TestClock()
 {
     UtcNow = new DateTimeOffset(2013, 6, 11, 12, 34, 56, 789, TimeSpan.Zero);
 }
Esempio n. 35
0
 /// <summary>
 /// Creates a new instance and sets the <see cref="CreatedOn"/> and
 /// <see cref="UpdatedOn"/> to <see cref="DateTimeOffset.Now"/>
 /// </summary>
 protected EntityWithAllMetaAndVersionAsLong()
 {
     _createdOn = _updatedOn = DateTimeOffset.Now;
 }
Esempio n. 36
0
 /// <summary>
 /// Creates a new instance and sets the <see cref="CreatedOn"/> and
 /// <see cref="UpdatedOn"/> to <see cref="DateTimeOffset.Now"/>
 /// </summary>
 /// <param name="id">The entity id</param>
 protected EntityWithAllMetaAndVersionAsLong(TIdentity id) : base(id)
 {
     _createdOn = _updatedOn = DateTimeOffset.Now;
 }
Esempio n. 37
0
 public Project(string ownerUrl, string url, int id, string nodeId, string name, string body, int number, ItemState state, User creator, DateTimeOffset createdAt, DateTimeOffset updatedAt)
 {
     OwnerUrl  = ownerUrl;
     Url       = url;
     Id        = id;
     NodeId    = nodeId;
     Name      = name;
     Body      = body;
     Number    = number;
     State     = state;
     Creator   = creator;
     CreatedAt = createdAt;
     UpdatedAt = updatedAt;
 }
Esempio n. 38
0
 public static void Inc <T>(this ICounter <T> counter, T increment, DateTimeOffset timestamp)
     where T : struct
 {
     counter.Inc(increment, timestamp.ToUnixTime());
 }
Esempio n. 39
0
 protected MarkdownDocument(string relativeUri, string title, string content, DateTimeOffset published, Author author)
     : base(relativeUri, relativeUri + ".md", published, author)
 {
     Title   = title;
     Content = content;
 }
Esempio n. 40
0
 public static Mock <Commit> WithAuthor(this Mock <Commit> commit, DateTimeOffset commitTime)
 {
     return(commit.WithAuthor(Signature(commitTime)));
 }
Esempio n. 41
0
 public virtual void SetDateTimeOffset(int ordinal, DateTimeOffset value)
 {
     EnsureSubclassOverride();
     ValueUtilsSmi.SetDateTimeOffset(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value);
 }
Esempio n. 42
0
 private NotificationData(SerializationInfo info, StreamingContext context)
 {
     IsEnabled            = (bool)info.GetValue(EnabledKey, typeof(bool));
     LastNotificationDate = (DateTimeOffset)info.GetValue(LastNotificationDateKey,
                                                          typeof(DateTimeOffset));
 }
        internal static int Compare(JTokenType valueType, object objA, object objB)
        {
            if (objA == objB)
            {
                return 0;
            }
            if (objB == null)
            {
                return 1;
            }
            if (objA == null)
            {
                return -1;
            }

            switch (valueType)
            {
                case JTokenType.Integer:
                {
#if HAVE_BIG_INTEGER
                    if (objA is BigInteger integerA)
                    {
                        return CompareBigInteger(integerA, objB);
                    }
                    if (objB is BigInteger integerB)
                    {
                        return -CompareBigInteger(integerB, objA);
                    }
#endif
                    if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
                    {
                        return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
                    }
                    else if (objA is float || objB is float || objA is double || objB is double)
                    {
                        return CompareFloat(objA, objB);
                    }
                    else
                    {
                        return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
                    }
                }
                case JTokenType.Float:
                {
#if HAVE_BIG_INTEGER
                    if (objA is BigInteger integerA)
                    {
                        return CompareBigInteger(integerA, objB);
                    }
                    if (objB is BigInteger integerB)
                    {
                        return -CompareBigInteger(integerB, objA);
                    }
#endif
                    if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
                    {
                        return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
                    }
                    return CompareFloat(objA, objB);
                }
                case JTokenType.Comment:
                case JTokenType.String:
                case JTokenType.Raw:
                    string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
                    string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);

                    return string.CompareOrdinal(s1, s2);
                case JTokenType.Boolean:
                    bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
                    bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);

                    return b1.CompareTo(b2);
                case JTokenType.Date:
#if HAVE_DATE_TIME_OFFSET
                    if (objA is DateTime dateA)
                    {
#else
                        DateTime dateA = (DateTime)objA;
#endif
                        DateTime dateB;

#if HAVE_DATE_TIME_OFFSET
                        if (objB is DateTimeOffset offsetB)
                        {
                            dateB = offsetB.DateTime;
                        }
                        else
#endif
                        {
                            dateB = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);
                        }

                        return dateA.CompareTo(dateB);
#if HAVE_DATE_TIME_OFFSET
                    }
                    else
                    {
                        DateTimeOffset offsetA = (DateTimeOffset)objA;
                        if (!(objB is DateTimeOffset offsetB))
                        {
                            offsetB = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture));
                        }

                        return offsetA.CompareTo(offsetB);
                    }
#endif
                case JTokenType.Bytes:
                    if (!(objB is byte[] bytesB))
                    {
                        throw new ArgumentException("Object must be of type byte[].");
                    }

                    byte[] bytesA = objA as byte[];
                    Debug.Assert(bytesA != null);

                    return MiscellaneousUtils.ByteArrayCompare(bytesA, bytesB);
                case JTokenType.Guid:
                    if (!(objB is Guid))
                    {
                        throw new ArgumentException("Object must be of type Guid.");
                    }

                    Guid guid1 = (Guid)objA;
                    Guid guid2 = (Guid)objB;

                    return guid1.CompareTo(guid2);
                case JTokenType.Uri:
                    Uri uri2 = objB as Uri;
                    if (uri2 == null)
                    {
                        throw new ArgumentException("Object must be of type Uri.");
                    }

                    Uri uri1 = (Uri)objA;

                    return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
                case JTokenType.TimeSpan:
                    if (!(objB is TimeSpan))
                    {
                        throw new ArgumentException("Object must be of type TimeSpan.");
                    }

                    TimeSpan ts1 = (TimeSpan)objA;
                    TimeSpan ts2 = (TimeSpan)objB;

                    return ts1.CompareTo(ts2);
                default:
                    throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(valueType), valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
            }
        }
Esempio n. 44
0
 public static void SetCache(string key, object value, DateTimeOffset expiressAbsoulte)
 {
     _cache.SetCache(key, value, expiressAbsoulte);
 }
Esempio n. 45
0
 public Message()
 {
     Timestamp = new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds();
     Origin = System.AppDomain.CurrentDomain.FriendlyName;
 }
Esempio n. 46
0
 public static DateTime ToDateTimeUtc(this long dateTime)
 {
     return(DateTimeOffset.FromUnixTimeMilliseconds(dateTime).UtcDateTime);
 }
 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));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="JValue"/> class with the given value.
 /// </summary>
 /// <param name="value">The value.</param>
 public JValue(DateTimeOffset value)
     : this(value, JTokenType.Date)
 {
 }
Esempio n. 49
0
 private DateTimeOffset UnixTimeToDateTimeOffset(long seconds, long nanoseconds)
 {
     return(DateTimeOffset.FromUnixTimeSeconds(seconds).AddTicks(nanoseconds / NanosecondsPerTick).ToLocalTime());
 }
        private DateTimeOffset CalcLocalTime(FlightTime flightTime, AirportModel arrivingAt, DateTimeOffset departDate)
        {
            DateTimeOffset arrivalTime  = departDate.Add(flightTime.Duration);
            TimeZoneInfo   timeZoneInfo = ContosoTravel.Web.Application.Extensions.TimeZoneHelper.FindSystemTimeZoneById(arrivingAt.TimeZone);

            if (timeZoneInfo.IsDaylightSavingTime(arrivalTime))
            {
                arrivalTime = arrivalTime.AddHours(1);
            }

            return(TimeZoneInfo.ConvertTime(arrivalTime.DateTime, timeZoneInfo));
        }
Esempio n. 51
0
        public void Format(IEnumerable <LogEvent> logEvents, ITextFormatter formatter, TextWriter output)
        {
            if (logEvents == null)
            {
                throw new ArgumentNullException(nameof(logEvents));
            }
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            List <LogEvent> logs = logEvents.ToList();

            if (!logs.Any())
            {
                return;
            }

            var content = new BatchContent();

            foreach (LogEvent logEvent in logs)
            {
                // if (GetLevelRestriction(logEvent.Level) < _defaultLogLevelRestriction)
                //     continue;
                var stream = new BatchContentStream();
                content.Streams.Add(stream);

                stream.Labels.Add(new LokiLabel("level", GetLevel(logEvent.Level)));
                foreach (LokiLabel globalLabel in _globalLabels)
                {
                    stream.Labels.Add(new LokiLabel(globalLabel.Key, globalLabel.Value));
                }

                foreach (KeyValuePair <string, LogEventPropertyValue> property in logEvent.Properties)
                {
                    // Some enrichers pass strings with quotes surrounding the values inside the string,
                    // which results in redundant quotes after serialization and a "bad request" response.
                    // To avoid this, remove all quotes from the value.
                    stream.Labels.Add(new LokiLabel(property.Key, property.Value.ToString().Replace("\"", "")));
                }

                var localTime          = DateTime.Now;
                var localTimeAndOffset = new DateTimeOffset(localTime, TimeZoneInfo.Local.GetUtcOffset(localTime));
                var time = localTimeAndOffset.ToString("o");

                var sb = new StringBuilder();
                sb.AppendLine(logEvent.RenderMessage());
                if (logEvent.Exception != null)
                {
                    var e = logEvent.Exception;
                    while (e != null)
                    {
                        sb.AppendLine(e.Message);
                        sb.AppendLine(e.StackTrace);
                        e = e.InnerException;
                    }
                }

                stream.Entries.Add(new BatchEntry(time, sb.ToString()));
            }

            if (content.Streams.Count > 0)
            {
                output.Write(content.Serialize());
            }
        }
Esempio n. 52
0
 protected override void OnReceiveAny(List<string> msgs)
 {
     LastKeepalive = DateTimeOffset.UtcNow;
     SetKeepaliveTimer();
 }
Esempio n. 53
0
        /// <summary>
        /// 新建job,以cronExpression调度
        /// </summary>
        /// <param name="code">任务编码</param>
        /// <param name="group">模型分类</param>
        /// <param name="cronExpression">周期表达式</param>
        /// <param name="dataMap">扩展参数</param>
        /// <param name="startNow">是否现在启动</param>
        /// <param name="timeOffset">多少时间后启动</param>
        /// <param name="description">描述</param>
        /// <returns></returns>
        public static async Task NewJob(string code, string group, string cronExpression, IDictionary <string, object> dataMap, bool startNow, DateTimeOffset timeOffset, string description = "")
        {
            CheckProperties();

            IScheduler scheduler = await _schedulerFactory.GetScheduler();

            IJobDetail jobDetail = CreateJobDetail(code, group, dataMap, description);
            ITrigger   trigger   = CreateTrigger(code, group, cronExpression, startNow, timeOffset);

            await scheduler.ScheduleJob(jobDetail, trigger);

            await scheduler.Start();
        }
Esempio n. 54
0
 internal void SetLastWriteTime(string path, DateTimeOffset time) => SetAccessOrWriteTime(path, time, isAccessTime: false);
Esempio n. 55
0
 public ISpan Log(DateTimeOffset timestamp, string eventName)
 {
     // noop
     return(this);
 }
Esempio n. 56
0
        /// <summary>
        /// 更新job的运算周期
        /// </summary>
        /// <param name="code"></param>
        /// <param name="group"></param>
        /// <param name="cronExpression"></param>
        /// <param name="startNow">是否立刻运行</param>
        /// <param name="timeOffset">多少时间后执行</param>
        /// <returns></returns>
        public static async Task <Boolean> UpdateJobSchedule(string code, string group, string cronExpression, bool startNow, DateTimeOffset timeOffset)
        {
            IScheduler scheduler = await _schedulerFactory.GetScheduler();

            TriggerKey triggerKey = new TriggerKey(GetTriggerIdentityName(code));
            ITrigger   trigger    = CreateTrigger(code, group, cronExpression, startNow, timeOffset);
            await scheduler.RescheduleJob(triggerKey, trigger);

            return(true);
        }
Esempio n. 57
0
 /// <summary>
 /// To create the order book of volatility.
 /// </summary>
 /// <param name="currentTime">The current time.</param>
 /// <returns>The order book volatility.</returns>
 public override MarketDepth ImpliedVolatility(DateTimeOffset currentTime)
 {
     throw new NotSupportedException();
     //return UnderlyingAsset.GetMarketDepth().ImpliedVolatility(this);
 }
Esempio n. 58
0
        /// <summary>
        /// 创建cronExpression trigger
        /// </summary>
        /// <param name="code">唯一编码</param>
        /// <param name="group">组名</param>
        /// <param name="cronExpression">周期表达式</param>
        /// <param name="startNow">是否立刻启动</param>
        /// <param name="timeOffset">多少时间后启动</param>
        /// <returns></returns>
        private static ITrigger CreateTrigger(string code, string group, string cronExpression, bool startNow, DateTimeOffset timeOffset)
        {
            TriggerBuilder triggerBuilder = TriggerBuilder.Create()
                                            .WithIdentity(GetTriggerIdentityName(code), GetTriggerIdentifyGroup(group))
                                            // 运行模式
                                            .WithCronSchedule(cronExpression);

            if (startNow)
            {
                triggerBuilder.StartNow();
            }
            else
            {
                if (timeOffset != null)
                {
                    triggerBuilder.StartAt(timeOffset);
                }
            }

            return(triggerBuilder.Build());
        }
Esempio n. 59
0
 /// <summary>
 /// To calculate the implied volatility.
 /// </summary>
 /// <param name="currentTime">The current time.</param>
 /// <param name="premium">The option premium.</param>
 /// <returns>The implied volatility. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns>
 public override decimal?ImpliedVolatility(DateTimeOffset currentTime, decimal premium)
 {
     return(ProcessOptions(bs => bs.ImpliedVolatility(currentTime, premium), false));
 }
Esempio n. 60
0
 public ISpan Log(DateTimeOffset timestamp, IEnumerable <KeyValuePair <string, object> > fields)
 {
     // noop
     return(this);
 }