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();
        }
Ejemplo n.º 2
0
        public static void TurnOffDevice(string deviceId, DateTimeOffset departureTime)
        {
            SNMPDemoContext db = new SNMPDemoContext();
            //Device dev = db.Devices.Find(Int32.Parse(deviceId));

            string jobIdentity = "PreHeaterOffJob" + deviceId;
            string triggerIdentity = "PreHeaterOffTrigger" + deviceId;

            //DateTimeOffset turnOffTimer = departureTime;
            //turnOffTimer = turnOffTimer.AddMinutes(-5);

            departureTime = departureTime.AddMinutes(-5);

            // Build a job
            IJobDetail job = JobBuilder.Create<SetPreHeaterOffJob>()
                .WithIdentity(jobIdentity, "group1")
                //.UsingJobData("ip", dev.IpAddress)
                //.UsingJobData("communityString", dev.CommunityString)
                .UsingJobData("deviceId", deviceId)
                .Build();

            // Build a trigger
            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                .WithIdentity(triggerIdentity, "group1")
                .StartAt(departureTime)
                .Build();

            // Schedule a job with the trigger
            MvcApplication.Scheduler.ScheduleJob(job, trigger);
        }
Ejemplo n.º 3
0
    public static DateTimeOffset RoundToNearest(this DateTimeOffset time, int minutes)
    {
        var mins = time.Minute;
        var intervals = (int)((mins + (minutes / 2)) / minutes);
        mins = (intervals * minutes);

        var result = new DateTimeOffset(time.Year, time.Month, time.Day, time.Hour, 0, 0, time.Offset);
        return result.AddMinutes(mins);
    }
Ejemplo n.º 4
0
        public DateTimeOffset ScheduleNextTime(DateTimeOffset currentTime, JobExecutionRecord lastExecution)
        {
            var hour = new DateTimeOffset(currentTime.Year, currentTime.Month, currentTime.Day, currentTime.Hour, 0, 0,
                currentTime.Offset);

            while (hour < currentTime)
            {
                hour = hour.AddMinutes(10);
            }

            return hour;
        }
Ejemplo n.º 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());
        }
        private static DateTimeOffset? GetSendDate(DateTimeOffset now, ApplicationPushNotificationSetting appSettings, SubscriberNotificationSetting userNoteSettings)
        {
            DateTimeOffset? send = null;
            if (userNoteSettings.IsEnabled)
            {
                var addMinutes = appSettings.AntiNoiseSettings.IsConsolidationEnabled
                    ? appSettings.AntiNoiseSettings.InitialConsolidationDelayMinutes
                    : 0;
                send = now.AddMinutes(addMinutes);
            }
            return send;

        }
    public void From_FromFixedDateTime_Tests(int value)
    {
        var originalPointInTime = new DateTimeOffset(1976, 12, 31, 17, 0, 0, 0, TimeSpan.Zero);

        Assert.AreEqual(value.Years().From(originalPointInTime), originalPointInTime.AddYears(value));
        Assert.AreEqual(value.Months().From(originalPointInTime), originalPointInTime.AddMonths(value));
        Assert.AreEqual(value.Weeks().From(originalPointInTime), originalPointInTime.AddDays(value*DaysPerWeek));
        Assert.AreEqual(value.Days().From(originalPointInTime), originalPointInTime.AddDays(value));

        Assert.AreEqual(value.Hours().From(originalPointInTime), originalPointInTime.AddHours(value));
        Assert.AreEqual(value.Minutes().From(originalPointInTime), originalPointInTime.AddMinutes(value));
        Assert.AreEqual(value.Seconds().From(originalPointInTime), originalPointInTime.AddSeconds(value));
        Assert.AreEqual(value.Milliseconds().From(originalPointInTime), originalPointInTime.AddMilliseconds(value));
        Assert.AreEqual(value.Ticks().From(originalPointInTime), originalPointInTime.AddTicks(value));
    }
Ejemplo n.º 8
0
    public static void TestAddition()
    {
        DateTimeOffset dt = new DateTimeOffset(new DateTime(1986, 8, 15, 10, 20, 5, 70));
        Assert.Equal(17, dt.AddDays(2).Day);
        Assert.Equal(13, dt.AddDays(-2).Day);

        Assert.Equal(10, dt.AddMonths(2).Month);
        Assert.Equal(6, dt.AddMonths(-2).Month);

        Assert.Equal(1996, dt.AddYears(10).Year);
        Assert.Equal(1976, dt.AddYears(-10).Year);

        Assert.Equal(13, dt.AddHours(3).Hour);
        Assert.Equal(7, dt.AddHours(-3).Hour);

        Assert.Equal(25, dt.AddMinutes(5).Minute);
        Assert.Equal(15, dt.AddMinutes(-5).Minute);

        Assert.Equal(35, dt.AddSeconds(30).Second);
        Assert.Equal(2, dt.AddSeconds(-3).Second);

        Assert.Equal(80, dt.AddMilliseconds(10).Millisecond);
        Assert.Equal(60, dt.AddMilliseconds(-10).Millisecond);
    }
Ejemplo n.º 9
0
        public async Task ShouldThrowDependencyExceptionOnModifyIfSqlExceptionOccursAndLogItAsync()
        {
            // given
            int            randomNegativeNumber = GetNegativeRandomNumber();
            DateTimeOffset randomDateTime       = GetRandomDateTime();
            Calendar       randomCalendar       = CreateRandomCalendar(randomDateTime);
            Calendar       someCalendar         = randomCalendar;

            someCalendar.CreatedDate = randomDateTime.AddMinutes(randomNegativeNumber);
            SqlException sqlException = GetSqlException();

            var expectedCalendarDependencyException =
                new CalendarDependencyException(sqlException);

            this.storageBrokerMock.Setup(broker =>
                                         broker.SelectCalendarByIdAsync(someCalendar.Id))
            .ThrowsAsync(sqlException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(randomDateTime);

            // when
            ValueTask <Calendar> modifyCalendarTask =
                this.calendarService.ModifyCalendarAsync(someCalendar);

            // then
            await Assert.ThrowsAsync <CalendarDependencyException>(() =>
                                                                   modifyCalendarTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectCalendarByIdAsync(someCalendar.Id),
                                          Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogCritical(It.Is(SameExceptionAs(
                                                                       expectedCalendarDependencyException))),
                                          Times.Once);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
            this.dateTimeBrokerMock.VerifyNoOtherCalls();
        }
        public async void ShouldThrowValidationExceptionOnModifyWhenUpdatedDateIsNotRecentAndLogItAsync(
            int minutes)
        {
            // given
            DateTimeOffset dateTime      = GetRandomDateTime();
            Teacher        randomTeacher = CreateRandomTeacher(dateTime);
            Teacher        inputTeacher  = randomTeacher;

            inputTeacher.UpdatedBy   = inputTeacher.CreatedBy;
            inputTeacher.UpdatedDate = dateTime.AddMinutes(minutes);
            var invalidTeacherException = new InvalidTeacherException();

            invalidTeacherException.AddData(
                key: nameof(Teacher.UpdatedDate),
                values: $"Date is not recent");

            var expectedTeacherValidationException =
                new TeacherValidationException(invalidTeacherException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(dateTime);

            // when
            ValueTask <Teacher> modifyTeacherTask =
                this.teacherService.ModifyTeacherAsync(inputTeacher);

            // then
            await Assert.ThrowsAsync <TeacherValidationException>(() =>
                                                                  modifyTeacherTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedTeacherValidationException))),
                                          Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectTeacherByIdAsync(It.IsAny <Guid>()),
                                          Times.Never);

            this.dateTimeBrokerMock.VerifyNoOtherCalls();
            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 11
0
        public async void ShouldThrowValidationExceptionOnCreateWhenCreatedDateIsNotRecentAndLogItAsync(
            int minutes)
        {
            // given
            DateTimeOffset dateTime   = GetRandomDateTime();
            User           randomUser = CreateRandomUser(dates: dateTime);
            User           inputUser  = randomUser;

            inputUser.CreatedDate = dateTime.AddMinutes(minutes);
            inputUser.UpdatedDate = inputUser.CreatedDate;
            string password = GetRandomPassword();

            var invalidUserException = new InvalidUserException(
                parameterName: nameof(User.CreatedDate),
                parameterValue: inputUser.CreatedDate);

            var expectedUserValidationException =
                new UserValidationException(invalidUserException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(dateTime);

            // when
            ValueTask <User> registerUserTask =
                this.userService.RegisterUserAsync(inputUser, password);

            // then
            await Assert.ThrowsAsync <UserValidationException>(() =>
                                                               registerUserTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedUserValidationException))),
                                          Times.Once);

            this.userManagementBrokerMock.Verify(broker =>
                                                 broker.SelectUserByIdAsync(It.IsAny <Guid>()),
                                                 Times.Never);

            this.dateTimeBrokerMock.VerifyNoOtherCalls();
            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.userManagementBrokerMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 12
0
        public Task <QueryResult> Query(Query q)
        {
            // Need to determine the range of nodes to query
            var normalizedStart = new DateTimeOffset(q.Start.Year, q.Start.Month, q.Start.Day, q.Start.Hour, q.Start.Minute, 0, new TimeSpan());
            var tasks           = new List <Task <RecordQueryResult> >();
            var starts          = new List <DateTimeOffset>();

            while (normalizedStart <= q.End)
            {
                starts.Add(normalizedStart);
                normalizedStart = normalizedStart.AddMinutes(1);
            }
            var result = new QueryResult()
            {
                Query = q
            };

            // Since they come in any order and we cache by the attributes we want to reorder them to always be the same
            var sortedAttributes = (from x in q.Attributes orderby x.Name select x).ToList();

            // Originally had async but found slamming the async threadpool hard caused some problems, ie if querying over a month
            //   43k asyncs or so
            Parallel.ForEach(starts, x =>
            {
                var worker = new QueryMapGrain();
                var r      = worker.QueryIndividual(new RecordQuery()
                {
                    Aggregate   = q.Aggregate,
                    Attributes  = sortedAttributes,
                    End         = q.End,
                    Start       = q.Start,
                    EntryMinute = x,
                    MetricName  = q.Metric,
                    ServiceName = q.Service
                }).Result;
                if (r.Result == 0)
                {
                    return;
                }
                result.Results.Add(new ResultRecord()
                {
                    Start = r.Source.EntryMinute,
                    Value = r.Result
                });
            });
            return(Task.FromResult(result));
        }
        public async Task ShouldThrowDependencyExceptionOnModifyIfDbUpdateExceptionOccursAndLogItAsync()
        {
            // given
            int            randomNegativeNumber = GetNegativeRandomNumber();
            DateTimeOffset randomDateTime       = GetRandomDateTime();
            Attendance     randomAttendance     = CreateRandomAttendance(randomDateTime);
            Attendance     someAttendance       = randomAttendance;

            someAttendance.CreatedDate = randomDateTime.AddMinutes(randomNegativeNumber);
            var databaseUpdateException = new DbUpdateException();

            var expectedAttendanceDependencyException =
                new AttendanceDependencyException(databaseUpdateException);

            this.storageBrokerMock.Setup(broker =>
                                         broker.SelectAttendanceByIdAsync(someAttendance.Id))
            .ThrowsAsync(databaseUpdateException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(randomDateTime);

            // when
            ValueTask <Attendance> modifyAttendanceTask =
                this.attendanceService.ModifyAttendanceAsync(someAttendance);

            // then
            await Assert.ThrowsAsync <AttendanceDependencyException>(() =>
                                                                     modifyAttendanceTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectAttendanceByIdAsync(someAttendance.Id),
                                          Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(
                                                                    expectedAttendanceDependencyException))),
                                          Times.Once);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
            this.dateTimeBrokerMock.VerifyNoOtherCalls();
        }
        public async Task ShouldThorwValidationExceptionOnModifyIfTeacherDoesntExistAndLogItAsync()
        {
            // given
            int            randomNegativeMinutes = GetNegativeRandomNumber();
            DateTimeOffset dateTime           = GetRandomDateTime();
            Teacher        randomTeacher      = CreateRandomTeacher(dateTime);
            Teacher        nonExistentTeacher = randomTeacher;

            nonExistentTeacher.CreatedDate = dateTime.AddMinutes(randomNegativeMinutes);
            Teacher noTeacher = null;
            var     notFoundTeacherException = new NotFoundTeacherException(nonExistentTeacher.Id);

            var expectedTeacherValidationException =
                new TeacherValidationException(notFoundTeacherException);

            this.storageBrokerMock.Setup(broker =>
                                         broker.SelectTeacherByIdAsync(nonExistentTeacher.Id))
            .ReturnsAsync(noTeacher);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(dateTime);

            // when
            ValueTask <Teacher> modifyTeacherTask =
                this.teacherService.ModifyTeacherAsync(nonExistentTeacher);

            // then
            await Assert.ThrowsAsync <TeacherValidationException>(() =>
                                                                  modifyTeacherTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectTeacherByIdAsync(nonExistentTeacher.Id),
                                          Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedTeacherValidationException))),
                                          Times.Once);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
            this.dateTimeBrokerMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 15
