Esempio n. 1
0
 /// <summary>
 /// расчитываем все нерабочие периоды, пересекающиеся с указанным
 /// </summary>
 public List<DateSpan> GetIntersected(DateSpan interval)
 {
     var result = new List<DateSpan>();
     foreach (var dayOff in daysOff)
         result.AddRange(dayOff.GetIntersected(interval));
     return result;
 }
Esempio n. 2
0
        private List<Cortege2<DateTime, float>> LoadCandlesFromServer(string ticker, DateSpan span)
        {
            var candles = new List<CandleData>();
            const int stepDays = 7;
            for (var start = span.start; start < span.end; start = start.AddDays(stepDays))
            {
                var end = start.AddDays(stepDays);
                if (end > span.end) end = span.end;
                end = end.AddMinutes(1);

                bool error;
                var candlesM1 = FileGapActualizator.LoadQuotesFromDbSynch(ticker, start, end, out error);
                if (candlesM1 == null || candlesM1.Count == 0) continue;

                candles.AddRange(candlesM1);
            }

            // проредить котировки до дневных
            var dailyCandles = new List<Cortege2<DateTime, float>>();
            DateTime? lastTime = null;
            foreach (var quote in candles)
            {
                if (lastTime == null || lastTime.Value.Date != quote.timeOpen.Date)
                {
                    dailyCandles.Add(new Cortege2<DateTime, float>(quote.timeOpen, quote.open));
                    lastTime = quote.timeOpen;
                }
            }

            return dailyCandles;
        }
Esempio n. 3
0
        /// <summary>
        /// сообщить о возникшем гэпе - предложить закачать котировки или же
        /// закачать их автоматом
        /// </summary>
        private void ReportOnGapFound(DateTime startOfGap)
        {
            // определить, не пришелся ли "гэп" на выходные
            var gapInterval = new DateSpan(startOfGap, DateTime.Now);
            var miniHoles = DaysOff.Instance.GetIntersected(gapInterval);
            var gaps = QuoteCacheManager.SubtractPeriods(gapInterval, miniHoles);
            if (gaps == null || gaps.Count == 0) return;
            var sumMinutes = gaps.Sum(g => (g.end - g.start).TotalMinutes);
            if (sumMinutes < MinutesOfGapInQuoteStream) return;

            // вывести уведомление
            var msg = gaps.Count == 1
                          ? string.Format("заполнить гэп ({0} минут)", (int) sumMinutes)
                          : string.Format("заполнить гэпы ({0} минут суммарно)", (int) sumMinutes);
            AddUrlToStatusPanelSafe(DateTime.Now, msg, LinkTargetFillGaps);
            var action = UserSettings.Instance.GetAccountEventAction(AccountEventCode.GapFound);
            if (action == AccountEventAction.StatusPanelOnly || action == AccountEventAction.DoNothing)
                return;

            // показать желтое окошко
            var repeatNotification = false;
            var shouldFill = !UserSettings.Instance.ConfirmGapFilling ||
                (NotificationBox.Show(msg + Environment.NewLine + "Заполнить сейчас?", "Обнаружен гэп",
                    MessageBoxButtons.YesNo, out repeatNotification) == DialogResult.Yes);

            if (UserSettings.Instance.ConfirmGapFilling != repeatNotification)
            {
                UserSettings.Instance.ConfirmGapFilling = repeatNotification;
                UserSettings.Instance.SaveSettings();
            }
            if (!shouldFill) return;
            Invoke(new Action<string>(FillGapAfterReport), LinkTargetFillGaps);
        }
Esempio n. 4
0
        public void SmallGapIsStillAGap()
        {
            var gapInterval = new DateSpan(new DateTime(2013, 5, 31, 17, 49, 0),
                new DateTime(2013, 5, 31, 17, 51, 16));
            var miniHoles = DaysOff.Instance.GetIntersected(gapInterval);
            var gaps = QuoteCacheManager.SubtractPeriods(gapInterval, miniHoles);

            Assert.AreNotEqual(gaps.Count, 0, "после склейки таки должны оставаться гэпы (SmallGapIsStillAGap)");
            // закомментировал, т.к. пересекается с другими тестами
            //moq.Verify(lw => lw.GetMetadataByCategory(It.Is<string>(s => s == "DayOff")), Times.Once(),
            //    "выходные дни должны быть зачитаны из базы ровно один раз");
        }
Esempio n. 5
0
        public void Can_handle_composite_spans()
        {
            var start = new DateTime(2009, 9, 30);
            var end = new DateTime(2009, 10, 31);
            var span = new DateSpan(start, end);

            Assert.AreEqual(1, span.Months);
            Assert.AreEqual(1, span.Days);

            Console.WriteLine(span.Months);
            Console.WriteLine(span.Days);

            var difference = DateSpan.GetDifference(DateInterval.Days, start, end);
            Console.WriteLine(difference);
        }
Esempio n. 6
0
        public static DateSpan[] MakeGapsOnDaysOff(DateTime startTime, DateTime endTime)
        {
            var spans = new List<DateSpan>();
            DateSpan curSpan = null;
            for (var time = startTime; time <= endTime; time = time.AddHours(1))
            {
                if (DaysOff.Instance.IsDayOff(time))
                {
                    if (curSpan == null)
                        curSpan = new DateSpan(time, time);
                    else
                        curSpan.end = time;
                    continue;
                }
                if (curSpan != null)
                {
                    if (curSpan.end != curSpan.start)
                        spans.Add(curSpan);
                    curSpan = null;
                }
            }

            return spans.ToArray();
        }
Esempio n. 7
0
        public static List<CandleData> MakeQuotes(DateTime timeHistStart, DateTime timeHistEnd,
            DateSpan[] serverGaps)
        {
            // подготовить список котировок для "клиента" и "сервера"
            var allCandles = new List<CandleData>();

            var index = 0;
            for (var time = timeHistStart; time <= timeHistEnd; time = time.AddMinutes(1))
            {
                // проверить попадание в дырку на сервере
                if (serverGaps.Any(g => g.IsIn(time))) continue;

                if (DaysOff.Instance.IsDayOff(time)) continue;
                var o = (float)Math.Sin((index++) / 15.0);
                var candle = new CandleData(o, o + 0.001f, o - 0.003f, o - 0.001f, time, time.AddMinutes(1));
                allCandles.Add(candle);
            }

            return allCandles;
        }
		private void LoadAppointments(DateSpan dateSpan)
		{
			this.Appointments.Clear();
			this.IsLoading = true;

			ScheduleViewRepository.Context.Load(ScheduleViewRepository.Context.GetSqlAppointmentsByRangeQuery(dateSpan.Start, dateSpan.End)).Completed += (o, u) =>
			{
				ScheduleViewRepository.Context.Load(ScheduleViewRepository.Context.GetSqlAppointmentResourcesByRangeQuery(dateSpan.Start, dateSpan.End));

				ScheduleViewRepository.Context.Load(ScheduleViewRepository.Context.GetSqlExceptionOccurrencesByRangeQuery(dateSpan.Start, dateSpan.End)).Completed += (os, us) =>
				{
					ScheduleViewRepository.Context.Load(ScheduleViewRepository.Context.GetSqlExceptionAppointmentsByRangeQuery(dateSpan.Start, dateSpan.End)).Completed += (ea, ua) =>
					{
						ScheduleViewRepository.Context.Load(ScheduleViewRepository.Context.GetSqlExceptionResourcesByRangeQuery(dateSpan.Start, dateSpan.End)).Completed += (s, t) =>
						{
							this.Appointments.AddRange((o as LoadOperation).Entities.Select(a => a as SqlAppointment));
							this.IsLoading = false;
						};
					};
				};
			};
		}
        private void LoadAppointments(DateSpan dateSpan)
        {
            this.Appointments.Clear();

            this.IsLoading = true;

            this.Appointments.AddRange(ScheduleViewRepository.GetSqlAppointmentsByRange(dateSpan.Start, dateSpan.End));

            this.IsLoading = false;
        }
