Exemple #1
0
        public static bool TryParseUserTime(string s, out DateTime result)
        {
            DateTime time;

            if (TryParseCTCPTime(s, DateTimeStyles.NoCurrentDateDefault, out time))
            {
                if (time.Year == 1)
                {
                    // If they didn't specify a date, we add our own code.
                    result = new DateTime(999, 1, 3, time.Hour, time.Minute, time.Second, time.Millisecond);
                }
                else
                {
                    result = time;
                }
                return(true);
            }

            // If they specified a day of the week but no date, handle it specially.
            DateTimeFormatInfo format = DateTimeFormatInfo.CurrentInfo;

            s = s.TrimStart();
            DayOfWeek day;

            for (day = DayOfWeek.Sunday; day <= DayOfWeek.Saturday; ++day)
            {
                if (s.StartsWith(format.GetDayName(day)))
                {
                    s = s.Substring(format.GetDayName(day).Length);
                    break;
                }
                if (s.StartsWith(format.GetAbbreviatedDayName(day)))
                {
                    s = s.Substring(format.GetAbbreviatedDayName(day).Length);
                    break;
                }
            }
            if ((int)day == 7)
            {
                result = default(DateTime);
                return(false);
            }

            if (!TryParseCTCPTime(s, DateTimeStyles.NoCurrentDateDefault, out time) || time.Year != 1)
            {
                result = default(DateTime);
                return(false);
            }
            result = new DateTime(999, 1, 6 + (int)day, time.Hour, time.Minute, time.Second, time.Millisecond);
            return(true);
        }
Exemple #2
0
    private bool VerificationHelper(DateTimeFormatInfo info, string[] expected, string errorno)
    {
        bool retval = true;

        DayOfWeek[] values = new DayOfWeek[] {
            DayOfWeek.Sunday,
            DayOfWeek.Monday,
            DayOfWeek.Tuesday,
            DayOfWeek.Wednesday,
            DayOfWeek.Thursday,
            DayOfWeek.Friday,
            DayOfWeek.Saturday
        };

        for (int i = 0; i < values.Length; ++i)
        {
            string actual = info.GetAbbreviatedDayName(values[i]);
            if (actual != expected[i])
            {
                TestLibrary.TestFramework.LogError(errorno, "GetAbbreviatedDayName returns wrong value");
                TestLibrary.TestFramework.LogInformation("WARNING[LOCAL VARIABLES] values[i] = " + values[i] + ", expected[i] = " + expected[i] + ", actual = " + actual);
                retval = false;
            }
        }

        return(retval);
    }
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when dayofweek is not a valid System.DayOfWeek value. ");

        try
        {
            DateTimeFormatInfo info = new DateTimeFormatInfo();

            info.GetAbbreviatedDayName((DayOfWeek)(-1));

            TestLibrary.TestFramework.LogError("101.1", "ArgumentOutOfRangeException is not thrown");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException)
        {
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return(retVal);
    }
        /// <summary>
        /// Format <see cref="BirthDate.Day"/> and append the format-result to the <paramref name="result"/>
        /// and return the length of the token.
        /// </summary>
        /// <remarks>
        /// The formatted day will be:
        ///  - If <see cref="BirthDateFormatInfo.MaskDay"/> is true, masked with the same length as token, with
        ///    <see cref="BirthDateFormatInfo.NumberMaskChar"/> (Token Length &lt;= 2) or
        ///    <see cref="BirthDateFormatInfo.TextMaskChar"/> (Token Length &gt; 2).
        ///  - Token length = 1: (Day mod 100) without leading zero.
        ///  - Token length = 2: (Day mod 100) with leading zero.
        ///  - Token length = 3: Day name abbreviated as 3 characters.
        ///  - Token length > 3: Day name (not abbreviated).
        /// </remarks>
        /// <param name="result">The result.</param>
        /// <param name="format">The format.</param>
        /// <param name="pos">The position.</param>
        /// <param name="day">The day.</param>
        /// <param name="dateTime">The date time.</param>
        /// <returns></returns>
        private int FormatDay(StringBuilder result, string format, int pos, int day, DateTime dateTime)
        {
            int tokenLen = FormatHelper.ParseLengthOfRepeatPattern(format, pos, 'd');

            if (tokenLen <= 2)
            {
                // tokenLen == 1 : Day of month as digits with no leading zero.
                // tokenLen == 2 : Day of month as digits with leading zero for single-digit months.
                FormatHelper.FormatDigits(result, day, tokenLen, _birthDateFormatInfo.MaskDay, _birthDateFormatInfo.NumberMaskChar);
            }
            else if (tokenLen == 3 && !_birthDateFormatInfo.MaskDay)
            {
                // tokenLen == 3 : Day of week as a three-leter abbreviation.
                int dayOfWeek = (int)_calendar.GetDayOfWeek(dateTime);
                result.Append(_dateTimeFormatInfo.GetAbbreviatedDayName((DayOfWeek)dayOfWeek));
            }
            else if (!_birthDateFormatInfo.MaskDay)
            {
                // tokenLen >= 4 : Day of week as its full name.
                int dayOfWeek = (int)_calendar.GetDayOfWeek(dateTime);
                result.Append(_dateTimeFormatInfo.GetDayName((DayOfWeek)dayOfWeek));
            }
            else
            {
                result.Append("".PadLeft(tokenLen, _birthDateFormatInfo.TextMaskChar));
            }

            return(tokenLen);
        }
Exemple #5
0
        private static Month GenerateMonth(int year, int month)
        {
            DateTimeFormatInfo dtfi = CultureInfo.CurrentCulture.DateTimeFormat;
            string             name = UppercaseFirst(dtfi.GetMonthName(month));

            // Populating the months
            Day[]    days     = new Day[32];
            DateTime myDT     = new DateTime(year, month, 1, new GregorianCalendar());
            int      curMonth = myDT.Month;

            for (int i = 1; i <= 31; i++)
            {
                if (curMonth != myDT.Month)
                {
                    days[i - 1] = EMPTY;
                }
                else
                {
                    DayOfWeek dw = myDT.DayOfWeek;

                    days[i - 1] = new Day(myDT.Day, UppercaseFirst(dtfi.GetAbbreviatedDayName(dw)), IsMoon(myDT), dw == DayOfWeek.Sunday || IsFestivity(myDT));
                }
                myDT = myDT.AddDays(1);
            }
            days[31] = EMPTY;

            Month mesecontainer = new Month(year, name, days);

            return(mesecontainer);
        }
 // Token: 0x060015E0 RID: 5600 RVA: 0x00040577 File Offset: 0x0003E777
 private static string FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi)
 {
     if (repeat == 3)
     {
         return(dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek));
     }
     return(dtfi.GetDayName((DayOfWeek)dayOfWeek));
 }
 public void NegTest1()
 {
     DateTimeFormatInfo info = new DateTimeFormatInfo();
     Assert.Throws<ArgumentOutOfRangeException>(() =>
     {
         info.GetAbbreviatedDayName((DayOfWeek)(-1));
     });
 }
Exemple #8
0
        /// <summary>
        /// Returns the internationalised name of the weekday dependent on the setting of the 'Abbreviate' flag.
        /// </summary>
        /// <param name="month">The weekday number - 1 to 7.</param>
        /// <returns>The internationalised name of the weekday, short or long.</returns>
        private string GetDayName(DayOfWeek day)
        {
            if (abbreviate)
            {
                return(dateTimeInfo.GetAbbreviatedDayName(day));
            }

            return(dateTimeInfo.GetDayName(day));
        }