0
        public async void ShouldThrowValidationExceptionOnAddWhenCreatedDateIsNotRecentAndLogItAsync(
            int minutes)
        {
            // given
            DateTimeOffset dateTime           = GetRandomDateTime();
            Registration   randomRegistration = CreateRandomRegistration(dateTime);
            Registration   inputRegistration  = randomRegistration;

            inputRegistration.UpdatedBy   = inputRegistration.CreatedBy;
            inputRegistration.CreatedDate = dateTime.AddMinutes(minutes);
            inputRegistration.UpdatedDate = inputRegistration.CreatedDate;

            var invalidRegistrationInputException = new InvalidRegistrationException(
                parameterName: nameof(Registration.CreatedDate),
                parameterValue: inputRegistration.CreatedDate);

            var expectedRegistrationValidationException =
                new RegistrationValidationException(invalidRegistrationInputException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(dateTime);

            // when
            ValueTask <Registration> registerRegistrationTask =
                this.registrationService.AddRegistrationAsync(inputRegistration);

            // then
            await Assert.ThrowsAsync <RegistrationValidationException>(() =>
                                                                       registerRegistrationTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedRegistrationValidationException))),
                                          Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.InsertRegistrationAsync(It.IsAny <Registration>()),
                                          Times.Never);

            this.dateTimeBrokerMock.VerifyNoOtherCalls();
            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
        }
        public async Task ShouldThrowDependencyExceptionOnModifyIfDbUpdateConcurrencyExceptionOccursAndLogItAsync()
        {
            // given
            int            randomNegativeNumber = GetNegativeRandomNumber();
            DateTimeOffset randomDateTime       = GetRandomDateTime();
            Classroom      randomClassroom      = CreateRandomClassroom(randomDateTime);
            Classroom      someClassroom        = randomClassroom;

            someClassroom.CreatedDate = randomDateTime.AddMinutes(randomNegativeNumber);
            var databaseUpdateConcurrencyException = new DbUpdateConcurrencyException();
            var lockedClassroomException           = new LockedClassroomException(databaseUpdateConcurrencyException);

            var expectedClassroomDependencyException =
                new ClassroomDependencyException(lockedClassroomException);

            this.storageBrokerMock.Setup(broker =>
                                         broker.SelectClassroomByIdAsync(someClassroom.Id))
            .ThrowsAsync(databaseUpdateConcurrencyException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(randomDateTime);

            // when
            ValueTask <Classroom> modifyClassroomTask =
                this.classroomService.ModifyClassroomAsync(someClassroom);

            // then
            await Assert.ThrowsAsync <ClassroomDependencyException>(() =>
                                                                    modifyClassroomTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectClassroomByIdAsync(someClassroom.Id),
                                          Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedClassroomDependencyException))),
                                          Times.Once);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
            this.dateTimeBrokerMock.VerifyNoOtherCalls();
        }
        public async void ShouldThrowValidationExceptionOnCreateWhenCreatedDateIsNotRecentAndLogItAsync(
            int minutes)
        {
            // given
            DateTimeOffset dateTime         = GetRandomDateTime();
            Assignment     randomAssignment = CreateRandomAssignment(dateTime);
            Assignment     inputAssignment  = randomAssignment;

            inputAssignment.UpdatedBy   = inputAssignment.CreatedBy;
            inputAssignment.CreatedDate = dateTime.AddMinutes(minutes);
            inputAssignment.UpdatedDate = inputAssignment.CreatedDate;

            var invalidAssignmentInputException = new InvalidAssignmentException(
                parameterName: nameof(Assignment.CreatedDate),
                parameterValue: inputAssignment.CreatedDate);

            var expectedAssignmentValidationException =
                new AssignmentValidationException(invalidAssignmentInputException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(dateTime);

            // when
            ValueTask <Assignment> createAssignmentTask =
                this.assignmentService.CreateAssignmentAsync(inputAssignment);

            // then
            await Assert.ThrowsAsync <AssignmentValidationException>(() =>
                                                                     createAssignmentTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedAssignmentValidationException))),
                                          Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectAssignmentByIdAsync(It.IsAny <Guid>()),
                                          Times.Never);

            this.dateTimeBrokerMock.VerifyNoOtherCalls();
            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 18
0
        public async Task ShouldThrowDependencyExceptionOnModifyIfDbUpdateExceptionOccursAndLogItAsync()
        {
            // given
            int                   randomNegativeNumber        = GetNegativeRandomNumber();
            DateTimeOffset        randomDateTime              = GetRandomDateTime();
            StudentSemesterCourse randomStudentSemesterCourse = CreateRandomStudentSemesterCourse(randomDateTime);
            StudentSemesterCourse someStudentSemesterCourse   = randomStudentSemesterCourse;

            someStudentSemesterCourse.CreatedDate = randomDateTime.AddMinutes(randomNegativeNumber);
            var databaseUpdateException = new DbUpdateException();

            var expectedStudentSemesterCourseDependencyException =
                new StudentSemesterCourseDependencyException(databaseUpdateException);

            this.storageBrokerMock.Setup(broker =>
                                         broker.SelectStudentSemesterCourseByIdAsync
                                             (someStudentSemesterCourse.StudentId, someStudentSemesterCourse.SemesterCourseId))
            .ThrowsAsync(databaseUpdateException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(randomDateTime);

            // when
            ValueTask <StudentSemesterCourse> modifyStudentSemesterCourseTask =
                this.studentSemesterCourseService.ModifyStudentSemesterCourseAsync(someStudentSemesterCourse);

            // then
            await Assert.ThrowsAsync <StudentSemesterCourseDependencyException>(() =>
                                                                                modifyStudentSemesterCourseTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectStudentSemesterCourseByIdAsync(It.IsAny <Guid>(), It.IsAny <Guid>()),
                                          Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedStudentSemesterCourseDependencyException))),
                                          Times.Once);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
            this.dateTimeBrokerMock.VerifyNoOtherCalls();
        }
        public async Task ShouldThrowValidationExceptionOnModifyIfStudentExamDoesntExistAndLogItAsync()
        {
            // given
            int            randomNegativeMinutes = GetNegativeRandomNumber();
            DateTimeOffset dateTime               = GetRandomDateTime();
            StudentExam    randomStudentExam      = CreateRandomStudentExam(dateTime);
            StudentExam    nonExistentStudentExam = randomStudentExam;

            nonExistentStudentExam.CreatedDate = dateTime.AddMinutes(randomNegativeMinutes);
            StudentExam noStudentExam = null;
            var         notFoundStudentExamException = new NotFoundStudentExamException(nonExistentStudentExam.Id);

            var expectedStudentExamValidationException =
                new StudentExamValidationException(notFoundStudentExamException);

            this.storageBrokerMock.Setup(broker =>
                                         broker.SelectStudentExamByIdAsync(nonExistentStudentExam.Id))
            .ReturnsAsync(noStudentExam);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(dateTime);

            // when
            ValueTask <StudentExam> modifyStudentExamTask =
                this.studentExamService.ModifyStudentExamAsync(nonExistentStudentExam);

            // then
            await Assert.ThrowsAsync <StudentExamValidationException>(() =>
                                                                      modifyStudentExamTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectStudentExamByIdAsync(nonExistentStudentExam.Id),
                                          Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedStudentExamValidationException))),
                                          Times.Once);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
            this.dateTimeBrokerMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 20
0
        public async void ShouldThrowValidationExceptionOnModifyWhenUpdatedDateIsNotRecentAndLogItAsync(
            int minutes)
        {
            // given
            DateTimeOffset dateTime            = GetRandomDateTime();
            CalendarEntry  randomCalendarEntry = CreateRandomCalendarEntry(dateTime);
            CalendarEntry  inputCalendarEntry  = randomCalendarEntry;

            inputCalendarEntry.UpdatedBy   = inputCalendarEntry.CreatedBy;
            inputCalendarEntry.UpdatedDate = dateTime.AddMinutes(minutes);
            var invalidCalendarEntryException = new InvalidCalendarEntryException();

            invalidCalendarEntryException.AddData(
                key: nameof(CalendarEntry.UpdatedDate),
                values: $"Date is not recent");

            var expectedCalendarEntryValidationException =
                new CalendarEntryValidationException(invalidCalendarEntryException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(dateTime);

            // when
            ValueTask <CalendarEntry> modifyCalendarEntryTask =
                this.calendarEntryService.ModifyCalendarEntryAsync(inputCalendarEntry);

            // then
            await Assert.ThrowsAsync <CalendarEntryValidationException>(() =>
                                                                        modifyCalendarEntryTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameValidationExceptionAs(expectedCalendarEntryValidationException))),
                                          Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectCalendarEntryByIdAsync(It.IsAny <Guid>()),
                                          Times.Never);

            this.dateTimeBrokerMock.VerifyNoOtherCalls();
            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
        }
        public async Task ShouldThrowValidationExceptionOnModifyIfAttendanceDoesntExistAndLogItAsync()
        {
            // given
            int            randomNegativeMinutes = GetNegativeRandomNumber();
            DateTimeOffset dateTime              = GetRandomDateTime();
            Attendance     randomAttendance      = CreateRandomAttendance(dateTime);
            Attendance     nonExistentAttendance = randomAttendance;

            nonExistentAttendance.CreatedDate = dateTime.AddMinutes(randomNegativeMinutes);
            Attendance noAttendance = null;
            var        notFoundAttendanceException = new NotFoundAttendanceException(nonExistentAttendance.Id);

            var expectedAttendanceValidationException =
                new AttendanceValidationException(notFoundAttendanceException);

            this.storageBrokerMock.Setup(broker =>
                                         broker.SelectAttendanceByIdAsync(nonExistentAttendance.Id))
            .ReturnsAsync(noAttendance);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(dateTime);

            // when
            ValueTask <Attendance> modifyAttendanceTask =
                this.attendanceService.ModifyAttendanceAsync(nonExistentAttendance);

            // then
            await Assert.ThrowsAsync <AttendanceValidationException>(() =>
                                                                     modifyAttendanceTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectAttendanceByIdAsync(nonExistentAttendance.Id),
                                          Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedAttendanceValidationException))),
                                          Times.Once);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
            this.dateTimeBrokerMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 22
