示例#1
0
文件: Pivot.cs 项目: shine8319/DLS
        void Initialize() {
            this.dataProvider = DataSource.GetDataProvider();
            this.range = this.currentRange = DateTimeUtils.GetOneYearRange();
            ucSales.Diagram.AxisY.Visibility = Utils.DefaultBoolean.False;
            ucSales.Diagram.AxisX.Visibility = Utils.DefaultBoolean.False;
            ucUnits.Diagram.AxisY.Visibility = Utils.DefaultBoolean.False;
            ucUnits.Diagram.AxisX.Visibility = Utils.DefaultBoolean.False;
            ucUnits.Diagram.Margins.All = 0;
            ucUnits.Diagram.Rotated = true;
            ucUnits.chart.Legend.AlignmentVertical = LegendAlignmentVertical.Top;
            ucUnits.chart.Legend.AlignmentHorizontal = LegendAlignmentHorizontal.RightOutside;

            ucUnits.chart.Legend.Border.Visibility = Utils.DefaultBoolean.False;
            ucUnits.chart.Legend.Margins.Right = 0;
            ucUnits.chart.Legend.MarkerSize = new System.Drawing.Size(18, 18);
            ucUnits.chart.Legend.MarkerVisible = true;
            ucUnits.chart.Legend.TextOffset = 8;
            ucUnits.chart.Legend.VerticalIndent = 4;
            ucUnits.chart.Legend.Visibility = Utils.DefaultBoolean.True;
            ucUnits.chart.Series[0].LegendTextPattern = "{A}";
            ucSales.Diagram.Margins.All = 0;

            Palette palette = ChartUtils.GeneratePalette();
            this.rangeControlClient = new RangeControlSalesClient(palette[3].Color);
            this.rangeControlClient.YearMonth = true;
            rangeControl.Client = this.rangeControlClient;
            IEnumerable<SalesGroup> sales = dataProvider.GetSales(range.Start, range.End, GroupingPeriod.Day);
            this.rangeControlClient.UpdateData(sales);

        }
        public void TestRoundRangeToInterval()
        {
            DateTime startDate = new DateTime(2008, 05, 1, 10, 2, 3, 4, DateTimeKind.Utc);
            DateTime startRounded1 = new DateTime(2008, 05, 1, 10, 2, 0, 0, DateTimeKind.Utc);
            DateTime startRounded15 = new DateTime(2008, 05, 1, 10, 0, 0, 0, DateTimeKind.Utc);
            DateTime endDate = new DateTime(2008, 05, 1, 11, 2, 3, 4, DateTimeKind.Utc);
            DateTime endRounded1 = new DateTime(2008, 05, 1, 11, 3, 0, 0, DateTimeKind.Utc);
            DateTime endRounded15 = new DateTime(2008, 05, 1, 11, 15, 0, 0, DateTimeKind.Utc);

            DateTimeRange range = new DateTimeRange(startDate, endDate);
            DateTimeRange rounded = DateUtil.RoundRangeToInterval(range, 1);
            Assert.AreEqual(rounded.Start, startRounded1);
            Assert.AreEqual(rounded.End, endRounded1);

            DateTimeRange twiceRounded = DateUtil.RoundRangeToInterval(rounded, 1);
            Assert.AreEqual(rounded.Start, twiceRounded.Start);
            Assert.AreEqual(rounded.End, twiceRounded.End);

            rounded = DateUtil.RoundRangeToInterval(range, 15);
            Assert.AreEqual(rounded.Start, startRounded15);
            Assert.AreEqual(rounded.End, endRounded15);

            twiceRounded = DateUtil.RoundRangeToInterval(rounded, 15);
            Assert.AreEqual(rounded.Start, twiceRounded.Start);
            Assert.AreEqual(rounded.End, twiceRounded.End);
        }
示例#3
0
 public void NotEqualSamePrecisionHourTest()
 {
     var d1 = new DateTimeRange(new DateTime(2011, 4, 4, 10, 34, 10), DateTimeRange.PrecisionType.Hours);
     var d2 = new DateTimeRange(new DateTime(2011, 4, 4, 11, 20, 10), DateTimeRange.PrecisionType.Hours);
     Assert.AreNotEqual(d1, d2);
     Assert.AreNotEqual(d2, d1);
 }
示例#4
0
 public void EqualDifferentPrecisionHourMinuteTest()
 {
     var d1 = new DateTimeRange(new DateTime(2011, 4, 4, 10, 34, 10), DateTimeRange.PrecisionType.Minutes);
     var d2 = new DateTimeRange(new DateTime(2011, 4, 4, 10, 1, 4), DateTimeRange.PrecisionType.Hours);
     Assert.AreEqual(d1, d2);
     Assert.AreEqual(d2, d1);
 }
示例#5
0
        public bool TryGetCrossRange(DateTimeRange range, out DateTimeRange? crossRange)
        {
            crossRange = null;
            if (!IsIntersect(range)) return false;

            // Range полностью лежит в периоде
            if (range.Begin >= Begin && range.End <= End)
            {
                crossRange = range;
                return true;
            }

            // Период анализируемый период слева
            if (range.Begin < Begin && range.End <= End)
            {
                crossRange = new DateTimeRange(Begin, range.End);
                return true;
            }

            // Период нарушения пересекает период справа
            if (range.Begin >= Begin && range.End > End)
            {
                crossRange = new DateTimeRange(range.Begin, End);
                return true;
            }

            // Период полностью лежит в периоде нарушения
            crossRange = this;
            return true;
        }
        public void TestSortedIntervalTree()
        {
            DateTimeRange r0 = new DateTimeRange(baseDate, baseDate.AddHours(2));
            DateTimeRange r1 = new DateTimeRange(baseDate, baseDate.AddHours(4));
            DateTimeRange r2 = new DateTimeRange(baseDate, baseDate.AddHours(7));
            DateTimeRange r3 = new DateTimeRange(baseDate.AddHours(3), baseDate.AddHours(3));
            DateTimeRange r4 = new DateTimeRange(baseDate.AddHours(4), baseDate.AddHours(12));
            DateTimeRange r5 = new DateTimeRange(baseDate.AddHours(5), baseDate.AddHours(7));

            tree.Insert(r0, r0);
            tree.Insert(r1, r1);
            tree.Insert(r2, r2);
            tree.Insert(r3, r3);
            tree.Insert(r4, r4);
            tree.Insert(r5, r5);

            Assert.AreEqual(6, tree.NumNodes);
            Assert.AreEqual(5, tree.MaxDepth); // TODO

            DateTimeRange s0 = new DateTimeRange(baseDate.AddHours(1), baseDate.AddHours(1));
            List<DateTimeRange> result = tree.FindAll(s0);

            Assert.AreEqual(3, result.Count);
            Assert.AreEqual(r0, result[0]);
            Assert.AreEqual(r1, result[1]);
            Assert.AreEqual(r2, result[2]);
        }
        /// <summary>
        /// Returns the free busy times for the specified exchange users
        /// </summary>
        /// <param name="users">The user which free/busy blocks will be looked up for</param>
        /// <param name="window">The time period to look up FB info for</param>
        /// <returns></returns>
        public Dictionary<ExchangeUser, FreeBusy> LookupFreeBusyTimes(
            ExchangeUserDict users,
            DateTimeRange window )
        {
            /* Create an array of mailboxes to retrieve from exchange */
            Dictionary<ExchangeUser, FreeBusy> result = new Dictionary<ExchangeUser, FreeBusy>();

            try
            {
                using (BlockTimer bt = new BlockTimer("LookupFreeBusyTimes"))
                {
                    /* Perform the retrieval of free busy times through WebDav */
                    result = webDavQuery.LoadFreeBusy(exchangeServerUrl, users, window);
                }
            }
            catch (Exception ex)
            {
                throw new GCalExchangeException(
                    GCalExchangeErrorCode.ExchangeUnreachable,
                   "Error occured while retrieving free busy ranges",
                   ex);
            }

            return result;
        }
        public IList<Portrait> GetPortraits(int cameraId, DateTimeRange range)
        {
            var portraits = from f in System.IO.Directory.GetFiles(this._directoryPath, "*.jpg")
                            select new Portrait(f);

            return portraits.ToList();
        }
        /// <summary>
        /// Generates a response from a GCalRequest
        /// </summary>
        /// <returns></returns>
        public string GenerateResponse()
        {
            /* Create a string builder to hold the text for the response */
            StringBuilder result = new StringBuilder(4096);

            /* Create an exchange provider */
            ExchangeService gateway = new ExchangeService(
                ConfigCache.ExchangeServerUrl,
                ConfigCache.ExchangeUserLogin,
                ConfigCache.ExchangeUserPassword);

            /* Return the exchangers from the GCal Request that was passed in */
            DateTimeRange range = new DateTimeRange(request.UTCStartDate, request.UTCEndDate);
            ExchangeUserDict exchangeUsers = gateway.SearchByEmail(range, request.ExchangeUsers);

            /* Create the header of the request */
            result.AppendFormat("['{0}','{1}',", request.VersionNumber, request.MessageId);

            result.AppendFormat("['_ME_AddData','{0}/{1}','{2}'",
                                DateUtil.FormatDateForGoogle(request.StartDate),
                                DateUtil.FormatDateForGoogle(request.EndDate),
                                DateUtil.FormatDateTimeForGoogle(request.Since));

            /* Flag for inserting commas */
            bool firstUser = true;

            result.Append(",[");

            foreach (ExchangeUser user in exchangeUsers.Values)
            {
                /* Don't add a comma if this is the first user */
                if (!firstUser)
                {
                    result.Append(",");
                }

                /* Add the user's credentials */
                string email = ConfigCache.MapToExternalDomain(user.Email);
                result.AppendFormat("'{0}','{1}','{2}',[",
                                    user.DisplayName,
                                    email,
                                    (int)user.AccessLevel);

                GenerateResponseForTimeBlocks(user,
                                              result);

                result.Append("]");
                firstUser = false;
            }

            result.Append("]");
            result.Append("]");
            result.Append("]");

            log.Info("GCal Free/Busy response successfully generated.");
            log.DebugFormat("Response = {0}", result);

            return result.ToString();
        }
    public Task<IReadOnlyList<EntityIdWithVersion<Uri, string>>> GetTodos (DateTimeRange? range)
    {
      if (range != null)
        throw new NotSupportedException ("range not supported");

      return Task.FromResult<IReadOnlyList<EntityIdWithVersion<Uri, string>>> (
          _entites.Select (e => EntityIdWithVersion.Create (e.Key, e.Value.Item1)).ToList());
    }