Exemple #9
0
        public void NegTest1()
        {
            DateTimeFormatInfo info = new DateTimeFormatInfo();

            Assert.Throws <ArgumentOutOfRangeException>(() =>
            {
                info.GetAbbreviatedDayName((DayOfWeek)(-1));
            });
        }
        /// <summary>
        /// Gets the abbreviated or full day name for the specified <see cref="DayOfWeek"/> value using,
        /// if not null, the <paramref name="nameProvider"/> or the <see cref="DateTimeFormatInfo"/> specified by <paramref name="info"/>.
        /// </summary>
        /// <param name="dayofweek">The <see cref="DayOfWeek"/> value to get the day name for.</param>
        /// <param name="info">The <see cref="DateTimeFormatInfo"/> to get the name.</param>
        /// <param name="nameProvider">The <see cref="ICustomFormatProvider"/> to get the name.
        /// This parameter has precedence before the <paramref name="info"/>. Can be <c>null</c>.</param>
        /// <param name="abbreviated">true to get the abbreviated day name; false otherwise.</param>
        /// <returns>The full or abbreviated day name specified by <paramref name="dayofweek"/> value.</returns>
        private static string GetDayName(DayOfWeek dayofweek, DateTimeFormatInfo info, ICustomFormatProvider nameProvider, bool abbreviated)
        {
            if (nameProvider != null)
            {
                return(abbreviated ? nameProvider.GetAbbreviatedDayName(dayofweek) : nameProvider.GetDayName(dayofweek));
            }

            return(abbreviated ? info.GetAbbreviatedDayName(dayofweek) : info.GetDayName(dayofweek));
        }
Exemple #11
0
        private TableRow CreateDayHeader(DateTime firstDay, DateTime visibleDate, System.Globalization.Calendar threadCalendar)
        {
            TableRow row = new TableRow();

            DateTimeFormatInfo dtf = DateTimeFormatInfo.CurrentInfo;

            TableItemStyle dayNameStyle = new TableItemStyle();

            dayNameStyle.HorizontalAlign = HorizontalAlign.Center;
            dayNameStyle.CopyFrom(DayHeaderStyle);
            DayNameFormat dayNameFormat = DayNameFormat;

            int numericFirstDay = (int)threadCalendar.GetDayOfWeek(firstDay);

            for (int i = numericFirstDay; i < numericFirstDay + 7; i++)
            {
                string dayName;
                int    dayOfWeek = i % 7;
                switch (dayNameFormat)
                {
                case DayNameFormat.FirstLetter:
                    dayName = dtf.GetDayName((DayOfWeek)dayOfWeek).Substring(0, 1);
                    break;

                case DayNameFormat.FirstTwoLetters:
                    dayName = dtf.GetDayName((DayOfWeek)dayOfWeek).Substring(0, 2);
                    break;

                case DayNameFormat.Full:
                    dayName = dtf.GetDayName((DayOfWeek)dayOfWeek);
                    break;

                case DayNameFormat.Short:
                    dayName = dtf.GetAbbreviatedDayName((DayOfWeek)dayOfWeek);
                    break;

                case DayNameFormat.Shortest:
                    dayName = dtf.GetShortestDayName((DayOfWeek)dayOfWeek);
                    break;

                default:
                    System.Diagnostics.Debug.Assert(false, "Unknown DayNameFormat value!");

                    goto
                case DayNameFormat.Short;
                }

                TableCell cell = new TableCell();
                cell.ApplyStyle(dayNameStyle);
                cell.Text = dayName;
                row.Cells.Add(cell);
            }
            return(row);
        }
Exemple #12
0
        public static string WeekdayName(int Weekday,
                                         [Optional, DefaultParameterValue(false)] bool Abbreviate,
                                         [Optional, DefaultParameterValue(FirstDayOfWeek.System)]
                                         FirstDayOfWeek FirstDayOfWeekValue)
        {
            string abbreviatedDayName;

            if ((Weekday < 1) || (Weekday > 7))
            {
                throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[] { "Weekday" }));
            }
            if ((FirstDayOfWeekValue < FirstDayOfWeek.System) || (FirstDayOfWeekValue > FirstDayOfWeek.Saturday))
            {
                throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[] { "FirstDayOfWeekValue" }));
            }
            DateTimeFormatInfo format = (DateTimeFormatInfo)Utils.GetCultureInfo().GetFormat(typeof(DateTimeFormatInfo));

            if (FirstDayOfWeekValue == FirstDayOfWeek.System)
            {
                FirstDayOfWeekValue = (FirstDayOfWeek)(format.FirstDayOfWeek + 1);
            }
            try
            {
                if (Abbreviate)
                {
                    abbreviatedDayName = format.GetAbbreviatedDayName((DayOfWeek)(((Weekday + (int)FirstDayOfWeekValue) - 2) % 7));
                }
                else
                {
                    abbreviatedDayName = format.GetDayName((DayOfWeek)(((Weekday + (int)FirstDayOfWeekValue) - 2) % 7));
                }
            }
            catch (StackOverflowException exception)
            {
                throw exception;
            }
            catch (OutOfMemoryException exception2)
            {
                throw exception2;
            }
            catch (ThreadAbortException exception3)
            {
                throw exception3;
            }
            catch (Exception)
            {
                throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[] { "Weekday" }));
            }
            if (abbreviatedDayName.Length == 0)
            {
                throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[] { "Weekday" }));
            }
            return(abbreviatedDayName);
        }
Exemple #13
0
 private static String FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi)
 {
     Contract.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6");
     if (repeat == 3)
     {
         return(dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek));
     }
     // Call dtfi.GetDayName() here, instead of accessing DayNames property, because we don't
     // want a clone of DayNames, which will hurt perf.
     return(dtfi.GetDayName((DayOfWeek)dayOfWeek));
 }
Exemple #14
0
        /// <summary>
        /// Gets day name.
        /// </summary>
        /// <param name="day"></param>
        /// <param name="abbreviate"></param>
        /// <param name="provider"></param>
        /// <returns></returns>
        public static string GetDayName(int day, bool abbreviate, IFormatProvider provider)
        {
            DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(provider);
            DateTime           date = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, day);

            if (abbreviate)
            {
                return(info.GetAbbreviatedDayName(date.DayOfWeek));
            }

            return(info.GetDayName(date.DayOfWeek));
        }
Exemple #15
0
        public async Task <Forecast> GetForecastAsync(Position location)
        {
            var openWeatherForecast = await _openWeatherMapService.Get7DayForecastAsync(location);

            var forecast = new Forecast()
            {
                Location = location
            };

            var daysClean = 0;
            var dtf       = new DateTimeFormatInfo();

            foreach (var forecastItem in openWeatherForecast.Forecasts)
            {
                var weather = forecastItem.WeatherList.FirstOrDefault();
                var date    = new DateTime(1970, 1, 1).AddSeconds(forecastItem.Dt);

                forecast.WeatherList.Add(new WeatherViewTemplate {
                    WeatherCondition = weather.Description,
                    DayAbbreviation  = dtf.GetAbbreviatedDayName(date.DayOfWeek),
                    TempHigh         = Convert.ToInt32(forecastItem.Temperature.Max) + "º",
                    TempLow          = Convert.ToInt32(forecastItem.Temperature.Min) + "º",
                    Icon             = GetWeatherIcon(weather.Main)
                });
            }

            foreach (var forecastItem in openWeatherForecast.Forecasts)
            {
                var date = new DateTime(1970, 1, 1).AddSeconds(forecastItem.Dt);

                if (date.Date.Date < DateTime.Now.Date.Date)
                {
                    continue;
                }

                var weatherForToday = forecastItem.WeatherList [0];

                forecast.BadWeatherDay     = date;
                forecast.Reason            = ConvertReason(weatherForToday.Main);
                forecast.ReasonDescription = weatherForToday.Description;

                if (WeatherIsBad(weatherForToday))
                {
                    break;
                }

                daysClean++;
            }

            forecast.DaysClean = daysClean;

            return(forecast);
        }