0
        public async void ShouldThrowValidationExceptionOnAddWhenCreatedDateIsNotRecentAndLogItAsync(
            int minutes)
        {
            // given
            DateTimeOffset dateTime      = GetRandomDateTime();
            Contact        randomContact = CreateRandomContact(dateTime);
            Contact        inputContact  = randomContact;

            inputContact.UpdatedBy   = inputContact.CreatedBy;
            inputContact.CreatedDate = dateTime.AddMinutes(minutes);
            inputContact.UpdatedDate = inputContact.CreatedDate;

            var invalidContactInputException = new InvalidContactException(
                parameterName: nameof(Contact.CreatedDate),
                parameterValue: inputContact.CreatedDate);

            var expectedContactValidationException =
                new ContactValidationException(invalidContactInputException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(dateTime);

            // when
            ValueTask <Contact> addContactTask =
                this.contactService.AddContactAsync(inputContact);

            // then
            await Assert.ThrowsAsync <ContactValidationException>(() =>
                                                                  addContactTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedContactValidationException))),
                                          Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.InsertContactAsync(It.IsAny <Contact>()),
                                          Times.Never);

            this.dateTimeBrokerMock.VerifyNoOtherCalls();
            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 23
0
        protected virtual void HandleStandardCriterion(string channel, string nickname, BounceCriterion criterion)
        {
            // add this join
            DateTimeOffset now = DateTimeOffset.Now;

            RelevantJoins.Add(new JoinQuitEvent(channel, nickname, now));

            // calculate unban time
            DateTimeOffset unbanTimestamp = now.AddMinutes(criterion.BanDurationMinutes.Value);

            // check if the criterion is fulfilled
            if (CheckAndDebounce(channel, nickname, criterion, now))
            {
                // unban after the set duration
                ConnectionManager.Timers.Register(unbanTimestamp, () => Unban(channel, nickname));
            }
        }
Ejemplo n.º 24
0
        public async void ShouldThrowValidationExceptionOnModifyWhenUpdatedDateIsNotRecentAndLogItAsync(
            int minutes)
        {
            // given
            DateTimeOffset  dateTime = GetRandomDateTime();
            StudentGuardian randomStudentGuardian = CreateRandomStudentGuardian(dateTime);
            StudentGuardian inputStudentGuardian  = randomStudentGuardian;

            inputStudentGuardian.UpdatedBy   = inputStudentGuardian.CreatedBy;
            inputStudentGuardian.UpdatedDate = dateTime.AddMinutes(minutes);

            var invalidStudentGuardianInputException = new InvalidStudentGuardianInputException(
                parameterName: nameof(StudentGuardian.UpdatedDate),
                parameterValue: inputStudentGuardian.UpdatedDate);

            var expectedStudentGuardianValidationException =
                new StudentGuardianValidationException(invalidStudentGuardianInputException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(dateTime);

            // when
            ValueTask <StudentGuardian> modifyStudentGuardianTask =
                this.studentGuardianService.ModifyStudentGuardianAsync(inputStudentGuardian);

            // then
            await Assert.ThrowsAsync <StudentGuardianValidationException>(() =>
                                                                          modifyStudentGuardianTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedStudentGuardianValidationException))),
                                          Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectStudentGuardianByIdAsync(It.IsAny <Guid>(), It.IsAny <Guid>()),
                                          Times.Never);

            this.dateTimeBrokerMock.VerifyNoOtherCalls();
            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 25
0
        public static string ToScheduleSummary(List <BusArrivalTime> arrivals, DateTimeOffset currentTime)
        {
            if (arrivals.Count <= 2)
            {
                return(string.Empty);
            }

            var lastTime            = currentTime.AddMinutes(arrivals.Last().MinutesFromNow);
            var lastTimeDescription = lastTime.ToString(DATE_FORMAT);

            if (arrivals.Count == 3)
            {
                return("Last arrival at " + lastTimeDescription);
            }

            // Check for whether there's a regular half-hourly or hourly arrival pattern.
            // If not, exit the loop early.
            bool isTwoHourly  = true;
            bool isHourly     = true;
            bool isHalfHourly = true;

            for (int i = 1; i < arrivals.Count - 1 && (isTwoHourly || isHourly || isHalfHourly); i++)
            {
                int difference = arrivals[i + 1].MinutesFromNow - arrivals[i].MinutesFromNow;
                isTwoHourly  = isTwoHourly && difference >= 110 && difference <= 130;
                isHourly     = isHourly && difference >= 50 && difference <= 70;
                isHalfHourly = isHalfHourly && difference >= 20 && difference <= 40;
            }

            if (isTwoHourly)
            {
                return("Every 2 hours until " + lastTimeDescription);
            }
            else if (isHourly)
            {
                return("Hourly until " + lastTimeDescription);
            }
            else if (isHalfHourly)
            {
                return("Every 30 minutes until " + lastTimeDescription);
            }
            else
            {
                return("Last arrival at " + lastTimeDescription);
            }
        }
Ejemplo n.º 26
0
        public async Task ShouldThrowDependencyExceptionOnModifyIfSqlExceptionOccursAndLogItAsync()
        {
            // given
            int            randomNegativeNumber = GetNegativeRandomNumber();
            DateTimeOffset randomDateTime       = GetRandomDateTime();
            StudentExam    randomStudentExam    = CreateRandomStudentExam(randomDateTime);
            StudentExam    someStudentExam      = randomStudentExam;

            someStudentExam.CreatedDate = randomDateTime.AddMinutes(randomNegativeNumber);
            SqlException sqlException = GetSqlException();

            var expectedStudentExamDependencyException =
                new StudentExamDependencyException(sqlException);

            this.storageBrokerMock.Setup(broker =>
                                         broker.SelectStudentExamByIdAsync(someStudentExam.Id))
            .ThrowsAsync(sqlException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(randomDateTime);

            // when
            ValueTask <StudentExam> modifyStudentExamTask =
                this.studentExamService.ModifyStudentExamAsync(someStudentExam);

            // then
            await Assert.ThrowsAsync <StudentExamDependencyException>(() =>
                                                                      modifyStudentExamTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectStudentExamByIdAsync(It.IsAny <Guid>()),
                                          Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogCritical(It.Is(SameExceptionAs(expectedStudentExamDependencyException))),
                                          Times.Once);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
            this.dateTimeBrokerMock.VerifyNoOtherCalls();
        }
        public async Task ShouldThrowServiceExceptionOnModifyIfServiceExceptionOccursAndLogItAsync()
        {
            // given
            int            randomNegativeNumber = GetNegativeRandomNumber();
            DateTimeOffset randomDateTime       = GetRandomDateTime();
            CalendarEntry  randomCalendarEntry  = CreateRandomCalendarEntry(randomDateTime);
            CalendarEntry  someCalendarEntry    = randomCalendarEntry;

            someCalendarEntry.CreatedDate = randomDateTime.AddMinutes(randomNegativeNumber);
            var serviceException = new Exception();

            var expectedCalendarEntryServiceException =
                new CalendarEntryServiceException(serviceException);

            this.storageBrokerMock.Setup(broker =>
                                         broker.SelectCalendarEntryByIdAsync(someCalendarEntry.Id))
            .ThrowsAsync(serviceException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(randomDateTime);

            // when
            ValueTask <CalendarEntry> modifyCalendarEntryTask =
                this.calendarEntryService.ModifyCalendarEntryAsync(someCalendarEntry);

            // then
            await Assert.ThrowsAsync <CalendarEntryServiceException>(() =>
                                                                     modifyCalendarEntryTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectCalendarEntryByIdAsync(someCalendarEntry.Id),
                                          Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedCalendarEntryServiceException))),
                                          Times.Once);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
            this.dateTimeBrokerMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 28
0
        private async void createNotificationTask(object sender, RoutedEventArgs e)
        {
            StackPanel parent_stck = (StackPanel)((Button)sender).Parent;
            DatePicker dp          = (DatePicker)parent_stck.Children.ElementAt(1);
            TimePicker tp          = (TimePicker)parent_stck.Children.ElementAt(2);

            DateTimeOffset selD = dp.Date;
            TimeSpan       tm   = tp.Time;

            // Set up the notification text.
            XmlDocument toastXml  = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
            XmlNodeList strings   = toastXml.GetElementsByTagName("text");
            ListView    parent_lv = (ListView)parent_stck.Parent;
            TextBox     tb_title  = (TextBox)parent_lv.Items.ElementAt(0);
            String      texto     = tb_title.Text;

            strings[0].AppendChild(toastXml.CreateTextNode(texto));
            strings[1].AppendChild(toastXml.CreateTextNode("Fecha: " + selD));

            // Create the toast notification object.
            selD = selD.AddSeconds(30);
            try{
                DateTimeOffset d = new DateTimeOffset();
                d = d.AddDays(selD.Day);
                d = d.AddMonths(selD.Month);
                d = d.AddYears(selD.Year);
                d = d.AddHours(tm.Hours);
                d = d.AddMinutes(tm.Minutes);
                d = d.AddSeconds(tm.Seconds + 30);
                ScheduledToastNotification toast = new ScheduledToastNotification(toastXml, d);
                toast.Id = "h" + new Random().Next();
                // Add to the schedule.
                ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
            } catch (Exception excep) {
                MessageDialog showDialog = new MessageDialog("Introduce una fecha futura");

                showDialog.Commands.Add(new UICommand("Vale")
                {
                    Id = 0
                });

                showDialog.DefaultCommandIndex = 0;

                var result = await showDialog.ShowAsync();
            }
        }
Ejemplo n.º 29
0
        /// <summary>Interpret time value and increment a DateTimeOffset based on the values.</summary>
        /// <param name="measureString">The measure or numeric value.</param>
        /// <param name="unit">The time unit.</param>
        /// <param name="dto">The DateTimeOffset to increment.</param>
        private static void InterpretTime(string measureString, string unit, ref DateTimeOffset dto)
        {
            // Only continue if these two have a valid value.
            if (int.TryParse(measureString, out int measure) && measure > 0 && unit.Length > 0)
            {
                switch (unit.ToLower())
                {
                case "month":
                case "months":
                    dto = dto.AddMonths(measure);
                    break;

                case "day":
                case "days":
                case "d":
                    dto = dto.AddDays(measure);
                    break;

                case "week":
                case "weeks":
                case "wk":
                case "wks":
                case "w":
                    dto = dto.AddDays(measure * 7);
                    break;

                case "hour":
                case "hours":
                case "hr":
                case "hrs":
                case "h":
                    dto = dto.AddHours(measure);
                    break;

                case "minute":
                case "minutes":
                case "min":
                case "mins":
                    dto = dto.AddMinutes(measure);
                    break;

                default:
                    break;
                }
            }
        }
