/// <summary> 
        /// Job that updates the JobPulse setting with the current date/time.
        /// This will allow us to notify an admin if the jobs stop running.
        /// 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void  Execute(IJobExecutionContext context)
        {
            // get the job map
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            int maxRecords = Int32.Parse( dataMap.GetString( "MaxRecordsPerRun" ) );
            int throttlePeriod = Int32.Parse( dataMap.GetString( "ThrottlePeriod" ) );
            int retryPeriod = Int32.Parse( dataMap.GetString( "RetryPeriod" ) );

            DateTime retryDate = DateTime.Now.Subtract(new TimeSpan(retryPeriod, 0, 0, 0));

            var rockContext = new Rock.Data.RockContext();
            LocationService locationService = new LocationService(rockContext);
            var addresses = locationService.Queryable()
                                .Where( l => (
                                    (l.IsGeoPointLocked == null || l.IsGeoPointLocked == false) // don't ever try locked address
                                    && (l.IsActive == true && l.Street1 != null && l.PostalCode != null) // or incomplete addresses
                                    && (
                                        (l.GeocodedDateTime == null && (l.GeocodeAttemptedDateTime == null || l.GeocodeAttemptedDateTime < retryDate)) // has not been attempted to be geocoded since retry date
                                        ||
                                        (l.StandardizedDateTime == null && (l.StandardizeAttemptedDateTime == null || l.StandardizeAttemptedDateTime < retryDate)) // has not been attempted to be standardize since retry date
                                    )
                                ))
                                .Take( maxRecords ).ToList();

            foreach ( var address in addresses )
            {
                locationService.Verify( address, false ); // currently not reverifying 
                rockContext.SaveChanges();
                System.Threading.Thread.Sleep( throttlePeriod );
            }

        }
Example #2
0
        /// <summary>
        /// Returns a list of matching people
        /// </summary>
        /// <param name="searchterm"></param>
        /// <returns></returns>
        public override IQueryable<string> Search( string searchterm )
        {
            var service = new LocationService();

            return service.Queryable().
                Where( a => a.Street1.Contains( searchterm ) ).
                OrderBy( a => a.Street1 ).
                Select( a => a.Street1 + " " + a.City ).Distinct();
        }
Example #3
0
        /// <summary> 
        /// Job that updates the JobPulse setting with the current date/time.
        /// This will allow us to notify an admin if the jobs stop running.
        /// 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            // get the job map
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            int maxRecords = Int32.Parse( dataMap.GetString( "MaxRecordsPerRun" ) );
            int throttlePeriod = Int32.Parse( dataMap.GetString( "ThrottlePeriod" ) );
            int retryPeriod = Int32.Parse( dataMap.GetString( "RetryPeriod" ) );

            DateTime retryDate = DateTime.Now.Subtract(new TimeSpan(retryPeriod, 0, 0, 0));

            var rockContext = new Rock.Data.RockContext();
            LocationService locationService = new LocationService(rockContext);
            var addresses = locationService.Queryable()
                .Where( l =>
                    (
                        ( l.IsGeoPointLocked == null || l.IsGeoPointLocked == false ) &&// don't ever try locked address
                        l.IsActive == true &&
                        l.Street1 != null &&
                        l.Street1 != "" &&
                        l.City != null &&
                        l.City != "" &&
                        (
                            ( l.GeocodedDateTime == null && ( l.GeocodeAttemptedDateTime == null || l.GeocodeAttemptedDateTime < retryDate ) ) || // has not been attempted to be geocoded since retry date
                            ( l.StandardizedDateTime == null && ( l.StandardizeAttemptedDateTime == null || l.StandardizeAttemptedDateTime < retryDate ) ) // has not been attempted to be standardize since retry date
                        )
                    ) )
                .Take( maxRecords ).ToList();

            int attempts = 0;
            int successes = 0;
            foreach ( var address in addresses )
            {
                attempts++;
                if ( locationService.Verify( address, true ) )
                {
                    successes++;
                }
                rockContext.SaveChanges();
                System.Threading.Thread.Sleep( throttlePeriod );
            }

            context.Result = string.Format( "{0:N0} address verifications attempted; {1:N0} successfully verified", attempts, successes );
        }
