private void btnImportCSV_AdminValuesDefault_Click(object sender, EventArgs e) { int days = (m_admin.m_curDate.Date - HDateTime.ToMoscowTimeZone(DateTime.Now).Date).Days; if (days < 0) { string strMsg = string.Format(@"Выбрана дата ретроспективных данных: {0}.", m_admin.m_curDate.Date.ToString(@"dd.MM.yyyy")); MessageBox.Show(this, strMsg, @"Внимание", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { OpenFileDialog files = new OpenFileDialog(); files.Multiselect = false; //files.InitialDirectory = Environment.GetFolderPath (Environment.SpecialFolder.Desktop); files.InitialDirectory = AdminTS_KomDisp.Folder_CSV; files.DefaultExt = @"csv"; files.Filter = @"Рекомендации-по-умолчанию (AdminValuesDefault)|AdminValuesDefault*.csv"; files.Title = "Выберите файл с рекомендациями по умолчанию..."; int iRes = -1; if (files.ShowDialog(FormMain.formParameters) == DialogResult.OK) { if (days > 0) { iRes = 0; } else { if (days == 0) { string strMsg = string.Format(@"Рекомендации по умолчанию будут загружены на текущие сутки: {0}.{1}Продолжить?", m_admin.m_curDate.Date.ToString(@"dd.MM.yyyy"), Environment.NewLine); if (MessageBox.Show(this, strMsg, @"Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { iRes = 0; } else { ; //По-прежнему ошибка... } } else { ; } } if (iRes == 0) { ((AdminTS_KomDisp)m_admin).ImpCSVValues(mcldrDate.SelectionStart, files.FileName); } else { ; } } else { } } }
/// <summary> /// /// </summary> /// <param name="tableOrigin"></param> /// <param name="tableRes"></param> /// <param name="err"></param> private void saveResult(DataTable tableOrigin, DataTable tableRes, out int err) { err = -1; DataTable tableEdit = new DataTable(); DataRow[] rowSel = null; tableEdit = tableOrigin.Clone(); foreach (DataRow r in tableOrigin.Rows) { rowSel = tableRes.Select(@"ID=" + r[@"ID_PUT"]); if (rowSel.Length == 1) { tableEdit.Rows.Add(new object[] { //r[@"ID"], r[@"ID_SESSION"] , r[@"ID_PUT"] , rowSel[0][@"QUALITY"] , rowSel[0][@"VALUE"] , HDateTime.ToMoscowTimeZone().ToString(CultureInfo.InvariantCulture) }); } else { ; //??? ошибка } } RecUpdateInsertDelete(s_NameDbTables[(int)INDEX_DBTABLE_NAME.OUTVALUES], @"ID_PUT", tableOrigin, tableEdit, out err); }
/// <summary> /// Load change log from a data row. /// </summary> /// <param name="dr">Data row containing the data to load.</param> /// <remarks></remarks> public ChangeLog(DataRow dr) { this.OwnerID = HString.SafeTrim(dr["owner_id"]); this.OwnerName = HString.SafeTrim(dr["owner_name"]); this.Type = HString.SafeTrim(dr["log_type"]); this.Timestamp = HDateTime.GetDateTime(dr["timestamp"]); }
public void testZinc() { TimeZoneInfo tziNewYork; try { tziNewYork = TimeZoneConverter.TZConvert.GetTimeZoneInfo("Eastern Standard Time"); } catch { // Ignore issues with locally installed timezones. return; } var tz = HTimeZone.make("New_York", false); HDateTime ts; // Ignore issues with locally installed timezones. if (tz != null) { ts = HDateTime.make(634429600180690000L, tz); verifyZinc(ts, "2011-06-06T12:26:58.069-05:00 New_York"); Assert.AreEqual(ts.date.ToString(), "2011-06-06"); Assert.AreEqual(ts.time.ToString(), "12:26:58.069"); Assert.AreEqual(ts.Offset.TotalSeconds, -5 * 60 * 60); Assert.AreEqual(ts.TimeZone.dntz, tziNewYork); Assert.AreEqual(ts.Ticks, 634429600180690000L); } // convert back to millis ts = HDateTime.make("2011-06-06T12:26:58.069-04:00 New_York", false); // Ignore issues with locally installed timezones. if (ts != null) { Assert.AreEqual(ts.Ticks, 634429600180690000L); } // different timezones ts = HDateTime.make(630850574400000000L, HTimeZone.make("New_York", false)); // Ignore issues with locally installed timezones. if (ts != null) { verifyZinc(ts, "2000-02-02T03:04:00-05:00 New_York"); } ts = HDateTime.make(630850754400000000L, HTimeZone.make("UTC", false)); // Ignore issues with locally installed timezones. if (ts != null) { verifyZinc(ts, "2000-02-02T08:04:00Z UTC"); } ts = HDateTime.make(630851042400000000L, HTimeZone.make("Taipei", false)); // Ignore issues with locally installed timezones. if (ts != null) { verifyZinc(ts, "2000-02-02T16:04:00+08:00 Taipei"); verifyZinc(HDateTime.make("2011-06-07T11:03:43-10:00 GMT+10", false), "2011-06-07T11:03:43-10:00 GMT+10"); verifyZinc(HDateTime.make("2011-06-08T04:07:33.771+07:00 GMT-7", false), "2011-06-08T04:07:33.771+07:00 GMT-7"); } }
protected virtual int GetCurrentTimeResponse(DataTable table) { if (table.Rows.Count == 1) { serverTime = ((DateTime)table.Rows[0][0]).Add(m_tsOffsetToMoscow); } else { //DaylightTime daylight = TimeZone.CurrentTimeZone.GetDaylightChanges(DateTime.Now.Year); //int timezone_offset = allTECComponents[indxTECComponents].tec.m_timezone_offset_msc; //if (TimeZone.IsDaylightSavingTime(DateTime.Now, daylight) == true) // timezone_offset++; //else // ; ////serverTime = TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now).AddHours(3); ////serverTime = TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now).AddHours(timezone_offset); //serverTime = TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now).AddHours(allTECComponents[indxTECComponents].tec.m_timezone_offset_msc); serverTime = HDateTime.ToMoscowTimeZone(); ErrorReport("Ошибка получения текущего времени сервера. Используется локальное время."); } return(0); }
protected int getPBRNumber(int hour = -1) { int iRes = -1 , iHour = hour; if (iHour < 0) { if (m_ignore_date == true) { iHour = HDateTime.ToMoscowTimeZone().Hour; } else { iHour = serverTime.Hour; } } else { ; } //// для интервала обновления ПБР = 2 ч //if ((iHour % 2) > 0) // iRes = iHour; //else iRes = iHour + 1; return(iRes); }
protected int getPBRNumber(int hour = -1) { int iRes = -1 , iHour = hour; if (iHour < 0) { if (m_ignore_date == true) { iHour = HDateTime.ToMoscowTimeZone(DateTime.Now).Hour; } else { iHour = serverTime.Hour; } } else { ; } if ((iHour % 2) > 0) { iRes = iHour; } else { iRes = iHour + 1; } return(iRes); }
public override HDict about() { return(new HDictBuilder() .add("haystackVersion", "3.0") .add("serverTime", HDateTime.now()) .add("serverBootTime", bootTime) .add("tz", HTimeZone.Default.ToString()) .toDict()); //.add(onAbout()) }
public void testCompare() { Assert.AreEqual(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).CompareTo(HDateTime.make(2011, 1, 2, 3, 4, 5, utc)), 0); Assert.IsTrue(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).CompareTo(HDateTime.make(2011, 1, 2, 3, 4, 6, utc)) < 0); Assert.IsTrue(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).CompareTo(HDateTime.make(2011, 1, 2, 3, 5, 5, utc)) < 0); Assert.IsTrue(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).CompareTo(HDateTime.make(2011, 1, 2, 4, 4, 5, utc)) < 0); Assert.IsTrue(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).CompareTo(HDateTime.make(2011, 1, 3, 3, 4, 5, utc)) < 0); Assert.IsTrue(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).CompareTo(HDateTime.make(2011, 2, 2, 3, 4, 5, utc)) < 0); Assert.IsTrue(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).CompareTo(HDateTime.make(2012, 1, 2, 3, 4, 5, utc)) < 0); Assert.IsTrue(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).CompareTo(HDateTime.make(2011, 1, 2, 3, 4, 0, utc)) > 0); }
protected void btnSubmit_Click(object sender, EventArgs e) { // Get the month the page should display. DateTime displayMonth = HDateTime.GetDateTime(HNumeric.GetSafeInteger(this.ddlYear.SelectedValue), HNumeric.GetSafeInteger(this.ddlMonth.SelectedValue), 1); // Set UI to indicate what month is being displayed. this.SetControls(displayMonth); // Output html to page. this.LoadCalendar(displayMonth); }
private bool fMaketEquipment(DataTable table, string[] listGuids, DateTime date) { bool bRes = false; Modes.BusinessLogic.IGenObject igo; IList <Modes.BusinessLogic.IMaketEquipment> listEquip; table.Columns.Add("ID", typeof(int)); table.Columns.Add("ID_INNER", typeof(int)); table.Columns.Add("WR_DATE_TIME", typeof(DateTime)); listEquip = _mcApi.GetMaket53500Equipment(Array.ConvertAll <string, Guid> (listGuids, Guid.Parse)); listEquip.ToList().ForEach(equip => { string mesDebug = string.Empty; mesDebug = $@"DbMCInterface::GetData () - equip=[{equip.Mrid}], children.Count={equip.GenTree.Count}"; equip.GenTree.ToList().ForEach(item => { mesDebug = $"{mesDebug}{Environment.NewLine}, item.IdIner ={item.IdInner}, item.GenObjType.Id={item.GenObjType.Id}, item.Name={item.Name}, item.children.Count={item.Children.Count}..."; item.Children.ToList().ForEach(child => { mesDebug = $"{mesDebug}{Environment.NewLine}, children.IdIner ={child.IdInner}, child.GenObjType.Id={child.GenObjType.Id}, child.Name={child.Name}, child.children.Count={child.Children.Count}..."; }); igo = null; //igo = findIGO (item.IdInner); //if (Equals (igo, null) == false) // if (item.GenObjType.Id == ID_GEN_OBJECT_TYPE.RGE) // m_listIGO.Add (item); // else // ; //else // ; if (Equals(igo, null) == false) { table.Rows.Add(new object [] { igo.Id, igo.IdInner, HDateTime.ToMoscowTimeZone() }); } else { ; } }); // equip.GenTree.ToList ().ForEach Logging.Logg().Debug(mesDebug, Logging.INDEX_MESSAGE.NOT_SET); }); //TODO: bRes = true; return(bRes); }
/// <summary> /// Initialize UI controls. /// </summary> private void InitControls() { // Populate "Year" dropdown. for (int i = 2000; i <= 2050; i++) { this.ddlYear.Items.Add(new ListItem(i.ToString(), i.ToString())); } // Populate "Month" dropdown. for (int j = 1; j <= 12; j++) { this.ddlMonth.Items.Add(new ListItem(HDateTime.GetMonthName(j), j.ToString())); } }
/// <summary> /// Обязательный метод для поддержки конструктора - не изменяйте /// содержимое данного метода при помощи редактора кода. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); this.m_dtprDate = new DateTimePicker(); this.m_dtprDate.Dock = DockStyle.Fill; //this.m_dtprDate.ValueChanged += new EventHandler(((PanelLastMinutes)Parent).OnDateTimeValueChanged); m_dtprDate.Value = HDateTime.ToMoscowTimeZone(DateTime.Now); this.m_dtprDate.ValueChanged += new EventHandler(OnDateTimeValueChanged); this.m_btnUpdate = new Button(); this.m_btnUpdate.Dock = DockStyle.Fill; this.m_btnUpdate.Text = @"Обнов."; this.m_btnUpdate.Click += new EventHandler(OnDateTimeValueChanged); }
/// <summary> /// Determine what month to create xml data for based on prev/next postback. /// </summary> /// <returns>The month to be displayed on the page.</returns> private DateTime SetCurrentMonth() { DateTime dt = DateTime.Now; if (Request.Form["__EVENTTARGET"] == "prev" || Request.Form["__EVENTTARGET"] == "next") { // Set postback value. dt = HDateTime.GetDateTime(Request.Form["__EVENTARGUMENT"]); // Set UI to indicate what month is being displayed. this.SetControls(dt); } return(dt); }
public void testEquality() { Assert.IsTrue(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).hequals(HDateTime.make(2011, 1, 2, 3, 4, 5, utc))); Assert.IsFalse(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).hequals(HDateTime.make(2009, 1, 2, 3, 4, 5, utc))); Assert.IsFalse(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).hequals(HDateTime.make(2011, 9, 2, 3, 4, 5, utc))); Assert.IsFalse(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).hequals(HDateTime.make(2011, 1, 9, 3, 4, 5, utc))); Assert.IsFalse(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).hequals(HDateTime.make(2011, 1, 2, 9, 4, 5, utc))); Assert.IsFalse(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).hequals(HDateTime.make(2011, 1, 2, 3, 9, 5, utc))); Assert.IsFalse(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).hequals(HDateTime.make(2011, 1, 2, 3, 4, 9, utc))); // Ignore issues with locally installed timezones. if (london != null) { Assert.IsFalse(HDateTime.make(2011, 1, 2, 3, 4, 5, utc).hequals(HDateTime.make(2011, 1, 2, 3, 4, 5, london))); } //Assert.AreNotEqual(HDateTime.make(2011, 1, 2, 3, 4, 5, utc), HDateTime.make(2011, 1, 2, 3, 4, 5, london, 3600)); }
protected override void GetPPBRValuesRequest(TEC t, TECComponent comp, DateTime date, AdminTS.TYPE_FIELDS mode) { string query = string.Empty; int i = -1; TimeSpan ts = HDateTime.GetUTCOffsetOfMoscowTimeZone(); query += @"SELECT [objName], [idFactor], [PBR_NUMBER], [Datetime], [Value_MBT] as VALUE FROM [dbo].[v_ALL_PARAM_MODES_BIYSK]" + @" WHERE [ID_Type_Data] = 3" + @" AND [objName] = '" + comp.m_listMTermId[0] + @"'" + @" AND [Datetime] > " + @"'" + date.Date.Add(-ts).ToString(@"yyyyMMdd HH:00:00.000") + @"'" + @" AND [PBR_NUMBER] > 0" + @" ORDER BY [Datetime], [PBR_NUMBER]" ; DbMCSources.Sources().Request(m_IdListenerCurrent, query); //Logging.Logg().Debug("AdminMT::GetPPBRValuesRequest (TEC, TECComponent, DateTime, AdminTS.TYPE_FIELDS) - вЫход...: query=" + query, Logging.INDEX_MESSAGE.NOT_SET); }
public void testWriter() { HGridBuilder gb = new HGridBuilder(); gb.addCol("a"); gb.addCol("b"); gb.addRow(new HVal[] { HNA.VAL, HBool.TRUE }); // Original Unit test had null - this is not valid gb.addRow(new HVal[] { HMarker.VAL, HNA.VAL }); gb.addRow(new HVal[] { HRemove.VAL, HNA.VAL }); gb.addRow(new HVal[] { HStr.make("test"), HStr.make("with:colon") }); gb.addRow(new HVal[] { HNum.make(12), HNum.make(72.3, "\u00b0F") }); gb.addRow(new HVal[] { HNum.make(double.NegativeInfinity), HNum.make(Double.NaN) }); gb.addRow(new HVal[] { HDate.make(2015, 6, 9), HTime.make(1, 2, 3) }); var tz = HTimeZone.make("UTC", true); gb.addRow(new HVal[] { HDateTime.make(634429600180690000L, tz), HUri.make("foo.txt") }); gb.addRow(new HVal[] { HRef.make("abc"), HRef.make("abc", "A B C") }); gb.addRow(new HVal[] { HBin.make("text/plain"), HCoord.make(90, -123) }); HGrid grid = gb.toGrid(); string actual = HJsonWriter.gridToString(grid); // System.out.println(actual); string[] lines = actual.Split('\n'); Assert.AreEqual(lines[0], "{"); Assert.AreEqual(lines[1], "\"meta\": {\"ver\":\"2.0\"},"); Assert.AreEqual(lines[2], "\"cols\":["); Assert.AreEqual(lines[3], "{\"name\":\"a\"},"); Assert.AreEqual(lines[4], "{\"name\":\"b\"}"); Assert.AreEqual(lines[5], "],"); Assert.AreEqual(lines[6], "\"rows\":["); Assert.AreEqual(lines[7], "{\"a\":\"z:\", \"b\":true},"); Assert.AreEqual(lines[8], "{\"a\":\"m:\", \"b\":\"z:\"},"); Assert.AreEqual(lines[9], "{\"a\":\"x:\", \"b\":\"z:\"},"); Assert.AreEqual(lines[10], "{\"a\":\"test\", \"b\":\"s:with:colon\"},"); Assert.AreEqual(lines[11], "{\"a\":\"n:12\", \"b\":\"n:72.3 \u00b0F\"},"); Assert.AreEqual(lines[12], "{\"a\":\"n:-INF\", \"b\":\"n:NaN\"},"); Assert.AreEqual(lines[13], "{\"a\":\"d:2015-06-09\", \"b\":\"h:01:02:03\"},"); Assert.AreEqual(lines[14], "{\"a\":\"t:2011-06-06T12:26:58.069Z UTC\", \"b\":\"u:foo.txt\"},"); Assert.AreEqual(lines[15], "{\"a\":\"r:abc\", \"b\":\"r:abc A B C\"},"); Assert.AreEqual(lines[16], "{\"a\":\"b:text/plain\", \"b\":\"c:90.0,-123.0\"}"); Assert.AreEqual(lines[17], "]"); Assert.AreEqual(lines[18], "}"); }
private void verifyMidnight(HDate date, string tzName, string str) { var tz = HTimeZone.make(tzName, false); // Ignore issues with locally installed timezones. if (tz == null) { return; } HDateTime ts = date.midnight(tz); Assert.AreEqual(ts.date, date); Assert.AreEqual(ts.time.Hour, 0); Assert.AreEqual(ts.time.Minute, 0); Assert.AreEqual(ts.time.Second, 0); Assert.AreEqual(ts.ToString(), str); Assert.IsTrue(ts.hequals(read(ts.toZinc()))); Assert.AreEqual(ts.Ticks, ((HDateTime)read(str)).Ticks); }
private HaystackToken dateTime(StringBuilder s) { bool bFlag1 = true; // xxx timezone if ((m_cCur < 0 || m_cPeek < 0) || ((char)m_cCur != ' ' || !char.IsUpper((char)m_cPeek))) { if (s[s.Length - 1] == 'Z') { s.Append(" UTC"); } else { err("Expecting timezone"); } bFlag1 = false; } if (bFlag1) { consume(); s.Append(' '); while (isIdPart(m_cCur)) { s.Append((char)m_cCur); consume(); } // handle GMT+xx or GMT-xx if ((m_cCur == '+' || m_cCur == '-') && s.ToString().EndsWith("GMT")) { s.Append((char)m_cCur); consume(); while (isDigit(m_cCur)) { s.Append((char)m_cCur); consume(); } } } // Java use to bubble Parse exception as err - this just accepts that the debug printing // will be done by the user of this toolkit. m_val = HDateTime.make(s.ToString(), true); return(HaystackToken.dateTime); }
public void testTicks() { HDate date = HDate.make(2014, 12, 24); HTime time = HTime.make(11, 12, 13, 456); HTimeZone newYork = HTimeZone.make("New_York", false); // Ignore issues with locally installed timezones. if (newYork == null) { return; } long utcTicks = 635550163334560000L; //635550163334560000 HDateTime a = HDateTime.make(date, time, newYork); // Not valid for us - HDateTime b = HDateTime.make(date, time, newYork, a.tzOffset); HDateTime c = HDateTime.make(utcTicks, newYork); HDateTime d = HDateTime.make("2014-12-24T11:12:13.456-05:00 New_York", false); Assert.AreEqual(a.Ticks, utcTicks); //Not Valid for us - Assert.AreEqual(b.millis(), utcTicks); Assert.AreEqual(c.Ticks, utcTicks); Assert.AreEqual(d.Ticks, utcTicks); }
private void addMessage(int id_msg, string msg, bool bSep, bool bDatetime, bool bLock) { if (m_listQueueMessage == null) { m_listQueueMessage = new List <MESSAGE> (); } else { ; } lock (m_objQueueMessage) { if (m_listQueueMessage.Count > MAXCOUNT_LISTQUEUEMESSAGE) { m_listQueueMessage.RemoveAt(0); } else { ; } m_listQueueMessage.Add(new MESSAGE((int)id_msg, HDateTime.ToMoscowTimeZone(DateTime.Now), msg, bSep, bDatetime, bLock)); } }
public void testDateTime() { HaystackToken dt = HaystackToken.dateTime; HTimeZone ny = HTimeZone.make("New_York", false); HTimeZone utc = HTimeZone.UTC; HTimeZone london = HTimeZone.make("London", false); // Ignore issues with locally installed timezones. if (ny != null) { verifyToks("2016-01-13T09:51:33-05:00 New_York", new object[] { dt, HDateTime.make(2016, 1, 13, 9, 51, 33, ny /*, tzOffset(-5, 0)*/) }); verifyToks("2016-01-13T09:51:33.353-05:00 New_York", new object[] { dt, HDateTime.make(HDate.make(2016, 1, 13), HTime.make(9, 51, 33, 353), ny /*, tzOffset(-5, 0)*/) }); } verifyToks("2010-12-18T14:11:30.924Z", new object[] { dt, HDateTime.make(HDate.make(2010, 12, 18), HTime.make(14, 11, 30, 924), utc) }); verifyToks("2010-12-18T14:11:30.924Z UTC", new object[] { dt, HDateTime.make(HDate.make(2010, 12, 18), HTime.make(14, 11, 30, 924), utc) }); // Ignore issues with locally installed timezones. if (london != null) { verifyToks("2010-12-18T14:11:30.924Z London", new object[] { dt, HDateTime.make(HDate.make(2010, 12, 18), HTime.make(14, 11, 30, 924), london) }); } // Apparently PST8PDT is not valid in java? - Not tested for windows either // verifyToks("2015-01-02T06:13:38.701-08:00 PST8PDT", new Object[] {dt, HDateTime.make(HDate.make(2015,1,2), HTime.make(6,13,38,701), HTimeZone.make("PST8PDT"), tzOffset(-8,0))}); var tz = HTimeZone.make("GMT+5", false); // Ignore issues with locally installed timezones. if (tz != null) { verifyToks("2010-03-01T23:55:00.013-05:00 GMT+5", new object[] { dt, HDateTime.make(HDate.make(2010, 3, 1), HTime.make(23, 55, 0, 13), tz /*, tzOffset(-5, 0)*/) }); } tz = HTimeZone.make("GMT-10", false); // Ignore issues with locally installed timezones. if (tz != null) { verifyToks("2010-03-01T23:55:00.013+10:00 GMT-10 ", new object[] { dt, HDateTime.make(HDate.make(2010, 3, 1), HTime.make(23, 55, 0, 13), tz /*, tzOffset(10, 0)*/) }); } }
/// <summary> /// получение временного диапазона /// для блоков 1,6 /// </summary> /// <returns>диапазон дат</returns> public DateTimeRange[] GetDateTimeRangeValuesVarExtremeBL() { DateTimeRange[] arRangesRes = null; int i = -1; bool bEndMonthBoudary = false; DateTime dtBegin = _Session.m_rangeDatetime.Begin.AddHours(-(TimeZoneInfo.Local.BaseUtcOffset + TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time").BaseUtcOffset).Hours - 2), dtEnd = _Session.m_rangeDatetime.End.AddHours(-(TimeZoneInfo.Local.BaseUtcOffset + TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time").BaseUtcOffset).Hours - 2).AddDays(1); arRangesRes = new DateTimeRange[(dtEnd.Month - dtBegin.Month) + 12 * (dtEnd.Year - dtBegin.Year) + 1]; bEndMonthBoudary = HDateTime.IsMonthBoundary(dtEnd); if (bEndMonthBoudary == false) { if (arRangesRes.Length == 1) { // самый простой вариант - один элемент в массиве - одна таблица arRangesRes[0] = new DateTimeRange(dtBegin, dtEnd); } else { // два ИЛИ более элементов в массиве - две ИЛИ болле таблиц for (i = 0; i < arRangesRes.Length; i++) { if (i == 0) { // предыдущих значений нет //arRangesRes[i] = new DateTimeRange(dtBegin, HDateTime.ToNextMonthBoundary(dtBegin)); arRangesRes[i] = new DateTimeRange(dtBegin, dtBegin.AddDays(1)); } else if (i == arRangesRes.Length - 1) { // крайний элемент массива arRangesRes[i] = new DateTimeRange(arRangesRes[i - 1].End, dtEnd); } else { // для элементов в "середине" массива arRangesRes[i] = new DateTimeRange(arRangesRes[i - 1].End, new DateTime(arRangesRes[i - 1].End.Year, arRangesRes[i - 1].End.AddMonths(1).Month, DateTime.DaysInMonth(arRangesRes[i - 1].End.Year, arRangesRes[i - 1].End.AddMonths(1).Month))); } } } } //HDateTime.ToNextMonthBoundary(arRangesRes[i - 1].End)); else if (bEndMonthBoudary == true) { // два ИЛИ более элементов в массиве - две ИЛИ болле таблиц ('diffMonth' всегда > 0) // + использование следующей за 'dtEnd' таблицы for (i = 0; i < arRangesRes.Length; i++) { if (i == 0) { // предыдущих значений нет arRangesRes[i] = new DateTimeRange(dtBegin, HDateTime.ToNextMonthBoundary(dtBegin)); } else if (i == arRangesRes.Length - 1) { // крайний элемент массива arRangesRes[i] = new DateTimeRange(arRangesRes[i - 1].End, dtEnd); } else { // для элементов в "середине" массива arRangesRes[i] = new DateTimeRange(arRangesRes[i - 1].End, HDateTime.ToNextMonthBoundary(arRangesRes[i - 1].End)); } } } else { ; } return(arRangesRes); }
/// <summary> /// Создать новую сессию для расчета /// - вставить входные данные во временную таблицу /// </summary> /// <param name="cntBasePeriod">Количество базовых периодов расчета в интервале расчета</param> /// <param name="tablePars">Таблица характеристик входных параметров</param> /// <param name="tableSessionValues">Таблица значений входных параметров</param> /// <param name="tableDefValues">Таблица значений по умолчанию входных параметров</param> /// <param name="dtRange">Диапазон даты/времени для интервала расчета</param> /// <param name="err">Идентификатор ошибки при выполнеинии функции</param> /// <param name="strErr">Строка текста сообщения при наличии ошибки</param> public virtual void CreateSession( int cntBasePeriod , DataTable tablePars , ref DataTable[] arTableValues , DateTimeRange dtRange , out int err, out string strErr) { err = 0; strErr = string.Empty; int iAVG = -1; string strQuery = string.Empty; // строки для удаления из таблицы значений "по умолчанию" // при наличии дубликатов строк в таблице с загруженными из источников с данными DataRow[] rowsSel = null; // удалить строки из таблицы со значениями "по умолчанию" foreach (DataRow rValVar in arTableValues[(int)HandlerDbTaskCalculate.INDEX_TABLE_VALUES.SESSION].Rows) { rowsSel = arTableValues[(int)HandlerDbTaskCalculate.INDEX_TABLE_VALUES.DEFAULT].Select(@"ID_PUT=" + rValVar[@"ID_PUT"]); foreach (DataRow rToRemove in rowsSel) { arTableValues[(int)HandlerDbTaskCalculate.INDEX_TABLE_VALUES.DEFAULT].Rows.Remove(rToRemove); } } // вставить строки из таблицы со значениями "по умолчанию" foreach (DataRow rValDef in arTableValues[(int)HandlerDbTaskCalculate.INDEX_TABLE_VALUES.DEFAULT].Rows) { rowsSel = tablePars.Select(@"ID=" + rValDef[@"ID_PUT"]); if (rowsSel.Length == 1) { iAVG = (Int16)rowsSel[0][@"AVG"]; arTableValues[(int)HandlerDbTaskCalculate.INDEX_TABLE_VALUES.SESSION].Rows.Add(new object[] { rValDef[@"ID_PUT"] //, HUsers.Id //ID_USER //, -1 //ID_SOURCE , _Session.m_Id //ID_SESSION , (int)HandlerDbTaskCalculate.ID_QUALITY_VALUE.DEFAULT //QUALITY , (iAVG == 0) ? cntBasePeriod * (double)rValDef[@"VALUE"] : (double)rValDef[@"VALUE"] //VALUE , HDateTime.ToMoscowTimeZone() //??? GETADTE() } ); } else { ; // по идентификатору найден не единственный параметр расчета } } if ((arTableValues[(int)HandlerDbTaskCalculate.INDEX_TABLE_VALUES.SESSION].Columns.Count > 0) && (arTableValues[(int)HandlerDbTaskCalculate.INDEX_TABLE_VALUES.SESSION].Rows.Count > 0)) { //Вставить строку с идентификатором новой сессии insertIdSession(cntBasePeriod, out err); //Вставить строки в таблицу БД со входными значениями для расчета insertInValues(arTableValues[(int)HandlerDbTaskCalculate.INDEX_TABLE_VALUES.SESSION], out err); //Вставить строки в таблицу БД со выходными значениями для расчета insertOutValues(out err); // необходимость очистки/загрузки - приведение структуры таблицы к совместимому с [inval] arTableValues[(int)HandlerDbTaskCalculate.INDEX_TABLE_VALUES.SESSION].Rows.Clear(); // получить входные для расчета значения для возможности редактирования strQuery = @"SELECT [ID_PUT], [ID_SESSION], [QUALITY], [VALUE], [WR_DATETIME]" // as [ID] + @" FROM [" + s_NameDbTables[(int)INDEX_DBTABLE_NAME.INVALUES] + @"]" + @" WHERE [ID_SESSION]=" + _Session.m_Id; arTableValues[(int)HandlerDbTaskCalculate.INDEX_TABLE_VALUES.SESSION] = Select(strQuery, out err); } else { Logging.Logg().Error(@"HandlerDbTaskCalculate::CreateSession () - отсутствуют строки для вставки ...", Logging.INDEX_MESSAGE.NOT_SET); } }
/// <summary> /// получение временного диапазона /// для всех значений /// </summary> /// <returns>диапазон дат</returns> public override DateTimeRange[] GetDateTimeRangeValuesVar() { DateTimeRange[] arRangesRes = null; int i = -1; bool bEndMonthBoudary = false; DateTime dtBegin = _Session.m_rangeDatetime.Begin.AddDays(-_Session.m_rangeDatetime.Begin.Day).AddMinutes(-1 * _Session.m_curOffsetUTC) , dtEnd = _Session.m_rangeDatetime.End.AddMinutes(-1 * _Session.m_curOffsetUTC).AddDays(0); arRangesRes = new DateTimeRange[(dtEnd.Month - dtBegin.Month) + 12 * (dtEnd.Year - dtBegin.Year) + 1]; bEndMonthBoudary = HDateTime.IsMonthBoundary(dtEnd); if (bEndMonthBoudary == false) { if (arRangesRes.Length == 1) { // самый простой вариант - один элемент в массиве - одна таблица arRangesRes[0] = new DateTimeRange(dtBegin, dtEnd); } else { // два ИЛИ более элементов в массиве - две ИЛИ болле таблиц for (i = 0; i < arRangesRes.Length; i++) { if (i == 0) { // предыдущих значений нет //arRangesRes[i] = new DateTimeRange(dtBegin, HDateTime.ToNextMonthBoundary(dtBegin)); arRangesRes[i] = new DateTimeRange(dtBegin, dtBegin.AddDays(1)); } else if (i == arRangesRes.Length - 1) { // крайний элемент массива arRangesRes[i] = new DateTimeRange(arRangesRes[i - 1].End, dtEnd); } else { // для элементов в "середине" массива arRangesRes[i] = new DateTimeRange(arRangesRes[i - 1].End, new DateTime(arRangesRes[i - 1].End.Year, arRangesRes[i - 1].End.AddMonths(1).Month, DateTime.DaysInMonth(arRangesRes[i - 1].End.Year, arRangesRes[i - 1].End.AddMonths(1).Month))); } } } } //HDateTime.ToNextMonthBoundary(arRangesRes[i - 1].End)); else if (bEndMonthBoudary == true) { // два ИЛИ более элементов в массиве - две ИЛИ болле таблиц ('diffMonth' всегда > 0) // + использование следующей за 'dtEnd' таблицы for (i = 0; i < arRangesRes.Length; i++) { if (i == 0) { // предыдущих значений нет arRangesRes[i] = new DateTimeRange(dtBegin, HDateTime.ToNextMonthBoundary(dtBegin)); } else if (i == arRangesRes.Length - 1) { // крайний элемент массива arRangesRes[i] = new DateTimeRange(arRangesRes[i - 1].End, dtEnd); } else { // для элементов в "середине" массива arRangesRes[i] = new DateTimeRange(arRangesRes[i - 1].End, HDateTime.ToNextMonthBoundary(arRangesRes[i - 1].End)); } } } else { ; } return(arRangesRes); }
public void testRange() { HTimeZone ny = HTimeZone.make("New_York", false); // Ignore issues with locally installed timezones. if (ny == null) { return; } HDate today = HDate.today(); HDate yesterday = today.minusDays(1); HDate x = HDate.make(2011, 7, 4); HDate y = HDate.make(2011, 11, 4); HDateTime xa = HDateTime.make(x, HTime.make(2, 30), ny); HDateTime xb = HDateTime.make(x, HTime.make(22, 5), ny); // this week HDate sun = today; HDate sat = today; while (sun.weekday() > DayOfWeek.Sunday) { sun = sun.minusDays(1); } while (sat.weekday() < DayOfWeek.Saturday) { sat = sat.plusDays(1); } verifyRange(HDateTimeRange.thisWeek(ny), sun, sat); // this month HDate first = today; HDate last = today; while (first.Day > 1) { first = first.minusDays(1); } while (last.Day < DateTime.DaysInMonth(today.Year, today.Month)) { last = last.plusDays(1); } verifyRange(HDateTimeRange.thisMonth(ny), first, last); // this year first = HDate.make(today.Year, 1, 1); last = HDate.make(today.Year, 12, 31); verifyRange(HDateTimeRange.thisYear(ny), first, last); // last week HDate prev = today.minusDays(7); sun = prev; sat = prev; while (sun.weekday() > DayOfWeek.Sunday) { sun = sun.minusDays(1); } while (sat.weekday() < DayOfWeek.Saturday) { sat = sat.plusDays(1); } verifyRange(HDateTimeRange.lastWeek(ny), sun, sat); // last month last = today; while (last.Month == today.Month) { last = last.minusDays(1); } first = HDate.make(last.Year, last.Month, 1); verifyRange(HDateTimeRange.lastMonth(ny), first, last); // last year first = HDate.make(today.Year - 1, 1, 1); last = HDate.make(today.Year - 1, 12, 31); verifyRange(HDateTimeRange.lastYear(ny), first, last); }
private void verifyRange(HDateTimeRange r, HDateTime start, HDateTime end) { Assert.IsTrue(r.Start.hequals(start)); Assert.IsTrue(r.End.hequals(end)); }
/// <summary> /// Выполнить операцию размещения значений в книге MS Excel /// , и в автоматическом режиме сохранить ее /// </summary> private void run(object obj) { List <FileInfo> listFileInfoDest; EventResultArgs arg; string pattern = string.Empty; int iTemplate = 0 // признак продолжения выполнения операции - наличие шаблона , err = 0; // по умолчанию ошибок нет try { #if HCLASSLIBRARY_MSEXCELIO if (IsReOpen == true) { ReCreate(); } else { ; } #else #endif // получить шаблон поиска документа pattern = string.Format("*{0}*.{1}", ConstantExportPBRValues.MaskDocument, ConstantExportPBRValues.MaskExtension); Logging.Logg().Action(string.Format("AdminTS_KomDisp.MSExcelIOExportPBRValues::Run () - поиск документа: каталог=<{0}>, шаблон=<{1}>...", Folder_CSV, pattern) , Logging.INDEX_MESSAGE.NOT_SET); listFileInfoDest = new List <FileInfo> (Directory.GetFiles(Folder_CSV, pattern, SearchOption.TopDirectoryOnly).ToList() .ConvertAll <FileInfo> (name => new FileInfo(string.Format(@"{0}", name)))); if (listFileInfoDest.Count > 1) { // выполнить сортировку, затем открыть "самый новый" файл listFileInfoDest.Sort((fileInfo1, fileInfo2) => { return((int)(fileInfo1.LastWriteTime - fileInfo2.LastWriteTime).TotalSeconds < 0 ? 1 : (int)(fileInfo1.LastWriteTime - fileInfo2.LastWriteTime).TotalSeconds > 0 ? -1 : 0); }); } else if (listFileInfoDest.Count > 0) { // файл единственный(вероятно, шаблон) - открыть iTemplate = 1; } else { // файл отсутствует - открыть шаблон iTemplate = -1; } if (!(iTemplate < 0)) { #if HCLASSLIBRARY_MSEXCELIO if (IsOpen(Path.GetFileName(listFileInfoDest [0].FullName), out err) == true) { Logging.Logg().Error(string.Format("AdminTS_KomDisp.MSExcelIOExportPBRValues::Run () - книга с наименованием={0}\\{1} открыта..." , Folder_CSV, TemplateDocument) , Logging.INDEX_MESSAGE.NOT_SET); if (Mode == MODE_EXPORT_PBRVALUES.AUTO) { Visible = !CloseExcelDoc(Path.GetFileName(listFileInfoDest [0].FullName)); } else if (Mode == MODE_EXPORT_PBRVALUES.MANUAL) { Visible = true; } else { ; } #else #endif #if HCLASSLIBRARY_MSEXCELIO } else { if (Visible == true) { Visible = false; } else { ; } } if (Visible == false) #else #endif { if (openDocument(listFileInfoDest [0].FullName) == 0) { Logging.Logg().Debug(string.Format("AdminTS_KomDisp.MSExcelIOExportPBRValues::Run () - открыли документ {0}...", listFileInfoDest [0].FullName) , Logging.INDEX_MESSAGE.NOT_SET); #region Заполнить лист книги MS Excel значениями selectWorksheet(1); if (writeValue(ConstantExportPBRValues.NumberColumn_Date, ConstantExportPBRValues.NumberRow_Date, HDateTime.ToMoscowTimeZone().ToString(ConstantExportPBRValues.Format_Date)) == false) { Logging.Logg().Error(string.Format("AdminTS_KomDisp.MSExcelIOExportPBRValues::Run () - не удалось сохранить дату/время обновления...") , Logging.INDEX_MESSAGE.NOT_SET); } else { Logging.Logg().Action(string.Format("AdminTS_KomDisp.MSExcelIOExportPBRValues::Run () - сохранили дату/время обновления [столб.={0}, стр.={1}, знач.={2}]..." , ConstantExportPBRValues.NumberColumn_Date, ConstantExportPBRValues.NumberRow_Date, HDateTime.ToMoscowTimeZone().ToString(ConstantExportPBRValues.Format_Date)) , Logging.INDEX_MESSAGE.NOT_SET); } foreach (KeyValuePair <int, IVALUES> pair in _dictValues) { for (int iHour = 0; iHour < pair.Value.m_data.Length; iHour++) { if (writeValue(pair.Value.m_indxColumn, ConstantExportPBRValues.NumberRow_0 + iHour, pair.Value.m_data [iHour].pbr) == false) { Logging.Logg().Error(string.Format("AdminTS_KomDisp.MSExcelIOExportPBRValues::Run () - [компонент_ID={0}, час={1}] не удалось сохранить значение {2}" , pair.Key, iHour + 1, pair.Value.m_data [iHour].pbr) , Logging.INDEX_MESSAGE.NOT_SET); } else { ; } } } #endregion _previousNameDocument = NameDocument; save(_previousNameDocument); Logging.Logg().Action(string.Format("AdminTS_KomDisp.MSExcelIOExportPBRValues::Run () - сохранили документ {0} с наименованием {1}...", listFileInfoDest [0].FullName, _previousNameDocument) , Logging.INDEX_MESSAGE.NOT_SET); try { listFileInfoDest.ForEach(fi => { if ((_previousNameDocument.Equals(fi.FullName) == false) && (TemplateDocument.Equals(fi.FullName) == false)) { fi.Delete(); } else { ; } }); } catch (Exception e) { Logging.Logg().Error(string.Format("AdminTS_KomDisp.MSExcelIOExportPBRValues::Run () - ошибка удаления '{0}', причина={1}..." , listFileInfoDest [0].FullName, e.Message) , Logging.INDEX_MESSAGE.NOT_SET); } if (Mode == MODE_EXPORT_PBRVALUES.AUTO) { #if HCLASSLIBRARY_MSEXCELIO CloseExcelDoc(); #else #endif arg = new EventResultArgs() { Result = RESULT.OK }; } else { arg = new EventResultArgs() { Result = RESULT.VISIBLE }; } } else { Logging.Logg().Error(string.Format("AdminTS_KomDisp.MSExcelIOExportPBRValues::Run () - не удалось открыть книгу MS Excel с наименованием={0}..." , listFileInfoDest [0].FullName) , Logging.INDEX_MESSAGE.NOT_SET); arg = new EventResultArgs() { Result = RESULT.ERROR_OPEN }; } } #if HCLASSLIBRARY_MSEXCELIO else { // Видимость 'true' - ожидать действий пользователя arg = new EventResultArgs() { Result = RESULT.ERROR_RETRY } }; #else #endif } else { Logging.Logg().Error(string.Format("AdminTS_KomDisp.MSExcelIOExportPBRValues::Run () - отсутствует шаблон с наименованием={0}\\{1}..." , Folder_CSV, TemplateDocument) , Logging.INDEX_MESSAGE.NOT_SET); arg = new EventResultArgs() { Result = RESULT.ERROR_TEMPLATE }; } } catch (Exception e) { Logging.Logg().Exception(e, string.Format("AdminTS_KomDisp.MSExcelIOExportPBRValues::Run () - ..."), Logging.INDEX_MESSAGE.NOT_SET); arg = new EventResultArgs() { Result = RESULT.ERROR_APP }; } // остановить таймер ожидания завершения длительной операции stop_TimerWait(); clearContext(); _mnlResetEventBusy.Reset(); // при внештатном завершении потока - продолжить логгирование и работу приложения в целом try { Logging.Logg().Debug(string.Format("AdminTS_KomDisp.MSExcelIOExportPBRValues::Run() - завершение потока..."), Logging.INDEX_MESSAGE.NOT_SET); } catch { } Result(this, _prevArg = arg); }
public override void Fill(TecView.valuesTEC[] values, params object [] pars) { double sumFact = 0, sumUDGe = 0, sumDiviation = 0; Hd2PercentControl d2PercentControl = new Hd2PercentControl(); int lastHour = (int)pars[0]; //m_tecView.lastHour; int receivedHour = (int)pars[1]; //m_tecView.lastReceivedHour; int itemscount = (int)pars[2]; //m_tecView.m_valuesHours.Length; int warn = -1, cntWarn = -1; string strWarn = string.Empty; bool bPmin = (int)pars[3] == 5 , bCurrHour = (bool)pars[4] //m_tecView.currHour , bIsTypeConnSettAISKUEHour = (bool)pars[5]; //m_tecView.m_arTypeSourceData[(int)HDateTime.INTERVAL.HOURS] == CONN_SETT_TYPE.DATA_AISKUE DateTime serverTime = (DateTime)pars[6]; //m_tecView.serverTime DataGridViewCellStyle curCellStyle; cntWarn = 0; for (int i = 0; i < itemscount; i++) { d2PercentControl.Calculate(values[i], bPmin, out warn); if ((!(warn == 0)) && (values[i + 0].valuesLastMinutesTM > 1)) { cntWarn++; } else { cntWarn = 0; } if (!(cntWarn == 0)) { if (cntWarn > 3) { curCellStyle = s_dgvCellStyleError; } else { curCellStyle = s_dgvCellStyleWarning; } } else { curCellStyle = s_dgvCellStyleCommon; } Rows[i + 0].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.LAST_MINUTES].Style = curCellStyle; if (values[i + 0].valuesLastMinutesTM > 1) { if (cntWarn > 0) { strWarn = cntWarn + @":"; } else { strWarn = string.Empty; } Rows[i + 0].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.LAST_MINUTES].Value = strWarn + values[i + 0].valuesLastMinutesTM.ToString("F2"); } else { Rows[i + 0].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.LAST_MINUTES].Value = 0.ToString("F2"); } bool bDevVal = false; if (bCurrHour == true) { if ((i < (receivedHour + 1)) && ((!(values[i].valuesUDGe == 0)) && (values[i].valuesFact > 0))) { if ((bIsTypeConnSettAISKUEHour == true) || (i < receivedHour)) { bDevVal = true; } else { ; } } else { } } else if (serverTime.Date.Equals(HDateTime.ToMoscowTimeZone(DateTime.Now.Date)) == true) { if ((i < (receivedHour + 1)) && (!(values[i].valuesUDGe == 0)) && (values[i].valuesFact > 0)) { bDevVal = true; } else { } } else if ((!(values[i].valuesUDGe == 0)) && (values[i].valuesFact > 0)) { bDevVal = true; } else { } Rows[i].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.FACT].Value = values[i].valuesFact.ToString("F2"); if (bDevVal == true) { sumFact += values[i].valuesFact; } else { ; } Rows[i].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.PBR].Value = values[i].valuesPBR.ToString("F2"); Rows[i].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.PBRe].Value = values[i].valuesPBRe.ToString("F2"); Rows[i].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.UDGe].Value = values[i].valuesUDGe.ToString("F2"); sumUDGe += values[i].valuesUDGe; if (bDevVal == true) { Rows[i].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.DEVIATION].Value = ((double)(values[i].valuesFact - values[i].valuesUDGe)).ToString("F2"); if ((Math.Round(Math.Abs(values[i].valuesFact - values[i].valuesUDGe), 2) > Math.Round(values[i].valuesDiviation, 2)) && (!(values[i].valuesDiviation == 0))) { Rows[i].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.DEVIATION].Style = s_dgvCellStyleError; } else { Rows[i].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.DEVIATION].Style = s_dgvCellStyleCommon; } sumDiviation += Math.Abs(values[i].valuesFact - values[i].valuesUDGe); } else { Rows[i].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.DEVIATION].Value = 0.ToString("F2"); Rows[i].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.DEVIATION].Style = s_dgvCellStyleCommon; } } Rows[itemscount].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.FACT].Value = sumFact.ToString("F2"); Rows[itemscount].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.UDGe].Value = sumUDGe.ToString("F2"); Rows[itemscount].Cells[(int)DataGridViewStandardHours.INDEX_COLUMNS.DEVIATION].Value = sumDiviation.ToString("F2"); setFirstDisplayedScrollingRowIndex(lastHour, !bIsTypeConnSettAISKUEHour); }
/// <summary> /// Determine that the form is valid by checking each input. /// </summary> /// <returns></returns> private Boolean IsValidForm() { Boolean valid = true; // Validate e-mail input. if (HString.IsValidEmail(this.txtEmail.Text.Trim())) { this.AddResultControl(this.inputEmail, this.txtEmail.Text.Trim(), true); } else { this.AddResultControl(this.inputEmail, this.txtEmail.Text.Trim(), false); valid = false; } // Validate password input. if (HString.IsValidPassword(this.txtPassword.Text.Trim())) { this.AddResultControl(this.inputPassword, this.txtPassword.Text.Trim(), true); } else { this.AddResultControl(this.inputPassword, this.txtPassword.Text.Trim(), false); valid = false; } // Validate phone number input. if (HString.IsValidPhoneNumber(this.txtTelephoneNo.Text.Trim())) { this.AddResultControl(this.inputTelephoneNo, this.txtTelephoneNo.Text.Trim(), true); } else { this.AddResultControl(this.inputTelephoneNo, this.txtTelephoneNo.Text.Trim(), false); valid = false; } // Validate URL input. if (HString.IsValidURL(this.txtWebsite.Text.Trim())) { this.AddResultControl(this.inputWebsite, this.txtWebsite.Text.Trim(), true); } else { this.AddResultControl(this.inputWebsite, this.txtWebsite.Text.Trim(), false); valid = false; } // Validate ZIP code input. if (HString.IsValidZIPCode(this.txtZipCode.Text.Trim())) { this.AddResultControl(this.inputZipCode, this.txtZipCode.Text.Trim(), true); } else { this.AddResultControl(this.inputZipCode, this.txtZipCode.Text.Trim(), false); valid = false; } // Validate date input. if (HDateTime.IsValidDate(this.txtDate.Text.Trim(), "M/d/yyyy", "MM/dd/yyyy")) { this.AddResultControl(this.inputDate, this.txtDate.Text.Trim(), true); } else { this.AddResultControl(this.inputDate, this.txtDate.Text.Trim(), false); valid = false; } // Validate DOB input. if (HDateTime.IsValidDateOfBirth(this.txtDOB.Text.Trim(), "M/d/yyyy", "MM/dd/yyyy")) { this.AddResultControl(this.inputDOB, this.txtDOB.Text.Trim(), true); } else { this.AddResultControl(this.inputDOB, this.txtDOB.Text.Trim(), false); valid = false; } // Validate military time input. if (HDateTime.IsValidMilitaryTime(this.txtTimeMilitary.Text.Trim())) { this.AddResultControl(this.inputTimeMilitary, this.txtTimeMilitary.Text.Trim(), true); } else { this.AddResultControl(this.inputTimeMilitary, this.txtTimeMilitary.Text.Trim(), false); valid = false; } // Validate standard time input. if (HDateTime.IsValidStandardTime(this.txtTimeStandard.Text.Trim())) { this.AddResultControl(this.inputTimeStandard, this.txtTimeStandard.Text.Trim(), true); } else { this.AddResultControl(this.inputTimeStandard, this.txtTimeStandard.Text.Trim(), false); valid = false; } // Validate number input. if (HNumeric.GetNullableInteger(this.txtNumber.Text.Trim()) != null) { this.AddResultControl(this.inputNumber, this.txtNumber.Text.Trim(), true); } else { this.AddResultControl(this.inputNumber, this.txtNumber.Text.Trim(), false); valid = false; } // Validate currency input. if (HNumeric.GetNullableCurrency(this.txtCurrency.Text.Trim(), CultureInfo.GetCultureInfo("en-US")) != null) { this.AddResultControl(this.inputCurrency, this.txtCurrency.Text.Trim(), true); } else { this.AddResultControl(this.inputCurrency, this.txtCurrency.Text.Trim(), false); valid = false; } return(valid); }