Ejemplo n.º 30
0
        public void MinuteOfHour_StartGreaterThanEnd()
        {
            var expected = new DateTimeOffset(1985, 12, 17, 0, 0, 0, TimeSpan.FromHours(-6));
            var events   = Schedule.Build()
                           .OnMinuteOfHourRange(23, 3)
                           .GetNextEvents(expected)
                           .Take(60)
                           .ToList();

            foreach (var e in events)
            {
                Console.WriteLine(e.ToString("O"));
                expected = expected.AddMinutes(expected.Minute == 3 ? 20 : 1);
                Assert.AreEqual(expected.Minute, e.Minute);
                Assert.AreEqual(expected, e);
            }
        }
Ejemplo n.º 31
0
        public async Task ShouldThrowServiceExceptionOnModifyIfServiceExceptionOccursAndLogItAsync()
        {
            // given
            int            randomNegativeNumber = GetNegativeRandomNumber();
            DateTimeOffset randomDateTime       = GetRandomDateTime();
            User           randomUser           = CreateRandomUser(randomDateTime);
            User           someUser             = randomUser;

            someUser.CreatedDate = randomDateTime.AddMinutes(randomNegativeNumber);
            var serviceException = new Exception();

            var expectedUserServiceException =
                new UserServiceException(serviceException);

            this.userManagementBrokerMock.Setup(broker =>
                                                broker.SelectUserByIdAsync(someUser.Id))
            .ThrowsAsync(serviceException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(randomDateTime);

            // when
            ValueTask <User> modifyUserTask =
                this.userService.ModifyUserAsync(someUser);

            // then
            await Assert.ThrowsAsync <UserServiceException>(() =>
                                                            modifyUserTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.userManagementBrokerMock.Verify(broker =>
                                                 broker.SelectUserByIdAsync(someUser.Id),
                                                 Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedUserServiceException))),
                                          Times.Once);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.userManagementBrokerMock.VerifyNoOtherCalls();
            this.dateTimeBrokerMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 32
0
        public async Task ShouldThrowServiceExceptionOnModifyIfServiceExceptionOccursAndLogItAsync()
        {
            // given
            int            randomNegativeNumber = GetNegativeRandomNumber();
            DateTimeOffset randomDateTime       = GetRandomDateTime();
            Assignment     randomAssignment     = CreateRandomAssignment(randomDateTime);
            Assignment     someAssignment       = randomAssignment;

            someAssignment.CreatedDate = randomDateTime.AddMinutes(randomNegativeNumber);
            var serviceException = new Exception();

            var expectedAssignmentServiceException =
                new AssignmentServiceException(serviceException);

            this.storageBrokerMock.Setup(broker =>
                                         broker.SelectAssignmentByIdAsync(someAssignment.Id))
            .ThrowsAsync(serviceException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(randomDateTime);

            // when
            ValueTask <Assignment> modifyAssignmentTask =
                this.assignmentService.ModifyAssignmentAsync(someAssignment);

            // then
            await Assert.ThrowsAsync <AssignmentServiceException>(() =>
                                                                  modifyAssignmentTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectAssignmentByIdAsync(someAssignment.Id),
                                          Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedAssignmentServiceException))),
                                          Times.Once);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
            this.dateTimeBrokerMock.VerifyNoOtherCalls();
        }
        public async void ShouldThrowValidationExceptionOnModifyWhenUpdatedDateIsNotRecentAndLogItAsync(
            int minutes)
        {
            // given
            DateTimeOffset dateTime     = GetRandomDateTime();
            Course         randomCourse = CreateRandomCourse(dateTime);
            Course         inputCourse  = randomCourse;

            inputCourse.UpdatedBy   = inputCourse.CreatedBy;
            inputCourse.UpdatedDate = dateTime.AddMinutes(minutes);

            var invalidCourseInputException = new InvalidCourseInputException(
                parameterName: nameof(Course.UpdatedDate),
                parameterValue: inputCourse.UpdatedDate);

            var expectedCourseValidationException =
                new CourseValidationException(invalidCourseInputException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Returns(dateTime);

            // when
            ValueTask <Course> modifyCourseTask =
                this.courseService.ModifyCourseAsync(inputCourse);

            // then
            await Assert.ThrowsAsync <CourseValidationException>(() =>
                                                                 modifyCourseTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedCourseValidationException))),
                                          Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectCourseByIdAsync(It.IsAny <Guid>()),
                                          Times.Never);

            this.dateTimeBrokerMock.VerifyNoOtherCalls();
            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
        }
        public async Task ShouldThrowServiceExceptionOnModifyIfServiceExceptionOccursAndLogItAsync()
        {
            // given
            int            randomNegativeNumber = GetNegativeRandomNumber();
            DateTimeOffset randomDateTime       = GetRandomDateTime();
            Course         randomCourse         = CreateRandomCourse(randomDateTime);
            Course         someCourse           = randomCourse;

            someCourse.CreatedDate = randomDateTime.AddMinutes(randomNegativeNumber);
            var serviceException = new Exception();

            var failedCourseServiceException =
                new FailedCourseServiceException(serviceException);

            var expectedCourseServiceException =
                new CourseServiceException(failedCourseServiceException);

            this.dateTimeBrokerMock.Setup(broker =>
                                          broker.GetCurrentDateTime())
            .Throws(serviceException);

            // when
            ValueTask <Course> modifyCourseTask =
                this.courseService.ModifyCourseAsync(someCourse);

            // then
            await Assert.ThrowsAsync <CourseServiceException>(() =>
                                                              modifyCourseTask.AsTask());

            this.dateTimeBrokerMock.Verify(broker =>
                                           broker.GetCurrentDateTime(),
                                           Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(
                                                                    expectedCourseServiceException))),
                                          Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectCourseByIdAsync(It.IsAny <Guid>()),
                                          Times.Never);

            this.dateTimeBrokerMock.VerifyNoOtherCalls();
            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 35
0
        private static DateTimeOffset AddDurationTimeToEvent(DateTimeOffset FromDateTime, decimal TargetDuration, Timing.UnitsOfTime?TargetUnitsOfTime)
        {
            switch (TargetUnitsOfTime)
            {
            case Timing.UnitsOfTime.S:
            {
                return(FromDateTime.AddSeconds(Convert.ToDouble(TargetDuration)));
            }

            case Timing.UnitsOfTime.Min:
            {
                return(FromDateTime.AddMinutes(Convert.ToDouble(TargetDuration)));
            }

            case Timing.UnitsOfTime.H:
            {
                return(FromDateTime.AddHours(Convert.ToDouble(TargetDuration)));
            }

            case Timing.UnitsOfTime.D:
            {
                return(FromDateTime.AddDays(Convert.ToDouble(TargetDuration)));
            }

            case Timing.UnitsOfTime.Wk:
            {
                return(FromDateTime.AddDays(Convert.ToDouble(TargetDuration * 7)));
            }

            case Timing.UnitsOfTime.Mo:
            {
                return(FromDateTime.AddMonths(Convert.ToInt32(TargetDuration)));
            }

            case Timing.UnitsOfTime.A:
            {
                return(FromDateTime.AddYears(Convert.ToInt32(TargetDuration)));
            }

            default:
            {
                throw new System.ComponentModel.InvalidEnumArgumentException(TargetUnitsOfTime.ToString(), (int)TargetUnitsOfTime, typeof(Timing.UnitsOfTime));
            }
            }
        }
Ejemplo n.º 36
0
        public async Task ShouldThrowDependencyExceptionOnModifyIfDbUpdateExceptionOccursAndLogItAsync()
        {
            // given
            int            randomNegativeNumber = GetNegativeRandomNumber();
            DateTimeOffset randomDateTime       = GetRandomDateTime();
            Tag            someTag = CreateRandomTag(randomDateTime);

            someTag.CreatedDate = randomDateTime.AddMinutes(randomNegativeNumber);
            var databaseUpdateException = new DbUpdateException();

            var expectedTagDependencyException =
                new TagDependencyException(databaseUpdateException);

            this.storageBrokerMock.Setup(broker =>
                                         broker.SelectTagByIdAsync(someTag.Id))
            .ThrowsAsync(databaseUpdateException);

            //this.dateTimeBrokerMock.Setup(broker =>
            //    broker.GetCurrentDateTime())
            //        .Returns(randomDateTime);

            // when
            ValueTask <Tag> modifyTagTask =
                this.tagService.ModifyTagAsync(someTag);

            // then
            await Assert.ThrowsAsync <TagDependencyException>(() =>
                                                              modifyTagTask.AsTask());

            //this.dateTimeBrokerMock.Verify(broker =>
            //    broker.GetCurrentDateTime(),
            //        Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectTagByIdAsync(someTag.Id),
                                          Times.Once);

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedTagDependencyException))),
                                          Times.Once);

            this.dateTimeBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
            this.loggingBrokerMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 37
0
        public void TestMinutelyIntervalGetFireTimeAfter()
        {
            DateTimeOffset startCalendar = DateBuilder.DateOf(9, 30, 17, 1, 6, 2005);

            var yearlyTrigger = new CalendarIntervalTriggerImpl
            {
                StartTimeUtc       = startCalendar,
                RepeatIntervalUnit = IntervalUnit.Minute,
                RepeatInterval     = 100 // every 100 minutes
            };

            DateTimeOffset targetCalendar = startCalendar.AddMinutes(400); // jump 400 minutes (4 intervals)

            IList <DateTimeOffset> fireTimes = TriggerUtils.ComputeFireTimes(yearlyTrigger, null, 6);
            DateTimeOffset         fifthTime = fireTimes[4]; // get the fifth fire time

            Assert.AreEqual(targetCalendar, fifthTime, "Minutes increment result not as expected.");
        }
Ejemplo n.º 38
0
        public async Task SendAsync_MinFreshOneMinuteAndCachedResponseIsStillFreshForTenMinutes_CachedResponseIsReturned()
        {
            var request        = RequestBuilder.Request(HttpMethod.Get, Url).WithMinFresh(60).Build();
            var cachedResponse = ResponseBuilder.Response(HttpStatusCode.OK)
                                 .Created(TenMinutesAgo)
                                 .Expires(_testDate.AddMinutes(10))
                                 .Build();

            _cacheMock.Setup(x => x.Get(It.IsAny <string>())).Returns(() => cachedResponse);

            var response = await _client.SendAsync(request);

            Assert.Equal(cachedResponse, response);
            Assert.Equal(CacheStatus.Hit, response.Headers.GetCashewStatusHeader());
            _cacheMock.Verify(x => x.Get(It.IsAny <string>()), Times.Once);

            _cacheMock.Reset();
        }
Ejemplo n.º 39
0
		public static DateTimeOffset Round(this DateTimeOffset dateTime, RoundTo rt)
		{
			DateTimeOffset rounded;

		    switch (rt)
			{
				case RoundTo.Second:
					{
                        rounded = new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second,dateTime.Offset);
						if (dateTime.Millisecond >= 500)
						{
							rounded = rounded.AddSeconds(1);
						}
						break;
					}
				case RoundTo.Minute:
					{
                        rounded = new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, 0,dateTime.Offset);
						if (dateTime.Second >= 30)
						{
							rounded = rounded.AddMinutes(1);
						}
						break;
					}
				case RoundTo.Hour:
					{
                        rounded = new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, 0, 0,dateTime.Offset);
						if (dateTime.Minute >= 30)
						{
							rounded = rounded.AddHours(1);
						}
						break;
					}
				case RoundTo.Day:
					{
                        rounded = new DateTimeOffset(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0,dateTime.Offset);
						if (dateTime.Hour >= 12)
						{
							rounded = rounded.AddDays(1);
						}
						break;
					}
				default:
					{
                        throw new ArgumentOutOfRangeException("rt");
					}
			}

			return rounded;
		}