示例#11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Appointment"/> class.
        /// </summary>
        /// <param name="staff">The staff.</param>
        /// <param name="appointmentDateTimeRange">The appointment date time range.</param>
        protected internal Appointment( Staff staff, DateTimeRange appointmentDateTimeRange )
        {
            Check.IsNotNull ( staff, "Staff is required." );
            Check.IsNotNull ( appointmentDateTimeRange, "AppointmentDateTimeRange is required." );

            _staff = staff;
            _appointmentDateTimeRange = appointmentDateTimeRange;
        }
示例#12
0
        /// <summary>
        /// Creates the appointment.
        /// </summary>
        /// <param name="staff">
        /// The staff.
        /// </param>
        /// <param name="appointmentDateTimeRange">
        /// The appointment date time range.
        /// </param>
        /// <returns>
        /// An Appointment.
        /// </returns>
        public Appointment CreateAppointment( Staff staff, DateTimeRange appointmentDateTimeRange )
        {
            var appointment = new Appointment ( staff, appointmentDateTimeRange );

            _appointmentRepository.MakePersistent ( appointment );

            return appointment;
        }
        public void TestDateTimeRange()
        {
            DateTimeRange range = new DateTimeRange(startDate, endDate);
            DateTimeRange compareRange = new DateTimeRange(startDate, endDate);

            Assert.AreEqual(startDate, range.Start);
            Assert.AreEqual(endDate, range.End);
            Assert.AreEqual(range, compareRange);
            Assert.AreEqual(range.GetHashCode(), compareRange.GetHashCode());
        }
示例#14
0
        public void DateTimeRangeTest_Ctor()
        {
            DateTimeRange range = new DateTimeRange();
            Assert.AreEqual(range.StartTime, DateTime.MinValue);
            Assert.AreEqual(range.EndTime, DateTime.MaxValue);

            DateTime now = new DateTime(2015, 8, 7, 11, 15, 22);
            range = new DateTimeRange(now.Date.AddDays(-1), now.Date.AddDays(2));
            Assert.AreEqual(range.StartTime.Day, 6);
            Assert.AreEqual(range.EndTime.Day, 9);
        }
        public void LoadVideo()
        {
            var selectedCamera = this._screen.SelectedCamera;
            if (selectedCamera == null)
            {
                return;
            }

            var range = this._screen.TimeRange;
            var type = this._screen.SearchScope;
            var frameQuery = _portraitRepository.GetFrames(selectedCamera.Id, range).ToArray();
            var portraitQuery = _portraitRepository.GetPortraits(selectedCamera.Id, range).ToArray();
            Core.Video v;
            this._screen.ClearAll();

            for (int i = currentPage * PageSize; i < currentPage * PageSize + PageSize; i++)
            {
                if (i >= TotalCount)
                {
                    break;
                }
                v = TotalVideos[i];
                var queryTime = new DateTimeRange(v.CapturedAt, v.CapturedAt);
                v.HasMotionDetected = frameQuery.FirstOrDefault(f => f.CapturedAt.RoundToMinute() == v.CapturedAt.RoundToMinute()) != null;
                v.HasFaceCaptured = portraitQuery.FirstOrDefault(p => p.CapturedAt.RoundToMinute() == v.CapturedAt.RoundToMinute()) != null;
                if ((type & SearchScope.FaceCapturedVideo)
                      == SearchScope.FaceCapturedVideo)
                {
                    if (v.HasFaceCaptured)
                    {
                        _screen.AddVideo(v);
                    }
                }

                if ((type & SearchScope.MotionWithoutFaceVideo)
                     == SearchScope.MotionWithoutFaceVideo)
                {
                    if (v.HasMotionDetected && !v.HasFaceCaptured)
                    {
                        _screen.AddVideo(v);
                    }
                }

                if ((type & SearchScope.MotionLessVideo)
                      == SearchScope.MotionLessVideo)
                {
                    if (!v.HasFaceCaptured && !v.HasMotionDetected)
                    {
                        _screen.AddVideo(v);
                    }
                }

            }
        }
