Example #1
0
        protected override void OnLog(LogEventArgs itm)
        {
            var createdAt = DateTimeFormatter.WriteToString(itm.CreatedAtUtc);
            var level     = LogLevelFormatter.WriteToString(itm.Level);

            Console.WriteLine($"{createdAt} {level}: {itm.Message}");
        }
Example #2
0
        public void DigitChecking(DateTime dt)
        {
            Span <char> outputChars = stackalloc char[50];

            Assert.True(DateTimeFormatter.TryFormat(dt, outputChars, out var written));
            Assert.True(DateTimeParser.TryParseDateTime(outputChars, out var outputDt, out var consumed));
            Assert.Equal(dt, outputDt);
            Assert.Equal(written, consumed);

            Span <byte> outputBytes = stackalloc byte[50];

            Assert.True(DateTimeFormatter.TryFormat(dt, outputBytes, out written));
            Assert.True(DateTimeParser.TryParseDateTime(outputBytes, out outputDt, out consumed));
            Assert.Equal(dt, outputDt);
            Assert.Equal(written, consumed);

            var dto = new DateTimeOffset(dt);

            Assert.True(DateTimeFormatter.TryFormat(dto, outputChars, out written));
            Assert.True(DateTimeParser.TryParseDateTime(outputChars, out var outputdto, out consumed));
            Assert.Equal(dto, outputdto);
            Assert.Equal(written, consumed);

            Assert.True(DateTimeFormatter.TryFormat(dto, outputBytes, out written));
            Assert.True(DateTimeParser.TryParseDateTime(outputBytes, out outputdto, out consumed));
            Assert.Equal(dto, outputdto);
            Assert.Equal(written, consumed);
        }
Example #3
0
        public string DateExtended(int value)
        {
            var dateTime = Utils.UnixTimestampToDateTime(value);

            //Today
            if (dateTime.Date == System.DateTime.Now.Date)
            {
                //TimeLabel.Text = dateTime.ToString(string.Format("{0}", shortTimePattern), cultureInfo);
                return(ShortTime.Format(dateTime));
            }

            //Week
            if (dateTime.Date.AddDays(6) >= System.DateTime.Now.Date)
            {
                if (_formatterCache.TryGetValue("dayofweek.abbreviated", out DateTimeFormatter formatter) == false)
                {
                    //var region = new GeographicRegion();
                    //var code = region.CodeTwoLetter;

                    formatter = new DateTimeFormatter("dayofweek.abbreviated", GlobalizationPreferences.Languages, GlobalizationPreferences.HomeGeographicRegion, GlobalizationPreferences.Calendars.FirstOrDefault(), GlobalizationPreferences.Clocks.FirstOrDefault());
                    _formatterCache["dayofweek.abbreviated"] = formatter;
                }

                return(formatter.Format(dateTime));
            }

            //Long long time ago
            //TimeLabel.Text = dateTime.ToString(string.Format("d.MM.yyyy", shortTimePattern), cultureInfo);
            return(ShortDate.Format(dateTime));
        }
Example #4
0
        public JournalView(IToolTipCreator toolTipCreator, IImageListRetriever imageListRetriever)
        {
            _toolTipCreator     = toolTipCreator;
            _imageListRetriever = imageListRetriever;
            InitializeComponent();
            _gridViewBinder = new GridViewBinder <JournalPageDTO>(gridView);
            gridView.ShouldUseColorForDisabledCell = false;
            gridView.ShowColumnChooser             = true;
            _rowFontSize    = AppearanceObject.DefaultFont.Size;
            PopupBarManager = new BarManager {
                Form = this, Images = imageListRetriever.AllImagesForContextMenu
            };
            _toolTipCreator = toolTipCreator;
            var toolTipController = new ToolTipController();

            toolTipController.GetActiveObjectInfo += onToolTipControllerGetActiveObjectInfo;
            toolTipController.Initialize(imageListRetriever);
            gridControl.ToolTipController = toolTipController;

            gridView.MouseDown              += (o, e) => OnEvent(onGridViewMouseDown, e);
            gridView.DoubleClick            += (o, e) => OnEvent(onGridViewDoubleClicked, e);
            gridView.RowCellStyle           += (o, e) => OnEvent(onRowCellStyle, e);
            gridView.CustomDrawRowPreview   += (o, e) => OnEvent(onCustomDrawRowPreview, e);
            gridView.ShowFilterPopupListBox += (o, e) => OnEvent(onShowFilterPopupListBox, e);
            gridView.MeasurePreviewHeight   += (o, e) => OnEvent(onMeasurePreviewHeight, e);

            _titleRepository = new RepositoryItemTextEdit();

            _dateTimeFormatter     = new DateTimeFormatter();
            _descriptionRepository = new RepositoryItemRichTextEdit {
                DocumentFormat = DocumentFormat.Html
            };
        }