Esempio n. 10
0
        public void TyrParse_StringValue_IsInvalid()
        {
            string str = "InvalidString";

            Assert.IsFalse(DateSpan.TryParse(str, out _), "Valid");
        }
Esempio n. 11
0
        public void TyrParse_Null_IsInvalid()
        {
            string str = null;

            Assert.IsFalse(DateSpan.TryParse(str, out _));
        }
Esempio n. 12
0
        public void MaxValue_EqualsDateMaxDateMin()
        {
            var max = DateSpan.Subtract(Date.MaxValue, Date.MinValue);

            Assert.AreEqual(DateSpan.MaxValue, max);
        }
Esempio n. 13
0
        private void FillGrid()
        {
            long clinicNum = 0;

            //if clinics are not enabled, comboClinic.SelectedIndex will be -1, so clinicNum will be 0 and list will not be filtered by clinic
            if (Security.CurUser.ClinicIsRestricted && comboClinics.SelectedIndex > -1)
            {
                clinicNum = _listClinics[comboClinics.SelectedIndex].ClinicNum;
            }
            else if (comboClinics.SelectedIndex > 0)                                //if user is not restricted, clinicNum will be 0 and the query will get all clinic data
            {
                clinicNum = _listClinics[comboClinics.SelectedIndex - 1].ClinicNum; //if user is not restricted, comboClinic will contain "All" so minus 1
            }
            int clinicWidth  = 80;
            int patientWidth = 180;
            int carrierWidth = 220;

            if (PrefC.HasClinicsEnabled)
            {
                patientWidth = 140;
                carrierWidth = 200;
            }
            gridMain.BeginUpdate();
            gridMain.ListGridColumns.Clear();
            GridColumn col = new GridColumn(Lan.g("TableAutoOrthoClaims", "Patient"), patientWidth);

            gridMain.ListGridColumns.Add(col);
            col = new GridColumn(Lan.g("TableAutoOrthoClaims", "Carrier"), carrierWidth);
            gridMain.ListGridColumns.Add(col);
            col = new GridColumn(Lan.g("TableAutoOrthoClaims", "TxMonths"), 70);
            gridMain.ListGridColumns.Add(col);
            col = new GridColumn(Lan.g("TableAutoOrthoClaims", "Banding"), 80, HorizontalAlignment.Center);
            gridMain.ListGridColumns.Add(col);
            col = new GridColumn(Lan.g("TableAutoOrthoClaims", "MonthsRem"), 100);
            gridMain.ListGridColumns.Add(col);
            col = new GridColumn(Lan.g("TableAutoOrthoClaims", "#Sent"), 60);
            gridMain.ListGridColumns.Add(col);
            col = new GridColumn(Lan.g("TableAutoOrthoClaims", "LastSent"), 80, HorizontalAlignment.Center);
            gridMain.ListGridColumns.Add(col);
            col = new GridColumn(Lan.g("TableAutoOrthoClaims", "NextClaim"), 80, HorizontalAlignment.Center);
            gridMain.ListGridColumns.Add(col);
            if (PrefC.HasClinicsEnabled)              //clinics is turned on
            {
                col = new GridColumn(Lan.g("TableAutoOrthoClaims", "Clinic"), clinicWidth, HorizontalAlignment.Center);
                gridMain.ListGridColumns.Add(col);
            }
            gridMain.ListGridRows.Clear();
            GridRow row;

            foreach (DataRow rowCur in _tableOutstandingAutoClaims.Rows)
            {
                //need a check for if clinics is on here
                if (PrefC.HasClinicsEnabled &&             //Clinics are enabled
                    (Security.CurUser.ClinicIsRestricted || comboClinics.SelectedIndex != 0) &&                   //"All" is not selected
                    clinicNum != PIn.Long(rowCur["ClinicNum"].ToString()))                        //currently selected clinic doesn't match the row's clinic
                {
                    continue;
                }
                row = new GridRow();
                DateTime dateLastSeen      = PIn.Date(rowCur["LastSent"].ToString());
                DateTime dateBanding       = PIn.Date(rowCur["DateBanding"].ToString());
                DateTime dateNextClaim     = PIn.Date(rowCur["OrthoAutoNextClaimDate"].ToString());
                DateSpan dateSpanMonthsRem = new DateSpan(PIn.Date(rowCur["DateBanding"].ToString()).AddMonths(PIn.Int(rowCur["MonthsTreat"].ToString())), DateTimeOD.Today);
                row.Cells.Add(PIn.String(rowCur["Patient"].ToString()));
                row.Cells.Add(PIn.String(rowCur["CarrierName"].ToString()));
                row.Cells.Add(PIn.String(rowCur["MonthsTreat"].ToString()));
                row.Cells.Add(dateBanding.Year < 1880 ? "" : dateBanding.ToShortDateString()); //add blank if there is no banding
                if (dateBanding.Year < 1880)                                                   //add blank if there is no banding
                {
                    row.Cells.Add("");
                }
                else
                {
                    row.Cells.Add(((dateSpanMonthsRem.YearsDiff * 12) + dateSpanMonthsRem.MonthsDiff) + " " + Lan.g(this, "months")
                                  + ", " + dateSpanMonthsRem.DaysDiff + " " + Lan.g(this, "days"));
                }
                row.Cells.Add(PIn.String(rowCur["NumSent"].ToString()));
                row.Cells.Add(dateLastSeen.Year < 1880 ? "" : dateLastSeen.ToShortDateString());
                row.Cells.Add(dateNextClaim.Year < 1880 ? "" : dateNextClaim.ToShortDateString());
                if (PrefC.HasClinicsEnabled)                  //clinics is turned on
                //Use the long list of clinics so that hidden clinics can be shown for unrestricted users.
                {
                    row.Cells.Add(Clinics.GetAbbr(PIn.Long(rowCur["ClinicNum"].ToString())));
                }
                row.Tag = rowCur;
                gridMain.ListGridRows.Add(row);
            }
            gridMain.EndUpdate();
        }
        /// <summary>
        /// Increments the specified value.
        /// </summary>
        /// <param name="value">The value to increment.</param>
        /// <param name="buildStart">The build start date/time.</param>
        /// <param name="projectStart">The project start date/time.</param>
        /// <returns>The incremented value.</returns>
        private string Increment(string value, DateTime buildStart, DateTime projectStart, string projectFilePath)
        {
            string dayOfyear  = buildStart.DayOfYear.ToString("000");
            int    deltaYears = buildStart.Year - projectStart.Year;
            string yearDecade = buildStart.ToString("yy");

            int intValue = 0;

            Int32.TryParse(value, out intValue);
            if (intValue < 0)
            {
                intValue = 0;
            }

            switch (IncrementStyle)
            {
            case OLD_IncrementStyle.None:
                return(value);

            case OLD_IncrementStyle.Increment:
                return((intValue + 1).ToString());

            case OLD_IncrementStyle.TimeStamp:
                return(string.Format("{0:00}{1:00}", buildStart.Hour, buildStart.Minute));

            case OLD_IncrementStyle.YearStamp:
                return((buildStart.Year).ToString());

            case OLD_IncrementStyle.DeltaBaseDate:
                DateSpan ds = DateSpan.GetDateDifference(buildStart, projectStart);
                return(string.Format("{0}{1:00}", (ds.Years * 12) + ds.Months, ds.Days));

            case OLD_IncrementStyle.DeltaBaseDateInDays:
                TimeSpan ts = buildStart.Subtract(projectStart);
                return(((int)ts.TotalDays).ToString());

            case OLD_IncrementStyle.YearDayOfYear:
                return(string.Format("{0}{1:000}", yearDecade, dayOfyear));

            case OLD_IncrementStyle.DeltaBaseYearDayOfYear:
                return(string.Format("{0}{1:000}", deltaYears, dayOfyear));

            case OLD_IncrementStyle.DeltaBaseYear:
                return(deltaYears.ToString());

            case OLD_IncrementStyle.YearDecadeStamp:
                return(yearDecade);

            case OLD_IncrementStyle.MonthStamp:
                return(buildStart.Month.ToString());

            case OLD_IncrementStyle.DayStamp:
                return(buildStart.Day.ToString());

            case OLD_IncrementStyle.MonthAndDayStamp:
                return(string.Format("{0:00}{1:00}", buildStart.Month, buildStart.Day));

            default:
                throw (new ApplicationException("Unknown increment style: " + IncrementStyle.ToString()));
            }
        }
