/// <summary>
        /// This is the click handler for the 'Display' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Display_Click(object sender, RoutedEventArgs e)
        {
            // This scenario illustrates TimeZone support in DateTimeFormatter class

            // Displayed TimeZones (other than local timezone)
            String[] timeZones = new String[] { "UTC", "America/New_York", "Asia/Kolkata" };

            // Store results here.
            StringBuilder results = new StringBuilder();

            // Create formatter object using longdate and longtime template
            DateTimeFormatter formatter = new DateTimeFormatter("longdate longtime");

            // Create date/time to format and display.
            DateTime dateTime = DateTime.Now;

            // Show current time in timezones desired to be displayed including local timezone
            results.AppendLine("Current date and time -");
            results.AppendLine("In Local timezone:   " + formatter.Format(dateTime));
            foreach (String timeZone in timeZones)
            {
                results.AppendLine("In " + timeZone + " timezone:   " + formatter.Format(dateTime, timeZone));
            }
            results.AppendLine();

            // Show a time on 14th day of second month of next year in local, and other desired Time Zones
            // This will show if there were day light savings in time
            results.AppendLine("Same time on 14th day of second month of next year -");
            dateTime = new DateTime(dateTime.Year + 1, 2, 14, dateTime.Hour, dateTime.Minute, dateTime.Second);
            results.AppendLine("In Local timezone:   " + formatter.Format(dateTime));
            foreach (String timeZone in timeZones)
            {
                results.AppendLine("In " + timeZone + " timezone:   " + formatter.Format(dateTime, timeZone));
            }
            results.AppendLine();

            // Show a time on 14th day of 10th month of next year in local, and other desired Time Zones
            // This will show if there were day light savings in time
            results.AppendLine("Same time on 14th day of tenth month of next year -");
            dateTime = dateTime.AddMonths(8);
            results.AppendLine("In Local timezone:   " + formatter.Format(dateTime));
            foreach (String timeZone in timeZones)
            {
                results.AppendLine("In " + timeZone + " timezone:   " + formatter.Format(dateTime, timeZone));
            }
            results.AppendLine();

            // Display the results
            OutputTextBlock.Text = results.ToString();
        }
コード例 #2
0
        /// <summary>
        /// This is the click handler for the 'combine' button.  The values of the TimePicker and DatePicker are combined into a single DateTimeOffset.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void combine_Click(object sender, RoutedEventArgs e)
        {
            DateTimeFormatter dateFormatter = new DateTimeFormatter("shortdate");
            DateTimeFormatter timeFormatter = new DateTimeFormatter("shorttime");

            // We use a calendar to determine daylight savings time transition days
            Calendar calendar = new Calendar();
            calendar.ChangeClock("24HourClock");

            // The value of the selected time in a TimePicker is stored as a TimeSpan, so it is possible to add it directly to the value of the selected date
            DateTimeOffset selectedDate = this.datePicker.Date;
            DateTimeOffset combinedValue = new DateTimeOffset(new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day) + this.timePicker.Time);

            calendar.SetDateTime(combinedValue);

            // If the day does not have 24 hours, then the user has selected a day in which a Daylight Savings Time transition occurs.
            //    It is the app developer's responsibility for validating the combination of the date and time values.
            if (calendar.NumberOfHoursInThisPeriod != 24)
            {
                rootPage.NotifyUser("You selected a DST transition day", NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser("Combined value: " + dateFormatter.Format(combinedValue) + " " + timeFormatter.Format(combinedValue), NotifyType.StatusMessage);
            }
        }
コード例 #3
0
ファイル: Scenario1.xaml.cs プロジェクト: mbin/Win81App
        /// <summary>
        /// This is the handler for the DateChanged event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void datePicker_DateChanged(object sender, DatePickerValueChangedEventArgs e)
        {
            // The DateTimeFormatter class formats dates and times with the user's default settings
            DateTimeFormatter dateFormatter = new DateTimeFormatter("shortdate");

            rootPage.NotifyUser("Date changed to " + dateFormatter.Format(e.NewDate), NotifyType.StatusMessage);
        }
コード例 #4
0
        public object Convert( object value, Type targetType, object parameter, string culture ) {
            if( value == null )
                throw new ArgumentNullException( "value", "Value cannot be null." );

            if( !typeof( DateTime ).Equals( value.GetType() ) )
                throw new ArgumentException( "Value must be of type DateTime.", "value" );

            DateTime dt = (DateTime)value;

            if( parameter == null ) {
                // Date "7/27/2011 9:30:59 AM" returns "7/27/2011"
                return DateTimeFormatter.ShortDate.Format( dt );
            }
            else if( (string)parameter == "day" ) {
                // Date "7/27/2011 9:30:59 AM" returns "27"
                DateTimeFormatter dateFormatter = new DateTimeFormatter( "{day.integer(2)}" );
                return dateFormatter.Format( dt );
            }
            else if( (string)parameter == "month" ) {
                // Date "7/27/2011 9:30:59 AM" returns "JUL"
                DateTimeFormatter dateFormatter = new DateTimeFormatter( "{month.abbreviated(3)}" );
                return dateFormatter.Format( dt ).ToUpper();
            }
            else if( (string)parameter == "year" ) {
                // Date "7/27/2011 9:30:59 AM" returns "2011"
                DateTimeFormatter dateFormatter = new DateTimeFormatter( "{year.full}" );
                return dateFormatter.Format( dt );
            }
            else {
                // Requested format is unknown. Return in the original format.
                return dt.ToString();
            }
        }
コード例 #5
0
        public void FormatUsingDefaults()
        {
            DateTimeFormatter fmt = new DateTimeFormatter("d", "en-US");
            Assert.AreEqual("8/14/2004", fmt.Format(new DateTime(2004, 8, 14)));
            Assert.AreEqual("8/24/1974", fmt.Format(new DateTime(1974, 8, 24)));

            fmt = new DateTimeFormatter("dd-MMM-yyyy", "en-US");
            Assert.AreEqual("14-Aug-2004", fmt.Format(new DateTime(2004, 8, 14)));
            Assert.AreEqual("24-Aug-1974", fmt.Format(new DateTime(1974, 8, 24)));

            fmt = new DateTimeFormatter("D", CultureInfoUtils.SerbianLatinCultureName);

            Console.WriteLine("Steve:  " + Environment.Version);


            if (CultureInfoUtils.OperatingSystemIsAfterWindows7AndBeforeWindows10Build10586 && CultureInfoUtils.ClrIsVersion4OrLater)
            {
                Assert.AreEqual("14. avgust 2004.", fmt.Format(new DateTime(2004, 8, 14)));
                Assert.AreEqual("24. avgust 1974.", fmt.Format(new DateTime(1974, 8, 24)));
            }

            else if (CultureInfoUtils.OperatingSystemIsAtLeastWindows10Build10586 && CultureInfoUtils.ClrIsVersion4OrLater)
            {
                Assert.AreEqual("subota, 14. avgust 2004.", fmt.Format(new DateTime(2004, 8, 14)));
                Assert.AreEqual("subota, 24. avgust 1974.", fmt.Format(new DateTime(1974, 8, 24)));
            }

            else
            {
                Assert.AreEqual("14. avgust 2004", fmt.Format(new DateTime(2004, 8, 14)));
                Assert.AreEqual("24. avgust 1974", fmt.Format(new DateTime(1974, 8, 24)));
            }

            fmt = new DateTimeFormatter("dd-MMM-yyyy", CultureInfoUtils.SerbianCyrillicCultureName);

            if (CultureInfoUtils.OperatingSystemIsAfterWindows7 && CultureInfoUtils.ClrIsVersion4OrLater)
            {
                Assert.AreEqual("14-авг.-2004", fmt.Format(new DateTime(2004, 8, 14)));
                Assert.AreEqual("24-авг.-1974", fmt.Format(new DateTime(1974, 8, 24)));
            }
            else
            {
                Assert.AreEqual("14-авг-2004", fmt.Format(new DateTime(2004, 8, 14)));
                Assert.AreEqual("24-авг-1974", fmt.Format(new DateTime(1974, 8, 24)));
            }

        }
