private static void InitCustomers()
        {
            DateTimeOffset dto = new DateTimeOffset(2015, 1, 1, 1, 2, 3, 4, TimeSpan.Zero);
            _customers = Enumerable.Range(1, 5).Select(e =>
                new DCustomer
                {
                    Id = e,
                    DateTime = dto.AddYears(e).DateTime,
                    Offset = e % 2 == 0 ? dto.AddMonths(e) : dto.AddDays(e).AddMilliseconds(10),
                    Date = e % 2 == 0 ? dto.AddDays(e).Date : dto.AddDays(-e).Date,
                    TimeOfDay = e % 3 == 0 ? dto.AddHours(e).TimeOfDay : dto.AddHours(-e).AddMilliseconds(10).TimeOfDay,

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

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

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

                }).ToList();
        }
Example #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);
        }
Example #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);
    }
Example #4
0
        static void Main(string[] args)
        {
            //var offset = DateTimeOffset.Now;
            //Debug.WriteLine(offset);

            //Debug.WriteLine(DateTimeOffset.UtcNow);

            //String s = "10/1/2014 6:17 PM";
            //DateTime dt = DateTime.ParseExact(s, "MM/dd/yyyy h:mm tt", CultureInfo.InvariantCulture);
            //DateTimeOffset dto = new DateTimeOffset(dt);
            DateTimeOffset dto1 = new DateTimeOffset();

            dto1 = DateTimeOffset.Now;
            dto1 = dto1.AddHours(2);
            dto1 = dto1.AddMinutes(30);

            Debug.WriteLine(DateTimeOffset.Now);
            Debug.WriteLine(dto1);

            TimeSpan diff = dto1.Subtract(DateTimeOffset.Now);
            Debug.WriteLine(diff);
            Debug.WriteLine(diff.TotalHours);
            Debug.WriteLine(diff.TotalSeconds);
            var diffsec = (DateTimeOffset.Now - dto1).TotalSeconds;
            Debug.WriteLine(diffsec);

            //dtoff.Value.ToLocalTime().ToString("dddd, MMM dd yyyy HH:mm", new CultureInfo("en-US"));

            //Debug.WriteLine(dto1);
            //Debug.WriteLine(dto2);
            //Debug.WriteLine(DateTimeOffset.Now);
            //Debug.WriteLine(dto1 - DateTimeOffset.Now);
            //Debug.WriteLine(DateTimeOffset.Now - dto1);
            //Debug.WriteLine(dto1.CompareTo(DateTimeOffset.Now));
            //Debug.WriteLine(DateTimeOffset.Now.CompareTo(dto1));
            //Debug.WriteLine("  ");

            //Debug.WriteLine(dto1.Hour);

            double temp = -26;
            double res = 0;
            for (int i = 0; i < 40; i++)
            {
                temp++;
                res = 0.5 - (temp * 0.1);
                Debug.WriteLine("Temp: " + temp + "  Result: " + res);
            }

            //Debug.WriteLine(s);
            //Debug.WriteLine(dt.ToString());
            //Debug.WriteLine(dt.ToUniversalTime().ToString());
            //Debug.WriteLine(dto.ToString());
        }
        public 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;
        }
        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));
    }
Example #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);
    }
        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));
        }
        /// <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);
            }
        }
        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());
        }
Example #12
0
 public static void AddMinutes(DateTimeOffset dateTimeOffset, double minutes, DateTimeOffset expected)
 {
     Assert.Equal(expected, dateTimeOffset.AddMinutes(minutes));
 }
 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";
 }
        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();
            }
        }
Example #15
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)));
        }
Example #16
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);
        }
        /// <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);
            }
        }
Example #18
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);
 }
        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));
        }
Example #20
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");
 }
        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.");
        }
Example #22
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)));
 }
		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;
		}
Example #24
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);
        }
Example #25
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");
     }
 }
        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);
        }
Example #27
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;
		}
        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;
        }
        /// <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;
        }