示例#16
0
        /// <summary>
        /// Creates the visit.
        /// </summary>
        /// <param name="staff">The staff.</param>
        /// <param name="appointmentDateTimeRange">The appointment date time range.</param>
        /// <param name="clinicalCase">The clinical case.</param>
        /// <param name="visitTemplate">The visit template.</param>
        /// <param name="serviceLocation">The service location.</param>
        /// <returns>
        /// A Visit.
        /// </returns>
        public Visit CreateVisit(Staff staff, 
            DateTimeRange appointmentDateTimeRange,
            ClinicalCase clinicalCase,
            VisitTemplate visitTemplate,
            Location serviceLocation )
        {
            var visitStatus = _visitStatusRepository.GetByWellKnownName ( WellKnownNames.VisitModule.VisitStatus.Scheduled );
            var visit = new Visit (staff, appointmentDateTimeRange, clinicalCase, visitStatus, serviceLocation, visitTemplate.Name, visitTemplate.CptCode );

            _visitRepository.MakePersistent ( visit );
            return visit;
        }
        public void TestOverlapsAndContains()
        {
            DateTime date7AM = new DateTime(2007, 1, 1, 7, 0, 0);
            DateTime date8AM = new DateTime(2007, 1, 1, 8, 0, 0);
            DateTime date9AM = new DateTime(2007, 1, 1, 9, 0, 0);
            DateTime date10AM = new DateTime(2007, 1, 1, 10, 0, 0);

            DateTimeRange range7AM8AM = new DateTimeRange(date7AM, date8AM);
            DateTimeRange range9AM10AM = new DateTimeRange(date9AM, date10AM);

            // The first test case is
            // 7-8  [.....]
            // 9-10           [.....]
            // Don't intersect and don't contain
            Assert.IsFalse(range7AM8AM.Overlaps(range9AM10AM));
            Assert.IsFalse(range9AM10AM.Overlaps(range7AM8AM));
            Assert.IsFalse(range7AM8AM.Contains(range9AM10AM));
            Assert.IsFalse(range9AM10AM.Contains(range7AM8AM));

            DateTimeRange range7AM10AM = new DateTimeRange(date7AM, date10AM);
            DateTimeRange range8AM9AM = new DateTimeRange(date8AM, date9AM);

            // The second test case is
            // 7-10 [...............]
            // 8-9       [.....]
            // Intersect, the bigger contains the smaller
            Assert.IsTrue(range7AM10AM.Overlaps(range8AM9AM));
            Assert.IsTrue(range8AM9AM.Overlaps(range7AM10AM));
            Assert.IsTrue(range7AM10AM.Contains(range8AM9AM));
            Assert.IsFalse(range8AM9AM.Contains(range7AM10AM));

            // The third test case is
            // 8-9       [.....]
            // 9-10           [.....]
            // Intersect (touch), don't contain each other
            Assert.IsTrue(range8AM9AM.Overlaps(range9AM10AM));
            Assert.IsTrue(range9AM10AM.Overlaps(range8AM9AM));
            Assert.IsFalse(range8AM9AM.Contains(range9AM10AM));
            Assert.IsFalse(range9AM10AM.Contains(range8AM9AM));

            DateTimeRange range7AM9AM = new DateTimeRange(date7AM, date9AM);
            DateTimeRange range8AM10AM = new DateTimeRange(date8AM, date10AM);

            // The forth test case is
            // 7-9  [..........]
            // 9-10      [..........]
            // Intersect, don't contain each other
            Assert.IsTrue(range7AM9AM.Overlaps(range8AM10AM));
            Assert.IsTrue(range8AM10AM.Overlaps(range7AM9AM));
            Assert.IsFalse(range7AM9AM.Contains(range8AM10AM));
            Assert.IsFalse(range8AM10AM.Contains(range7AM9AM));
        }
        public static ExchangeUserDict QueryFreeBusy(string email)
        {
            ExchangeService gw = new ExchangeService(
                ConfigCache.ExchangeServerUrl,
                ConfigCache.ExchangeUserLogin,
                ConfigCache.ExchangeUserPassword );

            DateTimeRange range = new DateTimeRange(
                DateUtil.NowUtc.AddDays(-7),
                DateUtil.NowUtc.AddDays(+7));

            return gw.SearchByEmail( range, email );
        }
 public void TestConvertEventsToFreeBusy()
 {
     ExchangeUser user = new ExchangeUser();
     EventEntry googleAppsEvent = new EventEntry("title", "description", "location");
     DateTimeRange coveredRange = new DateTimeRange(DateTime.MaxValue, DateTime.MinValue);
     List<DateTimeRange> busyTimes = new List<DateTimeRange>();
     List<DateTimeRange> tentativeTimes = new List<DateTimeRange>();
     DateTime startDate = new DateTime(2007, 07, 1, 10, 0, 0, DateTimeKind.Utc);
     DateTime endDate = new DateTime(2007, 07, 1, 11, 0, 0, DateTimeKind.Utc);
     When when = new When(startDate, endDate);
     Uri uri = new Uri("https://www.google.com/calendar/feeds/[email protected]/private/full");
     EventFeed googleAppsFeed = new EventFeed(uri, null);
     AtomEntryCollection entries = new AtomEntryCollection(googleAppsFeed);
 }
        public void FreeBusyUrls()
        {
            Assert.AreEqual(FreeBusyTestUrl, FreeBusyUrl.GenerateUrl(ExchangeServer, Organization, OrgUnit));
            Assert.AreEqual(FreeBusyFromDNUrl, FreeBusyUrl.GenerateUrlFromDN(ExchangeServer, LegacyDN));
            Assert.AreEqual(AdminGroupUrl, FreeBusyUrl.GenerateAdminGroupUrl(ExchangeServer, AdminGroup));

            ExchangeUserDict users = new ExchangeUserDict();
            users.Add(User1Email, createFauxUser("User1", User1Email));

            DateTimeRange range = new DateTimeRange(start, end);
            Assert.AreEqual(SingleUserFreeBusyUrl, FreeBusyUrl.GenerateFreeBusyLookupUrl(ExchangeServer, users, range, 15));

            users.Add(User2Email, createFauxUser("User2", User2Email));
            Assert.AreEqual(MultiUserFreeBusyUrl, FreeBusyUrl.GenerateFreeBusyLookupUrl(ExchangeServer, users, range, 15));
        }
        public AppointmentLookupFuture(
            ExchangeService exchange,
            ExchangeUserDict users,
            DateTimeRange window)
        {
            this.exchange = exchange;
            this.users = users;
            this.syncWindow = window;

            // Only do this if appointment
            // lookup is enabled
            if (ConfigCache.EnableAppointmentLookup)
            {
                this.start();
            }
        }
        public IEnumerable<DtoLicensePlateInfo> GetLicensePlatesBetween(int cameraId, DateTimeRange dateTimeRange)
        {
            return _db4oContainer.Query<DtoLicensePlateInfo>(l =>
                                                                 {

                                                                     var match = l.CaptureTime >= dateTimeRange.From &&
                                                                                 l.CaptureTime <= dateTimeRange.To;

                                                                     if (cameraId != -1)
                                                                     {
                                                                         match = match && l.CapturedFrom == cameraId;
                                                                     }
                                                                                 ;
                                                                     return match;
                                                                 });
        }
        public void TestDateCompare()
        {
            Assert.That(dateUnspec.CompareTo(dateLocal) == 0);
            Assert.That(dateUnspec.Equals(dateLocal));
            Assert.AreEqual(dateUnspec.GetHashCode(), dateLocal.GetHashCode());
            Assert.That(dateLocal.CompareTo(dateUnspec) == 0);
            Assert.That(dateLocal.Equals(dateUnspec));
            Assert.AreEqual(dateLocal.GetHashCode(), dateUnspec.GetHashCode());

            DateTimeRange rangeUnspec = new DateTimeRange(dateUnspec, dateUnspec);
            DateTimeRange rangeLocal = new DateTimeRange(dateLocal, dateLocal);

            Assert.That(rangeUnspec.CompareTo(rangeLocal) == 0);
            Assert.That(rangeUnspec.Equals(rangeLocal));
            Assert.AreEqual(rangeUnspec.GetHashCode(), rangeLocal.GetHashCode());
        }
        /// <summary>
        /// Sync a users free busy information between Google Calendar and the
        /// SchedulePlus Public Folder store
        /// </summary>
        /// <param name="user">The user to synchronize</param>
        /// <param name="googleAppsFeed">The Google Calendar events for the user</param>
        /// <param name="exchangeGateway">The Exchange Gateway to use</param>
        /// <param name="window">The DateTimeRange to synchronize for</param>
        public void SyncUser(
            ExchangeUser user,
            EventFeed googleAppsFeed,
            ExchangeService exchangeGateway,
            DateTimeRange window)
        {
            if (_log.IsInfoEnabled)
            {
                _log.InfoFormat("Creating F/B message.  [User={0}]", user.Email);
                _log.DebugFormat("The feed time zone is {0}", googleAppsFeed.TimeZone.Value);
            }

            string userFreeBusyUrl = FreeBusyUrl.GenerateUrlFromDN(_exchangeServerUrl,
                                                                   user.LegacyExchangeDN);

            List<string> busyMonthValues = new List<string>();
            List<string> busyBase64Data = new List<string>();
            List<string> tentativeMonthValues = new List<string>();
            List<string> tentativeBase64Data = new List<string>();

            ConvertEventsToFreeBusy(user,
                                    googleAppsFeed.Entries,
                                    window,
                                    busyMonthValues,
                                    busyBase64Data,
                                    tentativeMonthValues,
                                    tentativeBase64Data);



            string startDate = FreeBusyConverter.ConvertToSysTime(window.Start).ToString();
            string endDate = FreeBusyConverter.ConvertToSysTime(window.End).ToString();

            exchangeGateway.FreeBusy.CreateFreeBusyMessage(userFreeBusyUrl,
                                                           user.FreeBusyCommonName,
                                                           busyMonthValues,
                                                           busyBase64Data,
                                                           tentativeMonthValues,
                                                           tentativeBase64Data,
                                                           startDate,
                                                           endDate);

            if ( _log.IsInfoEnabled )
            {
                _log.Info( "Free/Busy message with the right properties created successfully." );
            }
        }
        public ExchangeGatewayTest() : base()
        {
            calendarUrl = ExchangeUtil.GetDefaultCalendarUrl(exchangeServer, "test");
            _freeBusy = new List<DateTimeRange>();
            _appointments = new List<Appointment>();

            DateTime start = DateUtil.ParseDateToUtc("2007-06-30T05:16:11.000Z");
            _window = new DateTimeRange(start, start.AddDays(60));

            // One hour block as free busy AND appointment
            _freeBusy.Add(new DateTimeRange(start.AddHours(2), start.AddHours(3)));
            _appointments.Add(createAppointment(start.AddHours(2), start.AddHours(3)));

            // Two adjacent appointments - one free busy event
            start = start.AddDays(5);

            _freeBusy.Add(new DateTimeRange(start, start.AddMinutes(60)));
            _appointments.Add(createAppointment(start, start.AddMinutes(30)));
            _appointments.Add(createAppointment(start.AddMinutes(30), start.AddMinutes(60)));

            // Add event only to Free Busy
            start = start.AddDays(4);

            _freeBusy.Add(new DateTimeRange(start.AddMinutes(30), start.AddMinutes(50)));

            // Add event only to Appointments
            start = start.AddDays(20);

            _appointments.Add(createAppointment(start.AddMinutes(45), start.AddMinutes(50)));

            // Add all day appointment
            start = DateUtil.ParseDateToUtc("2007-07-30T00:00:00.000Z");

            _appointments.Add(createAppointment(start, start.AddHours(24), true));
            _freeBusy.Add(new DateTimeRange(start, start.AddHours(24)));

            // Add two appointments that start at the same time,
            // one overlapping and one not
            start = start.AddDays(2);

            _appointments.Add(createAppointment(start, start.AddHours(2)));
            _appointments.Add(createAppointment(start, start.AddHours(6)));
            _freeBusy.Add(new DateTimeRange(start, start.AddHours(2)));

        }
        /// <summary>
        /// Returns appointments for the specified exchange user
        /// </summary>
        /// <param name="user">The user which appointments will be looked up for</param>
        /// <param name="window">The event window to return appointments for</param>
        /// <returns>The event appointments that were looked up</returns>
        public List<Appointment> Lookup(ExchangeUser user, DateTimeRange window)
        {
            /* Create a holder for appointments */
            List<Appointment> appointments = new List<Appointment>();
            if (!ConfigCache.EnableAppointmentLookup)
            {
                if (log.IsDebugEnabled)
                    log.DebugFormat("Appointment lookup supressed for {0}", user.Email );
                return appointments;
            }

            try
            {
                /* Attempt to retrieve the Exchanger user's appointments
                 * This may fail if there is a permissions issue for this user's calendar */
                string calendarUrl = ExchangeUtil.GetDefaultCalendarUrl(exchangeServerUrl, user);

                appointments = webDavQuery.LoadAppointments(calendarUrl, window.Start, window.End);
                user.AccessLevel = GCalAccessLevel.ReadAccess;
                user.HaveAppointmentDetail = true;

                log.InfoFormat(
                    "Appointments read succesfully for '{0}', setting access level to ReadAccess.",
                    user.Email );
            }
            catch (WebException ex)
            {
                log.InfoFormat("Appointment access denied for {0} - {1}", user.Email, ex);
            }
            catch (Exception ex)
            {
                string errorMessage = string.Format(
                    "Error occured while retrieving appointments for user '{0}'", user.Email );

                throw new GCalExchangeException(
                    GCalExchangeErrorCode.ExchangeUnreachable,
                    errorMessage,
                    ex);
            }

            return appointments;
        }
示例#27
0
        public static EventFeed QueryGCalFreeBusy(
            string gcalUserEmail)
        {
            IConnectionThrottle throttle = new FakeThrottle();
            GCalGateway gw = new GCalGateway(ConfigCache.GoogleAppsLogin,
                                             ConfigCache.GoogleAppsPassword,
                                             ConfigCache.GoogleAppsDomain,
                                             throttle);

            DateTime now = DateTime.Now;
            DateTime start = now.AddDays(-7);
            DateTime end = now.AddDays(+7);
            DateTimeRange range = new DateTimeRange(start, end);

            EventFeed feed = gw.QueryGCal(gcalUserEmail,
                                          GCalVisibility.Private,
                                          GCalProjection.FreeBusy,
                                          DateTime.MinValue,
                                          range);
            return feed;
        }
示例#28
0
 private Order()
 {
     OrderProducts = new List <OrderProduct>();
     DispatchDate  = new DateTimeRange(DateTime.Now, DateTime.Now);
 }
示例#29
0
 /// <summary>
 /// Get the set of appointments from the collection
 /// with the matching date time range.
 /// </summary>
 /// <param name="r">DateRange to match against</param>
 /// <returns>The set of appointments with matching range</returns>
 public List <Appointment> Get(DateTimeRange r)
 {
     return(this.ContainsKey(r) ?
            this[r] : new List <Appointment>());
 }
