private void AssertSameValues(DateTimeFormatInfo expected, DateTimeFormatInfo value)
        {
            if (value.Equals(expected))
            {
                // same instance, we don't have to test the values 
                return;
            }

            Assert.Equal(expected.AbbreviatedDayNames, value.AbbreviatedDayNames);
            Assert.Equal(expected.AbbreviatedMonthGenitiveNames, value.AbbreviatedMonthGenitiveNames);
            Assert.Equal(expected.AbbreviatedMonthNames, value.AbbreviatedMonthNames);
            Assert.Equal(expected.DayNames, value.DayNames);
            Assert.Equal(expected.MonthGenitiveNames, value.MonthGenitiveNames);
            Assert.Equal(expected.MonthNames, value.MonthNames);
            Assert.Equal(expected.ShortestDayNames, value.ShortestDayNames);

            Assert.Equal(expected.AMDesignator, value.AMDesignator);
            Assert.Equal(expected.FullDateTimePattern, value.FullDateTimePattern);
            Assert.Equal(expected.LongDatePattern, value.LongDatePattern);
            Assert.Equal(expected.LongTimePattern, value.LongTimePattern);
            Assert.Equal(expected.MonthDayPattern, value.MonthDayPattern);
            Assert.Equal(expected.PMDesignator, value.PMDesignator);
            Assert.Equal(expected.RFC1123Pattern, value.RFC1123Pattern);
            Assert.Equal(expected.ShortDatePattern, value.ShortDatePattern);
            Assert.Equal(expected.ShortTimePattern, value.ShortTimePattern);
            Assert.Equal(expected.SortableDateTimePattern, value.SortableDateTimePattern);
            Assert.Equal(expected.UniversalSortableDateTimePattern, value.UniversalSortableDateTimePattern);
            Assert.Equal(expected.YearMonthPattern, value.YearMonthPattern);
            Assert.Equal(expected.CalendarWeekRule, value.CalendarWeekRule);
            Assert.Equal(expected.FirstDayOfWeek, value.FirstDayOfWeek);
        }
 public void AMDesignator_Set()
 {
     string newAMDesignator = "AA";
     var format = new DateTimeFormatInfo();
     format.AMDesignator = newAMDesignator;
     Assert.Equal(newAMDesignator, format.AMDesignator);
 }
 public void DayNames_Set()
 {
     string[] newDayNames = new string[] { "1", "2", "3", "4", "5", "6", "7" };
     var format = new DateTimeFormatInfo();
     format.DayNames = newDayNames;
     Assert.Equal(newDayNames, format.DayNames);
 }
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Call GetFormat to to get an valid DateTimeFormatInfo instance");

        try
        {
            DateTimeFormatInfo expected = new DateTimeFormatInfo();
            object obj = expected.GetFormat(typeof(DateTimeFormatInfo));

            if (!(obj is DateTimeFormatInfo))
            {
                TestLibrary.TestFramework.LogError("001.1", "Calling GetFormat returns a non DateTimeFormatInfo instance");
                retVal = false;
            }

            DateTimeFormatInfo actual = obj as DateTimeFormatInfo;
            if (actual != expected)
            {
                TestLibrary.TestFramework.LogError("001.2", "Calling GetFormat returns wrong instance");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
 public void GetAbbreviatedMonthName(DateTimeFormatInfo info, string[] expected)
 {
     for (int i = MinMonth; i <= MaxMonth; ++i)
     {
         Assert.Equal(expected[i], info.GetAbbreviatedMonthName(i));
     }
 }
 public void GetMonthName(DateTimeFormatInfo format, string[] expected)
 {
     for (int i = MinMonth; i <= MaxMonth; ++i)
     {
         Assert.Equal(expected[i], format.GetMonthName(i));
     }
 }
        public void Clone(DateTimeFormatInfo format)
        {
            DateTimeFormatInfo clone = (DateTimeFormatInfo)format.Clone();
            Assert.NotSame(format, clone);

            Assert.False(clone.IsReadOnly);
            Assert.Equal(format.AbbreviatedDayNames, clone.AbbreviatedDayNames);
            Assert.Equal(format.AbbreviatedMonthGenitiveNames, clone.AbbreviatedMonthGenitiveNames);
            Assert.Equal(format.AbbreviatedMonthNames, clone.AbbreviatedMonthNames);
            Assert.Equal(format.DayNames, clone.DayNames);
            Assert.Equal(format.MonthGenitiveNames, clone.MonthGenitiveNames);
            Assert.Equal(format.MonthNames, clone.MonthNames);
            Assert.Equal(format.ShortestDayNames, clone.ShortestDayNames);

            Assert.Equal(format.AMDesignator, clone.AMDesignator);
            Assert.Equal(format.FullDateTimePattern, clone.FullDateTimePattern);
            Assert.Equal(format.LongDatePattern, clone.LongDatePattern);
            Assert.Equal(format.LongTimePattern, clone.LongTimePattern);
            Assert.Equal(format.MonthDayPattern, clone.MonthDayPattern);
            Assert.Equal(format.PMDesignator, clone.PMDesignator);
            Assert.Equal(format.RFC1123Pattern, clone.RFC1123Pattern);
            Assert.Equal(format.ShortDatePattern, clone.ShortDatePattern);
            Assert.Equal(format.ShortTimePattern, clone.ShortTimePattern);
            Assert.Equal(format.SortableDateTimePattern, clone.SortableDateTimePattern);
            Assert.Equal(format.UniversalSortableDateTimePattern, clone.UniversalSortableDateTimePattern);
            Assert.Equal(format.YearMonthPattern, clone.YearMonthPattern);
            Assert.Equal(format.CalendarWeekRule, clone.CalendarWeekRule);
            Assert.Equal(format.FirstDayOfWeek, clone.FirstDayOfWeek);
        }
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Call ReadOnly on a writable DateTimeFormatInfo instance");

        try
        {
            DateTimeFormatInfo info = new DateTimeFormatInfo();
            DateTimeFormatInfo actual = DateTimeFormatInfo.ReadOnly(info);

            if (!actual.IsReadOnly)
            {
                TestLibrary.TestFramework.LogError("001.1", "Calling ReadOnly on a writable DateTimeFormatInfo instance does not make the instance read only");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
 public void AbbreviatedMonthNames_Set()
 {
     string[] newAbbreviatedMonthGenitiveNames = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "" };
     var format = new DateTimeFormatInfo();
     format.AbbreviatedMonthGenitiveNames = newAbbreviatedMonthGenitiveNames;
     Assert.Equal(newAbbreviatedMonthGenitiveNames, format.AbbreviatedMonthGenitiveNames);
 }
Example #10
0
    public static void SetFormViewParameters(IOrderedDictionary parameters, object instance)
    {
        Type ObjType = instance.GetType();
        foreach (DictionaryEntry parameter in parameters)
        {
            PropertyInfo property = ObjType.GetProperty(parameter.Key.ToString());
            if (property != null)
            {
                Type t = property.PropertyType;
                object value = null;
                     switch (t.Name)
                {
                    case "Decimal":
                        if (!string.IsNullOrEmpty(parameter.Value.ToString()))
                            value = Convert.ToDecimal(parameter.Value);
                        else
                            value = Convert.ToDecimal(0.0);
                        break;
                    case "Boolean":
                        value = Convert.ToBoolean(parameter.Value);
                        break;
                    case "DateTime":
                        String DateTimeFormat = "dd/MM/yyyy";
                        DateTimeFormatInfo info = new DateTimeFormatInfo();
                        info.ShortDatePattern = DateTimeFormat;
                        String date = Convert.ToString(parameter.Value);
                        if (!String.IsNullOrEmpty(date) || date == "null")
                            value = Convert.ToDateTime(date,info);
                        break;
                    case "Double":
                        if (!string.IsNullOrEmpty(parameter.Value.ToString()))
                            value = Convert.ToDouble(parameter.Value);
                        else
                            value = 0.0;
                        break;
                    case "Int32":
                        value = Convert.ToInt32(parameter.Value);
                        break;
                    case "Single":
                        value = Convert.ToSingle(parameter.Value);
                        break;
                    case "String":
                        value = Convert.ToString(parameter.Value);
                        break;
                    case "Guid":
                        if (!string.IsNullOrEmpty(parameter.Value.ToString()))
                            value = new Guid("11111111111111111111111111111111");
                        break;
                    default:
                        break;
                }

                property.SetValue(instance, value, null);

            }
        }
        parameters.Clear();
        parameters.Add("Values", instance);
    }
 public void NegTest1()
 {
     DateTimeFormatInfo info = new DateTimeFormatInfo();
     Assert.Throws<ArgumentOutOfRangeException>(() =>
     {
         info.GetAbbreviatedDayName((DayOfWeek)(-1));
     });
 }
Example #12
0
    public static string GetMonthName(DateTime dateValue)
    {
        DateTimeFormatInfo info = new DateTimeFormatInfo();
        string[] names;

        names = info.MonthNames;

        return names[dateValue.Month - 1];
    }
Example #13
0
 public static List<tshirt> not_expired()
 {
     DateTimeFormatInfo  format = new DateTimeFormatInfo();
     format.ShortDatePattern = "MM/dd/yyyy";
     DateTime now = Convert.ToDateTime(DateTime.Now.Date, format);
     return (from s in db.tshirts
             where s.expire_time > now
             select  s).ToList();
 }
        public void Calendar_Set()
        {
            Calendar newCalendar = new GregorianCalendar(GregorianCalendarTypes.Localized);
            var format = new DateTimeFormatInfo();
            format.Calendar = newCalendar;
            Assert.Equal(newCalendar, format.Calendar);

            format.Calendar = newCalendar;
            Assert.Equal(newCalendar, format.Calendar);
        }
        public static IEnumerable<object[]> DateTimeFormatInfo_Set_TestData()
        {
            DateTimeFormatInfo customDateTimeFormatInfo1 = new DateTimeFormatInfo();
            customDateTimeFormatInfo1.AMDesignator = "a.m.";
            customDateTimeFormatInfo1.MonthDayPattern = "MMMM-dd";
            customDateTimeFormatInfo1.ShortTimePattern = "HH|mm";
            yield return new object[] { "en-US", customDateTimeFormatInfo1 };

            DateTimeFormatInfo customDateTimeFormatInfo2 = new DateTimeFormatInfo();
            customDateTimeFormatInfo2.LongTimePattern = "H:mm:ss";
            yield return new object[] { "fi-FI", customDateTimeFormatInfo2 };
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!User.Identity.IsAuthenticated)
            Server.Transfer("Login.aspx?redirect=UserProfile.aspx");
        else
        {
            ((HtmlGenericControl)Master.FindControl("profile")).Attributes.Add("class", "current_page_item");

            if (!IsPostBack)
            {
                /*populate birth date dropdownlists*/
                //day
                Day_DropDownList.Items.Add(new ListItem("--Day--", "0"));
                for (int day = 1; day <= 31; day++)
                    Day_DropDownList.Items.Add(new ListItem(day.ToString(), day.ToString()));

                //month
                DateTimeFormatInfo dtf = new DateTimeFormatInfo();
                Month_DropDownList.Items.Add(new ListItem("--Month--", "0"));
                for (int month = 1; month <= 12; month++)
                    Month_DropDownList.Items.Add(new ListItem(dtf.GetAbbreviatedMonthName(month).ToString(), month.ToString()));

                //year
                int currYear = DateTime.Now.Year;

                Year_DropDownList.Items.Add(new ListItem("--Year--", "0"));
                for (int year = 1; year <= 50; year++)
                    Year_DropDownList.Items.Add(new ListItem((currYear - year + 1).ToString(), year.ToString()));
                /*populate birth date dropdownlists*/

                /*populate with user details if any*/
                UserExtraInfo info = DataBaseManager.GetUserExtraInfo(((Guid)(Membership.GetUser().ProviderUserKey)).ToString());
                if (info != null)
                {
                    Name_TextBox.Text = info.RealName;
                    Gender_RadioButtonList.SelectedIndex = Convert.ToInt32(info.Gender);
                    if (currYear - 50 < info.BirthDate.Year && info.BirthDate.Year <= currYear)
                    {
                        Day_DropDownList.SelectedIndex = info.BirthDate.Day;
                        Month_DropDownList.SelectedIndex = info.BirthDate.Month;
                        Year_DropDownList.SelectedIndex = currYear - info.BirthDate.Year + 1;
                    }
                    Country_TextBox.Text = info.Country;
                    City_TextBox.Text = info.City;
                    Description_TextBox.Text = info.Description;
                }
                else
                    Gender_RadioButtonList.SelectedIndex = 0;
                /*populate with user details if any*/
            }
        }
    }
 public void NativeCalendarNameTest(DateTimeFormatInfo dtfi, Calendar calendar, string nativeCalendarName)
 {
     try 
     {
         dtfi.Calendar = calendar;
         Assert.Equal(nativeCalendarName, dtfi.NativeCalendarName);
     }
     catch 
     {
         // Persian calendar is recently supported as one of the optional calendars for fa-IR
         Assert.True(calendar is PersianCalendar, "Exception can occur only with PersianCalendar");
     }
 }
Example #18
0
    public LocalDateTimeHelper()
    {
        PolicyLanguageCache.Instance.CurrentLanguageName = "en";
        SetCurrentLanguage();

        m_dateTimeFormatInfo = Thread.CurrentThread.CurrentCulture.DateTimeFormat;
        m_shortDate = m_dateTimeFormatInfo.ShortDatePattern;
        m_longDate = m_dateTimeFormatInfo.LongDatePattern;
        m_shortTimeFormat = m_dateTimeFormatInfo.ShortTimePattern;
        m_longTimeFormat = m_dateTimeFormatInfo.LongTimePattern;

        SetDateTimeFormat();
    }
    private bool VerificationHelper(DateTimeFormatInfo info, string expected, string errorno)
    {
        bool retval = true;

        string actual = info.UniversalSortableDateTimePattern;
        if (actual != expected)
        {
            TestLibrary.TestFramework.LogError(errorno, "Call UniversalSortableDateTimePattern returns wrong value");
            TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
            retval = false;
        }

        return retval;
    }
        public void ReadOnly(DateTimeFormatInfo format, bool originalFormatIsReadOnly)
        {
            Assert.Equal(originalFormatIsReadOnly, format.IsReadOnly);

            DateTimeFormatInfo readOnlyFormat = DateTimeFormatInfo.ReadOnly(format);
            if (originalFormatIsReadOnly) 
            {
            	Assert.Same(format, readOnlyFormat);
            }
            else 
            {
            	Assert.NotSame(format, readOnlyFormat);
            }
            Assert.True(readOnlyFormat.IsReadOnly);
        }
        public void PosTest4()
        {
            DateTimeFormatInfo info = new DateTimeFormatInfo();
            string[] expected = new string[] {
                "Sunday",
                "Monday",
                "Tuesday",
                "Wednesday",
                "Thursday",
                "Friday",
                "Saturday"
            };

            VerificationHelper(info, expected);
        }
        public void PosTest4()
        {
            DateTimeFormatInfo info = new DateTimeFormatInfo();
            string[] expected = new string[] {
                "Sun",
                "Mon",
                "Tue",
                "Wed",
                "Thu",
                "Fri",
                "Sat"
            };

            VerificationHelper(info, expected);
        }
Example #23
0
 internal CultureInfo()
 {
     mName = "en-US";
     mLCID = 0x7f;
     mParentName = mDisplayName = mEnglishName = mNativeName = "English";
     mTwoLetterISOLanguageName = "en";
     mThreeLetterISOLanguageName = "eng";
     mThreeLetterWindowsLanguageName = "ENU";
     mCultureTypes = Globalization.CultureTypes.AllCultures;
     mIETFLanguageTag = "en";
     mIsNeutralCulture = true;
     mNumberFormatInfo = NumberFormatInfo.InvariantInfo;
     mTextInfo = TextInfo.InvariantInfo;
     mDateTimeFormat = DateTimeFormatInfo.InvariantInfo;
 }
        public void Can_use_specification_validation_to_block_request()
        {
            var info = new DateTimeFormatInfo { Email = "nowhere" };

            var client = new RestClient
            {
                Authority = "http://nowhere.com",
                Info = info
            };

            var request = new RestRequest
            {
                Path = "fast"
            };

            client.Request(request);
        }
        public void Can_use_date_time_validation_to_transform_header_value()
        {
            var info = new DateTimeFormatInfo {IAmADate = DateTime.Now };

            var client = new RestClient
                             {
                                 Authority = "http://nowhere.com",
                                 Info = info
                             };

            var request = new RestRequest
                              {
                                  Path = "fast"
                              };

            client.Request(request);
        }
        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.GetDayName(values[i]);
                Assert.Equal(expected[i], actual);
            }
        }
        public void GetDayName(DateTimeFormatInfo format, 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], format.GetDayName(values[i]));
            }
        }