コード例 #6
0
        /// <summary>
        /// Formates the Timespan to a culture specific format.
        /// </summary>
        /// <param name="inDuration">The Timespan to Format</param>
        /// <returns>Localised timespan.</returns>
        public static string LocaliseDuration(TimeSpan inDuration)
        {
            var formatter = new DateTimeFormatter("hour minute second");
            var unformattedDuration = DateTime.MinValue.Add(inDuration);
            var localisedDuration = formatter.Format(unformattedDuration);

            return localisedDuration;
        }
コード例 #7
0
        public void FormatUsingDefaults()
        {
            DateTimeFormatter fmt = new DateTimeFormatter("d", "en-US");
            Assert.AreEqual("8/14/2004", fmt.Format(new DateTime(2004, 8, 14)));
            Assert.AreEqual("8/24/1974", fmt.Format(new DateTime(1974, 8, 24)));

            fmt = new DateTimeFormatter("dd-MMM-yyyy", "en-US");
            Assert.AreEqual("14-Aug-2004", fmt.Format(new DateTime(2004, 8, 14)));
            Assert.AreEqual("24-Aug-1974", fmt.Format(new DateTime(1974, 8, 24)));

            fmt = new DateTimeFormatter("D", CultureInfoUtils.SerbianLatinCultureName);
            Assert.AreEqual("14. avgust 2004", fmt.Format(new DateTime(2004, 8, 14)));
            Assert.AreEqual("24. avgust 1974", fmt.Format(new DateTime(1974, 8, 24)));

            fmt = new DateTimeFormatter("dd-MMM-yyyy", CultureInfoUtils.SerbianCyrillicCultureName);
            Assert.AreEqual("14-авг-2004", fmt.Format(new DateTime(2004, 8, 14)));
            Assert.AreEqual("24-авг-1974", fmt.Format(new DateTime(1974, 8, 24)));
        }
コード例 #8
0
        /// <summary>
        /// This is the click handler for the 'changeDate' button; the DatePicker value is changed to 1/31/2013.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void changeDate_Click(object sender, RoutedEventArgs e)
        {
            // The DateTimeFormatter class formats dates and times with the user's default settings
            DateTimeFormatter dateFormatter = new DateTimeFormatter("shortdate");

            // A DateTimeOffset instantiated with a DateTime will have its Offset set to the user default
            //    (i.e. the same Offset used to display the DatePicker value)
            this.datePicker.Date = new DateTimeOffset(new DateTime(2013, 1, 31));

            rootPage.NotifyUser("DatePicker date set to " + dateFormatter.Format(this.datePicker.Date), NotifyType.StatusMessage);
        }
        /// <summary>
        /// Invoked when 'GetCurrentButton' is clicked.
        /// 'ReadingChanged' will not be fired when there is no activity on the pedometer 
        /// and hence can't be reliably used to get the current step count. This handler makes
        /// use of 'GetCurrentReadings' API to determine the current step count
        /// </summary>
        async private void GetCurrentButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            // Determine if we can access pedometers
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId);
            if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
            {
                // Determine if a pedometer is present
                // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
                var sensor = await Pedometer.GetDefaultAsync();
                if (sensor != null)
                {
                    DateTime dt = DateTime.FromFileTimeUtc(0);
                    int totalStepCount = 0;

                    // Get the current readings to find the current step counters
                    var currentReadings = sensor.GetCurrentReadings();
                    bool updateTimestamp = true;
                    foreach (PedometerStepKind kind in Enum.GetValues(typeof(PedometerStepKind)))
                    {
                        PedometerReading reading;
                        if (currentReadings.TryGetValue(kind, out reading))
                        {
                            totalStepCount += reading.CumulativeSteps;
                        }
                        if (updateTimestamp)
                        {
                            DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime");
                            ScenarioOutput_Timestamp.Text = timestampFormatter.Format(reading.Timestamp);
                            updateTimestamp = false;
                        }
                    }

                    ScenarioOutput_TotalStepCount.Text = totalStepCount.ToString();
                    rootPage.NotifyUser("Hit the 'Get steps count' Button", NotifyType.StatusMessage);

                    // Re-enable button
                    GetCurrentButton.IsEnabled = true;
                }
                else
                {
                    rootPage.NotifyUser("No pedometers found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access to pedometers is denied", NotifyType.ErrorMessage);
            }
        }
コード例 #10
0
 public object Convert(object value, Type targetType, object parameter, string culture)
 {
     if (value == null)
         throw new ArgumentNullException("value", "Value cannot be null.");
     String datetime = (String)value;
     DateTime dt = DateTime.ParseExact(datetime, "yyyy-MM-dd HH:mm:ss", null);
     if (parameter == null)
     {
         // Date "7/27/2011 9:30:59 AM" returns "7/27/2011"
         return DateTimeFormatter.ShortDate.Format(dt);
     }
     else if ((string)parameter == "day")
     {
         // Date "7/27/2011 9:30:59 AM" returns "27"
         DateTimeFormatter dateFormatter = new DateTimeFormatter("{day.integer(2)}");
         return dateFormatter.Format(dt);
     }
     else if ((string)parameter == "month")
     {
         // Date "7/27/2011 9:30:59 AM" returns "JUL"
         DateTimeFormatter dateFormatter = new DateTimeFormatter("{month.abbreviated(3)}");
         return dateFormatter.Format(dt).ToUpper();
     }
     else if ((string)parameter == "month_full")
     {
         // Date "7/27/2011 9:30:59 AM" returns "July"
         DateTimeFormatter dateFormatter = new DateTimeFormatter("{month.full}");
         return dateFormatter.Format(dt);
     }
     else if ((string)parameter == "year")
     {
         // Date "7/27/2011 9:30:59 AM" returns "2011"
         DateTimeFormatter dateFormatter = new DateTimeFormatter("{year.full}");
         return dateFormatter.Format(dt);
     }
     else
     {
         // Requested format is unknown. Return in the original format.
         return dt.ToString();
     }
 }
コード例 #11
0
 private static string DateToString(DateTime date, DateTimeFormatter formatter)
 {
     date = date.Date;
     if (date == DateTime.Today)
     {
         return("Today");
     }
     else if (date == DateTime.Today.Tomorrow())
     {
         return("Tomorrow");
     }
     else if (date == DateTime.Today.Yesterday())
     {
         return("Yesterday");
     }
     else if (date > DateTime.Today.Tomorrow() && date < DateTime.Today.AddWeeks(1))
     {
         return(date.ToString("dddd"));
     }
     return(formatter?.Format(date));
 }
コード例 #12
0
ファイル: MonthDay.cs プロジェクト: ranganathsb/JavaSharp
 /// <summary>
 /// Formats this month-day using the specified formatter.
 /// <para>
 /// This month-day will be passed to the formatter to produce a string.
 ///
 /// </para>
 /// </summary>
 /// <param name="formatter">  the formatter to use, not null </param>
 /// <returns> the formatted month-day string, not null </returns>
 /// <exception cref="DateTimeException"> if an error occurs during printing </exception>
 public String Format(DateTimeFormatter formatter)
 {
     Objects.RequireNonNull(formatter, "formatter");
     return(formatter.Format(this));
 }
