/// <summary>
    /// Run the code example.
    /// </summary>
    /// <param name="service">An initialized Dfa Reporting service object
    /// </param>
    public override void Run(DfareportingService service) {
      long profileId = long.Parse(_T("INSERT_USER_PROFILE_ID_HERE"));

      string reportName = _T("INSERT_REPORT_NAME_HERE");

      // Create a date range to report on.
      DateRange dateRange = new DateRange();
      dateRange.RelativeDateRange = "YESTERDAY";

      // Create a dimension to report on.
      SortedDimension dimension = new SortedDimension();
      dimension.Name = "dfa:campaign";

      // Create the criteria for the report.
      Report.CriteriaData criteria = new Report.CriteriaData();
      criteria.DateRange = dateRange;
      criteria.Dimensions = new List<SortedDimension>() { dimension };
      criteria.MetricNames = new List<string>() { "dfa:clicks" };

      // Create the report.
      Report report = new Report();
      report.Criteria = criteria;
      report.Name = reportName;
      report.Type = "STANDARD";

      // Insert the report.
      Report result = service.Reports.Insert(report, profileId).Execute();

      // Display the new report ID.
      Console.WriteLine("Standard report with ID {0} was created.", result.Id);
    }
Ejemplo n.º 2
0
 public ImportConsent(Guid notificationId, DateRange consentRange, string conditions, Guid userId)
 {
     ConsentRange = consentRange;
     Conditions = conditions;
     UserId = userId;
     NotificationId = notificationId;
 }
Ejemplo n.º 3
0
        public static double ItemCount(CalendarAppointmentItem currentApp, UIElementCollection children)
        {
            double count = 0;
            foreach (UIElement child in children)
            {
                if (child is CalendarAppointmentItem)
                {
                    var currentChild = child as CalendarAppointmentItem;

                    var cStart = currentApp.GetValue(TimeSlotPanel.StartTimeProperty) as DateTime?;
                    var cEnd = currentApp.GetValue(TimeSlotPanel.EndTimeProperty) as DateTime?;
                    var toTest = new DateRange(cStart.Value, cEnd.Value);

                    var aStart = currentChild.GetValue(TimeSlotPanel.StartTimeProperty) as DateTime?;
                    var aEnd = currentChild.GetValue(TimeSlotPanel.EndTimeProperty) as DateTime?;
                    var current = new DateRange(aStart.Value, aEnd.Value);

                    if (toTest.Overlaps(current))
                    {
                        count++;
                    }
                }
            }
            return count;
        }
        public void Map()
        {
            // Arrange
            var start = new DateTime(2010, 1, 1);
            var end = DateUtility.MaxDate;
            var range = new DateRange(start, end);

            var id = new MDM.Contracts.NexusId { SystemName = "Test", Identifier = "A" };
            var contractDetails = new MDM.Contracts.CurveDetails();
            var contract = new MDM.Contracts.Curve
            {
                Identifiers = new MDM.Contracts.NexusIdList { id },
                Details = contractDetails,
                Nexus = new MDM.Contracts.SystemData { StartDate = start, EndDate = end }
            };

            // NB Don't assign validity here, want to prove SUT sets it
            var details = new Curve();

            var mapping = new CurveMapping();

            var mappingEngine = new Mock<IMappingEngine>();
            mappingEngine.Setup(x => x.Map<MDM.Contracts.NexusId, CurveMapping>(id)).Returns(mapping);
            mappingEngine.Setup(x => x.Map<MDM.Contracts.CurveDetails, Curve>(contractDetails)).Returns(details);

            var mapper = new CurveMapper(mappingEngine.Object);

            // Act
            var candidate = mapper.Map(contract);

            // Assert
            //Assert.AreEqual(1, candidate.Details.Count, "Detail count differs");
            Assert.AreEqual(1, candidate.Mappings.Count, "Mapping count differs");
            Check(range, details.Validity, "Validity differs");
        }
Ejemplo n.º 5
0
 protected DateTime GetRangeStart(DateRange range)
 {
     switch (range) {
         case DateRange.Today:
             return DateTime.Now.Date;
         case DateRange.Last24Hours:
             return DateTime.Now.AddDays(-1);
         case DateRange.ThisWeek:
             //TODO #################
             int diff = DateTime.Now.DayOfWeek - DayOfWeek.Monday;
             if (diff < 0){
                 diff += 7;
             }
             return DateTime.Now.AddDays(-1 * diff).Date;
         case DateRange.Last7Days:
             return DateTime.Now.Date.AddDays(-7);
         case DateRange.ThisMonth:
             return new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
         case DateRange.Last30Days:
             return new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(-30);
         case DateRange.ThisYear:
             return new DateTime(DateTime.Now.Year, 1, 1);
         case DateRange.LastYear:
             return new DateTime(DateTime.Now.Year, 1, 1).AddYears(-1);
         case DateRange.All:
             return new DateTime(1790, 1, 1);
         case DateRange.LastMonth:
             return new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1);
         default:
             break;
     }
     return DateTime.Now;
 }
Ejemplo n.º 6
0
        private object GenerateUsageReport(IUnitOfWork uow, DateRange dateRange, int start,
            int length, out int count)
        {
            _dataUrlMappings = new Dictionary<string, string>();
            _dataUrlMappings.Add("BookingRequest", "/Dashboard/Index/");
            _dataUrlMappings.Add("Email", "/Dashboard/Index/");
            _dataUrlMappings.Add("User", "/User/Details?userID=");


            var factDO = uow.FactRepository.GetQuery().WhereInDateRange(e => e.CreateDate, dateRange);

            count = factDO.Count();

            return factDO
                .OrderByDescending(e => e.CreateDate)
                .Skip(start)
                .Take(length)
                .AsEnumerable()
                .Select(
                    f => new
                        {
                            PrimaryCategory = f.PrimaryCategory,
                            SecondaryCategory = f.SecondaryCategory,
                            Activity = f.Activity,
                            Status = f.Status,
                            Data = AddClickability(f.Data),
                            CreateDate = f.CreateDate.ToString(DateStandardFormat),
                        })
                .ToList();

        }
Ejemplo n.º 7
0
        public void EqualityTest()
        {
            DateRange sd = new DateRange(d1, d1);
            DateRange sd2 = new DateRange(d1, d1);
            Assert.AreEqual(sd, sd2);

            sd = new DateRange(d1, d2);
            sd2 = new DateRange(d1, d1);
            Assert.AreNotEqual(sd, sd2);

            sd = new DateRange(null, d1);
            sd2 = new DateRange(null, d1);
            Assert.AreEqual(sd, sd2);

            sd = new DateRange(d1, null);
            sd2 = new DateRange(d1, null);
            Assert.AreEqual(sd, sd2);

            sd = new DateRange(null, d1);
            sd2 = new DateRange(d1, null);
            Assert.AreNotEqual(sd, sd2);

            sd = new DateRange(null, null);
            sd2 = new DateRange(d1, null);
            Assert.AreNotEqual(sd, sd2);
        }
Ejemplo n.º 8
0
        public void Constructor_ValidDateRange_Succeeds()
        {
            DateTime effectiveDate = new DateTime ( 2000, 1, 1 );
            DateTime expirationDate = new DateTime ( 2000, 2, 1 );

            DateRange dateRange = new DateRange ( effectiveDate, expirationDate );
        }
Ejemplo n.º 9
0
        public void Constructor_NullEffectiveDate_Succeeds()
        {
            DateTime? effectiveDate = null;
            DateTime expirationDate = new DateTime ( 2000, 1, 1 );

            DateRange dateRange = new DateRange ( effectiveDate, expirationDate );
        }
Ejemplo n.º 10
0
        public void Constructor_LaterThanExpiration_ThrowsException()
        {
            DateTime effectiveDate = new DateTime ( 2000, 1, 2 );
            DateTime expirationDate = new DateTime ( 2000, 1, 1 );

            DateRange dateRange = new DateRange ( effectiveDate, expirationDate );
        }
Ejemplo n.º 11
0
        public void StartDateHaveToBeEarlierThanEndDate_ArgumentException()
        {
            DateTime startDate = DateTime.Now.AddMonths(months: 2);
            DateTime endDate = DateTime.Now.AddMonths(months: 1);

            DateRange range = new DateRange(startDate, endDate);
        }
Ejemplo n.º 12
0
        public DateFilter(Point point)
        {
            InitializeComponent();
            DateRange = new DateRange();
            this.Location = point;
            panelDtp.Visible = false;
            panelMonth.Visible = false;

            cbFromMonth.SelectedIndex = 0;
            cbToMonth.SelectedIndex = 0;

            for (int i = DateTime.Now.Year - 5; i < DateTime.Now.Year + 5; i++)
            {
                cbFromYear.Items.Add(i);
                cbToYear.Items.Add(i);
            }
            cbFromYear.SelectedIndex = 0;
            cbToYear.SelectedIndex = 0;
            cbDateFilterType.SelectedIndex = 0;
            cbFromYear.SelectedIndexChanged += new System.EventHandler(cbFromYear_SelectedIndexChanged);
            cbToYear.SelectedIndexChanged += new System.EventHandler(cbToYear_SelectedIndexChanged);

            this.cbToMonth.SelectedIndexChanged += new System.EventHandler(this.cbToMonth_SelectedIndexChanged);
            this.cbFromMonth.SelectedIndexChanged += new System.EventHandler(this.cbFromMonth_SelectedIndexChanged);
        }
Ejemplo n.º 13
0
        public MyViewModel()
        {
            var date = DateTime.Now;
            var ganttAPI = new GanttTask(date, date.AddDays(2), "Design public API") { Description = "Description: Design public API" };

            var ganttRendering = new GanttTask(date.AddDays(2).AddHours(8), date.AddDays(4), "Gantt Rendering") { Description = "Description: Gantt Rendering" };

            var ganttDemos = new GanttTask(date.AddDays(4.5), date.AddDays(7), "Gantt Demos") { Description = "Description: Gantt Demos" };

            var milestone = new GanttTask(date.AddDays(7), date.AddDays(7).AddHours(1), "Review") { Description = "Review", IsMilestone = true };

            ganttRendering.Dependencies.Add(new Dependency { FromTask = ganttAPI });
            ganttDemos.Dependencies.Add(new Dependency { FromTask = ganttRendering });

            var iterationTask = new GanttTask(date, date.AddDays(7), "Iteration 1")
            {
                Children = { ganttAPI, ganttRendering, ganttDemos, milestone }
            };

            this.tasks = new ObservableCollection<GanttTask>() { iterationTask };
            this.visibleTime = new DateRange(date.AddDays(-1), date.AddDays(9));
            this.timeLineDeadlineBehavior = new TimeLineDeadlineBehavior();

            this.ProjectDeadline = date.AddDays(8);
        }
Ejemplo n.º 14
0
 public object Generate(IUnitOfWork uow, DateRange dateRange, string type, int start,
     int length, out int recordcount)
 {
     recordcount = 0;
     switch (type)
     {
         case "alllogs":
             return ShowAllLogs(uow, dateRange, start,
      length, out recordcount);
         case "usage":
             return GenerateUsageReport(uow, dateRange, start,
      length, out recordcount);
         case "incident":
             return ShowAllIncidents(uow, dateRange, start,
     length, out recordcount);
         case "fiveRecentIncident":
             return ShowMostRecent5Incidents(uow, out recordcount);
         case "showBookerThroughput":
             return ShowBookerThroughput(uow, dateRange, start,
      length, out recordcount);
         case "showBRResponsiveness":
             return ShowBRResponsiveness(uow, dateRange, start,
      length, out recordcount);
     }
     return this;
 }
Ejemplo n.º 15
0
 /**
  * @param validSince `validSince` is a <code>DateTime</code> object, it's the first time Pipl's
  *                   crawlers found this data on the page.
  * @param degree     degree
  * @param school     school
  * @param dateRange  `dateRange` is A <code>DateRange</code> object (Pipl.APIs.Data.Fields.DateRange),
  *                   that's the time the person was studying.
  */
 public Education(string degree = null, string school = null, DateRange dateRange = null, DateTime? validSince = null)
     : base(validSince)
 {
     this.Degree = degree;
     this.School = school;
     this.DateRange = dateRange;
 }