Example #4
0
        /// <summary>
        /// Gets the Location ID of a location already in Rock. --looks under dbo.group.foreignId then compares group.description with location name.
        /// </summary>
        /// <param name="rlcID">rlc ID </param>
        /// <returns>Location ID</returns>
        private int GetLocationId(int rlcId)
        {
            var lookupContext = new RockContext();
            var groupService = new GroupService(lookupContext);
            var rlcGroup = new Group();
            string rlcIdString = rlcId.ToString();
            rlcGroup = groupService.Queryable().Where(g => g.ForeignId == (rlcIdString)).FirstOrDefault();
            string groupLocation = String.Empty;
            if ( rlcGroup != null ) { groupLocation = rlcGroup.Description; }

            if (!String.IsNullOrWhiteSpace(groupLocation))
            {
                var locationService = new LocationService(lookupContext);
                var location = new List<Location>();
                location = locationService.Queryable().Where(l => l.ParentLocationId.HasValue).ToList();

                switch (groupLocation)
                {
                    case "A201":
                        {
                            return location.Where(l => l.Name == "A201").FirstOrDefault().Id;
                        }
                    case "A202":
                        {
                            return location.Where(l => l.Name == "A202").FirstOrDefault().Id;
                        }
                    case "Area X Basketball":
                        {
                            return location.Where(l => l.Name == "Area X").FirstOrDefault().Id;
                        }
                    case "Area X Main Area":
                        {
                            return location.Where(l => l.Name == "Area X").FirstOrDefault().Id;
                        }
                    case "Auditorium":
                        {
                            return location.Where(l => l.Name == "Auditorium").FirstOrDefault().Id;
                        }
                    case "Auditorium Recording Booth":
                        {
                            return location.Where(l => l.Name == "Auditorium").FirstOrDefault().Id;
                        }
                    case "Auditorium Sound Booth":
                        {
                            return location.Where(l => l.Name == "Auditorium").FirstOrDefault().Id;
                        }
                    case "Bookstore Downstairs":
                        {
                            return location.Where(l => l.Name == "Bookstore").FirstOrDefault().Id;
                        }
                    case "Bookstore Upstairs":
                        {
                            return location.Where(l => l.Name == "Bookstore").FirstOrDefault().Id;
                        }
                    case "Bug 117":
                        {
                            return location.Where(l => l.Name == "Bug").FirstOrDefault().Id;
                        }
                    case "Bunny 114":
                        {
                            return location.Where(l => l.Name == "Bunny").FirstOrDefault().Id;
                        }
                    case "Butterfly 108":
                        {
                            return location.Where(l => l.Name == "Butterfly").FirstOrDefault().Id;
                        }
                    case "C201":
                        {
                            return location.Where(l => l.Name == "C201").FirstOrDefault().Id;
                        }
                    case "C202":
                        {
                            return location.Where(l => l.Name == "C202").FirstOrDefault().Id;
                        }
                    case "C203":
                        {
                            return location.Where(l => l.Name == "C203").FirstOrDefault().Id;
                        }
                    case "Car 1":
                        {
                            return location.Where(l => l.Name == "Car 1").FirstOrDefault().Id;
                        }
                    case "Car 10":
                        {
                            return location.Where(l => l.Name == "Car 10").FirstOrDefault().Id;
                        }
                    case "Car 2":
                        {
                            return location.Where(l => l.Name == "Car 2").FirstOrDefault().Id;
                        }
                    case "Car 3":
                        {
                            return location.Where(l => l.Name == "Car 3").FirstOrDefault().Id;
                        }
                    case "Car 4":
                        {
                            return location.Where(l => l.Name == "Car 4").FirstOrDefault().Id;
                        }
                    case "Car 5":
                        {
                            return location.Where(l => l.Name == "Car 5").FirstOrDefault().Id;
                        }
                    case "Car 6":
                        {
                            return location.Where(l => l.Name == "Car 6").FirstOrDefault().Id;
                        }
                    case "Car 7":
                        {
                            return location.Where(l => l.Name == "Car 7").FirstOrDefault().Id;
                        }
                    case "Car 8":
                        {
                            return location.Where(l => l.Name == "Car 8").FirstOrDefault().Id;
                        }
                    case "Car 9":
                        {
                            return location.Where(l => l.Name == "Car 9").FirstOrDefault().Id;
                        }
                    case "Catapiller 107":
                        {
                            return location.Where( l => l.Name == "Caterpillar" ).FirstOrDefault().Id;
                        }
                    case "Chapel":
                        {
                            return location.Where(l => l.Name == "Chapel").FirstOrDefault().Id;
                        }
                    case "Chapel 101":
                        {
                            return location.Where(l => l.Name == "Chapel 101").FirstOrDefault().Id;
                        }
                    case "Chapel 102":
                        {
                            return location.Where( l => l.Name == "Chapel 102" ).FirstOrDefault().Id;
                        }
                    case "Chapel Hallway":
                        {
                            return location.Where(l => l.Name == "Chapel Entrance").FirstOrDefault().Id;
                        }
                    case "Chapel Sound Booth":
                        {
                            return location.Where(l => l.Name == "Chapel").FirstOrDefault().Id;
                        }
                    //case "Children's Lobby":  //Kayla doesn't know what location this is
                    //    {
                    //        return location.Where(l => l.Name == "A201").FirstOrDefault().Id;
                    //    }
                    case "College House":
                        {
                            return location.Where(l => l.Name == "The College House").FirstOrDefault().Id;
                        }
                    case "Communion Prep Room":
                        {
                            return location.Where(l => l.Name == "Communion Prep Room").FirstOrDefault().Id;
                        }
                    case "Cross Street Classroom":
                        {
                            return location.Where(l => l.Name == "Cross Street").FirstOrDefault().Id;
                        }
                    case "Cross Street Main Area":
                        {
                            return location.Where(l => l.Name == "Cross Street").FirstOrDefault().Id;
                        }
                    case "Crossroads Station Registration":
                        {
                            return location.Where(l => l.Name == "Crossroads Station").FirstOrDefault().Id;
                        }
                    case "Decision Room A":
                        {
                            return location.Where(l => l.Name == "Decision Room - A").FirstOrDefault().Id;
                        }
                    case "Decision Room B":
                        {
                            return location.Where(l => l.Name == "Decision Room - B").FirstOrDefault().Id;
                        }
                    case "Decision Room C":
                        {
                            return location.Where( l => l.Name == "Decision Room - C" ).FirstOrDefault().Id;
                        }
                    case "Duck 116":
                        {
                            return location.Where(l => l.Name == "Duck").FirstOrDefault().Id;
                        }
                    case "Giggleville Hallway":
                        {
                            return location.Where(l => l.Name == "Giggleville").FirstOrDefault().Id;
                        }
                    case "Giggleville Registration":
                        {
                            return location.Where(l => l.Name == "Giggleville").FirstOrDefault().Id;
                        }
                    case "Grand Hall":
                        {
                            return location.Where(l => l.Name == "Grand Hall").FirstOrDefault().Id;
                        }
                    case "Grand Hall 105":
                        {
                            return location.Where(l => l.Name == "Grand Hall").FirstOrDefault().Id;
                        }
                    case "Helping Hands House":
                        {
                            return location.Where(l => l.Name == "Helping Hands").FirstOrDefault().Id;
                        }
                    case "Kitchen":
                        {
                            return location.Where(l => l.Name == "Kitchen").FirstOrDefault().Id;
                        }
                    case "Lamb 115":
                        {
                            return location.Where(l => l.Name == "Lamb").FirstOrDefault().Id;
                        }
                    case "Main Lobby":
                        {
                            return location.Where(l => l.Name == "Main Lobby").FirstOrDefault().Id;
                        }
                    case "Main Lobby Upstairs":
                        {
                            return location.Where(l => l.Name == "Main Lobby").FirstOrDefault().Id;
                        }
                    case "Music Suite Main Area":
                        {
                            return location.Where(l => l.Name == "Music Suite").FirstOrDefault().Id;
                        }
                    case "Music Suite Room B":
                        {
                            return location.Where(l => l.Name == "Music Suite").FirstOrDefault().Id;
                        }
                    case "North Lobby":
                        {
                            return location.Where(l => l.Name == "North Lobby").FirstOrDefault().Id;
                        }
                    case "North Lobby Upstairs":
                        {
                            return location.Where(l => l.Name == "North Lobby").FirstOrDefault().Id;
                        }
                    case "Parking Lot A":
                        {
                            return location.Where(l => l.Name == "Parking Lot A").FirstOrDefault().Id;
                        }
                    case "Parking Lot B":
                        {
                            return location.Where(l => l.Name == "Parking Lot B").FirstOrDefault().Id;
                        }
                    case "Parking Lot C":
                        {
                            return location.Where(l => l.Name == "Parking Lot C").FirstOrDefault().Id;
                        }
                    case "Parking Lot D":
                        {
                            return location.Where(l => l.Name == "Parking Lot D").FirstOrDefault().Id;
                        }
                    case "Patio 1A":
                        {
                            return location.Where(l => l.Name == "Patio 1A").FirstOrDefault().Id;
                        }
                    case "Patio 1B":
                        {
                            return location.Where(l => l.Name == "Patio 1B").FirstOrDefault().Id;
                        }
                    case "Patio 2A":
                        {
                            return location.Where(l => l.Name == "Patio 2A").FirstOrDefault().Id;
                        }
                    case "Patio 2B":
                        {
                            return location.Where(l => l.Name == "Patio 2B").FirstOrDefault().Id;
                        }
                    case "Patio 2C":
                        {
                            return location.Where(l => l.Name == "Patio 2C").FirstOrDefault().Id;
                        }
                    case "Patio 3A":
                        {
                            return location.Where(l => l.Name == "Patio 3A").FirstOrDefault().Id;
                        }
                    case "Patio 3B":
                        {
                            return location.Where(l => l.Name == "Patio 3B").FirstOrDefault().Id;
                        }
                    case "Patio 3C":
                        {
                            return location.Where(l => l.Name == "Patio 3C").FirstOrDefault().Id;
                        }
                    case "Patio 4A":
                        {
                            return location.Where(l => l.Name == "Patio 4A").FirstOrDefault().Id;
                        }
                    case "Patio 4B":
                        {
                            return location.Where(l => l.Name == "Patio 4B").FirstOrDefault().Id;
                        }
                    case "Prayer Room":
                        {
                            return location.Where(l => l.Name == "Prayer Room").FirstOrDefault().Id;
                        }
                    case "Puppy 118":
                        {
                            return location.Where(l => l.Name == "Puppy").FirstOrDefault().Id;
                        }
                    case "South Lobby":
                        {
                            return location.Where(l => l.Name == "South Lobby").FirstOrDefault().Id;
                        }
                    case "Sportcenter":
                        {
                            return location.Where(l => l.Name == "SportCenter").FirstOrDefault().Id;
                        }
                    case "Squirrel 113":
                        {
                            return location.Where(l => l.Name == "Squirrel").FirstOrDefault().Id;
                        }
                    case "Texas Hall - Dallas":
                        {
                            return location.Where(l => l.Name == "Dallas").FirstOrDefault().Id;
                        }
                    case "Texas Hall - Fort Worth":
                        {
                            return location.Where(l => l.Name == "Fort Worth").FirstOrDefault().Id;
                        }
                    case "Texas Hall - Houston":
                        {
                            return location.Where(l => l.Name == "Houston").FirstOrDefault().Id;
                        }
                    case "Texas Hall - San Antonio":
                        {
                            return location.Where(l => l.Name == "San Antonio").FirstOrDefault().Id;
                        }
                    case "Youth Cafe":
                        {
                            return location.Where(l => l.Name == "Doulos").FirstOrDefault().Id;
                        }
                    case "Youth Lobby":
                        {
                            return location.Where(l => l.Name == "Doulos").FirstOrDefault().Id;
                        }
                    case "Youth Main Area":
                        {
                            return location.Where(l => l.Name == "Doulos").FirstOrDefault().Id;
                        }
                    default:
                        return location.Where(l => l.Name == "Main Building").FirstOrDefault().Id;
               }
            }
            else
            {
                var locationService = new LocationService(lookupContext);
                var location = new Location();
                location = locationService.Queryable().Where(l => l.Name == "Main Building").FirstOrDefault();
                return location.Id;
            }
        }