Ejemplo n.º 40
0
        public void TestMinutelyIntervalGetFireTimeAfter()
        {
            DateTimeOffset startCalendar = new DateTimeOffset(2005, 6, 1, 9, 30, 17, TimeSpan.Zero);

            CalendarIntervalTriggerImpl yearlyTrigger = new CalendarIntervalTriggerImpl();
            yearlyTrigger.StartTimeUtc = startCalendar;
            yearlyTrigger.RepeatIntervalUnit = IntervalUnit.Minute;
            yearlyTrigger.RepeatInterval = 100; // every 100 minutes

            DateTimeOffset targetCalendar = new DateTimeOffset(2005, 6, 1, 9, 30, 17, TimeSpan.Zero);

            targetCalendar = targetCalendar.AddMinutes(400); // jump 400 minutes (4 intervals)

            IList<DateTimeOffset> fireTimes = TriggerUtils.ComputeFireTimes(yearlyTrigger, null, 6);
            DateTimeOffset fifthTime = fireTimes[4]; // get the fifth fire time

            Assert.AreEqual(targetCalendar, fifthTime, "Minutes increment result not as expected.");
        }
        public void ToRelativeTimeTest()
        {
            var date = new DateTimeOffset(2015, 8, 7, 13, 26, 30, TimeSpan.Zero);
            var now = DateTimeOffset.Now;

            Assert.AreEqual("now", now.ToRelativeTimeString());
            Assert.AreEqual("now", now.ToRelativeTimeString(now));

            Assert.AreEqual("1 second ago", date.AddSeconds(-1).ToRelativeTimeString(date));
            Assert.AreEqual("10 seconds ago", date.AddSeconds(-10).ToRelativeTimeString(date));
            Assert.AreEqual("1 minute ago", date.AddSeconds(-90).ToRelativeTimeString(date));
            Assert.AreEqual("1 minute ago", date.AddSeconds(-100).ToRelativeTimeString(date));
            Assert.AreEqual("2 minutes ago", date.AddSeconds(-120).ToRelativeTimeString(date));
            Assert.AreEqual("7 minutes ago", date.AddMinutes(-7).ToRelativeTimeString(date));
            Assert.AreEqual("59 minutes ago", date.AddMinutes(-59).ToRelativeTimeString(date));
            Assert.AreEqual("1 hour ago", date.AddMinutes(-60).ToRelativeTimeString(date));
            Assert.AreEqual("1 hour ago", date.AddHours(-1).ToRelativeTimeString(date));
            Assert.AreEqual("9 hours ago", date.AddHours(-9).ToRelativeTimeString(date));
            Assert.AreEqual("1 day ago", date.AddHours(-24).ToRelativeTimeString(date));
            Assert.AreEqual("1 day ago", date.AddHours(-30).ToRelativeTimeString(date));
            Assert.AreEqual("2 days ago", date.AddHours(-48).ToRelativeTimeString(date));
            Assert.AreEqual("1 day ago", date.AddDays(-1).ToRelativeTimeString(date));
            Assert.AreEqual("12 days ago", date.AddDays(-12).ToRelativeTimeString(date));
            Assert.AreEqual("29 days ago", date.AddDays(-29).ToRelativeTimeString(date));
            Assert.AreEqual("1 month ago", date.AddDays(-30).ToRelativeTimeString(date));
            Assert.AreEqual("1 month ago", date.AddMonths(-1).ToRelativeTimeString(date));
            Assert.AreEqual("3 months ago", date.AddMonths(-3).ToRelativeTimeString(date));
            Assert.AreEqual("11 months ago", date.AddMonths(-11).ToRelativeTimeString(date));
            Assert.AreEqual("1 year ago", date.AddMonths(-12).ToRelativeTimeString(date));
            Assert.AreEqual("1 year ago", date.AddYears(-1).ToRelativeTimeString(date));
            Assert.AreEqual("3 years ago", date.AddYears(-3).ToRelativeTimeString(date));

            Assert.AreEqual("1 second from now", date.AddSeconds(1).ToRelativeTimeString(date));
            Assert.AreEqual("10 seconds from now", date.AddSeconds(10).ToRelativeTimeString(date));
            Assert.AreEqual("1 minute from now", date.AddSeconds(90).ToRelativeTimeString(date));
            Assert.AreEqual("1 minute from now", date.AddSeconds(100).ToRelativeTimeString(date));
            Assert.AreEqual("2 minutes from now", date.AddSeconds(120).ToRelativeTimeString(date));
            Assert.AreEqual("7 minutes from now", date.AddMinutes(7).ToRelativeTimeString(date));
            Assert.AreEqual("59 minutes from now", date.AddMinutes(59).ToRelativeTimeString(date));
            Assert.AreEqual("1 hour from now", date.AddMinutes(60).ToRelativeTimeString(date));
            Assert.AreEqual("1 hour from now", date.AddHours(1).ToRelativeTimeString(date));
            Assert.AreEqual("9 hours from now", date.AddHours(9).ToRelativeTimeString(date));
            Assert.AreEqual("1 day from now", date.AddDays(1).ToRelativeTimeString(date));
            Assert.AreEqual("1 day from now", date.AddHours(24).ToRelativeTimeString(date));
            Assert.AreEqual("12 days from now", date.AddDays(12).ToRelativeTimeString(date));
            Assert.AreEqual("29 days from now", date.AddDays(29).ToRelativeTimeString(date));
            Assert.AreEqual("1 month from now", date.AddDays(30).ToRelativeTimeString(date));
            Assert.AreEqual("1 month from now", date.AddMonths(1).ToRelativeTimeString(date));
            Assert.AreEqual("3 months from now", date.AddMonths(3).ToRelativeTimeString(date));
            Assert.AreEqual("11 months from now", date.AddMonths(11).ToRelativeTimeString(date));
            Assert.AreEqual("1 year from now", date.AddMonths(12).ToRelativeTimeString(date));
            Assert.AreEqual("1 year from now", date.AddYears(1).ToRelativeTimeString(date));
            Assert.AreEqual("3 years from now", date.AddYears(3).ToRelativeTimeString(date));
        }
Ejemplo n.º 42
0
 public static string ToDatabase(DateTimeOffset value)
 {
     if (value.Offset == TimeSpan.Zero)
         return value.ToString("yyyy-MM-dd HH:mm:ss.FFFFFF+00");
     var offset = value.Offset;
     if (offset.Minutes != 0)
         value = value.AddMinutes(offset.Minutes);
     if (offset.Hours >= 0)
         return value.ToString("yyyy-MM-dd HH:mm:ss.FFFFFF") + "+" + offset.Hours.ToString("00");
     return value.ToString("yyyy-MM-dd HH:mm:ss.FFFFFF") + offset.Hours.ToString("00");
 }
Ejemplo n.º 43
0
        /// <summary>
        /// Appends a wide tile with a big block of text. Used to display up-coming buses.
        /// </summary>
        public void AppendTileWithBlockTextAndLines(DateTimeOffset scheduledTime, string blockText, string statusText, string busName, string tripHeadsign, string stopName, string scheduledArrivalTime, string predictedArrivalTime)
        {
            //<tile>
            //  <visual>
            //    <binding template="TileWideBlockAndText01">
            //      <text id="1">Text Field 1</text>
            //      <text id="2">Text Field 2</text>
            //      <text id="3">Text Field 3</text>
            //      <text id="4">Text Field 4</text>
            //      <text id="5">T5</text>
            //      <text id="6">Text Field 6</text>
            //    </binding>  
            //  </visual>
            //</tile>
            var document = new XmlDocument();
            var rootElement = document.CreateElement("tile");
            document.AppendChild(rootElement);

            XmlElement visualElement = document.CreateElement("visual");
            visualElement.SetAttribute("version", "2");
            rootElement.AppendChild(visualElement);

            // Support large tiles for Win 8.1 and higher:
            //<visual version="2">
            //  <binding template="TileSquare310x310BlockAndText01">
            //    <text id="1">Text Field 1 (large text)</text>
            //    <text id="2">Text Field 2</text>
            //    <text id="3">Text Field 3</text>
            //    <text id="4">Text Field 4</text>
            //    <text id="5">Text Field 5</text>
            //    <text id="6">Text Field 6</text>
            //    <text id="7">Text Field 7</text>
            //    <text id="8">Text Field 8 (block text)</text>
            //    <text id="9">Text Field 9</text>
            //  </binding>  
            //</visual>
            XmlElement largeBindingElement = document.CreateElement("binding");
            largeBindingElement.SetAttribute("template", "TileSquare310x310BlockAndText01");

            AddSubTextElements(largeBindingElement, new string[]
            {
                busName,
                tripHeadsign,
                stopName,
                "SCHED / ETA",
                string.Format("{0} / {1}", scheduledArrivalTime, predictedArrivalTime),
                string.Empty,
                string.Empty,
                blockText,
                statusText,
            });

            visualElement.AppendChild(largeBindingElement);


            XmlElement wideBindingElement = document.CreateElement("binding");            
            wideBindingElement.SetAttribute("template", "TileWide310x150BlockAndText01");
            wideBindingElement.SetAttribute("fallback", "TileWideBlockAndText01");
            visualElement.AppendChild(wideBindingElement);

            AddSubTextElements(wideBindingElement, new string[]
            {
                busName,
                tripHeadsign,
                stopName,
                string.Format("{0} / {1}", scheduledArrivalTime, predictedArrivalTime),
                blockText,
                statusText,
            });

            // Unfortunately, there is only one small tile template that supports block text.
            //<tile>
            //  <visual>
            //    <binding template="TileSquareBlock">
            //      <text id="1">Text Field 1</text>
            //      <text id="2">Text Field 2</text>
            //    </binding>  
            //  </visual>
            //</tile>
            XmlElement smallBindingElement = document.CreateElement("binding");
            smallBindingElement.SetAttribute("template", "TileSquare150x150Block");
            smallBindingElement.SetAttribute("fallback", "TileSquareBlock");
            visualElement.AppendChild(smallBindingElement);

            XmlElement smallBlockTextElement = document.CreateElement("text");
            smallBlockTextElement.SetAttribute("id", "1");
            smallBlockTextElement.InnerText = blockText;
            smallBindingElement.AppendChild(smallBlockTextElement);

            XmlElement smallSubTextElement = document.CreateElement("text");
            smallSubTextElement.SetAttribute("id", "2");
            smallSubTextElement.InnerText = busName;
            smallBindingElement.AppendChild(smallSubTextElement);

            if ((scheduledTime - DateTime.Now).TotalMinutes < 1)
            {
                var notification = new TileNotification(document);
                notification.ExpirationTime = scheduledTime.AddMinutes(1);
                notification.Tag = (busName + tripHeadsign + stopName + scheduledTime.ToString("hh:mm")).GetHashCode().ToString("X");
                this.tileUpdater.Update(notification);
            }
            else
            {
                var notification = new ScheduledTileNotification(document, scheduledTime);
                notification.ExpirationTime = scheduledTime.AddMinutes(1);
                notification.Tag = (busName + tripHeadsign + stopName + scheduledTime.ToString("hh:mm")).GetHashCode().ToString("X");
                this.tileUpdater.AddToSchedule(notification);
            }
        }