コード例 #13
0
        /// <summary>
        /// Invoked when 'Get History' button is clicked.
        /// Depending on the user selection, this handler uses one of the overloaded
        /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            IReadOnlyList <PedometerReading> historyReadings = null;
            DateTimeFormatter timestampFormatter             = new DateTimeFormatter("shortdate longtime");

            // Disable subsequent history retrieval while the async operation is in progress
            GetHistory.IsEnabled = false;

            // clear previous content being displayed
            historyRecords.Clear();

            try
            {
                if (getAllHistory)
                {
                    DateTime       dt            = DateTime.FromFileTimeUtc(0);
                    DateTimeOffset fromBeginning = new DateTimeOffset(dt);
                    rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage);
                    historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);
                }
                else
                {
                    String   notificationString = "Retrieving history from: ";
                    Calendar calendar           = new Calendar();
                    calendar.ChangeClock("24HourClock");

                    // DateTime picker will also include hour, minute and seconds from the the system time.
                    // Decrement the same to be able to correctly add TimePicker values.

                    calendar.SetDateTime(FromDate.Date);
                    calendar.AddNanoseconds(-calendar.Nanosecond);
                    calendar.AddSeconds(-calendar.Second);
                    calendar.AddMinutes(-calendar.Minute);
                    calendar.AddHours(-calendar.Hour);
                    calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds));

                    DateTimeOffset fromTime = calendar.GetDateTime();

                    calendar.SetDateTime(ToDate.Date);
                    calendar.AddNanoseconds(-calendar.Nanosecond);
                    calendar.AddSeconds(-calendar.Second);
                    calendar.AddMinutes(-calendar.Minute);
                    calendar.AddHours(-calendar.Hour);
                    calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds));

                    DateTimeOffset toTime = calendar.GetDateTime();

                    notificationString += timestampFormatter.Format(fromTime);
                    notificationString += " To ";
                    notificationString += timestampFormatter.Format(toTime);

                    if (toTime.ToFileTime() < fromTime.ToFileTime())
                    {
                        rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage);

                        // Enable subsequent history retrieval while the async operation is in progress
                        GetHistory.IsEnabled = true;
                    }
                    else
                    {
                        TimeSpan span;
                        span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks);
                        rootPage.NotifyUser(notificationString, NotifyType.StatusMessage);
                        historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span);
                    }
                }

                if (historyReadings != null)
                {
                    foreach (PedometerReading reading in historyReadings)
                    {
                        HistoryRecord record = new HistoryRecord(reading);
                        historyRecords.Add(record);
                    }

                    rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage);
                }
            }
            catch (UnauthorizedAccessException)
            {
                rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
            }

            // Finally, re-enable history retrieval
            GetHistory.IsEnabled = true;
        }
コード例 #14
0
ファイル: DateTimeFormatter.cs プロジェクト: nhannd/Xian
 static public string Format(DateTime dt, string format)
 {
     DateTimeFormatter formatter = new DateTimeFormatter();
     return formatter.Format(format, dt, formatter);
 }
コード例 #15
0
 public static string ToString(this DateTimeOffset dt, DateTimeFormatter formatter)
 {
     return(formatter.Format(dt));
 }
コード例 #16
0
        /// <summary>
        /// Invoked when the underlying Pedometer sees a change in the step count for a step kind
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="args">Pedometer reading that is being notified</param>
        async private void Pedometer_ReadingChanged(Pedometer sender, PedometerReadingChangedEventArgs args)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                PedometerReading reading = args.Reading;
                int newCount = 0;

                // update step counts based on the step kind
                switch (reading.StepKind)
                {
                    case PedometerStepKind.Unknown:
                        if (reading.CumulativeSteps < unknownStepCount)
                        {
                            unknownStepCount = 0;
                        }
                        newCount = reading.CumulativeSteps - unknownStepCount;
                        unknownStepCount = reading.CumulativeSteps;
                        ScenarioOutput_UnknownCount.Text = unknownStepCount.ToString();
                        ScenarioOutput_UnknownDuration.Text = reading.CumulativeStepsDuration.TotalMilliseconds.ToString();
                        break;
                    case PedometerStepKind.Walking:
                        if (reading.CumulativeSteps < walkingStepCount)
                        {
                            walkingStepCount = 0;
                        }
                        newCount = reading.CumulativeSteps - walkingStepCount;
                        walkingStepCount = reading.CumulativeSteps;
                        ScenarioOutput_WalkingCount.Text = walkingStepCount.ToString();
                        ScenarioOutput_WalkingDuration.Text = reading.CumulativeStepsDuration.TotalMilliseconds.ToString();
                        break;
                    case PedometerStepKind.Running:
                        if (reading.CumulativeSteps < runningStepCount)
                        {
                            runningStepCount = 0;
                        }
                        newCount = reading.CumulativeSteps - runningStepCount;
                        runningStepCount = reading.CumulativeSteps;
                        ScenarioOutput_RunningCount.Text = runningStepCount.ToString();
                        ScenarioOutput_RunningDuration.Text = reading.CumulativeStepsDuration.TotalMilliseconds.ToString();
                        break;
                    default:
                        break;
                }

                totalCumulativeSteps += newCount;
                ScenarioOutput_TotalStepCount.Text = totalCumulativeSteps.ToString();

                DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime");
                ScenarioOutput_Timestamp.Text = timestampFormatter.Format(reading.Timestamp);
            });
        }
コード例 #17
0
        private void render()
        {
            _schedulesGrid.Children.Clear();
            _schedulesGrid.RowDefinitions.Clear();

            if (Classes == null || Date == DateTime.MinValue || !ViewModel.Semester.IsDateDuringThisSemester(Date))
            {
                UpdateVisibility();
                return;
            }

            if (!_arrangedItems.IsValid())
            {
                UpdateVisibility();
                return;
            }

            base.Visibility = Visibility.Visible;

            //put in the vertical gap divider
            Rectangle verticalGap = new Rectangle()
            {
                Fill = new SolidColorBrush((Color)Application.Current.Resources["SystemAltHighColor"])
            };

            Grid.SetColumn(verticalGap, 1);
            Grid.SetRowSpan(verticalGap, int.MaxValue);
            _schedulesGrid.Children.Add(verticalGap);

            var hourFormatter = new DateTimeFormatter("{hour.integer}");

            for (TimeSpan time = _arrangedItems.StartTime; time <= _arrangedItems.EndTime; time = time.Add(TimeSpan.FromHours(1)))
            {
                _schedulesGrid.RowDefinitions.Add(new RowDefinition()
                {
                    Height = new GridLength(TIME_INDICATOR_SIZE)
                });

                TextBlock hour = new TextBlock()
                {
                    Text                = hourFormatter.Format(DateTime.Today.Add(time)),
                    FontSize            = 26,
                    VerticalAlignment   = Windows.UI.Xaml.VerticalAlignment.Center,
                    HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center,
                    FontWeight          = FontWeights.Light
                };
                Grid.SetRow(hour, _schedulesGrid.RowDefinitions.Count - 1);
                _schedulesGrid.Children.Add(hour);

                //if not last row, add the divider
                if (time + TimeSpan.FromHours(1) <= _arrangedItems.EndTime)
                {
                    _schedulesGrid.RowDefinitions.Add(new RowDefinition()
                    {
                        Height = new GridLength(GAP_SIZE)
                    });

                    Rectangle gap = new Rectangle()
                    {
                        Fill = new SolidColorBrush((Color)Application.Current.Resources["SystemAltHighColor"])
                    };
                    Grid.SetRow(gap, _schedulesGrid.RowDefinitions.Count - 1);
                    Grid.SetColumnSpan(gap, 3);
                    _schedulesGrid.Children.Add(gap);
                }
            }

            foreach (var s in _arrangedItems.ScheduleItems)
            {
                MyScheduleItem visual = new MyScheduleItem(s.Item);

                AddVisualItem(visual, s);
            }

            // Reverse the order so that when items expand, they appear on top of the items beneath them.
            // Otherwise I would have to do some crazy Z-order logic.
            foreach (var e in _arrangedItems.EventItems.Reverse())
            {
                FrameworkElement visual;
                if (e.IsCollapsedMode)
                {
                    visual = new MyCollapsedEventItem()
                    {
                        Item = e
                    };
                }
                else
                {
                    visual = new MyFullEventItem()
                    {
                        Item = e
                    };
                }

                AddVisualItem(visual, e);
            }
        }