Example #5
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            Device Device = null;

            var rockContext = new RockContext();
            var deviceService = new DeviceService( rockContext );
            var attributeService = new AttributeService( rockContext );
            var locationService = new LocationService( rockContext );

            int DeviceId = int.Parse( hfDeviceId.Value );

            if ( DeviceId != 0 )
            {
                Device = deviceService.Get( DeviceId );
            }

            if ( Device == null )
            {
                // Check for existing
                var existingDevice = deviceService.Queryable()
                    .Where( d => d.Name == tbName.Text )
                    .FirstOrDefault();
                if ( existingDevice != null )
                {
                    nbDuplicateDevice.Text = string.Format( "A device already exists with the name '{0}'. Please use a different device name.", existingDevice.Name );
                    nbDuplicateDevice.Visible = true;
                }
                else
                {
                    Device = new Device();
                    deviceService.Add( Device );
                }
            }

            if ( Device != null )
            {
                Device.Name = tbName.Text;
                Device.Description = tbDescription.Text;
                Device.IPAddress = tbIpAddress.Text;
                Device.DeviceTypeValueId = ddlDeviceType.SelectedValueAsInt().Value;
                Device.PrintToOverride = (PrintTo)System.Enum.Parse( typeof( PrintTo ), ddlPrintTo.SelectedValue );
                Device.PrinterDeviceId = ddlPrinter.SelectedValueAsInt();
                Device.PrintFrom = (PrintFrom)System.Enum.Parse( typeof( PrintFrom ), ddlPrintFrom.SelectedValue );

                if ( Device.Location == null )
                {
                    Device.Location = new Location();
                }
                Device.Location.GeoPoint = geopPoint.SelectedValue;
                Device.Location.GeoFence = geopFence.SelectedValue;

                if ( !Device.IsValid || !Page.IsValid )
                {
                    // Controls will render the error messages
                    return;
                }

                // Remove any deleted locations
                foreach ( var location in Device.Locations
                    .Where( l =>
                        !Locations.Keys.Contains( l.Id ) )
                    .ToList() )
                {
                    Device.Locations.Remove( location );
                }

                // Add any new locations
                var existingLocationIDs = Device.Locations.Select( l => l.Id ).ToList();
                foreach ( var location in locationService.Queryable()
                    .Where( l =>
                        Locations.Keys.Contains( l.Id ) &&
                        !existingLocationIDs.Contains( l.Id ) ) )
                {
                    Device.Locations.Add( location );
                }

                rockContext.SaveChanges();

                Rock.CheckIn.KioskDevice.Flush( Device.Id );

                NavigateToParentPage();
            }
        }
Example #6
0
        /// <summary>
        /// Creates a Linq Expression that can be applied to an IQueryable to filter the result set.
        /// </summary>
        /// <param name="entityType">The type of entity in the result set.</param>
        /// <param name="serviceInstance">A service instance that can be queried to obtain the result set.</param>
        /// <param name="parameterExpression">The input parameter that will be injected into the filter expression.</param>
        /// <param name="selection">A formatted string representing the filter settings.</param>
        /// <returns>
        /// A Linq Expression that can be used to filter an IQueryable.
        /// </returns>
        /// <exception cref="System.Exception">Filter issue(s):  + errorMessages.AsDelimited( ;  )</exception>
        public override Expression GetExpression( Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection )
        {
            var settings = new FilterSettings( selection );

            var context = (RockContext)serviceInstance.Context;

            // Get the Location Data View that defines the set of candidates from which proximate Locations can be selected.
            var dataView = DataComponentSettingsHelper.GetDataViewForFilterComponent( settings.DataViewGuid, context );

            // Evaluate the Data View that defines the candidate Locations.
            var locationService = new LocationService( context );

            var locationQuery = locationService.Queryable();

            if ( dataView != null )
            {
                locationQuery = DataComponentSettingsHelper.FilterByDataView( locationQuery, dataView, locationService );
            }

            // Get all the Family Groups that have a Location matching one of the candidate Locations.
            int familyGroupTypeId = GroupTypeCache.Read( SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid() ).Id;

            var groupLocationsQuery = new GroupLocationService( context ).Queryable()
                                                                         .Where( gl => gl.Group.GroupTypeId == familyGroupTypeId && locationQuery.Any( l => l.Id == gl.LocationId ) );

            // If a Location Type is specified, apply the filter condition.
            if (settings.LocationTypeGuid.HasValue)
            {
                int groupLocationTypeId = DefinedValueCache.Read( settings.LocationTypeGuid.Value ).Id;

                groupLocationsQuery = groupLocationsQuery.Where( x => x.GroupLocationTypeValue.Id == groupLocationTypeId );
            }

            // Get all of the Group Members of the qualifying Families.
            var groupMemberServiceQry = new GroupMemberService( context ).Queryable()
                                                                         .Where( gm => groupLocationsQuery.Any( gl => gl.GroupId == gm.GroupId ) );

            // Get all of the People corresponding to the qualifying Group Members.
            var qry = new PersonService( context ).Queryable()
                                                  .Where( p => groupMemberServiceQry.Any( gm => gm.PersonId == p.Id ) );

            // Retrieve the Filter Expression.
            var extractedFilterExpression = FilterExpressionExtractor.Extract<Model.Person>( qry, parameterExpression, "p" );

            return extractedFilterExpression;
        }