Example #5
0
        private static bool IsUsing24HoursTime()
        {
            // a hack to get "real" culture when app runs on a machine where it's not localized (example: Finland)
            var cultureName = new DateTimeFormatter("longdate", new[] { "US" }).ResolvedLanguage;

            return(new CultureInfo(cultureName).DateTimeFormat.ShortTimePattern.Contains("H"));
        }
Example #6
0
        protected override string GetRenderedDateTimeText()
        {
            if (String.IsNullOrEmpty(Value))
            {
                return(EmptyValueText);
            }

            DateTime?dt = DateParser.Parse(Value);

            if (dt != null)
            {
                if (String.IsNullOrEmpty(Format))
                {
                    return(DateTimeFormatter.Format(dt.Value, DateTimeFormatter.Style.Date));
                }
                else
                {
                    return(dt.Value.ToString(Format));
                }
            }
            else
            {
                return(null);
            }
        }
 public object Convert(object value, Type targetType, object parameter, string language)
 {
     try
     {
         if (value is DateTime dateTime)
         {
             if (dateTime == DateTime.MinValue)
             {
                 return("");
             }
             value = new DateTimeOffset(dateTime);
         }
         if (value is DateTimeOffset dateTimeOffset)
         {
             string format        = parameter as String ?? "shortdate";
             var    userLanguages = GlobalizationPreferences.Languages;
             var    dateFormatter = new DateTimeFormatter(format, userLanguages);
             return(dateFormatter.Format(dateTimeOffset.ToLocalTime()));
         }
         return("N/A");
     }
     catch
     {
         return("");
     }
 }
Example #8
0
        internal async Task <object> GetAppointmentForWorksOrder(string workOrderReference)
        {
            _logger.LogInformation($"Getting booked appointment for work order reference {workOrderReference}");
            //Get DRS sessionId
            var sessionId = await OpenDrsServiceSession();

            // get the work order details and pass it to the request builder
            var workOrder = await _repairsService.GetWorkOrderDetails(workOrderReference);

            if (string.IsNullOrEmpty(workOrder.wo_ref))
            {
                _logger.LogError($"could not find the work order in UH with reference {workOrderReference}");
                throw new InvalidWorkOrderInUHException();
            }
            // Get booking id & order id for the primary order reference
            var orderResponse = await GetOrderFromDrs(workOrderReference, sessionId);

            // close session
            await CloseDrsServiceSession(sessionId);

            var returnResponse = orderResponse.@return;

            if ([email protected] != responseStatus.success)
            {
                _logger.LogError(returnResponse.errorMsg);
                throw new AppointmentServiceException();
            }
            return(new
            {
                beginDate = DateTimeFormatter.FormatDateTimeToUtc([email protected][0].theBookings[0].assignedStart),
                endDate = DateTimeFormatter.FormatDateTimeToUtc([email protected][0].theBookings[0].assignedEnd)
            });
        }
Example #9
0
        public void Mapper_NullableDateTime_Format()
        {
            var      formatter = new DateTimeFormatter();
            DateTime?date      = new DateTime(2000, 1, 1, 1, 1, 1, 1);

            formatter.Format(date).Should().Be("2000-01-01T01:01:01.0010000");
        }
        /// <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);
            }
        }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value == null)
            {
                value = DateTime.Now;                // TEST;
            }
            if (value is DateTimeOffset)
            {
                value = ((DateTimeOffset)value).DateTime;
            }

            var format = (string)parameter;

            if (format.StartsWith("unigram"))
            {
                switch (format)
                {
                case "unigram.monthgrouping":
                    return(ConvertMonthGrouping((DateTime)value));
                }
            }
            else
            {
                var formatted = new DateTimeFormatter(format, GlobalizationPreferences.Languages).Format((DateTime)value).Trim('\u200E', '\u200F');
                if (format.Contains("full"))
                {
                    return(formatted.Substring(0, 1).ToUpper() + formatted.Substring(1));
                }

                return(formatted);
            }

            return(value);
        }