Esempio n. 15
0
        private void LoadHistoryFromServer(string ticker, List<CandleData> candles, DateSpan range)
        {
            var loadedList = new List<CandleData>();
            var pointCost = DalSpot.Instance.GetPrecision10(ticker);

            try
            {
                IQuoteStorage quoteStorage;
                try
                {
                    quoteStorage = Contract.Util.Proxy.QuoteStorage.Instance.proxy;
                }
                catch (Exception)
                {
                    Logger.Error("LoadHistoryFromServer - связь с сервером (IQuoteStorageBinding) не установлена");
                    throw;
                }

                for (var start = range.start.AddMinutes(1); start < range.end;)
                {
                    var end = start.AddDays(10);
                    if (end > range.end)
                        end = range.end;
                    else
                    {
                        if ((range.end - end).TotalDays < 2)
                            end = range.end;
                    }

                    var candlesPacked = quoteStorage.GetMinuteCandlesPacked(ticker, start, end);
                    start = end.AddMinutes(1);

                    if (candlesPacked == null || candlesPacked.count == 0) continue;

                    // добавить свечи в список закачанных
                    loadedList.AddRange(candlesPacked.GetCandles().Select(c => new CandleData(c, pointCost)));
                }

                if (loadedList.Count == 0) return;

                // добавить свечи в общий список
                if (candles.Count == 0 || candles[candles.Count - 1].timeOpen < loadedList[0].timeOpen)
                {
                    candles.AddRange(loadedList);
                    return;
                }
                candles.InsertRange(0, loadedList);
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в LoadHistoryFromServer (" + ticker + ")", ex);
                throw;
            }
        }
Esempio n. 16
0
 public void DateRangeTests()
 {
     Assert.IsTrue(DateSpan.EntireMonth(2000, 4).Contains(new DateTime(2000, 4, 5, 13, 24, 53)));
     Assert.IsTrue(DateSpan.EntireYear(2005).Contains(DateSpan.EntireMonth(2005, 7)));
     Assert.AreEqual(new DateTime(2000, 4, 10), DateSpan.Parse("2000-4-10 to 2000-5-10").Begin);
 }
Esempio n. 17
0
 ///<summary>DEPRECATED. Use CodeBase.DateSpan.
 ///Pass in the two dates that you want to compare. Results will be stored in YearsDiff, MonthsDiff, and DaysDiff.
 ///Always subtracts the smaller date from the larger date to return a positive (or 0) value.</summary>
 public DateTimeOD(DateTime date1, DateTime date2)
 {
     _dateSpan = new DateSpan(date1, date2);
 }
Esempio n. 18
0
        private void UpdateTicker(string ticker)
        {
            // прочитать содержимое файла
            var tickerQuotes = LoadTickerQuotesFromFile(ticker);

            // интервал истории, хранимой на сервере
            var serverRange = quoteHistoryOnServer.GetServerTickerHistorySpan(ticker);
            if (serverRange == null && tickerQuotes.Count == 0) return;
            if (serverRange != null && serverRange.TotalDays < 1)
                serverRange = null;
            if (serverRange == null) // записать, что есть
            {
                var oldQuotes = quotes.ReceiveValue(ticker);
                if (oldQuotes == null || oldQuotes.Count < tickerQuotes.Count)
                {
                    quotes.UpdateValues(ticker, tickerQuotes);
                    SaveUpdatedQuotesInFile(ticker, tickerQuotes);
                }
                return;
            }

            // уточнить, за какой период загружать данные
            var intervalsToUpdate = new List<DateSpan>();
            if (tickerQuotes.Count == 0)
                intervalsToUpdate.Add(serverRange);
            else
            {
                if (serverRange.start.Date < tickerQuotes[0].a)
                    intervalsToUpdate.Add(new DateSpan(serverRange.start.Date, tickerQuotes[0].a));
                var lastDate = tickerQuotes[tickerQuotes.Count - 1].a;
                if ((DateTime.Now.Date - lastDate).TotalDays < 2)
                    lastDate = DateTime.Now.Date.AddDays(-2);
                if (intervalsToUpdate.Count > 0 && lastDate <= intervalsToUpdate[0].end)
                    intervalsToUpdate[0] = new DateSpan(intervalsToUpdate[0].start, DateTime.Now.Date);
                else
                    intervalsToUpdate.Add(new DateSpan(lastDate, DateTime.Now.Date));
            }

            // таки загрузить данные
            tickerQuotes = UpdateTickerQuotesFromServer(ticker, intervalsToUpdate, tickerQuotes);

            // и сохранить их в файле
            quotes.UpdateValues(ticker, tickerQuotes);
            if (tickerQuotes.Count > 0)
                SaveUpdatedQuotesInFile(ticker, tickerQuotes);
        }
Esempio n. 19
0
            private string GetAutoNum()
            {
                int      autoLength = this.AutoLength.ToInt32();
                int      autoMode   = this.AutoMode.ToInt32();
                int      baseNumber = this.BaseNumber.ToInt32();
                DateTime startDate  = this.StartDate.ToDateTime();
                DateTime start      = new DateTime(startDate.Year, startDate.Month, startDate.Day);
                DateTime end        = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                //DateTime end = new DateTime(2012, 07, 27);
                DateSpan span   = new DateSpan(startDate, end);
                int      number = 0;

                switch (autoMode)
                {
                case 0:
                    number = baseNumber + 1;
                    this.BaseNumber.value = number;
                    this.Update();
                    break;

                case 1:                                                     //每年一次
                    if (span.Years > 0)
                    {
                        number = 1;
                        this.BaseNumber.value = number;
                        this.Update();
                    }
                    else
                    {
                        //更新数据库中的值为1
                        number = baseNumber + 1;
                        this.BaseNumber.value = number;
                        this.StartDate.set_DateTime_Now();
                        this.Update();
                    }
                    break;

                case 2:                                                         //每月一次
                    if (span.Months > 0)
                    {
                        number = 1;
                        this.BaseNumber.value = number;
                        this.Update();
                    }
                    else
                    {
                        //更新数据库中的值为1
                        number = baseNumber + 1;
                        this.BaseNumber.value = number;
                        this.StartDate.set_DateTime_Now();
                        this.Update();
                    }
                    break;

                case 3:                                                         //每日一次
                    if (span.Days > 0)
                    {
                        number = 1;
                        this.BaseNumber.value = number;
                        this.StartDate.set_DateTime_Now();
                        this.Update();
                    }
                    else
                    {
                        //更新数据库中的值为1
                        number = baseNumber + 1;
                        this.BaseNumber.value = number;
                        this.Update();
                    }
                    break;
                }
                string str = String.Format("{0:D" + autoLength + "}", number);

                return(str);
            }