Example #7
0
        /// <summary>
        /// Gets the device group types.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        /// <returns></returns>
        private List<GroupType> GetDeviceGroupTypes( int deviceId )
        {
            var groupTypes = new Dictionary<int, GroupType>();

            var locationService = new LocationService( new RockContext() );

            // Get all locations (and their children) associated with device
            var locationIds = locationService
                .GetByDevice(deviceId, true)
                .Select( l => l.Id)
                .ToList();

            // Requery using EF
            foreach ( var groupType in locationService.Queryable()
                .Where( l => locationIds.Contains( l.Id ) )
                .SelectMany( l => l.GroupLocations )
                .Select( gl => gl.Group.GroupType )
                .ToList() )
            {
                if ( !groupTypes.ContainsKey( groupType.Id ) )
                {
                    groupTypes.Add( groupType.Id, groupType );
                }
            }

            return groupTypes.Select( g => g.Value ).ToList();
        }
        /// <summary>
        /// Gets occurrence data for the selected group
        /// </summary>
        /// <param name="group">The group.</param>
        /// <param name="fromDateTime">From date time.</param>
        /// <param name="toDateTime">To date time.</param>
        /// <param name="locationIds">The location ids.</param>
        /// <param name="scheduleIds">The schedule ids.</param>
        /// <param name="loadSummaryData">if set to <c>true</c> [load summary data].</param>
        /// <param name="campusId">The campus identifier.</param>
        /// <returns></returns>
        public List <ScheduleOccurrence> GetGroupOccurrences(Group group, DateTime?fromDateTime, DateTime?toDateTime,
                                                             List <int> locationIds, List <int> scheduleIds, bool loadSummaryData, int?campusId)
        {
            var occurrences = new List <ScheduleOccurrence>();

            if (group != null)
            {
                var rockContext       = (RockContext)this.Context;
                var attendanceService = new AttendanceService(rockContext);
                var scheduleService   = new ScheduleService(rockContext);
                var locationService   = new LocationService(rockContext);

                using (new Rock.Data.QueryHintScope(rockContext, QueryHintType.RECOMPILE))
                {
                    // Set up an 'occurrences' query for the group
                    var qry = attendanceService
                              .Queryable().AsNoTracking()
                              .Where(a => a.GroupId == group.Id);

                    // Filter by date range
                    if (fromDateTime.HasValue)
                    {
                        var fromDate = fromDateTime.Value.Date;
                        qry = qry.Where(a => DbFunctions.TruncateTime(a.StartDateTime) >= (fromDate));
                    }
                    if (toDateTime.HasValue)
                    {
                        var toDate = toDateTime.Value.Date;
                        qry = qry.Where(a => DbFunctions.TruncateTime(a.StartDateTime) < (toDate));
                    }

                    // Location Filter
                    if (locationIds.Any())
                    {
                        qry = qry.Where(a => locationIds.Contains(a.LocationId ?? 0));
                    }

                    // Schedule Filter
                    if (scheduleIds.Any())
                    {
                        qry = qry.Where(a => scheduleIds.Contains(a.ScheduleId ?? 0));
                    }

                    // Get the unique combination of location/schedule/date for the selected group
                    var occurrenceDates = qry
                                          .Select(a => new
                    {
                        a.LocationId,
                        a.ScheduleId,
                        Date = DbFunctions.TruncateTime(a.StartDateTime)
                    })
                                          .Distinct()
                                          .ToList();

                    // Get the locations for each unique location id
                    var selectedlocationIds = occurrenceDates.Select(o => o.LocationId).Distinct().ToList();

                    var locations = locationService
                                    .Queryable().AsNoTracking()
                                    .Where(l => selectedlocationIds.Contains(l.Id))
                                    .Select(l => new { l.Id, l.ParentLocationId, l.Name })
                                    .ToList();
                    var locationNames = new Dictionary <int, string>();
                    locations.ForEach(l => locationNames.Add(l.Id, l.Name));

                    // Get the parent location path for each unique location
                    var parentlocationPaths = new Dictionary <int, string>();
                    locations
                    .Where(l => l.ParentLocationId.HasValue)
                    .Select(l => l.ParentLocationId.Value)
                    .Distinct()
                    .ToList()
                    .ForEach(l => parentlocationPaths.Add(l, locationService.GetPath(l)));
                    var locationPaths = new Dictionary <int, string>();
                    locations
                    .Where(l => l.ParentLocationId.HasValue)
                    .ToList()
                    .ForEach(l => locationPaths.Add(l.Id, parentlocationPaths[l.ParentLocationId.Value]));

                    // Get the schedules for each unique schedule id
                    var selectedScheduleIds = occurrenceDates.Select(o => o.ScheduleId).Distinct().ToList();
                    var schedules           = scheduleService
                                              .Queryable().AsNoTracking()
                                              .Where(s => selectedScheduleIds.Contains(s.Id))
                                              .ToList();
                    var scheduleNames      = new Dictionary <int, string>();
                    var scheduleStartTimes = new Dictionary <int, TimeSpan>();
                    schedules
                    .ForEach(s =>
                    {
                        scheduleNames.Add(s.Id, s.Name);
                        scheduleStartTimes.Add(s.Id, s.StartTimeOfDay);
                    });

                    foreach (var occurrence in occurrenceDates.Where(o => o.Date.HasValue))
                    {
                        occurrences.Add(
                            new ScheduleOccurrence(
                                occurrence.Date.Value,
                                occurrence.ScheduleId.HasValue && scheduleStartTimes.ContainsKey(occurrence.ScheduleId.Value) ?
                                scheduleStartTimes[occurrence.ScheduleId.Value] : new TimeSpan(),
                                occurrence.ScheduleId,
                                occurrence.ScheduleId.HasValue && scheduleNames.ContainsKey(occurrence.ScheduleId.Value) ?
                                scheduleNames[occurrence.ScheduleId.Value] : string.Empty,
                                occurrence.LocationId,
                                occurrence.LocationId.HasValue && locationNames.ContainsKey(occurrence.LocationId.Value) ?
                                locationNames[occurrence.LocationId.Value] : string.Empty,
                                occurrence.LocationId.HasValue && locationPaths.ContainsKey(occurrence.LocationId.Value) ?
                                locationPaths[occurrence.LocationId.Value] : string.Empty
                                ));
                    }
                }

                // Load the attendance data for each occurrence
                if (loadSummaryData && occurrences.Any())
                {
                    var minDate       = occurrences.Min(o => o.Date);
                    var maxDate       = occurrences.Max(o => o.Date).AddDays(1);
                    var attendanceQry = attendanceService
                                        .Queryable().AsNoTracking()
                                        .Where(a =>
                                               a.GroupId.HasValue &&
                                               a.GroupId == group.Id &&
                                               a.StartDateTime >= minDate &&
                                               a.StartDateTime < maxDate &&
                                               a.PersonAlias != null &&
                                               a.PersonAliasId.HasValue)
                                        .Select(a => new
                    {
                        a.LocationId,
                        a.ScheduleId,
                        a.StartDateTime,
                        a.DidAttend,
                        a.DidNotOccur,
                        a.PersonAliasId,
                        PersonId = a.PersonAlias.PersonId
                    });

                    if (campusId.HasValue)
                    {
                        var familyGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid());
                        var campusQry       = new GroupMemberService(rockContext)
                                              .Queryable()
                                              .Where(g =>
                                                     g.Group != null &&
                                                     g.Group.GroupTypeId == familyGroupType.Id &&
                                                     g.Group.CampusId.HasValue &&
                                                     g.Group.CampusId.Value == campusId.Value
                                                     )
                                              .Select(m => m.PersonId);

                        attendanceQry = attendanceQry
                                        .Where(s => campusQry.Contains(s.PersonId));
                    }

                    var attendances = attendanceQry.ToList();

                    foreach (var summary in attendances
                             .GroupBy(a => new
                    {
                        a.LocationId,
                        a.ScheduleId,
                        Date = a.StartDateTime.Date
                    })
                             .Select(a => new
                    {
                        a.Key.LocationId,
                        a.Key.ScheduleId,
                        a.Key.Date,
                        DidAttendCount = a
                                         .Where(t => t.DidAttend.HasValue && t.DidAttend.Value)
                                         .Select(t => t.PersonAliasId.Value)
                                         .Distinct()
                                         .Count(),
                        DidNotOccurCount = a
                                           .Where(t => t.DidNotOccur.HasValue && t.DidNotOccur.Value)
                                           .Select(t => t.PersonAliasId.Value)
                                           .Distinct()
                                           .Count(),
                        TotalCount = a
                                     .Select(t => t.PersonAliasId)
                                     .Distinct()
                                     .Count()
                    }))
                    {
                        var occurrence = occurrences
                                         .Where(o =>
                                                o.ScheduleId.Equals(summary.ScheduleId) &&
                                                o.LocationId.Equals(summary.LocationId) &&
                                                o.Date.Equals(summary.Date))
                                         .FirstOrDefault();
                        if (occurrence != null)
                        {
                            occurrence.DidAttendCount   = summary.DidAttendCount;
                            occurrence.DidNotOccurCount = summary.DidNotOccurCount;
                            occurrence.TotalCount       = summary.TotalCount;
                        }
                    }
                }

                // Create any missing occurrences from the group's schedule (not location schedules)
                Schedule groupSchedule = null;
                if (group.ScheduleId.HasValue)
                {
                    groupSchedule = group.Schedule;
                    if (groupSchedule == null)
                    {
                        groupSchedule = new ScheduleService(rockContext).Get(group.ScheduleId.Value);
                    }
                }

                if (groupSchedule != null)
                {
                    var newOccurrences = new List <ScheduleOccurrence>();

                    var existingDates = occurrences
                                        .Where(o => o.ScheduleId.Equals(groupSchedule.Id))
                                        .Select(o => o.Date)
                                        .Distinct()
                                        .ToList();

                    var startDate = fromDateTime.HasValue ? fromDateTime.Value : RockDateTime.Today.AddMonths(-2);
                    var endDate   = toDateTime.HasValue ? toDateTime.Value : RockDateTime.Today.AddDays(1);

                    DDay.iCal.Event calEvent = groupSchedule.GetCalenderEvent();
                    if (calEvent != null)
                    {
                        // If schedule has an iCal schedule, get all the past occurrences
                        foreach (var occurrence in calEvent.GetOccurrences(startDate, endDate))
                        {
                            var scheduleOccurrence = new ScheduleOccurrence(
                                occurrence.Period.StartTime.Date, occurrence.Period.StartTime.TimeOfDay, groupSchedule.Id, groupSchedule.Name);
                            if (!existingDates.Contains(scheduleOccurrence.Date))
                            {
                                newOccurrences.Add(scheduleOccurrence);
                            }
                        }
                    }
                    else
                    {
                        // if schedule does not have an iCal, then check for weekly schedule and calculate occurrences starting with first attendance or current week
                        if (groupSchedule.WeeklyDayOfWeek.HasValue)
                        {
                            // default to start with date 2 months earlier
                            startDate = fromDateTime.HasValue ? fromDateTime.Value : RockDateTime.Today.AddMonths(-2);
                            if (existingDates.Any(d => d < startDate))
                            {
                                startDate = existingDates.Min();
                            }

                            // Back up start time to the correct day of week
                            while (startDate.DayOfWeek != groupSchedule.WeeklyDayOfWeek.Value)
                            {
                                startDate = startDate.AddDays(-1);
                            }

                            // Add the start time
                            if (groupSchedule.WeeklyTimeOfDay.HasValue)
                            {
                                startDate = startDate.Add(groupSchedule.WeeklyTimeOfDay.Value);
                            }

                            // Create occurrences up to current time
                            while (startDate < endDate)
                            {
                                if (!existingDates.Contains(startDate.Date))
                                {
                                    var scheduleOccurrence = new ScheduleOccurrence(startDate.Date, startDate.TimeOfDay, groupSchedule.Id, groupSchedule.Name);
                                    newOccurrences.Add(scheduleOccurrence);
                                }

                                startDate = startDate.AddDays(7);
                            }
                        }
                    }

                    if (newOccurrences.Any())
                    {
                        // Filter Exclusions
                        var groupType = GroupTypeCache.Read(group.GroupTypeId);
                        foreach (var exclusion in groupType.GroupScheduleExclusions)
                        {
                            if (exclusion.Start.HasValue && exclusion.End.HasValue)
                            {
                                foreach (var occurrence in newOccurrences.ToList())
                                {
                                    if (occurrence.Date >= exclusion.Start.Value &&
                                        occurrence.Date < exclusion.End.Value.AddDays(1))
                                    {
                                        newOccurrences.Remove(occurrence);
                                    }
                                }
                            }
                        }
                    }

                    foreach (var occurrence in newOccurrences)
                    {
                        occurrences.Add(occurrence);
                    }
                }
            }

            return(occurrences);
        }