Exemple #16
0
        /// <summary>
        /// Gets the string representation for a particular day in the week.
        /// </summary>
        /// <param name="weekDay">Specifies the day of the week.</param>
        /// <returns>the string representation for the specified day.</returns>
        internal protected virtual string GetDayHeaderString(int weekDay)
        {
            DateTimeFormatInfo dateLocalInfo = this.Calendar.DateTimeFormat;
            DayNameFormat      dayFormat     = this.Calendar.DayNameFormat;
            string             dayString     = String.Empty;

            switch (dayFormat)
            {
            case DayNameFormat.Full:
            {
                dayString = dateLocalInfo.GetDayName((DayOfWeek)weekDay);
                break;
            }

            case DayNameFormat.FirstLetter:
            {
                string str = dateLocalInfo.ShortestDayNames[weekDay];
                TextElementEnumerator iter = StringInfo.GetTextElementEnumerator(str);
                iter.MoveNext();
                dayString = iter.Current.ToString();
                break;
            }

            case DayNameFormat.FirstTwoLetters:
            {
                string str = dateLocalInfo.ShortestDayNames[weekDay];
                TextElementEnumerator iter = StringInfo.GetTextElementEnumerator(str);
                iter.MoveNext();
                StringBuilder ftl = new StringBuilder(iter.Current.ToString());
                if (iter.MoveNext())         //in case of Arabic cultures
                {
                    ftl.Append(iter.Current.ToString());
                }
                dayString = ftl.ToString();
                break;
            }

            case DayNameFormat.Short:
            {
                dayString = dateLocalInfo.GetAbbreviatedDayName((DayOfWeek)weekDay);
                break;
            }

            case DayNameFormat.Shortest:
            default:
            {
                dayString = dateLocalInfo.ShortestDayNames[weekDay];
                break;
            }
            }
            return(dayString);
        }
Exemple #17
0
    public static string[] getShortWeekdays(string langTag, string[] swdays)
    {
        CultureInfo ci;

        if (TryGetCultureInfoFromLangTag(langTag, out ci))
        {
            DateTimeFormatInfo dtfi = ci.DateTimeFormat;
            for (int i = 0; i < 7; i++)
            {
                swdays[i + 1] = dtfi.GetAbbreviatedDayName((DayOfWeek)i);
            }
        }
        return(swdays);
    }
Exemple #18
0
        public async Task <RelatorioImpressaoCalendarioDto> Handle(ObterRelatorioImpressaoCalendarioQuery request, CancellationToken cancellationToken)
        {
            var consideraHistorico = request.TipoCalendario.AnoLetivo != DateTime.Today.Year;


            string dreCodigo = "", ueCodigo = "";

            if (request.Dre != null)
            {
                dreCodigo = request.Dre.Codigo;
            }

            if (request.Ue != null)
            {
                ueCodigo = request.Ue.Codigo;
            }


            var retornoQuery = await calendarioEventoRepository.ObterEventosPorUsuarioTipoCalendarioPerfilDreUe(request.UsuarioRF, request.UsuarioPerfil, consideraHistorico, request.ConsideraPendenteAprovacao,
                                                                                                                dreCodigo, ueCodigo, !request.EhSME, request.PodeVisualizarEventosOcorrenciaDre, request.TipoCalendario.Id);

            var retorno = MontarCabecalho(request.Dre, request.Ue, request.TipoCalendario);

            var meses = retornoQuery.Select(a => a.DataInicio.Month).Distinct().OrderBy(a => a);

            CultureInfo        cultureinfo = new CultureInfo("pt-BR");
            DateTimeFormatInfo dtfi        = cultureinfo.DateTimeFormat;

            foreach (var mes in meses)
            {
                var mesParaIncluir = new RelatorioImpressaoCalendarioMesDto();
                mesParaIncluir.MesDescricao = new DateTime(2020, mes, 1).ToString("MMMM", cultureinfo).ToUpper();
                mesParaIncluir.MesNumero    = mes;

                var eventosDoMes = retornoQuery.Where(a => a.DataInicio.Month == mes);
                foreach (var eventoDoMes in eventosDoMes.OrderBy(a => a.DataInicio))
                {
                    var eventoParaIncluir = new RelatorioImpressaoCalendarioEventoDto();
                    eventoParaIncluir.Dia        = eventoDoMes.DataInicio.Day.ToString().PadLeft(2, '0');
                    eventoParaIncluir.DiaSemana  = dtfi.GetAbbreviatedDayName(eventoDoMes.DataInicio.DayOfWeek).ToUpper();
                    eventoParaIncluir.Evento     = eventoDoMes.Nome;
                    eventoParaIncluir.EventoTipo = eventoDoMes.TipoEvento;
                    mesParaIncluir.Eventos.Add(eventoParaIncluir);
                }

                retorno.Meses.Add(mesParaIncluir);
            }

            return(retorno);
        }
        public bool GetLocationData(City city)
        {
            int cityId;

            // Other grabbers store string IDs and this would fail here
            if (city.Grabber != GetServiceName() || !int.TryParse(city.Id, out cityId))
            {
                return(false);
            }
            var client         = new OpenWeatherMapClient(GetKey());
            var currentWeather = Task.Run(async() => await client.CurrentWeather.GetByCityId(cityId, _metricSystem, _language)).Result;

            city.Condition.Temperature   = FormatTemp(currentWeather.Temperature.Value, currentWeather.Temperature.Unit);
            city.Condition.Humidity      = string.Format("{0} {1}", currentWeather.Humidity.Value, currentWeather.Humidity.Unit);
            city.Condition.Pressure      = string.Format("{0:F0} {1}", currentWeather.Pressure.Value, currentWeather.Pressure.Unit);
            city.Condition.Precipitation = string.Format("{0} {1}", currentWeather.Precipitation.Value, currentWeather.Precipitation.Unit);
            city.Condition.Wind          = string.Format("{0} {1}", currentWeather.Wind.Speed.Name, currentWeather.Wind.Direction.Name);
            city.Condition.Condition     = currentWeather.Weather.Value;
            var  now     = DateTime.Now;
            bool isNight = now >= currentWeather.City.Sun.Set || now < currentWeather.City.Sun.Rise;

            city.Condition.BigIcon   = @"Weather\128x128\" + GetWeatherIcon(currentWeather.Weather.Number, isNight);
            city.Condition.SmallIcon = @"Weather\64x64\" + GetWeatherIcon(currentWeather.Weather.Number, isNight);

            var forecasts = Task.Run(async() => await client.Forecast.GetByCityId(cityId, true, _metricSystem, _language)).Result;

            foreach (var forecast in forecasts.Forecast)
            {
                DayForecast dayForecast = new DayForecast();
                dayForecast.High = FormatTemp(forecast.Temperature.Max, currentWeather.Temperature.Unit);
                dayForecast.Low  = FormatTemp(forecast.Temperature.Min, currentWeather.Temperature.Unit);

                dayForecast.Humidity = string.Format("{0} {1}", forecast.Humidity.Value, forecast.Humidity.Unit);
                // TODO:
                //dayForecast.Pressure = string.Format("{0} {1}", forecast.Pressure.Value, forecast.Pressure.Unit);
                dayForecast.Precipitation = string.Format("{0} {1}", forecast.Precipitation.Value, forecast.Precipitation.Unit);
                dayForecast.Wind          = string.Format("{0} {1}", forecast.WindSpeed.Mps, currentWeather.Wind.Direction.Name);
                dayForecast.Overview      = forecast.Symbol.Name;
                dayForecast.BigIcon       = @"Weather\128x128\" + GetWeatherIcon(forecast.Symbol.Number, false);
                dayForecast.SmallIcon     = @"Weather\64x64\" + GetWeatherIcon(forecast.Symbol.Number, false);
                string fomattedDate = forecast.Day.ToString(_dateFormat.ShortDatePattern, _dateFormat);
                string day          = _dateFormat.GetAbbreviatedDayName(forecast.Day.DayOfWeek);
                dayForecast.Day = String.Format("{0} {1}", day, fomattedDate);

                city.ForecastCollection.Add(dayForecast);
            }
            city.ForecastCollection.FireChange();
            return(true);
        }