示例#30
0
        private void addBtn_Click(object sender, EventArgs e)
        {
            bool allSucceed = true;

            try
            {
                ServicePriority servicePriority      = ServicePriority.Low;
                Edge.Core.SettingsCollection options = new Edge.Core.SettingsCollection();
                DateTime targetDateTime = new DateTime(dateToRunPicker.Value.Year, dateToRunPicker.Value.Month, dateToRunPicker.Value.Day, timeToRunPicker.Value.Hour, timeToRunPicker.Value.Minute, 0);
                bool     result         = false;

                if (priorityCmb.SelectedItem != null)
                {
                    switch (priorityCmb.SelectedItem.ToString())
                    {
                    case "Low":
                    {
                        servicePriority = ServicePriority.Low;
                        break;
                    }

                    case "Normal":
                    {
                        servicePriority = ServicePriority.Normal;
                        break;
                    }

                    case "High":
                    {
                        servicePriority = ServicePriority.High;
                        break;
                    }

                    case "Immediate":
                    {
                        servicePriority = ServicePriority.Immediate;
                        break;
                    }
                    }
                }
                int countedSelectedServices = 0;
                foreach (TreeNode accountNode in servicesTreeView.Nodes)
                {
                    foreach (TreeNode serviceNode in accountNode.Nodes)
                    {
                        if (serviceNode.Checked)
                        {
                            countedSelectedServices++;
                            AccountElement       account = (AccountElement)accountNode.Tag;
                            ActiveServiceElement service = (ActiveServiceElement)serviceNode.Tag;
                            if (useOptionsCheckBox.Checked)
                            {
                                foreach (ListViewItem item in optionsListView.Items)
                                {
                                    options.Add(item.SubItems[0].Text.Trim(), item.SubItems[1].Text.Trim());
                                }

                                DateTime from = FromPicker.Value;
                                DateTime to   = toPicker.Value;
                                if (to.Date < from.Date || to.Date > DateTime.Now.Date)
                                {
                                    throw new Exception("to date must be equal or greater then from date, and both should be less then today's date");
                                }

                                if (chkBackward.Checked)
                                {
                                    while (from.Date <= to.Date)
                                    {
                                        //For backward compatbility
                                        options["Date"] = from.ToString("yyyyMMdd");
                                        result          = _listner.FormAddToSchedule(service, account, targetDateTime, options, servicePriority);
                                        options.Clear();
                                        if (!result)
                                        {
                                            allSucceed = result;
                                            MessageBox.Show(string.Format("Service {0} for account {1} did not run", service.Name, accountNode.Text));
                                        }
                                        from = from.AddDays(1);
                                    }
                                }
                                else
                                {
                                    DateTimeRange daterange = new DateTimeRange()
                                    {
                                        Start = new DateTimeSpecification()
                                        {
                                            BaseDateTime = from,
                                            Hour         = new DateTimeTransformation()
                                            {
                                                Type = DateTimeTransformationType.Exact, Value = 0
                                            },
                                        },
                                        End = new DateTimeSpecification()
                                        {
                                            BaseDateTime = to,
                                            Hour         = new DateTimeTransformation()
                                            {
                                                Type = DateTimeTransformationType.Max
                                            },
                                        }
                                    };
                                    options.Add(PipelineService.ConfigurationOptionNames.TimePeriod, daterange.ToAbsolute().ToString());
                                    result = _listner.FormAddToSchedule(service, account, targetDateTime, options, servicePriority);
                                    options.Clear();
                                    if (!result)
                                    {
                                        allSucceed = result;
                                        MessageBox.Show(string.Format("Service {0} for account {1} did not run", service.Name, accountNode.Text));
                                    }
                                }
                            }
                            else
                            {
                                result = _listner.FormAddToSchedule(service, account, targetDateTime, options, servicePriority);
                                if (!result)
                                {
                                    allSucceed = result;
                                }
                            }
                        }
                    }
                }
                if (!allSucceed)
                {
                    throw new Exception("Some services did not run");
                }
                else
                {
                    if (countedSelectedServices > 0)
                    {
                        MessageBox.Show(@"Unplaned service\services added successfully");
                    }
                    else
                    {
                        MessageBox.Show(@"No services selected");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 EmployerMemberViewingReport IEmployerMemberAccessReportsQuery.GetEmployerMemberViewingReport(Channel channel, DateTimeRange timeRange)
 {
     return(new EmployerMemberViewingReport
     {
         TotalViewings = _repository.GetMemberViewings(channel, timeRange),
         DistinctViewings = _repository.GetDistinctMemberViewings(channel, timeRange),
         AnonymousViewings = _repository.GetAnonymousMemberViewings(channel, timeRange),
     });
 }
 int IEmployerMemberAccessReportsQuery.GetEmployerAccesses(Guid employerId, MemberAccessReason reason, DateTimeRange timeRange)
 {
     return(_repository.GetEmployerAccesses(employerId, reason, timeRange));
 }
 IDictionary <Guid, int> IEmployerMemberAccessReportsQuery.GetEmployerAccesses(IEnumerable <Guid> employerIds, MemberAccessReason reason, DateTimeRange timeRange)
 {
     return(_repository.GetEmployerAccesses(employerIds, reason, timeRange));
 }
 int IEmployerMemberAccessReportsQuery.GetMemberViewings(Guid memberId, DateTimeRange timeRange)
 {
     return(_repository.GetMemberViewings(memberId, timeRange));
 }
        /// <summary>
        /// Worker to query one aggregate of a topology
        /// </summary>
        /// <param name="aggregateIndex">The aggregation view to update by the worker</param>
        /// <param name="token">CancellationToken</param>
        public async Task Worker(int aggregateIndex, CancellationToken token)
        {
            RDXOpcUaQueries  opcUaQueries  = new RDXOpcUaQueries(token);
            RDXOeeKpiQueries oeeKpiQueries = new RDXOeeKpiQueries(opcUaQueries, token);

            RDXTrace.TraceInformation("RDX Worker {0} started", aggregateIndex);

            // give app some time to start before updating queries
            await Task.Delay(10000 *(aggregateIndex + 1));

            while (!token.IsCancellationRequested)
            {
                Stopwatch stopWatch         = new Stopwatch();
                DateTime  nextUpdate        = DateTime.MaxValue;
                bool      resetStartDelayed = false;

                stopWatch.Start();

                Interlocked.Increment(ref _busyWorkers);

                // the station and node list is updated, other workers are delayed
                while (_workerStartDelayed != 0)
                {
                    RDXTrace.TraceInformation("RDX Worker {0} delayed", aggregateIndex);
                    await Task.Delay(1000);
                }

                try
                {
                    List <Task>         tasks    = new List <Task>();
                    ContosoTopologyNode rootNode = _topology.GetRootNode();
                    ContosoAggregatedOeeKpiHistogram aggregatedTimeSpan = rootNode[aggregateIndex];
                    DateTimeRange searchSpan = RDXUtils.TotalSearchRangeFromNow(aggregatedTimeSpan);

                    RDXTrace.TraceInformation("RDX Worker {0} updating Range {1} to {2}",
                                              aggregateIndex, searchSpan.From, searchSpan.To);

                    // calc next update. To time is already rounded for update time span.
                    nextUpdate = searchSpan.To + rootNode[aggregateIndex].UpdateTimeSpan;

                    // query all stations in topology and find all active servers in timespan
                    Task <StringDimensionResult> aggServerTask = opcUaQueries.AggregateServers(searchSpan);

                    // always get an aggregate of all activity for the latest interval, use it as a cache
                    TimeSpan                 intervalTimeSpan = aggregatedTimeSpan[0].IntervalTimeSpan;
                    DateTimeRange            aggregateSpan    = RDXUtils.CalcAggregationRange(aggregatedTimeSpan, searchSpan.To);
                    RDXCachedAggregatedQuery fullQuery        = new RDXCachedAggregatedQuery(opcUaQueries);
                    Task aggServerAndNodesTask = fullQuery.Execute(aggregateSpan);

                    // wait for all outstanding aggregates
                    tasks.Add(aggServerTask);
                    tasks.Add(aggServerAndNodesTask);
                    await RDXUtils.WhenAllTasks("Aggregates", tasks, stopWatch);

                    fullQuery.UpdateCacheQueryResult();

                    List <string> topologyStations = _topology.GetAllChildren(_tree.TopologyRoot.Key, typeof(Station));
                    List <string> opcUaServers     = await aggServerTask;

                    // intersect list of active servers and schedule all queries
                    tasks.Clear();
                    List <string> opcUaServersToQuery = opcUaServers.Intersect(topologyStations, StringComparer.InvariantCultureIgnoreCase).ToList();
                    // query known servers
                    await oeeKpiQueries.ScheduleAllOeeKpiQueries(searchSpan, _topology, fullQuery, opcUaServersToQuery, tasks, aggregateIndex);

                    // wait for all outstanding queries
                    await RDXUtils.WhenAllTasks("Queries", tasks, stopWatch);

                    // Update the topology Oee and KPI values
                    _topology.UpdateAllKPIAndOEEValues(aggregateIndex);

                    // one worker issues the Browser update
                    if (aggregatedTimeSpan.UpdateBrowser)
                    {
                        // Push updates to dashboard
                        try
                        {
                            TriggerSessionOeeKpiDataUpdate();
                            TriggerSessionAlertDataUpdate();
                            TriggerSessionChildrenDataUpdate();
                        }
                        catch (Exception e)
                        {
                            RDXTrace.TraceError($"Exception {e.Message} in Worker while updating browser sessions");
                        }
                    }

                    // add new stations and nodes to topology
                    if (aggregatedTimeSpan.UpdateTopology)
                    {
                        // delay other workers
                        Interlocked.Exchange(ref _workerStartDelayed, 1);
                        resetStartDelayed = true;
                        // only add stations and nodes if no other worker is busy yet
                        if (Interlocked.Increment(ref _busyWorkers) == 2)
                        {
                            AddNewServers(fullQuery, topologyStations);
                            await AddNewNodes(fullQuery, topologyStations);

                            RDXTrace.TraceInformation("Add New Server and Nodes finished after {0}ms",
                                                      stopWatch.ElapsedMilliseconds);
                        }
                    }
                }
                catch (Exception e)
                {
                    RDXTrace.TraceError("Exception {0} in Worker after {1}ms",
                                        e.Message, stopWatch.ElapsedMilliseconds);
                }
                finally
                {
                    Interlocked.Decrement(ref _busyWorkers);
                    if (resetStartDelayed)
                    {
                        Interlocked.Decrement(ref _busyWorkers);
                        Interlocked.Exchange(ref _workerStartDelayed, 0);
                    }
                }

                RDXTrace.TraceInformation("RDX Worker {0} schedule next update for {1}",
                                          aggregateIndex, nextUpdate);

                TimeSpan delay = nextUpdate.Subtract(DateTime.UtcNow);
                if (delay.TotalMilliseconds > 0)
                {
                    await Task.Delay(delay, token);
                }
            }
        }
 /// <summary>
 /// Get the aggregated query of a specific search span.
 /// </summary>
 /// <param name="searchSpan">Date and time span for the query</param>
 /// <returns>Aggregated query or null if not found</returns>
 public RDXCachedAggregatedQuery Find(DateTimeRange searchSpan)
 {
     return(List.Find(x => x.SearchSpan == searchSpan));
 }
示例#37
0
        /// <summary>
        /// Merges a users appointment schedule from with appointments generated from a
        /// GoogleApps feed
        /// </summary>
        /// <param name="user">User to update with Google Apps information</param>
        /// <param name="googleAppsFeed">Source feed to generate appointment information</param>
        /// <param name="exchangeGateway">Gateway to sync Appointments with</param>
        /// <param name="window">DateRange to sync for</param>
        public void SyncUser(
            ExchangeUser user,
            EventFeed googleAppsFeed,
            ExchangeService exchangeGateway,
            DateTimeRange window)
        {
            exchangeGateway.GetCalendarInfoForUser(user, window);
            if (!user.HaveAppointmentDetail)
            {
                // Cannot sync if there is no appointment detail
                log.InfoFormat("Skipped Sync of {0} due to missing appointment lookup failure", user.Email);
                return;
            }

            List <Appointment> toUpdate = new List <Appointment>();
            List <Appointment> toDelete = new List <Appointment>();
            List <Appointment> toCreate = new List <Appointment>();

            OlsonTimeZone feedTimeZone = OlsonUtil.GetTimeZone(googleAppsFeed.TimeZone.Value);
            IntervalTree <Appointment> gcalApptTree =
                CreateAppointments(user, feedTimeZone, googleAppsFeed);

            /* Iterate through each Free/Busy time block for the user */
            foreach (FreeBusyTimeBlock fbtb in user.BusyTimes.Values)
            {
                /* Iterate through each appointment for the Free/Busy time block */
                foreach (Appointment appt in fbtb.Appointments)
                {
                    log.Debug(String.Format("Exchange @ '{0} {1}'",
                                            appt.Range,
                                            ValidateOwnership(appt)));
                    /* Validate that this is a GCalender appoint */
                    if (ValidateOwnership(appt))
                    {
                        /* If the GCalender appointments do not contain an
                         * appointment for this period, add it for deletion */
                        if (gcalApptTree.FindExact(appt.Range) == null)
                        {
                            toDelete.Add(appt);
                        }
                    }
                }
            }

            /* Iterate through each Google Apps appointment */
            AppointmentCollection appointments = user.BusyTimes.Appointments;
            List <Appointment>    gcalApptList = gcalApptTree.GetNodeList();

            foreach (Appointment newAppt in gcalApptList)
            {
                // If the meeting was cancelled
                log.DebugFormat("Looking @ {0} {1}", newAppt.Range, newAppt.Range.Start.Kind);

                if (newAppt.MeetingStatus == MeetingStatus.Cancelled)
                {
                    // Check if there is an existing appointment that matches
                    List <Appointment> matches = appointments.Get(newAppt.Range);
                    foreach (Appointment a in matches)
                    {
                        if (ValidateOwnership(a))
                        {
                            toDelete.Add(a);
                        }
                    }

                    // Work is done for this appointment, continue to next entry
                    continue;
                }

                bool updatedAppointment = false;

                List <Appointment> apptList = appointments.Get(newAppt.Range);
                log.DebugFormat("Looking up preexisting event: {0} {1}", newAppt.Range, newAppt.Range.Start.Kind);
                log.DebugFormat("Found {0} matching items", apptList.Count);

                // Check that there is a free busy block that correlates with this appointment
                foreach (Appointment existingAppt in apptList)
                {
                    if (ValidateOwnership(existingAppt) && !updatedAppointment)
                    {
                        UpdateAppointmentInfo(existingAppt, newAppt);
                        toUpdate.Add(existingAppt);
                        updatedAppointment = true;
                    }
                }

                if (!updatedAppointment)
                {
                    toCreate.Add(newAppt);
                    log.DebugFormat("ADDING '{0}' - Not an update",
                                    newAppt.Range);
                }
            }

            if (log.IsInfoEnabled)
            {
                log.InfoFormat(
                    "AppointmentWriter for '{0}'.  [{1} deleted, {2} updated, {3} new]",
                    user.Email,
                    toDelete.Count,
                    toUpdate.Count,
                    toCreate.Count);
            }

            exchangeGateway.Appointments.DeleteAppointments(user, toDelete);
            // TODO: Updates are not currently published
            // exchangeGateway.Appointments.UpdateAppointments( user, updateAppointments );
            exchangeGateway.Appointments.WriteAppointments(user, toCreate);
        }
示例#38
0
        /// <summary>
        /// Queries all intervals, servers and nodes in a topology for new values.
        /// Updates all relevances and checks for alerts.
        /// Returns list of task.
        /// Caller must wait for tasks to run to completion before topology is fully up to date.
        /// </summary>
        /// <param name="totalSearchSpan">Search span of query</param>
        /// <param name="topology">Topology to update</param>
        /// <param name="fullQuery">The cached query for the search span</param>
        /// <param name="opcUaServers">List of OPC UA servers to query for values</param>
        /// <param name="tasks">List of async tasks processing queries</param>
        /// <param name="aggregateIndex">The index of the aggregate in the topology nodes</param>
        public async Task ScheduleAllOeeKpiQueries(
            DateTimeRange totalSearchSpan,
            ContosoTopology topology,
            RDXCachedAggregatedQuery fullQuery,
            List <string> opcUaServers,
            List <Task> tasks,
            int aggregateIndex)
        {
            RDXAggregatedQueryCache queryCache = new RDXAggregatedQueryCache();

            queryCache.List.Add(fullQuery);

            foreach (string appUri in opcUaServers)
            {
                Station station = topology[appUri] as Station;
                if (station != null)
                {
                    ContosoAggregatedOeeKpiHistogram oeeKpiHistogram = station[aggregateIndex];
                    DateTime toTime    = totalSearchSpan.To;
                    int      intervals = oeeKpiHistogram.Intervals.Count;
                    oeeKpiHistogram.EndTime         = toTime;
                    station[aggregateIndex].EndTime = toTime;

                    foreach (ContosoAggregatedOeeKpiTimeSpan oeeKpiTimeSpan in oeeKpiHistogram.Intervals)
                    {
                        DateTime fromTime;

                        // first interval is current time
                        if (totalSearchSpan.To != toTime || intervals == 1)
                        {
                            fromTime = toTime.Subtract(oeeKpiTimeSpan.IntervalTimeSpan);
                        }
                        else
                        {
                            fromTime = RDXUtils.RoundDateTimeToTimeSpan(toTime.Subtract(TimeSpan.FromSeconds(1)), oeeKpiTimeSpan.IntervalTimeSpan);
                        }

                        DateTimeRange intervalSearchSpan = new DateTimeRange(fromTime, toTime);

                        if (toTime <= oeeKpiTimeSpan.EndTime)
                        {
                            // The interval is still up to date from a previous query, skip
                            toTime = fromTime;
                            continue;
                        }

                        oeeKpiTimeSpan.EndTime = toTime;
                        toTime = fromTime;

                        // find a cached query, if not try to cache the aggregation for this search span
                        RDXCachedAggregatedQuery aggregatedQuery = queryCache.Find(intervalSearchSpan);
                        if (aggregatedQuery == null)
                        {
                            RDXCachedAggregatedQuery newQuery = new RDXCachedAggregatedQuery(_opcUaQueries);
                            queryCache.List.Add(newQuery);
                            tasks.Add(newQuery.Execute(intervalSearchSpan));
                            aggregatedQuery = queryCache.Find(intervalSearchSpan);
                        }

                        RDXOeeKpiQuery oeeKpiQuery = new RDXOeeKpiQuery(_opcUaQueries, intervalSearchSpan, appUri, oeeKpiTimeSpan);

                        await oeeKpiQuery.QueryAllNodes(tasks, station.NodeList, oeeKpiHistogram.AwaitTasks, aggregatedQuery);

                        if (oeeKpiHistogram.CheckAlerts)
                        {
                            station.Status = ContosoPerformanceStatus.Good;
                            foreach (ContosoOpcUaNode node in station.NodeList)
                            {
                                if (node.Minimum != null || node.Maximum != null)
                                {
                                    station.Status |= await CheckAlert(intervalSearchSpan, appUri, station, node);
                                }
                            }
                        }
                    }
                }
            }
        }
        public void TestFastFreeBusyLookup()
        {
            _requestor.ValidMethod = Method.GET;
            _requestor.ResponseBody = getResponseXML("FreeBusyResponse.xml");

            // These dates correspond to when the response XML was captured
            DateTime start = DateUtil.ParseDateToUtc("2007-12-25T01:46:50Z");
            DateTime end = DateUtil.ParseDateToUtc("2008-01-08T01:42:50Z");
            DateTimeRange range = new DateTimeRange(start, end);

            ExchangeUserDict users = new ExchangeUserDict();
            users.Add(_user.Email, _user);

            Dictionary<ExchangeUser, FreeBusy> result = _webdav.LoadFreeBusy(exchangeServer,
                                                                             users,
                                                                             range);
            Assert.AreEqual(1, result.Count);

            FreeBusy fb = result[_user];

            Assert.AreEqual(6, fb.All.Count);
            Assert.AreEqual(6, fb.Busy.Count);
            Assert.AreEqual(0, fb.OutOfOffice.Count);
            Assert.AreEqual(0, fb.Tentative.Count);

            //dumpFreeBusy(fb.Busy);

            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-26T18:00:00Z"), fb.Busy[0].Start);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-26T18:30:00Z"), fb.Busy[0].End);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-26T20:30:00Z"), fb.Busy[1].Start);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-26T21:00:00Z"), fb.Busy[1].End);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-31T17:30:00Z"), fb.Busy[2].Start);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-31T18:00:00Z"), fb.Busy[2].End);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-31T21:00:00Z"), fb.Busy[3].Start);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-31T21:30:00Z"), fb.Busy[3].End);

            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-26T18:00:00Z"), fb.All[0].Start);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-26T18:30:00Z"), fb.All[0].End);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-26T20:30:00Z"), fb.All[1].Start);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-26T21:00:00Z"), fb.All[1].End);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-31T17:30:00Z"), fb.All[2].Start);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-31T18:00:00Z"), fb.All[2].End);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-31T21:00:00Z"), fb.All[3].Start);
            Assert.AreEqual(DateUtil.ParseDateToUtc("2007-12-31T21:30:00Z"), fb.All[3].End);
        }