コード例 #18
0
            public MyScheduleItem(ViewItemSchedule s)
            {
                ViewItemClass c = s.Class as ViewItemClass;

                base.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                base.Background        = new SolidColorBrush(ColorTools.GetColor(c.Color));

                var timeSpan     = s.EndTime.TimeOfDay - s.StartTime.TimeOfDay;
                var hours        = timeSpan.TotalHours;
                var showTimeText = timeSpan.TotalMinutes >= 38;

                base.Height = Math.Max(HEIGHT_OF_HOUR * hours, 0);

                base.RowDefinitions.Add(new RowDefinition()
                {
                    Height = GridLength.Auto
                });
                base.RowDefinitions.Add(new RowDefinition()
                {
                    Height = GridLength.Auto
                });
                base.RowDefinitions.Add(new RowDefinition()
                {
                    Height = new GridLength(1, GridUnitType.Star)
                });

                base.ColumnDefinitions.Add(new ColumnDefinition()
                {
                    Width = GridLength.Auto
                });
                base.ColumnDefinitions.Add(new ColumnDefinition()
                {
                    Width = new GridLength(1, GridUnitType.Star)
                });

                TextBlock tbClass = new TextBlock()
                {
                    Text         = c.Name,
                    Style        = Application.Current.Resources["BaseTextBlockStyle"] as Style,
                    Foreground   = Brushes.White,
                    FontWeight   = FontWeights.SemiBold,
                    Margin       = new Windows.UI.Xaml.Thickness(6, 0, 6, 0),
                    TextWrapping = Windows.UI.Xaml.TextWrapping.NoWrap,
                    FontSize     = 14
                };

                Grid.SetColumnSpan(tbClass, 2);
                base.Children.Add(tbClass);

                // Add the time text (xx:xx to xx:xx) - do NOT show the date text for anything below 38 minutes as that will overlap with the title and get pushed beneath it.
                TextBlock tbTime = null;

                if (showTimeText)
                {
                    var timeFormatter = new DateTimeFormatter("shorttime");
                    tbTime = new TextBlock()
                    {
                        Text         = LocalizedResources.Common.GetStringTimeToTime(timeFormatter.Format(s.StartTime), timeFormatter.Format(s.EndTime)),
                        Style        = Application.Current.Resources["BaseTextBlockStyle"] as Style,
                        Foreground   = Brushes.White,
                        FontWeight   = FontWeights.SemiBold,
                        Margin       = new Windows.UI.Xaml.Thickness(6, -2, 6, 0),
                        TextWrapping = Windows.UI.Xaml.TextWrapping.NoWrap,
                        FontSize     = 14
                    };
                }

                TextBlock tbRoom = new TextBlock()
                {
                    Style        = Application.Current.Resources["BaseTextBlockStyle"] as Style,
                    Foreground   = Brushes.White,
                    FontWeight   = FontWeights.SemiBold,
                    Margin       = new Windows.UI.Xaml.Thickness(6, -2, 6, 0),
                    TextWrapping = Windows.UI.Xaml.TextWrapping.WrapWholeWords,
                    FontSize     = 14
                };

                TextBlockExtensions.SetHyperlinkColor(tbRoom, Brushes.White);
                TextBlockExtensions.SetRawText(tbRoom, s.Room);

                if (hours >= 1.1)
                {
                    if (showTimeText)
                    {
                        Grid.SetRow(tbTime, 1);
                        Grid.SetColumnSpan(tbTime, 2);
                        base.Children.Add(tbTime);
                    }

                    if (!string.IsNullOrWhiteSpace(s.Room))
                    {
                        Grid.SetRow(tbRoom, showTimeText ? 2 : 1);
                        Grid.SetColumnSpan(tbRoom, 2);
                        base.Children.Add(tbRoom);
                    }
                }

                else
                {
                    if (showTimeText)
                    {
                        tbTime.Margin            = new Thickness(tbTime.Margin.Left, tbTime.Margin.Top, tbTime.Margin.Right, 8);
                        tbTime.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Bottom;
                        Grid.SetRow(tbTime, 2);
                        base.Children.Add(tbTime);
                    }

                    tbRoom.Margin            = new Thickness(tbRoom.Margin.Left, tbRoom.Margin.Top, tbRoom.Margin.Right, 8);
                    tbRoom.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Bottom;
                    tbRoom.TextAlignment     = TextAlignment.Right;
                    tbRoom.TextWrapping      = TextWrapping.NoWrap;
                    tbRoom.TextTrimming      = TextTrimming.CharacterEllipsis;
                    Grid.SetRow(tbRoom, showTimeText ? 2 : 1);
                    Grid.SetColumn(tbRoom, 1);
                    base.Children.Add(tbRoom);
                }
            }
コード例 #19
0
        public void UpdateDisplayString()
        {
            DateTimeFormatter dateFormat = new DateTimeFormatter("month.abbreviated day hour minute");

            var startDate = (this.Start == DateTimeOffset.MinValue) ? string.Empty : dateFormat.Format(this.Start);
            var endDate = (this.End == DateTimeOffset.MinValue) ? string.Empty : dateFormat.Format(this.End);

            DisplayString = String.Format("Subject: {0} Location: {1} Start: {2} End: {3}",
                    Subject,
                    LocationName,
                    startDate,
                    endDate
                    );
            DisplayString = (this.IsNewOrDirty) ? DisplayString + " *" : DisplayString;
        }
コード例 #20
0
        private async Task <bool> CheckForConflictingDictionary(WordlistReader wordlistReader)
        {
            DictionaryViewModel conflictingDictionary = Dictionaries.FirstOrDefault(dict =>
                                                                                    (dict.OriginLanguageCode == wordlistReader.OriginLanguageCode && dict.DestinationLanguageCode == wordlistReader.DestinationLanguageCode) ||
                                                                                    (dict.OriginLanguageCode == wordlistReader.DestinationLanguageCode && dict.DestinationLanguageCode == wordlistReader.OriginLanguageCode));

            if (conflictingDictionary == null)
            {
                return(true);
            }

            DateTimeFormatter dateTimeFormatter = new DateTimeFormatter("shortdate shorttime");

            string content = resourceLoader.GetString("Import_Conflict_Body1");

            content += "\r\n\r\n";
            content += string.Format(resourceLoader.GetString("Import_Conflict_Body2"),
                                     conflictingDictionary.OriginLanguage, conflictingDictionary.DestinationLanguage, dateTimeFormatter.Format(conflictingDictionary.CreationDate));
            content += "\r\n";
            content += string.Format(resourceLoader.GetString("Import_Conflict_Body3"),
                                     conflictingDictionary.OriginLanguage, conflictingDictionary.DestinationLanguage, dateTimeFormatter.Format(wordlistReader.CreationDate));

            ContentDialog contentDialog = new ContentDialog()
            {
                Title             = resourceLoader.GetString("Import_Conflict_Title"),
                Content           = content,
                PrimaryButtonText = resourceLoader.GetString("Import_Conflict_Replace"),
                CloseButtonText   = resourceLoader.GetString("Import_Conflict_Skip"),
                DefaultButton     = ContentDialogButton.Primary,
                XamlRoot          = MainWindow.Instance.Content.XamlRoot
            };

            bool replace = await contentDialog.ShowAsync() == ContentDialogResult.Primary;

            if (replace)
            {
                bool removedSuccessfully = await RemoveDictionary(conflictingDictionary);

                // as long as another import is still in process, we cannot replace a dictionary
                if (!removedSuccessfully)
                {
                    return(false);
                }
            }

            return(replace);
        }
コード例 #21
0
ファイル: SessionManager.cs プロジェクト: hksonngan/Xian
        /// <summary>
        /// Sets up the principal for the thread and save the authentiction ticket.
        /// </summary>
        /// <param name="session"></param>
        public static void InitializeSession(SessionInfo session)
        {
            // this should throw exception if the session is no longer valid. It also loads the authority tokens}
            if (!session.Valid)
            {
                throw new Exception("This session is no longer valid");
            }
            Current = session;

            string         loginId  = session.User.Identity.Name;
            CustomIdentity identity = session.User.Identity as CustomIdentity;

            if (identity == null)
            {
                Platform.CheckForNullReference(identity, "identity"); // throw exception
            }
            else
            {
                string       displayName = identity.DisplayName;
                SessionToken token       = session.Credentials.SessionToken;
                string[]     authorities = session.Credentials.Authorities;

                String data = String.Format("{0}|{1}|{2}", token.Id, displayName, authorities);

                // the expiry time is determined by the authentication service
                DateTime expiryTime = token.ExpiryTime;

                FormsAuthenticationTicket authTicket = new
                                                       FormsAuthenticationTicket(1,             // version
                                                                                 loginId,       // user name
                                                                                 Platform.Time, // creation
                                                                                 expiryTime,    // Expiration
                                                                                 false,         // Persistent
                                                                                 data);         // User data

                // Now encrypt the ticket.
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                // Create a cookie with the encrypted data
                HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                //Create an unencrypted cookie that contains the userid and the expiry time so the browser
                //can check for session timeout.
                HttpCookie expiryCookie = new HttpCookie(GetExpiryTimeCookieName(session), DateTimeFormatter.Format(expiryTime.ToUniversalTime(), ImageServerConstants.CookieDateTimeFormat));

                HttpContext.Current.Response.Cookies.Add(authCookie);
                HttpContext.Current.Response.Cookies.Add(expiryCookie);

                SessionTimeout = expiryTime.ToUniversalTime() - Platform.Time.ToUniversalTime();
            }
        }