Exemple #20
0
        private void VerificationHelper(DateTimeFormatInfo info, string[] expected)
        {
            DayOfWeek[] values = new DayOfWeek[] {
                DayOfWeek.Sunday,
                DayOfWeek.Monday,
                DayOfWeek.Tuesday,
                DayOfWeek.Wednesday,
                DayOfWeek.Thursday,
                DayOfWeek.Friday,
                DayOfWeek.Saturday
            };

            for (int i = 0; i < values.Length; ++i)
            {
                string actual = info.GetAbbreviatedDayName(values[i]);
                Assert.Equal(expected[i], actual);
            }
        }
        private void VerificationHelper(DateTimeFormatInfo info, string[] expected)
        {
            DayOfWeek[] values = new DayOfWeek[] {
            DayOfWeek.Sunday,
            DayOfWeek.Monday,
            DayOfWeek.Tuesday,
            DayOfWeek.Wednesday,
            DayOfWeek.Thursday,
            DayOfWeek.Friday,
            DayOfWeek.Saturday
            };

            for (int i = 0; i < values.Length; ++i)
            {
                string actual = info.GetAbbreviatedDayName(values[i]);
                Assert.Equal(expected[i], actual);
            }
        }
        public void GetAbbreviatedDayName(DateTimeFormatInfo info, string[] expected)
        {
            DayOfWeek[] values = new DayOfWeek[]
            {
                DayOfWeek.Sunday,
                DayOfWeek.Monday,
                DayOfWeek.Tuesday,
                DayOfWeek.Wednesday,
                DayOfWeek.Thursday,
                DayOfWeek.Friday,
                DayOfWeek.Saturday
            };

            for (int i = 0; i < values.Length; ++i)
            {
                Assert.Equal(expected[i], info.GetAbbreviatedDayName(values[i]));
            }
        }
        public void GetAbbreviatedDayName(DateTimeFormatInfo info, string[] expected)
        {
            DayOfWeek[] values = new DayOfWeek[]
            {
                DayOfWeek.Sunday,
                DayOfWeek.Monday,
                DayOfWeek.Tuesday,
                DayOfWeek.Wednesday,
                DayOfWeek.Thursday,
                DayOfWeek.Friday,
                DayOfWeek.Saturday
            };

            for (int i = 0; i < values.Length; ++i)
            {
                Assert.Equal(expected[i], info.GetAbbreviatedDayName(values[i]));
            }
        }
Exemple #24
0
        protected internal virtual string GetDayHeaderString(int weekDay)
        {
            DateTimeFormatInfo dateTimeFormat = this.Calendar.DateTimeFormat;
            DayNameFormat      dayNameFormat  = this.Calendar.DayNameFormat;
            string             empty          = string.Empty;
            string             str;

            switch (dayNameFormat)
            {
            case DayNameFormat.Full:
                str = dateTimeFormat.GetDayName((DayOfWeek)weekDay);
                break;

            case DayNameFormat.Short:
                str = dateTimeFormat.GetAbbreviatedDayName((DayOfWeek)weekDay);
                break;

            case DayNameFormat.FirstLetter:
                TextElementEnumerator elementEnumerator1 = StringInfo.GetTextElementEnumerator(dateTimeFormat.ShortestDayNames[weekDay]);
                elementEnumerator1.MoveNext();
                str = elementEnumerator1.Current.ToString();
                break;

            case DayNameFormat.FirstTwoLetters:
                TextElementEnumerator elementEnumerator2 = StringInfo.GetTextElementEnumerator(dateTimeFormat.ShortestDayNames[weekDay]);
                elementEnumerator2.MoveNext();
                StringBuilder stringBuilder = new StringBuilder(elementEnumerator2.Current.ToString());
                if (elementEnumerator2.MoveNext())
                {
                    stringBuilder.Append(elementEnumerator2.Current.ToString());
                }
                str = stringBuilder.ToString();
                break;

            default:
                str = dateTimeFormat.ShortestDayNames[weekDay];
                break;
            }
            return(str);
        }
        protected string GetTotalString(object Total, object Day1, object Day2, object Day3, object Day4, object Day5, object Day6, object Day7)
        {
            string sToolTip = "";

            string[] hrs = new string[7];
            hrs[0] = Mediachase.UI.Web.Util.CommonHelper.GetHours((int)(double)Day1);
            hrs[1] = Mediachase.UI.Web.Util.CommonHelper.GetHours((int)(double)Day2);
            hrs[2] = Mediachase.UI.Web.Util.CommonHelper.GetHours((int)(double)Day3);
            hrs[3] = Mediachase.UI.Web.Util.CommonHelper.GetHours((int)(double)Day4);
            hrs[4] = Mediachase.UI.Web.Util.CommonHelper.GetHours((int)(double)Day5);
            hrs[5] = Mediachase.UI.Web.Util.CommonHelper.GetHours((int)(double)Day6);
            hrs[6] = Mediachase.UI.Web.Util.CommonHelper.GetHours((int)(double)Day7);
            string separator = "\r\n";

            if ((Request.UserAgent.IndexOf("MSIE") < 0) && (Request.UserAgent.IndexOf("Safari") < 0))
            {
                separator = " ";
            }

            for (int i = 0; i < 7; i++)
            {
                sToolTip += dtf.GetAbbreviatedDayName((DayOfWeek)index) + ":&nbsp;" + hrs[i] + separator;
                index++;
                if (index == 7)
                {
                    index = 0;
                }
            }
            sToolTip = sToolTip.Substring(0, sToolTip.Length - separator.Length);
            string imageUrl = ResolveClientUrl("~/layouts/images/info.gif");

            return(String.Format(CultureInfo.InvariantCulture,
                                 "<table width='100%' cellpadding='0' cellspacing='0'><tr><td width='15px'><img align='absmiddle' style='cursor:pointer' title='{0}' src='{1}' width='13px' border='0'></td><td class='text' align='right'>{2}</td></tr></table>",
                                 sToolTip,
                                 imageUrl,
                                 Mediachase.UI.Web.Util.CommonHelper.GetHours((int)(double)Total)));
        }