示例#40
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the CustomerSyncService.
            CustomerSyncService customerSyncService =
                (CustomerSyncService)user.GetService(AdWordsService.v201509.
                                                     CustomerSyncService);

            // The date time string should be of the form  yyyyMMdd HHmmss zzz
            string minDateTime = DateTime.Now.AddDays(-1).ToUniversalTime().ToString(
                "yyyyMMdd HHmmss") + " UTC";
            string maxDateTime = DateTime.Now.ToUniversalTime().ToString("yyyyMMdd HHmmss") +
                                 " UTC";

            // Create date time range.
            DateTimeRange dateTimeRange = new DateTimeRange();

            dateTimeRange.min = minDateTime;
            dateTimeRange.max = maxDateTime;

            try {
                // Create the selector.
                CustomerSyncSelector selector = new CustomerSyncSelector();
                selector.dateTimeRange = dateTimeRange;
                selector.campaignIds   = GetAllCampaignIds(user);

                // Get all account changes for campaign.
                CustomerChangeData accountChanges = customerSyncService.get(selector);

                // Display the changes.
                if (accountChanges != null && accountChanges.changedCampaigns != null)
                {
                    Console.WriteLine("Displaying changes up to: {0}", accountChanges.lastChangeTimestamp);
                    foreach (CampaignChangeData campaignChanges in accountChanges.changedCampaigns)
                    {
                        Console.WriteLine("Campaign with id \"{0}\" was changed:", campaignChanges.campaignId);
                        Console.WriteLine("  Campaign changed status: {0}",
                                          campaignChanges.campaignChangeStatus);
                        if (campaignChanges.campaignChangeStatus != ChangeStatus.NEW)
                        {
                            Console.WriteLine("  Added ad extensions: {0}", GetFormattedList(
                                                  campaignChanges.addedAdExtensions));
                            Console.WriteLine("  Added campaign criteria: {0}",
                                              GetFormattedList(campaignChanges.addedCampaignCriteria));
                            Console.WriteLine("  Removed ad extensions: {0}",
                                              GetFormattedList(campaignChanges.removedAdExtensions));
                            Console.WriteLine("  Removed campaign criteria: {0}",
                                              GetFormattedList(campaignChanges.removedAdExtensions));

                            if (campaignChanges.changedAdGroups != null)
                            {
                                foreach (AdGroupChangeData adGroupChanges in campaignChanges.changedAdGroups)
                                {
                                    Console.WriteLine("  Ad group with id \"{0}\" was changed:",
                                                      adGroupChanges.adGroupId);
                                    Console.WriteLine("    Ad group changed status: {0}",
                                                      adGroupChanges.adGroupChangeStatus);
                                    if (adGroupChanges.adGroupChangeStatus != ChangeStatus.NEW)
                                    {
                                        Console.WriteLine("    Ads changed: {0}",
                                                          GetFormattedList(adGroupChanges.changedAds));
                                        Console.WriteLine("    Criteria changed: {0}",
                                                          GetFormattedList(adGroupChanges.changedCriteria));
                                        Console.WriteLine("    Criteria removed: {0}",
                                                          GetFormattedList(adGroupChanges.removedCriteria));
                                    }
                                }
                            }
                        }
                        Console.WriteLine();
                    }
                }
                else
                {
                    Console.WriteLine("No account changes were found.");
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to get account changes.", e);
            }
        }