Esempio n. 20
0
        private void butGenerateClaims_Click(object sender, EventArgs e)
        {
            if (gridMain.SelectedIndices.Count() < 1)
            {
                MsgBox.Show(this, "Please select the rows for which you would like to create procedures and claims.");
                return;
            }
            if (!MsgBox.Show(this, MsgBoxButtons.YesNo, "Are you sure you want to generate claims and procedures for all patients and insurance plans?"))
            {
                return;
            }
            List <long> listPlanNums    = new List <long>();
            List <long> listPatPlanNums = new List <long>();
            List <long> listInsSubNums  = new List <long>();

            for (int i = 0; i < gridMain.SelectedIndices.Count(); i++)
            {
                DataRow rowCur = (DataRow)gridMain.ListGridRows[gridMain.SelectedIndices[i]].Tag;
                listPlanNums.Add(PIn.Long(rowCur["PlanNum"].ToString()));
                listPatPlanNums.Add(PIn.Long(rowCur["PatPlanNum"].ToString()));
                listInsSubNums.Add(PIn.Long(rowCur["InsSubNum"].ToString()));
            }
            List <InsPlan> listSelectedInsPlans = InsPlans.GetPlans(listPlanNums);
            List <PatPlan> listSelectedPatPlans = PatPlans.GetPatPlans(listPatPlanNums);
            List <InsSub>  listSelectedInsSubs  = InsSubs.GetMany(listInsSubNums);
            List <DataRow> rowsSucceeded        = new List <DataRow>();
            int            rowsFailed           = 0;
            List <Benefit> listBenefitsAll      = Benefits.Refresh(listSelectedPatPlans, listSelectedInsSubs);

            for (int i = 0; i < gridMain.SelectedIndices.Count(); i++)
            {
                try {
                    DataRow     rowCur        = (DataRow)gridMain.ListGridRows[gridMain.SelectedIndices[i]].Tag;
                    long        patNumCur     = PIn.Long(rowCur["PatNum"].ToString());
                    Patient     patCur        = Patients.GetPat(patNumCur);
                    PatientNote patNoteCur    = PatientNotes.Refresh(patNumCur, patCur.Guarantor);
                    long        codeNumCur    = PIn.Long(rowCur["AutoCodeNum"].ToString());
                    long        provNumCur    = PIn.Long(rowCur["ProvNum"].ToString());
                    long        clinicNumCur  = PIn.Long(rowCur["ClinicNum"].ToString());
                    long        insPlanNumCur = PIn.Long(rowCur["PlanNum"].ToString());
                    long        patPlanNumCur = PIn.Long(rowCur["PatPlanNum"].ToString());
                    long        insSubNumCur  = PIn.Long(rowCur["InsSubNum"].ToString());
                    int         monthsTreat   = PIn.Int(rowCur["MonthsTreat"].ToString());
                    DateTime    dateDue       = PIn.Date(rowCur["OrthoAutoNextClaimDate"].ToString());
                    //for each selected row
                    //create a procedure
                    //Procedures.CreateProcForPat(patNumCur,codeNumCur,"","",ProcStat.C,provNumCur);
                    Procedure      proc        = Procedures.CreateOrthoAutoProcsForPat(patNumCur, codeNumCur, provNumCur, clinicNumCur, dateDue);
                    InsPlan        insPlanCur  = InsPlans.GetPlan(insPlanNumCur, listSelectedInsPlans);
                    PatPlan        patPlanCur  = listSelectedPatPlans.FirstOrDefault(x => x.PatPlanNum == patPlanNumCur);
                    InsSub         insSubCur   = listSelectedInsSubs.FirstOrDefault(x => x.InsSubNum == insSubNumCur);
                    List <Benefit> benefitList = listBenefitsAll.FindAll(x => x.PatPlanNum == patPlanCur.PatPlanNum || x.PlanNum == insSubCur.PlanNum);
                    //create a claimproc
                    List <ClaimProc> listClaimProcs = new List <ClaimProc>();
                    Procedures.ComputeEstimates(proc, patNumCur, ref listClaimProcs, true, new List <InsPlan> {
                        insPlanCur
                    },
                                                new List <PatPlan> {
                        patPlanCur
                    }, benefitList, null, null, true, patCur.Age, new List <InsSub> {
                        insSubCur
                    }, isForOrtho: true);
                    //make the feebilled == the insplan feebilled or patplan feebilled
                    double feebilled = patPlanCur.OrthoAutoFeeBilledOverride == -1 ? insPlanCur.OrthoAutoFeeBilled : patPlanCur.OrthoAutoFeeBilledOverride;
                    //create a claim with that claimproc
                    string claimType = "";
                    switch (patPlanCur.Ordinal)
                    {
                    case 1:
                        claimType = "P";
                        break;

                    case 2:
                        claimType = "S";
                        break;
                    }
                    DateSpan dateSpanMonthsRem = new DateSpan(PIn.Date(rowCur["DateBanding"].ToString()).AddMonths(PIn.Int(rowCur["MonthsTreat"].ToString())), DateTimeOD.Today);
                    Claims.CreateClaimForOrthoProc(claimType, patPlanCur, insPlanCur, insSubCur,
                                                   ClaimProcs.GetForProcWithOrdinal(proc.ProcNum, patPlanCur.Ordinal), proc, feebilled, PIn.Date(rowCur["DateBanding"].ToString()),
                                                   PIn.Int(rowCur["MonthsTreat"].ToString()), ((dateSpanMonthsRem.YearsDiff * 12) + dateSpanMonthsRem.MonthsDiff));
                    PatPlans.IncrementOrthoNextClaimDates(patPlanCur, insPlanCur, monthsTreat, patNoteCur);
                    rowsSucceeded.Add(rowCur);
                    SecurityLogs.MakeLogEntry(Permissions.ProcComplCreate, patCur.PatNum
                                              , Lan.g(this, "Automatic ortho procedure and claim generated for") + " " + dateDue.ToShortDateString());
                }
                catch (Exception) {
                    rowsFailed++;
                }
            }
            string message = Lan.g(this, "Done.") + " " + Lan.g(this, "There were") + " " + rowsSucceeded.Count + " "
                             + Lan.g(this, "claim(s) generated and") + " " + rowsFailed + " " + Lan.g(this, "failures") + ".";

            MessageBox.Show(message);
            foreach (DataRow row in rowsSucceeded)
            {
                _tableOutstandingAutoClaims.Rows.Remove(row);
            }
            FillGrid();
        }
        public float GetDimmingLevel()
        {
            if (currentState == -1)
            {
                autoDimmingLevel = 0;
            }
            else
            {
                DateSpan start, end, now = DateSpan.Now;
                if (lightingStates[currentState].startTime.Before(lightingStates[currentState].endTime))
                {
                    start = new DateSpan(lightingStates[currentState].startTime);
                    end   = new DateSpan(lightingStates[currentState].endTime);
                }
                else
                {
                    var otherDay = DateSpan.Now;
                    // its after midnight
                    if (now.Before(lightingStates[currentState].endTime))
                    {
                        otherDay.AddDays(-1);
                        start = new DateSpan(otherDay, lightingStates[currentState].startTime);
                        end   = new DateSpan(lightingStates[currentState].endTime);
                    }
                    else
                    {
                        otherDay.AddDays(1);
                        start = new DateSpan(lightingStates[currentState].startTime);
                        end   = new DateSpan(otherDay, lightingStates[currentState].endTime);
                    }
                }

                if (lightingStates[currentState].type == LightingStateType.LinearRamp)
                {
                    autoDimmingLevel = Utils.CalcLinearRamp(
                        start,
                        end,
                        now,
                        lightingStates[currentState].startingDimmingLevel,
                        lightingStates[currentState].endingDimmingLevel);
                }
                else if (lightingStates[currentState].type == LightingStateType.HalfParabolaRamp)
                {
                    autoDimmingLevel = Utils.CalcHalfParabola(
                        start,
                        end,
                        now,
                        lightingStates[currentState].startingDimmingLevel,
                        lightingStates[currentState].endingDimmingLevel);
                }
                else if (lightingStates[currentState].type == LightingStateType.On)
                {
                    autoDimmingLevel = lightingStates[currentState].startingDimmingLevel;
                }
            }

            autoDimmingLevel = autoDimmingLevel.Constrain(0, 100);
            if (plugState)
            {
                if (dimmingMode == Mode.Auto)
                {
                    requestedDimmingLevel = autoDimmingLevel;
                }

                currentDimmingLevel = rateOfChangeLimiter.RateOfChange(requestedDimmingLevel);
            }

            return(currentDimmingLevel);
        }