コード例 #22
0
ファイル: FeedData.cs プロジェクト: rebornix/rebornix4windows
        private async Task<FeedData> GetFeedAsync(string feedUriString)
        {
            Windows.Web.Syndication.SyndicationClient client = new SyndicationClient();
            Uri feedUri = new Uri(feedUriString);

            try
            {
                SyndicationFeed feed = await client.RetrieveFeedAsync(feedUri);

                // This code is executed after RetrieveFeedAsync returns the SyndicationFeed.
                // Process the feed and copy the data you want into the FeedData and FeedItem classes.
                FeedData feedData = new FeedData();

                if (feed.Title != null && feed.Title.Text != null)
                {
                    feedData.Title = feed.Title.Text;
                }
                if (feed.Subtitle != null && feed.Subtitle.Text != null)
                {
                    feedData.Description = feed.Subtitle.Text;
                }
                if (feed.Items != null && feed.Items.Count > 0)
                {
                    // Use the date of the latest post as the last updated date.
                    feedData.PubDate = feed.Items[0].LastUpdatedTime.DateTime;

                    var datatimeformatter = new DateTimeFormatter("longdate");

                    foreach (SyndicationItem item in feed.Items)
                    {
                        FeedItem feedItem = new FeedItem();
                        if (item.Title != null && item.Title.Text != null)
                        {
                            feedItem.Title = item.Title.Text;
                        }
                        if (item.PublishedDate != null)
                        {
                            feedItem.PubDate = datatimeformatter.Format(item.LastUpdatedTime.DateTime);
                        }
                        if (item.Authors != null && item.Authors.Count > 0)
                        {
                            feedItem.Author = item.Authors[0].Name.ToString();
                        }
                        // Handle the differences between RSS and Atom feeds.
                        if (feed.SourceFormat == SyndicationFormat.Atom10)
                        {
                            if (item.Content != null && item.Content.Text != null)
                            {
                                feedItem.Content = item.Content.Text;
                                var renderHtml = HtmlUtilities.ConvertToText(item.Content.Text);
                                if(renderHtml != null ){
                                    feedItem.Summary = renderHtml.Substring(0, renderHtml.Length > 300 ? 300 : renderHtml.Length - 1) + "...";
                                }
                                else{
                                    feedItem.Summary = feedItem.Content;
                                }
                            }
                            if (item.Id != null)
                            {
                                feedItem.Link = new Uri(item.Id);
                            }
                        }
                        else if (feed.SourceFormat == SyndicationFormat.Rss20)
                        {
                            if (item.Summary != null && item.Summary.Text != null)
                            {
                                feedItem.Content = item.Summary.Text;
                            }
                            if (item.Links != null && item.Links.Count > 0)
                            {
                                feedItem.Link = item.Links[0].Uri;
                            }
                        }
                        feedData.Items.Add(feedItem);
                    }
                }
                return feedData;
            }
            catch (Exception)
            {
                return null;
            }
        }
コード例 #23
0
        private void ShowResults()
        {
            // This scenario uses the Windows.Globalization.Calendar class to enumerate through a calendar and
            // perform calendar math
            StringBuilder results = new StringBuilder();

            results.AppendLine("The number of years in each era of the Japanese era calendar is not regular. " +
                               "It is determined by the length of the given imperial era:");
            results.AppendLine();

            // Create Japanese calendar.
            Calendar calendar = new Calendar(new[] { "en-US" }, CalendarIdentifiers.Japanese, ClockIdentifiers.TwentyFourHour);

            // Enumerate all supported years in all supported Japanese eras.
            for (calendar.Era = calendar.FirstEra; true; calendar.AddYears(1))
            {
                // Process current era.
                results.AppendLine("Era " + calendar.EraAsString() + " contains " + calendar.NumberOfYearsInThisEra + " year(s)");

                // Enumerate all years in this era.
                for (calendar.Year = calendar.FirstYearInThisEra; true; calendar.AddYears(1))
                {
                    // Begin sample processing of current year.

                    // Move to first day of year. Change of month can affect day so order of assignments is important.
                    calendar.Month = calendar.FirstMonthInThisYear;
                    calendar.Day = calendar.FirstDayInThisMonth;

                    // Set time to midnight (local).
                    calendar.Period = calendar.FirstPeriodInThisDay;    // All days have 1 or 2 periods depending on clock type
                    calendar.Hour = calendar.FirstHourInThisPeriod;     // Hours start from 12 or 0 depending on clock type
                    calendar.Minute = 0;
                    calendar.Second = 0;
                    calendar.Nanosecond = 0;

                    if (calendar.Year % 1000 == 0)
                    {
                        results.AppendLine();
                    }
                    else if (calendar.Year % 10 == 0)
                    {
                        results.Append(".");
                    }

                    // End sample processing of current year.

                    // Break after processing last year.
                    if (calendar.Year == calendar.LastYearInThisEra)
                    {
                        break;
                    }
                }
                results.AppendLine();

                // Break after processing last era.
                if (calendar.Era == calendar.LastEra)
                {
                    break;
                }
            }
            results.AppendLine();

            // This section shows enumeration through the hours in a day to demonstrate that the number of time units in a given period (hours in a day, minutes in an hour, etc.)
            // should not be regarded as fixed. With Daylight Saving Time and other local calendar adjustments, a given day may have not have 24 hours, and
            // a given hour may not have 60 minutes, etc.
            results.AppendLine("The number of hours in a day is not constant. " +
                               "The US calendar transitions from daylight saving time to standard time on 4 November 2012:\n");

            // Create a DateTimeFormatter to display dates
            DateTimeFormatter displayDate = new DateTimeFormatter("longdate");

            // Create a gregorian calendar for the US with 12-hour clock format
            Calendar currentCal = new Windows.Globalization.Calendar(new string[] { "en-US" }, CalendarIdentifiers.Gregorian, ClockIdentifiers.TwentyFourHour, "America/Los_Angeles");

            // Set the calendar to a the date of the Daylight Saving Time-to-Standard Time transition for the US in 2012.
            // DST ends in the America/Los_Angeles time zone at 4 November 2012 02:00 PDT = 4 November 2012 09:00 UTC.
            DateTime dstDate = new DateTime(2012, 11, 4, 9, 0, 0, DateTimeKind.Utc);
            currentCal.SetDateTime(dstDate);

            // Set the current calendar to one day before DST change. Create a second calendar for comparision and set it to one day after DST change.
            Calendar endDate = currentCal.Clone();
            currentCal.AddDays(-1);
            endDate.AddDays(1);

            // Enumerate the day before, the day of, and the day after the 2012 DST-to-Standard time transition
            while (currentCal.Day <= endDate.Day)
            {
                // Process current day.
                DateTimeOffset date = currentCal.GetDateTime();
                results.AppendFormat("{0} contains {1} hour(s)\n", displayDate.Format(date), currentCal.NumberOfHoursInThisPeriod);

                // Enumerate all hours in this day.
                // Create a calendar to represent the following day.
                Calendar nextDay = currentCal.Clone();
                nextDay.AddDays(1);
                for (currentCal.Hour = currentCal.FirstHourInThisPeriod; true; currentCal.AddHours(1))
                {
                    // Display the hour for each hour in the day.             
                    results.AppendFormat("{0} ", currentCal.HourAsPaddedString(2));

                    // Break upon reaching the next period (i.e. the first period in the following day).
                    if (currentCal.Day == nextDay.Day && currentCal.Period == nextDay.Period)
                    {
                        break;
                    }
                }
                results.AppendLine();
            }

            // Display results
            OutputTextBlock.Text = results.ToString();
        }