示例#41
0
        protected override IEnumerable <ValidationResult> Validate()
        {
            Channel channel = new Channel();

            progress += 0.1;
            this.ReportProgress(progress);

            #region Getting Service option params
            //Getting Accounts list
            string[] accounts;
            if (this.Instance.AccountID == -1)
            {
                if (String.IsNullOrEmpty(this.Instance.Configuration.Options["AccountsList"]))
                {
                    throw new Exception("Missing Configuration option AccountsList");
                }
                accounts = this.Instance.Configuration.Options["AccountsList"].Split(',');
            }
            else
            {
                List <string> account = new List <string>()
                {
                    this.Instance.AccountID.ToString()
                };
                accounts = account.ToArray();
            }


            //Getting Table
            string comparisonTable;
            if (String.IsNullOrEmpty(this.Instance.Configuration.Options["SourceTable"]))
            {
                throw new Exception("Missing Configuration option SourceTable");
            }
            else
            {
                comparisonTable = this.Instance.Configuration.Options["SourceTable"];
            }

            //Getting Channel List
            if (String.IsNullOrEmpty(this.Instance.Configuration.Options["ChannelList"]))
            {
                throw new Exception("Missing Configuration option ChannelList");
            }
            string[] channels = this.Instance.Configuration.Options["ChannelList"].Split(',');

            //Getting TimePeriod
            DateTime fromDate, toDate;
            if ((String.IsNullOrEmpty(this.Instance.Configuration.Options["fromDate"])) && (String.IsNullOrEmpty(this.Instance.Configuration.Options["toDate"])))
            {
                fromDate = this.TargetPeriod.Start.ToDateTime();
                toDate   = this.TargetPeriod.End.ToDateTime();
            }
            else
            {
                fromDate = Convert.ToDateTime(this.Instance.Configuration.Options["fromDate"]);
                toDate   = Convert.ToDateTime(this.Instance.Configuration.Options["toDate"]);
            }
            #endregion



            if (this.Delivery == null || this.Delivery.DeliveryID.Equals(Guid.Empty))
            {
                #region Creating Delivery Search List
                List <DeliverySearchItem> deliverySearchList = new List <DeliverySearchItem>();

                while (fromDate <= toDate)
                {
                    // {start: {base : '2009-01-01', h:0}, end: {base: '2009-01-01', h:'*'}}
                    var subRange = new DateTimeRange()
                    {
                        Start = new DateTimeSpecification()
                        {
                            BaseDateTime = fromDate,
                            Hour         = new DateTimeTransformation()
                            {
                                Type = DateTimeTransformationType.Exact, Value = 0
                            },
                        },

                        End = new DateTimeSpecification()
                        {
                            BaseDateTime = fromDate,
                            Hour         = new DateTimeTransformation()
                            {
                                Type = DateTimeTransformationType.Max
                            },
                        }
                    };

                    foreach (var Channel in channels)
                    {
                        foreach (string account in accounts)
                        {
                            DeliverySearchItem delivery = new DeliverySearchItem();
                            delivery.account = new Account()
                            {
                                ID = Convert.ToInt32(account)
                            };
                            delivery.channel = new Channel()
                            {
                                ID = Convert.ToInt32(Channel)
                            };
                            delivery.targetPeriod = subRange;
                            deliverySearchList.Add(delivery);

                            progress += 0.3 * ((1 - progress) / (channels.LongLength + accounts.LongLength));
                            this.ReportProgress(progress);
                        }
                    }
                    fromDate = fromDate.AddDays(1);
                }
                #endregion
                foreach (DeliverySearchItem deliveryToSearch in deliverySearchList)
                {
                    #region Foreach

                    //Getting criterion matched deliveries
                    Delivery[] deliveriesToCheck = Delivery.GetByTargetPeriod(deliveryToSearch.targetPeriod.Start.ToDateTime(), deliveryToSearch.targetPeriod.End.ToDateTime(), deliveryToSearch.channel, deliveryToSearch.account);
                    bool       foundCommited     = false;

                    progress += 0.3 * (1 - progress);
                    this.ReportProgress(progress);

                    foreach (Delivery d in deliveriesToCheck)
                    {
                        int rollbackIndex = -1;
                        int commitIndex   = -1;

                        #region Searching and researching commited and rolledback deliveries
                        for (int i = 0; i < d.History.Count; i++)
                        {
                            if (d.History[i].Operation == DeliveryOperation.Committed)
                            {
                                commitIndex = i;
                            }
                            else if (d.History[i].Operation == DeliveryOperation.RolledBack)
                            {
                                rollbackIndex = i;
                            }
                        }

                        if (commitIndex > rollbackIndex)
                        {
                            object totalso;
                            foundCommited = true;

                            DeliveryHistoryEntry commitEntry = null;
                            IEnumerable <DeliveryHistoryEntry> processedEntries = d.History.Where(entry => (entry.Operation == DeliveryOperation.Imported));
                            if (processedEntries != null && processedEntries.Count() > 0)
                            {
                                commitEntry = (DeliveryHistoryEntry)processedEntries.Last();
                            }
                            else
                            {
                                continue;
                            }

                            if (commitEntry.Parameters.TryGetValue(Edge.Data.Pipeline.Common.Importing.Consts.DeliveryHistoryParameters.ChecksumTotals, out totalso))
                            {
                                Dictionary <string, double> totals = (Dictionary <string, double>)totalso;

                                //Check Delivery data vs OLTP
                                yield return(DeliveryDbCompare(d, totals, "OltpDB", comparisonTable));
                            }
                        }
                        #endregion
                    }


                    //could not find deliveries by user criterions
                    if (deliveriesToCheck.Length == 0)
                    {
                        yield return(new ValidationResult()
                        {
                            ResultType = ValidationResultType.Error,
                            AccountID = deliveryToSearch.account.ID,
                            TargetPeriodStart = deliveryToSearch.targetPeriod.Start.ToDateTime(),
                            TargetPeriodEnd = deliveryToSearch.targetPeriod.End.ToDateTime(),
                            Message = "Cannot find deliveries in DB",
                            ChannelID = deliveryToSearch.channel.ID,
                            CheckType = this.Instance.Configuration.Name
                        });
                    }
                    else if (!foundCommited)
                    {
                        yield return(new ValidationResult()
                        {
                            ResultType = ValidationResultType.Error,
                            AccountID = deliveryToSearch.account.ID,
                            TargetPeriodStart = deliveryToSearch.targetPeriod.Start.ToDateTime(),
                            TargetPeriodEnd = deliveryToSearch.targetPeriod.End.ToDateTime(),
                            Message = "Cannot find Commited deliveries in DB",
                            ChannelID = deliveryToSearch.channel.ID,
                            CheckType = this.Instance.Configuration.Name
                        });
                    }
                    #endregion
                }                 // End of foreach
            }
            else
            {
                //Getting current Delivery totals
                object totalso;
                DeliveryHistoryEntry commitEntry = null;
                IEnumerable <DeliveryHistoryEntry> processedEntries = this.Delivery.History.Where(entry => (entry.Operation == DeliveryOperation.Imported));
                if (processedEntries != null && processedEntries.Count() > 0)
                {
                    commitEntry = (DeliveryHistoryEntry)processedEntries.Last();
                    if (commitEntry.Parameters.TryGetValue(Edge.Data.Pipeline.Common.Importing.Consts.DeliveryHistoryParameters.ChecksumTotals, out totalso))
                    {
                        Dictionary <string, double> totals = (Dictionary <string, double>)totalso;
                        yield return(DeliveryDbCompare(this.Delivery, totals, "OltpDB", comparisonTable));
                    }
                }
            }
        }
    public bool Intersects(DateTimeRange range)
    {
        var type = GetIntersectionType(range);

        return(type != IntersectionType.None);
    }