Example #28
0
 protected void Button_BookNow_Click(object sender, EventArgs e)
 {
     DateTimeFormatInfo dtFormat = new DateTimeFormatInfo();
     dtFormat.ShortDatePattern = "yyyy/MM/dd";
     Table_HotelReservation reservation = new Table_HotelReservation();
     reservation.Id = -1;
     reservation.CheckIn = Convert.ToDateTime(CheckIn, dtFormat);
     reservation.CheckOut = Convert.ToDateTime(CheckOut, dtFormat);
     reservation.HotelId = hotel.Id;
     reservation.RoomNum = RoomNum;
     reservation.RoomType = GridView1.SelectedRow.Cells[0].Text;
     reservation.GuestNum = GuestNum;
     reservation.Status = 0;
     reservation.Value = dbc.GetRoomByHotelIdAndRoomType(reservation.HotelId, reservation.RoomType).FullRate * reservation.RoomNum * (reservation.CheckOut - reservation.CheckIn).Days;
     //订单的用户将在下一个页面确定
     Session["Reservation"] = null;
     Session["Reservation"] = reservation;
     Response.Redirect("ConfirmOrder.aspx?hotelId=" + Request["hotelId"] + "&Address=" + Request["Address"] + "&CheckIn=" + Request["CheckIn"] + "&CheckOut=" + Request["CheckOut"] + "&RoomNum=" + Request["RoomNum"] + "&GuestNum=" + Request["GuestNum"]);
 }
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Call Clone method on a instance created from Ctor");

        try
        {
            DateTimeFormatInfo expected = new DateTimeFormatInfo();

            retVal = VerificationHelper(expected, expected.Clone(), "001.1") && retVal;
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
 public void NativeCalendarNameTest(DateTimeFormatInfo dtfi, Calendar calendar, string nativeCalendarName)
 {
     try 
     {
         dtfi.Calendar = calendar;
         Assert.Equal(nativeCalendarName, dtfi.NativeCalendarName);
     }
     catch
     {
         if (PlatformDetection.IsWindows)
         {
             // Persian calendar is recently supported as one of the optional calendars for fa-IR
             Assert.True(calendar is PersianCalendar, "Exception can occur only with PersianCalendar");
         }
         else // !PlatformDetection.IsWindows
         {                 
             Assert.True(calendar is HijriCalendar || calendar is UmAlQuraCalendar || calendar is ThaiBuddhistCalendar || 
                         calendar is HebrewCalendar || calendar is KoreanCalendar, "failed to set the calendar on DTFI");
         }
     }
 }
Example #31
0
        public override bool IsValid(string test, out string message)
        {
            message = null;
            foreach (DomainCodedValueRow codedvalueCode in this.Rows)
            {
                switch (this.FieldType)
                {
                case esriFieldType.esriFieldTypeSmallInteger:
                    short valueCode1;
                    short valueTest1;
                    bool  validCode1 = short.TryParse(codedvalueCode.Code, out valueCode1);
                    bool  validTest1 = short.TryParse(test, out valueTest1);
                    if (validCode1 && validTest1)
                    {
                        if (valueCode1 == valueTest1)
                        {
                            return(true);
                        }
                    }
                    break;

                case esriFieldType.esriFieldTypeInteger:
                    int  valueCode2;
                    int  valueTest2;
                    bool validCode2 = int.TryParse(codedvalueCode.Code, out valueCode2);
                    bool validTest2 = int.TryParse(test, out valueTest2);
                    if (validCode2 && validTest2)
                    {
                        if (valueCode2 == valueTest2)
                        {
                            return(true);
                        }
                    }
                    break;

                case esriFieldType.esriFieldTypeSingle:
                    float valueCode3;
                    float valueTest3;
                    bool  validCode3 = float.TryParse(codedvalueCode.Code, out valueCode3);
                    bool  validTest3 = float.TryParse(test, out valueTest3);
                    if (validCode3 && validTest3)
                    {
                        if (valueCode3 == valueTest3)
                        {
                            return(true);
                        }
                    }
                    break;

                case esriFieldType.esriFieldTypeDouble:
                    double valueCode4;
                    double valueTest4;
                    bool   validCode4 = double.TryParse(codedvalueCode.Code, out valueCode4);
                    bool   validTest4 = double.TryParse(test, out valueTest4);
                    if (validCode4 && validTest4)
                    {
                        if (valueCode4 == valueTest4)
                        {
                            return(true);
                        }
                    }
                    break;

                case esriFieldType.esriFieldTypeString:
                    if (codedvalueCode.Code == test)
                    {
                        return(true);
                    }
                    break;

                case esriFieldType.esriFieldTypeDate:
                    CultureInfo        cultureInfo        = CultureInfo.CurrentCulture;
                    DateTimeFormatInfo dateTimeFormatInfo = cultureInfo.DateTimeFormat;
                    DateTime           valueCode5;
                    DateTime           valueTest5;
                    bool validCode5 = DateTime.TryParseExact(codedvalueCode.Code, dateTimeFormatInfo.SortableDateTimePattern, cultureInfo, DateTimeStyles.None, out valueCode5);
                    bool validTest5 = DateTime.TryParseExact(test, dateTimeFormatInfo.SortableDateTimePattern, cultureInfo, DateTimeStyles.None, out valueTest5);
                    if (validCode5 && validTest5)
                    {
                        if (valueCode5 == valueTest5)
                        {
                            return(true);
                        }
                    }
                    break;
                }
            }

            message = string.Format("Value [{0}] not found in coded value domain [{1}]", test, this.Name);
            return(false);
        }
 public static string ToString(DateTime dt, string format, DateTimeFormatInfo dfi)
 {
     return(ToString(dt, null, format, dfi));
 }
 public static string GetStandardPattern(char format, DateTimeFormatInfo dfi, out bool useutc, out bool use_invariant)
 {
     return(GetStandardPattern(format, dfi, out useutc, out use_invariant, false));
 }
Example #34
0
        protected void ddlTipoFiltro_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtFechaInicio.Attributes["type"] != null)
                {
                    txtFechaInicio.Attributes.Remove("type");
                }
                if (txtFechaFin.Attributes["type"] != null)
                {
                    txtFechaFin.Attributes.Remove("type");
                }

                if (txtFechaInicio.Attributes["min"] != null)
                {
                    txtFechaInicio.Attributes.Remove("type");
                }
                if (txtFechaFin.Attributes["max"] != null)
                {
                    txtFechaFin.Attributes.Remove("max");
                }

                switch (ddlTipoFiltro.SelectedValue)
                {
                case "1":
                    txtFechaInicio.Attributes["type"] = "date";
                    txtFechaFin.Attributes["type"]    = "date";
                    txtFechaFin.Attributes["max"]     = DateTime.Now.ToString("yyyy-MM-dd");
                    break;

                case "2":
                    txtFechaInicio.Attributes["type"] = "week";
                    txtFechaFin.Attributes["type"]    = "week";
                    DateTimeFormatInfo dfi   = DateTimeFormatInfo.CurrentInfo;
                    DateTime           date1 = new DateTime(DateTime.Now.Year, 12, 31);
                    Calendar           cal   = dfi.Calendar;
                    ;
                    txtFechaInicio.Attributes["min"] = string.Format("{0}-W{1}", DateTime.Now.Year, "01");
                    txtFechaInicio.Attributes["max"] = string.Format("{0}-W{1}", DateTime.Now.Year, cal.GetWeekOfYear(date1, dfi.CalendarWeekRule, dfi.FirstDayOfWeek));

                    break;

                case "3":
                    txtFechaInicio.Attributes["type"] = "month";
                    txtFechaFin.Attributes["type"]    = "month";
                    txtFechaInicio.Attributes["min"]  = new DateTime(DateTime.Now.Year, 1, 1).ToString("yyyy-MM");
                    txtFechaInicio.Attributes["max"]  = new DateTime(DateTime.Now.Year, 12, 31).ToString("yyyy-MM");

                    break;

                case "4":
                    txtFechaInicio.Attributes["type"] = "number";
                    txtFechaFin.Attributes["type"]    = "number";
                    txtFechaInicio.Attributes["min"]  = "2000";
                    txtFechaInicio.Attributes["max"]  = DateTime.Now.Year.ToString();
                    txtFechaInicio.Text = DateTime.Now.AddYears(-1).Year.ToString();
                    txtFechaFin.Text    = DateTime.Now.Year.ToString();
                    break;
                }
            }
            catch (Exception ex)
            {
                if (_lstError == null)
                {
                    _lstError = new List <string>();
                }
                _lstError.Add(ex.Message);
                Alerta = _lstError;
            }
        }