Exemple #26
0
        public static string ToString(DateTime dt, TimeSpan?utc_offset, string format, DateTimeFormatInfo dfi)
        {
            // the length of the format is usually a good guess of the number
            // of chars in the result. Might save us a few bytes sometimes
            // Add + 10 for cases like mmmm dddd
            StringBuilder result = new StringBuilder(format.Length + 10);

            // For some cases, the output should not use culture dependent calendar
            DateTimeFormatInfo inv = DateTimeFormatInfo.InvariantInfo;

            if (format == inv.RFC1123Pattern)
            {
                dfi = inv;
            }
            else if (format == inv.UniversalSortableDateTimePattern)
            {
                dfi = inv;
            }

            int i = 0;

            while (i < format.Length)
            {
                int  tokLen;
                bool omitZeros = false;
                char ch        = format [i];

                switch (ch)
                {
                //
                // Time Formats
                //
                case 'h':
                    // hour, [1, 12]
                    tokLen = DateTimeUtils.CountRepeat(format, i, ch);

                    int hr = dt.Hour % 12;
                    if (hr == 0)
                    {
                        hr = 12;
                    }

                    DateTimeUtils.ZeroPad(result, hr, tokLen == 1 ? 1 : 2);
                    break;

                case 'H':
                    // hour, [0, 23]
                    tokLen = DateTimeUtils.CountRepeat(format, i, ch);
                    DateTimeUtils.ZeroPad(result, dt.Hour, tokLen == 1 ? 1 : 2);
                    break;

                case 'm':
                    // minute, [0, 59]
                    tokLen = DateTimeUtils.CountRepeat(format, i, ch);
                    DateTimeUtils.ZeroPad(result, dt.Minute, tokLen == 1 ? 1 : 2);
                    break;

                case 's':
                    // second [0, 29]
                    tokLen = DateTimeUtils.CountRepeat(format, i, ch);
                    DateTimeUtils.ZeroPad(result, dt.Second, tokLen == 1 ? 1 : 2);
                    break;

                case 'F':
                    omitZeros = true;
                    goto case 'f';

                case 'f':
                    // fraction of second, to same number of
                    // digits as there are f's

                    tokLen = DateTimeUtils.CountRepeat(format, i, ch);
                    if (tokLen > 7)
                    {
                        throw new FormatException("Invalid Format String");
                    }

                    int dec      = (int)((long)(dt.Ticks % TimeSpan.TicksPerSecond) / (long)Math.Pow(10, 7 - tokLen));
                    int startLen = result.Length;
                    DateTimeUtils.ZeroPad(result, dec, tokLen);

                    if (omitZeros)
                    {
                        while (result.Length > startLen && result [result.Length - 1] == '0')
                        {
                            result.Length--;
                        }
                        // when the value was 0, then trim even preceding '.' (!) It is fixed character.
                        if (dec == 0 && startLen > 0 && result [startLen - 1] == '.')
                        {
                            result.Length--;
                        }
                    }

                    break;

                case 't':
                    // AM/PM. t == first char, tt+ == full
                    tokLen = DateTimeUtils.CountRepeat(format, i, ch);
                    string desig = dt.Hour < 12 ? dfi.AMDesignator : dfi.PMDesignator;

                    if (tokLen == 1)
                    {
                        if (desig.Length >= 1)
                        {
                            result.Append(desig [0]);
                        }
                    }
                    else
                    {
                        result.Append(desig);
                    }

                    break;

                case 'z':
                    // timezone. t = +/-h; tt = +/-hh; ttt+=+/-hh:mm
                    tokLen = DateTimeUtils.CountRepeat(format, i, ch);
                    TimeSpan offset =
                        utc_offset ??
                        TimeZone.CurrentTimeZone.GetUtcOffset(dt);

                    if (offset.Ticks >= 0)
                    {
                        result.Append('+');
                    }
                    else
                    {
                        result.Append('-');
                    }

                    switch (tokLen)
                    {
                    case 1:
                        result.Append(Math.Abs(offset.Hours));
                        break;

                    case 2:
                        result.Append(Math.Abs(offset.Hours).ToString("00"));
                        break;

                    default:
                        result.Append(Math.Abs(offset.Hours).ToString("00"));
                        result.Append(':');
                        result.Append(Math.Abs(offset.Minutes).ToString("00"));
                        break;
                    }
                    break;

                case 'K':                 // 'Z' (UTC) or zzz (Local)
                    tokLen = 1;

                    if (utc_offset != null || dt.Kind == DateTimeKind.Local)
                    {
                        offset = utc_offset ?? TimeZone.CurrentTimeZone.GetUtcOffset(dt);
                        if (offset.Ticks >= 0)
                        {
                            result.Append('+');
                        }
                        else
                        {
                            result.Append('-');
                        }
                        result.Append(Math.Abs(offset.Hours).ToString("00"));
                        result.Append(':');
                        result.Append(Math.Abs(offset.Minutes).ToString("00"));
                    }
                    else if (dt.Kind == DateTimeKind.Utc)
                    {
                        result.Append('Z');
                    }
                    break;

                //
                // Date tokens
                //
                case 'd':
                    // day. d(d?) = day of month (leading 0 if two d's)
                    // ddd = three leter day of week
                    // dddd+ full day-of-week
                    tokLen = DateTimeUtils.CountRepeat(format, i, ch);

                    if (tokLen <= 2)
                    {
                        DateTimeUtils.ZeroPad(result, dfi.Calendar.GetDayOfMonth(dt), tokLen == 1 ? 1 : 2);
                    }
                    else if (tokLen == 3)
                    {
                        result.Append(dfi.GetAbbreviatedDayName(dfi.Calendar.GetDayOfWeek(dt)));
                    }
                    else
                    {
                        result.Append(dfi.GetDayName(dfi.Calendar.GetDayOfWeek(dt)));
                    }

                    break;

                case 'M':
                    // Month.m(m?) = month # (with leading 0 if two mm)
                    // mmm = 3 letter name
                    // mmmm+ = full name
                    tokLen = DateTimeUtils.CountRepeat(format, i, ch);
                    int month = dfi.Calendar.GetMonth(dt);
                    if (tokLen <= 2)
                    {
                        DateTimeUtils.ZeroPad(result, month, tokLen);
                    }
                    else if (tokLen == 3)
                    {
                        result.Append(dfi.GetAbbreviatedMonthName(month));
                    }
                    else
                    {
                        result.Append(dfi.GetMonthName(month));
                    }

                    break;

                case 'y':
                    // Year. y(y?) = two digit year, with leading 0 if yy
                    // yyy+ full year with leading zeros if needed.
                    tokLen = DateTimeUtils.CountRepeat(format, i, ch);

                    if (tokLen <= 2)
                    {
                        DateTimeUtils.ZeroPad(result, dfi.Calendar.GetYear(dt) % 100, tokLen);
                    }
                    else
                    {
                        DateTimeUtils.ZeroPad(result, dfi.Calendar.GetYear(dt), tokLen);
                    }
                    break;

                case 'g':
                    // Era name
                    tokLen = DateTimeUtils.CountRepeat(format, i, ch);
                    result.Append(dfi.GetEraName(dfi.Calendar.GetEra(dt)));
                    break;

                //
                // Other
                //
                case ':':
                    result.Append(dfi.TimeSeparator);
                    tokLen = 1;
                    break;

                case '/':
                    result.Append(dfi.DateSeparator);
                    tokLen = 1;
                    break;

                case '\'':
                case '"':
                    tokLen = DateTimeUtils.ParseQuotedString(format, i, result);
                    break;

                case '%':
                    if (i >= format.Length - 1)
                    {
                        throw new FormatException("% at end of date time string");
                    }
                    if (format [i + 1] == '%')
                    {
                        throw new FormatException("%% in date string");
                    }

                    // Look for the next char
                    tokLen = 1;
                    break;

                case '\\':
                    // C-Style escape
                    if (i >= format.Length - 1)
                    {
                        throw new FormatException("\\ at end of date time string");
                    }

                    result.Append(format [i + 1]);
                    tokLen = 2;

                    break;

                default:
                    // catch all
                    result.Append(ch);
                    tokLen = 1;
                    break;
                }
                i += tokLen;
            }
            return(result.ToString());
        }