示例#43
0
        /// <summary>
        /// Creates the lab specimen.
        /// </summary>
        /// <param name="clinicalCase">The clinical case.</param>
        /// <param name="provenance">The provenance.</param>
        /// <param name="activityDateTimeRange">The activity date time range.</param>
        /// <returns>A LabSpecimen.</returns>
        public LabSpecimen CreateLabSpecimen(ClinicalCase clinicalCase, Provenance provenance, DateTimeRange activityDateTimeRange)
        {
            var type = _lookupValueRepository.GetLookupByWellKnownName <VisitModule.ActivityType>(ActivityType.LabSpecimen);

            var labSpecimen = new LabSpecimen(clinicalCase, type, provenance, activityDateTimeRange);

            _labSpecimenRepository.MakePersistent(labSpecimen);

            return(labSpecimen);
        }
 /// <inheritdoc/>
 public async Task <IList <MeetingNotificationItemEntity> > GetMeetingNotificationsByDateRangeAndStatus(string applicationName, DateTimeRange dateRange, List <NotificationItemStatus> statusList)
 {
     return(await this.emailNotificationRepository.GetPendingOrFailedMeetingNotificationsByDateRange(dateRange, applicationName, statusList).ConfigureAwait(false));
 }
 EmployerMemberAccessReport IEmployerMemberAccessReportsQuery.GetEmployerMemberAccessReport(Channel channel, DateTimeRange timeRange)
 {
     return(new EmployerMemberAccessReport
     {
         TotalAccesses = _repository.GetMemberAccesses(channel, timeRange),
         DistinctAccesses = _repository.GetDistinctMemberAccesses(channel, timeRange),
         MessagesSent = _repository.GetMemberAccesses(MemberAccessReason.MessageSent, channel, timeRange),
         PhoneNumbersViewed = _repository.GetMemberAccesses(MemberAccessReason.PhoneNumberViewed, channel, timeRange),
         ResumesDownloaded = _repository.GetMemberAccesses(MemberAccessReason.ResumeDownloaded, channel, timeRange),
         ResumesSent = _repository.GetMemberAccesses(MemberAccessReason.ResumeSent, channel, timeRange),
         Unlockings = _repository.GetMemberAccesses(MemberAccessReason.Unlock, channel, timeRange),
     });
 }
 public Appointment_Create()
 {
     _endTime = _startTime.AddHours(3);
     _range   = new DateTimeRange(_startTime, _endTime);
 }
示例#47
0
 /// <summary>
 /// Creates the activity.
 /// </summary>
 /// <param name="clinicalCase">The clinical case.</param>
 /// <param name="provenance">The provenance.</param>
 /// <param name="activityDateTimeRange">The activity date time range.</param>
 /// <returns> An Activity. </returns>
 public Activity CreateActivity(ClinicalCase clinicalCase, Provenance provenance, DateTimeRange activityDateTimeRange)
 {
     return(CreateLabSpecimen(clinicalCase, provenance, activityDateTimeRange));
 }
        /// <summary>
        /// Combines the free busy and appointment blocks supplied to the exchange user object
        /// If no appointments are supplied the user will still have free busy time blocks assigned
        /// to them, with a null appointment assigned to the free busy time.
        /// </summary>
        /// <param name="exchangeUser">Exchange users to apply freeBusy and appointments</param>
        /// <param name="freeBusy">The collection of FreeBusy blocks to assign to exchangeUser</param>
        /// <param name="appointments">The collection of appointment blocks to assign to exchangeUser</param>
        /// <param name="window">Window to merge for</param>
        protected void MergeFreeBusyWithAppointments(
            ExchangeUser exchangeUser,
            FreeBusy freeBusy,
            List <Appointment> appointments,
            DateTimeRange window)
        {
            using (BlockTimer bt = new BlockTimer("MergeFreeBusyWithAppointments"))
            {
                IntervalTree <FreeBusyTimeBlock> busyIntervals =
                    new IntervalTree <FreeBusyTimeBlock>();
                FreeBusyCollection busyTimes       = new FreeBusyCollection();
                int appointmentsCount              = 0;
                List <DateTimeRange> combinedTimes =
                    FreeBusyConverter.MergeFreeBusyLists(freeBusy.All, freeBusy.Tentative);

                /* Add the date ranges from each collection in the FreeBusy object */
                ConvertFreeBusyToBlocks(window,
                                        combinedTimes,
                                        busyTimes,
                                        busyIntervals);

                if (appointments != null && appointments.Count > 0)
                {
                    appointmentsCount = appointments.Count;
                    foreach (Appointment appt in appointments)
                    {
                        log.DebugFormat("Appt \"{0}\" {1} {2} response = {3} status = {4} busy = {5}",
                                        appt.Subject,
                                        appt.Range,
                                        appt.StartDate.Kind,
                                        appt.ResponseStatus,
                                        appt.MeetingStatus,
                                        appt.BusyStatus);

                        if (appt.BusyStatus == BusyStatus.Free)
                        {
                            continue;
                        }

                        DateTimeRange            range  = new DateTimeRange(appt.StartDate, appt.EndDate);
                        List <FreeBusyTimeBlock> result =
                            busyIntervals.FindAll(range, IntervalTreeMatch.Overlap);

                        log.DebugFormat("Found {0} ranges overlap {1}", result.Count, range);

                        foreach (FreeBusyTimeBlock block in result)
                        {
                            log.DebugFormat("Adding \"{0}\" to FB {1} {2}",
                                            appt.Subject,
                                            block.Range,
                                            block.StartDate.Kind);
                            block.Appointments.Add(appt);
                        }

                        busyTimes.Appointments.Add(appt);
                    }
                }

                foreach (FreeBusyTimeBlock block in busyTimes.Values)
                {
                    block.Appointments.Sort(CompareAppointmentsByRanges);
                }

                log.InfoFormat("Merge Result of {0} + Appointment {1} -> {2}",
                               combinedTimes.Count,
                               appointmentsCount,
                               busyTimes.Count);

                /* Assign the data structure to the exchange user */
                exchangeUser.BusyTimes = busyTimes;
            }
        }
 int IEmployerMemberAccessReportsQuery.GetMemberAccesses(DateTimeRange timeRange)
 {
     return(_repository.GetMemberAccesses(timeRange));
 }
 /// <summary>
 /// Returns a list of Exchange users matching an email address, provides
 /// free busy times and appointments if available within the date range.
 /// </summary>
 /// <param name="utcRange">DateRange for search</param>
 /// <param name="searchTerms">Search terms to search exchange for</param>
 /// <returns></returns>
 public ExchangeUserDict SearchByEmail(
     DateTimeRange utcRange, params string[] searchTerms)
 {
     return(Search("mail", utcRange, searchTerms));
 }
        /// <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()
                        , 0                                                                                   //EXTENSION_DEFAULT
                    }
                                                                                                   );
                }
                else
                {
                    ; // по идентификатору найден не единственный параметр расчета
                }
            }

            correctValues(ref arTableValues[(int)HandlerDbTaskCalculate.INDEX_TABLE_VALUES.SESSION]
                          , ref tablePars);

            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>
 /// Issue a task for a cached query for all active nodes and stations
 /// </summary>
 /// <param name="searchSpan">Date and time span for the query</param>
 public Task Execute(DateTimeRange searchSpan)
 {
     SearchSpan = searchSpan;
     _task      = _opcUaQueries.GetAllAggregatedStationsAndNodes(searchSpan);
     return(_task);
 }
        ///// <summary>
        ///// Возвратить наименование таблицы
        ///// </summary>
        ///// <param name="req">Индекс таблицы, требуемой при расчете</param>
        ///// <returns>Наименование таблицы</returns>
        //private string getNameDbTable(TABLE_CALCULATE_REQUIRED req)
        //{
        //    return getNameDbTable(m_taskCalculate.Type, req);
        //}
        /// <summary>
        /// Возвратить массив диапазонов даты/времени для запроса значений
        /// </summary>
        /// <returns>Массив диапазонов даты/времени</returns>
        public virtual DateTimeRange[] GetDateTimeRangeValuesVar()
        {
            DateTimeRange[] arRangesRes = null;

            int  i = -1;
            bool bEndMonthBoudary = false;
            // привести дату/время к UTC
            DateTime dtBegin = _Session.m_rangeDatetime.Begin.AddMinutes(-1 * _Session.m_curOffsetUTC)
            , dtEnd          = _Session.m_rangeDatetime.End.AddMinutes(-1 * _Session.m_curOffsetUTC);

            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));
                        }
                        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
            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 Initialize(long id, ID_PERIOD idPeriod, ID_TIMEZONE idTimezone, int curOffsetUTC, DateTimeRange rangeDatetime)
 {
     m_Id             = id;
     m_currIdPeriod   = idPeriod;
     m_currIdTimezone = idTimezone;
     m_curOffsetUTC   = curOffsetUTC;
     m_rangeDatetime  = rangeDatetime;
 }
 public static bool Between(this DateTime dateTime, DateTimeRange dateTimeRange)
 {
     return(dateTime >= dateTimeRange.Start &&
            dateTime <= dateTimeRange.End);
 }