Esempio n. 22
0
        private void LoadHistoryFromServer(string ticker, List <CandleData> candles, DateSpan range)
        {
            var loadedList = new List <CandleData>();
            var pointCost  = DalSpot.Instance.GetPrecision10(ticker);

            try
            {
                IQuoteStorage quoteStorage;
                try
                {
                    quoteStorage = Contract.Util.Proxy.QuoteStorage.Instance.proxy;
                }
                catch (Exception)
                {
                    Logger.Error("LoadHistoryFromServer - связь с сервером (IQuoteStorageBinding) не установлена");
                    throw;
                }

                for (var start = range.start.AddMinutes(1); start < range.end;)
                {
                    var end = start.AddDays(10);
                    if (end > range.end)
                    {
                        end = range.end;
                    }
                    else
                    {
                        if ((range.end - end).TotalDays < 2)
                        {
                            end = range.end;
                        }
                    }

                    var candlesPacked = quoteStorage.GetMinuteCandlesPacked(ticker, start, end);
                    start = end.AddMinutes(1);

                    if (candlesPacked == null || candlesPacked.count == 0)
                    {
                        continue;
                    }

                    // добавить свечи в список закачанных
                    loadedList.AddRange(candlesPacked.GetCandles().Select(c => new CandleData(c, pointCost)));
                }

                if (loadedList.Count == 0)
                {
                    return;
                }

                // добавить свечи в общий список
                if (candles.Count == 0 || candles[candles.Count - 1].timeOpen < loadedList[0].timeOpen)
                {
                    candles.AddRange(loadedList);
                    return;
                }
                candles.InsertRange(0, loadedList);
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в LoadHistoryFromServer (" + ticker + ")", ex);
                throw;
            }
        }
Esempio n. 23
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string fileName = "PPDK" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".txt";

        if (Request.Browser.Browser == "IE")
        {
            fileName = Server.UrlPathEncode(fileName);

            if (fileName != null)
            {
                fileName = fileName.Replace(@"+", @"%20");
            }
        }


        Response.ContentType     = "text/plain";
        Response.ContentEncoding = Encoding.UTF8;

        //Response.ContentType = "application/octet-stream";

        Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");

        if (_authority.HasPermission(Permission.CanSeePeople, Organization.PPDKid, Geography.DenmarkId, Authorization.Flag.ExactGeographyExactOrganization))
        {
            StringBuilder sb           = new StringBuilder();
            int           org          = "" + Request["o"] == "UP" ? Organization.UPDKid : Organization.PPDKid;
            People        danishPeople = People.FromOrganizationAndGeography(org, Geography.RootIdentity);
            danishPeople = danishPeople.GetVisiblePeopleByAuthority(_authority).RemoveUnlisted();

            sb.Append("Identity");
            sb.Append("\tName");
            sb.Append("\tEmail");
            sb.Append("\tStreet");
            sb.Append("\tPostalCode");
            sb.Append("\tCity");
            sb.Append("\tCountry.Name");
            sb.Append("\tPhone");
            sb.Append("\tBirthdate");
            sb.Append("\tGender");
            sb.Append("\tGeography.Name");
            sb.Append("\tpp.start");
            sb.Append("\tpp.end");
            sb.Append("\tup.start");
            sb.Append("\tup.end");
            sb.Append("\r\n");
            foreach (Person p in danishPeople)
            {
                sb.Append(p.Identity);
                sb.Append("\t" + p.Name);
                sb.Append("\t" + p.Email);
                sb.Append("\t" + p.Street);
                sb.Append("\t" + p.PostalCode);
                sb.Append("\t" + p.CityName);
                sb.Append("\t" + p.Country.Name);
                sb.Append("\t" + p.Phone);
                sb.Append("\t" + p.Birthdate);
                sb.Append("\t" + p.Gender);
                sb.Append("\t" + p.Geography.Name);
                Memberships pMemberships = p.GetMemberships();
                DateSpan    ppdkspan     = null;
                DateSpan    updkspan     = null;
                foreach (Membership m in pMemberships)
                {
                    if (m.OrganizationId == Organization.PPDKid)
                    {
                        ppdkspan = new DateSpan(m.MemberSince, m.Expires);
                    }
                    else if (m.OrganizationId == Organization.UPDKid || m.Organization.Inherits(Organization.UPDKid))
                    {
                        updkspan = new DateSpan(m.MemberSince, m.Expires);
                    }
                }
                if (ppdkspan != null)
                {
                    sb.Append("\t" + ppdkspan.start);
                    sb.Append("\t" + ppdkspan.end);
                }
                else
                {
                    sb.Append("\t\t");
                }

                if (updkspan != null)
                {
                    sb.Append("\t" + updkspan.start);
                    sb.Append("\t" + updkspan.end);
                }
                else
                {
                    sb.Append("\t\t");
                }
                sb.Append("\r\n");
            }

            Response.Write(sb.ToString());
        }
    }
Esempio n. 24
0
        public void MinValue_EqualsDateMinDateMax()
        {
            var min = DateSpan.Subtract(Date.MinValue, Date.MaxValue);

            Assert.AreEqual(DateSpan.MinValue, min);
        }