Exemple #27
0
        public static string ToString(DateTime dt, TimeSpan?utc_offset, string format, DateTimeFormatInfo dfi)
        {
            StringBuilder      stringBuilder = new StringBuilder(format.Length + 10);
            DateTimeFormatInfo invariantInfo = DateTimeFormatInfo.InvariantInfo;

            if (format == invariantInfo.RFC1123Pattern)
            {
                dfi = invariantInfo;
            }
            else if (format == invariantInfo.UniversalSortableDateTimePattern)
            {
                dfi = invariantInfo;
            }
            int i = 0;

            while (i < format.Length)
            {
                bool flag = false;
                char c    = format[i];
                char c2   = c;
                int  num;
                switch (c2)
                {
                case 'd':
                    num = DateTimeUtils.CountRepeat(format, i, c);
                    if (num <= 2)
                    {
                        DateTimeUtils.ZeroPad(stringBuilder, dfi.Calendar.GetDayOfMonth(dt), (num != 1) ? 2 : 1);
                    }
                    else if (num == 3)
                    {
                        stringBuilder.Append(dfi.GetAbbreviatedDayName(dfi.Calendar.GetDayOfWeek(dt)));
                    }
                    else
                    {
                        stringBuilder.Append(dfi.GetDayName(dfi.Calendar.GetDayOfWeek(dt)));
                    }
                    break;

                default:
                    switch (c2)
                    {
                    case 'F':
                        flag = true;
                        goto IL_1E3;

                    default:
                        switch (c2)
                        {
                        case 's':
                            num = DateTimeUtils.CountRepeat(format, i, c);
                            DateTimeUtils.ZeroPad(stringBuilder, dt.Second, (num != 1) ? 2 : 1);
                            break;

                        case 't':
                        {
                            num = DateTimeUtils.CountRepeat(format, i, c);
                            string text = (dt.Hour >= 12) ? dfi.PMDesignator : dfi.AMDesignator;
                            if (num == 1)
                            {
                                if (text.Length >= 1)
                                {
                                    stringBuilder.Append(text[0]);
                                }
                            }
                            else
                            {
                                stringBuilder.Append(text);
                            }
                            break;
                        }

                        default:
                            switch (c2)
                            {
                            case '"':
                            case '\'':
                                num = DateTimeUtils.ParseQuotedString(format, i, stringBuilder);
                                break;

                            default:
                                if (c2 != '/')
                                {
                                    if (c2 != ':')
                                    {
                                        if (c2 != '\\')
                                        {
                                            stringBuilder.Append(c);
                                            num = 1;
                                        }
                                        else
                                        {
                                            if (i >= format.Length - 1)
                                            {
                                                throw new FormatException("\\ at end of date time string");
                                            }
                                            stringBuilder.Append(format[i + 1]);
                                            num = 2;
                                        }
                                    }
                                    else
                                    {
                                        stringBuilder.Append(dfi.TimeSeparator);
                                        num = 1;
                                    }
                                }
                                else
                                {
                                    stringBuilder.Append(dfi.DateSeparator);
                                    num = 1;
                                }
                                break;

                            case '%':
                                if (i >= format.Length - 1)
                                {
                                    throw new FormatException("% at end of date time string");
                                }
                                if (format[i + 1] == '%')
                                {
                                    throw new FormatException("%% in date string");
                                }
                                num = 1;
                                break;
                            }
                            break;

                        case 'y':
                            num = DateTimeUtils.CountRepeat(format, i, c);
                            if (num <= 2)
                            {
                                DateTimeUtils.ZeroPad(stringBuilder, dfi.Calendar.GetYear(dt) % 100, num);
                            }
                            else
                            {
                                DateTimeUtils.ZeroPad(stringBuilder, dfi.Calendar.GetYear(dt), num);
                            }
                            break;

                        case 'z':
                        {
                            num = DateTimeUtils.CountRepeat(format, i, c);
                            TimeSpan timeSpan = (utc_offset == null) ? TimeZone.CurrentTimeZone.GetUtcOffset(dt) : utc_offset.Value;
                            if (timeSpan.Ticks >= 0L)
                            {
                                stringBuilder.Append('+');
                            }
                            else
                            {
                                stringBuilder.Append('-');
                            }
                            int num2 = num;
                            if (num2 != 1)
                            {
                                if (num2 != 2)
                                {
                                    stringBuilder.Append(Math.Abs(timeSpan.Hours).ToString("00"));
                                    stringBuilder.Append(':');
                                    stringBuilder.Append(Math.Abs(timeSpan.Minutes).ToString("00"));
                                }
                                else
                                {
                                    stringBuilder.Append(Math.Abs(timeSpan.Hours).ToString("00"));
                                }
                            }
                            else
                            {
                                stringBuilder.Append(Math.Abs(timeSpan.Hours));
                            }
                            break;
                        }
                        }
                        break;

                    case 'H':
                        num = DateTimeUtils.CountRepeat(format, i, c);
                        DateTimeUtils.ZeroPad(stringBuilder, dt.Hour, (num != 1) ? 2 : 1);
                        break;

                    case 'K':
                        num = 1;
                        if (utc_offset != null || dt.Kind == DateTimeKind.Local)
                        {
                            TimeSpan timeSpan = (utc_offset == null) ? TimeZone.CurrentTimeZone.GetUtcOffset(dt) : utc_offset.Value;
                            if (timeSpan.Ticks >= 0L)
                            {
                                stringBuilder.Append('+');
                            }
                            else
                            {
                                stringBuilder.Append('-');
                            }
                            stringBuilder.Append(Math.Abs(timeSpan.Hours).ToString("00"));
                            stringBuilder.Append(':');
                            stringBuilder.Append(Math.Abs(timeSpan.Minutes).ToString("00"));
                        }
                        else if (dt.Kind == DateTimeKind.Utc)
                        {
                            stringBuilder.Append('Z');
                        }
                        break;

                    case 'M':
                    {
                        num = DateTimeUtils.CountRepeat(format, i, c);
                        int month = dfi.Calendar.GetMonth(dt);
                        if (num <= 2)
                        {
                            DateTimeUtils.ZeroPad(stringBuilder, month, num);
                        }
                        else if (num == 3)
                        {
                            stringBuilder.Append(dfi.GetAbbreviatedMonthName(month));
                        }
                        else
                        {
                            stringBuilder.Append(dfi.GetMonthName(month));
                        }
                        break;
                    }
                    }
                    break;

                case 'f':
                    goto IL_1E3;

                case 'g':
                    num = DateTimeUtils.CountRepeat(format, i, c);
                    stringBuilder.Append(dfi.GetEraName(dfi.Calendar.GetEra(dt)));
                    break;

                case 'h':
                {
                    num = DateTimeUtils.CountRepeat(format, i, c);
                    int num3 = dt.Hour % 12;
                    if (num3 == 0)
                    {
                        num3 = 12;
                    }
                    DateTimeUtils.ZeroPad(stringBuilder, num3, (num != 1) ? 2 : 1);
                    break;
                }

                case 'm':
                    num = DateTimeUtils.CountRepeat(format, i, c);
                    DateTimeUtils.ZeroPad(stringBuilder, dt.Minute, (num != 1) ? 2 : 1);
                    break;
                }
IL_6C6:
                i += num;
                continue;
IL_1E3:
                num = DateTimeUtils.CountRepeat(format, i, c);
                if (num > 7)
                {
                    throw new FormatException("Invalid Format String");
                }
                int num4   = (int)(dt.Ticks % 10000000L / (long)Math.Pow(10.0, (double)(7 - num)));
                int length = stringBuilder.Length;
                DateTimeUtils.ZeroPad(stringBuilder, num4, num);
                if (flag)
                {
                    while (stringBuilder.Length > length && stringBuilder[stringBuilder.Length - 1] == '0')
                    {
                        stringBuilder.Length--;
                    }
                    if (num4 == 0 && length > 0 && stringBuilder[length - 1] == '.')
                    {
                        stringBuilder.Length--;
                    }
                }
                goto IL_6C6;
            }
            return(stringBuilder.ToString());
        }