Example #12
0
        /// <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);
        }
        public Scenario4()
        {
            this.InitializeComponent();

            try
            {
                formatterShortDateLongTime = new DateTimeFormatter("{month.integer}/{day.integer}/{year.full} {hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                formatterLongTime = new DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                calendar = new Calendar();
                decimalFormatter = new DecimalFormatter();
                geofenceCollection = new  ObservableCollection<GeofenceItem>();
                eventCollection = new ObservableCollection<string>();

                // Geofencing setup
                InitializeGeolocation();

                // using data binding to the root page collection of GeofenceItems
                RegisteredGeofenceListBox.DataContext = geofenceCollection;

                // using data binding to the root page collection of GeofenceItems associated with events
                GeofenceEventsListBox.DataContext = eventCollection;

                coreWindow = CoreWindow.GetForCurrentThread(); // this needs to be set before InitializeComponent sets up event registration for app visibility
                coreWindow.VisibilityChanged += OnVisibilityChanged;
            }
            catch (Exception ex)
            {
                // GeofenceMonitor failed in adding a geofence
                // exceptions could be from out of memory, lat/long out of range,
                // too long a name, not a unique name, specifying an activation
                // time + duration that is still in the past
                _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
        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();
            }
        }
        public Scenario4()
        {
            this.InitializeComponent();

            try
            {
                formatterShortDateLongTime = new DateTimeFormatter("{month.integer}/{day.integer}/{year.full} {hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                formatterLongTime          = new DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                calendar           = new Calendar();
                decimalFormatter   = new DecimalFormatter();
                geofenceCollection = new  ObservableCollection <GeofenceItem>();
                eventCollection    = new ObservableCollection <string>();

                // Geofencing setup
                InitializeGeolocation();

                // using data binding to the root page collection of GeofenceItems
                RegisteredGeofenceListBox.DataContext = geofenceCollection;

                // using data binding to the root page collection of GeofenceItems associated with events
                GeofenceEventsListBox.DataContext = eventCollection;

                coreWindow = CoreWindow.GetForCurrentThread(); // this needs to be set before InitializeComponent sets up event registration for app visibility
                coreWindow.VisibilityChanged += OnVisibilityChanged;
            }
            catch (Exception ex)
            {
                // GeofenceMonitor failed in adding a geofence
                // exceptions could be from out of memory, lat/long out of range,
                // too long a name, not a unique name, specifying an activation
                // time + duration that is still in the past
                _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
Example #16
0
        public void ShouldFormat()
        {
            DateTime dt = DateTime.ParseExact("20200101", "yyyyMMdd", CultureInfo.InvariantCulture);
            string   expectedDateStr = "2020-01-01";
            string   actualDateStr   = DateTimeFormatter.FormatDate(dt);

            Assert.True(actualDateStr == expectedDateStr);
        }
        /// <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;
        }
        private void LogReadOldImageFromCache(int userId)
        {
            string statusMessage = "From cache  . OLD IMAGE until cache is updated"
                                   + " ,  LastUpdate: " + DateTimeFormatter.ConvertTimeToCompactString(GetLastCacheAccess(userId), true) //(_lastCacheAccess, true) //
                                   + "    Request by UserId: " + userId.GetFormattedUserId();

            _logger?.LogCacheStat(statusMessage, userId);
        }
        private void LogBeforeReadingFromProvider(DateTime requestTime, int userId)
        {
            string msg = "[1]--Start reading image from source.".PadRight(84) +
                         " Request by UserId: " + userId.GetFormattedUserId() + " , at " +
                         DateTimeFormatter.ConvertTimeToCompactString(requestTime, true);

            _logger?.LogCacheStat(msg, userId);
        }
Example #20
0
        public bool GetImage(string outFileName, TimeSpan time, int width = -1, int height = 150)
        {
            string outFile = Path.Combine(_outFolder, outFileName);
            string args    = string.Format("-i \"{0}\" -ss {1} -vcodec mjpeg -vframes 1 -an -vf scale={2}:{3} \"{4}\"",
                                           _sourceFile, DateTimeFormatter.ToHHMMSSFFF(time, '.'), width, height, outFile);

            return(RunCommand(args));
        }
        public AttendanceManager(ISubscriptionManager sm)
        {
            subscriptionManager = sm;
            DataBaseManager     = subscriptionManager.DataBaseManager;
            messager            = subscriptionManager.messager;

            dtFormatter = new DateTimeFormatter();
        }
        public void TestDate()
        {
            var dateTime = DateTimeFormatter.FormatedToDateTime("2020-02-07 15:00:00");

            dateTime.Year.ShouldBe(2020);
            dateTime.Month.ShouldBe(02);
            dateTime.Day.ShouldBe(07);
        }
Example #23
0
 public static String ToShortDate(DateTime d)
 {
     if (userRegion == null)
     {
         userRegion = new GeographicRegion();
         userDateFormat = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate", new[] { userRegion.Code });
     }
     return userDateFormat.Format(d);
 }
        public void GetTimeMaxLength_WithShowSecondsTrue_ReturnsLengthForDoubleSpacedDigits_IncludingTheSeconds()
        {
            var formatter = new DateTimeFormatter();

            using (new CultureScope("en-US"))
            {
                Assert.That(formatter.GetTimeMaxLength(true), Is.EqualTo(11));
            }
        }
        public void GetDateMaxLength_ReturnsLengthForDoubleSpacedDigits()
        {
            var formatter = new DateTimeFormatter();

            using (new CultureScope("en-US"))
            {
                Assert.That(formatter.GetDateMaxLength(), Is.EqualTo(10));
            }
        }
        public void Is12HourTimeFormat_WithDeCulture_ReturnsFalse()
        {
            var formatter = new DateTimeFormatter();

            using (new CultureScope("de-AT"))
            {
                Assert.That(formatter.Is12HourTimeFormat(), Is.False);
            }
        }
        public void Is12HourTimeFormat_WithUsCulture_ReturnsTrue()
        {
            var formatter = new DateTimeFormatter();

            using (new CultureScope("en-US"))
            {
                Assert.That(formatter.Is12HourTimeFormat(), Is.True);
            }
        }
        public void FormatTimeValue_WithShowSecondsFalse_ReturnsTimeWithoutSeconds()
        {
            var formatter = new DateTimeFormatter();

            using (new CultureScope("en-US"))
            {
                Assert.That(formatter.FormatTimeValue(new DateTime(2013, 06, 20, 5, 30, 40), false), Is.EqualTo("5:30 AM"));
            }
        }
Example #29
0
        public static string ToDayOfWeekString(this DateTime dateTime)
        {
            if (_dayOfWeekFormatter == null)
            {
                _dayOfWeekFormatter = new DateTimeFormatter("dayofweek.full");
            }

            return(_dayOfWeekFormatter.Format(dateTime));
        }
Example #30
0
 static public String ToShortDate(DateTime d)
 {
     if (userRegion == null)
     {
         userRegion     = new GeographicRegion();
         userDateFormat = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("shortdate", new[] { userRegion.Code });
     }
     return(userDateFormat.Format(d));
 }
Example #31
0
        private string ParseDate(string date)
        {
            if (date == null)
            {
                return(null);
            }

            return(DateTime.TryParse(date, out var result) ? DateTimeFormatter.ToShortDate(result) : date);
        }
Example #32
0
        private string CreateMessageWhenCanReturnImage()
        {
            string statusMessage = ("From cache (2)." + // Granted access to cache
                                    "Current = userId: " + _cacheUpdateService.UserId.GetFormattedUserId()).PadRight(50)
                                   + "LastUpdate: " +
                                   DateTimeFormatter.ConvertTimeToCompactString(_cacheUpdateService.LastUpdate, true);

            return(statusMessage.PadRight(85));
        }
        private static (string strPrevTime, string strRequestTime) GetLogDateTimeValuesAsStrings(
            DateTime lastUpdate,
            DateTime requestTime)
        {
            string strPrevTime    = DateTimeFormatter.ConvertTimeToCompactString(lastUpdate, true);
            string strRequestTime = DateTimeFormatter.ConvertTimeToCompactString(requestTime, true);

            return(strPrevTime, strRequestTime);
        }
        private void LogAfterReadingFromProvider(int userId)
        {
            string msg = "[2]--Finish reading image from source. " +
                         "                                              " +
                         "Request by UserId: " + userId.GetFormattedUserId() + " , at " +
                         DateTimeFormatter.ConvertTimeToCompactString(GetLastCacheAccess(userId), true);

            _logger?.LogCacheStat(msg, userId);
        }
Example #35
0
        public DateCalculator()
        {
            InitializeComponent();

            // Set Calendar Identifier
            DateDiff_FromDate.CalendarIdentifier = localizationSettings.GetCalendarIdentifier();
            DateDiff_ToDate.CalendarIdentifier   = localizationSettings.GetCalendarIdentifier();

            // Setting the FirstDayofWeek
            DateDiff_FromDate.FirstDayOfWeek = localizationSettings.GetFirstDayOfWeek();
            DateDiff_ToDate.FirstDayOfWeek   = localizationSettings.GetFirstDayOfWeek();

            // Setting the Language explicitly is not required,
            // this is a workaround for the bug in the control due to which
            // the displayed date is incorrect for non Gregorian Calendar Systems
            // The displayed date doesn't honor the shortdate format, on setting the Language the format is refreshed
            DateDiff_FromDate.Language = localizationSettings.GetLocaleName();
            DateDiff_ToDate.Language   = localizationSettings.GetLocaleName();

            // Set Min and Max Dates according to the Gregorian Calendar(1601 & 9999)
            var calendar = new Calendar();
            var today    = calendar.GetDateTime();

            calendar.ChangeCalendarSystem(CalendarIdentifiers.Gregorian);
            calendar.Day   = 1;
            calendar.Month = 1;
            calendar.Year  = c_minYear;
            var minYear = calendar.GetDateTime(); // 1st January, 1601

            DateDiff_FromDate.MinDate = minYear;
            DateDiff_ToDate.MinDate   = minYear;

            calendar.Day   = 31;
            calendar.Month = 12;
            calendar.Year  = c_maxYear;
            var maxYear = calendar.GetDateTime(); // 31st December, 9878

            DateDiff_FromDate.MaxDate = maxYear;
            DateDiff_ToDate.MaxDate   = maxYear;

            // Set the PlaceHolderText for CalendarDatePicker
            DateTimeFormatter dateTimeFormatter = LocalizationService.GetInstance().GetRegionalSettingsAwareDateTimeFormatter(
                "day month year",
                localizationSettings.GetCalendarIdentifier(),
                ClockIdentifiers.TwentyFourHour); // Clock Identifier is not used

            DateDiff_FromDate.DateFormat = "day month year";
            DateDiff_ToDate.DateFormat   = "day month year";

            var placeholderText = dateTimeFormatter.Format(today);

            DateDiff_FromDate.PlaceholderText = placeholderText;
            DateDiff_ToDate.PlaceholderText   = placeholderText;

            CopyMenuItem.Text = AppResourceProvider.GetInstance().GetResourceString("copyMenuItem");
            DateCalculationOption.SelectionChanged += DateCalcOption_Changed;
        }
        public GeneralViewModel(NotificationApplication notification,
            ShipmentInfo shipmentInfo,
            FacilityCollection facilityCollection,
            DateTimeFormatter dateTimeFormatter,
            QuantityFormatter quantityFormatter,
            PhysicalCharacteristicsFormatter physicalCharacteristicsFormatter)
        {
            Number = notification.NotificationNumber;
            IsDisposal = notification.NotificationType.Equals(NotificationType.Disposal);
            IsRecovery = notification.NotificationType.Equals(NotificationType.Recovery);

            var isPreconsented = facilityCollection.AllFacilitiesPreconsented;
            if (!isPreconsented.HasValue)
            {
                IsPreconsented = false;
                IsNotPreconsented = false;
            }
            else
            {
                IsPreconsented = isPreconsented.GetValueOrDefault();
                IsNotPreconsented = !isPreconsented.GetValueOrDefault();
            }

            if (shipmentInfo.NumberOfShipments > 1)
            {
                IsIndividualShipment = false;
                IsNotIndividualShipment = true;
            }
            else
            {
                IsIndividualShipment = true;
                IsNotIndividualShipment = false;
            }

            IntendedNumberOfShipments = shipmentInfo.NumberOfShipments.ToString();
            FirstDeparture = dateTimeFormatter.DateTimeToDocumentFormatString(shipmentInfo.ShipmentPeriod.FirstDate);
            LastDeparture = dateTimeFormatter.DateTimeToDocumentFormatString(shipmentInfo.ShipmentPeriod.LastDate);
            SetIntendedQuantityFields(shipmentInfo, quantityFormatter);

            var hasSpecialHandlingRequirements = notification.HasSpecialHandlingRequirements;
            if (!hasSpecialHandlingRequirements.HasValue)
            {
                IsSpecialHandling = false;
                IsNotSpecialHandling = false;
            }
            else
            {
                IsSpecialHandling = hasSpecialHandlingRequirements.GetValueOrDefault();
                IsNotSpecialHandling = !hasSpecialHandlingRequirements.GetValueOrDefault();
            }

            PackagingTypes = GetPackagingInfo(notification);

            PhysicalCharacteristics =
                physicalCharacteristicsFormatter.PhysicalCharacteristicsToCommaDelimitedString(
                    notification.PhysicalCharacteristics);
        }
Example #37
0
        static Episode MapDocumentToEpisode(IDocument document)
        {
            var number          = document.GetString("Number");
            var title           = document.GetString("Title");
            var publishDateText = document.GetString("PublishDate");
            var publishDate     = DateTimeFormatter.ToDateTime(publishDateText);

            return(new Episode(number, title, publishDate));
        }
        /// <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>
        /// 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();
        }
        /// <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);
            }
        }
        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)));
            }

        }
        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)));
        }
