/// <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;
        }
Example #2
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));
		}
        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\":\"{");

        }
Example #4
0
 public ChainedHeader(BlockHeader blockHeader, int height, BigInteger totalWork, DateTimeOffset dateSeen)
 {
     BlockHeader = blockHeader;
     Height = height;
     TotalWork = totalWork;
     DateSeen = dateSeen;
 }
 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");
     }
 }
Example #6
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));
        }
		private void Syncronize()
		{
			lock (_stopwatch) {
				_baseTime = DateTimeOffset.UtcNow;
				_stopwatch.Restart();
			}
		}
        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
            };
        }
        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);
        }
Example #10
0
 internal IssueCommentItemViewModel(string body, string login, string avatar, DateTimeOffset createdAt)
 {
     Comment = body;
     Actor = login;
     AvatarUrl = new GitHubAvatar(avatar);
     CreatedAt = createdAt;
 }
Example #11
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 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();
            }
        }
        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);
        }
 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;
 }
Example #15
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);
 }
        /// <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);
        }
Example #17
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));
		}
 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;
 }
        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();
        }
Example #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;
        }
        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));
        }
Example #22
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");
        }
Example #23
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));
 }
Example #24
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;
 }
 /// <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;
 }
        /// <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);
        }
Example #27
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();
        }
Example #28
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>();
 }
Example #29
0
 public AccelerometerDatum(DateTimeOffset timestamp, double x, double y, double z)
     : base(timestamp)
 {
     _x = x;
     _y = y;
     _z = z;
 }
        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);
            }
        }