Example #9
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            Campus campus;
            var rockContext = new RockContext();
            var campusService = new CampusService( rockContext );
            var locationService = new LocationService( rockContext );
            var locationCampusValue = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.LOCATION_TYPE_CAMPUS.AsGuid());

            int campusId = int.Parse( hfCampusId.Value );

            if ( campusId == 0 )
            {
                campus = new Campus();
                campusService.Add( campus);
            }
            else
            {
                campus = campusService.Get( campusId );
            }

            campus.Name = tbCampusName.Text;
            campus.IsActive = cbIsActive.Checked;
            campus.Description = tbDescription.Text;
            campus.Url = tbUrl.Text;

            campus.PhoneNumber = tbPhoneNumber.Text;
            if ( campus.Location == null )
            {
                var location = locationService.Queryable()
                    .Where( l =>
                        l.Name.Equals( campus.Name, StringComparison.OrdinalIgnoreCase ) &&
                        l.LocationTypeValueId == locationCampusValue.Id )
                    .FirstOrDefault();
                if (location == null)
                {
                    location = new Location();
                    locationService.Add( location );
                }

                campus.Location = location;
            }

            campus.Location.Name = campus.Name;
            campus.Location.LocationTypeValueId = locationCampusValue.Id;

            string preValue = campus.Location.GetFullStreetAddress();
            acAddress.GetValues( campus.Location );
            string postValue = campus.Location.GetFullStreetAddress();

            campus.ShortCode = tbCampusCode.Text;

            var personService = new PersonService( rockContext );
            var leaderPerson = personService.Get( ppCampusLeader.SelectedValue ?? 0 );
            campus.LeaderPersonAliasId = leaderPerson != null ? leaderPerson.PrimaryAliasId : null;

            campus.ServiceTimes = kvlServiceTimes.Value;

            campus.LoadAttributes( rockContext );
            Rock.Attribute.Helper.GetEditValues( phAttributes, campus );

            if ( !campus.IsValid && campus.Location.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            rockContext.WrapTransaction( () =>
            {
                rockContext.SaveChanges();
                campus.SaveAttributeValues( rockContext );

                if (preValue != postValue && !string.IsNullOrWhiteSpace(campus.Location.Street1))
                {
                    locationService.Verify(campus.Location, true);
                }

            } );

            Rock.Web.Cache.CampusCache.Flush( campus.Id );

            NavigateToParentPage();
        }
        /// <summary>
        /// Creates the group editor controls.
        /// </summary>
        /// <param name="group">The group.</param>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="createExpanded">if set to <c>true</c> [create expanded].</param>
        private void CreateGroupEditorControls( Group group, Control parentControl, RockContext rockContext, bool createExpanded = false )
        {
            CheckinGroupEditor groupEditor = new CheckinGroupEditor();
            groupEditor.ID = "GroupEditor_" + group.Guid.ToString( "N" );
            if ( createExpanded )
            {
                groupEditor.Expanded = true;
            }

            parentControl.Controls.Add( groupEditor );
            groupEditor.SetGroup( group, rockContext );
            var locationService = new LocationService( rockContext );
            var locationQry = locationService.Queryable().Select( a => new { a.Id, a.ParentLocationId, a.Name } );

            groupEditor.Locations = new List<CheckinGroupEditor.LocationGridItem>();
            foreach ( var location in group.GroupLocations.Select( a => a.Location ).OrderBy( o => o.Name ) )
            {
                var gridItem = new CheckinGroupEditor.LocationGridItem();
                gridItem.LocationId = location.Id;
                gridItem.Name = location.Name;
                gridItem.FullNamePath = location.Name;
                gridItem.ParentLocationId = location.ParentLocationId;

                var parentLocationId = location.ParentLocationId;
                while ( parentLocationId != null )
                {
                    var parentLocation = locationQry.FirstOrDefault( a => a.Id == parentLocationId );
                    gridItem.FullNamePath = parentLocation.Name + " > " + gridItem.FullNamePath;
                    parentLocationId = parentLocation.ParentLocationId;
                }

                groupEditor.Locations.Add( gridItem );
            }

            groupEditor.AddLocationClick += groupEditor_AddLocationClick;
            groupEditor.DeleteLocationClick += groupEditor_DeleteLocationClick;
            groupEditor.DeleteGroupClick += groupEditor_DeleteGroupClick;
        }