コード例 #24
0
 public void FormatNonDate()
 {
     DateTimeFormatter fmt = new DateTimeFormatter("d");
     Assert.Throws<ArgumentException>(() => fmt.Format("not a date"));
 }
コード例 #25
0
 public void FormatNonDate()
 {
     DateTimeFormatter fmt = new DateTimeFormatter("d");
     fmt.Format("not a date");
 }
コード例 #26
0
ファイル: Cost.cs プロジェクト: hispafox/Petrolhead
        /// <summary>
        /// Expense.UpdateData() method
        /// Updates all data
        /// </summary>
        /// <returns>
        /// Returns a bool object.
        /// </returns>
        public async Task<bool> UpdateData()
        {
            try
            {
                while (App.Busy)
                {
                    await Task.Delay(100);
                }
                App.Busy = true;
                BudgetTotal = 0;
                Cost = 0;
                foreach (var part in Parts)
                {
                    Cost += part.Cost;
                    if (part.IsBudgetIncluded && this.IsBudgetIncluded)
                        BudgetTotal += part.Cost;
                }
                CurrencyFormatter currency = new CurrencyFormatter(Windows.System.UserProfile.GlobalizationPreferences.Currencies[0]);
                HumanCost = currency.Format(Cost);
                DateTimeFormatter datetime = new DateTimeFormatter("shortdate");
                HumanTransactionDate = datetime.Format(TransactionDate);
                return true;

            }
            catch (Exception ex)
            {
                App.Telemetry.TrackException(ex);
                return false;
            }
            finally
            {
                App.Busy = false;
            }
            
        }
コード例 #27
0
        private void combine_Click(object sender, RoutedEventArgs e)
        {
            DateTimeFormatter dateFormatter = new DateTimeFormatter("shortdate");
            DateTimeFormatter timeFormatter = new DateTimeFormatter("shorttime");

            // We use a calendar to determine daylight savings time transition days
            Calendar calendar = new Calendar();

            calendar.ChangeClock("24HourClock");

            // The value of the selected time in a TimePicker is stored as a TimeSpan, so it is possible to add it directly to the value of the selected date
            DateTimeOffset selectedDate  = this.datePicker.Date;
            DateTimeOffset combinedValue = new DateTimeOffset(new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day) + this.timePicker.Time);

            calendar.SetDateTime(combinedValue);

            // If the day does not have 24 hours, then the user has selected a day in which a Daylight Savings Time transition occurs.
            //    It is the app developer's responsibility for validating the combination of the date and time values.
            if (calendar.NumberOfHoursInThisPeriod != 24)
            {
                StatusBlock.Text = "You selected a DST transition day";
            }
            else
            {
                StatusBlock.Text = "Combined value: " + dateFormatter.Format(combinedValue) + " " + timeFormatter.Format(combinedValue);
            }
        }
コード例 #28
0
 /// <summary>
 /// 格式化日期和时间
 /// </summary>
 public string FormatDateTime(DateTime dateTime)
 {
     return(_dateTimeFormatter.Format(dateTime));
 }
コード例 #29
0
 public void FormatNullValue()
 {
     DateTimeFormatter fmt = new DateTimeFormatter("d");
     Assert.Throws<ArgumentNullException>(() => fmt.Format(null));
 }
コード例 #30
0
            public MyScheduleItem(ViewItemSchedule s)
            {
                ViewItemClass c = s.Class as ViewItemClass;

                base.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
                base.Background        = new SolidColorBrush(ColorTools.GetColor(c.Color));

                double hours = (s.EndTime.TimeOfDay - s.StartTime.TimeOfDay).TotalHours;

                base.Height = Math.Max(HEIGHT_OF_HOUR * hours, 0);


                base.RowDefinitions.Add(new RowDefinition()
                {
                    Height = GridLength.Auto
                });
                base.RowDefinitions.Add(new RowDefinition()
                {
                    Height = GridLength.Auto
                });
                base.RowDefinitions.Add(new RowDefinition()
                {
                    Height = new GridLength(1, GridUnitType.Star)
                });

                base.ColumnDefinitions.Add(new ColumnDefinition()
                {
                    Width = GridLength.Auto
                });
                base.ColumnDefinitions.Add(new ColumnDefinition()
                {
                    Width = new GridLength(1, GridUnitType.Star)
                });


                TextBlock tbClass = new TextBlock()
                {
                    Text         = c.Name,
                    Style        = Application.Current.Resources["BaseTextBlockStyle"] as Style,
                    Foreground   = Brushes.White,
                    FontWeight   = FontWeights.SemiBold,
                    Margin       = new Windows.UI.Xaml.Thickness(6, 0, 6, 0),
                    TextWrapping = Windows.UI.Xaml.TextWrapping.NoWrap,
                    FontSize     = 14
                };

                Grid.SetColumnSpan(tbClass, 2);
                base.Children.Add(tbClass);

                var timeFormatter = new DateTimeFormatter("shorttime");

                TextBlock tbTime = new TextBlock()
                {
                    Text         = LocalizedResources.Common.GetStringTimeToTime(timeFormatter.Format(s.StartTime), timeFormatter.Format(s.EndTime)),
                    Style        = Application.Current.Resources["BaseTextBlockStyle"] as Style,
                    Foreground   = Brushes.White,
                    FontWeight   = FontWeights.SemiBold,
                    Margin       = new Windows.UI.Xaml.Thickness(6, -2, 6, 0),
                    TextWrapping = Windows.UI.Xaml.TextWrapping.NoWrap,
                    FontSize     = 14
                };

                TextBlock tbRoom = new TextBlock()
                {
                    Text         = s.Room,
                    Style        = Application.Current.Resources["BaseTextBlockStyle"] as Style,
                    Foreground   = Brushes.White,
                    FontWeight   = FontWeights.SemiBold,
                    Margin       = new Windows.UI.Xaml.Thickness(6, -2, 6, 0),
                    TextWrapping = Windows.UI.Xaml.TextWrapping.WrapWholeWords,
                    FontSize     = 14
                };

                if (hours >= 1.1)
                {
                    Grid.SetRow(tbTime, 1);
                    Grid.SetColumnSpan(tbTime, 2);
                    base.Children.Add(tbTime);

                    if (!string.IsNullOrWhiteSpace(s.Room))
                    {
                        Grid.SetRow(tbRoom, 2);
                        Grid.SetColumnSpan(tbRoom, 2);
                        base.Children.Add(tbRoom);
                    }
                }

                else
                {
                    tbTime.Margin            = new Thickness(tbTime.Margin.Left, tbTime.Margin.Top, tbTime.Margin.Right, 8);
                    tbTime.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Bottom;
                    Grid.SetRow(tbTime, 2);
                    base.Children.Add(tbTime);

                    tbRoom.Margin            = new Thickness(tbRoom.Margin.Left, tbRoom.Margin.Top, tbRoom.Margin.Right, 8);
                    tbRoom.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Bottom;
                    tbRoom.TextAlignment     = TextAlignment.Right;
                    tbRoom.TextWrapping      = TextWrapping.NoWrap;
                    tbRoom.TextTrimming      = TextTrimming.CharacterEllipsis;
                    Grid.SetRow(tbRoom, 2);
                    Grid.SetColumn(tbRoom, 1);
                    base.Children.Add(tbRoom);
                }
            }
コード例 #31
0
        public void Mapper_NullableDateTime_Null_Format()
        {
            var formatter = new DateTimeFormatter();

            formatter.Format((DateTime?)null).Should().BeNull();
        }