Ejemplo n.º 16
0
        public static IList<ITask> Collapse(this IEnumerable<ITask> taskCollection)
        {
            var taskList = taskCollection.ToList();

            if (taskCollection == null)
            {
                return null;
            }

            var output = new Collection<ITask>();

            // Grabbing all time split points and sorting them
            List<DateTime> timeEvents = taskList.SelectMany(task => new[] { task.DateRange.StartTime, task.DateRange.EndTime })
                                                     .Distinct()
                                                     .OrderBy(x => x)
                                                     .ToList();

            for (var i = 0; i < timeEvents.Count - 1; i++)
            {
                var newSpan = new DateRange(timeEvents[i], timeEvents[i + 1]);

                var overlappingTasks = taskList.Where(x => x.DateRange.Overlaps(newSpan));

                if (overlappingTasks.Any())
                {
                    var quantityPerHour = overlappingTasks.Sum(x => x.QuantityPerHour);
                    output.Add(Task.CreateUsingQuantityPerHour(newSpan, quantityPerHour));
                }
            }

            return output;
        }
Ejemplo n.º 17
0
 protected DateTime GetRangeEnd(DateRange range)
 {
     switch (range) {
         case DateRange.Today:
             return DateTime.Now;
         case DateRange.Last24Hours:
             return DateTime.Now;
         case DateRange.ThisWeek:
             return DateTime.Now;
         case DateRange.Last7Days:
             return DateTime.Now;
         case DateRange.ThisMonth:
             return DateTime.Now;
         case DateRange.Last30Days:
             return DateTime.Now;
         case DateRange.ThisYear:
             return DateTime.Now;
         case DateRange.LastYear:
             return new DateTime(DateTime.Now.Year, 1, 1);
         case DateRange.All:
             return new DateTime(2030, 1, 1);
         case DateRange.LastMonth:
             return new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMinutes(-1);
         default:
             break;
     }
     return DateTime.Now;
 }
Ejemplo n.º 18
0
        public void Equals_ReturnsTrueForEquivelantStartAndNullEndDates()
        {
            var start = DateTime.Today;
            var target = new DateRange(start, null);
            var other = new DateRange(start, null);

            Assert.AreEqual(true, target.Equals(other));
        }
        public ViewModel()
        {
            var start = new DateTime(DateTime.Today.Year, Math.Max(1, DateTime.Today.Month - 1), 1);
            var end = start.AddMonths(5);
            this.visibleRange = new DateRange(start, end);

            this.HighlightCommand = new DelegateCommand(this.HighlightExecuted);
        }
        public int MostSolutionsBetween(DateRange range)
        {
            var result = this.quizzes.All()
                .Max(q => q.Solutions.Count(
                    s => range.From <= s.CreatedOn && s.CreatedOn <= range.To));

            return result;
        }
Ejemplo n.º 21
0
 public void DateRangeConstructorTest()
 {
     Nullable<DateTime> startDate = DateTime.Today;
     Nullable<DateTime> endDate = DateTime.Today.AddDays(1);
     DateRange target = new DateRange(startDate, endDate);
     Assert.AreEqual(startDate, target.StartDate);
     Assert.AreEqual(endDate, target.EndDate);
 }
Ejemplo n.º 22
0
 public void Constructor_SetsStartDateAndEndDateValues()
 {
     DateTime? startDate = DateTime.Today;
     DateTime? endDate = DateTime.Today.AddDays(1);
     var target = new DateRange(startDate, endDate);
     Assert.AreEqual(startDate, target.StartDate);
     Assert.AreEqual(endDate, target.EndDate);
 }
Ejemplo n.º 23
0
        public virtual RedirectToRouteResult DateRange(DateRange range)
        {
            var query = Session.Get<ActivityQuery>();
            query.DateFrom = DateRangeToDateTime(range);
            query.DateTo = null;

            return RedirectToAction(MVC.Activities.ActionNames.Index);
        }
Ejemplo n.º 24
0
        public MyViewModel()
        {
            this._TimeLineResourceBehavior = new ResourceTimeLineVisualizationBehavior();

            var resources = new ObservableCollection<GanttResource>()
            {
                new GanttResource("Thomas Hardy", Colors.Red),
                new GanttResource("Elizabeth Lincoln", Colors.Blue),
                new GanttResource("Christina Berglung", Colors.Orange)
            };

            var date = DateTime.Now;
            var ganttAPI = new GanttResourceTask()
            {
                Start = date,
                End = date.AddDays(2),
                Title = "Design public API",
                Description = "Description: Design public API",
                GanttResource = resources[0]
            };
            var ganttRendering = new GanttResourceTask()
            {
                Start = date.AddDays(2).AddHours(8),
                End = date.AddDays(4),
                Title = "Gantt Rendering",
                Description = "Description: Gantt Rendering",
                GanttResource = resources[1]
            };
            var ganttDemos = new GanttResourceTask()
            {
                Start = date.AddDays(4.5),
                End = date.AddDays(7),
                Title = "Gantt Demos",
                Description = "Description: Gantt Demos",
                GanttResource = resources[2]
            };
            var milestone = new GanttResourceTask()
            {
                Start = date.AddDays(7),
                End = date.AddDays(7).AddHours(1),
                Title = "Review",
                Description = "Review",
                GanttResource = resources[2],
                IsMilestone = true
            };
            ganttRendering.Dependencies.Add(new Dependency() { FromTask = ganttAPI });
            ganttDemos.Dependencies.Add(new Dependency() { FromTask = ganttRendering });
            var iterationTask = new GanttResourceTask()
            {
                Start = date,
                End = date.AddDays(7),
                Title = "Iteration 1",
                Children = { ganttAPI, ganttRendering, ganttDemos, milestone }
            };
            this._Tasks = new ObservableCollection<GanttResourceTask>() { iterationTask };

            this._VisibleTime = new DateRange(date.AddDays(-1), date.AddDays(12));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StaffIdentifier"/> class.
        /// </summary>
        /// <param name="staffIdentifierType">Type of the staff identifier.</param>
        /// <param name="identifierNumber">The identifier number.</param>
        /// <param name="effectiveDateRange">The effective date range.</param>
        public StaffIdentifier(StaffIdentifierType staffIdentifierType, string identifierNumber, DateRange effectiveDateRange)
        {
            Check.IsNotNull(staffIdentifierType, "Staff identifier type is required.");
            Check.IsNotNullOrWhitespace(identifierNumber, "Identifier number is required.");

            _staffIdentifierType = staffIdentifierType;
            _identifierNumber = identifierNumber;
            _effectiveDateRange = effectiveDateRange;
        }
Ejemplo n.º 26
0
        public ViewModel()
        {
            this.tasks = new SoftwarePlanning();
            var start = this.tasks.Min(t => t.Start).Date;
            var end = this.tasks.Max(t => t.End).Date;

            this.visibleRange = new DateRange(start.AddHours(-12), end.AddDays(3));
            this.doubleClickCommand = new DelegateCommand(OnDoubleClickCommandExecuted);
        }
		public string[] RetrieveAuthors(DateRange dateRange)
		{
			var authors = GetChangesets(CreateDateVSpec(dateRange.StartDate.GetValueOrDefault()), CreateDateVSpec(dateRange.EndDate.GetValueOrDefault()))
					.Select(changeset => changeset.Committer)
					.Distinct()
					.ToArray();

			return authors;
		}
Ejemplo n.º 28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LocationIdentifier"/> class.
        /// </summary>
        /// <param name="locationIdentifierType">Type of the location identifier.</param>
        /// <param name="identifierNumber">The identifier number.</param>
        /// <param name="effectiveDateRange">The effective date range.</param>
        protected internal LocationIdentifier(LocationIdentifierType locationIdentifierType, string identifierNumber, DateRange effectiveDateRange)
        {
            Check.IsNotNull ( locationIdentifierType, () => LocationIdentifierType );
            Check.IsNotNullOrWhitespace ( identifierNumber, () => IdentifierNumber );

            _locationIdentifierType = locationIdentifierType;
            _identifierNumber = identifierNumber;
            _effectiveDateRange = effectiveDateRange;
        }
Ejemplo n.º 29
0
 /**
  * @param validSince
  *            `validSince` is a <code>DateTime</code> object, it's the first
  *            time Pipl's crawlers found this data on the page.
  * @param title
  *            title
  * @param organization
  *            organization
  * @param industry
  *            industry
  * @param dateRange
  *            `dateRange` is A <code>DateRange</code> object
  *            (Pipl.APIs.Data.Fields.DateRange), that's the time the person
  *            held this job.
  */
 public Job(string title = null, string organization = null, string industry = null, DateRange dateRange = null,
     DateTime? validSince = null)
     : base(validSince)
 {
     this.Title = title;
     this.Organization = organization;
     this.Industry = industry;
     this.DateRange = dateRange;
 }
Ejemplo n.º 30
0
        protected int GetMaxSolutions(DateRange range)
        {
            var maxSolutions = this.Cache.Get(
                range.GetType().Name,
                () => this.Ranking.MostSolutionsBetween(range),
                CacheConstants.DurationMaxSolutions);

            return maxSolutions;
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext   = new RockContext();
            var pledgeService = new FinancialPledgeService(rockContext);
            var sortProperty  = gPledges.SortProperty;
            var pledges       = pledgeService.Queryable();

            Person person = null;

            if (TargetPerson != null)
            {
                person = TargetPerson;
            }
            else
            {
                int?personId = gfPledges.GetUserPreference("Person").AsIntegerOrNull();
                if (personId.HasValue && ppFilterPerson.Visible)
                {
                    person = new PersonService(rockContext).Get(personId.Value);
                }
            }

            if (person != null)
            {
                // if a person is specified, get pledges for that person ( and also anybody in their GivingUnit )
                pledges = pledges.Where(p => p.PersonAlias.Person.GivingId == person.GivingId);
            }

            // Filter by configured limit accounts if specified.
            var accountGuids = GetAttributeValue("Accounts").SplitDelimitedValues().AsGuidList();

            if (accountGuids.Any())
            {
                pledges = pledges.Where(p => accountGuids.Contains(p.Account.Guid));
            }

            // get the accounts and make sure they still exist by checking the database
            var accountIds = gfPledges.GetUserPreference("Accounts").Split(',').AsIntegerList();

            accountIds = new FinancialAccountService(rockContext).GetByIds(accountIds).Select(a => a.Id).ToList();

            if (accountIds.Any() && apFilterAccount.Visible)
            {
                pledges = pledges.Where(p => p.AccountId.HasValue && accountIds.Contains(p.AccountId.Value));
            }

            // Date Range
            DateRange filterDateRange = DateRangePicker.CalculateDateRangeFromDelimitedValues(gfPledges.GetUserPreference("Date Range"));
            var       filterStartDate = filterDateRange.Start ?? DateTime.MinValue;
            var       filterEndDate   = filterDateRange.End ?? DateTime.MaxValue;

            /****
             * Include any pledges whose Start/EndDates overlap with the Filtered Date Range
             *
             * * Pledge1 Range 1/1/2011 - 12/31/2011
             * * Pledge2 Range 1/1/0000 - 1/1/9999
             * * Pledge3 Range 6/1/2011 - 6/1/2012
             *
             * Filter1 Range 1/1/2010 - 1/1/2013
             * * * All Pledges should show
             * Filter1 Range 1/1/2012 - 1/1/2013
             * * * Pledge2 and Pledge3 should show
             * Filter2 Range 5/1/2012 - 5/2/2012
             * * * Pledge2 and Pledge3 should show
             * Filter3 Range 5/1/2012 - 1/1/9999
             * * * Pledge2 and Pledge3 should show
             * Filter4 Range 5/1/2010 - 5/1/2010
             * * * Pledge2 should show
             ***/

            // exclude pledges that start after the filter's end date or end before the filter's start date
            if (drpDates.Visible && (filterDateRange.Start.HasValue || filterDateRange.End.HasValue))
            {
                pledges = pledges.Where(p => !(p.StartDate > filterEndDate) && !(p.EndDate < filterStartDate));
            }

            // Filter query by any configured attribute filters
            if (AvailableAttributes != null && AvailableAttributes.Any())
            {
                foreach (var attribute in AvailableAttributes)
                {
                    var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString());
                    pledges = attribute.FieldType.Field.ApplyAttributeQueryFilter(pledges, filterControl, attribute, pledgeService, Rock.Reporting.FilterMode.SimpleFilter);
                }
            }

            // Last Modified
            DateRange filterModifiedDateRange = DateRangePicker.CalculateDateRangeFromDelimitedValues(gfPledges.GetUserPreference("Last Modified"));
            var       filterModifiedStartDate = filterModifiedDateRange.Start ?? DateTime.MinValue;
            var       filterModifiedEndDate   = filterModifiedDateRange.End ?? DateTime.MaxValue;

            if (drpLastModifiedDates.Visible && (filterModifiedDateRange.Start.HasValue || filterModifiedDateRange.End.HasValue))
            {
                pledges = pledges.Where(p => !(p.ModifiedDateTime >= filterModifiedEndDate) && !(p.ModifiedDateTime <= filterModifiedStartDate));
            }

            gPledges.DataSource = sortProperty != null?pledges.Sort(sortProperty).ToList() : pledges.OrderBy(p => p.AccountId).ToList();

            gPledges.DataBind();

            var showAccountSummary = this.GetAttributeValue("ShowAccountSummary").AsBoolean();

            if (showAccountSummary || TargetPerson == null)
            {
                pnlSummary.Visible = true;

                var summaryList = pledges
                                  .GroupBy(a => a.AccountId)
                                  .Select(a => new AccountSummaryRow
                {
                    AccountId   = a.Key.Value,
                    TotalAmount = a.Sum(x => x.TotalAmount),
                    Name        = a.Where(p => p.Account != null).Select(p => p.Account.Name).FirstOrDefault(),
                    Order       = a.Where(p => p.Account != null).Select(p => p.Account.Order).FirstOrDefault()
                }).ToList();

                var grandTotalAmount = (summaryList.Count > 0) ? summaryList.Sum(a => a.TotalAmount) : 0;
                lGrandTotal.Text             = grandTotalAmount.FormatAsCurrency();
                rptAccountSummary.DataSource = summaryList.Select(a => new { a.Name, TotalAmount = a.TotalAmount.FormatAsCurrency() }).ToList();
                rptAccountSummary.DataBind();
            }
            else
            {
                pnlSummary.Visible = false;
            }
        }