Example #11
0
        /// <summary>
        /// Gets occurrence data for the selected group
        /// </summary>
        /// <param name="group">The group.</param>
        /// <param name="fromDateTime">From date time.</param>
        /// <param name="toDateTime">To date time.</param>
        /// <param name="locationIds">The location ids.</param>
        /// <param name="scheduleIds">The schedule ids.</param>
        /// <param name="loadSummaryData">if set to <c>true</c> [load summary data].</param>
        /// <returns></returns>
        public List<ScheduleOccurrence> GetGroupOccurrences( Group group, DateTime? fromDateTime, DateTime? toDateTime, 
            List<int> locationIds, List<int> scheduleIds, bool loadSummaryData )
        {
            var occurrences = new List<ScheduleOccurrence>();

            if ( group != null )
            {
                var rockContext = (RockContext)this.Context;
                var attendanceService = new AttendanceService( rockContext );
                var scheduleService = new ScheduleService( rockContext );
                var locationService = new LocationService( rockContext );

                // Set up an 'occurrences' query for the group
                var qry = attendanceService
                    .Queryable().AsNoTracking()
                    .Where( a => a.GroupId == group.Id );

                // Filter by date range
                if ( fromDateTime.HasValue )
                {
                    var fromDate = fromDateTime.Value.Date;
                    qry = qry.Where( a => DbFunctions.TruncateTime( a.StartDateTime ) >= ( fromDate ) );
                }
                if ( toDateTime.HasValue )
                {
                    var toDate = toDateTime.Value.Date;
                    qry = qry.Where( a => DbFunctions.TruncateTime( a.StartDateTime ) < ( toDate ) );
                }

                // Location Filter
                if ( locationIds.Any()  )
                {
                    qry = qry.Where( a =>
                        a.LocationId.HasValue &&
                        locationIds.Contains( a.LocationId.Value ) );
                }

                // Schedule Filter
                if ( scheduleIds.Any() )
                {
                    qry = qry.Where( a =>
                        a.ScheduleId.HasValue &&
                        scheduleIds.Contains( a.ScheduleId.Value ) );
                }

                // Get the unique combination of location/schedule/date for the selected group
                var occurrenceDates = qry
                    .Select( a => new
                    {
                        a.LocationId,
                        a.ScheduleId,
                        Date = DbFunctions.TruncateTime( a.StartDateTime )
                    } )
                    .Distinct()
                    .ToList();

                // Get the locations for each unique location id
                var selectedlocationIds = occurrenceDates.Select( o => o.LocationId ).Distinct().ToList();
                var locations = locationService
                    .Queryable().AsNoTracking()
                    .Where( l => selectedlocationIds.Contains( l.Id ) )
                    .Select( l => new { l.Id, l.ParentLocationId, l.Name } )
                    .ToList();
                var locationNames = new Dictionary<int, string>();
                locations.ForEach( l => locationNames.Add( l.Id, l.Name ) );

                // Get the parent location path for each unique location
                var parentlocationPaths = new Dictionary<int, string>();
                locations
                    .Where( l => l.ParentLocationId.HasValue )
                    .Select( l => l.ParentLocationId.Value )
                    .Distinct()
                    .ToList()
                    .ForEach( l => parentlocationPaths.Add( l, locationService.GetPath( l ) ) );
                var locationPaths = new Dictionary<int, string>();
                locations
                    .Where( l => l.ParentLocationId.HasValue )
                    .ToList()
                    .ForEach( l => locationPaths.Add( l.Id, parentlocationPaths[l.ParentLocationId.Value] ) );

                // Get the schedules for each unique schedule id
                var selectedScheduleIds = occurrenceDates.Select( o => o.ScheduleId ).Distinct().ToList();
                var schedules = scheduleService
                    .Queryable().AsNoTracking()
                    .Where( s => selectedScheduleIds.Contains( s.Id ) )
                    .ToList();
                var scheduleNames = new Dictionary<int, string>();
                var scheduleStartTimes = new Dictionary<int, TimeSpan>();
                schedules
                    .ForEach( s => {
                        scheduleNames.Add( s.Id, s.Name );
                        scheduleStartTimes.Add( s.Id, s.StartTimeOfDay );
                    });

                foreach ( var occurrence in occurrenceDates.Where( o => o.Date.HasValue ) )
                {
                    occurrences.Add(
                        new ScheduleOccurrence(
                            occurrence.Date.Value,
                            occurrence.ScheduleId.HasValue && scheduleStartTimes.ContainsKey( occurrence.ScheduleId.Value ) ?
                                scheduleStartTimes[occurrence.ScheduleId.Value] : new TimeSpan(),
                            occurrence.ScheduleId,
                            occurrence.ScheduleId.HasValue && scheduleNames.ContainsKey( occurrence.ScheduleId.Value ) ?
                                scheduleNames[occurrence.ScheduleId.Value] : string.Empty,
                            occurrence.LocationId,
                            occurrence.LocationId.HasValue && locationNames.ContainsKey( occurrence.LocationId.Value ) ?
                                locationNames[occurrence.LocationId.Value] : string.Empty,
                            occurrence.LocationId.HasValue && locationPaths.ContainsKey( occurrence.LocationId.Value ) ?
                                locationPaths[occurrence.LocationId.Value] : string.Empty
                        ) );
                }

                // Load the attendance data for each occurrence
                if ( loadSummaryData && occurrences.Any())
                {
                    var minDate = occurrences.Min( o => o.Date );
                    var maxDate = occurrences.Max( o => o.Date ).AddDays( 1 );

                    foreach( var summary in attendanceService
                        .Queryable().AsNoTracking()
                        .Where( a =>
                            a.PersonAliasId.HasValue &&
                            a.GroupId.HasValue &&
                            a.GroupId == group.Id &&
                            a.StartDateTime >= minDate &&
                            a.StartDateTime < maxDate )
                        .GroupBy( a => new
                        {
                            a.LocationId,
                            a.ScheduleId,
                            Date = DbFunctions.TruncateTime( a.StartDateTime )
                        } )
                        .Select( a => new
                        {
                            a.Key.LocationId,
                            a.Key.ScheduleId,
                            a.Key.Date,
                            DidAttendCount = a
                                .Where( t => t.DidAttend.HasValue && t.DidAttend.Value )
                                .Select( t => t.PersonAliasId.Value )
                                .Distinct()
                                .Count(),
                            DidNotOccurCount = a
                                .Where( t => t.DidNotOccur.HasValue && t.DidNotOccur.Value )
                                .Select( t => t.PersonAliasId.Value )
                                .Distinct()
                                .Count(),
                            TotalCount = a
                                .Select( t => t.PersonAliasId )
                                .Distinct()
                                .Count()
                        } ) )
                    {
                        var occurrence = occurrences
                            .Where( o =>
                                o.ScheduleId.Equals( summary.ScheduleId ) &&
                                o.LocationId.Equals( summary.LocationId ) &&
                                o.Date.Equals( summary.Date ) )
                            .FirstOrDefault();
                        if ( occurrence != null )
                        {
                            occurrence.DidAttendCount = summary.DidAttendCount;
                            occurrence.DidNotOccurCount = summary.DidNotOccurCount;
                            occurrence.TotalCount = summary.TotalCount;
                        }
                    }
                }

                // Create any missing occurrences from the group's schedule (not location schedules)
                Schedule groupSchedule = null;
                if ( group.ScheduleId.HasValue )
                {
                    groupSchedule = group.Schedule;
                    if ( groupSchedule == null )
                    {
                        groupSchedule = new ScheduleService( rockContext ).Get( group.ScheduleId.Value );
                    }
                }

                if ( groupSchedule != null )
                {
                    var newOccurrences = new List<ScheduleOccurrence>();

                    var existingDates = occurrences
                        .Where( o => o.ScheduleId.Equals( groupSchedule.Id ) )
                        .Select( o => o.Date )
                        .Distinct()
                        .ToList();

                    var startDate = fromDateTime.HasValue ? fromDateTime.Value : RockDateTime.Today.AddMonths( -2 );
                    var endDate = toDateTime.HasValue ? toDateTime.Value : RockDateTime.Today.AddDays( 1 );

                    DDay.iCal.Event calEvent = groupSchedule.GetCalenderEvent();
                    if ( calEvent != null )
                    {
                        // If schedule has an iCal schedule, get all the past occurrences
                        foreach ( var occurrence in calEvent.GetOccurrences( startDate, endDate ) )
                        {
                            var scheduleOccurrence = new ScheduleOccurrence(
                                occurrence.Period.StartTime.Date, occurrence.Period.StartTime.TimeOfDay, groupSchedule.Id, groupSchedule.Name );
                            if ( !existingDates.Contains( scheduleOccurrence.Date ) )
                            {
                                newOccurrences.Add( scheduleOccurrence );
                            }
                        }
                    }
                    else
                    {
                        // if schedule does not have an iCal, then check for weekly schedule and calculate occurrences starting with first attendance or current week
                        if ( groupSchedule.WeeklyDayOfWeek.HasValue )
                        {

                            // default to start with date 2 months earlier
                            startDate = fromDateTime.HasValue ? fromDateTime.Value : RockDateTime.Today.AddMonths( -2 );
                            if ( existingDates.Any( d => d < startDate ) )
                            {
                                startDate = existingDates.Min();
                            }

                            // Back up start time to the correct day of week
                            while ( startDate.DayOfWeek != groupSchedule.WeeklyDayOfWeek.Value )
                            {
                                startDate = startDate.AddDays( -1 );
                            }

                            // Add the start time
                            if ( groupSchedule.WeeklyTimeOfDay.HasValue )
                            {
                                startDate = startDate.Add( groupSchedule.WeeklyTimeOfDay.Value );
                            }

                            // Create occurrences up to current time
                            while ( startDate < endDate )
                            {
                                if ( !existingDates.Contains( startDate.Date ) )
                                {
                                    var scheduleOccurrence = new ScheduleOccurrence( startDate.Date, startDate.TimeOfDay, groupSchedule.Id, groupSchedule.Name );
                                    newOccurrences.Add( scheduleOccurrence );
                                }

                                startDate = startDate.AddDays( 7 );
                            }
                        }
                    }

                    if ( newOccurrences.Any() )
                    {
                        // Filter Exclusions
                        var groupType = GroupTypeCache.Read( group.GroupTypeId );
                        foreach ( var exclusion in groupType.GroupScheduleExclusions )
                        {
                            if ( exclusion.Start.HasValue && exclusion.End.HasValue )
                            {
                                foreach ( var occurrence in newOccurrences.ToList() )
                                {
                                    if ( occurrence.Date >= exclusion.Start.Value &&
                                        occurrence.Date < exclusion.End.Value.AddDays( 1 ) )
                                    {
                                        newOccurrences.Remove( occurrence );
                                    }
                                }
                            }
                        }
                    }

                    foreach( var occurrence in newOccurrences )
                    {
                        occurrences.Add( occurrence );
                    }

                }
            }

            return occurrences;
        }