Esempio n. 25
0
        private string Increment(string value, DateTime buildStart, DateTime projectStart, string projectFilePath)
        {
            string arg  = buildStart.DayOfYear.ToString("000");
            int    num  = buildStart.Year - projectStart.Year;
            string text = buildStart.ToString("yy");
            int    num2 = 0;

            int.TryParse(value, out num2);
            if (num2 < 0)
            {
                num2 = 0;
            }
            string result;

            switch (this.IncrementStyle)
            {
            case OLD_IncrementStyle.None:
                result = value;
                break;

            case OLD_IncrementStyle.DayStamp:
                result = buildStart.Day.ToString();
                break;

            case OLD_IncrementStyle.DeltaBaseDate:
            {
                DateSpan dateDifference = DateSpan.GetDateDifference(buildStart, projectStart);
                result = string.Format("{0}{1:00}", dateDifference.Years * 12 + dateDifference.Months, dateDifference.Days);
                break;
            }

            case OLD_IncrementStyle.DeltaBaseYearDayOfYear:
                result = string.Format("{0}{1:000}", num, arg);
                break;

            case OLD_IncrementStyle.DeltaBaseYear:
                result = num.ToString();
                break;

            case OLD_IncrementStyle.Increment:
                result = (num2 + 1).ToString();
                break;

            case OLD_IncrementStyle.MonthStamp:
                result = buildStart.Month.ToString();
                break;

            case OLD_IncrementStyle.TimeStamp:
                result = string.Format("{0:00}{1:00}", buildStart.Hour, buildStart.Minute);
                break;

            case OLD_IncrementStyle.YearStamp:
                result = buildStart.Year.ToString();
                break;

            case OLD_IncrementStyle.YearDayOfYear:
                result = string.Format("{0}{1:000}", text, arg);
                break;

            case OLD_IncrementStyle.YearDecadeStamp:
                result = text;
                break;

            case OLD_IncrementStyle.MonthAndDayStamp:
                result = string.Format("{0:00}{1:00}", buildStart.Month, buildStart.Day);
                break;

            case OLD_IncrementStyle.DeltaBaseDateInDays:
                result = ((int)buildStart.Subtract(projectStart).TotalDays).ToString();
                break;

            default:
                throw new ApplicationException("Unknown increment style: " + this.IncrementStyle.ToString());
            }
            return(result);
        }
Esempio n. 26
0
        public void TyrParse_StringEmpty_IsInvalid()
        {
            string str = string.Empty;

            Assert.IsFalse(DateSpan.TryParse(str, out _));
        }
Esempio n. 27
0
 // ReSharper restore ReturnTypeCanBeEnumerable.Local
 // вычитание из временного интервала множества интервалов
 // ReSharper disable ReturnTypeCanBeEnumerable.Local
 public static List<DateSpan> SubtractPeriods(DateSpan p1, List<DateSpan> p2)
 {
     if (p2 == null || p2.Count == 0) return new List<DateSpan> { p1 };
     var result = new List<DateSpan>();
     var hasCross = false;
     foreach (var period in p2)
     {
         // нет пересечения
         if ((period.end < p1.start) || (period.start > p1.end))
             continue;
         hasCross = true;
         // возможно разделение на 2 части
         if (p1.start < period.start)
             result.Add(new DateSpan(p1.start, period.start));
         p1.start = period.end;
         if (p1.start > p1.end)
             return result;
     }
     if (hasCross)
         result.Add(p1);
     return result;
 }
Esempio n. 28
0
        private List <EntityExample> GenerateEntities(DateSpan span, TimeZoneInfo tz, DateTime dstHour)
        {
            var   adjusted  = false;
            Color nextColor = Color.White;

            var result = new List <EntityExample>();

            DateTime start = span.Start;
            DateTime end   = span.End;

            while (start < end)
            {
                var entity = new EntityExample()
                {
                    ImportEffectiveDateStart = start,
                    ImportEffectiveDateEnd   = start.AddHours(1),
                    RowColor = nextColor
                };

                nextColor = Color.White;

                start = start.AddHours(1);

                if (IsSourceDataAdjustedDST)
                {
                    if (entity.ImportEffectiveDateEnd == dstHour)
                    {
                        if (IsSpringForward)
                        {
                            entity.RowColor = Color.Yellow;
                            entity.ImportEffectiveDateEnd = entity.ImportEffectiveDateEnd.AddHours(1);
                        }
                        else
                        {
                            if (!adjusted)
                            {
                                entity.ImportEffectiveDateEnd = entity.ImportEffectiveDateEnd.AddHours(-1);
                                start           = start.AddHours(-1); //repeat the hour
                                adjusted        = true;
                                entity.RowColor = Color.Yellow;
                                nextColor       = Color.Red;
                            }
                        }
                    }

                    if (entity.ImportEffectiveDateEnd == dstHour.AddHours(-1))
                    {
                        if (!IsSpringForward)
                        {
                            if (!adjusted)
                            {
                                entity.RowColor = Color.Yellow;
                            }
                        }
                    }

                    if (entity.ImportEffectiveDateStart == dstHour)
                    {
                        if (IsSpringForward)
                        {
                            nextColor = Color.Yellow;
                            continue; //skip the hour
                        }
                    }
                }
                else
                {
                    if (IsSpringForward)
                    {
                        if (entity.ImportEffectiveDateStart == dstHour)
                        {
                            entity.RowColor = Color.Yellow;
                        }
                    }
                    else
                    {
                        if (entity.ImportEffectiveDateEnd == dstHour)
                        {
                            entity.RowColor = Color.Yellow;
                        }
                    }
                }

                var importDateTimeInfo = entity.ImportEffectiveDateStart.ParseImportDateTimeInfo(tz, ContractHour, IsSourceDataAdjustedDST);

                entity.UtcEffectiveDateStart     = importDateTimeInfo.DateTimeUtc;
                entity.UtcEffectiveDateEnd       = entity.ImportEffectiveDateEnd.ToUtc(tz, IsSourceDataAdjustedDST);
                entity.ContractHour              = importDateTimeInfo.ContractDateTimeInfo.ContractHour;
                entity.ContractDay               = importDateTimeInfo.ContractDateTimeInfo.ContractDay;
                entity.ContractMonth             = importDateTimeInfo.ContractDateTimeInfo.ContractMonth;
                entity.DisplayEffectiveDateStart = entity.UtcEffectiveDateStart.ToSpecified(tz);
                entity.DisplayEffectiveDateEnd   = entity.UtcEffectiveDateEnd.ToSpecified(tz);

                result.Add(entity);
            }

            return(result);
        }
Esempio n. 29
0
 public static DateSpan DateSpanTo(this DateTime min, DateTime max)
 {
     return(DateSpan.FromToDates(min, max));
 }
		private void GenerateAppointments(DateSpan dateSpan)
		{
			if (!this.isInitialLoad)
			{
				ScheduleViewRepository.SaveData(() => this.LoadAppointments(dateSpan));
			}
			else
			{
				LoadAppointments(dateSpan);

				isInitialLoad = false;
			}
		}
Esempio n. 31
0
        public void Can_handle_composite_spans()
        {
            var start = new DateTime(2009, 9, 30);
            var end = new DateTime(2009, 10, 31);

            var span = new DateSpan(start, end);

            Assert.AreEqual(1, span.Months);
            Assert.AreEqual(1, span.Days);
        }