コード例 #32
0
        /// <summary>
        /// Invoked when 'Get History' button is clicked.
        /// Depending on the user selection, this handler uses one of the overloaded
        /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            GetHistory.IsEnabled = false;

            // Determine if we can access pedometers
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId);

            if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
            {
                // Determine if a pedometer is present
                // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
                var sensor = await Pedometer.GetDefaultAsync();

                if (sensor != null)
                {
                    IReadOnlyList <PedometerReading> historyReadings = null;
                    var timestampFormatter = new DateTimeFormatter("shortdate longtime");

                    // Disable subsequent history retrieval while the async operation is in progress
                    GetHistory.IsEnabled = false;

                    // clear previous content being displayed
                    historyRecords.Clear();

                    try
                    {
                        if (getAllHistory)
                        {
                            var dt            = DateTime.FromFileTimeUtc(0);
                            var fromBeginning = new DateTimeOffset(dt);
                            rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage);
                            historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);
                        }
                        else
                        {
                            String notificationString = "Retrieving history from: ";
                            var    calendar           = new Calendar();
                            calendar.ChangeClock("24HourClock");

                            // DateTime picker will also include hour, minute and seconds from the the system time.
                            // Decrement the same to be able to correctly add TimePicker values.

                            calendar.SetDateTime(FromDate.Date);
                            calendar.AddNanoseconds(-calendar.Nanosecond);
                            calendar.AddSeconds(-calendar.Second);
                            calendar.AddMinutes(-calendar.Minute);
                            calendar.AddHours(-calendar.Hour);
                            calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds));

                            DateTimeOffset fromTime = calendar.GetDateTime();

                            calendar.SetDateTime(ToDate.Date);
                            calendar.AddNanoseconds(-calendar.Nanosecond);
                            calendar.AddSeconds(-calendar.Second);
                            calendar.AddMinutes(-calendar.Minute);
                            calendar.AddHours(-calendar.Hour);
                            calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds));

                            DateTimeOffset toTime = calendar.GetDateTime();

                            notificationString += timestampFormatter.Format(fromTime);
                            notificationString += " To ";
                            notificationString += timestampFormatter.Format(toTime);

                            if (toTime.ToFileTime() < fromTime.ToFileTime())
                            {
                                rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage);

                                // Enable subsequent history retrieval while the async operation is in progress
                                GetHistory.IsEnabled = true;
                            }
                            else
                            {
                                TimeSpan span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks);
                                rootPage.NotifyUser(notificationString, NotifyType.StatusMessage);
                                historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span);
                            }
                        }

                        if (historyReadings != null)
                        {
                            foreach (PedometerReading reading in historyReadings)
                            {
                                HistoryRecord record = new HistoryRecord(reading);
                                historyRecords.Add(record);

                                // Get at most 100 records (number is arbitrary chosen for demonstration purposes)
                                if (historyRecords.Count == 100)
                                {
                                    break;
                                }
                            }

                            rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
                    }

                    // Finally, re-enable history retrieval
                    GetHistory.IsEnabled = true;
                }
                else
                {
                    rootPage.NotifyUser("No pedometers found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access to pedometers is denied", NotifyType.ErrorMessage);
            }
        }
        /// <summary>
        /// Invoked when 'GetCurrentButton' is clicked.
        /// 'ReadingChanged' will not be fired when there is no activity on the pedometer
        /// and hence can't be reliably used to get the current step count. This handler makes
        /// use of pedometer history on the system to get the current step count of the parameter
        /// </summary>
        async private void GetCurrentButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            // Determine if we can access pedometers
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId);

            if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
            {
                // Determine if a pedometer is present
                // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
                var sensor = await Pedometer.GetDefaultAsync();

                if (sensor != null)
                {
                    DateTime dt             = DateTime.FromFileTimeUtc(0);
                    int      totalStepCount = 0;
                    int      lastTotalCount = 0;

                    rootPage.NotifyUser("Retrieving history to get current step counts", NotifyType.StatusMessage);

                    // Disable the button while we get the history
                    GetCurrentButton.IsEnabled = false;

                    DateTimeOffset fromBeginning = new DateTimeOffset(dt);

                    try
                    {
                        var historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);

                        // History always returns chronological list of step counts for all PedometerStepKinds
                        // And each record represents cumulative step counts for that step kind.
                        // So we will use the last set of records - that gives us the cumulative step count for
                        // each kind and ignore rest of the records
                        PedometerStepKind stepKind = PedometerStepKind.Unknown;
                        DateTimeOffset    lastReadingTimestamp;
                        bool resetTotal = false;
                        foreach (PedometerReading reading in historyReadings)
                        {
                            if (stepKind == PedometerStepKind.Running)
                            {
                                // reset the total after reading the 'PedometerStepKind.Running' count
                                resetTotal = true;
                            }

                            totalStepCount += reading.CumulativeSteps;
                            if (resetTotal)
                            {
                                lastReadingTimestamp = reading.Timestamp;
                                lastTotalCount       = totalStepCount;
                                stepKind             = PedometerStepKind.Unknown;
                                totalStepCount       = 0;
                                resetTotal           = false;
                            }
                            else
                            {
                                stepKind++;
                            }
                        }

                        ScenarioOutput_TotalStepCount.Text = lastTotalCount.ToString();

                        DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime");
                        ScenarioOutput_Timestamp.Text = timestampFormatter.Format(lastReadingTimestamp);

                        rootPage.NotifyUser("Hit the 'Get steps count' Button", NotifyType.StatusMessage);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
                    }

                    // Re-enable button
                    GetCurrentButton.IsEnabled = true;
                }
                else
                {
                    rootPage.NotifyUser("No pedometers found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access to pedometers is denied", NotifyType.ErrorMessage);
            }
        }
コード例 #34
0
        public void Mapper_DateTime_Format()
        {
            var formatter = new DateTimeFormatter();

            formatter.Format(new DateTime(2000, 1, 1, 1, 1, 1, 1)).Should().Be("2000-01-01T01:01:01.0010000");
        }
コード例 #35
0
        /// <summary>
        /// Invoked when 'Get History' button is clicked.
        /// Depending on the user selection, this handler uses one of the overloaded
        /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            GetHistory.IsEnabled = false;

            // Determine if we can access pedometers
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId);
            if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
            {
                // Determine if a pedometer is present
                // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
                var sensor = await Pedometer.GetDefaultAsync();
                if (sensor != null)
                {
                    IReadOnlyList<PedometerReading> historyReadings = null;
                    var timestampFormatter = new DateTimeFormatter("shortdate longtime");

                    // Disable subsequent history retrieval while the async operation is in progress
                    GetHistory.IsEnabled = false;

                    // clear previous content being displayed
                    historyRecords.Clear();

                    try
                    {
                        if (getAllHistory)
                        {
                            var dt = DateTime.FromFileTimeUtc(0);
                            var fromBeginning = new DateTimeOffset(dt);
                            rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage);
                            historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);
                        }
                        else
                        {
                            String notificationString = "Retrieving history from: ";
                            var calendar = new Calendar();
                            calendar.ChangeClock("24HourClock");

                            // DateTime picker will also include hour, minute and seconds from the the system time.
                            // Decrement the same to be able to correctly add TimePicker values.

                            calendar.SetDateTime(FromDate.Date);
                            calendar.AddNanoseconds(-calendar.Nanosecond);
                            calendar.AddSeconds(-calendar.Second);
                            calendar.AddMinutes(-calendar.Minute);
                            calendar.AddHours(-calendar.Hour);
                            calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds));

                            DateTimeOffset fromTime = calendar.GetDateTime();

                            calendar.SetDateTime(ToDate.Date);
                            calendar.AddNanoseconds(-calendar.Nanosecond);
                            calendar.AddSeconds(-calendar.Second);
                            calendar.AddMinutes(-calendar.Minute);
                            calendar.AddHours(-calendar.Hour);
                            calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds));

                            DateTimeOffset toTime = calendar.GetDateTime();

                            notificationString += timestampFormatter.Format(fromTime);
                            notificationString += " To ";
                            notificationString += timestampFormatter.Format(toTime);

                            if (toTime.ToFileTime() < fromTime.ToFileTime())
                            {
                                rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage);

                                // Enable subsequent history retrieval while the async operation is in progress
                                GetHistory.IsEnabled = true;
                            }
                            else
                            {
                                TimeSpan span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks);
                                rootPage.NotifyUser(notificationString, NotifyType.StatusMessage);
                                historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span);
                            }
                        }

                        if (historyReadings != null)
                        {
                            foreach (PedometerReading reading in historyReadings)
                            {
                                HistoryRecord record = new HistoryRecord(reading);
                                historyRecords.Add(record);

                                // Get at most 100 records (number is arbitrary chosen for demonstration purposes)
                                if (historyRecords.Count == 100)
                                {
                                    break;
                                }
                            }

                            rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
                    }

                    // Finally, re-enable history retrieval
                    GetHistory.IsEnabled = true;
                }
                else
                {
                    rootPage.NotifyUser("No pedometers found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access to pedometers is denied", NotifyType.ErrorMessage);
            }
        }