Example #35
0
        void WriteTitle(HtmlTextWriter writer, bool enabled)
        {
            TableCell cellNextPrev = null;
            TableCell titleCell    = new TableCell();
            Table     tableTitle   = new Table();

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            titleCell.ColumnSpan = HasWeekSelectors(SelectionMode) ? 8 : 7;

            if (titleStyle != null && !titleStyle.IsEmpty && !titleStyle.BackColor.IsEmpty)
            {
                titleCell.BackColor = titleStyle.BackColor;
            }
            else
            {
                titleCell.BackColor = Color.Silver;
            }

            titleCell.RenderBeginTag(writer);

            // Table
            tableTitle.Width = Unit.Percentage(100);
            if (titleStyle != null && !titleStyle.IsEmpty)
            {
                tableTitle.ApplyStyle(titleStyle);
            }

            tableTitle.RenderBeginTag(writer);
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            if (ShowNextPrevMonth)               // Previous Table Data
            {
                cellNextPrev = new TableCell();
                cellNextPrev.ApplyStyle(nextPrevStyle);
                cellNextPrev.Width = Unit.Percentage(15);

                DateTime date = GetGlobalCalendar().AddMonths(DisplayDate, -1);
                date = GetGlobalCalendar().AddDays(date, -date.Day + 1);
                cellNextPrev.RenderBeginTag(writer);
                writer.Write(BuildLink("V" + GetDaysFromZenith(date), GetNextPrevFormatText(date, false), cellNextPrev.ForeColor, enabled));
                cellNextPrev.RenderEndTag(writer);
            }

            // Current Month Table Data
            {
                DateTimeFormatInfo dti = DateInfo;
                string             str;
                TableCell          cellMonth = new TableCell();
                cellMonth.Width           = Unit.Percentage(70);
                cellMonth.HorizontalAlign = HorizontalAlign.Center;

                cellMonth.RenderBeginTag(writer);

                if (TitleFormat == TitleFormat.MonthYear)
                {
                    str = DisplayDate.ToString(dti.YearMonthPattern, dti);
                }
                else
                {
                    str = dti.GetMonthName(GetGlobalCalendar().GetMonth(DisplayDate));
                }

                writer.Write(str);
                cellMonth.RenderEndTag(writer);
            }

            if (ShowNextPrevMonth)               // Next Table Data
            {
                DateTime date = GetGlobalCalendar().AddMonths(DisplayDate, +1);
                date = GetGlobalCalendar().AddDays(date, -date.Day + 1);

                cellNextPrev.HorizontalAlign = HorizontalAlign.Right;
                cellNextPrev.RenderBeginTag(writer);
                writer.Write(BuildLink("V" + GetDaysFromZenith(date), GetNextPrevFormatText(date, true), cellNextPrev.ForeColor, enabled));
                cellNextPrev.RenderEndTag(writer);
            }

            writer.RenderEndTag();
            tableTitle.RenderEndTag(writer);
            titleCell.RenderEndTag(writer);
            writer.RenderEndTag();              //tr
        }
        //
        //  FormatHebrewMonthName
        //
        //  Action: Return the Hebrew month name for the specified DateTime.
        //  Returns: The month name string for the specified DateTime.
        //  Arguments:
        //        time   the time to format
        //        month  The month is the value of HebrewCalendar.GetMonth(time).
        //        repeat Return abbreviated month name if repeat=3, or full month name if repeat=4
        //        dtfi    The DateTimeFormatInfo which uses the Hebrew calendars as its calendar.
        //  Exceptions: None.
        //

        /* Note:
         *  If DTFI is using Hebrew calendar, GetMonthName()/GetAbbreviatedMonthName() will return month names like this:
         *  1   Hebrew 1st Month
         *  2   Hebrew 2nd Month
         *  ..  ...
         *  6   Hebrew 6th Month
         *  7   Hebrew 6th Month II (used only in a leap year)
         *  8   Hebrew 7th Month
         *  9   Hebrew 8th Month
         *  10  Hebrew 9th Month
         *  11  Hebrew 10th Month
         *  12  Hebrew 11th Month
         *  13  Hebrew 12th Month
         *
         *  Therefore, if we are in a regular year, we have to increment the month name if moth is greater or eqaul to 7.
         */
        private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi)
        {
            BCLDebug.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4");
            if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time)))
            {
                // This month is in a leap year
                return(dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, (repeatCount == 3)));
            }
            // This is in a regular year.
            if (month >= 7)
            {
                month++;
            }
            if (repeatCount == 3)
            {
                return(dtfi.GetAbbreviatedMonthName(month));
            }
            return(dtfi.GetMonthName(month));
        }
Example #37
0
        private void VerificationHelper(DateTimeFormatInfo info, int era, string expected)
        {
            string actual = info.GetAbbreviatedEraName(era);

            Assert.Equal(expected, actual);
        }
        public OpenWeatherMapCatcher()
        {
            CultureInfo currentCulture = ServiceRegistration.Get <ILocalization>().CurrentCulture;

            _dateFormat   = currentCulture.DateTimeFormat;
            _metricSystem = new RegionInfo(currentCulture.Name).IsMetric ? MetricSystem.Metric : MetricSystem.Imperial;
            if (!Enum.TryParse(currentCulture.TwoLetterISOLanguageName, true, out _language))
            {
                _language = OpenWeatherMapLanguage.EN;
            }

            // Start with a random key
            _keyIndex = new Random(DateTime.Now.Millisecond).Next(KEYS.Length);
            _settings.SettingsChanged += (sender, args) => ApiToken = _settings.Settings.ApiKey;

            #region Weather code translation

            // See https://openweathermap.org/weather-conditions
            // See https://github.com/ronie/weather.openweathermap.extended/blob/master/resources/lib/utils.py#L118
            _weatherCodeTranslation[200] = 4;
            _weatherCodeTranslation[200] = 4;
            _weatherCodeTranslation[201] = 4;
            _weatherCodeTranslation[202] = 3;
            _weatherCodeTranslation[210] = 4;
            _weatherCodeTranslation[211] = 4;
            _weatherCodeTranslation[212] = 3;
            _weatherCodeTranslation[221] = 38;
            _weatherCodeTranslation[230] = 4;
            _weatherCodeTranslation[231] = 4;
            _weatherCodeTranslation[232] = 4;
            _weatherCodeTranslation[300] = 9;
            _weatherCodeTranslation[301] = 9;
            _weatherCodeTranslation[302] = 9;
            _weatherCodeTranslation[310] = 9;
            _weatherCodeTranslation[311] = 9;
            _weatherCodeTranslation[312] = 9;
            _weatherCodeTranslation[313] = 9;
            _weatherCodeTranslation[314] = 9;
            _weatherCodeTranslation[321] = 9;
            _weatherCodeTranslation[500] = 11;
            _weatherCodeTranslation[501] = 11;
            _weatherCodeTranslation[502] = 11;
            _weatherCodeTranslation[503] = 11;
            _weatherCodeTranslation[504] = 11;
            _weatherCodeTranslation[511] = 11;
            _weatherCodeTranslation[520] = 11;
            _weatherCodeTranslation[521] = 11;
            _weatherCodeTranslation[522] = 11;
            _weatherCodeTranslation[531] = 40;
            _weatherCodeTranslation[600] = 14;
            _weatherCodeTranslation[601] = 16;
            _weatherCodeTranslation[602] = 41;
            _weatherCodeTranslation[611] = 18;
            _weatherCodeTranslation[612] = 6;
            _weatherCodeTranslation[615] = 5;
            _weatherCodeTranslation[616] = 5;
            _weatherCodeTranslation[620] = 14;
            _weatherCodeTranslation[621] = 46;
            _weatherCodeTranslation[622] = 43;
            _weatherCodeTranslation[701] = 20;
            _weatherCodeTranslation[711] = 22;
            _weatherCodeTranslation[721] = 21;
            _weatherCodeTranslation[731] = 19;
            _weatherCodeTranslation[741] = 20;
            _weatherCodeTranslation[751] = 19;
            _weatherCodeTranslation[761] = 19;
            _weatherCodeTranslation[762] = 19;
            _weatherCodeTranslation[771] = 2;
            _weatherCodeTranslation[781] = 0;
            _weatherCodeTranslation[800] = 32;
            _weatherCodeTranslation[801] = 34;
            _weatherCodeTranslation[802] = 30;
            _weatherCodeTranslation[803] = 30;
            _weatherCodeTranslation[804] = 28;
            _weatherCodeTranslation[900] = 0;
            _weatherCodeTranslation[901] = 1;
            _weatherCodeTranslation[902] = 2;
            _weatherCodeTranslation[903] = 25;
            _weatherCodeTranslation[904] = 36;
            _weatherCodeTranslation[905] = 24;
            _weatherCodeTranslation[906] = 17;
            _weatherCodeTranslation[951] = 33;
            _weatherCodeTranslation[952] = 24;
            _weatherCodeTranslation[953] = 24;
            _weatherCodeTranslation[954] = 24;
            _weatherCodeTranslation[955] = 24;
            _weatherCodeTranslation[956] = 24;
            _weatherCodeTranslation[957] = 23;
            _weatherCodeTranslation[958] = 23;
            _weatherCodeTranslation[959] = 23;
            _weatherCodeTranslation[960] = 4;
            _weatherCodeTranslation[961] = 3;
            _weatherCodeTranslation[962] = 2;

            _weatherCodeTranslationNight[200] = 47;
            _weatherCodeTranslationNight[201] = 47;
            _weatherCodeTranslationNight[202] = 47;
            _weatherCodeTranslationNight[210] = 47;
            _weatherCodeTranslationNight[211] = 47;
            _weatherCodeTranslationNight[212] = 47;
            _weatherCodeTranslationNight[221] = 47;
            _weatherCodeTranslationNight[230] = 47;
            _weatherCodeTranslationNight[231] = 47;
            _weatherCodeTranslationNight[232] = 47;
            _weatherCodeTranslationNight[300] = 45;
            _weatherCodeTranslationNight[301] = 45;
            _weatherCodeTranslationNight[302] = 45;
            _weatherCodeTranslationNight[310] = 45;
            _weatherCodeTranslationNight[311] = 45;
            _weatherCodeTranslationNight[312] = 45;
            _weatherCodeTranslationNight[313] = 45;
            _weatherCodeTranslationNight[314] = 45;
            _weatherCodeTranslationNight[321] = 45;
            _weatherCodeTranslationNight[500] = 45;
            _weatherCodeTranslationNight[501] = 45;
            _weatherCodeTranslationNight[502] = 45;
            _weatherCodeTranslationNight[503] = 45;
            _weatherCodeTranslationNight[504] = 45;
            _weatherCodeTranslationNight[511] = 45;
            _weatherCodeTranslationNight[520] = 45;
            _weatherCodeTranslationNight[521] = 45;
            _weatherCodeTranslationNight[522] = 45;
            _weatherCodeTranslationNight[531] = 45;
            _weatherCodeTranslationNight[600] = 46;
            _weatherCodeTranslationNight[601] = 46;
            _weatherCodeTranslationNight[602] = 46;
            _weatherCodeTranslationNight[611] = 46;
            _weatherCodeTranslationNight[612] = 46;
            _weatherCodeTranslationNight[615] = 46;
            _weatherCodeTranslationNight[616] = 46;
            _weatherCodeTranslationNight[620] = 46;
            _weatherCodeTranslationNight[621] = 46;
            _weatherCodeTranslationNight[622] = 46;
            _weatherCodeTranslationNight[701] = 29;
            _weatherCodeTranslationNight[711] = 29;
            _weatherCodeTranslationNight[721] = 29;
            _weatherCodeTranslationNight[731] = 29;
            _weatherCodeTranslationNight[741] = 29;
            _weatherCodeTranslationNight[751] = 29;
            _weatherCodeTranslationNight[761] = 29;
            _weatherCodeTranslationNight[762] = 29;
            _weatherCodeTranslationNight[771] = 29;
            _weatherCodeTranslationNight[781] = 29;
            _weatherCodeTranslationNight[800] = 31;
            _weatherCodeTranslationNight[801] = 33;
            _weatherCodeTranslationNight[802] = 29;
            _weatherCodeTranslationNight[803] = 29;
            _weatherCodeTranslationNight[804] = 27;
            _weatherCodeTranslationNight[900] = 29;
            _weatherCodeTranslationNight[901] = 29;
            _weatherCodeTranslationNight[902] = 27;
            _weatherCodeTranslationNight[903] = 33;
            _weatherCodeTranslationNight[904] = 31;
            _weatherCodeTranslationNight[905] = 27;
            _weatherCodeTranslationNight[906] = 45;
            _weatherCodeTranslationNight[951] = 31;
            _weatherCodeTranslationNight[952] = 31;
            _weatherCodeTranslationNight[953] = 33;
            _weatherCodeTranslationNight[954] = 33;
            _weatherCodeTranslationNight[955] = 29;
            _weatherCodeTranslationNight[956] = 29;
            _weatherCodeTranslationNight[957] = 29;
            _weatherCodeTranslationNight[958] = 27;
            _weatherCodeTranslationNight[959] = 27;
            _weatherCodeTranslationNight[960] = 27;
            _weatherCodeTranslationNight[961] = 45;
            _weatherCodeTranslationNight[962] = 45;

            #endregion
        }