Ejemplo n.º 44
0
 public void DividingNone()
 {
     var now = new DateTimeOffset(2013, 8, 13, 13, 0, 0, TimeSpan.FromHours(12));
     var availableTime = new TimeRange(now, now.AddMinutes(14));
     var freeSlots = availableTime
         .Divide(TimeSpan.FromMinutes(15))
         .ToArray();
     Assert.AreEqual(0, freeSlots.Length);
 }
Ejemplo n.º 45
0
 public static void AddMinutes(DateTimeOffset dateTimeOffset, double minutes, DateTimeOffset expected)
 {
     Assert.Equal(expected, dateTimeOffset.AddMinutes(minutes));
 }
Ejemplo n.º 46
0
 public void DividingUneven()
 {
     var now = new DateTimeOffset(2013, 8, 13, 13, 0, 0, TimeSpan.FromHours(12));
     var availableTime = new TimeRange(now, now.AddMinutes(59));
     var freeSlots = availableTime
         .Divide(TimeSpan.FromMinutes(15))
         .ToArray();
     Assert.AreEqual(3, freeSlots.Length);
     Assert.IsTrue(freeSlots.All(s => s.Duration == TimeSpan.FromMinutes(15)));
 }
 private static string RenderArrivalTime(DateTimeOffset currentTime, int minutesFromNow)
 {
     if (minutesFromNow > 30)
     {
         return currentTime.AddMinutes(minutesFromNow).ToString("h:mm tt");
     }
     if (minutesFromNow == 1)
     {
         return $"{minutesFromNow} minute";
     }
     return $"{minutesFromNow} minutes";
 }
Ejemplo n.º 48
0
        public void CanAddMinutesAcrossDstTransition()
        {
            var tz = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
            var dto = new DateTimeOffset(2015, 3, 8, 1, 59, 0, TimeSpan.FromHours(-8));
            var result = dto.AddMinutes(1, tz);

            var expected = new DateTimeOffset(2015, 3, 8, 3, 0, 0, TimeSpan.FromHours(-7));
            Assert.Equal(expected, result);
            Assert.Equal(expected.Offset, result.Offset);
        }
        /// <summary>
        /// Determines if the current rule should be applied depending on the time pattern that has been applied to it.
        /// </summary>
        /// <param name="timezone">The timezone to adjust for. This will typically be the timezone set by the user that owns
        /// the dialplan. If no timezone is specified UTC will be assumed.</param>
        /// <returns>True if the rule should be applied, false otherwise.</returns>
        public bool IsTimeMatch(DateTimeOffset now, string timezone)
        {
            var localTime = now.AddMinutes(TimeZoneHelper.GetTimeZonesUTCOffsetMinutes(timezone));

            if (localTime.DayOfWeek == DayOfWeek.Monday && TimePattern.IndexOf("M", StringComparison.OrdinalIgnoreCase) == -1)
            {
                return false;
            }
            else if (localTime.DayOfWeek == DayOfWeek.Tuesday && TimePattern.IndexOf("Tu", StringComparison.OrdinalIgnoreCase) == -1)
            {
                return false;
            }
            else if (localTime.DayOfWeek == DayOfWeek.Wednesday && TimePattern.IndexOf("W", StringComparison.OrdinalIgnoreCase) == -1)
            {
                return false;
            }
            else if (localTime.DayOfWeek == DayOfWeek.Thursday && TimePattern.IndexOf("Th", StringComparison.OrdinalIgnoreCase) == -1)
            {
                return false;
            }
            else if (localTime.DayOfWeek == DayOfWeek.Friday && TimePattern.IndexOf("F", StringComparison.OrdinalIgnoreCase) == -1)
            {
                return false;
            }
            else if (localTime.DayOfWeek == DayOfWeek.Saturday && TimePattern.IndexOf("Sa", StringComparison.OrdinalIgnoreCase) == -1)
            {
                return false;
            }
            else if (localTime.DayOfWeek == DayOfWeek.Sunday && TimePattern.IndexOf("Su", StringComparison.OrdinalIgnoreCase) == -1)
            {
                return false;
            }

            var timesMatch = Regex.Match(TimePattern, TIMES_REGEX);
            if(timesMatch.Success)
            {
                int startHour = Convert.ToInt32(timesMatch.Result("${startHour}"));
                int startMinute = Convert.ToInt32(timesMatch.Result("${startMinute}"));
                int endHour = Convert.ToInt32(timesMatch.Result("${endHour}"));
                int endMinute = Convert.ToInt32(timesMatch.Result("${endMinute}"));

                TimeSpan startTime = new TimeSpan(startHour, startMinute, 0);
                TimeSpan endTime = new TimeSpan(endHour, endMinute, 0);

                if (localTime.TimeOfDay < startTime || localTime.TimeOfDay > endTime)
                {
                    return false;
                }
            }

            return true;
        }