コード例 #36
0
 public void FormatNullValue()
 {
     DateTimeFormatter fmt = new DateTimeFormatter("d");
     fmt.Format(null);
 }
コード例 #37
0
        /// <summary>
        /// Invoked when 'Get History' button is clicked.
        /// Depending on the user selection, this handler uses one of the overloaded
        /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            IReadOnlyList<PedometerReading> historyReadings = null;
            DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime");

            // Disable subsequent history retrieval while the async operation is in progress
            GetHistory.IsEnabled = false;

            // clear previous content being displayed
            historyRecords.Clear();

            try
            {
                if (getAllHistory)
                {
                    DateTime dt = DateTime.FromFileTimeUtc(0);
                    DateTimeOffset fromBeginning = new DateTimeOffset(dt);
                    rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage);
                    historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);
                }
                else
                {
                    String notificationString = "Retrieving history from: ";
                    Calendar calendar = new Calendar();
                    calendar.ChangeClock("24HourClock");

                    // DateTime picker will also include hour, minute and seconds from the the system time.
                    // Decrement the same to be able to correctly add TimePicker values.

                    calendar.SetDateTime(FromDate.Date);
                    calendar.AddNanoseconds(-calendar.Nanosecond);
                    calendar.AddSeconds(-calendar.Second);
                    calendar.AddMinutes(-calendar.Minute);
                    calendar.AddHours(-calendar.Hour);
                    calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds));

                    DateTimeOffset fromTime = calendar.GetDateTime();

                    calendar.SetDateTime(ToDate.Date);
                    calendar.AddNanoseconds(-calendar.Nanosecond);
                    calendar.AddSeconds(-calendar.Second);
                    calendar.AddMinutes(-calendar.Minute);
                    calendar.AddHours(-calendar.Hour);
                    calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds));

                    DateTimeOffset toTime = calendar.GetDateTime();

                    notificationString += timestampFormatter.Format(fromTime);
                    notificationString += " To ";
                    notificationString += timestampFormatter.Format(toTime);

                    if (toTime.ToFileTime() < fromTime.ToFileTime())
                    {
                        rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage);

                        // Enable subsequent history retrieval while the async operation is in progress
                        GetHistory.IsEnabled = true;
                    }
                    else
                    {
                        TimeSpan span;
                        span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks);
                        rootPage.NotifyUser(notificationString, NotifyType.StatusMessage);
                        historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span);
                    }
                }

                if (historyReadings != null)
                {
                    foreach(PedometerReading reading in historyReadings)
                    {
                        HistoryRecord record = new HistoryRecord(reading);
                        historyRecords.Add(record);
                    }

                    rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage);
                }
            }
            catch (UnauthorizedAccessException)
            {
                rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
            }

            // Finally, re-enable history retrieval
            GetHistory.IsEnabled = true;
        }
        /// <summary>
        /// Invoked when 'GetCurrentButton' is clicked.
        /// 'ReadingChanged' will not be fired when there is no activity on the pedometer 
        /// and hence can't be reliably used to get the current step count. This handler makes
        /// use of pedometer history on the system to get the current step count of the parameter
        /// </summary>
        async private void GetCurrentButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            DateTime dt = DateTime.FromFileTimeUtc(0);
            int totalStepCount = 0;
            int lastTotalCount = 0;

            rootPage.NotifyUser("Retrieving history to get current step counts", NotifyType.StatusMessage);

            // Disable the button while we get the history
            GetCurrentButton.IsEnabled = false;

            DateTimeOffset fromBeginning = new DateTimeOffset(dt);

            try
            {
                IReadOnlyList<PedometerReading> historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);

                // History always returns chronological list of step counts for all PedometerStepKinds
                // And each record represents cumulative step counts for that step kind.
                // So we will use the last set of records - that gives us the cumulative step count for 
                // each kind and ignore rest of the records
                PedometerStepKind stepKind = PedometerStepKind.Unknown;
                DateTimeOffset lastReadingTimestamp;
                bool resetTotal = false;
                foreach (PedometerReading reading in historyReadings)
                {
                    if(stepKind == PedometerStepKind.Running)
                    {
                        // reset the total after reading the 'PedometerStepKind.Running' count
                        resetTotal = true;
                    }

                    totalStepCount += reading.CumulativeSteps;
                    if (resetTotal)
                    {
                        lastReadingTimestamp = reading.Timestamp;
                        lastTotalCount = totalStepCount;
                        stepKind = PedometerStepKind.Unknown;
                        totalStepCount = 0;
                        resetTotal = false;
                    }
                    else
                    {
                        stepKind++;
                    }
                }

                ScenarioOutput_TotalStepCount.Text = lastTotalCount.ToString();

                DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime");
                ScenarioOutput_Timestamp.Text = timestampFormatter.Format(lastReadingTimestamp);

                rootPage.NotifyUser("Hit the 'Get steps count' Button", NotifyType.StatusMessage);
            }
            catch (UnauthorizedAccessException)
            {
                rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
            }

            // Re-enable button
            GetCurrentButton.IsEnabled = true;
        }
コード例 #39
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            Profile responseProfile;
            SolidColorBrush scb = new SolidColorBrush();

            // Get the userId of the user we're currently looking at
            userID = Convert.ToInt32(e.Parameter);


            try
            {
                var profileRequest = new ApiRequest("user/profile");
                profileRequest.Authenticated = true;
                profileRequest.Parameters.Add("userId", userID.ToString());
                profileRequest.Parameters.Add("currentUserId", App.LoggedInUser.UserId.ToString()); 
                responseProfile = await profileRequest.ExecuteAsync<Profile>();

                this.DataContext = responseProfile;
                isFollowing = responseProfile.User.Following;
                if (isFollowing)
                {
                    followButton.Content = "Unfollow";
                    scb.Color = Color.FromArgb(255, 139, 139, 137);
                    followButton.Background = scb; 
                }
                else
                {
                    followButton.Content = "Follow";
                    scb.Color = Color.FromArgb(255, 85, 107, 47);
                    followButton.Background = scb; 
                }

                DateTimeFormatter dtFormatter = new DateTimeFormatter("shortdate");
                var signedUpDateShort = dtFormatter.Format(responseProfile.User.Created);

                //profilePicture.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(responseProfile.User.Avatar, UriKind.Absolute));
                usernameTxtBlock.Text = responseProfile.User.Username;
                emailTxtBlock.Text = responseProfile.User.Email;
                dateJoinedTxtBlock.Text = "Date joined: " + signedUpDateShort;
                numberOfVideosTxtBox.Text = responseProfile.User.TotalVideos.ToString();
                numberOfFollowersTxtBox.Text = responseProfile.Followers.Count.ToString();
                numberOfFollowingTxtBox.Text = responseProfile.Following.Count.ToString();

                videosGridView.ItemsSource = responseProfile.Videos;
                followersGridView.ItemsSource = responseProfile.Followers;
                followingGridView.ItemsSource = responseProfile.Following;

                progressRing.Visibility = Visibility.Collapsed; 
                videosTxtBlock.Visibility = Visibility.Visible;
                followersTxtBlock.Visibility = Visibility.Visible;
                followingTxtBlock.Visibility = Visibility.Visible;
                videosSideTxtBlock.Visibility = Visibility.Visible;
                followersSideTxtBlock.Visibility = Visibility.Visible;
                followingSideTxtBlock.Visibility = Visibility.Visible;
                followButton.Visibility = Visibility.Visible; 


            }
            catch(Exception ex)
            {
            }
            base.OnNavigatedTo(e);
        }