Example #39
0
        private void button2_Click(object sender, EventArgs e)
        {
            string ID = this.maskedTextBox3.Text;

            if (ID == "")
            {
                MessageBox.Show("请填写证件号码");
                return;
            }
            string Name = this.maskedTextBox1.Text;

            if (Name == "")
            {
                MessageBox.Show("请填写姓名");
                return;
            }
            string Phone = this.maskedTextBox2.Text;

            if (Phone == "")
            {
                MessageBox.Show("请填写手机号码");
                return;
            }
            string Gender = "";

            if (this.radioButton1.Checked)
            {
                Gender = "男";
            }
            else if (this.radioButton2.Checked)
            {
                Gender = "女";
            }
            else
            {
                MessageBox.Show("请填写性别");
                return;
            }

            /*
             * 短日期ShortDate
             * 输入字符串"1998-04-13"
             * 输出短日期1998-04-13
             * 对应SQL的数据类型Date
             */
            string birth = this.maskedTextBox4.Text;

            if (birth == "")
            {
                MessageBox.Show("请填写出生日期");
                return;
            }

            /*
             * 数据类型转换
             * 字符串转换为DateTime短日期数据类型
             * 与SQL数据库的Date数据类型匹配存储
             */
            DateTime           dt;
            DateTimeFormatInfo dtformat = new DateTimeFormatInfo();

            dtformat.ShortDatePattern = @"yyyy-MM-dd";
            dt = Convert.ToDateTime(birth, dtformat);
            Console.WriteLine(dt.ToString("d", dtformat));

            string job = this.maskedTextBox5.Text;

            if (job == "")
            {
                MessageBox.Show("请填写职业");
                return;
            }
            string degree = this.maskedTextBox6.Text;

            if (degree == "")
            {
                MessageBox.Show("请填写学历");
                return;
            }
            string commit = string.Format("UPDATE Account SET Name='{0}',Phone='{1}', Gender='{2}', Birth='{3}', Job='{4}',Degree='{5}' where userID={6};", Name, Phone, Gender, dt, job, degree, ID);

            using (SqlConnection mySqlConnection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = commit;
                cmd.Connection  = mySqlConnection;
                try
                {
                    mySqlConnection.Open();
                    int number = cmd.ExecuteNonQuery();
                    if (number != 0)
                    {
                        if (MessageBox.Show("账户个人信息已更改", "更改信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk) == DialogResult.OK)
                        {
                            this.Close();
                        }
                    }
                    else
                    {
                        MessageBox.Show("账户个人信息更改失败", "更改信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                catch (Exception err)
                {
                    string err_str = string.Format("账户个人信息更改失败!\n\n错误:{0}", err.Message);
                    MessageBox.Show("账户个人信息更改失败", "更改信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
Example #40
0
 public void GetInstance_NotNull(IFormatProvider provider)
 {
     Assert.NotNull(DateTimeFormatInfo.GetInstance(provider));
 }
Example #41
0
        private static bool DoParse(string input,
                                    string format,
                                    bool exact,
                                    out DateTimeOffset result,
                                    DateTimeFormatInfo dfi,
                                    DateTimeStyles styles)
        {
            if ((styles & DateTimeStyles.AllowLeadingWhite) != 0)
            {
                format = format.TrimStart(null);
                input  = input.TrimStart(null);
            }

            if ((styles & DateTimeStyles.AllowTrailingWhite) != 0)
            {
                format = format.TrimEnd(null);
                input  = input.TrimEnd(null);
            }

            bool allow_white_spaces = false;

            if ((styles & DateTimeStyles.AllowInnerWhite) != 0)
            {
                allow_white_spaces = true;
            }

            bool useutc = false, use_invariants = false;

            if (format.Length == 1)
            {
                format = DateTimeUtils.GetStandardPattern(format[0], dfi, out useutc, out use_invariants, true);
            }

            int      year         = -1;
            int      month        = -1;
            int      day          = -1;
            int      partial_hour = -1;        // for 'hh tt' formats
            int      hour         = -1;
            int      minute       = -1;
            int      second       = -1;
            double   fraction     = -1;
            int      temp_int     = -1;
            TimeSpan offset       = TimeSpan.MinValue;

            result = DateTimeOffset.MinValue;

            int fi = 0;             //format iterator
            int ii = 0;             //input iterator

            while (fi < format.Length)
            {
                int  tokLen;
                char ch = format [fi];

                switch (ch)
                {
                case 'd':
                    tokLen = DateTimeUtils.CountRepeat(format, fi, ch);
                    if (day != -1 || tokLen > 4)
                    {
                        return(false);
                    }

                    if (tokLen <= 2)
                    {
                        ii += ParseNumber(input, ii, 2, tokLen == 2, allow_white_spaces, out day);
                    }
                    else
                    {
                        ii += ParseEnum(input, ii, tokLen == 3 ? dfi.AbbreviatedDayNames : dfi.DayNames, allow_white_spaces, out temp_int);
                    }
                    break;

                case 'f':
                    tokLen = DateTimeUtils.CountRepeat(format, fi, ch);
                    ii    += ParseNumber(input, ii, tokLen, true, allow_white_spaces, out temp_int);
                    if (fraction >= 0 || tokLen > 7 || temp_int == -1)
                    {
                        return(false);
                    }
                    fraction = (double)temp_int / Math.Pow(10, tokLen);
                    break;

                case 'F':
                    tokLen = DateTimeUtils.CountRepeat(format, fi, ch);
                    int digits;
                    int read = ParseNumber(input, ii, tokLen, true, allow_white_spaces, out temp_int, out digits);
                    if (temp_int == -1)
                    {
                        ii += ParseNumber(input, ii, digits, true, allow_white_spaces, out temp_int);
                    }
                    else
                    {
                        ii += read;
                    }
                    if (fraction >= 0 || tokLen > 7 || temp_int == -1)
                    {
                        return(false);
                    }
                    fraction = (double)temp_int / Math.Pow(10, digits);
                    break;

                case 'h':
                    tokLen = DateTimeUtils.CountRepeat(format, fi, ch);
                    if (hour != -1 || tokLen > 2)
                    {
                        return(false);
                    }

                    ii += ParseNumber(input, ii, 2, tokLen == 2, allow_white_spaces, out temp_int);
                    if (temp_int == -1)
                    {
                        return(false);
                    }

                    if (partial_hour == -1)
                    {
                        partial_hour = temp_int;
                    }
                    else
                    {
                        hour = partial_hour + temp_int;
                    }
                    break;

                case 'H':
                    tokLen = DateTimeUtils.CountRepeat(format, fi, ch);
                    if (hour != -1 || tokLen > 2)
                    {
                        return(false);
                    }

                    ii += ParseNumber(input, ii, 2, tokLen == 2, allow_white_spaces, out hour);
                    break;

                case 'm':
                    tokLen = DateTimeUtils.CountRepeat(format, fi, ch);
                    if (minute != -1 || tokLen > 2)
                    {
                        return(false);
                    }

                    ii += ParseNumber(input, ii, 2, tokLen == 2, allow_white_spaces, out minute);
                    break;

                case 'M':
                    tokLen = DateTimeUtils.CountRepeat(format, fi, ch);
                    if (month != -1 || tokLen > 4)
                    {
                        return(false);
                    }

                    if (tokLen <= 2)
                    {
                        ii += ParseNumber(input, ii, 2, tokLen == 2, allow_white_spaces, out month);
                    }
                    else
                    {
                        ii    += ParseEnum(input, ii, tokLen == 3 ? dfi.AbbreviatedMonthNames : dfi.MonthNames, allow_white_spaces, out month);
                        month += 1;
                    }

                    break;

                case 's':
                    tokLen = DateTimeUtils.CountRepeat(format, fi, ch);
                    if (second != -1 || tokLen > 2)
                    {
                        return(false);
                    }
                    ii += ParseNumber(input, ii, 2, tokLen == 2, allow_white_spaces, out second);
                    break;

                case 't':
                    tokLen = DateTimeUtils.CountRepeat(format, fi, ch);
                    if (hour != -1 || tokLen > 2)
                    {
                        return(false);
                    }

                    ii += ParseEnum(input, ii,
                                    tokLen == 1 ? new string[] { new string (dfi.AMDesignator[0], 1), new string (dfi.PMDesignator[0], 0) }
                                                                     : new string[] { dfi.AMDesignator, dfi.PMDesignator },
                                    allow_white_spaces, out temp_int);
                    if (temp_int == -1)
                    {
                        return(false);
                    }

                    if (partial_hour == -1)
                    {
                        partial_hour = temp_int * 12;
                    }
                    else
                    {
                        hour = partial_hour + temp_int * 12;
                    }
                    break;

                case 'y':
                    if (year != -1)
                    {
                        return(false);
                    }

                    tokLen = DateTimeUtils.CountRepeat(format, fi, ch);
                    if (tokLen <= 2)
                    {
                        ii += ParseNumber(input, ii, 2, tokLen == 2, allow_white_spaces, out year);
                        if (year != -1)
                        {
                            year += DateTime.Now.Year - DateTime.Now.Year % 100;
                        }
                    }
                    else if (tokLen <= 4)                         // yyy and yyyy accept up to 5 digits with leading 0
                    {
                        int digit_parsed;
                        ii += ParseNumber(input, ii, 5, false, allow_white_spaces, out year, out digit_parsed);
                        if (digit_parsed < tokLen || (digit_parsed > tokLen && (year / Math.Pow(10, digit_parsed - 1) < 1)))
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        ii += ParseNumber(input, ii, tokLen, true, allow_white_spaces, out year);
                    }
                    break;

                case 'z':
                    tokLen = DateTimeUtils.CountRepeat(format, fi, ch);
                    if (offset != TimeSpan.MinValue || tokLen > 3)
                    {
                        return(false);
                    }

                    int off_h, off_m = 0, sign;
                    temp_int = 0;
                    ii      += ParseEnum(input, ii, new string [] { "-", "+" }, allow_white_spaces, out sign);
                    ii      += ParseNumber(input, ii, 2, tokLen != 1, false, out off_h);
                    if (tokLen == 3)
                    {
                        ii += ParseEnum(input, ii, new string [] { dfi.TimeSeparator }, false, out temp_int);
                        ii += ParseNumber(input, ii, 2, true, false, out off_m);
                    }
                    if (off_h == -1 || off_m == -1 || sign == -1)
                    {
                        return(false);
                    }

                    if (sign == 0)
                    {
                        sign = -1;
                    }
                    offset = new TimeSpan(sign * off_h, sign * off_m, 0);
                    break;

                case ':':
                    tokLen = 1;
                    ii    += ParseEnum(input, ii, new string [] { dfi.TimeSeparator }, false, out temp_int);
                    if (temp_int == -1)
                    {
                        return(false);
                    }
                    break;

                case '/':
                    tokLen = 1;
                    ii    += ParseEnum(input, ii, new string [] { dfi.DateSeparator }, false, out temp_int);
                    if (temp_int == -1)
                    {
                        return(false);
                    }
                    break;

                case '%':
                    tokLen = 1;
                    if (fi != 0)
                    {
                        return(false);
                    }
                    break;

                case ' ':
                    tokLen = 1;
                    ii    += ParseChar(input, ii, ' ', false, out temp_int);
                    if (temp_int == -1)
                    {
                        return(false);
                    }
                    break;

                case '\\':
                    tokLen = 2;
                    ii    += ParseChar(input, ii, format [fi + 1], allow_white_spaces, out temp_int);
                    if (temp_int == -1)
                    {
                        return(false);
                    }
                    break;

                default:
                    //Console.WriteLine ("un-parsed character: {0}", ch);
                    tokLen = 1;
                    ii    += ParseChar(input, ii, format [fi], allow_white_spaces, out temp_int);
                    if (temp_int == -1)
                    {
                        return(false);
                    }
                    break;
                }
                fi += tokLen;
            }

            //Console.WriteLine ("{0}-{1}-{2} {3}:{4} {5}", year, month, day, hour, minute, offset);
            if (offset == TimeSpan.MinValue && (styles & DateTimeStyles.AssumeLocal) != 0)
            {
                offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
            }

            if (offset == TimeSpan.MinValue && (styles & DateTimeStyles.AssumeUniversal) != 0)
            {
                offset = TimeSpan.Zero;
            }

            if (hour < 0)
            {
                hour = 0;
            }
            if (minute < 0)
            {
                minute = 0;
            }
            if (second < 0)
            {
                second = 0;
            }
            if (fraction < 0)
            {
                fraction = 0;
            }
            if (year > 0 && month > 0 && day > 0)
            {
                result = new DateTimeOffset(year, month, day, hour, minute, second, 0, offset);
                result = result.AddSeconds(fraction);
                if ((styles & DateTimeStyles.AdjustToUniversal) != 0)
                {
                    result = result.ToUniversalTime();
                }
                return(true);
            }

            return(false);
        }
        /// <summary>
        /// Initialize Editing Control, control type is AIDataGridViewDateTimePickerEditingControl.
        /// </summary>
        /// <param name="rowIndex"></param>
        /// <param name="initialFormattedValue"></param>
        /// <param name="dataGridViewCellStyle"></param>
        public override void InitializeEditingControl(int rowIndex, object
                                                      initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            // Set the value of the editing control to the current cell value.
            try
            {
                base.InitializeEditingControl(rowIndex,
                                              initialFormattedValue,
                                              dataGridViewCellStyle);

                string typeOfValue = string.Empty;
                IType  type        = this.Tag as IType;
                if (type == null || type.IsNullable)
                {
                    type =
                        this.DataGridView.Rows[rowIndex].Cells[Constants.QUERY_GRID_FIELDTYPE_DISPLAY_HIDDEN].Value as
                        IType;
                }
                if (type.IsNullable)
                {
                    typeOfValue = CommonValues.GetSimpleNameForNullable(type.FullName);
                }
                else
                {
                    typeOfValue = type.DisplayName;
                }
                // }

                if (typeOfValue == typeof(System.DateTime).ToString() ||
                    (type != null && type.IsSameAs(typeof(DateTime))))
                {
                    dbDataGridViewDateTimePickerEditingControl ctl =
                        DataGridView.EditingControl as dbDataGridViewDateTimePickerEditingControl;

                    if (this.Value != null && this.Value != this.OwningColumn.DefaultCellStyle)
                    {
                        try
                        {
                            DateTimeFormatInfo dateTimeFormatterProvider = DateTimeFormatInfo.CurrentInfo.Clone() as DateTimeFormatInfo;
                            dateTimeFormatterProvider.ShortDatePattern = "MM/dd/yyyy hh:mm:ss tt";
                            DateTime dateTime = DateTime.Parse(Value.ToString(), dateTimeFormatterProvider);
                            ctl.Value = dateTime;
                        }
                        catch (Exception ex)
                        {
                            ex.ToString();
                            ctl.Value = System.DateTime.Now;
                        }
                    }
                }
                else if (typeOfValue == typeof(System.Boolean).ToString() ||
                         (type != null && type.IsSameAs(typeof(Boolean))))
                {
                    //intializing editing control (DataGridViewComboBoxEditingControl)
                    DataGridViewComboBoxEditingControl ctl =
                        this.DataGridView.EditingControl as DataGridViewComboBoxEditingControl;

                    //setting combox style
                    ctl.DropDownStyle = ComboBoxStyle.DropDownList;
                    ctl.FlatStyle     = FlatStyle.Popup;
                    FillBoolColumnValue(ctl);

                    if (this.Value != null && this.Value != this.OwningColumn.DefaultCellStyle)
                    {
                        try
                        {
                            ctl.EditingControlFormattedValue = this.Value.ToString();
                        }
                        catch (Exception ex)
                        {
                            ex.ToString();
                            ctl.SelectedItem = ctl.Items[0].ToString();
                        }
                    }
                    ctl.Width = this.OwningColumn.Width;
                }
            }
            catch (Exception oEx)
            {
                string str = oEx.Message;
            }
        }
Example #43
0
        public static int GetWeekOfYear(this DateTime date, IFormatProvider provider = null)
        {
            DateTimeFormatInfo format = DateTimeFormatInfo.GetInstance(provider ?? CultureInfo.InvariantCulture);

            return(format.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, format.FirstDayOfWeek));
        }
Example #44
0
        public static void GenerateForToday(SQLiteConnection db, ObservableCollection <WordMap> words)
        {
            if (words.Count == 0)
            {
                return;
            }
            DateTimeFormatInfo
                dtfi = CultureInfo.CreateSpecificCulture("en-GB").DateTimeFormat;

            dtfi.ShortDatePattern = @"dd-MM-yyyy";
            DateTime
                now = DateTime.Now;
            string
                filename = now.ToString("d", dtfi);
            M3UHandler
                m3u = new M3UHandler(db, filename, "./Playlists");

            if (m3u.Done)
            {
                return;
            }
            // Get the start of the week (about midnight on sunday).
//            DateTime
//                startOfWeek = now.AddDays(-(int)now.DayOfWeek - now.TimeOfDay.TotalDays);
//            // Get all the words older than this cutoff (so that we aren't
//            // including newly added words just yet (actually, why not).
            IOrderedEnumerable <WordMap>
            ws = words.OrderByDescending(x => x.Added);
            // The newest 50 words twice.
            // The second oldest 50 words once.
            List <WordMap>
            olderWords;

            foreach (WordMap w in Concatenate(ws.Take(50), ws.Take(50), ws.Skip(50).Take(50)).ToList())
            {
                Console.WriteLine("Adding: " + w.Id + " = " + w.Meaning);
                m3u.AddFile("../Clips/" + w.Id + "_English_Russian.mp3");
                m3u.AddFile("../Clips/" + w.Id + "_Russian_English.mp3");
            }
            // A random 15 of the third oldest 50 words.
            olderWords = ws.Skip(100).Take(50).ToList();
            if (olderWords.Count != 0)
            {
                for (int i = 0; i != 15; ++i)
                {
                    WordMap
                        w = GetRandom(olderWords);
                    Console.WriteLine("Adding: " + w.Id + " = " + w.Meaning);
                    m3u.AddFile("../Clips/" + w.Id + "_English_Russian.mp3");
                    m3u.AddFile("../Clips/" + w.Id + "_Russian_English.mp3");
                }
            }
            // A random 15 of all the older words.
            olderWords = ws.Skip(150).ToList();
            if (olderWords.Count != 0)
            {
                for (int i = 0; i != 15; ++i)
                {
                    WordMap
                        w = GetRandom(olderWords);
                    Console.WriteLine("Adding: " + w.Id + " = " + w.Meaning);
                    m3u.AddFile("../Clips/" + w.Id + "_English_Russian.mp3");
                    m3u.AddFile("../Clips/" + w.Id + "_Russian_English.mp3");
                }
            }
            // A random 20 of all the words.
            if (olderWords.Count != 0)
            {
                for (int i = 0; i != 20; ++i)
                {
                    WordMap
                        w = GetRandom(words);
                    Console.WriteLine("Adding: " + w.Id + " = " + w.Meaning);
                    m3u.AddFile("../Clips/" + w.Id + "_English_Russian.mp3");
                    m3u.AddFile("../Clips/" + w.Id + "_Russian_English.mp3");
                }
            }
            m3u.Dispose();
        }
Example #45
0
        public void Render(string eventType, DateTime startDateTime, DateTime endDateTime, IEnumerable <Event> events, IDictionary <string, int> weightedTags, IDictionary <string, int> weightedPeople, IEnumerable <string> importantSentences)
        {
            var sb = new StringBuilder(events.Count() * 250);

            if (!eventType.Equals("Summary"))
            {
                sb.AppendLine("<h1>Work Summary - " + HtmlEscape(eventType) + "</h1>");
            }
            else
            {
                sb.AppendLine("<h1>Work Summary - " + startDateTime.ToShortDateString() + " to " + endDateTime.ToShortDateString() + "</h1>");

                var ts = endDateTime - startDateTime;

                var g = from e in events
                        group e by e.EventType
                        into grp
                        select new
                {
                    key      = grp.Key,
                    count    = grp.Count(),
                    avgDays  = grp.Count() / ts.TotalDays,
                    avgHours = grp.Count() / (ts.TotalHours * 0.33d),
                    hours    = grp.Sum(s => s.Duration.Hours)
                };

                DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
                Calendar           cal = dfi.Calendar;

                var g1 = from e in events
                         group e by new
                {
                    type  = e.EventType,
                    month = e.Date.Month
                }
                into grp
                    select new
                {
                    type       = grp.Key.type,
                    month      = grp.Key.month,
                    monthCount = grp.Count()
                };

                var g2 = from e in events
                         group e by new
                {
                    type = e.EventType,
                    week = cal.GetWeekOfYear(e.Date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek)
                }
                into grp
                    select new
                {
                    type      = grp.Key.type,
                    week      = grp.Key.week,
                    weekCount = grp.Count()
                };

                var g3 = from e in events
                         group e by new
                {
                    type = e.EventType,
                    day  = e.Date.Date
                }
                into grp
                    select new
                {
                    type     = grp.Key.type,
                    day      = grp.Key.day,
                    dayCount = grp.Count()
                };



                //sb.AppendLine("<table id=\"overall_summary\" data-role=\"table\"><thead><tr><th>Event Type</th><th>Count</th><th>Total Hours<th><th>Avg / Day</th><th>Avg / Hour</th></tr></thead><tbody>");
                //foreach (var r in g.OrderByDescending(ks=>ks.count))
                //{
                //    sb.AppendLine("<tr><td>" + r.key + "</td><td>" + r.count + "</td><td>" + r.hours + "</td><td>" + r.avgDays + "</td><td>" + r.avgHours + "</td></tr>");
                //}
                //sb.AppendLine("</tbody></table>");

                foreach (var r in g)
                {
                    sb.AppendLine("<div class=\"container\">");

                    sb.AppendLine("<div class=\"meetings-attended\">");
                    sb.AppendLine("<span>" + r.count + "</span>");
                    sb.AppendLine("<h2>" + DetermineHeader(r.key) + "</h2>");
                    sb.AppendLine("</div>");

                    sb.AppendLine("<div class=\"hours\">");
                    sb.AppendLine("<span>" + Math.Round(r.avgDays, 1) + "</span>");
                    sb.AppendLine("<p>" + DetermineHeader(r.key) + "<br /> per day (on average)</p>");
                    sb.AppendLine("</div>");

                    sb.AppendLine("<div class=\"hours\">");
                    sb.AppendLine("<span>" + Math.Round(r.avgHours, 1) + "</span>");
                    sb.AppendLine("<p>" + DetermineHeader(r.key) + "<br /> per hour (on average)</p>");
                    sb.AppendLine("</div>");

                    sb.Append("</div>");
                }
            }

            if (weightedPeople != null)
            {
                sb.AppendLine("<h2>Connections</h2>");
                BuildTagCloud(sb, weightedPeople);
            }

            if (weightedTags != null)
            {
                sb.AppendLine("<h2>Frequent words</h2>");
                BuildTagCloud(sb, weightedTags);
            }

            if (importantSentences != null)
            {
                sb.AppendLine("<h2>Important events</h2>");
                sb.AppendLine("<ul id=\"important_events\">");
                foreach (var sentence in importantSentences)
                {
                    sb.AppendLine("<li>" + HtmlEscape(sentence) + "</li>");
                }
                sb.AppendLine("</ul>");
            }
            if (events != null)
            {
                sb.AppendLine("<h2>Events</h2>");
                foreach (var evnt in events)
                {
                    BuildEventHtml(sb, evnt);
                }
            }

            /* Boilerplate has 5 areas
             * 0: Title
             * 1: CSS
             * 2: JS (blocking JS)
             * 3: Your Content
             * 4: Your other JS
             */
            var htmlBoilerplate = LoadResource("boilerplate2.html");
            var cssNormalize    = LoadResource("normalize.css");
            var cssMain         = LoadResource("main.css");
            var cssTagCloud     = BuildTagCloudCss();
            var jsMain          = LoadResource("main.js");
            var jsOther         = BuildOtherJs(weightedTags);

            var htmlFinal = string.Format(
                CultureInfo.InvariantCulture,
                htmlBoilerplate,
                HtmlEscape(eventType),
                cssNormalize + cssMain + cssTagCloud,
                string.Empty,
                sb,
                jsMain + jsOther);

            string fileName = string.Format("WorkSummarizer_{0}.html", eventType);

            fileName = Path.Combine(m_settings[HtmlRenderSettingConstants.OutputDirectory].Value, fileName);
            File.WriteAllText(fileName, htmlFinal);
            Process.Start(fileName);
        }
Example #46
0
        /// <summary>
        /// 收款作废
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BarButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int      rowHandle = gridView1.FocusedRowHandle;
            DateTime dt_fa200;                 //收费日期



            if (rowHandle >= 0)
            {
                //只能作废当日收费记录
                DateTimeFormatInfo dtFormat = new DateTimeFormatInfo();
                dtFormat.ShortDatePattern = "yyyy-MM-dd";
                dt_fa200 = Convert.ToDateTime(gridView1.GetRowCellValue(rowHandle, "FA200").ToString(), dtFormat);
                if (String.Compare(dt_fa200.ToString("yyyy-MM-dd"), MiscAction.GetServerDateString()) < 0 && Envior.cur_userId != AppInfo.ROOTID)
                {
                    MessageBox.Show("只能作废当天的收费记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (MessageBox.Show("确认要作废吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return;
                }
                string s_rc001 = gridView1.GetRowCellValue(rowHandle, "AC001").ToString();
                if (Convert.ToDecimal(gridView1.GetRowCellValue(rowHandle, "FA004")) < 0)
                {
                    MessageBox.Show("退费业务不能作废!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (gridView1.GetRowCellValue(rowHandle, "FA002").ToString() == "2")                  //寄存业务
                {
                    decimal count = (decimal)SqlAssist.ExecuteScalar("select count(*) from v_rc04 where rc001='" + s_rc001 + "'", null);
                    if (count <= 1)
                    {
                        if (MessageBox.Show("此记录是唯一一次交费记录,作废此记录将删除寄存登记信息,是否继续?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                        {
                            return;
                        }
                    }
                }

                string s_fa001   = gridView1.GetRowCellValue(rowHandle, "FA001").ToString();
                string s_fa005   = gridView1.GetRowCellValue(rowHandle, "FA005").ToString();                 //电子发票号
                string s_retCode = string.Empty;

                int re = MiscAction.FinanceRemove(s_fa001, Envior.cur_userId);
                if (re > 0)
                {
                    ////////// 发票作废 ///////////////////////////////////////////////////
                    if (!string.IsNullOrEmpty(s_fa005))
                    {
                        if (!Envior.TAX_READY)
                        {
                            MessageBox.Show("金税卡没有打开!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                        else
                        {
                            s_retCode = PrtServAction.InvoiceRemoved(s_fa001, Envior.mform.Handle.ToInt32());
                        }
                    }
                    ///////////////////////////////////////////////////////////////////////

                    if (!string.IsNullOrEmpty(s_fa005) && s_retCode == "6011")
                    {
                        MessageBox.Show("作废成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else if (!string.IsNullOrEmpty(s_fa005) && s_retCode != "6011")
                    {
                        MessageBox.Show("作废成功但未作废发票!" + s_retCode, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    else
                    {
                        MessageBox.Show("作废成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }


                    //MessageBox.Show("作废成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    dt_finance.Rows.RemoveAt(gridView1.GetDataSourceRowIndex(rowHandle));
                    if (gridView1.RowCount == 0)
                    {
                        dt_detail.Rows.Clear();
                    }
                    else
                    {
                        this.RetrieveDetail(gridView1.FocusedRowHandle);
                    }
                    return;
                }
            }
        }
        public void PMDesignator_SetNullValue_ThrowsArgumentNullException()
        {
            var format = new DateTimeFormatInfo();

            AssertExtensions.Throws <ArgumentNullException>("value", () => format.PMDesignator = null);
        }
Example #48
0
        public static String ToMonthString(this DateTime dateTime, [NotNull] DateTimeFormatInfo formatInfo)
        {
            formatInfo.ThrowIfNull(nameof(formatInfo));

            return(dateTime.ToString("MMMM", formatInfo));
        }
        /// <summary>
        /// This method is useful if metadata values are already obtained and a
        /// comparison is needed. The method compares val1 against val2.
        /// If the types don't match, then the type of val1 is
        /// used to determine the semantics of val2, and an attempt
        /// to cast val2 into the same type of val1 is made. This is useful
        /// when val1 is a uri/number and val2 is a string.
        /// </summary>
        /// <param name="val1">a value of some type</param>
        /// <param name="val2">another value of the same type, or a string that can be cast into the type of val1</param>
        /// <param name="ignoreCase">indicates if we should ignore the case for text-related comparisons</param>
        /// <returns>a comparison result: 0, 1, -1</returns>
        public static int CompareTagValues(object val1, object val2, bool ignoreCase)
        {
            string type1 = val1.GetType().ToString();
            string type2 = val2.GetType().ToString();

            object v1 = val1;
            object v2 = val2;

            if (type1 != type2)
            {
                // If the data types for the two objects don't match
                // I do my best to convert the second object
                // into a data type of the first object.
                string strval2 = val2.ToString();
                switch (type1)
                {
                case "System.Char":
                    v2 = strval2[0];
                    break;

                case "System.String":
                    v2 = strval2;
                    break;

                case "System.Boolean":
                    if ((strval2 == "0") || (strval2 == "no"))
                    {
                        v2 = false;
                    }
                    else if ((strval2 == "1") || (strval2 == "yes"))
                    {
                        v2 = true;
                    }
                    else
                    {
                        try
                        {
                            v2 = bool.Parse(strval2);
                        }
                        catch
                        {
                            v2 = strval2;
                        }
                    }
                    break;

                case "System.Uri":
                    //Uri is an exception - we'll always compare as a string.
                    v2 = strval2;
                    break;

                case "System.Byte":
                    v2 = byte.Parse(strval2);
                    break;

                case "System.UInt16":
                    v2 = UInt16.Parse(strval2);
                    break;

                case "System.UInt32":
                    v2 = UInt32.Parse(strval2);
                    break;

                case "System.Int32":
                    v2 = Int32.Parse(strval2);
                    break;

                case "System.Int16":
                    v2 = Int16.Parse(strval2);
                    break;

                case "System.SByte":
                    v2 = sbyte.Parse(strval2);
                    break;

                case "System.Single":
                    v2 = Single.Parse(strval2);
                    break;

                case "System.Double":
                    v2 = Double.Parse(strval2);
                    break;

                case "System.DateTime":
                    DateTimeFormatInfo formatInfo = PropertyDateTime.GetFormatInfo();
                    v2 = DateTime.Parse(strval2, formatInfo);
                    break;

                default:
                    throw new Exception("Cannot recast object of " + type2 + " into object of " + type1);
                }
            }

            return(CompareObject(v1, v2, ignoreCase));
        }
Example #50
0
    private static void ListSimilarChildCultures(String name)
    {
        // Create the neutral DateTimeFormatInfo object.
        DateTimeFormatInfo dtfi = CultureInfo.GetCultureInfo(name).DateTimeFormat;

        // Retrieve all specific cultures of the neutral culture.
        CultureInfo[] cultures = Array.FindAll(CultureInfo.GetCultures(CultureTypes.SpecificCultures),
                                               culture => culture.Name.StartsWith(name + "-", StringComparison.OrdinalIgnoreCase));
        // Create an array of DateTimeFormatInfo properties
        PropertyInfo[] properties  = typeof(DateTimeFormatInfo).GetProperties(BindingFlags.Instance | BindingFlags.Public);
        bool           hasOneMatch = false;

        foreach (var ci in cultures)
        {
            bool match = true;
            // Get the DateTimeFormatInfo for a specific culture.
            DateTimeFormatInfo specificDtfi = ci.DateTimeFormat;
            // Compare the property values of the two.
            foreach (var prop in properties)
            {
                // We're not interested in the value of IsReadOnly.
                if (prop.Name == "IsReadOnly")
                {
                    continue;
                }

                // For arrays, iterate the individual elements to see if they are the same.
                if (prop.PropertyType.IsArray)
                {
                    IList nList = (IList)prop.GetValue(dtfi, null);
                    IList sList = (IList)prop.GetValue(specificDtfi, null);
                    if (nList.Count != sList.Count)
                    {
                        match = false;
                        Console.WriteLine("   Different n in {2} array for {0} and {1}", name, ci.Name, prop.Name);
                        break;
                    }

                    for (int ctr = 0; ctr < nList.Count; ctr++)
                    {
                        if (!nList[ctr].Equals(sList[ctr]))
                        {
                            match = false;
                            Console.WriteLine("   {0} value different for {1} and {2}", prop.Name, name, ci.Name);
                            break;
                        }
                    }

                    if (!match)
                    {
                        break;
                    }
                }
                // Get non-array values.
                else
                {
                    Object specificValue = prop.GetValue(specificDtfi);
                    Object neutralValue  = prop.GetValue(dtfi);

                    // Handle comparison of Calendar objects.
                    if (prop.Name == "Calendar")
                    {
                        // The cultures have a different calendar type.
                        if (specificValue.ToString() != neutralValue.ToString())
                        {
                            Console.WriteLine("   Different calendar types for {0} and {1}", name, ci.Name);
                            match = false;
                            break;
                        }

                        if (specificValue is GregorianCalendar)
                        {
                            if (((GregorianCalendar)specificValue).CalendarType != ((GregorianCalendar)neutralValue).CalendarType)
                            {
                                Console.WriteLine("   Different Gregorian calendar types for {0} and {1}", name, ci.Name);
                                match = false;
                                break;
                            }
                        }
                    }
                    else if (!specificValue.Equals(neutralValue))
                    {
                        match = false;
                        Console.WriteLine("   Different {0} values for {1} and {2}", prop.Name, name, ci.Name);
                        break;
                    }
                }
            }
            if (match)
            {
                Console.WriteLine("DateTimeFormatInfo object for '{0}' matches '{1}'",
                                  name, ci.Name);
                hasOneMatch = true;
            }
        }
        if (!hasOneMatch)
        {
            Console.WriteLine("DateTimeFormatInfo object for '{0}' --> No Match", name);
        }

        Console.WriteLine();
    }
Example #51
0
        // Retrieving info from the inventory retrieval table and then populating into the actual data table
        private static void CheckActualData()
        {
            using (SA45Team12AD context = new SA45Team12AD())
            {
                List <InventoryCatalogue> iList = context.InventoryCatalogues.ToList();

                foreach (var item in iList)
                {
                    // Specify our itemID
                    string itemID = item.ItemID;

                    // Other attrs..
                    List <InventoryRetrievalList> i = context.InventoryRetrievalLists.Where(x => x.ItemID.Equals(itemID)).ToList();
                    int totalQty = 0;

                    // Getting the present datetime
                    DateTime now = DateTime.Now;

                    // Getting the datetime for the start of last week
                    DateTime prev = DateTime.Now.AddDays(-7);

                    // Isolating only those that are relevant (with ref to their DateRetrieved)
                    foreach (var ir in i)
                    {
                        DateTime tempDate = (DateTime)ir.DateRetrieved;

                        if (tempDate > prev && tempDate < now)
                        {
                            totalQty += (int)ir.RequestedQuantity;
                        }
                    }

                    // Finding the year
                    int season = DateTime.Now.Year;

                    // Finding the week no for the year (aka our period currently)
                    DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
                    Calendar           cal = dfi.Calendar;
                    int period             = cal.GetWeekOfYear(DateTime.Now, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);


                    // Check if there are existing entries in the database
                    List <ActualData> cList = context.ActualDatas.Where(x => x.ItemID.Equals(itemID)).ToList();
                    bool anyDuplicates      = false;
                    foreach (var c in cList)
                    {
                        if (c.Season == season && c.Period == period)
                        {
                            anyDuplicates = true;
                        }
                    }
                    Console.WriteLine(period);
                    // Populating back to the database
                    if (anyDuplicates == false && totalQty != 0)
                    {
                        ActualData a = new ActualData();
                        a.ItemID       = itemID;
                        a.Season       = season;
                        a.Period       = period;
                        a.ActualDemand = totalQty;

                        context.ActualDatas.Add(a);
                    }

                    context.SaveChanges();
                }
            }
        }
Example #52
0
        public PartialViewResult GetAbsenceDataPerEMP(string FromAbsence = "", string ToAbsence = "", string userName = "")
        {
            DateTime fromParsed = DateTime.Now;
            DateTime toParse    = DateTime.Now;
            int      FromYear   = DateTime.Now.Year;
            int      ToYear     = DateTime.Now.Year;

            DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
            Calendar           cal = dfi.Calendar;

            if (FromAbsence != "" && ToAbsence != "")
            {
                fromParsed = DateTime.ParseExact(FromAbsence, "dd.MM.yyyy", null); // check this
                toParse    = DateTime.ParseExact(ToAbsence, "dd.MM.yyyy", null);   // --------^
                FromYear   = fromParsed.Year;
                ToYear     = toParse.Year;
            }
            else
            {
                return(PartialView("~/Views/WTR/GetWTRDataEmpty.cshtml"));
            }

            Employee employee = repository.Employees.Where(e => e.EID == userName).FirstOrDefault();

            if (employee == null)
            {
                return(PartialView("NoData"));
            }

            AbsenceViewModelForEMP absenceData = new AbsenceViewModelForEMP {
                ID = employee.EID, FirstName = employee.FirstName, LastName = employee.LastName, FactorDetails = new Dictionary <CalendarItemType, List <AbsenceFactorData> >()
            };

            List <AbsenceFactorData> sicknessList        = new List <AbsenceFactorData>();
            List <AbsenceFactorData> paidVacationList    = new List <AbsenceFactorData>();
            List <AbsenceFactorData> unpaidVacationList  = new List <AbsenceFactorData>();
            List <AbsenceFactorData> overtimeList        = new List <AbsenceFactorData>();
            List <AbsenceFactorData> paidOvertimeList    = new List <AbsenceFactorData>();
            List <AbsenceFactorData> privateOvertimeList = new List <AbsenceFactorData>();
            List <AbsenceFactorData> journeyList         = new List <AbsenceFactorData>();

            if (employee.Sicknesses.Count != 0)
            {
                foreach (Sickness sick in employee.Sicknesses)
                {
                    if (sick.From >= fromParsed && sick.To <= toParse)
                    {
                        AbsenceFactorData data = new AbsenceFactorData();
                        data.AbsenceFactorDataID = sick.SickID;
                        data.From = sick.From;
                        data.To   = sick.To;

                        sicknessList.Add(data);
                    }
                }
            }

            if (employee.Vacations.Count != 0)
            {
                foreach (Vacation vacation in employee.Vacations.OrderBy(d => d.From))
                {
                    if (vacation.From >= fromParsed && vacation.To <= toParse)
                    {
                        switch (vacation.Type)
                        {
                        case VacationType.PaidVacation:
                            AbsenceFactorData data = new AbsenceFactorData();
                            data.AbsenceFactorDataID = vacation.VacationID;
                            data.From = vacation.From;
                            data.To   = vacation.To;

                            paidVacationList.Add(data);
                            break;

                        case VacationType.UnpaidVacation:
                            AbsenceFactorData dataUnpaid = new AbsenceFactorData();
                            dataUnpaid.AbsenceFactorDataID = vacation.VacationID;
                            dataUnpaid.From = vacation.From;
                            dataUnpaid.To   = vacation.To;

                            unpaidVacationList.Add(dataUnpaid);
                            break;
                        }
                    }
                }
            }

            if (employee.Overtimes.Count != 0)
            {
                List <Overtime> overtimeDaysOffTrue = employee.Overtimes.Where(d => d.DayOff == true).OrderBy(d => d.Date).ToList();
                foreach (Overtime overtime in overtimeDaysOffTrue)
                {
                    if (overtime.Date >= fromParsed && overtime.Date <= toParse)
                    {
                        switch (overtime.Type)
                        {
                        //case OvertimeType.Overtime:
                        //    AbsenceFactorData overtimeData = new AbsenceFactorData();
                        //    overtimeData.AbsenceFactorDataID = overtime.OvertimeID;
                        //    overtimeData.From = overtime.Date;
                        //    overtimeData.To = overtime.Date;
                        //    overtimeData.ReclaimDate = overtime.ReclaimDate;

                        //    overtimeList.Add(overtimeData);
                        //    break;

                        case OvertimeType.Paid:
                            AbsenceFactorData paidOvertime = new AbsenceFactorData();
                            paidOvertime.AbsenceFactorDataID = overtime.OvertimeID;
                            paidOvertime.From        = overtime.Date;
                            paidOvertime.To          = overtime.Date;
                            paidOvertime.ReclaimDate = overtime.ReclaimDate;

                            paidOvertimeList.Add(paidOvertime);
                            if (overtime.ReclaimDate != null && overtime.ReclaimDate != DateTime.MinValue)
                            {
                                AbsenceFactorData overtimeData = new AbsenceFactorData();
                                overtimeData.AbsenceFactorDataID = overtime.OvertimeID;
                                overtimeData.From        = overtime.ReclaimDate.Value;
                                overtimeData.To          = overtime.ReclaimDate.Value;
                                overtimeData.ReclaimDate = overtime.Date;

                                overtimeList.Add(overtimeData);
                            }
                            break;

                        case OvertimeType.Private:
                            AbsenceFactorData privateOvertime = new AbsenceFactorData();
                            privateOvertime.AbsenceFactorDataID = overtime.OvertimeID;
                            privateOvertime.From        = overtime.Date;
                            privateOvertime.To          = overtime.Date;
                            privateOvertime.ReclaimDate = overtime.ReclaimDate;

                            privateOvertimeList.Add(privateOvertime);
                            break;
                        }
                    }
                }
            }

            if (employee.BusinessTrips.Count != 0)
            {
                List <Journey> employeeJourneys = (from bts in repository.BusinessTrips
                                                   where bts.EmployeeID == employee.EmployeeID
                                                   from j in bts.Journeys
                                                   where j.BusinessTripID == bts.BusinessTripID && j.DayOff == true
                                                   orderby j.Date
                                                   select j).ToList();

                if (employeeJourneys.Count != 0)
                {
                    foreach (Journey journey in employeeJourneys)
                    {
                        if (journey.Date >= fromParsed && journey.Date <= toParse)
                        {
                            AbsenceFactorData journeyData = new AbsenceFactorData();
                            journeyData.AbsenceFactorDataID = journey.JourneyID;
                            journeyData.From        = journey.Date;
                            journeyData.To          = journey.Date;
                            journeyData.ReclaimDate = journey.ReclaimDate;

                            journeyList.Add(journeyData);
                            if (journey.ReclaimDate != null && journey.ReclaimDate != DateTime.MinValue && journey.DayOff == true)
                            {
                                AbsenceFactorData overtimeData = new AbsenceFactorData();
                                overtimeData.AbsenceFactorDataID = journey.JourneyID;
                                overtimeData.From        = journey.ReclaimDate.Value;
                                overtimeData.To          = journey.ReclaimDate.Value;
                                overtimeData.ReclaimDate = journey.Date;

                                overtimeList.Add(overtimeData);
                            }
                        }
                    }
                }
            }


            absenceData.FactorDetails.Add(CalendarItemType.SickAbsence, sicknessList);
            absenceData.FactorDetails.Add(CalendarItemType.PaidVacation, paidVacationList);
            absenceData.FactorDetails.Add(CalendarItemType.UnpaidVacation, unpaidVacationList);
            absenceData.FactorDetails.Add(CalendarItemType.ReclaimedOvertime, overtimeList);
            absenceData.FactorDetails.Add(CalendarItemType.OvertimeForReclaim, paidOvertimeList);
            absenceData.FactorDetails.Add(CalendarItemType.PrivateMinus, privateOvertimeList);
            absenceData.FactorDetails.Add(CalendarItemType.Journey, journeyList);


            if (sicknessList.Count == 0 && paidVacationList.Count == 0 && unpaidVacationList.Count == 0 &&
                overtimeList.Count == 0 && paidVacationList.Count == 0 && privateOvertimeList.Capacity == 0 &
                journeyList.Count == 0)
            {
                return(PartialView("NoAbsenceData"));
            }

            ViewBag.FromWeek = cal.GetWeekOfYear(fromParsed, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
            ViewBag.ToWeek   = cal.GetWeekOfYear(toParse, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
            ViewBag.FromYear = FromYear;
            ViewBag.ToYear   = ToYear;

            return(PartialView("GetAbsenceDataPerEMP", absenceData));
        }
Example #53
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();
        }
Example #54
0
        private static string GetStandardPattern(char format, DateTimeFormatInfo dfi, out bool useUtc, out bool useInvariant)
        {
            String pattern;

            useUtc       = false;
            useInvariant = false;

            switch (format)
            {
            case 'd':
                pattern = dfi.ShortDatePattern;
                break;

            case 'D':
                pattern = dfi.LongDatePattern;
                break;

            case 'f':
                pattern = dfi.LongDatePattern + " " + dfi.ShortTimePattern;
                break;

            case 'F':
                pattern = dfi.FullDateTimePattern;
                break;

            case 'g':
                pattern = dfi.ShortDatePattern + " " + dfi.ShortTimePattern;
                break;

            case 'G':
                pattern = dfi.ShortDatePattern + " " + dfi.LongTimePattern;
                break;

            case 'm':
            case 'M':
                pattern = dfi.MonthDayPattern;
                break;

#if NET_2_0
            case 'o':
                pattern = dfi.RoundtripPattern;
                break;
#endif
            case 'r':
            case 'R':
                pattern = dfi.RFC1123Pattern;
                // commented by LP 09/jun/2002, rfc 1123 pattern is always in GMT
                // uncommented by AE 27/may/2004
                //              useutc = true;
                useInvariant = true;
                break;

            case 's':
                pattern = dfi.SortableDateTimePattern;
                break;

            case 't':
                pattern = dfi.ShortTimePattern;
                break;

            case 'T':
                pattern = dfi.LongTimePattern;
                break;

            case 'u':
                pattern = dfi.UniversalSortableDateTimePattern;
                useUtc  = true;
                break;

            case 'U':
                //              pattern = dfi.LongDatePattern + " " + dfi.LongTimePattern;
                pattern = dfi.FullDateTimePattern;
                useUtc  = true;
                break;

            case 'y':
            case 'Y':
                pattern = dfi.YearMonthPattern;
                break;

            default:
                pattern = null;
                break;
                //              throw new FormatException (String.Format ("Invalid format pattern: '{0}'", format));
            }

            return(pattern);
        }
        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);

            int  i = 0;
            bool saw_day_specifier = false;

            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)));
                    }

                    saw_day_specifier = true;
                    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
                    {
                        // Handles MMMM dd format
                        if (!saw_day_specifier)
                        {
                            for (int ii = i + 1; ii < format.Length; ++ii)
                            {
                                ch = format[ii];
                                if (ch == 'd')
                                {
                                    saw_day_specifier = true;
                                    break;
                                }

                                if (ch == '\'' || ch == '"')
                                {
                                    ii += ParseQuotedString(format, ii, null) - 1;
                                }
                            }
                        }

                        // NOTE: .NET ignores quoted 'd' and reads it as day specifier but I think
                        // that's wrong
#if NETCF
                        result.Append(/*saw_day_specifier ? dfi.GetMonthGenitiveName (month) :*/ dfi.GetMonthName(month));
#else
                        result.Append(saw_day_specifier ? dfi.GetMonthGenitiveName(month) : dfi.GetMonthName(month));
#endif
                    }

                    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 = 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());
        }
Example #56
0
        private string ToString2(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 = CountRepeat(format, i, ch);

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

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

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

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

                case 's':
                    // second [0, 29]
                    tokLen = CountRepeat(format, i, ch);
                    ZeroPad(result, this.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 = CountRepeat(format, i, ch);
                    if (tokLen > 7)
                    {
                        throw new FormatException("Invalid Format String");
                    }

                    int dec      = (int)((long)(this.Ticks % TimeSpan.TicksPerSecond) / (long)Math.Pow(10, 7 - tokLen));
                    int startLen = result.Length;
                    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 = CountRepeat(format, i, ch);
                    string desig = this.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 = CountRepeat(format, i, ch);
                    throw new NotImplementedException("TimeZone not supported");

                /*TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(this);
                 *
                 * 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;
                    switch (kind)
                    {
                    case DateTimeKind.Utc:
                        result.Append('Z');
                        break;

                    case DateTimeKind.Local:
                        throw new NotImplementedException("TimeZone not supported");

                        /*offset = TimeZone.CurrentTimeZone.GetUtcOffset (this);
                         * 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"));
                         * break;*/
                    }
                    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 = CountRepeat(format, i, ch);

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

                    break;

                case 'M':
                    // Month.m(m?) = month # (with leading 0 if two mm)
                    // mmm = 3 letter name
                    // mmmm+ = full name
                    tokLen = CountRepeat(format, i, ch);
                    int month = dfi.Calendar.GetMonth(this);
                    if (tokLen <= 2)
                    {
                        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, if yyy and yr < 1000, displayed as three digits
                    tokLen = CountRepeat(format, i, ch);

                    if (tokLen <= 2)
                    {
                        ZeroPad(result, dfi.Calendar.GetYear(this) % 100, tokLen);
                    }
                    else
                    {
                        ZeroPad(result, dfi.Calendar.GetYear(this), (tokLen == 3 ? 3 : 4));
                    }

                    break;

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

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

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

                case '\'':
                case '"':
                    tokLen = 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());
        }
        public static string GetStandardPattern(char format, DateTimeFormatInfo dfi, out bool useutc, out bool use_invariant, bool date_time_offset)
        {
            String pattern;

            useutc        = false;
            use_invariant = false;

            switch (format)
            {
            case 'd':
                pattern = dfi.ShortDatePattern;
                break;

            case 'D':
                pattern = dfi.LongDatePattern;
                break;

            case 'f':
                pattern = dfi.LongDatePattern + " " + dfi.ShortTimePattern;
                break;

            case 'F':
                pattern = dfi.FullDateTimePattern;
                break;

            case 'g':
                pattern = dfi.ShortDatePattern + " " + dfi.ShortTimePattern;
                break;

            case 'G':
                pattern = dfi.ShortDatePattern + " " + dfi.LongTimePattern;
                break;

            case 'm':
            case 'M':
                pattern = dfi.MonthDayPattern;
                break;

#if !NETCF
            case 'o':
            case 'O':
                pattern       = dfi.RoundtripPattern;
                use_invariant = true;
                break;
#endif
            case 'r':
            case 'R':
                pattern = dfi.RFC1123Pattern;
                if (date_time_offset)
                {
                    useutc = true;
                }
                use_invariant = true;
                break;

            case 's':
                pattern       = dfi.SortableDateTimePattern;
                use_invariant = true;
                break;

            case 't':
                pattern = dfi.ShortTimePattern;
                break;

            case 'T':
                pattern = dfi.LongTimePattern;
                break;

            case 'u':
                pattern = dfi.UniversalSortableDateTimePattern;
                if (date_time_offset)
                {
                    useutc = true;
                }
                use_invariant = true;
                break;

            case 'U':
                if (date_time_offset)
                {
                    pattern = null;
                }
                else
                {
                    //					pattern = dfi.LongDatePattern + " " + dfi.LongTimePattern;
                    pattern = dfi.FullDateTimePattern;
                    useutc  = true;
                }
                break;

            case 'y':
            case 'Y':
                pattern = dfi.YearMonthPattern;
                break;

            default:
                pattern = null;
                break;
                //				throw new FormatException (String.Format ("Invalid format pattern: '{0}'", format));
            }

            return(pattern);
        }
        private void FormatInitializer()
        {
            var adminInfo = Company.GetCompanyService().GetAdminInfo();

            #region NumberFormatInfo

            NumberFormatInfo = new NumberFormatInfo
            {
                NumberDecimalSeparator = adminInfo.DecimalSeparator,
                NumberGroupSeparator   = adminInfo.ThousandsSeparator,
            };

            #endregion

            #region DateTimeFormatInfo

            string dateFormatPattern;

            switch (adminInfo.DateTemplate)
            {
            case BoDateTemplate.dt_DDMMYY:
                dateFormatPattern = "dd{0}MM{0}yy";
                break;

            case BoDateTemplate.dt_DDMMCCYY:
                dateFormatPattern = "dd{0}MM{0}yyyy";
                break;

            case BoDateTemplate.dt_MMDDYY:
                dateFormatPattern = "MM{0}dd{0}yy";
                break;

            case BoDateTemplate.dt_MMDDCCYY:
                dateFormatPattern = "MM{0}dd{0}yyyy";
                break;

            case BoDateTemplate.dt_CCYYMMDD:
                dateFormatPattern = "yyyy{0}MM{0}dd";
                break;

            case BoDateTemplate.dt_DDMonthYYYY:
                dateFormatPattern = "dd{0}MMMM{0}yyyy";
                break;

            default:                     // Desconhecido
                throw new InvalidOperationException("Formato de data identificado não é conhecido (AdminInfo.DateTemplate).");
            }

            var datePattern = String.Format(dateFormatPattern, adminInfo.DateSeparator);
            var timePattern = adminInfo.TimeTemplate == BoTimeTemplate.tt_24H ? "HH:mm" : "hh:mm";

            var newDateTimeFormat = (DateTimeFormatInfo)DateTimeFormatInfo.Clone();

            newDateTimeFormat.DateSeparator    = adminInfo.DateSeparator;
            newDateTimeFormat.LongDatePattern  = datePattern;
            newDateTimeFormat.ShortDatePattern = datePattern;
            newDateTimeFormat.LongTimePattern  = timePattern;
            newDateTimeFormat.ShortTimePattern = timePattern;

            DateTimeFormatInfo = newDateTimeFormat;

            #endregion
        }
Example #59
0
 public String ToString(String format, IFormatProvider formatProvider)
 {
     Contract.Ensures(Contract.Result <String>() != null);
     return(DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset));
 }
        /// <summary>
        /// Background task entrypoint. Voice Commands using the <VoiceCommandService Target="...">
        /// tag will invoke this when they are recognized by Cortana, passing along details of the
        /// invocation.
        ///
        /// Background tasks must respond to activation by Cortana within 0.5 seconds, and must
        /// report progress to Cortana every 5 seconds (unless Cortana is waiting for user
        /// input). There is no execution time limit on the background task managed by Cortana,
        /// but developers should use plmdebug (https://msdn.microsoft.com/en-us/library/windows/hardware/jj680085%28v=vs.85%29.aspx)
        /// on the Cortana app package in order to prevent Cortana timing out the task during
        /// debugging.
        ///
        /// Cortana dismisses its UI if it loses focus. This will cause it to terminate the background
        /// task, even if the background task is being debugged. Use of Remote Debugging is recommended
        /// in order to debug background task behaviors. In order to debug background tasks, open the
        /// project properties for the app package (not the background task project), and enable
        /// Debug -> "Do not launch, but debug my code when it starts". Alternatively, add a long
        /// initial progress screen, and attach to the background task process while it executes.
        /// </summary>
        /// <param name="taskInstance">Connection to the hosting background service process.</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();

            // Register to receive an event if Cortana dismisses the background task. This will
            // occur if the task takes too long to respond, or if Cortana's UI is dismissed.
            // Any pending operations should be cancelled or waited on to clean up where possible.
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            // Load localized resources for strings sent to Cortana to be displayed to the user.
            cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");

            // Select the system language, which is what Cortana should be running as.
            cortanaContext = ResourceContext.GetForViewIndependentUse();

            // Get the currently used system date format
            dateFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat;

            // This should match the uap:AppService and VoiceCommandService references from the
            // package manifest and VCD files, respectively. Make sure we've been launched by
            // a Cortana Voice Command.
            if (triggerDetails != null && triggerDetails.Name == "BandOnTheRunVoiceCommandService")
            {
                try
                {
                    voiceServiceConnection =
                        VoiceCommandServiceConnection.FromAppServiceTriggerDetails(
                            triggerDetails);

                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                    VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage();

                    // Depending on the operation (defined in AdventureWorks:AdventureWorksCommands.xml)
                    // perform the appropriate command.
                    switch (voiceCommand.CommandName)
                    {
                    case "showbandinformation":
                        //hardcoded - needs to be hooked into real data flow.
                        userMessage.DisplayMessage = "Band 1 \n" +
                                                     "status: connected\n" +
                                                     "Motion: Jogging\n" +
                                                     "Speed: 10kph\n" +
                                                     "Skin Temp: 37\n" +
                                                     "UV: medium";
                        userMessage.SpokenMessage = "Showing band information";
                        ;
                        var response = VoiceCommandResponse.CreateResponse(userMessage);
                        await voiceServiceConnection.ReportSuccessAsync(response);

                        break;

                    default:

                        break;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
                finally
                {
                    if (this.serviceDeferral != null)
                    {
                        this.serviceDeferral.Complete();
                    }
                }
            }
        }