Example #43
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();
     }
 }
Example #44
0
        public TicketHistoryForm(Ticket ticket)
        {
            if (ticket == null)
            {
                throw new ArgumentNullException("ticket");
            }

            Ticket = ticket;

            InitializeComponent();

            if (Settings.Default.FormatDateTime)
            {
                try
                {
                    DateTimeFormatter dateTimeFormatter = new DateTimeFormatter
                    (
                        Settings.Default.DateTimePattern,
                        Settings.Default.Calendar
                    );

                    ticketHistoryListUserControl.DateTimeFormatter = dateTimeFormatter;
                    ticketHistoryDetailsUserControl.DateTimeFormatter = dateTimeFormatter;
                }
                catch (Exception)
                {
                    // Nothing.
                }
            }

            ticketHistoryListUserControl.TicketHistoryListView.SelectedIndexChanged += TicketHistoryListView_SelectedIndexChanged;

            ShowTicketHistory();

            // Select last history.
            if (ticketHistoryListUserControl.TicketHistoryListView.Items.Count > 0)
            {
                ticketHistoryListUserControl.TicketHistoryListView.SelectedIndices.Clear();
                ticketHistoryListUserControl.TicketHistoryListView.SelectedIndices.Add(0);
            }
        }
Example #45
0
        public static string ToDayOfWeekString(this DateTime dateTime)
        {
            if (_dayOfWeekFormatter == null)
            {
                _dayOfWeekFormatter = new DateTimeFormatter("dayofweek.full");
            }

            return _dayOfWeekFormatter.Format(dateTime);
        }
        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;
        }
 private void EnsureFormatter()
 {
     if (_formatter == null)
     {
         _formatter = new DateTimeFormatter(Format);
     }
 }
 public void ParseNullOrEmptyValue()
 {
     DateTimeFormatter fmt = new DateTimeFormatter("d");
     Assert.AreEqual(DateTime.MinValue, fmt.Parse(null));
     Assert.IsTrue(fmt.Parse("") is DateTime);
 }
        /// <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;
        }