Exemple #28
0
        /// <summary>Returns a <see langword="String" /> value containing the name of the specified weekday.</summary>
        /// <param name="Weekday">Required. <see langword="Integer" />. The numeric designation for the weekday, from 1 through 7; 1 indicates the first day of the week and 7 indicates the last day of the week. The identities of the first and last days depend on the setting of <paramref name="FirstDayOfWeekValue" />.</param>
        /// <param name="Abbreviate">Optional. <see langword="Boolean" /> value that indicates if the weekday name is to be abbreviated. If omitted, the default is <see langword="False" />, which means the weekday name is not abbreviated.</param>
        /// <param name="FirstDayOfWeekValue">Optional. A value chosen from the <see langword="FirstDayOfWeek" /> enumeration that specifies the first day of the week. If not specified, <see langword="FirstDayOfWeek.System" /> is used.</param>
        /// <returns>Returns a <see langword="String" /> value containing the name of the specified weekday.</returns>
        /// <exception cref="T:System.ArgumentException">
        /// <paramref name="Weekday" /> is less than 1 or greater than 7, or <paramref name="FirstDayOfWeekValue" /> is less than 0 or greater than 7.</exception>
        public static string WeekdayName(int Weekday, bool Abbreviate = false, FirstDayOfWeek FirstDayOfWeekValue = FirstDayOfWeek.System)
        {
            if (Weekday < 1 || Weekday > 7)
            {
                throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[1]
                {
                    nameof(Weekday)
                }));
            }
            switch (FirstDayOfWeekValue)
            {
            case FirstDayOfWeek.System:
            case FirstDayOfWeek.Sunday:
            case FirstDayOfWeek.Monday:
            case FirstDayOfWeek.Tuesday:
            case FirstDayOfWeek.Wednesday:
            case FirstDayOfWeek.Thursday:
            case FirstDayOfWeek.Friday:
            case FirstDayOfWeek.Saturday:
                DateTimeFormatInfo format = (DateTimeFormatInfo)Utils.GetCultureInfo().GetFormat(typeof(DateTimeFormatInfo));
                if (FirstDayOfWeekValue == FirstDayOfWeek.System)
                {
                    FirstDayOfWeekValue = (FirstDayOfWeek)(format.FirstDayOfWeek + 1);
                }
                string str;
                try
                {
                    str = !Abbreviate?format.GetDayName((DayOfWeek)((int)(Weekday + FirstDayOfWeekValue - 2) % 7)) : format.GetAbbreviatedDayName((DayOfWeek)((int)(Weekday + FirstDayOfWeekValue - 2) % 7));
                }
                catch (StackOverflowException ex)
                {
                    throw ex;
                }
                catch (OutOfMemoryException ex)
                {
                    throw ex;
                }
                catch (ThreadAbortException ex)
                {
                    throw ex;
                }
                catch (Exception ex)
                {
                    throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[1]
                    {
                        nameof(Weekday)
                    }));
                }
                if (str.Length == 0)
                {
                    throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[1]
                    {
                        nameof(Weekday)
                    }));
                }
                return(str);

            default:
                throw new ArgumentException(Utils.GetResourceString("Argument_InvalidValue1", new string[1]
                {
                    nameof(FirstDayOfWeekValue)
                }));
            }
        }
        public void GetAbbreviatedDayName_Invalid_ThrowsArgumentOutOfRangeException(DayOfWeek dayofweek)
        {
            var format = new DateTimeFormatInfo();

            AssertExtensions.Throws <ArgumentOutOfRangeException>("dayofweek", () => format.GetAbbreviatedDayName(dayofweek));
        }
    public bool NegTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when dayofweek is not a valid System.DayOfWeek value. ");

        try
        {
            DateTimeFormatInfo info = new DateTimeFormatInfo();

            info.GetAbbreviatedDayName((DayOfWeek)(-1));

            TestLibrary.TestFramework.LogError("101.1", "ArgumentOutOfRangeException is not thrown");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException)
        {
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Exemple #31
0
        //
        // Private methods
        //
        void WriteDayHeader(HtmlTextWriter writer, bool enabled)
        {
            int    i, first;
            string dayName;

            i = first = (int)(DisplayFirstDayOfWeek);
            TableCell cell;


            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            if (SelectionMode == CalendarSelectionMode.DayWeek)
            {
                cell = new TableCell();
                cell.HorizontalAlign = HorizontalAlign.Center;
                cell.ApplyStyle(DayHeaderStyle);

                // Empty Cell
                cell.RenderBeginTag(writer);
                cell.RenderEndTag(writer);
            }
            else
            {
                if (SelectionMode == CalendarSelectionMode.DayWeekMonth)
                {
                    TableCell selector = new TableCell();
                    selector.ApplyStyle(SelectorStyle);
                    selector.HorizontalAlign = HorizontalAlign.Center;

                    DateTime date = new DateTime(DisplayDate.Year, DisplayDate.Month, 1);                      // first date
                    int      days = DateTime.DaysInMonth(DisplayDate.Year, DisplayDate.Month);

                    selector.RenderBeginTag(writer);
                    writer.Write(BuildLink("R" + GetDaysFromZenith(date) + days, SelectMonthText, DayHeaderStyle.ForeColor, enabled));
                    selector.RenderEndTag(writer);
                }
            }

            DateTimeFormatInfo dti = DateInfo;

            while (true)
            {
                DayOfWeek dayOfWeek = (DayOfWeek)i;
                dayName = dti.GetDayName(dayOfWeek);

                if (UseAccessibleHeader)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Abbr, dayName);
                    writer.AddAttribute(HtmlTextWriterAttribute.Scope, "col", false);
                    cell = new TableHeaderCell();
                }
                else
                {
                    cell = new TableCell();
                }

                cell.HorizontalAlign = HorizontalAlign.Center;
                cell.ApplyStyle(DayHeaderStyle);

                cell.RenderBeginTag(writer);

                switch (DayNameFormat)
                {
                case DayNameFormat.FirstLetter:
                    dayName = dayName.Substring(0, 1);
                    break;

                case DayNameFormat.FirstTwoLetters:
                    dayName = dayName.Substring(0, 2);
                    break;

                case DayNameFormat.Shortest:
                    dayName = dti.GetShortestDayName(dayOfWeek);
                    break;

                case DayNameFormat.Full:
                    break;

                case DayNameFormat.Short:
                default:
                    dayName = dti.GetAbbreviatedDayName(dayOfWeek);
                    break;
                }

                writer.Write(dayName);
                cell.RenderEndTag(writer);

                if (i >= daysInAWeek - 1)
                {
                    i = 0;
                }
                else
                {
                    i++;
                }

                if (i == first)
                {
                    break;
                }
            }

            writer.RenderEndTag();
        }