Example #12
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            Device Device;
            var rockContext = new RockContext();
            var deviceService = new DeviceService( rockContext );
            var attributeService = new AttributeService( rockContext );
            var locationService = new LocationService( rockContext );

            int DeviceId = int.Parse( hfDeviceId.Value );

            if ( DeviceId == 0 )
            {
                Device = new Device();
                deviceService.Add( Device );
            }
            else
            {
                Device = deviceService.Get( DeviceId );
            }

            Device.Name = tbName.Text;
            Device.Description = tbDescription.Text;
            Device.IPAddress = tbIpAddress.Text;
            Device.DeviceTypeValueId = ddlDeviceType.SelectedValueAsInt().Value;
            Device.PrintToOverride = (PrintTo)System.Enum.Parse( typeof( PrintTo ), ddlPrintTo.SelectedValue );
            Device.PrinterDeviceId = ddlPrinter.SelectedValueAsInt();
            Device.PrintFrom = (PrintFrom)System.Enum.Parse( typeof( PrintFrom ), ddlPrintFrom.SelectedValue );

            if ( Device.Location == null )
            {
                Device.Location = new Location();
            }
            Device.Location.GeoPoint = geopPoint.SelectedValue;
            Device.Location.GeoFence = geopFence.SelectedValue;

            if ( !Device.IsValid || !Page.IsValid )
            {
                // Controls will render the error messages
                return;
            }

            // Remove any deleted locations
            foreach ( var location in Device.Locations
                .Where( l =>
                    !Locations.Keys.Contains( l.Id ) )
                .ToList() )
            {
                Device.Locations.Remove( location );
            }

            // Add any new locations
            var existingLocationIDs = Device.Locations.Select( l => l.Id ).ToList();
            foreach ( var location in locationService.Queryable()
                .Where( l =>
                    Locations.Keys.Contains( l.Id ) &&
                    !existingLocationIDs.Contains( l.Id) ) )
            {
                Device.Locations.Add(location);
            }

            rockContext.SaveChanges();

            NavigateToParentPage();
        }