示例#56
0
        public MonthViewViewModel()
        {
            this.SelectedEvents = new ObservableCollection <EventData>();
            var recurrencePattern = new RecurrencePattern(new int[] { }, RecurrenceDays.WeekDays, RecurrenceFrequency.Daily, 1, null, null)
            {
                MaxOccurrences = 37
            };
            var dailyRecurrenceRule = new RecurrenceRule(recurrencePattern);

            this.OpenDrawerCommand = new Command(this.OnOpenDrawerCommandExecute);
            this.Events            = new ObservableCollection <EventData>()
            {
                new EventData(
                    DateTime.Today.AddHours(11),
                    DateTime.Today.AddHours(11).AddMinutes(15),
                    "Daily SCRUM",
                    Color.FromHex("59B6B8"),
                    Color.FromHex("59B6B8"))
                {
                    RecurrenceRule = dailyRecurrenceRule
                },
                new EventData(
                    DateTime.Today.AddDays(-7).AddHours(10),
                    DateTime.Today.AddDays(-7).AddHours(11),
                    "Tokyo Deall call",
                    Color.FromHex("FFA200"),
                    Color.White),
                new EventData(
                    DateTime.Today.AddDays(-7).AddHours(16),
                    DateTime.Today.AddDays(-7).AddHours(17).AddMinutes(30),
                    "Dinner with the Morgans",
                    Color.FromHex("59B6B8"),
                    Color.White),
                new EventData(
                    DateTime.Today.AddDays(-4).AddHours(15),
                    DateTime.Today.AddDays(-4).AddHours(16).AddMinutes(30),
                    "Theater evening",
                    Color.FromHex("59B6B8"),
                    Color.White),
                new EventData(
                    DateTime.Today.AddDays(-3).AddHours(9),
                    DateTime.Today.AddDays(-3).AddHours(10),
                    "Conference call with HQ2",
                    Color.FromHex("FFA200"),
                    Color.White),
                new EventData(
                    DateTime.Today.AddDays(-2),
                    DateTime.Today.AddDays(-2).AddSeconds(1),
                    "Weekend barbecue",
                    Color.FromHex("59B6B8"),
                    Color.FromHex("59B6B8"),
                    true),
                new EventData(
                    DateTime.Today.AddDays(-1),
                    DateTime.Today.AddDays(-1).AddSeconds(1),
                    "Mountain biking",
                    Color.FromHex("C9353E"),
                    Color.FromHex("C9353E"),
                    true),
                //Today`s events
                new EventData(
                    DateTime.Today.AddHours(9),
                    DateTime.Today.AddHours(10),
                    "Job Interview",
                    Color.FromHex("FFA200"),
                    Color.White),
                new EventData(
                    DateTime.Today.AddHours(10),
                    DateTime.Today.AddHours(11),
                    "Tokyo deal call",
                    Color.FromHex("FFA200"),
                    Color.White),
                new EventData(
                    DateTime.Today.AddHours(14),
                    DateTime.Today.AddHours(15).AddMinutes(30),
                    "Yachting",
                    Color.FromHex("59B6B8"),
                    Color.White),
                new EventData(
                    DateTime.Today.AddHours(16),
                    DateTime.Today.AddHours(17).AddMinutes(30),
                    "Dinner with the Morgans",
                    Color.FromHex("59B6B8"),
                    Color.White),
                new EventData(
                    DateTime.Today.AddHours(18),
                    DateTime.Today.AddHours(19).AddMinutes(30),
                    "Fitness",
                    Color.FromHex("C9353E"),
                    Color.White),
                new EventData(
                    DateTime.Today.AddHours(20),
                    DateTime.Today.AddHours(22),
                    "Watch a movie",
                    Color.FromHex("C42FBA"),
                    Color.White),
                //Tomorrow
                new EventData(
                    DateTime.Today.AddHours(20),
                    DateTime.Today.AddHours(22),
                    "Date with Candice",
                    Color.FromHex("C42FBA"),
                    Color.White),
                //Day after tomorrow
                new EventData(
                    DateTime.Today.AddDays(2).AddHours(18),
                    DateTime.Today.AddDays(2).AddHours(19).AddMinutes(30),
                    "Watch your favourite show",
                    Color.FromHex("59B6B8"),
                    Color.White),
                new EventData(
                    DateTime.Today.AddDays(2).AddHours(19),
                    DateTime.Today.AddDays(2).AddHours(20).AddMinutes(30),
                    "Football",
                    Color.FromHex("C9353E"),
                    Color.White),
                //Two days after tomorrow
                new EventData(
                    DateTime.Today.AddDays(3).AddHours(10),
                    DateTime.Today.AddDays(3).AddHours(11),
                    "Coordination meeting",
                    Color.FromHex("FFA200"),
                    Color.White),
                new EventData(
                    DateTime.Today.AddDays(3).AddHours(15),
                    DateTime.Today.AddDays(3).AddHours(16).AddMinutes(30),
                    "Theater evening",
                    Color.FromHex("59B6B8"),
                    Color.White),
                new EventData(
                    DateTime.Today.AddDays(3).AddHours(18),
                    DateTime.Today.AddDays(3).AddHours(19).AddMinutes(30),
                    "Table tennis",
                    Color.FromHex("C9353E"),
                    Color.White),
                //Three days after tomorrow
                new EventData(
                    DateTime.Today.AddDays(4).AddHours(9),
                    DateTime.Today.AddDays(4).AddHours(10),
                    "Conference call with HQ2",
                    Color.FromHex("FFA200"),
                    Color.White),
                //Four days after tomorrow
                new EventData(
                    DateTime.Today.AddDays(5).AddHours(21),
                    DateTime.Today.AddDays(5).AddHours(23),
                    "Birthday party",
                    Color.FromHex("C42FBA"),
                    Color.White),
            };

            this.SelectionModes = new List <SelectionModeItem>();
            this.SelectionModes.Add(new SelectionModeItem(char.ConvertFromUtf32(0xe864), CalendarSelectionMode.None));
            this.SelectionModes.Add(new SelectionModeItem(char.ConvertFromUtf32(0xe866), CalendarSelectionMode.Single));

            if (!Device.RuntimePlatform.Equals("UWP"))
            {
                this.SelectionModes.Add(new SelectionModeItem(char.ConvertFromUtf32(0xe867), CalendarSelectionMode.Multiple));
                this.SelectionModes.Add(new SelectionModeItem(char.ConvertFromUtf32(0xe868), CalendarSelectionMode.Range));
            }

            this.selectedMode  = Device.RuntimePlatform == "UWP" ? this.SelectionModes[1] : this.SelectionModes[3];
            this.selectedRange = new DateTimeRange(DateTime.Today, DateTime.Today.AddDays(2));
        }
    private async Task<IReadOnlyList<EntityVersion<WebResourceName, string>>> GetVersions (DateTimeRange? range, string entityType)
    {
      var entities = new List<EntityVersion<WebResourceName, string>>();

      try
      {
        var responseXml = await _webDavClient.ExecuteWebDavRequestAndReadResponse (
            _serverUrl,
            "REPORT",
            1,
            null,
            null,
            "application/xml",
            string.Format (
                @"<?xml version=""1.0""?>
                    <C:calendar-query xmlns:C=""urn:ietf:params:xml:ns:caldav"">
                        <D:prop xmlns:D=""DAV:"">
                            <D:getetag/>
                        </D:prop>
                        <C:filter>
                            <C:comp-filter name=""VCALENDAR"">
                                <C:comp-filter name=""{0}"">
                                  {1}
                                </C:comp-filter>
                            </C:comp-filter>
                        </C:filter>
                    </C:calendar-query>
                    ",
                entityType,
                range == null ? string.Empty : string.Format (@"<C:time-range start=""{0}"" end=""{1}""/>",
                    range.Value.From.ToString (s_calDavDateTimeFormatString),
                    range.Value.To.ToString (s_calDavDateTimeFormatString))
                ));


        XmlNodeList responseNodes = responseXml.XmlDocument.SelectNodes ("/D:multistatus/D:response", responseXml.XmlNamespaceManager);

        // ReSharper disable once LoopCanBeConvertedToQuery
        // ReSharper disable once PossibleNullReferenceException
        foreach (XmlElement responseElement in responseNodes)
        {
          var urlNode = responseElement.SelectSingleNode ("D:href", responseXml.XmlNamespaceManager);
          var etagNode = responseElement.SelectSingleNode ("D:propstat/D:prop/D:getetag", responseXml.XmlNamespaceManager);
          if (urlNode != null &&
              etagNode != null &&
              _serverUrl.AbsolutePath != UriHelper.DecodeUrlString (urlNode.InnerText))
          {
            var uri = new WebResourceName (urlNode.InnerText);
            entities.Add (EntityVersion.Create (uri, HttpUtility.GetQuotedEtag (etagNode.InnerText)));
          }
        }
      }
      catch (WebDavClientException x)
      {
        // Workaround for Synology NAS, which returns 404 insteaod of an empty response if no events are present
        if (x.StatusCode == HttpStatusCode.NotFound && await IsResourceCalender())
          return entities;

        throw;
      }

      return entities;
    }
示例#58
0
 /// <summary>
 /// 卡片延期
 /// </summary>
 /// <param name="info"></param>
 /// <param name="newValidDate"></param>
 /// <param name="paymentMode"></param>
 /// <param name="money"></param>
 /// <param name="memo"></param>
 /// <param name="keepParkingStatus">是否保持卡片运行状态</param>
 /// <returns></returns>
 public CommandResult CardDefer(CardInfo info, DateTimeRange deferDate, PaymentMode paymentMode, decimal money, bool keepParkingStatus, string memo)
 {
     return(new CardBll(AppConifg.Current.ParkingConnection).CardDefer(info, deferDate, paymentMode, money, memo, keepParkingStatus));
 }
        /// <summary>
        /// Create a new appointment
        /// </summary>
        public Appointment()
        {
            Created = DateUtil.NowUtc;
            range = new DateTimeRange(Created, Created);

            Body = string.Empty;
            Subject = string.Empty;
            Location = string.Empty;
            Comment = string.Empty;
            Organizer = string.Empty;

            BusyStatus = BusyStatus.Free;
            ResponseStatus = ResponseStatus.None;
            InstanceType = InstanceType.Single;
            MeetingStatus = MeetingStatus.Tentative;

            IsPrivate = false;
            AllDayEvent = false;

            HRef = string.Empty;
        }
 public void SetRangeDatetime(DateTimeRange dtRange)
 {
     SetRangeDatetime(dtRange.Begin, dtRange.End);
 }