Ejemplo n.º 32
0
        // check if a given user has used his hourly comment posting quota
        protected bool UserHourlyCommentPostingQuotaUsed(VoatRuleContext context)
        {
            // read hourly posting quota configuration parameter from web.config
            int limit = VoatSettings.Instance.HourlyCommentPostingQuota;

            using (var repo = new Repository())
            {
                // check how many comments user made in the last 59 minutes
                var userCommentSubmissionsInPastHour = repo.UserContributionCount(context.UserName, Domain.Models.ContentType.Comment, null, DateRange.StartFrom(TimeSpan.FromHours(1)));

                if (limit <= userCommentSubmissionsInPastHour)
                {
                    return(true);
                }
                return(false);
            }
        }
Ejemplo n.º 33
0
        // check if a given user has used his daily posting quota for a given subverse
        protected bool UserDailyPostingQuotaForSubUsed(VoatRuleContext context, string subverse)
        {
            // read daily posting quota per sub configuration parameter from web.config
            int limit = VoatSettings.Instance.DailyPostingQuotaPerSub;

            using (var repo = new Repository())
            {
                // check how many submission user made today
                var userSubmissionsToTargetSub = repo.UserContributionCount(context.UserName, Domain.Models.ContentType.Submission, subverse, DateRange.StartFrom(TimeSpan.FromHours(24)));
                //var userSubmissionsToTargetSub = repo.UserSubmissionCount(context.UserName, TimeSpan.FromHours(24), null, subverse);

                if (limit <= userSubmissionsToTargetSub)
                {
                    return(true);
                }
                return(false);
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// SaveOrUpdate given Booking
        /// </summary>
        /// <param name="booking"></param>
        /// <returns>The saved booking, with its new id, if a new booking (which was never saved) is passed</returns>
        public async static Task <Booking> Save(Booking booking)
        {
            using (ResotelContext ctx = new ResotelContext())
            {
                Booking savedBooking = null;

                List <Room> rooms = await _getRoomRequest(ctx, true)
                                    .ToListAsync();

                List <Option> options = await _getOptionRequest(ctx)
                                        .ToListAsync();

                Client client = await _getClientRequest(ctx).FirstOrDefaultAsync(
                    cl => cl.Id == booking.Client.Id
                    );

                _assignCtxRooms(booking, rooms);
                _assignCtxOptions(booking, options);

                if (client != null)
                {
                    booking.Client = client;
                }

                if (booking.Id == 0)
                {
                    ctx.Entry(booking).State = EntityState.Added;
                }
                else
                {
                    Booking trackedBooking = await ctx.Bookings.FirstOrDefaultAsync(b => b.Id == booking.Id);

                    _updateTrackedBooking(trackedBooking, booking, ctx);
                    await _updateOptionChoices(trackedBooking.OptionChoices, booking.OptionChoices, ctx);
                    await _updateBookingRooms(trackedBooking, booking.Rooms, ctx);
                    await _updateRoomPacks(trackedBooking, trackedBooking.RoomPacks, booking.RoomPacks, ctx);

                    _updateTrackedBookingState(trackedBooking, booking.State, ctx);

                    DateRange trackedBookingDates = await _getTrackedBookingDates(booking.Dates, ctx);

                    trackedBooking.Dates = trackedBookingDates;
                }



                List <Room> unavailableRooms = new List <Room>();

                using (DbContextTransaction transaction = ctx.Database.BeginTransaction())
                {
                    try
                    {
                        await _fillUnavailableRooms(booking, ctx, unavailableRooms);

                        if (unavailableRooms.Count == 0)
                        {
                            savedBooking = await _saveBooking(booking, ctx, transaction);
                        }
                        else
                        {
                            List <Room> unavailableReplacementRooms = await _replaceRooms(booking, ctx, unavailableRooms);

                            if (unavailableReplacementRooms.Count > 0)
                            {
                                HashSet <RoomKind> unreplaceableRoomKinds = new HashSet <RoomKind>(unavailableReplacementRooms.ConvertAll(room => room.Kind));
                                transaction.Rollback();
                                throw new InvalidOperationException(
                                          $"Impossible de sauvegarder la réservation : nous n'avons plus assez de chambres des types {string.Join(",", unreplaceableRoomKinds)}");
                            }
                            else
                            {
                                savedBooking = await _saveBooking(booking, ctx, transaction);
                            }
                        }

                        return(savedBooking);
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="node"></param>
        /// <param name="mgr"></param>
        /// <returns></returns>
        public override IFeature FromXml(XmlNode node, XmlNamespaceManager mgr)
        {
            if (node != null && node.HasChildNodes)
            {
                if (node.FirstChild.Attributes.Count > 0)
                {
                    Id = node.FirstChild.Attributes["gml:id"].InnerText;
                }
            }

            var fixedDateRangeNode = node.FirstChild.SelectSingleNode("fixedDateRange", mgr);

            if (fixedDateRangeNode != null && fixedDateRangeNode.HasChildNodes)
            {
                FixedDateRange = new DateRange();
                FixedDateRange.FromXml(fixedDateRangeNode, mgr);
            }

            var periodicDateRangeNodes = node.FirstChild.SelectNodes("periodicDateRange", mgr);

            if (periodicDateRangeNodes != null && periodicDateRangeNodes.Count > 0)
            {
                var dateRanges = new List <DateRange>();
                foreach (XmlNode periodicDateRangeNode in periodicDateRangeNodes)
                {
                    var newDateRange = new DateRange();
                    newDateRange.FromXml(periodicDateRangeNode, mgr);
                    dateRanges.Add(newDateRange);
                }
                PeriodicDateRange = dateRanges.ToArray();
            }

            var featureNameNodes = node.FirstChild.SelectNodes("featureName", mgr);

            if (featureNameNodes != null && featureNameNodes.Count > 0)
            {
                var featureNames = new List <FeatureName>();
                foreach (XmlNode featureNameNode in featureNameNodes)
                {
                    var newFeatureName = new FeatureName();
                    newFeatureName.FromXml(featureNameNode, mgr);
                    featureNames.Add(newFeatureName);
                }
                FeatureName = featureNames.ToArray();
            }

            var sourceIndicationNodes = node.FirstChild.SelectNodes("sourceIndication", mgr);

            if (sourceIndicationNodes != null && sourceIndicationNodes.Count > 0)
            {
                var sourceIndications = new List <SourceIndication>();
                foreach (XmlNode sourceIndicationNode in sourceIndicationNodes)
                {
                    if (sourceIndicationNode != null && sourceIndicationNode.HasChildNodes)
                    {
                        var sourceIndication = new SourceIndication();
                        sourceIndication.FromXml(sourceIndicationNode, mgr);
                        sourceIndications.Add(sourceIndication);
                    }
                }
                SourceIndication = sourceIndications.ToArray();
            }

            var callNameNode = node.FirstChild.SelectSingleNode("callName", mgr);

            if (callNameNode != null && callNameNode.HasChildNodes)
            {
                CallName = callNameNode.FirstChild.InnerText;
            }

            var callSignNode = node.FirstChild.SelectSingleNode("callSign", mgr);

            if (callSignNode != null && callSignNode.HasChildNodes)
            {
                CallSign = callSignNode.FirstChild.InnerText;
            }

            var categoryOfCommPrefNode = node.FirstChild.SelectSingleNode("categoryOfCommPref", mgr);

            if (categoryOfCommPrefNode != null && categoryOfCommPrefNode.HasChildNodes)
            {
                CategoryOfCommPref = categoryOfCommPrefNode.FirstChild.InnerText;
            }

            var communicationChannelNodes = node.FirstChild.SelectNodes("communicationChannel", mgr);

            if (communicationChannelNodes != null && communicationChannelNodes.Count > 0)
            {
                var channels = new List <string>();
                foreach (XmlNode communicationChannelNode in communicationChannelNodes)
                {
                    if (communicationChannelNode != null && communicationChannelNode.HasChildNodes)
                    {
                        channels.Add(communicationChannelNode.FirstChild.InnerText);
                    }
                }

                CommunicationChannel = channels.ToArray();
            }

            var contactInstructionsNode = node.FirstChild.SelectSingleNode("contactInstructions", mgr);

            if (contactInstructionsNode != null && contactInstructionsNode.HasChildNodes)
            {
                ContactInstructions = contactInstructionsNode.FirstChild.InnerText;
            }

            var mmsiCodeNode = node.FirstChild.SelectSingleNode("mMSICode", mgr);

            if (mmsiCodeNode != null && mmsiCodeNode.HasChildNodes)
            {
                MMsiCode = mmsiCodeNode.FirstChild.InnerText;
            }

            var contactAddressNodes = node.FirstChild.SelectNodes("contactAddress", mgr);

            if (contactAddressNodes != null && contactAddressNodes.Count > 0)
            {
                var contactAddresses = new List <ContactAddress>();
                foreach (XmlNode contactAddressNode in contactAddressNodes)
                {
                    if (contactAddressNode != null && contactAddressNode.HasChildNodes)
                    {
                        var newContactAddress = new ContactAddress();
                        newContactAddress.FromXml(contactAddressNode, mgr);
                        contactAddresses.Add(newContactAddress);
                    }
                }
                ContactAddress = contactAddresses.ToArray();
            }

            var informationNodes = node.FirstChild.SelectNodes("information", mgr);

            if (informationNodes != null && informationNodes.Count > 0)
            {
                var informations = new List <Information>();
                foreach (XmlNode informationNode in informationNodes)
                {
                    if (informationNode != null && informationNode.HasChildNodes)
                    {
                        var newInformation = new Information();
                        newInformation.FromXml(informationNode, mgr);
                        informations.Add(newInformation);
                    }
                }
                Information = informations.ToArray();
            }

            var frequencyPairNodes = node.FirstChild.SelectNodes("frequencyPair", mgr);

            if (frequencyPairNodes != null && frequencyPairNodes.Count > 0)
            {
                var frequencyPairs = new List <FrequencyPair>();
                foreach (XmlNode frequencyPairNode in frequencyPairNodes)
                {
                    if (frequencyPairNode != null && frequencyPairNode.HasChildNodes)
                    {
                        var newFrequencyPair = new FrequencyPair();
                        newFrequencyPair.FromXml(frequencyPairNode, mgr);
                        frequencyPairs.Add(newFrequencyPair);
                    }
                }
                FrequencyPair = frequencyPairs.ToArray();
            }

            var onlineResourceNodes = node.FirstChild.SelectNodes("onlineResource", mgr);

            if (onlineResourceNodes != null && onlineResourceNodes.Count > 0)
            {
                var onlineResources = new List <OnlineResource>();
                foreach (XmlNode onlineResourceNode in onlineResourceNodes)
                {
                    if (onlineResourceNode != null && onlineResourceNode.HasChildNodes)
                    {
                        var newOnlineResource = new OnlineResource();
                        newOnlineResource.FromXml(onlineResourceNode, mgr);
                        onlineResources.Add(newOnlineResource);
                    }
                }
                OnlineResource = onlineResources.ToArray();
            }

            var radioCommunicationNodes = node.FirstChild.SelectNodes("radiocommunications", mgr);

            if (radioCommunicationNodes != null && radioCommunicationNodes.Count > 0)
            {
                var radioCommunications = new List <RadioCommunications>();
                foreach (XmlNode radioCommunicationNode in radioCommunicationNodes)
                {
                    if (radioCommunicationNode != null && radioCommunicationNode.HasChildNodes)
                    {
                        var newRadioCommunications = new RadioCommunications();
                        newRadioCommunications.FromXml(radioCommunicationNode, mgr);
                        radioCommunications.Add(newRadioCommunications);
                    }
                }
                RadioCommunications = radioCommunications.ToArray();
            }

            var teleCommunicationNodes = node.FirstChild.SelectNodes("telecommunications", mgr);

            if (teleCommunicationNodes != null && teleCommunicationNodes.Count > 0)
            {
                var teleCommunications = new List <Telecommunications>();
                foreach (XmlNode teleCommunicationNode in teleCommunicationNodes)
                {
                    if (teleCommunicationNode != null && teleCommunicationNode.HasChildNodes)
                    {
                        var newTelecommunications = new Telecommunications();
                        newTelecommunications.FromXml(teleCommunicationNode, mgr);
                        teleCommunications.Add(newTelecommunications);
                    }
                }
                Telecommunications = teleCommunications.ToArray();
            }

            var linkNodes = node.FirstChild.SelectNodes("*[boolean(@xlink:href)]", mgr);

            if (linkNodes != null && linkNodes.Count > 0)
            {
                var links = new List <Link>();
                foreach (XmlNode linkNode in linkNodes)
                {
                    var newLink = new Link();
                    newLink.FromXml(linkNode, mgr);
                    links.Add(newLink);
                }
                Links = links.ToArray();
            }

            return(this);
        }
Ejemplo n.º 36
0
        public static DatesRangeLimits GetRangeLimits(DateRange range)
        {
            var today     = DateTime.Today;
            var weekStart = GetStartOfTheWeek(today);

            switch (range)
            {
            case DateRange.Future:
                return(new DatesRangeLimits(today.AddDays(-today.Day + 1).AddMonths(2), DateTime.MaxValue));

            case DateRange.NextMonth:
                return(new DatesRangeLimits(
                           today.AddDays(-today.Day + 1).AddMonths(1),
                           today.AddDays(-today.Day + 1).AddMonths(2).AddMilliseconds(-1)));

            case DateRange.NextWeek:
                return(new DatesRangeLimits(weekStart.AddDays(14), weekStart.AddDays(14).AddMilliseconds(-1)));

            case DateRange.Tomorrow:
                return(new DatesRangeLimits(today.AddDays(1), today.AddDays(2).AddMilliseconds(-1)));

            case DateRange.Today:
                return(new DatesRangeLimits(today, today.AddDays(1).AddMilliseconds(-1)));

            case DateRange.Yesterday:
                return(new DatesRangeLimits(today.AddDays(-1), today.AddMilliseconds(-1)));

            case DateRange.ThisWeek:
                return(new DatesRangeLimits(weekStart, weekStart.AddDays(7).AddMilliseconds(-1)));

            case DateRange.PrevWeek:
                return(new DatesRangeLimits(weekStart.AddDays(-7), weekStart.AddMilliseconds(-1)));

            case DateRange.ThisMonth:
                return(new DatesRangeLimits(
                           today.AddDays(-today.Day + 1),
                           today.AddDays(-today.Day + 1).AddMonths(1).AddMilliseconds(-1)));

            case DateRange.PrevMonth:
                return(new DatesRangeLimits(
                           today.AddDays(-today.Day + 1).AddMonths(-1),
                           today.AddDays(-today.Day + 1).AddMilliseconds(-1)));

            case DateRange.ThisYear:
                return(new DatesRangeLimits(
                           today.AddDays(-today.Day + 1).AddMonths(-today.Month + 1),
                           today.AddDays(-today.Day + 1).AddMonths(-today.Month + 1).AddYears(1).AddMilliseconds(-1)));

            case DateRange.PrevYear:
                return(new DatesRangeLimits(
                           today.AddDays(-today.Day + 1).AddMonths(-today.Month + 1).AddYears(-1),
                           today.AddDays(-today.Day + 1).AddMonths(-today.Month + 1).AddMilliseconds(-1)));

            case DateRange.LongAgo:
                return(new DatesRangeLimits(
                           DateTime.MinValue,
                           today.AddDays(-today.Day + 1).AddMonths(-today.Month + 1).AddYears(-1).AddMilliseconds(-1)));
            }

            throw new ArgumentException($"{range} range is not implemented");
        }
Ejemplo n.º 37
0
        public void ToJournalEntryFileName_ReturnsValidName(DateTime from, DateTime to, string expectedFileName)
        {
            var range = new DateRange(from, to);

            range.ToJournalEntryFileName().Should().Be(expectedFileName);
        }
Ejemplo n.º 38
0
        public void Includes_ReturnsFalse_WhenDateIsOutOfRange(DateTime from, DateTime to, DateTime targetDate)
        {
            var range = new DateRange(from, to);

            range.Includes(LocalDate.FromDateTime(targetDate)).Should().BeFalse();
        }
Ejemplo n.º 39
0
        public void Includes_ReturnsTrue_WhenDateIsWithinRange(DateTime from, DateTime to, DateTime targetDate)
        {
            var range = new DateRange(from, to);

            range.Includes(LocalDate.FromDateTime(targetDate)).Should().BeTrue();
        }
Ejemplo n.º 40
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="node"></param>
        /// <param name="mgr"></param>
        /// <returns></returns>
        public override IFeature FromXml(XmlNode node, XmlNamespaceManager mgr)
        {
            if (node != null && node.HasChildNodes)
            {
                if (node.FirstChild.Attributes.Count > 0)
                {
                    Id = node.FirstChild.Attributes["gml:id"].InnerText;
                }
            }

            var periodicDateRangeNodes = node.FirstChild.SelectNodes("periodicDateRange", mgr);

            if (periodicDateRangeNodes != null && periodicDateRangeNodes.Count > 0)
            {
                var dateRanges = new List <DateRange>();
                foreach (XmlNode periodicDateRangeNode in periodicDateRangeNodes)
                {
                    var newDateRange = new DateRange();
                    newDateRange.FromXml(periodicDateRangeNode, mgr);
                    dateRanges.Add(newDateRange);
                }
                PeriodicDateRange = dateRanges.ToArray();
            }

            var fixedDateRangeNode = node.FirstChild.SelectSingleNode("fixedDateRange", mgr);

            if (fixedDateRangeNode != null && fixedDateRangeNode.HasChildNodes)
            {
                FixedDateRange = new DateRange();
                FixedDateRange.FromXml(fixedDateRangeNode, mgr);
            }

            var featureNameNodes = node.FirstChild.SelectNodes("featureName", mgr);

            if (featureNameNodes != null && featureNameNodes.Count > 0)
            {
                var featureNames = new List <FeatureName>();
                foreach (XmlNode featureNameNode in featureNameNodes)
                {
                    var newFeatureName = new FeatureName();
                    newFeatureName.FromXml(featureNameNode, mgr);
                    featureNames.Add(newFeatureName);
                }
                FeatureName = featureNames.ToArray();
            }

            var sourceIndication = node.FirstChild.SelectSingleNode("sourceIndication", mgr);

            if (sourceIndication != null && sourceIndication.HasChildNodes)
            {
                SourceIndication = new SourceIndication();
                SourceIndication.FromXml(sourceIndication, mgr);
            }

            var textContentNodes = node.FirstChild.SelectNodes("textContent", mgr);

            if (textContentNodes != null && textContentNodes.Count > 0)
            {
                var textContents = new List <TextContent>();
                foreach (XmlNode textContentNode in textContentNodes)
                {
                    if (textContentNode != null && textContentNode.HasChildNodes)
                    {
                        var content = new TextContent();
                        content.FromXml(textContentNode, mgr);
                        textContents.Add(content);
                    }
                }
                TextContent = textContents.ToArray();
            }

            var categoryOfVesselTrafficServiceNode = node.FirstChild.SelectSingleNode("categoryOfVesselTrafficService", mgr);

            if (categoryOfVesselTrafficServiceNode != null && categoryOfVesselTrafficServiceNode.HasChildNodes)
            {
                CategoryOfVesselTrafficService = categoryOfVesselTrafficServiceNode.FirstChild.InnerText;
            }

            var serviceAccessProcedureNode = node.FirstChild.SelectSingleNode("serviceAccessProcedure", mgr);

            if (serviceAccessProcedureNode != null)
            {
                ServiceAccessProcedure = serviceAccessProcedureNode.FirstChild.InnerText;
            }

            var requirementsForMaintenanceOfListeningWatchNode = node.FirstChild.SelectSingleNode("requirementsForMaintenanceOfListeningWatch", mgr);

            if (requirementsForMaintenanceOfListeningWatchNode != null && requirementsForMaintenanceOfListeningWatchNode.HasChildNodes)
            {
                RequirementsForMaintenanceOfListeningWatch = requirementsForMaintenanceOfListeningWatchNode.FirstChild.InnerText;
            }

            var linkNodes = node.FirstChild.SelectNodes("*[boolean(@xlink:href)]", mgr);

            if (linkNodes != null && linkNodes.Count > 0)
            {
                var links = new List <Link>();
                foreach (XmlNode linkNode in linkNodes)
                {
                    var newLink = new Link();
                    newLink.FromXml(linkNode, mgr);
                    links.Add(newLink);
                }
                Links = links.ToArray();
            }

            return(this);
        }
Ejemplo n.º 41
0
        /// <summary>
        /// محاسبه کارکرد پرسنل اقماری
        /// </summary>
        /// <param name="MyRule"></param>
        public void R2501(AssignedRule MyRule)
        {
            //5 کارکرد خالص روانه ماهانه
            //7  کارکرددرروز
            //8  کارکردخالص ساعتي ماهانه
            //3 کارکرد ناخالص ماهانه
            //9 حضور ماهانه
            //3005 غیبت ماهانه
            //4005 اضافه کار ماهانه
            //3034 غیبت ساعتی ماهانه
            //10 کارکرد لازم ماهانه
            if (this.DoConcept(5021).Value > 0)
            {
                GetLog(MyRule, DebugRuleState.Before, 3, 4005, 5, 3034, 3005, 8, 10, 4002);
                int       karkerd   = this.DoConcept(5).Value;
                DateRange dateRange = this.GetDateRange(5, this.RuleCalculateDate);
                if (dateRange != null)
                {
                    int monthDays = (dateRange.ToDate - dateRange.FromDate).Days + 1;

                    int  maxKarkerd       = 23;
                    bool calcHouryAbsence = true;
                    if (maxKarkerd - karkerd > 0) //غیبت روزانه
                    {
                        this.DoConcept(10).Value = karkerd * this.DoConcept(7).Value;
                    }
                    else
                    {
                        this.DoConcept(10).Value = maxKarkerd * this.DoConcept(7).Value;
                    }
                    float resultKarkerd = 0;
                    if (this.DoConcept(3).Value < this.DoConcept(10).Value)//به لحاظ مقدار حضور کسری دارد
                    {
                        //(karkerd na khales / 230) * month days
                        resultKarkerd    = (((float)this.DoConcept(3).Value / (float)(maxKarkerd * this.DoConcept(7).Value)) * monthDays);
                        calcHouryAbsence = false;
                    }
                    else
                    {
                        //(karkerd ruzane / 23) * month days
                        resultKarkerd = (((float)karkerd / (float)maxKarkerd) * monthDays);
                        if (resultKarkerd > monthDays)
                        {
                            resultKarkerd = monthDays;
                        }
                        calcHouryAbsence = true;
                    }

                    if (resultKarkerd > (int)resultKarkerd + 0.5)
                    {
                        resultKarkerd = (int)resultKarkerd + 1;
                    }

                    this.DoConcept(8).Value    = 0;
                    this.DoConcept(5).Value    = (int)resultKarkerd;
                    this.DoConcept(3005).Value = ((dateRange.ToDate - dateRange.FromDate).Days + 1) - (int)resultKarkerd;
                    this.DoConcept(4005).Value = this.DoConcept(3).Value - this.DoConcept(10).Value;
                    if (this.DoConcept(4005).Value < 0 && calcHouryAbsence)
                    {
                        int absence = this.DoConcept(4005).Value * -1;
                        this.DoConcept(3005).Value += (int)((float)absence / (float)this.DoConcept(7).Value);
                        this.DoConcept(3034).Value  = absence % this.DoConcept(7).Value;
                        this.DoConcept(5).Value    -= (int)((float)absence / (float)this.DoConcept(7).Value);
                        this.DoConcept(4005).Value  = 0;
                    }
                    else if (!calcHouryAbsence && this.DoConcept(4005).Value < 0)
                    {
                        this.DoConcept(4005).Value = 0;
                    }
                }
            }
            ((PairableScndCnpValue)this.DoConcept(4002)).ClearPairs();
            GetLog(MyRule, DebugRuleState.After, 3, 4005, 5, 3034, 3005, 8, 10, 4002);
        }
Ejemplo n.º 42
0
 /// <summary>
 /// Конструктор.
 /// </summary>
 /// <param name="creationDateRange">Период создания сборки.</param>
 public WithCreationDateRangeSpecification(DateRange creationDateRange)
 {
     this.creationDateRange = creationDateRange ?? throw new ArgumentNullException(nameof(creationDateRange));
 }
Ejemplo n.º 43
0
        /// <summary>
        /// Displays the metric as a donut value.
        /// </summary>
        /// <param name="pageContext">The page context.</param>
        /// <param name="dateRange">The date range.</param>
        /// <param name="primaryMetricSource">The primary metric source.</param>
        private void DisplayDonutValue(DateRange dateRange, List <int> primaryMetricSource)
        {
            var currentWeekValues = GetMetricValues(primaryMetricSource, dateRange, PrimaryMetricKey);

            // does a donut compare to the previous week?
            //var previousWeekValues = GetMetricValues( primaryMetricSource, dateRange - 7 , PrimaryMetricKey );

            var blockValues = new List <MetricValueItem>();

            int currentItemId = 0;

            foreach (var currentValue in currentWeekValues)
            {
                // color each metric by offset
                string metricItemColor = "#6bac43";

                if (currentItemId % 2 != 0)
                {
                    metricItemColor = "#1c683e";
                }
                else if (currentItemId % 3 == 0)
                {
                    metricItemColor = "#2a4930";
                }

                // Create JSON array of data
                if (currentValue != null)
                {
                    blockValues.Add(new MetricValueItem()
                    {
                        value     = (int)currentValue.YValue,
                        color     = metricItemColor,
                        highlight = metricItemColor,
                        label     = currentValue.Metric.Title
                    });
                }
                else
                {
                    // i don't think this ever gets hit
                    blockValues.Add(new MetricValueItem()
                    {
                        value     = 0,
                        color     = metricItemColor,
                        highlight = metricItemColor,
                        label     = currentValue.Metric.Title
                    });
                }

                currentItemId++;
            }

            MetricBlockValues = JsonConvert.SerializeObject(blockValues.ToArray());

            //unused variables
            //var calendar = DateTimeFormatInfo.CurrentInfo.Calendar;

            //var donutMetrics = new MetricService( new RockContext() ).GetByIds( primaryMetricSource );

            //// Current Week of Year
            //var currentWeekOfYear = calendar.GetWeekOfYear( DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Sunday );

            //// Last Week
            //var lastWeekOfYear = calendar.GetWeekOfYear( DateTime.Now.AddDays( -7 ), CalendarWeekRule.FirstDay, DayOfWeek.Sunday );
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="node"></param>
        /// <param name="mgr"></param>
        /// <returns></returns>
        public override IFeature FromXml(XmlNode node, XmlNamespaceManager mgr)
        {
            if (node != null && node.HasChildNodes)
            {
                if (node.FirstChild.Attributes.Count > 0)
                {
                    Id = node.FirstChild.Attributes["gml:id"].InnerText;
                }
            }

            var periodicDateRangeNodes = node.FirstChild.SelectNodes("periodicDateRange", mgr);

            if (periodicDateRangeNodes != null && periodicDateRangeNodes.Count > 0)
            {
                var dateRanges = new List <DateRange>();
                foreach (XmlNode periodicDateRangeNode in periodicDateRangeNodes)
                {
                    var newDateRange = new DateRange();
                    newDateRange.FromXml(periodicDateRangeNode, mgr);
                    dateRanges.Add(newDateRange);
                }
                PeriodicDateRange = dateRanges.ToArray();
            }

            var fixedDateRangeNode = node.FirstChild.SelectSingleNode("fixedDateRange", mgr);

            if (fixedDateRangeNode != null && fixedDateRangeNode.HasChildNodes)
            {
                FixedDateRange = new DateRange();
                FixedDateRange.FromXml(fixedDateRangeNode, mgr);
            }

            var featureNameNodes = node.FirstChild.SelectNodes("featureName", mgr);

            if (featureNameNodes != null && featureNameNodes.Count > 0)
            {
                var featureNames = new List <FeatureName>();
                foreach (XmlNode featureNameNode in featureNameNodes)
                {
                    var newFeatureName = new FeatureName();
                    newFeatureName.FromXml(featureNameNode, mgr);
                    featureNames.Add(newFeatureName);
                }
                FeatureName = featureNames.ToArray();
            }

            var sourceIndication = node.FirstChild.SelectSingleNode("sourceIndication", mgr);

            if (sourceIndication != null && sourceIndication.HasChildNodes)
            {
                SourceIndication = new SourceIndication();
                SourceIndication.FromXml(sourceIndication, mgr);
            }

            var textContentNodes = node.FirstChild.SelectNodes("textContent", mgr);

            if (textContentNodes != null && textContentNodes.Count > 0)
            {
                var textContents = new List <TextContent>();
                foreach (XmlNode textContentNode in textContentNodes)
                {
                    if (textContentNode != null && textContentNode.HasChildNodes)
                    {
                        var content = new TextContent();
                        content.FromXml(textContentNode, mgr);
                        textContents.Add(content);
                    }
                }
                TextContent = textContents.ToArray();
            }

            var underkeelAllowanceNode = node.FirstChild.SelectSingleNode("underkeelAllowance", mgr);

            if (underkeelAllowanceNode != null && underkeelAllowanceNode.HasChildNodes)
            {
                UnderkeelAllowance = new UnderkeelAllowance();
                UnderkeelAllowance.FromXml(underkeelAllowanceNode, mgr);
            }

            var waterLevelTrendNode = node.FirstChild.SelectSingleNode("waterLevelTrend", mgr);

            if (waterLevelTrendNode != null && waterLevelTrendNode.HasChildNodes)
            {
                WaterLevelTrend = waterLevelTrendNode.FirstChild.InnerText;
            }

            var linkNodes = node.FirstChild.SelectNodes("*[boolean(@xlink:href)]", mgr);

            if (linkNodes != null && linkNodes.Count > 0)
            {
                var links = new List <Link>();
                foreach (XmlNode linkNode in linkNodes)
                {
                    var newLink = new Link();
                    newLink.FromXml(linkNode, mgr);
                    links.Add(newLink);
                }
                Links = links.ToArray();
            }

            return(this);
        }
Ejemplo n.º 45
0
        //public static Series MonthlySeries(Series daily, StatisticalMethods sm)
        //{
        //    SeriesList lst = new SeriesList();
        //    lst.Add(daily);
        //    DataTable tbl = MonthlySummary(lst, sm);
        //    return CreateSeries(lst, tbl, 0, 1);
        //}

        /// <summary>
        /// Compute monthly statisitcs
        /// </summary>
        static DataTable MonthlySummary(SeriesList list, StatisticalMethods sm, bool multiYear)
        {
            DataTable tbl = CreateMonthlySummaryTable(list, sm, multiYear);

            for (int i = 0; i < tbl.Rows.Count; i++)
            {
                DateTime  t  = Convert.ToDateTime(tbl.Rows[i][0]);
                DateRange dr = new DateRange(
                    new DateTime(t.Year, t.Month, 1),
                    new DateTime(t.Year, t.Month,
                                 DateTime.DaysInMonth(t.Year, t.Month), 23, 59, 59));

                int[] months = new int[] { t.Month };


                for (int j = 0; j < list.Count; j++)
                {
                    Series subset;
                    if (multiYear)
                    {
                        subset = Math.Subset(list[j], dr);
                    }
                    else
                    {
                        subset = Math.Subset(list[j], months);
                    }

                    if ((sm & StatisticalMethods.Min) == StatisticalMethods.Min)
                    {
                        tbl.Rows[i][m_minColumnIndex[j]] = Math.MinPoint(subset).Value;
                    }

                    if ((sm & StatisticalMethods.Max) == StatisticalMethods.Max)
                    {
                        tbl.Rows[i][m_maxColumnIndex[j]] = Math.MaxPoint(subset).Value;
                    }

                    if ((sm & StatisticalMethods.Mean) == StatisticalMethods.Mean)
                    {
                        tbl.Rows[i][m_meanColumnIndex[j]] = Math.AverageOfSeries(subset);
                    }

                    if ((sm & StatisticalMethods.Count) == StatisticalMethods.Count)
                    {
                        tbl.Rows[i][m_countColumnIndex[j]] = Math.Count(subset);
                    }

                    if ((sm & StatisticalMethods.Sum) == StatisticalMethods.Sum)
                    {
                        tbl.Rows[i][m_sumColumnIndex[j]] = Math.Sum(subset);
                    }

                    if ((sm & StatisticalMethods.Median) == StatisticalMethods.Median)
                    {
                        tbl.Rows[i][m_medianColumnIndex[j]] = Math.MedianOfSeries(subset);
                    }
                }
            }

            return(tbl);
        }
Ejemplo n.º 46
0
        private void AddWeekData(WeeklySummary result, DateRangeType weekRangeType)
        {
            var rangeData = new DateRange();

            rangeData.RangeType = weekRangeType;
            rangeData.CalculateDatesFromType(DateHelper.ConvertUtcToStoreTime(_hccApp));

            var totalCount = 0;
            var storeId    = _hccApp.CurrentStore.Id;

            var data = _hccApp.OrderServices.Transactions
                       .FindForReportByDateRange(rangeData.StartDate.ToUniversalTime(), rangeData.EndDate.ToUniversalTime(),
                                                 storeId, int.MaxValue, 1, ref totalCount);

            decimal m = 0;
            decimal t = 0;
            decimal w = 0;
            decimal r = 0;
            decimal f = 0;
            decimal s = 0;
            decimal y = 0;

            foreach (var ot in data)
            {
                var timeStamp = DateHelper.ConvertUtcToStoreTime(_hccApp, ot.TimeStampUtc);

                switch (timeStamp.DayOfWeek)
                {
                case DayOfWeek.Monday:
                    m += ot.AmountAppliedToOrder;
                    break;

                case DayOfWeek.Tuesday:
                    t += ot.AmountAppliedToOrder;
                    break;

                case DayOfWeek.Wednesday:
                    w += ot.AmountAppliedToOrder;
                    break;

                case DayOfWeek.Thursday:
                    r += ot.AmountAppliedToOrder;
                    break;

                case DayOfWeek.Friday:
                    f += ot.AmountAppliedToOrder;
                    break;

                case DayOfWeek.Saturday:
                    s += ot.AmountAppliedToOrder;
                    break;

                case DayOfWeek.Sunday:
                    y += ot.AmountAppliedToOrder;
                    break;
                }
            }

            result.Monday    = m;
            result.Tuesday   = t;
            result.Wednesday = w;
            result.Thursday  = r;
            result.Friday    = f;
            result.Saturday  = s;
            result.Sunday    = y;
        }
Ejemplo n.º 47
0
        /// <summary>Process all transactions (payments) from Service Reef.</summary>
        /// <param name="message">The message that is returned depending on the result.</param>
        /// <param name="state">The state of the process.</param>
        /// <returns><see cref="WorkerResultStatus"/></returns>
        public void Execute(IJobExecutionContext context)
        {
            RockContext                 dbContext                   = new RockContext();
            FinancialBatchService       financialBatchService       = new FinancialBatchService(dbContext);
            PersonService               personService               = new PersonService(dbContext);
            PersonAliasService          personAliasService          = new PersonAliasService(dbContext);
            FinancialAccountService     financialAccountService     = new FinancialAccountService(dbContext);
            FinancialAccountService     accountService              = new FinancialAccountService(dbContext);
            FinancialTransactionService financialTransactionService = new FinancialTransactionService(dbContext);
            FinancialGatewayService     financialGatewayService     = new FinancialGatewayService(dbContext);
            DefinedValueService         definedValueService         = new DefinedValueService(dbContext);
            DefinedTypeService          definedTypeService          = new DefinedTypeService(dbContext);
            TransactionService          transactionService          = new TransactionService(new PayPalReporting.Data.PayPalReportingContext());

            // Get the datamap for loading attributes
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            String warnings = string.Empty;

            FinancialBatch batch       = null;
            Double         totalAmount = 0;
            var            total       = 1;
            var            processed   = 0;

            try
            {
                DateRange dateRange = Rock.Web.UI.Controls.SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(dataMap.GetString("DateRange") ?? "-1||");

                String            SRApiKey          = Encryption.DecryptString(dataMap.GetString("ServiceReefAPIKey"));
                String            SRApiSecret       = Encryption.DecryptString(dataMap.GetString("ServiceReefAPISecret"));
                String            SRApiUrl          = dataMap.GetString("ServiceReefAPIURL");
                DefinedValueCache transactionSource = DefinedValueCache.Read(dataMap.GetString("TransactionSource").AsGuid(), dbContext);
                DefinedValueCache connectionStatus  = DefinedValueCache.Read(dataMap.GetString("ConnectionStatus").AsGuid(), dbContext);
                DefinedValueCache contribution      = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION);

                // Setup some lookups
                DefinedTypeCache        creditCards = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE.AsGuid(), dbContext);
                DefinedTypeCache        tenderType  = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE.AsGuid(), dbContext);
                FinancialAccount        specialFund = accountService.Get(dataMap.GetString("Account").AsGuid());
                FinancialGateway        gateway     = financialGatewayService.Get(dataMap.GetString("FinancialGateway").AsGuid());
                List <FinancialAccount> trips       = financialAccountService.Queryable().Where(fa => fa.ParentAccountId == specialFund.Id).OrderBy(fa => fa.Order).ToList();

                // Get the trips
                DefinedValueCache serviceReefAccountType = DefinedValueCache.Read(dataMap.Get("ServiceReefAccountType").ToString().AsGuid());

                // Setup the ServiceReef API Client
                var client = new RestClient(SRApiUrl);
                client.Authenticator = new HMACAuthenticator(SRApiKey, SRApiSecret);

                // Get all payments from ServiceReef
                var request = new RestRequest("v1/payments", Method.GET);
                request.AddParameter("pageSize", 100);
                if (dateRange.Start.HasValue)
                {
                    request.AddParameter("startDate", dateRange.Start.Value.ToString("o"));
                }
                if (dateRange.End.HasValue)
                {
                    request.AddParameter("endDate", dateRange.End.Value.ToString("o"));
                }
                request.AddParameter("page", 1);

                while (total > processed)
                {
                    var response = client.Execute <Contracts.Payments>(request);
                    if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        throw new Exception("ServiceReef API Response: " + response.StatusDescription + " Content Length: " + response.ContentLength);
                    }
                    if (response.Data != null && response.Data.PageInfo != null)
                    {
                        total = response.Data.PageInfo.TotalRecords;
                        foreach (Contracts.Payments.Result result in response.Data.Results)
                        {
                            // Process the transaction
                            if (result.PaymentProcessorTransactionId != null)
                            {
                                if (result.FirstName == null || result.LastName == null)
                                {
                                    warnings += "Missing Firstname/Lastname for ServiceReef transaction Id: " + result.TransactionId + Environment.NewLine;
                                    processed++;
                                    continue;
                                }
                                FinancialAccount trip = null;
                                // Make sure we have a sub-account to go with this transaction
                                if (result.EventId > 0)
                                {
                                    trip = trips.Where(t => t.GlCode == result.EventCode && t.Url == result.EventUrl).FirstOrDefault();
                                }
                                if (trip == null)
                                {
                                    if (result.EventCode == null)
                                    {
                                        warnings += "Event Code is missing on the Service Reef Trip for ServiceReef transaction Id: " + result.TransactionId + Environment.NewLine;
                                        processed++;
                                        continue;
                                    }

                                    // Create the trip subaccount
                                    FinancialAccount tripFA = new FinancialAccount();
                                    tripFA.Name = result.EventName;
                                    // Name is limited to 50
                                    if (tripFA.Name.Length > 50)
                                    {
                                        tripFA.Name = tripFA.Name.Substring(0, 50);
                                    }
                                    tripFA.Description = "Service Reef Event.  Name: " + result.EventName + " ID: " + result.EventId;
                                    tripFA.GlCode      = result.EventCode;
                                    tripFA.Url         = result.EventUrl;
                                    tripFA.PublicName  = result.EventName;
                                    // Public Name is limited to 50
                                    if (tripFA.PublicName.Length > 50)
                                    {
                                        tripFA.PublicName = tripFA.PublicName.Substring(0, 50);
                                    }
                                    tripFA.IsTaxDeductible    = true;
                                    tripFA.IsPublic           = false;
                                    tripFA.ParentAccountId    = specialFund.Id;
                                    tripFA.Order              = specialFund.Order + 1;
                                    tripFA.AccountTypeValueId = serviceReefAccountType.Id;
                                    // Figure out what order it should be;
                                    foreach (FinancialAccount tmpTrip in trips)
                                    {
                                        if (tmpTrip.Name.CompareTo(tripFA.Name) < 0)
                                        {
                                            tripFA.Order++;
                                        }
                                    }

                                    financialAccountService.Add(tripFA);

                                    // Now save the trip
                                    dbContext.SaveChanges();
                                    // Increment all the rest of the Orders
                                    financialAccountService.Queryable().Where(fa => fa.Order >= tripFA.Order && fa.Id != tripFA.Id).ToList().ForEach(c => c.Order++);
                                    dbContext.SaveChanges();
                                    trips = financialAccountService.Queryable().Where(fa => fa.ParentAccountId == specialFund.Id).OrderBy(fa => fa.Order).ToList();
                                    trip  = tripFA;
                                }

                                FinancialTransaction tran = financialTransactionService.Queryable().Where(tx => tx.TransactionCode == result.PaymentProcessorTransactionId).FirstOrDefault();

                                // We haven't processed this before so get busy!
                                if (tran == null)
                                {
                                    tran = new FinancialTransaction();
                                    tran.FinancialPaymentDetail = new FinancialPaymentDetail();
                                    if (result.Type == "CreditCard")
                                    {
                                        tran.FinancialPaymentDetail.CurrencyTypeValueId = tenderType.DefinedValues.Where(t => t.Value == "Credit Card").FirstOrDefault().Id;
                                    }
                                    else
                                    {
                                        tran.TransactionTypeValueId = tenderType.DefinedValues.Where(t => t.Value == "Credit Card").FirstOrDefault().Id;
                                    }

                                    Person person = null;
                                    // Find the person this transaction belongs to
                                    // 1. First start by determining whether this was a person
                                    //    paying their application fee or contributing to themselves
                                    //    because then we can just use their member info
                                    if (result.UserId > 0 &&
                                        result.DonatedToUserId == result.UserId &&
                                        result.DonatedToFirstName == result.FirstName &&
                                        result.DonatedToLastName == result.LastName)
                                    {
                                        var memberRequest = new RestRequest("v1/members/{userId}", Method.GET);
                                        memberRequest.AddUrlSegment("userId", result.UserId.ToString());
                                        var memberResult = client.Execute <Contracts.Member>(memberRequest);
                                        if (memberResult.Data != null && memberResult.Data.ArenaId > 0)
                                        {
                                            try
                                            {
                                                Person personMatch = personAliasService.Queryable().Where(pa => pa.AliasPersonId == memberResult.Data.ArenaId).Select(pa => pa.Person).FirstOrDefault();
                                                if (personMatch == null)
                                                {
                                                    throw new Exception("Person not found: " + memberResult.Data.ArenaId);
                                                }
                                                person = personMatch;
                                            } catch (Exception e)
                                            {
                                                warnings += "Loading the person failed transaction id " + result.TransactionId + " for " + result.FirstName + " " + result.LastName + " with the following error: " + e.Message + Environment.NewLine;
                                                processed++;
                                                continue;
                                            }
                                        }
                                    }
                                    // 2. If we didn't get a person match via their Alias Id
                                    //    then just use the standard person match logic
                                    if (person == null)
                                    {
                                        String street1    = null;
                                        String postalCode = null;
                                        if (result.Address != null)
                                        {
                                            street1    = result.Address.Address1;
                                            postalCode = result.Address.Zip;
                                        }
                                        List <Person> matches = personService.GetByMatch(result.FirstName.Trim(), result.LastName.Trim(), null, result.Email, null, street1, postalCode).ToList();

                                        if (matches.Count > 1)
                                        {
                                            // Find the oldest member record in the list
                                            person = matches.Where(p => p.ConnectionStatusValue.Value == "Member").OrderBy(p => p.Id).FirstOrDefault();
                                            if (person == null)
                                            {
                                                // Find the oldest attendee record in the list
                                                person = matches.Where(p => p.ConnectionStatusValue.Value == "Attendee").OrderBy(p => p.Id).FirstOrDefault();
                                                if (person == null)
                                                {
                                                    person = matches.OrderBy(p => p.Id).First();
                                                }
                                            }
                                        }
                                        else if (matches.Count == 1)
                                        {
                                            person = matches.First();
                                        }
                                        else
                                        {
                                            // Create the person
                                            person                         = new Person();
                                            person.FirstName               = result.FirstName.Trim();
                                            person.LastName                = result.LastName.Trim();
                                            person.Email                   = result.Email.Trim();
                                            person.RecordTypeValueId       = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                                            person.ConnectionStatusValueId = connectionStatus.Id;
                                            person.RecordStatusValueId     = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;
                                            Group         family   = PersonService.SaveNewPerson(person, dbContext);
                                            GroupLocation location = new GroupLocation();
                                            location.GroupLocationTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;
                                            location.Location = new Location()
                                            {
                                                Street1    = result.Address.Address1,
                                                Street2    = result.Address.Address2,
                                                City       = result.Address.City,
                                                State      = result.Address.State,
                                                PostalCode = result.Address.Zip,
                                            };
                                            family.CampusId = CampusCache.All().FirstOrDefault().Id;
                                            family.GroupLocations.Add(location);
                                            dbContext.SaveChanges();
                                        }
                                    }

                                    // Get details about the transaction from our PayPal report table
                                    Transaction tx = transactionService.Get(result.PaymentProcessorTransactionId);
                                    if (tx != null)
                                    {
                                        if (tx.TenderType.Contains("ACH"))
                                        {
                                            result.Type   = "ACH";
                                            result.Method = null;
                                        }
                                        else
                                        {
                                            result.Type   = "Credit Card";
                                            result.Method = tx.TenderType;
                                        }
                                    }
                                    else
                                    {
                                        // Defaults
                                        result.Type   = "Credit Card";
                                        result.Method = "Visa";

                                        warnings += "Unable to find transaction in _org_secc_PaypalReporting_Transaction table: " + result.TransactionId + Environment.NewLine;
                                    }

                                    // If we don't have a batch, create one
                                    if (batch == null)
                                    {
                                        batch = new FinancialBatch();
                                        batch.BatchStartDateTime = result.Date;
                                        batch.BatchEndDateTime   = DateTime.Now;
                                        batch.Name   = "Service Reef Payments";
                                        batch.Status = BatchStatus.Open;
                                        financialBatchService.Add(batch);
                                        dbContext.SaveChanges();
                                    }

                                    // Complete the FinancialTransaction
                                    tran.AuthorizedPersonAliasId = person.PrimaryAliasId;
                                    tran.BatchId             = batch.Id;
                                    tran.Summary             = "F" + specialFund.Id + ":$" + result.Amount.ToString();
                                    tran.TransactionDateTime = result.Date;
                                    tran.FinancialGatewayId  = gateway.Id;

                                    FinancialTransactionDetail financialTransactionDetail = new FinancialTransactionDetail();
                                    financialTransactionDetail.AccountId = trip.Id;
                                    financialTransactionDetail.Amount    = result.Amount.ToString().AsDecimal();
                                    tran.TransactionDetails.Add(financialTransactionDetail);
                                    tran.TransactionTypeValueId = contribution.Id;

                                    tran.FinancialPaymentDetail = new FinancialPaymentDetail();
                                    tran.FinancialPaymentDetail.CurrencyTypeValueId = tenderType.DefinedValues.Where(type => type.Value.ToLower() == result.Type.ToLower()).FirstOrDefault().Id;
                                    if (result.Method != null)
                                    {
                                        tran.FinancialPaymentDetail.CreditCardTypeValueId = creditCards.DefinedValues.Where(card => card.Value.ToLower() == result.Method.ToLower()).FirstOrDefault().Id;
                                    }
                                    tran.TransactionCode   = result.PaymentProcessorTransactionId;
                                    tran.SourceTypeValueId = transactionSource.Id;

                                    financialTransactionService.Add(tran);
                                    dbContext.SaveChanges();

                                    totalAmount += result.Amount;
                                }
                            }
                            processed++;
                        }
                    }
                    else
                    {
                        total = 0;
                    }
                    // Update the page number for the next request
                    var pageParam = request.Parameters.Where(p => p.Name == "page").FirstOrDefault();
                    pageParam.Value = (int)pageParam.Value + 1;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("ServiceReef Job Failed", ex);
            } finally
            {
                if (batch != null && totalAmount > 0)
                {
                    batch.ControlAmount = (Decimal)totalAmount;
                }
                dbContext.SaveChanges();
            }
            if (warnings.Length > 0)
            {
                throw new Exception(warnings);
            }
            context.Result = "Successfully imported " + processed + " transactions.";
        }
        public string GetCalendarEventsAsJson(int id, int start = 0, int end = 0)
        {
            DateTime startDate = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);

            startDate = startDate.AddSeconds(start);
            DateTime endDate = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);

            endDate = endDate.AddSeconds(end);

            List <EventsOverviewModel> events    = new List <EventsOverviewModel>();
            List <Schedule>            schedules = new List <Schedule>();
            DateRange range = new DateRange();

            range.StartDateTime = startDate;
            range.EndDateTime   = endDate;

            //Handle normal events
            var normal_events = this._db.Query <CalendarEntry>("SELECT * FROM ec_events WHERE calendarId = @0", id).ToList();

            foreach (var ne in normal_events)
            {
                events.Add(
                    new EventsOverviewModel()
                {
                    type        = EventType.Normal,
                    title       = ne.title,
                    allDay      = ne.allDay,
                    description = ne.description,
                    end         = ne.end,
                    start       = ne.start,
                    id          = ne.Id
                });
            }

            //Handle recurring events
            var recurring_events = this._db.Query <RecurringEvent>("SELECT * FROM ec_recevents WHERE calendarId = @0 ORDER BY id DESC", id).ToList();

            foreach (var e in recurring_events)
            {
                var schedule = new Schedule(
                    new Event()
                {
                    Title                  = e.title,
                    ID                     = e.Id,
                    DaysOfWeekOptions      = (DayOfWeekEnum)e.day,
                    FrequencyTypeOptions   = (FrequencyTypeEnum)e.frequency,
                    MonthlyIntervalOptions = (MonthlyIntervalEnum)e.monthly_interval
                });
                foreach (var tmp in schedule.Occurrences(range))
                {
                    events.Add(new EventsOverviewModel()
                    {
                        title       = e.title,
                        id          = e.Id,
                        allDay      = e.allDay,
                        description = e.description,
                        start       = tmp,
                        type        = EventType.Recurring
                    });
                }
            }

            string json = JsonConvert.SerializeObject(events);

            return(json);
        }
Ejemplo n.º 49
0
 private static void _updateTrackedOptionDates(DateRange trackedOptDates, DateRange newDateRange, ResotelContext ctx)
 {
     ctx.Entry(trackedOptDates).CurrentValues.SetValues(newDateRange);
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            accountingMasterPage = (AccountingMasterPage)Page.Master;
            accountingMasterPage.InitializeMasterPageComponents();

            if (!String.IsNullOrEmpty(Request["action"]))
            {
                action = Request["action"];
            }

            if (!String.IsNullOrEmpty(Request["currPage"]))
            {
                currentPage = int.Parse(Request["currPage"]);
            }


            if (!Page.IsPostBack) // Ajusta os valores iniciais do filtro
            {
                SqlConnection sqlConnection = accountingMasterPage.dataAccess.GetConnection();

                ListItem[] printerList = DropDownScaffold.Retrieve("pr_retrievePrinter", sqlConnection, typeof(Printer));
                printerList[0].Text = "Todas as copiadoras";
                cmbPrinter.Items.AddRange(printerList);

                chkLastMonth.Checked = true;
            }

            // Configura os valores para a faixa de datas (considerando o periodo do último mês)
            DateRange dateRange = new DateRange(false);

            hiddenStartDate.Value = dateRange.GetFirstDay().ToString("yyyy-MM-dd");
            hiddenStartHour.Value = "08:00";
            hiddenEndDate.Value   = dateRange.GetLastDay().ToString("yyyy-MM-dd");
            hiddenEndHour.Value   = "18:00";

            if (chkLastMonth.Checked)
            {
                // caso o checkbox esteja marcado configura o último mês, senão recupera o viewstate
                txtStartDate.Value = hiddenStartDate.Value;
                txtStartHour.Value = hiddenStartHour.Value;
                txtEndDate.Value   = hiddenEndDate.Value;
                txtEndHour.Value   = hiddenEndHour.Value;
            }
            txtStartDate.Disabled     = chkLastMonth.Checked;
            btnOpenCalendar1.Disabled = chkLastMonth.Checked;
            txtStartHour.Disabled     = chkLastMonth.Checked;
            txtEndDate.Disabled       = chkLastMonth.Checked;
            btnOpenCalendar2.Disabled = chkLastMonth.Checked;
            txtEndHour.Disabled       = chkLastMonth.Checked;

            EmbedClientScript.AddButtonClickHandler(this.Page, "GenerateReport");
            lblErrorMessages.Text = "";

            // caso "action" não exista encerra por aqui
            if (action == "")
            {
                return;
            }

            int?     printerId = null;
            DateTime startDate = DateTime.Now;
            DateTime endDate   = DateTime.Now;

            try
            {
                printerId = DropDownScaffold.GetSelectedItemId(cmbPrinter);
                startDate = DateTime.Parse(txtStartDate.Value + " " + txtStartHour.Value);
                endDate   = DateTime.Parse(txtEndDate.Value + " " + txtEndHour.Value);
            }
            catch (System.FormatException)
            {
                lblErrorMessages.Text = "As datas informadas não estão em um formato válido.";
                return;
            }

            if (printerId != null)
            {
                String queryString = "?printerId=" + printerId.ToString() + "&" +
                                     "startDate=" + startDate.ToString() + "&" +
                                     "endDate=" + endDate.ToString() + "&" +
                                     "detailType=CopyingCosts";

                Response.Redirect("DeviceCostDetails.aspx" + queryString);
                return;
            }

            GenerateReport(startDate, endDate);
        }
Ejemplo n.º 51
0
        public void GetEnumeratorTest()
        {
            // Case 1
            var range1     = new DateRange(new DateTime(2017, 2, 1), new DateTime(2017, 2, 5));
            var expecteds1 = new DateTime[]
            {
                new DateTime(2017, 2, 1),
                new DateTime(2017, 2, 2),
                new DateTime(2017, 2, 3),
                new DateTime(2017, 2, 4),
                new DateTime(2017, 2, 5)
            };
            var i = 0;

            foreach (var dt in range1)
            {
                Assert.AreEqual(expecteds1[i++], dt);
            }
            Assert.AreEqual(5, i);

            // Case 2
            var range2     = new DateRange(new DateTime(2017, 2, 5), new DateTime(2017, 2, 28), 5);
            var expecteds2 = new DateTime[]
            {
                new DateTime(2017, 2, 5),
                new DateTime(2017, 2, 10),
                new DateTime(2017, 2, 15),
                new DateTime(2017, 2, 20),
                new DateTime(2017, 2, 25)
            };

            i = 0;
            foreach (var dt in range2)
            {
                Assert.AreEqual(expecteds2[i++], dt);
            }
            Assert.AreEqual(5, i);

            // Case 3
            var range3     = new DateRange(new DateTime(2017, 1, 1), new DateTime(2021, 1, 1), 1, Types.DatePart.Year);
            var expecteds3 = new DateTime[]
            {
                new DateTime(2017, 1, 1),
                new DateTime(2018, 1, 1),
                new DateTime(2019, 1, 1),
                new DateTime(2020, 1, 1),
                new DateTime(2021, 1, 1)
            };

            i = 0;
            foreach (var dt in range3)
            {
                Assert.AreEqual(expecteds3[i++], dt);
            }
            Assert.AreEqual(5, i);

            // Case 4
            var range4     = new DateRange(new DateTime(2017, 1, 31), new DateTime(2017, 5, 31), 1, Types.DatePart.Month);
            var expecteds4 = new DateTime[]
            {
                new DateTime(2017, 1, 31),
                new DateTime(2017, 2, 28),
                new DateTime(2017, 3, 31),
                new DateTime(2017, 4, 30),
                new DateTime(2017, 5, 31)
            };

            i = 0;
            foreach (var dt in range4)
            {
                Assert.AreEqual(expecteds4[i++], dt);
            }
            Assert.AreEqual(5, i);

            // Case 5
            var range5     = new DateRange(new DateTime(2017, 2, 1), new DateTime(2017, 2, 1, 4, 0, 0, 0), 1, Types.DatePart.Hour);
            var expecteds5 = new DateTime[]
            {
                new DateTime(2017, 2, 1, 0, 0, 0, 0),
                new DateTime(2017, 2, 1, 1, 0, 0, 0),
                new DateTime(2017, 2, 1, 2, 0, 0, 0),
                new DateTime(2017, 2, 1, 3, 0, 0, 0),
                new DateTime(2017, 2, 1, 4, 0, 0, 0)
            };

            i = 0;
            foreach (var dt in range5)
            {
                Assert.AreEqual(expecteds5[i++], dt);
            }
            Assert.AreEqual(5, i);

            // Case 6
            var range6     = new DateRange(new DateTime(2017, 2, 1), new DateTime(2017, 2, 1, 0, 40, 0, 0), 10, Types.DatePart.Minute);
            var expecteds6 = new DateTime[]
            {
                new DateTime(2017, 2, 1, 0, 0, 0, 0),
                new DateTime(2017, 2, 1, 0, 10, 0, 0),
                new DateTime(2017, 2, 1, 0, 20, 0, 0),
                new DateTime(2017, 2, 1, 0, 30, 0, 0),
                new DateTime(2017, 2, 1, 0, 40, 0, 0)
            };

            i = 0;
            foreach (var dt in range6)
            {
                Assert.AreEqual(expecteds6[i++], dt);
            }
            Assert.AreEqual(5, i);

            // Case 7
            var range7     = new DateRange(new DateTime(2017, 2, 1), new DateTime(2017, 2, 1, 0, 2, 00, 0), 30, Types.DatePart.Second);
            var expecteds7 = new DateTime[]
            {
                new DateTime(2017, 2, 1, 0, 0, 0, 0),
                new DateTime(2017, 2, 1, 0, 0, 30, 0),
                new DateTime(2017, 2, 1, 0, 1, 0, 0),
                new DateTime(2017, 2, 1, 0, 1, 30, 0),
                new DateTime(2017, 2, 1, 0, 2, 0, 0)
            };

            i = 0;
            foreach (var dt in range7)
            {
                Assert.AreEqual(expecteds7[i++], dt);
            }
            Assert.AreEqual(5, i);

            // Case 8
            var range8     = new DateRange(new DateTime(2017, 2, 1), new DateTime(2017, 2, 1, 0, 0, 0, 400), 100, Types.DatePart.Milisecond);
            var expecteds8 = new DateTime[]
            {
                new DateTime(2017, 2, 1, 0, 0, 0, 0),
                new DateTime(2017, 2, 1, 0, 0, 0, 100),
                new DateTime(2017, 2, 1, 0, 0, 0, 200),
                new DateTime(2017, 2, 1, 0, 0, 0, 300),
                new DateTime(2017, 2, 1, 0, 0, 0, 400)
            };

            i = 0;
            foreach (var dt in range8)
            {
                Assert.AreEqual(expecteds8[i++], dt);
            }
            Assert.AreEqual(5, i);

            // Case 9
            var range9 = new DateRange(DateTime.Today, DateTime.Today.AddDays(-1));

            i = 0;
            foreach (var dt in range9)
            {
                i++;
            }
            Assert.AreEqual(0, i);
        }
Ejemplo n.º 52
0
 public MeetingScheduled(Guid meetingId, DateRange occurs)
 {
     MeetingId = meetingId;
     Occurs    = occurs;
 }
Ejemplo n.º 53
0
        // check if a given user has used his daily posting quota
        protected bool UserDailyPostingQuotaForNegativeScoreUsed(VoatRuleContext context)
        {
            int limit = VoatSettings.Instance.DailyPostingQuotaForNegativeScore;

            using (var repo = new Repository())
            {
                // check how many submission user made today
                var userSubmissionsToTargetSub = repo.UserContributionCount(context.UserName, Domain.Models.ContentType.Submission, null, DateRange.StartFrom(TimeSpan.FromHours(24)));

                if (limit <= userSubmissionsToTargetSub)
                {
                    return(true);
                }
                return(false);
            }
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Displays the text value.
        /// </summary>
        /// <param name="dateRange">The date range.</param>
        /// <param name="primaryMetricSource">The primary metric source.</param>
        /// <param name="comparisonMetricSource">The comparison metric source.</param>
        private void DisplayTextValue(DateRange dateRange, List <int> primaryMetricSource, List <int> comparisonMetricSource)
        {
            // this may be a little complicated to compare date ranges while accepting two metric keys/sources
            decimal currentMetricValues    = FormatValues(primaryMetricSource, comparisonMetricSource, dateRange);
            decimal comparisonMetricValues = 0;

            // if doing a date comparison
            //DateTime dateRangeStart = dateRange.Start ?? DateTime.Now;
            //DateTime dateRangeEnd = dateRange.End ?? DateTime.Now;
            //TimeSpan ts = dateRangeEnd - dateRangeStart;

            //if ( ts.Days > 0 )
            //{
            //    var differenceInDays = ts.Days + 1;

            //    var comparisonDateRange = new DateRange
            //    {
            //        Start = dateRange.Start.Value.AddDays( -differenceInDays ),
            //        End = dateRange.End.Value.AddDays( -differenceInDays )
            //    };

            //    comparisonMetricValues = FormatValues( primaryMetricSource, percentageMetricSource, comparisonDateRange );
            //}

            if (currentMetricValues > 0)
            {
                currentMetricValue.Value = string.Format("{0:n0}", currentMetricValues);

                if (comparisonMetricValues > 0)
                {
                    if (currentMetricValues > comparisonMetricValues)
                    {
                        metricClass.Value = "fa-caret-up brand-success";
                    }
                    else if (currentMetricValues < comparisonMetricValues)
                    {
                        metricClass.Value = "fa-caret-down brand-danger";
                    }
                }

                if ((comparisonMetricSource.Any() || !string.IsNullOrEmpty(ComparisonMetricKey)) && GetAttributeValue("DisplayComparisonAs").Equals("Percentage"))
                {
                    metricComparisonDisplay.Value = "%";
                }
            }
            else
            {
                currentMetricValue.Value = "—";
            }

            //if ( MetricCompareLastYear == "Yes" )
            //{
            //    var comparePreviousYearMetricValue = new DateRange
            //    {
            //        Start = dateRange.Start.Value.AddYears( -1 ),
            //        End = dateRange.End.Value.AddYears( -1 )
            //    };

            //    decimal? previousYearRangeMetricValue = MetricValueFunction( primaryMetricSource, comparePreviousYearMetricValue, campusContext, groupContext, scheduleContext );

            //    previousMetricValue.Value = string.Format( "{0:n0}", previousYearRangeMetricValue );
            //}

            // This Week Last Year
            //else if ( metricCustomDates == "This Week Last Year" )
            //{
            //currentMetricValue.Value = string.Format( "{0:n0}", newMetric.MetricValues
            //.Where( a => calendar.GetWeekOfYear( a.MetricValueDateTime.Value.Date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday ) == calendar.GetWeekOfYear( DateTime.Now.AddYears( -1 ).Date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday ) && a.MetricValueDateTime.Value.Year.ToString() == DateTime.Now.AddYears( -1 ).ToString() )
            //.Select( a => a.YValue )
            //.Sum()
            //);
            //}
        }
Ejemplo n.º 55
0
        // check if a given user has used his global daily posting quota
        protected bool UserDailyGlobalPostingQuotaUsed(VoatRuleContext context)
        {
            //DRY: Repeat Block #1
            // only execute this check if user account is less than a month old and user SCP is less than 50 and user is not posting to a sub they own/moderate
            DateTime userRegistrationDateTime = context.UserData.Information.RegistrationDate;
            int      memberInDays             = (Repository.CurrentDate - userRegistrationDateTime).Days;

            if (memberInDays > 30)
            {
                return(false);
            }
            else
            {
                int userScp = context.UserData.Information.SubmissionPoints.Sum;
                if (userScp >= 50)
                {
                    return(false);
                }
            }

            // read daily global posting quota configuration parameter from web.config
            int limit = VoatSettings.Instance.DailyGlobalPostingQuota;

            using (var repo = new Repository())
            {
                // check how many submission user made today
                var userSubmissionsToTargetSub = repo.UserContributionCount(context.UserName, Domain.Models.ContentType.Submission, null, DateRange.StartFrom(TimeSpan.FromHours(24)));

                if (limit <= userSubmissionsToTargetSub)
                {
                    return(true);
                }
                return(false);
            }
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Formats the values.
        /// </summary>
        /// <param name="primaryMetricSource">The primary metric source.</param>
        /// <param name="percentageMetricSource">The percentage metric source.</param>
        /// <param name="dateRange">The date range.</param>
        /// <returns></returns>
        protected decimal FormatValues(List <int> primaryMetricSource, List <int> comparisonMetricSource, DateRange dateRange)
        {
            var primaryMetricValues = GetMetricValues(primaryMetricSource, dateRange, PrimaryMetricKey);
            var primaryValueSum     = primaryMetricValues.Select(a => a.YValue).Sum() ?? 0.0M;

            // if comparing values, make sure we have a valid percentage source
            if (primaryValueSum > 0 && (comparisonMetricSource.Any() || !string.IsNullOrEmpty(ComparisonMetricKey)))
            {
                var comparisonMetricValues = GetMetricValues(comparisonMetricSource, dateRange, ComparisonMetricKey);
                var comparisonValueSum     = comparisonMetricValues.Select(a => a.YValue).Sum() ?? 0.0M;

                if (comparisonValueSum > 0)
                {
                    decimal comparison = primaryValueSum / comparisonValueSum;

                    if (GetAttributeValue("DisplayComparisonAs").Equals("Integer"))
                    {
                        return(comparison);
                    }
                    else
                    {
                        return(comparison * 100);
                    }
                }
                else
                {
                    return(0.0M);
                }
            }

            return(primaryValueSum);
        }
Ejemplo n.º 57
0
        // check if a given user has used his daily comment posting quota
        protected bool UserDailyCommentPostingQuotaUsed(VoatRuleContext context)
        {
            // read daily posting quota per sub configuration parameter from web.config
            int limit = VoatSettings.Instance.DailyCommentPostingQuota;

            using (var repo = new Repository())
            {
                // check how many submission user made today
                var userCommentSubmissionsInPast24Hours = repo.UserContributionCount(context.UserName, Domain.Models.ContentType.Comment, null, DateRange.StartFrom(TimeSpan.FromHours(24)));

                if (limit <= userCommentSubmissionsInPast24Hours)
                {
                    return(true);
                }
                return(false);
            }
        }
Ejemplo n.º 58
0
        // <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Page.IsPostBack)
            {
                // check the page context
                bool pageScope = GetAttributeValue("ContextScope") == "Page";

                // If the blocks respect page context let's set those vars
                if (pageScope)
                {
                    // Get Current Campus Context
                    CampusContext = RockPage.GetCurrentContext(EntityTypeCache.Read(typeof(Campus)));

                    // Get Current Schedule Context
                    ScheduleContext = RockPage.GetCurrentContext(EntityTypeCache.Read(typeof(Schedule)));

                    // Get Current Group Context
                    GroupContext = RockPage.GetCurrentContext(EntityTypeCache.Read(typeof(Group)));

                    // Get Current GroupType Context
                    GroupTypeContext = RockPage.GetCurrentContext(EntityTypeCache.Read(typeof(GroupType)));
                }

                // Output variables direct to the ascx
                metricBlockNumber.Value = BlockId.ToString();
                metricBlockId.Value     = BlockName.Replace(" ", "").ToString();
                metricTitle.Value       = BlockName;
                metricDisplay.Value     = GetAttributeValue("MetricDisplayType");
                metricWidth.Value       = GetAttributeValue("NumberofColumns");

                PrimaryMetricKey    = GetAttributeValue("PrimaryMetricKey");
                ComparisonMetricKey = GetAttributeValue("ComparisonMetricKey");

                var churchMetricPeriod = GetAttributeValue("MetricPeriod");
                var metricComparison   = GetAttributeValue("MetricComparison");
                var metricDisplayType  = GetAttributeValue("MetricDisplayType");

                var rockContext   = new RockContext();
                var metricService = new MetricService(rockContext);

                var primarySourceGuids = GetAttributeValue("PrimaryMetricSource")
                                         .SplitDelimitedValues()
                                         .AsGuidList();

                var comparisonSourceGuids = GetAttributeValue("ComparisonMetricSource")
                                            .SplitDelimitedValues()
                                            .AsGuidList();

                // lookup the metric sources
                List <int> primaryMetricSource = metricService.GetByGuids(primarySourceGuids)
                                                 .Select(a => a.Id).ToList();

                List <int> comparisonMetricSource = metricService.GetByGuids(comparisonSourceGuids)
                                                    .Select(a => a.Id).ToList();

                DateRange dateRange = new DateRange(DateTime.Now.AddMonths(-6), DateTime.Now);

                // Show data if metric source is selected
                if (primaryMetricSource.Any() || !string.IsNullOrEmpty(PrimaryMetricKey))
                {
                    if (metricDisplayType.Equals("Text"))
                    {
                        DisplayTextValue(dateRange, primaryMetricSource, comparisonMetricSource);
                    }
                    else if (metricDisplayType.Equals("Line"))
                    {
                        DisplayLineValue(dateRange, primaryMetricSource);
                    }
                    else if (metricDisplayType.Equals("Donut"))
                    {
                        DisplayDonutValue(dateRange, primaryMetricSource);
                    }
                }
                else
                {
                    // nothing selected, display an error message
                    churchMetricWarning.Visible = true;
                }
            }

            // unused variables
            // var metricCustomDates = GetAttributeValue( "CustomDates" );
            // MetricCompareLastYear = GetAttributeValue( "CompareAgainstLastYear" ).ToString();
            // var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( this.GetAttributeValue( "SlidingDateRange" ) ?? string.Empty );
        }
Ejemplo n.º 59
0
 public bool AreIntersect(SeasonRange range) => DateRange.AreIntersect(StartDate, EndDate, range.StartDate, range.EndDate);
Ejemplo n.º 60
0
        /// <summary>
        /// Displays the line value.
        /// </summary>
        /// <param name="dateRange">The date range.</param>
        /// <param name="primaryMetricSource">The primary metric source.</param>
        private void DisplayLineValue(DateRange dateRange, List <int> primaryMetricSource)
        {
            var metricLegend            = new List <string>();
            var metricCurrentYearValues = new List <string>();

            // if compare to previous year was set, also grab values from the previous year

            //var previousYearValues = GetMetricValues( primaryMetricSource, dateRange, PrimaryMetricKey );

            //if ( GetAttributeValue( "CompareAgainstLastYear" ) == "Yes" )
            //{
            //    metricPreviousYear = newMetric.MetricValues
            //        .Where( a => a.MetricValueDateTime >= dateRange.Start.Value.AddYears( -1 ) && a.MetricValueDateTime <= dateRange.End.Value.AddYears( -1 ) && a.EntityId.ToString() == CampusContext.Id.ToString() )
            //        .OrderBy( a => a.MetricValueDateTime )
            //        .Select( a => new MetricJson
            //        {
            //            date = a.MetricValueDateTime.Value.Date,
            //            week = calendar.GetWeekOfYear( a.MetricValueDateTime.Value.Date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday ),
            //            year = a.MetricValueDateTime.Value.Year,
            //            value = string.Format( "{0:0}", a.YValue )
            //        } )
            //        .ToList();
            //}

            var currentDateValues = GetMetricValues(primaryMetricSource, dateRange, PrimaryMetricKey);

            foreach (var currentValue in currentDateValues)
            {
                var metricDate         = currentValue.MetricValueDateTime.Value.Date;
                var currentMetricValue = string.Format("{0:0}", currentValue.YValue);

                var currentMetricLabel = new DateTime(metricDate.Year, metricDate.Month, metricDate.Day)
                                         .ToString("MMMM dd");

                // format these with ticks so the JS can parse it as an array
                // possibly pass this as a ToArray call and see what happens?
                currentMetricLabel = string.Format("'{0}'", currentMetricLabel);
                currentMetricValue = string.Format("'{0}'", currentMetricValue);

                metricLegend.Add(currentMetricLabel);
                metricCurrentYearValues.Add(currentMetricValue);

                // if compare to previous year
                // var metricPreviousYear = new List<MetricJson>();
                //if ( metricPreviousYear.Count > 0 )
                //{
                //    var count = 0;

                //    foreach ( var previousMetric in metricPreviousYear )
                //    {
                //        var previousMetricCount = count++;
                //        if ( currentMetric.week == previousMetric.week )
                //        {
                //            metricPreviousYearValues.Add( previousMetric.value );
                //            break;
                //        }
                //        else if ( count == metricPreviousYear.Count )
                //        {
                //            metricPreviousYearValues.Add( "0" );
                //            break;
                //        }
                //    }
                //}
                //else
                //{
                //    metricPreviousYearValues.Add( "0" );
                //}
            }

            metricLabels.Value = string.Format("'{0}'", metricLegend.ToString());

            metricDataPointsCurrent.Value = string.Format("'{0}'", metricCurrentYearValues.ToString());
        }