Ejemplo n.º 50
0
		private static int Main(string[] args)
		{
			CommandLineParser clp = new CommandLineParser();
			clp.AddKnownOption("a", "assembly-info");
			clp.AddKnownOption("", "test-b36min");
			clp.AddKnownOption("b", "test-bmin");
			clp.AddKnownOption("f", "format", true);
			clp.AddKnownOption("h", "help");
			clp.AddKnownOption("i", "ignore-missing");
			clp.AddKnownOption("m", "multi-project");
			clp.AddKnownOption("r", "revision");
			clp.AddKnownOption("s", "restore");
			clp.AddKnownOption("v", "version");
			clp.AddKnownOption("x", "test-xmin");
			clp.AddKnownOption("B", "de-bmin");
			clp.AddKnownOption("", "de-b36min");
			clp.AddKnownOption("D", "de-dmin");
			clp.AddKnownOption("I", "only-infver");
			clp.AddKnownOption("M", "stop-if-modified");
			clp.AddKnownOption("X", "de-xmin");
			clp.AddKnownOption("", "debug");

			debugOutput = clp.IsOptionSet("debug");

			if (clp.IsOptionSet("h") || clp.IsOptionSet("v"))
			{
				HandleHelp(clp.IsOptionSet("h"));
				return 0;
			}
			if (clp.IsOptionSet("X"))
			{
				int baseYear;
				if (!int.TryParse(clp.GetArgument(0), out baseYear))
				{
					Console.Error.WriteLine("Invalid argument: Base year expected");
					return 1;
				}
				string xmin = clp.GetArgument(1).Trim().ToLowerInvariant();
				DateTime time = DehexMinutes(baseYear, xmin);
				if (time == DateTime.MinValue)
				{
					Console.Error.WriteLine("Invalid xmin value.");
					return 0;
				}
				Console.WriteLine(time.ToString("yyyy-MM-dd HH:mm") + " UTC");
				Console.WriteLine(time.ToLocalTime().ToString("yyyy-MM-dd HH:mm K"));
				return 0;
			}
			if (clp.IsOptionSet("B"))
			{
				int baseYear;
				if (!int.TryParse(clp.GetArgument(0), out baseYear))
				{
					Console.Error.WriteLine("Invalid argument: Base year expected");
					return 1;
				}
				string bmin = clp.GetArgument(1).Trim().ToLowerInvariant();
				DateTime time = Debase28Minutes(baseYear, bmin);
				if (time == DateTime.MinValue)
				{
					Console.Error.WriteLine("Invalid bmin value.");
					return 0;
				}
				Console.WriteLine(time.ToString("yyyy-MM-dd HH:mm") + " UTC");
				Console.WriteLine(time.ToLocalTime().ToString("yyyy-MM-dd HH:mm K"));
				return 0;
			}
			if (clp.IsOptionSet("de-b36min"))
			{
				int baseYear;
				if (!int.TryParse(clp.GetArgument(0), out baseYear))
				{
					Console.Error.WriteLine("Invalid argument: Base year expected");
					return 1;
				}
				string bmin = clp.GetArgument(1).Trim().ToLowerInvariant();
				DateTime time = Debase36Minutes(baseYear, bmin);
				if (time == DateTime.MinValue)
				{
					Console.Error.WriteLine("Invalid b36min value.");
					return 0;
				}
				Console.WriteLine(time.ToString("yyyy-MM-dd HH:mm") + " UTC");
				Console.WriteLine(time.ToLocalTime().ToString("yyyy-MM-dd HH:mm K"));
				return 0;
			}
			if (clp.IsOptionSet("D"))
			{
				int baseYear;
				if (!int.TryParse(clp.GetArgument(0), out baseYear))
				{
					Console.Error.WriteLine("Invalid argument: Base year expected");
					return 1;
				}
				string dmin = clp.GetArgument(1).Trim();
				DateTime time = DedecMinutes(baseYear, dmin);
				if (time == DateTime.MinValue)
				{
					Console.Error.WriteLine("Invalid dmin value.");
					return 0;
				}
				Console.WriteLine(time.ToString("yyyy-MM-dd HH:mm") + " UTC");
				Console.WriteLine(time.ToLocalTime().ToString("yyyy-MM-dd HH:mm K"));
				return 0;
			}
			if (clp.IsOptionSet("x"))
			{
				int baseYear;
				if (!int.TryParse(clp.GetArgument(0), out baseYear))
				{
					Console.Error.WriteLine("Invalid argument: Base year expected");
					return 1;
				}
				revTime = DateTime.UtcNow;
				long ticks1min = TimeSpan.FromMinutes(1).Ticks;
				revTime = new DateTime(revTime.Ticks / ticks1min * ticks1min, DateTimeKind.Utc);
				for (int i = 0; i < 10; i++)
				{
					Console.WriteLine(revTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm K") + " = " + HexMinutes(baseYear, 1));
					revTime = revTime.AddMinutes(1);
				}
				return 0;
			}
			if (clp.IsOptionSet("b"))
			{
				int baseYear;
				if (!int.TryParse(clp.GetArgument(0), out baseYear))
				{
					Console.Error.WriteLine("Invalid argument: Base year expected");
					return 1;
				}
				revTime = DateTime.UtcNow;
				long ticks20min = TimeSpan.FromMinutes(20).Ticks;
				revTime = new DateTime(revTime.Ticks / ticks20min * ticks20min, DateTimeKind.Utc);
				for (int i = 0; i < 10; i++)
				{
					Console.WriteLine(revTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm K") + " = " + Base28Minutes(baseYear, 1));
					revTime = revTime.AddMinutes(20);
				}
				return 0;
			}
			if (clp.IsOptionSet("test-b36min"))
			{
				int baseYear;
				if (!int.TryParse(clp.GetArgument(0), out baseYear))
				{
					Console.Error.WriteLine("Invalid argument: Base year expected");
					return 1;
				}
				revTime = DateTime.UtcNow;
				long ticks10min = TimeSpan.FromMinutes(10).Ticks;
				revTime = new DateTime(revTime.Ticks / ticks10min * ticks10min, DateTimeKind.Utc);
				for (int i = 0; i < 10; i++)
				{
					Console.WriteLine(revTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm K") + " = " + Base36Minutes(baseYear, 1));
					revTime = revTime.AddMinutes(10);
				}
				return 0;
			}

			buildTime = DateTimeOffset.Now;

			bool patchAssemblyInfoFile = clp.IsOptionSet("a");
			bool restoreAssemblyInfoFile = clp.IsOptionSet("s");
			multiProjectMode = clp.IsOptionSet("m");
			bool showRevision = clp.IsOptionSet("r");
			bool stopIfModified = clp.IsOptionSet("M");
			bool ignoreMissing = clp.IsOptionSet("i");
			onlyInformationalVersion = clp.IsOptionSet("I");
			string path = clp.GetArgument(0);
			string customFormat = "{!}{commit}";
			if (clp.IsOptionSet("f"))
				customFormat = clp.GetOptionValue("f");

			if (!patchAssemblyInfoFile && !restoreAssemblyInfoFile && !showRevision)
				showRevision = true;   // Default action
			if (string.IsNullOrEmpty(path))
				path = ".";
			if (debugOutput)
				Console.Error.WriteLine("Working on path " + path);

			bool hasProcessed = false;

			List<string> projectDirs = new List<string>();
			if (multiProjectMode)
			{
				// Treat the single directory argument as the solution file name
				if (!path.ToLowerInvariant().EndsWith(".sln"))
				{
					Console.Error.WriteLine("Error: Specified file name is invalid. Only *.sln files accepted in\nmulti-project mode.");
					return 1;
				}
				if (!File.Exists(path))
				{
					Console.Error.WriteLine("Error: Specified solution file does not exist.");
					return 1;
				}

				// Scan the solution file for projects and add them to the list
				string solutionDir = Path.GetDirectoryName(path);
				using (StreamReader sr = new StreamReader(path))
				{
					while (!sr.EndOfStream)
					{
						string line = sr.ReadLine();
						Match m = Regex.Match(line, @"^Project\(.+\) = "".+"", ""(.+\.(?:csproj|vbproj))""");
						if (m.Success)
						{
							string projectPath = Path.Combine(solutionDir, m.Groups[1].Value);
							string projectDir = Path.GetDirectoryName(projectPath);
							if (debugOutput)
								Console.Error.WriteLine("Add project in " + projectDir);
							projectDirs.Add(projectDir);
						}
					}
				}

				if (projectDirs.Count == 0)
				{
					Console.Error.WriteLine("Error: Specified solution file contains no projects.");
					return 1;
				}

				// From now on, work with the solution directory as default path to get the revision of
				path = solutionDir;
			}

			if (patchAssemblyInfoFile)
			{
				if (!hasProcessed)
				{
					ProcessDirectory(path, ignoreMissing, true);
					if (revision == 0)
					{
						if (ignoreMissing)
						{
							revTime = DateTimeOffset.Now;
						}
						else
						{
							Console.Error.WriteLine("Error: Not a Subversion working directory.");
							return 1;
						}
					}
					hasProcessed = true;
				}

				if (stopIfModified && isModified)
				{
					Console.Error.WriteLine("Error: Subversion working directory contains uncommited changes, stop requested by option.");
					return 1;
				}

				if (multiProjectMode)
				{
					bool success = true;
					foreach (string projectDir in projectDirs)
					{
						success &= PatchAssemblyInfoFile(projectDir);
					}
					if (!success)
					{
						return 1;
					}
				}
				else
				{
					if (!PatchAssemblyInfoFile(path))
					{
						return 1;
					}
				}
			}
			if (restoreAssemblyInfoFile)
			{
				if (multiProjectMode)
				{
					bool success = true;
					foreach (string projectDir in projectDirs)
					{
						success &= RestoreAssemblyInfoFile(projectDir);
					}
					if (!success)
					{
						return 1;
					}
				}
				else
				{
					if (!RestoreAssemblyInfoFile(path))
					{
						return 1;
					}
				}
			}
			if (showRevision)
			{
				if (!hasProcessed)
				{
					ProcessDirectory(path, ignoreMissing, true);
					if (revision == 0)
					{
						if (ignoreMissing)
						{
							revTime = DateTimeOffset.Now;
						}
						else
						{
							Console.Error.WriteLine("Error: Not a Subversion working directory.");
							return 1;
						}
					}
					hasProcessed = true;
				}

				Console.WriteLine(ResolveFormat(customFormat));
			}

			return 0;
		}
Ejemplo n.º 51
0
        public void Subtracting()
        {
            var now = new DateTimeOffset(2013, 8, 13, 13, 0, 0, TimeSpan.FromHours(12));
            var tick = new TimeSpan(1);
            var time = new TimeRange(now, now.AddHours(1));
            var before = new TimeRange(now - TimeSpan.FromHours(1), time.StartsOn);
            var after = new TimeRange(time.EndsOn, TimeSpan.FromHours(1));
            var mid = new TimeRange(now.AddMinutes(15), TimeSpan.FromMinutes(30));

            // No intersection
            Assert.AreEqual(1, time.Subtract(before).Count());
            Assert.AreEqual(time, time.Subtract(before).First());
            Assert.AreEqual(1, time.Subtract(after).Count());
            Assert.AreEqual(time, time.Subtract(after).First());

            // Identity
            Assert.AreEqual(0, time.Subtract(time).Count());

            // Subsumes
            Assert.AreEqual(0, time.Subtract(new TimeRange(before.StartsOn, after.EndsOn)).Count());

            // Middle
            Assert.AreEqual(2, time.Subtract(mid).Count());
            Assert.IsTrue(time.Subtract(mid).Any(t => t.StartsOn == now && t.Duration == TimeSpan.FromMinutes(15)));
            Assert.IsTrue(time.Subtract(mid).Any(t => t.StartsOn == now.AddMinutes(45) && t.Duration == TimeSpan.FromMinutes(15)));
        }
Ejemplo n.º 52
0
        public async Task ProcessAsync_UsesExpiresOn_ToExpireCacheEntry()
        {
            // Arrange - 1
            var currentTime = new DateTimeOffset(2010, 1, 1, 0, 0, 0, TimeSpan.Zero);
            var id = "unique-id";
            var childContent1 = "original-child-content";
            var clock = new Mock<ISystemClock>();
            clock.SetupGet(p => p.UtcNow)
                 .Returns(() => currentTime);
            var cache = new MemoryCache(new MemoryCacheOptions { Clock = clock.Object });
            var tagHelperContext1 = GetTagHelperContext(id, childContent1);
            var tagHelperOutput1 = new TagHelperOutput("cache", new TagHelperAttributeList { { "attr", "value" } });
            tagHelperOutput1.PreContent.SetContent("<cache>");
            tagHelperOutput1.PostContent.SetContent("</cache>");
            var cacheTagHelper1 = new CacheTagHelper(cache)
            {
                ViewContext = GetViewContext(),
                ExpiresOn = currentTime.AddMinutes(5)
            };

            // Act - 1
            await cacheTagHelper1.ProcessAsync(tagHelperContext1, tagHelperOutput1);

            // Assert - 1
            Assert.Empty(tagHelperOutput1.PreContent.GetContent());
            Assert.Empty(tagHelperOutput1.PostContent.GetContent());
            Assert.True(tagHelperOutput1.IsContentModified);
            Assert.Equal(childContent1, tagHelperOutput1.Content.GetContent());

            // Arrange - 2
            currentTime = currentTime.AddMinutes(5).AddSeconds(2);
            var childContent2 = "different-content";
            var tagHelperContext2 = GetTagHelperContext(id, childContent2);
            var tagHelperOutput2 = new TagHelperOutput("cache", new TagHelperAttributeList { { "attr", "value" } });
            tagHelperOutput2.PreContent.SetContent("<cache>");
            tagHelperOutput2.PostContent.SetContent("</cache>");
            var cacheTagHelper2 = new CacheTagHelper(cache)
            {
                ViewContext = GetViewContext(),
                ExpiresOn = currentTime.AddMinutes(5)
            };

            // Act - 2
            await cacheTagHelper2.ProcessAsync(tagHelperContext2, tagHelperOutput2);

            // Assert - 2
            Assert.Empty(tagHelperOutput2.PreContent.GetContent());
            Assert.Empty(tagHelperOutput2.PostContent.GetContent());
            Assert.True(tagHelperOutput2.IsContentModified);
            Assert.Equal(childContent2, tagHelperOutput2.Content.GetContent());
        }
Ejemplo n.º 53
0
 private static DateTimeOffset TranslatedAdd(DateTimeOffset date, IntervalUnit unit, int amountToAdd)
 {
     switch (unit)
     {
         case IntervalUnit.Day:
             return date.AddDays(amountToAdd);
         case IntervalUnit.Hour:
             return date.AddHours(amountToAdd);
         case IntervalUnit.Minute:
             return date.AddMinutes(amountToAdd);
         case IntervalUnit.Month:
             return date.AddMonths(amountToAdd);
         case IntervalUnit.Second:
             return date.AddSeconds(amountToAdd);
         case IntervalUnit.Millisecond:
             return date.AddMilliseconds(amountToAdd);
         case IntervalUnit.Week:
             return date.AddDays(amountToAdd*7);
         case IntervalUnit.Year:
             return date.AddYears(amountToAdd);
         default:
             throw new ArgumentException("Unknown IntervalUnit");
     }
 }
Ejemplo n.º 54
0
        /// <summary>
        /// Appends a wide tile with a big block of text. Used to display up-coming buses.
        /// </summary>
        public void AppendTileWithBlockTextAndLines(DateTimeOffset scheduledTime, string blockText, string subBlockText, string text1 = null, string text2 = null, string text3 = null, string text4 = null)
        {
            //<tile>
            //  <visual>
            //    <binding template="TileWideBlockAndText01">
            //      <text id="1">Text Field 1</text>
            //      <text id="2">Text Field 2</text>
            //      <text id="3">Text Field 3</text>
            //      <text id="4">Text Field 4</text>
            //      <text id="5">T5</text>
            //      <text id="6">Text Field 6</text>
            //    </binding>  
            //  </visual>
            //</tile>
            var document = new XmlDocument();
            var rootElement = document.CreateElement("tile");
            document.AppendChild(rootElement);

            XmlElement visualElement = document.CreateElement("visual");
            rootElement.AppendChild(visualElement);

            XmlElement wideBindingElement = document.CreateElement("binding");
            wideBindingElement.SetAttribute("template", "TileWideBlockAndText01");
            visualElement.AppendChild(wideBindingElement);

            string[] wideTexts = new string[]
            {
                text1,
                text2,
                text3,
                text4,
                blockText,
                subBlockText,
            };

            for (int i = 0; i < wideTexts.Length; i++)
            {
                string text = wideTexts[i];
                if (!string.IsNullOrEmpty(text))
                {
                    XmlElement textElement = document.CreateElement("text");
                    textElement.SetAttribute("id", (i + 1).ToString());
                    textElement.InnerText = text;
                    wideBindingElement.AppendChild(textElement);
                }
            }

            // Unfortunately, there is only one small tile template that supports block text.
            //<tile>
            //  <visual>
            //    <binding template="TileSquareBlock">
            //      <text id="1">Text Field 1</text>
            //      <text id="2">Text Field 2</text>
            //    </binding>  
            //  </visual>
            //</tile>
            XmlElement smallBindingElement = document.CreateElement("binding");
            smallBindingElement.SetAttribute("template", "TileSquareBlock");
            visualElement.AppendChild(smallBindingElement);

            XmlElement smallBlockTextElement = document.CreateElement("text");
            smallBlockTextElement.SetAttribute("id", "1");
            smallBlockTextElement.InnerText = blockText;
            smallBindingElement.AppendChild(smallBlockTextElement);

            XmlElement smallSubTextElement = document.CreateElement("text");
            smallSubTextElement.SetAttribute("id", "2");
            smallSubTextElement.InnerText = text1;
            smallBindingElement.AppendChild(smallSubTextElement);

            if ((scheduledTime - DateTime.Now).TotalMinutes < 1)
            {
                var notification = new TileNotification(document);
                notification.ExpirationTime = scheduledTime.AddMinutes(1);
                notification.Tag = (text1 + text2 + text3 + scheduledTime.ToString("hh:mm")).GetHashCode().ToString("X");
                this.tileUpdater.Update(notification);
            }
            else
            {
                var notification = new ScheduledTileNotification(document, scheduledTime);
                notification.ExpirationTime = scheduledTime.AddMinutes(1);
                notification.Tag = (text1 + text2 + text3 + scheduledTime.ToString("hh:mm")).GetHashCode().ToString("X");
                this.tileUpdater.AddToSchedule(notification);
            }
        }
Ejemplo n.º 55
0
        private async void buyMag_Click(object sender, RoutedEventArgs e)
        {
            if (licenseInformation == null) return;

            if (!licenseInformation.ProductLicenses[product_id].IsActive)
            {
                try
                {
                    // The customer doesn't own this feature, so 
                    // show the purchase dialog.

                    var receipt = await CurrentAppSimulator.RequestProductPurchaseAsync(product_id, true);
                    if (!licenseInformation.ProductLicenses[product_id].IsActive || receipt == "") return;
                    await DownloadManager.StoreReceiptAsync(product_id, receipt);
                    // the in-app purchase was successful

                    // TEST ONLY
                    // =================================================
                    var f = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\test\receipt.pmd");
                    var xml = new XmlDocument();
                    xml = await XmlDocument.LoadFromFileAsync(f);
                    var item = xml.GetElementsByTagName("ProductReceipt")[0] as XmlElement;
                    item.SetAttribute("ProductId", product_id);
                    var date = new DateTimeOffset(DateTime.Now);
                    date = date.AddMinutes(3);
                    var str = date.ToString("u");
                    str = str.Replace(" ", "T");
                    item.SetAttribute("ExpirationDate", str);
                    receipt = xml.GetXml();
                    if (DownloadManager.ReceiptExpired(receipt)) return;
                    // =================================================

                    buyMag.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    if (Bought != null)
                    {
                        Bought(this, DownloadManager.GetUrl(product_id, receipt, relativePath));
                        this.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    }
                    else
                    {
                        var messageDialog = new MessageDialog("Purchase successfull");
                        var task = messageDialog.ShowAsync().AsTask();
                    }
                }
                catch (Exception)
                {
                    // The in-app purchase was not completed because 
                    // an error occurred.
                    var messageDialog = new MessageDialog("Unexpected error");
                    var task = messageDialog.ShowAsync().AsTask();
                }
            }
            else
            {
                var messageDialog = new MessageDialog("You already purchased this app");
                var task = messageDialog.ShowAsync().AsTask();
            }
        }
Ejemplo n.º 56
0
        public static async Task StoreReceiptAsync(string productId, string receipt)
        {
            if (productId.Contains("subscritpion") && DownloadManager.ReceiptExpired(receipt)) return;

            var encryptedFilename = CipherEncryption(productId);
            var encodedFileName = Convert.ToBase64String(encryptedFilename.ToArray());
            var encodedAndEscapedFilename = encodedFileName.Replace('/', '-');

            // TEST ONLY
            // =================================================
            var f = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\test\receipt.pmd");
            var xml = new XmlDocument();
            xml = await XmlDocument.LoadFromFileAsync(f);
            var item = xml.GetElementsByTagName("ProductReceipt")[0] as XmlElement;
            item.SetAttribute("ProductId", productId);
            var date = new DateTimeOffset(DateTime.Now);
            date = date.AddMinutes(3);
            var str = date.ToString("u");
            str = str.Replace(" ", "T");
            item.SetAttribute("ExpirationDate", str);
            receipt = xml.GetXml();
            if (DownloadManager.ReceiptExpired(receipt)) return;
            // =================================================

            var folder = ApplicationData.Current.RoamingFolder;
            if (folder == null) return;
            folder = await folder.CreateFolderAsync("Receipts", CreationCollisionOption.OpenIfExists);

            var file = await folder.CreateFileAsync(encodedAndEscapedFilename + ".pmd", CreationCollisionOption.ReplaceExisting);

            IBuffer buffEncrypted = CipherEncryption(receipt);

            var stream = await file.OpenAsync(FileAccessMode.ReadWrite);
            await stream.WriteAsync(buffEncrypted);
            await stream.FlushAsync();
            stream.Dispose();

            stream = null;
            buffEncrypted = null;
            file = null;

            ApplicationData.Current.SignalDataChanged();

            //CipherDecryption(buffEncrypted);
        }
        public async System.Threading.Tasks.Task ReturnNoErrorForItineraryTaskWhenModelsDatesAreValid()
        {
            var now = new DateTimeOffset(2016, 10, 4, 8, 0, 0, TimeSpan.FromSeconds(0));

            var @event = new Event { Campaign = new Campaign { TimeZoneId = "UTC", }, StartDateTime = now, EndDateTime = now.AddDays(1), TimeZoneId = "UTC", EventType = EventType.Itinerary };

            var mockMediator = new Mock<IMediator>();
            mockMediator.Setup(x => x.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(@event);

            var validator = new TaskEditViewModelValidator(mockMediator.Object);
            var errors = await validator.Validate(new EditViewModel
            {
                StartDateTime = now.AddMinutes(15),
                EndDateTime = now.AddMinutes(120)
            });

            Assert.True(errors.Count == 0);
        }
        private async void btnSaveNoteExtra_Click(object sender, RoutedEventArgs e)
        {
            if (chkTimer.IsChecked == true)
            {
                if (!VerifyDateIsFuture(dtmDate.Date))
                {
                    await (new MessageDialog(AppConstants.AppMessages[AppConstants.UsedLanguage]["np_verifyDate"]).ShowAsync());
                    return;
                }

                if (!VerifyTimeIsFuture(dtmTime.Time))
                {
                    await (new MessageDialog(AppConstants.AppMessages[AppConstants.UsedLanguage]["np_verifyTime"]).ShowAsync());
                    return;
                }

                DateTimeOffset scheduledDateTime = new DateTimeOffset(dtmDate.Date.Year, dtmDate.Date.Month, dtmDate.Date.Day, 0, 0, 0, dtmDate.Date.Offset);
                scheduledDateTime = scheduledDateTime.AddMinutes(dtmTime.Time.TotalMinutes);
                TmpShedule.Schedule = (int)scheduledDateTime.UtcDateTime.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

                if  (_noteItem != null)
                {
                    if (TmpShedule.Schedule != _noteItem.N_timer_timestamp)
                        TmpShedule.IsChanged = true;
                }
                else
                {
                    TmpShedule.IsChanged = true;
                }
            }

            if (chkPassword.IsChecked == true)
            {
                if (_isPassword && (txtNoteOldPassword.Visibility == Visibility.Visible))
                {
                    if (!Hash.VerifyHash(txtNoteOldPassword.Password, _noteItem.N_shadow))
                    {
                        await (new MessageDialog(AppConstants.AppMessages[AppConstants.UsedLanguage]["np_verifyHash"]).ShowAsync());
                        return;
                    }

                    if (string.IsNullOrEmpty(txtNoteOldPassword.Password) || string.IsNullOrWhiteSpace(txtNoteOldPassword.Password))
                    {
                        await (new MessageDialog(AppConstants.AppMessages[AppConstants.UsedLanguage]["np_verifyPass"]).ShowAsync());
                        return;
                    }
                }

                if (string.IsNullOrEmpty(txtNotePassword.Password) || string.IsNullOrWhiteSpace(txtNotePassword.Password))
                {
                    await (new MessageDialog(AppConstants.AppMessages[AppConstants.UsedLanguage]["np_verifyPass"]).ShowAsync());
                    return;
                }

                TmpPassword.IsChanged = true;
                TmpPassword.NewPassword = txtNotePassword.Password;
            }

            if (TmpPassword.IsChanged || TmpShedule.IsChanged)
                Frame.GoBack();
        }
        private bool DaylightSavingHourShiftOccuredAndAdvanceNeeded(ref DateTimeOffset newTime, int initialHourOfDay)
        {
            //need to apply timezone again to properly check if initialHourOfDay has changed.
            DateTimeOffset toCheck = TimeZoneUtil.ConvertTime(newTime, this.TimeZone);

            if (PreserveHourOfDayAcrossDaylightSavings && toCheck.Hour != initialHourOfDay)
            {
                //first apply the date, and then find the proper timezone offset
                newTime = new DateTimeOffset(newTime.Year, newTime.Month, newTime.Day, initialHourOfDay, newTime.Minute, newTime.Second, newTime.Millisecond, TimeSpan.Zero);
                newTime = new DateTimeOffset(newTime.DateTime, this.TimeZone.GetUtcOffset(newTime.DateTime));

                //TimeZone.IsInvalidTime is true, if this hour does not exist in the specified timezone
                bool isInvalid = this.TimeZone.IsInvalidTime(newTime.DateTime);

                if (isInvalid && skipDayIfHourDoesNotExist)
                {
                    return skipDayIfHourDoesNotExist;
                }
                else
                {
                    //don't skip this day, instead find cloest valid time by adding minutes.
                    while (this.TimeZone.IsInvalidTime(newTime.DateTime))
                    {
                        newTime = newTime.AddMinutes(1);
                    }

                    //apply proper offset for the adjusted time
                    newTime = new DateTimeOffset(newTime.DateTime, this.TimeZone.GetUtcOffset(newTime.DateTime));
                }
            }
            return false;
        }
        public void CancelTest()
        {
            var testScheduler = new TestScheduler();
            var recorder = testScheduler.CreateObserver<int>();

            var notifier = new ScheduledNotifier<int>(testScheduler);
            notifier.Subscribe(recorder);

            var noCancel1 = notifier.Report(10, TimeSpan.FromMinutes(1));
            var cancel1 = notifier.Report(20, TimeSpan.FromMinutes(3));
            cancel1.Dispose();

            recorder.Messages.Count.Is(0);
            testScheduler.AdvanceBy(TimeSpan.FromMinutes(5).Ticks);
            recorder.Messages.Count.Is(1);
            recorder.Messages[0].Is(OnNext(TimeSpan.FromMinutes(1).Ticks, 10));

            var lastTime = recorder.Messages.Last().Time;
            recorder.Messages.Clear();

            var origin = new DateTimeOffset(1999, 1, 1, 1, 1, 1, TimeSpan.Zero);
            var noCancel2 = notifier.Report(30, origin.AddMinutes(1));
            var cancel2 = notifier.Report(40, origin.AddMinutes(3));
            cancel2.Dispose();

            testScheduler.AdvanceTo(origin.AddMinutes(5).Ticks);
            recorder.Messages.Is(
                OnNext(origin.AddMinutes(1).Ticks, 30));
        }