Example #50
0
        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;
            }
        }
 /// <summary>
 /// Invalidates the display format for the date/time.
 /// </summary>
 protected void InvalidateFormat()
 {
     _formatter = null;
     UpdateFlyoutButtonContent();
 }
        public void ParseUsingDefaults()
        {
            DateTimeFormatter fmt = new DateTimeFormatter("d", "en-US");
            Assert.AreEqual(new DateTime(2004, 8, 14), fmt.Parse("8/14/2004"));
            Assert.AreEqual(new DateTime(1974, 8, 24), fmt.Parse("8/24/1974"));

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

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

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

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

            if (CultureInfoUtils.OperatingSystemIsLaterThanWindows7 && CultureInfoUtils.ClrIsVersion4OrLater)
            {
                Assert.AreEqual(new DateTime(2004, 8, 14), fmt.Parse("14-авг.-2004"));
                Assert.AreEqual(new DateTime(1974, 8, 24), fmt.Parse("24-авг.-1974"));
            }
            else
            {
                Assert.AreEqual(new DateTime(2004, 8, 14), fmt.Parse("14-авг-2004"));
                Assert.AreEqual(new DateTime(1974, 8, 24), fmt.Parse("24-авг-1974"));
            }
        }
Example #53
0
 static public string Format(DateTime dt, string format)
 {
     DateTimeFormatter formatter = new DateTimeFormatter();
     return formatter.Format(format, dt, formatter);
 }
        /// <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);
            });
        }
 public void FormatNullValue()
 {
     DateTimeFormatter fmt = new DateTimeFormatter("d");
     fmt.Format(null);
 }