Example #13
0
        /// <summary>
        /// Gets the device group types.
        /// </summary>
        /// <param name="deviceId">The device identifier.</param>
        /// <returns></returns>
        private List<GroupType> GetDeviceGroupTypes( int deviceId, RockContext rockContext )
        {
            var groupTypes = new Dictionary<int, GroupType>();

            var locationService = new LocationService( rockContext );

            // Get all locations (and their children) associated with device
            var locationIds = locationService
                .GetByDevice( deviceId, true )
                .Select( l => l.Id )
                .ToList();

            // Requery using EF
            foreach ( var groupType in locationService
                .Queryable().AsNoTracking()
                .Where( l => locationIds.Contains( l.Id ) )
                .SelectMany( l => l.GroupLocations )
                .Where( gl => gl.Group.GroupType.TakesAttendance )
                .Select( gl => gl.Group.GroupType )
                .ToList() )
            {
                groupTypes.AddOrIgnore( groupType.Id, groupType );
            }

            return groupTypes
                .Select( g => g.Value )
                .OrderBy( g => g.Order )
                .ToList();
        }
Example #14
0
        private void SelectGroup( Guid? groupGuid )
        {
            hfIsDirty.Value = "false";

            checkinArea.Visible = false;
            checkinGroup.Visible = false;
            btnSave.Visible = false;

            if ( groupGuid.HasValue )
            {
                using ( var rockContext = new RockContext() )
                {
                    var groupService = new GroupService( rockContext );
                    var group = groupService.Get( groupGuid.Value );
                    if ( group != null )
                    {
                        _currentGroupGuid = group.Guid;

                        checkinGroup.SetGroup( group, rockContext );

                        var locationService = new LocationService( rockContext );
                        var locationQry = locationService.Queryable().Select( a => new { a.Id, a.ParentLocationId, a.Name } );

                        checkinGroup.Locations = new List<CheckinGroup.LocationGridItem>();
                        foreach ( var groupLocation in group.GroupLocations.OrderBy( gl => gl.Order ).ThenBy( gl => gl.Location.Name ) )
                        {
                            var location = groupLocation.Location;
                            var gridItem = new CheckinGroup.LocationGridItem();
                            gridItem.LocationId = location.Id;
                            gridItem.Name = location.Name;
                            gridItem.FullNamePath = location.Name;
                            gridItem.ParentLocationId = location.ParentLocationId;
                            gridItem.Order = groupLocation.Order;

                            var parentLocationId = location.ParentLocationId;
                            while ( parentLocationId != null )
                            {
                                var parentLocation = locationQry.FirstOrDefault( a => a.Id == parentLocationId );
                                gridItem.FullNamePath = parentLocation.Name + " > " + gridItem.FullNamePath;
                                parentLocationId = parentLocation.ParentLocationId;
                            }

                            checkinGroup.Locations.Add( gridItem );
                        }

                        checkinGroup.Visible = true;
                        btnSave.Visible = true;
                    }
                    else
                    {
                        _currentGroupGuid = null;
                    }
                }
            }
            else
            {
                _currentGroupGuid = null;
                checkinGroup.CreateGroupAttributeControls( null, null );
            }

            BuildRows();
        }
Example #15
0
 private void AddChildLocations( LocationService service, int locationId, List<int> ids )
 {
     foreach ( var location in service.Queryable().Where( l => l.ParentLocationId == locationId ) )
     {
         ids.Add( location.Id );
         AddChildLocations( service, location.Id, ids );
     }
 }