Esempio n. 32
0
        /// <summary>
        /// 1、开始绘图
        /// </summary>
        /// <param name="CreateNewExcelApp">是否要新开一个Excel程序</param>
        /// <param name="DrawDynamicDrawing">是否是要绘制动态曲线图</param>
        /// <param name="SelectedTags">选择的测点</param>
        /// <param name="RowNum_SelectedTags">选择的测点在Excel数据工作表中所在的行号</param>
        /// <remarks></remarks>
        private void Generate(bool CreateNewExcelApp, bool DrawDynamicDrawing,
                              string[] SelectedTags, int[] RowNum_SelectedTags)
        {
            // ----------arrDateRange----------------------- 获取此工作表中的整个施工日期的数组(0-Based,数据类型为Date)
            DateTime[] arrDateRange        = GetDate();
            double[]   arrDateRange_Double = new double[arrDateRange.Count() - 1 + 1];
            for (int i = 0; i <= arrDateRange.Count() - 1; i++)
            {
                arrDateRange_Double[i] = arrDateRange[i].ToOADate();
            }
            //-----------AllSelectedMonitorData------------ 获取所有"选择的"监测点位的监测数据的大数组。其中不包含选择的测点编号信息与施工日期的信息
            //此数组的第一个元素的下标值为0
            object[,] AllSelectedMonitorData = null;
            AllSelectedMonitorData           = GetAllSelectedMonitorData(this.F_shtMonitorData, RowNum_SelectedTags);

            //----------------- 设置监测曲线的时间跨度
            Array.Sort(arrDateRange);
            DateSpan Date_Span = new DateSpan();

            Date_Span.StartedDate  = arrDateRange[0];
            Date_Span.FinishedDate = arrDateRange[arrDateRange.Length - 1];

            //----------------------------打开用来绘图的Excel程序,并将此界面加入主程序的监测曲线集合
            Cls_ExcelForMonitorDrawing clsExcelForMonitorDrawing = null;

            //   --------------- 获取用来绘图的Excel程序,并将此界面加入主程序的监测曲线集合 -------------------
            F_AppDrawing = GetApplication(NewExcelApp: CreateNewExcelApp, ExcelForMntDrawing: clsExcelForMonitorDrawing, MntDrawingExcelApps:
                                          GlobalApplication.Application.MntDrawing_ExcelApps);
            F_AppDrawing.ScreenUpdating = false;
            //打开工作簿以画图
            if (F_AppDrawing.Workbooks.Count == 0)
            {
                F_wkbkDrawing = F_AppDrawing.Workbooks.Add();
            }
            else
            {
                F_wkbkDrawing = F_AppDrawing.Workbooks[1]; //总是定义为第一个,因为就只开了一个
            }
            //新开一个工作表以画图
            F_shtDrawing = F_wkbkDrawing.Worksheets.Add();
            F_shtDrawing.Activate();


            //-------  根据是要绘制动态的曲线图还是静态的曲线图,来执行不同的操作  ---------------------
            if (DrawDynamicDrawing)
            {
                //-------------绘制动态的曲线图--------------
                F_dicDate_ChosenDatum = GetdicDate_Datum_ForDynamic(arrDateRange, AllSelectedMonitorData);
                //开始画图
                F_Chart = DrawDynamicChart(F_dicDate_ChosenDatum, SelectedTags, AllSelectedMonitorData);
                //设置图表的Tag属性
                MonitorInfo Tags = GetChartTags(F_shtMonitorData);
                //-------------------------------------------------------------------------
                ClsDrawing_Mnt_OtherDynamics DynamicSheet = new ClsDrawing_Mnt_OtherDynamics(F_shtMonitorData, F_Chart,
                                                                                             clsExcelForMonitorDrawing, Date_Span,
                                                                                             DrawingType.Monitor_Dynamic, true, F_textbox_Info, Tags, this.F_MonitorType,
                                                                                             F_dicDate_ChosenDatum, this.F_TheFirstseriesTag);

                //-------------------------------------------------------------------------
            }
            else
            {
                //-------绘制静态的曲线图--------
                //开始画图
                Dictionary <Excel.Series, object[]> dicSeriesData = new Dictionary <Excel.Series, object[]>();
                F_Chart = DrawStaticChart(SelectedTags, arrDateRange_Double, AllSelectedMonitorData, dicSeriesData);
                //设置图表的Tag属性
                MonitorInfo Tags = GetChartTags(F_shtMonitorData);
                if (this.F_WorkingStage != null)
                {
                    DrawWorkingStage(this.F_Chart, this.F_WorkingStage);
                }
                //-------------------------------------------------------------------------
                ClsDrawing_Mnt_Static staticSheet = new ClsDrawing_Mnt_Static(F_shtMonitorData, F_Chart,
                                                                              clsExcelForMonitorDrawing,
                                                                              DrawingType.Monitor_Static, false, F_textbox_Info, Tags, this.F_MonitorType,
                                                                              dicSeriesData, arrDateRange_Double);

                //-------------------------------------------------------------------------
            }

            //---------------------- 界面显示与美化
            ExcelAppBeauty(F_shtDrawing.Application, CreateNewExcelApp);
        }
Esempio n. 33
0
        public void WeekendIsNotGap()
        {
            // Выходные дни: май 2013, 4,5    9   11,12
            // выходной
            var gap = new DateSpan(new DateTime(2013, 5, 4, 3, 51, 12),
                                                       new DateTime(2013, 5, 5, 1, 19, 0));

            var miniHoles = DaysOff.Instance.GetIntersected(gap);
            var gaps = QuoteCacheManager.SubtractPeriods(gap, miniHoles);
            Assert.AreEqual(gaps.Count, 0);

            // праздник
            gap = new DateSpan(new DateTime(2013, 5, 9, 3, 21, 0),
                                                       new DateTime(2013, 5, 9, 11, 19, 0));
            miniHoles = DaysOff.Instance.GetIntersected(gap);
            gaps = QuoteCacheManager.SubtractPeriods(gap, miniHoles);
            Assert.AreEqual(gaps.Count, 0);

            // гэп присутствует
            gap = new DateSpan(new DateTime(2013, 5, 5, 16, 30, 0),
                                                       new DateTime(2013, 5, 6, 8, 30, 0));
            miniHoles = DaysOff.Instance.GetIntersected(gap);
            Assert.AreNotEqual(miniHoles.Count, 0, "DaysOff.Instance.GetIntersected");
            gaps = QuoteCacheManager.SubtractPeriods(gap, miniHoles);

            Assert.AreNotEqual(gaps.Count, 0, "gaps");
            // закомментировал, т.к. пересекается с другими тестами
            //moq.Verify(lw => lw.GetMetadataByCategory(It.Is<string>(s => s == "DayOff")), Times.Once(),
            //    "выходные дни должны быть зачитаны из базы ровно один раз");
        }
Esempio n. 34
0
 public static DateTime Add(this DateTime date, DateSpan dateSpan)
 {
     return(dateSpan.AddTo(date));
 }