Exemple #32
0
        private bool Parse(City city, XPathDocument doc)
        {
            if (city == null || doc == null)
            {
                return(false);
            }
            CultureInfo        currentCulture = ServiceRegistration.Get <ILocalization>().CurrentCulture;
            DateTimeFormatInfo dateFormat     = currentCulture.DateTimeFormat;

            _isMetricRegion = new RegionInfo(currentCulture.LCID).IsMetric;

            XPathNavigator navigator = doc.CreateNavigator();
            XPathNavigator condition = navigator.SelectSingleNode("/data/current_condition");

            if (condition != null)
            {
                city.Condition.Temperature   = FormatCurrentTemp(condition);
                city.Condition.Wind          = FormatWind(condition);
                city.Condition.Humidity      = FormatHumidity(condition);
                city.Condition.Precipitation = FormatPrecip(condition);
                city.Condition.Pressure      = FormatPressure(condition);

                XPathNavigator node = condition.SelectSingleNode("weatherDesc");
                if (node != null)
                {
                    city.Condition.Condition = node.Value;
                }

                node = condition.SelectSingleNode("weatherCode");
                if (node != null)
                {
                    city.Condition.BigIcon   = @"Weather\128x128\" + GetWeatherIcon(node.ValueAsInt);
                    city.Condition.SmallIcon = @"Weather\64x64\" + GetWeatherIcon(node.ValueAsInt);
                }
            }

            XPathNodeIterator forecasts = navigator.Select("/data/weather");

            city.ForecastCollection.Clear();
            while (forecasts.MoveNext())
            {
                if (forecasts.Current == null)
                {
                    continue;
                }

                DayForecast dayForecast = new DayForecast();

                XPathNavigator node = forecasts.Current.SelectSingleNode("date");
                if (node != null)
                {
                    DateTime date = node.ValueAsDateTime;
                    string   day  = dateFormat.GetAbbreviatedDayName(date.DayOfWeek);
                    // Attention: CurrentThread.Culture / UICulture are NOT set to ILocalization.Culture, so ILocalization.Culture
                    // has to be used explicitly here for formatting date correctly.
                    string fomattedDate = date.ToString(dateFormat.ShortDatePattern, dateFormat);
                    dayForecast.Day = String.Format("{0} {1}", day, fomattedDate);
                }

                dayForecast.Low           = FormatTempLow(forecasts.Current);
                dayForecast.High          = FormatTempHigh(forecasts.Current);
                dayForecast.Precipitation = FormatPrecip(forecasts.Current);
                dayForecast.Wind          = FormatWind(forecasts.Current);

                node = forecasts.Current.SelectSingleNode("weatherCode");
                if (node != null)
                {
                    dayForecast.BigIcon   = @"Weather\128x128\" + GetWeatherIcon(node.ValueAsInt);
                    dayForecast.SmallIcon = @"Weather\64x64\" + GetWeatherIcon(node.ValueAsInt);
                }

                node = forecasts.Current.SelectSingleNode("weatherDesc");
                if (node != null)
                {
                    dayForecast.Overview = node.Value;
                }

                city.ForecastCollection.Add(dayForecast);
            }
            return(true);
        }
        public async Task <bool> GetLocationData(City city)
        {
            int cityId;

            // Other grabbers store string IDs and this would fail here
            if (city.Grabber != GetServiceName() || !int.TryParse(city.Id, out cityId))
            {
                return(false);
            }

            Tuple <City, DateTime> data;
            await _lock.WaitAsync();

            try
            {
                if (_cache.TryGetValue(cityId, out data) && DateTime.Now - data.Item2 <= MAX_CACHE_DURATION)
                {
                    city.Copy(data.Item1);
                    return(true);
                }

                await new SynchronizationContextRemover();
                var client         = new OpenWeatherMapClient(GetKey());
                var currentWeather = await client.CurrentWeather.GetByCityId(cityId, _metricSystem, _language);

                city.Condition.Temperature   = FormatTemp(currentWeather.Temperature.Value, currentWeather.Temperature.Unit);
                city.Condition.Humidity      = string.Format("{0} {1}", currentWeather.Humidity.Value, currentWeather.Humidity.Unit);
                city.Condition.Pressure      = string.Format("{0:F0} {1}", currentWeather.Pressure.Value, currentWeather.Pressure.Unit);
                city.Condition.Precipitation = string.Format("{0} {1}", currentWeather.Precipitation.Value, currentWeather.Precipitation.Unit);
                city.Condition.Wind          = string.Format("{0} {1}", currentWeather.Wind.Speed.Name, currentWeather.Wind.Direction.Name);
                city.Condition.Condition     = currentWeather.Weather.Value;
                var  now     = DateTime.Now;
                bool isNight = now >= currentWeather.City.Sun.Set || now < currentWeather.City.Sun.Rise;
                city.Condition.BigIcon   = @"Weather\128x128\" + GetWeatherIcon(currentWeather.Weather.Number, isNight);
                city.Condition.SmallIcon = @"Weather\64x64\" + GetWeatherIcon(currentWeather.Weather.Number, isNight);

                var forecasts = await client.Forecast.GetByCityId(cityId, true, _metricSystem, _language);

                foreach (var forecast in forecasts.Forecast)
                {
                    DayForecast dayForecast = new DayForecast();
                    dayForecast.High = FormatTemp(forecast.Temperature.Max, currentWeather.Temperature.Unit);
                    dayForecast.Low  = FormatTemp(forecast.Temperature.Min, currentWeather.Temperature.Unit);

                    dayForecast.Humidity = string.Format("{0} {1}", forecast.Humidity.Value, forecast.Humidity.Unit);
                    // TODO:
                    //dayForecast.Pressure = string.Format("{0} {1}", forecast.Pressure.Value, forecast.Pressure.Unit);
                    dayForecast.Precipitation = string.Format("{0} {1}", forecast.Precipitation.Value, forecast.Precipitation.Unit);
                    dayForecast.Wind          = string.Format("{0} {1}", forecast.WindSpeed.Mps, currentWeather.Wind.Direction.Name);
                    dayForecast.Overview      = forecast.Symbol.Name;
                    dayForecast.BigIcon       = @"Weather\128x128\" + GetWeatherIcon(forecast.Symbol.Number, false);
                    dayForecast.SmallIcon     = @"Weather\64x64\" + GetWeatherIcon(forecast.Symbol.Number, false);
                    string fomattedDate = forecast.Day.ToString(_dateFormat.ShortDatePattern, _dateFormat);
                    string day          = _dateFormat.GetAbbreviatedDayName(forecast.Day.DayOfWeek);
                    dayForecast.Day = String.Format("{0} {1}", day, fomattedDate);

                    city.ForecastCollection.Add(dayForecast);
                }

                city.ForecastCollection.FireChange();
                _cache[cityId] = new Tuple <City, DateTime>(city, DateTime.Now);
            }
            finally
            {
                _lock.Release();
            }
            return(true);
        }
        protected virtual void OnRenderDayHeader(HtmlTextWriter writer, DateTime visibleDate, CalendarSelectionMode selectionMode, bool buttonsActive)
        {
            writer.Write("<tr>");
            DateTimeFormatInfo currentInfo = GetDateTimeFormatter();

            if (this.HasWeekSelectors(selectionMode))
            {
                TableItemStyle style = new TableItemStyle();
                style.HorizontalAlign = HorizontalAlign.Center;
                if (selectionMode == CalendarSelectionMode.DayWeekMonth)
                {
                    int days       = visibleDate.Subtract(baseDate).Days;
                    int dayOfMonth = this.threadCalendar.GetDaysInMonth(this.threadCalendar.GetYear(visibleDate), this.threadCalendar.GetMonth(visibleDate), this.threadCalendar.GetEra(visibleDate));
                    if (this.IsMinSupportedYearMonth(visibleDate))
                    {
                        dayOfMonth = (dayOfMonth - this.threadCalendar.GetDayOfMonth(visibleDate)) + 1;
                    }
                    else if (this.IsMaxSupportedYearMonth(visibleDate))
                    {
                        dayOfMonth = this.threadCalendar.GetDayOfMonth(this.maxSupportedDate);
                    }
                    string eventArgument = "R" + (((days * 100) + dayOfMonth)).ToString(CultureInfo.InvariantCulture);
                    style.CopyFrom(this.SelectorStyle);
                    string title = null;

                    this.OnRenderCalendarCell(writer, style, this.SelectMonthText, title, buttonsActive, eventArgument);
                }
                else
                {
                    style.CopyFrom(this.DayHeaderStyle);
                    this.OnRenderCalendarCell(writer, style, string.Empty, null, false, null);
                }
            }

            TableItemStyle weekdayStyle = new TableItemStyle();

            weekdayStyle.HorizontalAlign = HorizontalAlign.Center;
            weekdayStyle.CopyFrom(this.DayHeaderStyle);

            DayNameFormat dayNameFormat = this.DayNameFormat;
            int           firstDay      = this.NumericFirstDayOfWeek();

            for (int i = firstDay; i < (firstDay + 7); i++)
            {
                string dayName;
                int    dayOfWeekNumber = i % 7;

                switch (dayNameFormat)
                {
                case DayNameFormat.Full:
                    dayName = currentInfo.GetDayName((DayOfWeek)dayOfWeekNumber);
                    break;

                case DayNameFormat.FirstLetter:
                    dayName = currentInfo.GetDayName((DayOfWeek)dayOfWeekNumber).Substring(0, 1);
                    break;

                case DayNameFormat.FirstTwoLetters:
                    dayName = currentInfo.GetDayName((DayOfWeek)dayOfWeekNumber).Substring(0, 2);
                    break;

                case DayNameFormat.Shortest:
                    dayName = currentInfo.GetShortestDayName((DayOfWeek)dayOfWeekNumber);
                    break;

                default:
                    dayName = currentInfo.GetAbbreviatedDayName((DayOfWeek)dayOfWeekNumber);
                    break;
                }

                this.OnRenderCalendarCell(writer, weekdayStyle, dayName, null, false, null);
            }
            writer.Write("</tr>");
        }