Example #56
0
        /// <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;
            }
            
        }
 public void FormatNonDate()
 {
     DateTimeFormatter fmt = new DateTimeFormatter("d");
     fmt.Format("not a date");
 }
        public MovementViewModel(Movement movement,
            MovementDetails movementDetails,
            NotificationApplication notification,
            ShipmentInfo shipmentInfo,
            DateTimeFormatter dateTimeFormatter,
            QuantityFormatter quantityFormatter,
            PhysicalCharacteristicsFormatter physicalCharacteristicsFormatter,
            PackagingTypesFormatter packagingTypesFormatter)
        {
            if (notification == null)
            {
                return;
            }

            NotificationNumber = notification.NotificationNumber ?? string.Empty;
            IsSpecialHandling = notification.HasSpecialHandlingRequirements.GetValueOrDefault();
            IsNotSpecialHandling = !notification.HasSpecialHandlingRequirements.GetValueOrDefault(true);
            PhysicalCharacteristics =
                physicalCharacteristicsFormatter.PhysicalCharacteristicsToCommaDelimitedString(notification.PhysicalCharacteristics);
            IntendedNumberOfShipments = (shipmentInfo == null)
                ? "0"
                : shipmentInfo.NumberOfShipments.ToString();
            IsRecovery = notification.NotificationType == NotificationType.Recovery;
            IsDisposal = notification.NotificationType == NotificationType.Disposal;

            if (movement == null)
            {
                return;
            }

            Number = movement.Number.ToString();

            if (movementDetails == null)
            {
                return;
            }

            ActualDate = dateTimeFormatter.DateTimeToDocumentFormatString(movement.Date);
            SetQuantity(movementDetails, quantityFormatter);
            PackagingTypes = packagingTypesFormatter.PackagingTypesToCommaDelimitedString(movementDetails.PackagingInfos);
        }
Example #59
0
        /// <summary>
        /// Formats the specified date/time
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="outputStyle"></param>
        /// <returns></returns>
        /// 
        static public string Format(DateTime dt, Style outputStyle)
        {
            DateTimeFormatter formatter = new DateTimeFormatter();
                    
            switch(outputStyle)
            {
                case Style.DateTime:
                    return Format(dt, DefaultDateTimeFormat);
                case Style.Date:
                    return Format(dt, DefaultDateFormat);
                case Style.Time:
                    return Format(dt, DefaultTimeFormat);
				case Style.Timestamp:
					return Format(dt, DefaultTimestampFormat);

                default:
                    return dt.ToString();
            }
        }
        /// <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;
        }