Esempio n. 35
0
 // создать список нерабочих интервалов, имеющих пересечение с заданным
 public List<DateSpan> GetIntersected(DateSpan interval)
 {
     var result = new List<DateSpan>();
     if (!valid)
         return result;
     DateTime beginInterval;
     if (format == "WD")
     {
         beginInterval = new DateTime(interval.start.Year, interval.start.Month, interval.start.Day, hour, 0, 0);
         // ищем первый периодический нерабочий интервал, пересекающийся с указанным,
         // соблюдая условие, что начало его раньше начала указанного
         var dayDelta = (int)interval.start.DayOfWeek - day;
         if (dayDelta < 0)
             dayDelta += 7;
         beginInterval = beginInterval.AddDays(-dayDelta);
         // dayDelta = 0 и возможно расхождение в часах
         if (beginInterval > interval.start)
             beginInterval = beginInterval.AddDays(-7); // convert to GetPrevDate/GetNextDate to calc periodic DateTime
         // этот нерабочий интервал не пересекается с указанным
         // подставляем следующий
         if (beginInterval.AddHours(duration) < interval.start)
             beginInterval = beginInterval.AddDays(7);
         while (beginInterval < interval.end)
         {
             result.Add(new DateSpan(beginInterval, beginInterval.AddHours(duration)));
             beginInterval = beginInterval.AddDays(7);
         }
     }
     else if (format == "D")
     {
         // непериодический интервал
         if (year.HasValue)
         {
             beginInterval = new DateTime(year.Value, month, day, hour, 0, 0);
             // есть пересечение
             if ((beginInterval > interval.start) || (beginInterval.AddHours(duration) < interval.end))
                 result.Add(new DateSpan(beginInterval, beginInterval.AddHours(duration)));
         }
         // периодический ежегодный интервал
         else
         {
             beginInterval = new DateTime(interval.start.Year, month, day, hour, 0, 0);
             if (beginInterval > interval.start)
                 beginInterval = beginInterval.AddYears(-1); // convert to GetPrevDate/GetNextDate to calc periodic DateTime
             if (beginInterval.AddHours(duration) < interval.start)
                 beginInterval = beginInterval.AddYears(1);
             while (beginInterval < interval.end)
             {
                 result.Add(new DateSpan(beginInterval, beginInterval.AddHours(duration)));
                 beginInterval = beginInterval.AddYears(1);
             }
         }
     }
     return result;
 }
Esempio n. 36
0
    protected void Page_Load (object sender, EventArgs e)
    {
        string fileName = "PPDK"+DateTime.Now.ToString("yyyyMMdd_HHmm")+".txt";

        if (Request.Browser.Browser == "IE" )
        {

            fileName = Server.UrlPathEncode(fileName);

            if (fileName != null) fileName = fileName.Replace(@"+", @"%20");

        }


        Response.ContentType = "text/plain";
        Response.ContentEncoding = Encoding.UTF8 ;

        //Response.ContentType = "application/octet-stream";

        Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");

       if (_authority.HasPermission(Permission.CanSeePeople, Organization.PPDKid, Geography.DenmarkId , Authorization.Flag.ExactGeographyExactOrganization))
        {
            StringBuilder sb = new StringBuilder();
            int org = "" + Request["o"] == "UP" ? Organization.UPDKid : Organization.PPDKid;
            People danishPeople = People.FromOrganizationAndGeography(org, Geography.RootIdentity);
            danishPeople = danishPeople.GetVisiblePeopleByAuthority(_authority).RemoveUnlisted();
            
            sb.Append("Identity");
            sb.Append("\tName");
            sb.Append("\tEmail");
            sb.Append("\tStreet");
            sb.Append("\tPostalCode");
            sb.Append("\tCity");
            sb.Append("\tCountry.Name");
            sb.Append("\tPhone");
            sb.Append("\tBirthdate");
            sb.Append("\tGender");
            sb.Append("\tGeography.Name");
            sb.Append("\tpp.start");
            sb.Append("\tpp.end");
            sb.Append("\tup.start");
            sb.Append("\tup.end");
            sb.Append("\r\n");
            foreach (Person p in danishPeople)
            {
                sb.Append(p.Identity);
                sb.Append("\t" + p.Name);
                sb.Append("\t" + p.Email);
                sb.Append("\t" + p.Street);
                sb.Append("\t" + p.PostalCode);
                sb.Append("\t" + p.CityName);
                sb.Append("\t" + p.Country.Name);
                sb.Append("\t" + p.Phone);
                sb.Append("\t" + p.Birthdate);
                sb.Append("\t" + p.Gender);
                sb.Append("\t" + p.Geography.Name);
                Memberships pMemberships = p.GetMemberships();
                DateSpan ppdkspan = null;
                DateSpan updkspan = null;
                foreach (Membership m in pMemberships)
                {
                    if (m.OrganizationId == Organization.PPDKid)
                        ppdkspan = new DateSpan(m.MemberSince, m.Expires);
                    else if (m.OrganizationId == Organization.UPDKid || m.Organization.Inherits(Organization.UPDKid))
                        updkspan = new DateSpan(m.MemberSince, m.Expires);
                }
                if (ppdkspan != null)
                {
                    sb.Append("\t" + ppdkspan.start);
                    sb.Append("\t" + ppdkspan.end);
                }
                else
                    sb.Append("\t\t");

                if (updkspan != null)
                {
                    sb.Append("\t" + updkspan.start);
                    sb.Append("\t" + updkspan.end);
                }
                else
                    sb.Append("\t\t");
                sb.Append("\r\n");
            }

        Response.Write(sb.ToString());
        }
    }
Esempio n. 37
0
        // создать список нерабочих интервалов, имеющих пересечение с заданным
        public List <DateSpan> GetIntersected(DateSpan interval)
        {
            var result = new List <DateSpan>();

            if (!valid)
            {
                return(result);
            }
            DateTime beginInterval;

            if (format == "WD")
            {
                beginInterval = new DateTime(interval.start.Year, interval.start.Month, interval.start.Day, hour, 0, 0);
                // ищем первый периодический нерабочий интервал, пересекающийся с указанным,
                // соблюдая условие, что начало его раньше начала указанного
                var dayDelta = (int)interval.start.DayOfWeek - day;
                if (dayDelta < 0)
                {
                    dayDelta += 7;
                }
                beginInterval = beginInterval.AddDays(-dayDelta);
                // dayDelta = 0 и возможно расхождение в часах
                if (beginInterval > interval.start)
                {
                    beginInterval = beginInterval.AddDays(-7); // convert to GetPrevDate/GetNextDate to calc periodic DateTime
                }
                // этот нерабочий интервал не пересекается с указанным
                // подставляем следующий
                if (beginInterval.AddHours(duration) < interval.start)
                {
                    beginInterval = beginInterval.AddDays(7);
                }
                while (beginInterval < interval.end)
                {
                    result.Add(new DateSpan(beginInterval, beginInterval.AddHours(duration)));
                    beginInterval = beginInterval.AddDays(7);
                }
            }
            else if (format == "D")
            {
                // непериодический интервал
                if (year.HasValue)
                {
                    beginInterval = new DateTime(year.Value, month, day, hour, 0, 0);
                    // есть пересечение
                    if ((beginInterval > interval.start) || (beginInterval.AddHours(duration) < interval.end))
                    {
                        result.Add(new DateSpan(beginInterval, beginInterval.AddHours(duration)));
                    }
                }
                // периодический ежегодный интервал
                else
                {
                    beginInterval = new DateTime(interval.start.Year, month, day, hour, 0, 0);
                    if (beginInterval > interval.start)
                    {
                        beginInterval = beginInterval.AddYears(-1); // convert to GetPrevDate/GetNextDate to calc periodic DateTime
                    }
                    if (beginInterval.AddHours(duration) < interval.start)
                    {
                        beginInterval = beginInterval.AddYears(1);
                    }
                    while (beginInterval < interval.end)
                    {
                        result.Add(new DateSpan(beginInterval, beginInterval.AddHours(duration)));
                        beginInterval = beginInterval.AddYears(1);
                    }
                }
            }
            return(result);
        }