Data access and service class for Rock.Model.Location entities.
        /// <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>
        /// Binds the group members grid.
        /// </summary>
        protected void BindGrid()
        {
            if ( _group != null )
            {
                lHeading.Text = _group.Name;

                DateTime? fromDateTime = drpDates.LowerValue;
                DateTime? toDateTime = drpDates.UpperValue;
                List<int> locationIds = new List<int>();
                List<int> scheduleIds = new List<int>();

                // Location Filter
                if ( ddlLocation.Visible )
                {
                    string locValue = ddlLocation.SelectedValue;
                    if ( locValue.StartsWith( "P" ) )
                    {
                        int? parentLocationId = locValue.Substring( 1 ).AsIntegerOrNull();
                        if ( parentLocationId.HasValue )
                        {
                            locationIds = new LocationService( _rockContext )
                                .GetAllDescendents( parentLocationId.Value )
                                .Select( l => l.Id )
                                .ToList();
                        }
                    }
                    else
                    {
                        int? locationId = locValue.AsIntegerOrNull();
                        if ( locationId.HasValue )
                        {
                            locationIds.Add( locationId.Value );
                        }
                    }
                }

                // Schedule Filter
                if ( ddlSchedule.Visible && ddlSchedule.SelectedValue != "0" )
                {
                    scheduleIds.Add( ddlSchedule.SelectedValueAsInt() ?? 0 );
                }

                var qry = new ScheduleService( _rockContext ).GetGroupOccurrences( _group, fromDateTime, toDateTime, locationIds, scheduleIds, true ).AsQueryable();

                SortProperty sortProperty = gOccurrences.SortProperty;
                List<ScheduleOccurrence> occurrences = null;
                if ( sortProperty != null )
                {
                    occurrences = qry.Sort( sortProperty ).ToList();
                }
                else
                {
                    occurrences = qry.OrderByDescending( a => a.Date ).ThenByDescending( a => a.StartTime ).ToList();
                }

                gOccurrences.DataSource = occurrences;
                gOccurrences.DataBind();
            }
        }
Example #3
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 #4
0
        /// <summary>
        /// Sends statistics to the SDN server but only if there are more than 100 person records
        /// or the sample data has not been loaded.
        ///
        /// The statistics are:
        ///     * Rock Instance Id
        ///     * Update Version
        ///     * IP Address - The IP address of your Rock server.
        ///
        /// ...and we only send these if they checked the "Include Impact Statistics":
        ///     * Organization Name and Address
        ///     * Public Web Address
        ///     * Number of Active Records
        ///
        /// As per http://www.rockrms.com/Rock/Impact
        /// </summary>
        /// <param name="version">the semantic version number</param>
        private void SendStatictics(string version)
        {
            try
            {
                var rockContext           = new RockContext();
                int numberOfActiveRecords = new PersonService(rockContext).Queryable(includeDeceased: false, includeBusinesses: false).Count();

                if (numberOfActiveRecords > 100 || !Rock.Web.SystemSettings.GetValue(SystemSettingKeys.SAMPLEDATA_DATE).AsDateTime().HasValue)
                {
                    string         organizationName     = string.Empty;
                    ImpactLocation organizationLocation = null;
                    string         publicUrl            = string.Empty;

                    var rockInstanceId = Rock.Web.SystemSettings.GetRockInstanceId();
                    var ipAddress      = Request.ServerVariables["LOCAL_ADDR"];

                    if (cbIncludeStats.Checked)
                    {
                        var globalAttributes = GlobalAttributesCache.Read();
                        organizationName = globalAttributes.GetValue("OrganizationName");
                        publicUrl        = globalAttributes.GetValue("PublicApplicationRoot");

                        // Fetch the organization address
                        var organizationAddressLocationGuid = globalAttributes.GetValue("OrganizationAddress").AsGuid();
                        if (!organizationAddressLocationGuid.Equals(Guid.Empty))
                        {
                            var location = new Rock.Model.LocationService(rockContext).Get(organizationAddressLocationGuid);
                            if (location != null)
                            {
                                organizationLocation = new ImpactLocation(location);
                            }
                        }
                    }
                    else
                    {
                        numberOfActiveRecords = 0;
                    }

                    var environmentData = Rock.Web.Utilities.RockUpdateHelper.GetEnvDataAsJson(Request, ResolveRockUrl("~/"));

                    // now send them to SDN/Rock server
                    SendToSpark(rockInstanceId, version, ipAddress, publicUrl, organizationName, organizationLocation, numberOfActiveRecords, environmentData);
                }
            }
            catch (Exception ex)
            {
                // Just catch any exceptions, log it, and keep moving... We don't want to mess up the experience
                // over a few statistics/metrics.
                try
                {
                    LogException(ex);
                }
                catch { }
            }
        }
Example #5
0
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed )
        {
            string formattedValue = string.Empty;

            if ( !string.IsNullOrWhiteSpace( value ) )
            {
                var service = new LocationService();
                var location = service.Get( new Guid( value ) );

                if ( location != null )
                {
                    formattedValue = location.ToString();
                }
            }

            return base.FormatValue( parentControl, formattedValue, null, condensed );
        }
        public Location Geocode( Location location )
        {
            var user = CurrentUser();
            if ( user != null )
            {
                if ( location != null )
                {
                    var locationService = new LocationService();
                    locationService.Geocode( location, user.PersonId );
                    return location;
                }

                throw new HttpResponseException( HttpStatusCode.BadRequest );
            }

            throw new HttpResponseException( HttpStatusCode.Unauthorized );
        }
Example #7
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 #8
0
        /// <summary>
        /// Gets the tags.
        /// </summary>
        /// <returns></returns>
        private IQueryable <Location> GetLocations()
        {
            int filterCount = 0;
            var queryable   = new Rock.Model.LocationService(new RockContext()).Queryable()
                              .Where(l => l.Street1 != null && l.Street1 != string.Empty);

            if (!string.IsNullOrWhiteSpace(rFilter.GetUserPreference("Street Address")))
            {
                string streetAddress1 = rFilter.GetUserPreference("Street Address");
                queryable = queryable.Where(l => l.Street1.StartsWith(streetAddress1));
                filterCount++;
            }

            if (!string.IsNullOrWhiteSpace(rFilter.GetUserPreference("City")))
            {
                string city = rFilter.GetUserPreference("City");
                queryable = queryable.Where(l => l.City.StartsWith(city));
                filterCount++;
            }

            if (!string.IsNullOrWhiteSpace(rFilter.GetUserPreference("Not Geocoded")))
            {
                bool notGeocoded = Convert.ToBoolean(rFilter.GetUserPreference("Not Geocoded"));
                if (notGeocoded)
                {
                    queryable = queryable.Where(l => l.GeoPoint == null);
                    filterCount++;
                }
            }

            if (filterCount == 0)
            {
                return(null);
            }
            else
            {
                return(queryable);
            }
        }
Example #9
0
        /// <summary>
        /// Sends statistics to the SDN server but only if there are more than 100 person records
        /// or the sample data has not been loaded. 
        /// 
        /// The statistics are:
        ///     * Rock Instance Id
        ///     * Update Version
        ///     * IP Address - The IP address of your Rock server.
        ///     
        /// ...and we only send these if they checked the "Include Impact Statistics":
        ///     * Organization Name and Address
        ///     * Public Web Address
        ///     * Number of Active Records
        ///     
        /// As per http://www.rockrms.com/Rock/Impact
        /// </summary>
        /// <param name="version">the semantic version number</param>
        private void SendStatictics( string version )
        {
            try
            {
                var rockContext = new RockContext();
                int numberOfActiveRecords = new PersonService( rockContext ).Queryable( includeDeceased: false, includeBusinesses: false ).Count();

                if ( numberOfActiveRecords > 100 || !Rock.Web.SystemSettings.GetValue( SystemSettingKeys.SAMPLEDATA_DATE ).AsDateTime().HasValue )
                {
                    string organizationName = string.Empty;
                    ImpactLocation organizationLocation = null;
                    string publicUrl = string.Empty;

                    var rockInstanceId = Rock.Web.SystemSettings.GetRockInstanceId();
                    var ipAddress = Request.ServerVariables["LOCAL_ADDR"];

                    if ( cbIncludeStats.Checked )
                    {
                        var globalAttributes = GlobalAttributesCache.Read();
                        organizationName = globalAttributes.GetValue( "OrganizationName" );
                        publicUrl = globalAttributes.GetValue( "PublicApplicationRoot" );

                        // Fetch the organization address
                        var organizationAddressLocationGuid = globalAttributes.GetValue( "OrganizationAddress" ).AsGuid();
                        if ( !organizationAddressLocationGuid.Equals( Guid.Empty ) )
                        {
                            var location = new Rock.Model.LocationService( rockContext ).Get( organizationAddressLocationGuid );
                            if ( location != null )
                            {
                                organizationLocation = new ImpactLocation( location );
                            }
                        }
                    }
                    else
                    {
                        numberOfActiveRecords = 0;
                    }

                    // now send them to SDN/Rock server
                    SendToSpark( rockInstanceId, version, ipAddress, publicUrl, organizationName, organizationLocation, numberOfActiveRecords );
                }
            }
            catch ( Exception ex )
            {
                // Just catch any exceptions, log it, and keep moving... We don't want to mess up the experience
                // over a few statistics/metrics.
                try
                {
                    LogException( ex );
                }
                catch { }
            }
        }
Example #10
0
        protected void btnAddLocation_Click( object sender, EventArgs e )
        {
            // Add the location (ignore if they didn't pick one, or they picked one that already is selected)
            var location = new LocationService( new RockContext() ).Get( locationPicker.SelectedValue.AsInteger() );
            if ( location != null )
            {
                string path = location.Name;
                var parentLocation = location.ParentLocation;
                while ( parentLocation != null )
                {
                    path = parentLocation.Name + " > " + path;
                    parentLocation = parentLocation.ParentLocation;
                }
                Locations.Add( location.Id, path );
            }

            BindLocations();

            hfAddLocationId.Value = string.Empty;
            mdLocationPicker.Hide();
        }
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="location">The location.</param>
        private void ShowEditDetails( Location location )
        {
            if ( location.Id == 0 )
            {
                lReadOnlyTitle.Text = ActionTitle.Add( Location.FriendlyTypeName ).FormatAsHtmlTitle();
                hlInactive.Visible = false;
            }
            else
            {
                if ( string.IsNullOrWhiteSpace( location.Name ) )
                {
                    lReadOnlyTitle.Text = location.ToString().FormatAsHtmlTitle();
                }
                else
                {
                    lReadOnlyTitle.Text = location.Name.FormatAsHtmlTitle();
                }
            }

            SetEditMode( true );

            imgImage.BinaryFileId = location.ImageId;
            imgImage.NoPictureUrl = System.Web.VirtualPathUtility.ToAbsolute( "~/Assets/Images/no-picture.svg?" );

            tbName.Text = location.Name;
            cbIsActive.Checked = location.IsActive;
            acAddress.SetValues( location );
            ddlPrinter.SetValue( location.PrinterDeviceId );
            geopPoint.SetValue( location.GeoPoint );
            geopFence.SetValue( location.GeoFence );

            cbGeoPointLocked.Checked = location.IsGeoPointLocked ?? false;

            Guid mapStyleValueGuid = GetAttributeValue( "MapStyle" ).AsGuid();
            geopPoint.MapStyleValueGuid = mapStyleValueGuid;
            geopFence.MapStyleValueGuid = mapStyleValueGuid;

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

            ddlLocationType.BindToDefinedType( DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.LOCATION_TYPE.AsGuid() ), true );

            gpParentLocation.Location = location.ParentLocation ?? locationService.Get( location.ParentLocationId ?? 0 );

            // LocationType depends on Selected ParentLocation
            if ( location.Id == 0 && ddlLocationType.Items.Count > 1 )
            {
                // if this is a new location
                ddlLocationType.SelectedIndex = 0;
            }
            else
            {
                ddlLocationType.SetValue( location.LocationTypeValueId );
            }

            location.LoadAttributes( rockContext );
            BuildAttributeEdits( location, true );
        }
Example #12
0
        /// <summary>
        /// Sets from payment information.
        /// </summary>
        /// <param name="paymentInfo">The payment information.</param>
        /// <param name="paymentGateway">The payment gateway.</param>
        /// <param name="rockContext">The rock context.</param>
        public void SetFromPaymentInfo(PaymentInfo paymentInfo, GatewayComponent paymentGateway, RockContext rockContext)
        {
            if (AccountNumberMasked.IsNullOrWhiteSpace() && paymentInfo.MaskedNumber.IsNotNullOrWhitespace())
            {
                AccountNumberMasked = paymentInfo.MaskedNumber;
            }

            if (!CurrencyTypeValueId.HasValue && paymentInfo.CurrencyTypeValue != null)
            {
                CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;
            }

            if (!CreditCardTypeValueId.HasValue && paymentInfo.CreditCardTypeValue != null)
            {
                CreditCardTypeValueId = paymentInfo.CreditCardTypeValue.Id;
            }

            if (paymentInfo is CreditCardPaymentInfo)
            {
                var ccPaymentInfo = (CreditCardPaymentInfo)paymentInfo;

                string nameOnCard  = paymentGateway.SplitNameOnCard ? ccPaymentInfo.NameOnCard + " " + ccPaymentInfo.LastNameOnCard : ccPaymentInfo.NameOnCard;
                var    newLocation = new LocationService(rockContext).Get(
                    ccPaymentInfo.BillingStreet1, ccPaymentInfo.BillingStreet2, ccPaymentInfo.BillingCity, ccPaymentInfo.BillingState, ccPaymentInfo.BillingPostalCode, ccPaymentInfo.BillingCountry);

                if (NameOnCard.IsNullOrWhiteSpace() && NameOnCard.IsNotNullOrWhitespace())
                {
                    NameOnCardEncrypted = Encryption.EncryptString(nameOnCard);
                }

                if (!ExpirationMonth.HasValue)
                {
                    ExpirationMonthEncrypted = Encryption.EncryptString(ccPaymentInfo.ExpirationDate.Month.ToString());
                }

                if (!ExpirationYear.HasValue)
                {
                    ExpirationYearEncrypted = Encryption.EncryptString(ccPaymentInfo.ExpirationDate.Year.ToString());
                }

                if (!BillingLocationId.HasValue && newLocation != null)
                {
                    BillingLocationId = newLocation.Id;
                }
            }
            else if (paymentInfo is SwipePaymentInfo)
            {
                var swipePaymentInfo = (SwipePaymentInfo)paymentInfo;

                if (NameOnCard.IsNullOrWhiteSpace() && NameOnCard.IsNotNullOrWhitespace())
                {
                    NameOnCardEncrypted = Encryption.EncryptString(swipePaymentInfo.NameOnCard);
                }

                if (!ExpirationMonth.HasValue)
                {
                    ExpirationMonthEncrypted = Encryption.EncryptString(swipePaymentInfo.ExpirationDate.Month.ToString());
                }

                if (!ExpirationYear.HasValue)
                {
                    ExpirationYearEncrypted = Encryption.EncryptString(swipePaymentInfo.ExpirationDate.Year.ToString());
                }
            }
        }
Example #13
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        protected void BindGrid()
        {
            AddScheduleColumns();

            var rockContext = new RockContext();

            var groupLocationService = new GroupLocationService( rockContext );
            var groupTypeService = new GroupTypeService( rockContext );
            var groupService = new GroupService( rockContext );

            IEnumerable<GroupTypePath> groupPaths = new List<GroupTypePath>();
            var groupLocationQry = groupLocationService.Queryable();

            List<int> currentAndDescendantGroupTypeIds = new List<int>();
            var currentGroupTypeIds = this.CurrentGroupTypeIds.ToList();
            currentAndDescendantGroupTypeIds.AddRange( currentGroupTypeIds );
            foreach ( var templateGroupType in groupTypeService.Queryable().Where( a => currentGroupTypeIds.Contains( a.Id ) ) )
            {
                foreach ( var childGroupType in groupTypeService.GetChildGroupTypes( templateGroupType.Id ) )
                {
                    currentAndDescendantGroupTypeIds.Add( childGroupType.Id );
                    currentAndDescendantGroupTypeIds.AddRange( groupTypeService.GetAllAssociatedDescendents( childGroupType.Id ).Select( a => a.Id ).ToList() );
                }
            }

            groupLocationQry = groupLocationQry.Where( a => currentAndDescendantGroupTypeIds.Contains( a.Group.GroupTypeId ) );

            groupLocationQry = groupLocationQry.OrderBy( a => a.Group.Name ).ThenBy( a => a.Location.Name );

            List<int> currentDeviceLocationIdList = this.GetGroupTypesLocations( rockContext ).Select( a => a.Id ).Distinct().ToList();

            var qryList = groupLocationQry
                .Where( a => currentDeviceLocationIdList.Contains( a.LocationId ) )
                .Select( a =>
                new
                {
                    GroupLocationId = a.Id,
                    a.Location,
                    GroupId = a.GroupId,
                    GroupName = a.Group.Name,
                    ScheduleIdList = a.Schedules.Select( s => s.Id ),
                    GroupTypeId = a.Group.GroupTypeId
                } ).ToList();

            var locationService = new LocationService( rockContext );

            // put stuff in a datatable so we can dynamically have columns for each Schedule
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add( "GroupLocationId" );
            dataTable.Columns.Add( "GroupId" );
            dataTable.Columns.Add( "GroupName" );
            dataTable.Columns.Add( "GroupPath" );
            dataTable.Columns.Add( "LocationName" );
            dataTable.Columns.Add( "LocationPath" );
            foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() )
            {
                dataTable.Columns.Add( field.DataField, typeof( bool ) );
            }

            var locationPaths = new Dictionary<int, string>();

            foreach ( var row in qryList )
            {
                DataRow dataRow = dataTable.NewRow();
                dataRow["GroupLocationId"] = row.GroupLocationId;
                dataRow["GroupName"] = groupService.GroupAncestorPathName( row.GroupId );
                dataRow["GroupPath"] = groupPaths.Where( gt => gt.GroupTypeId == row.GroupTypeId ).Select( gt => gt.Path ).FirstOrDefault();
                dataRow["LocationName"] = row.Location.Name;

                if ( row.Location.ParentLocationId.HasValue )
                {
                    int locationId = row.Location.ParentLocationId.Value;

                    if ( !locationPaths.ContainsKey( locationId ) )
                    {
                        var locationNames = new List<string>();
                        var parentLocation = locationService.Get( locationId );
                        while ( parentLocation != null )
                        {
                            locationNames.Add( parentLocation.Name );
                            parentLocation = parentLocation.ParentLocation;
                        }

                        if ( locationNames.Any() )
                        {
                            locationNames.Reverse();
                            locationPaths.Add( locationId, locationNames.AsDelimited( " > " ) );
                        }
                        else
                        {
                            locationPaths.Add( locationId, string.Empty );
                        }
                    }

                    dataRow["LocationPath"] = locationPaths[locationId];
                }

                foreach ( var field in gGroupLocationSchedule.Columns.OfType<CheckBoxEditableField>() )
                {
                    int scheduleId = int.Parse( field.DataField.Replace( "scheduleField_", string.Empty ) );
                    dataRow[field.DataField] = row.ScheduleIdList.Any( a => a == scheduleId );
                }

                dataTable.Rows.Add( dataRow );
            }

            gGroupLocationSchedule.EntityTypeId = EntityTypeCache.Read<GroupLocation>().Id;
            gGroupLocationSchedule.DataSource = dataTable;
            gGroupLocationSchedule.DataBind();
        }
        /// <summary>
        /// Sets any payment information that the <seealso cref="GatewayComponent">paymentGateway</seealso> didn't set
        /// </summary>
        /// <param name="paymentInfo">The payment information.</param>
        /// <param name="paymentGateway">The payment gateway.</param>
        /// <param name="rockContext">The rock context.</param>
        public void SetFromPaymentInfo(PaymentInfo paymentInfo, GatewayComponent paymentGateway, RockContext rockContext)
        {
            /* 2020-08-27 MDP
             * This method should only update values haven't been set yet. So
             *  1) Make sure paymentInfo has the data (isn't null or whitespace)
             *  2) Don't overwrite data in this (FinancialPaymentDetail) that already has the data set.
             */

            if (AccountNumberMasked.IsNullOrWhiteSpace() && paymentInfo.MaskedNumber.IsNotNullOrWhiteSpace())
            {
                AccountNumberMasked = paymentInfo.MaskedNumber;
            }

            if (paymentInfo is ReferencePaymentInfo referencePaymentInfo)
            {
                if (GatewayPersonIdentifier.IsNullOrWhiteSpace())
                {
                    GatewayPersonIdentifier = referencePaymentInfo.GatewayPersonIdentifier;
                }

                if (!FinancialPersonSavedAccountId.HasValue)
                {
                    FinancialPersonSavedAccountId = referencePaymentInfo.FinancialPersonSavedAccountId;
                }
            }

            if (!CurrencyTypeValueId.HasValue && paymentInfo.CurrencyTypeValue != null)
            {
                CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;
            }

            if (!CreditCardTypeValueId.HasValue && paymentInfo.CreditCardTypeValue != null)
            {
                CreditCardTypeValueId = paymentInfo.CreditCardTypeValue.Id;
            }

            if (paymentInfo is CreditCardPaymentInfo)
            {
                var ccPaymentInfo = ( CreditCardPaymentInfo )paymentInfo;

                string nameOnCard = paymentGateway.SplitNameOnCard ? ccPaymentInfo.NameOnCard + " " + ccPaymentInfo.LastNameOnCard : ccPaymentInfo.NameOnCard;

                // since the Address info could coming from an external system (the Gateway), don't do Location validation when creating a new location
                var newLocation = new LocationService(rockContext).Get(
                    ccPaymentInfo.BillingStreet1, ccPaymentInfo.BillingStreet2, ccPaymentInfo.BillingCity, ccPaymentInfo.BillingState, ccPaymentInfo.BillingPostalCode, ccPaymentInfo.BillingCountry, new GetLocationArgs {
                    ValidateLocation = false, CreateNewLocation = true
                });

                if (NameOnCard.IsNullOrWhiteSpace() && nameOnCard.IsNotNullOrWhiteSpace())
                {
                    NameOnCard = nameOnCard;
                }

                if (!ExpirationMonth.HasValue)
                {
                    ExpirationMonth = ccPaymentInfo.ExpirationDate.Month;
                }

                if (!ExpirationYear.HasValue)
                {
                    ExpirationYear = ccPaymentInfo.ExpirationDate.Year;
                }

                if (!BillingLocationId.HasValue && newLocation != null)
                {
                    BillingLocationId = newLocation.Id;
                }
            }
            else if (paymentInfo is SwipePaymentInfo)
            {
                var swipePaymentInfo = ( SwipePaymentInfo )paymentInfo;

                if (NameOnCard.IsNullOrWhiteSpace() && swipePaymentInfo.NameOnCard.IsNotNullOrWhiteSpace())
                {
                    NameOnCard = swipePaymentInfo.NameOnCard;
                }

                if (!ExpirationMonth.HasValue)
                {
                    ExpirationMonth = swipePaymentInfo.ExpirationDate.Month;
                }

                if (!ExpirationYear.HasValue)
                {
                    ExpirationYear = swipePaymentInfo.ExpirationDate.Year;
                }
            }
            else
            {
                // since the Address info could coming from an external system (the Gateway), don't do Location validation when creating a new location
                var newLocation = new LocationService(rockContext).Get(
                    paymentInfo.Street1, paymentInfo.Street2, paymentInfo.City, paymentInfo.State, paymentInfo.PostalCode, paymentInfo.Country, new GetLocationArgs {
                    ValidateLocation = false, CreateNewLocation = true
                });

                if (!BillingLocationId.HasValue && newLocation != null)
                {
                    BillingLocationId = newLocation.Id;
                }
            }
        }
        /// <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 )
        {
            // confirmation was disabled by btnSave on client-side.  So if returning without a redirect,
            // it should be enabled.  If returning with a redirect, the control won't be updated to reflect
            // confirmation being enabled, so it's ok to enable it here
            confirmExit.Enabled = true;

            if ( Page.IsValid )
            {
                confirmExit.Enabled = true;

                RockTransactionScope.WrapTransaction( () =>
                {
                    var rockContext = new RockContext();
                    var familyService = new GroupService( rockContext );
                    var familyMemberService = new GroupMemberService( rockContext );
                    var personService = new PersonService( rockContext );
                    var historyService = new HistoryService( rockContext );

                    var familyChanges = new List<string>();

                    // SAVE FAMILY
                    _family = familyService.Get( _family.Id );

                    History.EvaluateChange( familyChanges, "Family Name", _family.Name, tbFamilyName.Text );
                    _family.Name = tbFamilyName.Text;

                    int? campusId = cpCampus.SelectedValueAsInt();
                    if ( _family.CampusId != campusId )
                    {
                        History.EvaluateChange( familyChanges, "Campus",
                            _family.CampusId.HasValue ? CampusCache.Read( _family.CampusId.Value ).Name : string.Empty,
                            campusId.HasValue ? CampusCache.Read( campusId.Value ).Name : string.Empty );
                        _family.CampusId = campusId;
                    }

                    var familyGroupTypeId = _family.GroupTypeId;

                    rockContext.SaveChanges();

                    // SAVE FAMILY MEMBERS
                    int? recordStatusValueID = ddlRecordStatus.SelectedValueAsInt();
                    int? reasonValueId = ddlReason.SelectedValueAsInt();
                    var newFamilies = new List<Group>();

                    foreach ( var familyMember in FamilyMembers )
                    {
                        var memberChanges = new List<string>();
                        var demographicChanges = new List<string>();

                        var role = familyRoles.Where( r => r.Guid.Equals( familyMember.RoleGuid ) ).FirstOrDefault();
                        if ( role == null )
                        {
                            role = familyRoles.FirstOrDefault();
                        }

                        bool isChild = role != null && role.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) );

                        // People added to family (new or from other family)
                        if ( !familyMember.ExistingFamilyMember )
                        {
                            var groupMember = new GroupMember();

                            if ( familyMember.Id == -1 )
                            {
                                // added new person
                                demographicChanges.Add( "Created" );

                                var person = new Person();
                                person.FirstName = familyMember.FirstName;
                                person.NickName = familyMember.NickName;
                                History.EvaluateChange( demographicChanges, "First Name", string.Empty, person.FirstName );

                                person.LastName = familyMember.LastName;
                                History.EvaluateChange( demographicChanges, "Last Name", string.Empty, person.LastName );

                                person.Gender = familyMember.Gender;
                                History.EvaluateChange( demographicChanges, "Gender", null, person.Gender );

                                person.BirthDate = familyMember.BirthDate;
                                History.EvaluateChange( demographicChanges, "Birth Date", null, person.BirthDate );

                                if ( !isChild )
                                {
                                    person.GivingGroupId = _family.Id;
                                    History.EvaluateChange( demographicChanges, "Giving Group", string.Empty, _family.Name );
                                }

                                person.EmailPreference = EmailPreference.EmailAllowed;

                                groupMember.Person = person;
                            }
                            else
                            {
                                // added from other family
                                groupMember.Person = personService.Get( familyMember.Id );
                            }

                            if ( recordStatusValueID > 0 )
                            {
                                History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( groupMember.Person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) );
                                groupMember.Person.RecordStatusValueId = recordStatusValueID;

                                History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( groupMember.Person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) );
                                groupMember.Person.RecordStatusReasonValueId = reasonValueId;
                            }

                            groupMember.GroupId = _family.Id;
                            if ( role != null )
                            {
                                History.EvaluateChange( memberChanges, "Role", string.Empty, role.Name );
                                groupMember.GroupRoleId = role.Id;
                            }

                            if ( groupMember.Person != null )
                            {
                                familyMemberService.Add( groupMember );
                                rockContext.SaveChanges();
                                familyMember.Id = groupMember.Person.Id;
                            }

                        }
                        else
                        {
                            // existing family members
                            var groupMember = familyMemberService.Queryable( "Person" ).Where( m =>
                                m.PersonId == familyMember.Id &&
                                m.Group.GroupTypeId == familyGroupTypeId &&
                                m.GroupId == _family.Id ).FirstOrDefault();

                            if ( groupMember != null )
                            {
                                if ( familyMember.Removed )
                                {
                                    var newFamilyChanges = new List<string>();

                                    // Family member was removed and should be created in their own new family
                                    var newFamily = new Group();
                                    newFamily.Name = familyMember.LastName + " Family";
                                    History.EvaluateChange( newFamilyChanges, "Family", string.Empty, newFamily.Name );

                                    newFamily.GroupTypeId = familyGroupTypeId;

                                    if ( _family.CampusId.HasValue )
                                    {
                                        History.EvaluateChange( newFamilyChanges, "Campus", string.Empty, CampusCache.Read( _family.CampusId.Value ).Name );
                                    }
                                    newFamily.CampusId = _family.CampusId;

                                    familyService.Add( newFamily );
                                    rockContext.SaveChanges();

                                    // If person's previous giving group was this family, set it to their new family id
                                    if ( groupMember.Person.GivingGroup != null && groupMember.Person.GivingGroupId == _family.Id )
                                    {
                                        History.EvaluateChange( demographicChanges, "Giving Group", groupMember.Person.GivingGroup.Name, _family.Name );
                                        groupMember.Person.GivingGroupId = newFamily.Id;
                                    }

                                    groupMember.Group = newFamily;
                                    rockContext.SaveChanges();

                                    var newMemberChanges = new List<string>();
                                    History.EvaluateChange( newMemberChanges, "Role", string.Empty, groupMember.GroupRole.Name );

                                    HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                        groupMember.Person.Id, newFamilyChanges, newFamily.Name, typeof( Group ), newFamily.Id );

                                    newFamilies.Add( newFamily );

                                    History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole.Name, string.Empty );
                                }
                                else
                                {
                                    // Existing member was not remvoved
                                    if ( role != null )
                                    {
                                        History.EvaluateChange( memberChanges, "Role",
                                            groupMember.GroupRole != null ? groupMember.GroupRole.Name : string.Empty, role.Name );
                                        groupMember.GroupRoleId = role.Id;

                                        if ( recordStatusValueID > 0 )
                                        {
                                            History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( groupMember.Person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) );
                                            groupMember.Person.RecordStatusValueId = recordStatusValueID;

                                            History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( groupMember.Person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) );
                                            groupMember.Person.RecordStatusReasonValueId = reasonValueId;
                                        }

                                        rockContext.SaveChanges();
                                    }
                                }
                            }
                        }

                        // Remove anyone that was moved from another family
                        if ( familyMember.RemoveFromOtherFamilies )
                        {
                            var otherFamilies = familyMemberService.Queryable()
                                .Where( m =>
                                    m.PersonId == familyMember.Id &&
                                    m.Group.GroupTypeId == familyGroupTypeId &&
                                    m.GroupId != _family.Id )
                                .ToList();

                            foreach ( var otherFamilyMember in otherFamilies )
                            {
                                var fm = familyMemberService.Get( otherFamilyMember.Id );

                                // If the person's giving group id was the family they are being removed from, update it to this new family's id
                                if ( fm.Person.GivingGroupId == fm.GroupId )
                                {
                                    var person = personService.Get( fm.PersonId );

                                    History.EvaluateChange( demographicChanges, "Giving Group", person.GivingGroup.Name, _family.Name );
                                    person.GivingGroupId = _family.Id;

                                    rockContext.SaveChanges();
                                }

                                var oldMemberChanges = new List<string>();
                                History.EvaluateChange( oldMemberChanges, "Role", fm.GroupRole.Name, string.Empty );
                                History.EvaluateChange( oldMemberChanges, "Family", fm.Group.Name, string.Empty );
                                HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                    fm.Person.Id, oldMemberChanges, fm.Group.Name, typeof( Group ), fm.Group.Id );

                                familyMemberService.Delete( fm );
                                rockContext.SaveChanges();

                                var f = familyService.Queryable()
                                    .Where( g =>
                                        g.Id == otherFamilyMember.GroupId &&
                                        !g.Members.Any() )
                                    .FirstOrDefault();
                                if ( f != null )
                                {
                                    familyService.Delete( f );
                                    rockContext.SaveChanges();
                                }

                            }
                        }

                        HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                            familyMember.Id, demographicChanges );

                        HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            familyMember.Id, memberChanges, _family.Name, typeof( Group ), _family.Id );
                    }

                    // SAVE LOCATIONS
                    var groupLocationService = new GroupLocationService( rockContext );

                    // delete any group locations that were removed
                    var remainingLocationIds = FamilyAddresses.Where( a => a.Id > 0 ).Select( a => a.Id ).ToList();
                    foreach ( var removedLocation in groupLocationService.Queryable( "GroupLocationTypeValue,Location" )
                        .Where( l => l.GroupId == _family.Id &&
                            !remainingLocationIds.Contains( l.Id ) ) )
                    {
                        History.EvaluateChange( familyChanges, removedLocation.GroupLocationTypeValue.Name + " Location",
                            removedLocation.Location.ToString(), string.Empty );
                        groupLocationService.Delete( removedLocation );
                    }
                    rockContext.SaveChanges();

                    foreach ( var familyAddress in FamilyAddresses )
                    {
                        Location updatedAddress = null;
                        if ( familyAddress.LocationIsDirty )
                        {
                            updatedAddress = new LocationService( rockContext ).Get(
                                familyAddress.Street1, familyAddress.Street2, familyAddress.City,
                                familyAddress.State, familyAddress.Zip );
                        }

                        GroupLocation groupLocation = null;
                        if ( familyAddress.Id > 0 )
                        {
                            groupLocation = groupLocationService.Get( familyAddress.Id );
                        }
                        if ( groupLocation == null )
                        {
                            groupLocation = new GroupLocation();
                            groupLocation.GroupId = _family.Id;
                            groupLocationService.Add( groupLocation );
                        }

                        History.EvaluateChange( familyChanges, "Location Type",
                            groupLocation.GroupLocationTypeValueId.HasValue ? DefinedValueCache.Read( groupLocation.GroupLocationTypeValueId.Value ).Name : string.Empty,
                            familyAddress.LocationTypeName );
                        groupLocation.GroupLocationTypeValueId = familyAddress.LocationTypeId;

                        History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Is Mailing",
                            groupLocation.IsMailingLocation.ToString(), familyAddress.IsMailing.ToString() );
                        groupLocation.IsMailingLocation = familyAddress.IsMailing;

                        History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Is Map Location",
                            groupLocation.IsMappedLocation.ToString(), familyAddress.IsLocation.ToString() );
                        groupLocation.IsMappedLocation = familyAddress.IsLocation;

                        if ( updatedAddress != null )
                        {
                            History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Location",
                                groupLocation.Location != null ? groupLocation.Location.ToString() : "", updatedAddress.ToString() );
                            groupLocation.Location = updatedAddress;
                        }

                        rockContext.SaveChanges();

                        // Add the same locations to any new families created by removing an existing family member
                        if ( newFamilies.Any() )
                        {
                            //reload grouplocation for access to child properties
                            groupLocation = groupLocationService.Get( groupLocation.Id );
                            foreach ( var newFamily in newFamilies )
                            {
                                var newFamilyLocation = new GroupLocation();
                                newFamilyLocation.GroupId = newFamily.Id;
                                newFamilyLocation.LocationId = groupLocation.LocationId;
                                newFamilyLocation.GroupLocationTypeValueId = groupLocation.GroupLocationTypeValueId;
                                newFamilyLocation.IsMailingLocation = groupLocation.IsMailingLocation;
                                newFamilyLocation.IsMappedLocation = groupLocation.IsMappedLocation;
                                groupLocationService.Add( newFamilyLocation );
                            }

                            rockContext.SaveChanges();
                        }
                    }

                    foreach ( var fm in _family.Members )
                    {
                        HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            fm.PersonId, familyChanges, _family.Name, typeof( Group ), _family.Id );
                    }

                    _family = familyService.Get( _family.Id );
                    if ( _family.Members.Any( m => m.PersonId == Person.Id ) )
                    {
                        Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false );
                    }
                    else
                    {
                        var fm = _family.Members
                            .Where( m =>
                                m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) &&
                                m.Person.Gender == Gender.Male )
                            .OrderByDescending( m => m.Person.Age )
                            .FirstOrDefault();
                        if ( fm == null )
                        {
                            fm = _family.Members
                                .Where( m =>
                                    m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) )
                                .OrderByDescending( m => m.Person.Age )
                                .FirstOrDefault();
                        }
                        if ( fm == null )
                        {
                            fm = _family.Members
                                .OrderByDescending( m => m.Person.Age )
                                .FirstOrDefault();
                        }
                        if ( fm != null )
                        {
                            Response.Redirect( string.Format( "~/Person/{0}", fm.PersonId ), false );
                        }
                        else
                        {
                            Response.Redirect( "~", false );
                        }
                    }

                } );
            }
        }
        /// <summary>
        /// Returns the first <see cref="Rock.Model.Location"/> with a GeoFence that matches
        /// the specified GeoFence.
        /// </summary>
        /// <param name="fence">A <see cref="System.Data.Entity.Spatial.DbGeography"/> object that 
        ///  represents the GeoFence of the location to retrieve.</param>
        /// <returns>The <see cref="Rock.Model.Location"/> for the specified GeoFence. </returns>
        public Location GetByGeoFence( DbGeography fence )
        {

            // get the first address that has a GeoPoint or GeoFence that matches the value
            var result = Queryable()
                .Where( a => 
                    a.GeoFence != null &&
                    a.GeoFence.SpatialEquals( fence ) )
                .FirstOrDefault();

            if ( result == null )
            {
                // if the Location can't be found, save the new location to the database
                Location newLocation = new Location
                {
                    GeoFence = fence,
                    Guid = Guid.NewGuid()
                };

                // Create a new context/service so that save does not affect calling method's context
                var rockContext = new RockContext();
                var locationService = new LocationService( rockContext );
                locationService.Add( newLocation );
                rockContext.SaveChanges();

                // refetch it from the database to make sure we get a valid .Id
                return Get( newLocation.Guid );
            }

            return result;

        }
Example #17
0
        /// <summary>
        /// Returns the first <see cref="Rock.Model.Location" /> where the address matches the provided address, otherwise the address will be saved as a new location.
        /// Note: if <paramref name="street1"/> is blank, null will be returned.
        /// Note: The location search IS NOT constrained by the provided group. Providing the group will cause this method to search that groups locations first, giving a faster result.
        /// </summary>
        /// <param name="street1">A <see cref="string" /> representing the Address Line 1 to search by.</param>
        /// <param name="street2">A <see cref="string" /> representing the Address Line 2 to search by.</param>
        /// <param name="city">A <see cref="string" /> representing the City to search by.</param>
        /// <param name="state">A <see cref="string" /> representing the State to search by.</param>
        /// <param name="postalCode">A <see cref="string" /> representing the Zip/Postal code to search by</param>
        /// <param name="country">A <see cref="string" /> representing the Country to search by</param>
        /// <param name="group">The <see cref="Group"/> (usually a Family) that should be searched first. This is NOT a search constraint.</param>
        /// <param name="verifyLocation">if set to <c>true</c> [verify location].</param>
        /// <param name="createNewLocation">if set to <c>true</c> a new location will be created if it does not exists.</param>
        /// <returns>
        /// The first <see cref="Rock.Model.Location" /> where an address match is found, if no match is found a new <see cref="Rock.Model.Location" /> is created and returned.
        /// </returns>
        public Location Get(string street1, string street2, string city, string state, string postalCode, string country, Group group, bool verifyLocation = true, bool createNewLocation = true)
        {
            //// Make sure it's not an empty address
            //// This will not be checked anymore to enable a location to save with whatever info is available. Sometimes the only info given or legible on the card is the city and state.
            //// If there are any downstream effects of this change do not fix them by uncommenting this code without speaking to the architect first.
            //if ( string.IsNullOrWhiteSpace( street1 ) )
            //{
            //    return null;
            //}

            // Try to find a location that matches the values, this is not a case sensitive match
            var foundLocation = Search(new Location {
                Street1 = street1, Street2 = street2, City = city, State = state, PostalCode = postalCode, Country = country
            }, group);

            if (foundLocation != null)
            {
                // Check for casing
                if (!String.Equals(street1, foundLocation.Street1) || !String.Equals(street2, foundLocation.Street2) || !String.Equals(city, foundLocation.City) || !String.Equals(state, foundLocation.State) || !String.Equals(postalCode, foundLocation.PostalCode) || !String.Equals(country, foundLocation.Country))
                {
                    var context  = new RockContext();
                    var location = new LocationService(context).Get(foundLocation.Id);
                    location.Street1    = street1;
                    location.Street2    = street2;
                    location.City       = city;
                    location.State      = state;
                    location.PostalCode = postalCode;
                    location.Country    = country;
                    context.SaveChanges();
                    return(Get(location.Guid));
                }
                return(foundLocation);
            }

            // If existing location wasn't found with entered values, try standardizing the values, and search for an existing value again
            var newLocation = new Location
            {
                Street1    = street1.FixCase(),
                Street2    = street2.FixCase(),
                City       = city.FixCase(),
                State      = state,
                PostalCode = postalCode,
                Country    = country
            };

            if (verifyLocation)
            {
                Verify(newLocation, false);
            }

            foundLocation = Search(newLocation, group);
            if (foundLocation != null)
            {
                return(foundLocation);
            }

            if (createNewLocation)
            {
                // Create a new context/service so that save does not affect calling method's context
                var rockContext     = new RockContext();
                var locationService = new LocationService(rockContext);
                locationService.Add(newLocation);
                rockContext.SaveChanges();
            }

            // refetch it from the database to make sure we get a valid .Id
            return(Get(newLocation.Guid));
        }
Example #18
0
        /// <summary>
        /// Sets any payment information that the <seealso cref="GatewayComponent">paymentGateway</seealso> didn't set
        /// </summary>
        /// <param name="paymentInfo">The payment information.</param>
        /// <param name="paymentGateway">The payment gateway.</param>
        /// <param name="rockContext">The rock context.</param>
        public void SetFromPaymentInfo(PaymentInfo paymentInfo, GatewayComponent paymentGateway, RockContext rockContext)
        {
            /* 2020-08-27 MDP
             * This method should only update values haven't been set yet. So
             *  1) Make sure paymentInfo has the data (isn't null or whitespace)
             *  2) Don't overwrite data in this (FinancialPaymentDetail) that already has the data set.
             */

            if (AccountNumberMasked.IsNullOrWhiteSpace() && paymentInfo.MaskedNumber.IsNotNullOrWhiteSpace())
            {
                AccountNumberMasked = paymentInfo.MaskedNumber;
            }

            if (paymentInfo is ReferencePaymentInfo referencePaymentInfo)
            {
                if (GatewayPersonIdentifier.IsNullOrWhiteSpace())
                {
                    GatewayPersonIdentifier = referencePaymentInfo.GatewayPersonIdentifier;
                }

                if (!FinancialPersonSavedAccountId.HasValue)
                {
                    FinancialPersonSavedAccountId = referencePaymentInfo.FinancialPersonSavedAccountId;
                }
            }

            if (!CurrencyTypeValueId.HasValue && paymentInfo.CurrencyTypeValue != null)
            {
                CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;
            }

            if (!CreditCardTypeValueId.HasValue && paymentInfo.CreditCardTypeValue != null)
            {
                CreditCardTypeValueId = paymentInfo.CreditCardTypeValue.Id;
            }

            if (paymentInfo is CreditCardPaymentInfo)
            {
                var ccPaymentInfo = ( CreditCardPaymentInfo )paymentInfo;

                string nameOnCard  = paymentGateway.SplitNameOnCard ? ccPaymentInfo.NameOnCard + " " + ccPaymentInfo.LastNameOnCard : ccPaymentInfo.NameOnCard;
                var    newLocation = new LocationService(rockContext).Get(
                    ccPaymentInfo.BillingStreet1, ccPaymentInfo.BillingStreet2, ccPaymentInfo.BillingCity, ccPaymentInfo.BillingState, ccPaymentInfo.BillingPostalCode, ccPaymentInfo.BillingCountry);

                if (NameOnCard.IsNullOrWhiteSpace() && NameOnCard.IsNotNullOrWhiteSpace())
                {
                    NameOnCardEncrypted = Encryption.EncryptString(nameOnCard);
                }

                if (!ExpirationMonth.HasValue)
                {
                    ExpirationMonthEncrypted = Encryption.EncryptString(ccPaymentInfo.ExpirationDate.Month.ToString());
                }

                if (!ExpirationYear.HasValue)
                {
                    ExpirationYearEncrypted = Encryption.EncryptString(ccPaymentInfo.ExpirationDate.Year.ToString());
                }

                if (!BillingLocationId.HasValue && newLocation != null)
                {
                    BillingLocationId = newLocation.Id;
                }
            }
            else if (paymentInfo is SwipePaymentInfo)
            {
                var swipePaymentInfo = ( SwipePaymentInfo )paymentInfo;

                if (NameOnCard.IsNullOrWhiteSpace() && NameOnCard.IsNotNullOrWhiteSpace())
                {
                    NameOnCardEncrypted = Encryption.EncryptString(swipePaymentInfo.NameOnCard);
                }

                if (!ExpirationMonth.HasValue)
                {
                    ExpirationMonthEncrypted = Encryption.EncryptString(swipePaymentInfo.ExpirationDate.Month.ToString());
                }

                if (!ExpirationYear.HasValue)
                {
                    ExpirationYearEncrypted = Encryption.EncryptString(swipePaymentInfo.ExpirationDate.Year.ToString());
                }
            }
            else
            {
                var newLocation = new LocationService(rockContext).Get(
                    paymentInfo.Street1, paymentInfo.Street2, paymentInfo.City, paymentInfo.State, paymentInfo.PostalCode, paymentInfo.Country);

                if (!BillingLocationId.HasValue && newLocation != null)
                {
                    BillingLocationId = newLocation.Id;
                }
            }
        }
Example #19
0
        /// <summary>
        /// Returns the first <see cref="Rock.Model.Location" /> where the address matches the provided address, otherwise the address will be saved as a new location.
        /// Note: if <paramref name="street1"/> is blank, null will be returned.
        /// </summary>
        /// <param name="street1">A <see cref="string" /> representing the Address Line 1 to search by.</param>
        /// <param name="street2">A <see cref="string" /> representing the Address Line 2 to search by.</param>
        /// <param name="city">A <see cref="string" /> representing the City to search by.</param>
        /// <param name="state">A <see cref="string" /> representing the State to search by.</param>
        /// <param name="postalCode">A <see cref="string" /> representing the Zip/Postal code to search by</param>
        /// <param name="country">A <see cref="string" /> representing the Country to search by</param>
        /// <param name="group">The <see cref="Group"/> (usually a Family) that should be searched first</param>
        /// <param name="verifyLocation">if set to <c>true</c> [verify location].</param>
        /// <param name="createNewLocation">if set to <c>true</c> a new location will be created if it does not exists.</param>
        /// <returns>
        /// The first <see cref="Rock.Model.Location" /> where an address match is found, if no match is found a new <see cref="Rock.Model.Location" /> is created and returned.
        /// </returns>
        public Location Get(string street1, string street2, string city, string state, string postalCode, string country, Group group, bool verifyLocation = true, bool createNewLocation = true)
        {
            // Make sure it's not an empty address
            if (string.IsNullOrWhiteSpace(street1))
            {
                return(null);
            }

            // Try to find a location that matches the values, this is not a case sensitive match
            var foundLocation = Search(new Location {
                Street1 = street1, Street2 = street2, City = city, State = state, PostalCode = postalCode, Country = country
            }, group);

            if (foundLocation != null)
            {
                // Check for casing
                if (!String.Equals(street1, foundLocation.Street1) || !String.Equals(street2, foundLocation.Street2) || !String.Equals(city, foundLocation.City) || !String.Equals(state, foundLocation.State) || !String.Equals(postalCode, foundLocation.PostalCode) || !String.Equals(country, foundLocation.Country))
                {
                    var context  = new RockContext();
                    var location = new LocationService(context).Get(foundLocation.Id);
                    location.Street1    = street1;
                    location.Street2    = street2;
                    location.City       = city;
                    location.State      = state;
                    location.PostalCode = postalCode;
                    location.Country    = country;
                    context.SaveChanges();
                    return(Get(location.Guid));
                }
                return(foundLocation);
            }

            // If existing location wasn't found with entered values, try standardizing the values, and search for an existing value again
            var newLocation = new Location
            {
                Street1    = street1.FixCase(),
                Street2    = street2.FixCase(),
                City       = city.FixCase(),
                State      = state,
                PostalCode = postalCode,
                Country    = country
            };

            if (verifyLocation)
            {
                Verify(newLocation, false);
            }

            foundLocation = Search(newLocation, group);
            if (foundLocation != null)
            {
                return(foundLocation);
            }

            if (createNewLocation)
            {
                // Create a new context/service so that save does not affect calling method's context
                var rockContext     = new RockContext();
                var locationService = new LocationService(rockContext);
                locationService.Add(newLocation);
                rockContext.SaveChanges();
            }

            // refetch it from the database to make sure we get a valid .Id
            return(Get(newLocation.Guid));
        }
Example #20
0
        /// <summary>
        /// Returns the first
        /// <see cref="Rock.Model.Location" /> where the address matches the provided address.  If no address is found with the provided values,
        /// the address will be standardized. If there is still not a match, the address will be saved as a new location.
        /// </summary>
        /// <param name="street1">A <see cref="System.String" /> representing the Address Line 1 to search by.</param>
        /// <param name="street2">A <see cref="System.String" /> representing the Address Line 2 to search by.</param>
        /// <param name="city">A <see cref="System.String" /> representing the City to search by.</param>
        /// <param name="state">A <see cref="System.String" /> representing the State to search by.</param>
        /// <param name="postalCode">A <see cref="System.String" /> representing the Zip/Postal code to search by</param>
        /// <param name="country">The country.</param>
        /// <param name="verifyLocation">if set to <c>true</c> [verify location].</param>
        /// <returns>
        /// The first <see cref="Rock.Model.Location" /> where an address match is found, if no match is found a new <see cref="Rock.Model.Location" /> is created and returned.
        /// </returns>
        public Location Get(string street1, string street2, string city, string state, string postalCode, string country, bool verifyLocation = true)
        {
            // Make sure it's not an empty address
            if (string.IsNullOrWhiteSpace(street1))
            {
                return(null);
            }

            // First check if a location exists with the entered values
            Location existingLocation = Queryable().FirstOrDefault(t =>
                                                                   (t.Street1 == street1 || ((street1 == null || street1 == "") && (t.Street1 == null || t.Street1 == ""))) &&
                                                                   (t.Street2 == street2 || ((street2 == null || street2 == "") && (t.Street2 == null || t.Street2 == ""))) &&
                                                                   (t.City == city || ((city == null || city == "") && (t.City == null || t.City == ""))) &&
                                                                   (t.State == state || ((state == null || state == "") && (t.State == null || t.State == ""))) &&
                                                                   (t.PostalCode == postalCode || ((postalCode == null || postalCode == "") && (t.PostalCode == null || t.PostalCode == ""))) &&
                                                                   (t.Country == country || ((country == null || country == "") && (t.Country == null || t.Country == ""))));

            if (existingLocation != null)
            {
                return(existingLocation);
            }

            // If existing location wasn't found with entered values, try standardizing the values, and
            // search for an existing value again
            var newLocation = new Location
            {
                Street1    = street1.FixCase(),
                Street2    = street2.FixCase(),
                City       = city.FixCase(),
                State      = state,
                PostalCode = postalCode,
                Country    = country
            };

            if (verifyLocation)
            {
                Verify(newLocation, false);
            }

            existingLocation = Queryable().FirstOrDefault(t =>
                                                          (t.Street1 == newLocation.Street1 || ((newLocation.Street1 == null || newLocation.Street1 == "") && (t.Street1 == null || t.Street1 == ""))) &&
                                                          (t.Street2 == newLocation.Street2 || ((newLocation.Street2 == null || newLocation.Street2 == "") && (t.Street2 == null || t.Street2 == ""))) &&
                                                          (t.City == newLocation.City || ((newLocation.City == null || newLocation.City == "") && (t.City == null || t.City == ""))) &&
                                                          (t.State == newLocation.State || ((newLocation.State == null || newLocation.State == "") && (t.State == null || t.State == ""))) &&
                                                          (t.PostalCode == newLocation.PostalCode || ((newLocation.PostalCode == null || newLocation.PostalCode == "") && (t.PostalCode == null || t.PostalCode == ""))) &&
                                                          (t.Country == newLocation.Country || ((newLocation.Country == null || newLocation.Country == "") && (t.Country == null || t.Country == ""))));

            if (existingLocation != null)
            {
                return(existingLocation);
            }

            // Create a new context/service so that save does not affect calling method's context
            var rockContext     = new RockContext();
            var locationService = new LocationService(rockContext);

            locationService.Add(newLocation);
            rockContext.SaveChanges();

            // refetch it from the database to make sure we get a valid .Id
            return(Get(newLocation.Guid));
        }
Example #21
0
        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.Get(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);

                    if (!string.IsNullOrWhiteSpace(groupSchedule.iCalendarContent))
                    {
                        // If schedule has an iCal schedule, get all the past occurrences
                        foreach (var occurrence in groupSchedule.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.Get(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 #22
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();
            }
        }
 /// <summary>
 /// Handles the Click event of the btnCancel 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 btnCancel_Click( object sender, EventArgs e )
 {
     if ( hfLocationId.Value.Equals( "0" ) )
     {
         int? parentLocationId = PageParameter( "ParentLocationId" ).AsIntegerOrNull();
         if ( parentLocationId.HasValue )
         {
             // Cancelling on Add, and we know the parentLocationId, so we are probably in treeview mode, so navigate to the current page
             var qryParams = new Dictionary<string, string>();
             qryParams["LocationId"] = parentLocationId.ToString();
             qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" );
             NavigateToPage( RockPage.Guid, qryParams );
         }
         else
         {
             // Cancelling on Add.  Return to Grid
             NavigateToParentPage();
         }
     }
     else
     {
         // Cancelling on Edit.  Return to Details
         LocationService locationService = new LocationService( new RockContext() );
         Location location = locationService.Get( int.Parse( hfLocationId.Value ) );
         ShowReadonlyDetails( location );
     }
 }
Example #24
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="DeviceId">The device identifier.</param>
        public void ShowDetail( int DeviceId )
        {
            pnlDetails.Visible = true;
            Device Device = null;

            var rockContext = new RockContext();

            if ( !DeviceId.Equals( 0 ) )
            {
                Device = new DeviceService( rockContext ).Get( DeviceId );
                lActionTitle.Text = ActionTitle.Edit( Device.FriendlyTypeName ).FormatAsHtmlTitle();
                pdAuditDetails.SetEntity( Device, ResolveRockUrl( "~" ) );
            }

            if ( Device == null )
            {
                Device = new Device { Id = 0 };
                lActionTitle.Text = ActionTitle.Add( Device.FriendlyTypeName ).FormatAsHtmlTitle();
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            LoadDropDowns();

            hfDeviceId.Value = Device.Id.ToString();

            tbName.Text = Device.Name;
            tbDescription.Text = Device.Description;
            tbIpAddress.Text = Device.IPAddress;
            ddlDeviceType.SetValue( Device.DeviceTypeValueId );
            ddlPrintTo.SetValue( Device.PrintToOverride.ConvertToInt().ToString() );
            ddlPrinter.SetValue( Device.PrinterDeviceId );
            ddlPrintFrom.SetValue( Device.PrintFrom.ConvertToInt().ToString() );

            SetPrinterVisibility();
            SetPrinterSettingsVisibility();

            string orgLocGuid = GlobalAttributesCache.Read().GetValue( "OrganizationAddress" );
            if ( !string.IsNullOrWhiteSpace( orgLocGuid ) )
            {
                Guid locGuid = Guid.Empty;
                if ( Guid.TryParse( orgLocGuid, out locGuid ) )
                {
                    var location = new LocationService( rockContext ).Get( locGuid );
                    if ( location != null )
                    {
                        geopPoint.CenterPoint = location.GeoPoint;
                        geopFence.CenterPoint = location.GeoPoint;
                    }
                }
            }

            if ( Device.Location != null )
            {
                geopPoint.SetValue( Device.Location.GeoPoint );
                geopFence.SetValue( Device.Location.GeoFence );
            }

            Locations = new Dictionary<int,string>();
            foreach ( var location in Device.Locations)
            {
                string path = location.Name;
                var parentLocation = location.ParentLocation;
                while ( parentLocation != null )
                {
                    path = parentLocation.Name + " > " + path;
                    parentLocation = parentLocation.ParentLocation;
                }
                Locations.Add( location.Id, path );
            }
            BindLocations();

            Guid mapStyleValueGuid = GetAttributeValue( "MapStyle" ).AsGuid();
            geopPoint.MapStyleValueGuid = mapStyleValueGuid;
            geopFence.MapStyleValueGuid = mapStyleValueGuid;

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !IsUserAuthorized( Authorization.EDIT ) )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Device.FriendlyTypeName );
            }

            if ( readOnly )
            {
                lActionTitle.Text = ActionTitle.View( Device.FriendlyTypeName );
                btnCancel.Text = "Close";
            }

            tbName.ReadOnly = readOnly;
            tbDescription.ReadOnly = readOnly;
            tbIpAddress.ReadOnly = readOnly;
            ddlDeviceType.Enabled = !readOnly;
            ddlPrintTo.Enabled = !readOnly;
            ddlPrinter.Enabled = !readOnly;
            ddlPrintFrom.Enabled = !readOnly;

            btnSave.Visible = !readOnly;
        }
 /// <summary>
 /// Handles the Click event of the btnEdit 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 btnEdit_Click( object sender, EventArgs e )
 {
     LocationService locationService = new LocationService( new RockContext() );
     Location location = locationService.Get( int.Parse( hfLocationId.Value ) );
     ShowEditDetails( location );
 }
        /// <summary>
        /// Returns the first <see cref="Rock.Model.Location"/> where the address matches the provided address.  If no address is found with the provided values, 
        /// the address will be standardized. If there is still not a match, the address will be saved as a new location.
        /// </summary>
        /// <param name="street1">A <see cref="System.String"/> representing the Address Line 1 to search by.</param>
        /// <param name="street2">A <see cref="System.String"/> representing the Address Line 2 to search by.</param>
        /// <param name="city">A <see cref="System.String"/> representing the City to search by.</param>
        /// <param name="state">A <see cref="System.String"/> representing the State to search by.</param>
        /// <param name="zip">A <see cref="System.String"/> representing the Zip/Postal code to search by</param>
        /// <returns>The first <see cref="Rock.Model.Location"/> where an address match is found, if no match is found a new <see cref="Rock.Model.Location"/> is created and returned.</returns>
        public Location Get( string street1, string street2, string city, string state, string zip )
        {
            // Make sure it's not an empty address
            if ( string.IsNullOrWhiteSpace( street1 ) &&
                string.IsNullOrWhiteSpace( street2 ) &&
                string.IsNullOrWhiteSpace( city ) &&
                string.IsNullOrWhiteSpace( state ) &&
                string.IsNullOrWhiteSpace( zip ) )
            {
                return null;
            }

            // First check if a location exists with the entered values
            Location existingLocation = Queryable().FirstOrDefault( t =>
                ( t.Street1 == street1 || ( street1 == null && t.Street1 == null ) ) &&
                ( t.Street2 == street2 || ( street2 == null && t.Street2 == null ) ) &&
                ( t.City == city || ( city == null && t.City == null ) ) &&
                ( t.State == state || ( state == null && t.State == null ) ) &&
                ( t.Zip == zip || ( zip == null && t.Zip == null ) ) );
            if ( existingLocation != null )
            {
                return existingLocation;
            }

            // If existing location wasn't found with entered values, try standardizing the values, and 
            // search for an existing value again
            var newLocation = new Location
            {
                Street1 = street1,
                Street2 = street2,
                City = city,
                State = state,
                Zip = zip
            };

            Verify( newLocation, false );

            existingLocation = Queryable().FirstOrDefault( t =>
                ( t.Street1 == newLocation.Street1 || ( newLocation.Street1 == null && t.Street1 == null ) ) &&
                ( t.Street2 == newLocation.Street2 || ( newLocation.Street2 == null && t.Street2 == null ) ) &&
                ( t.City == newLocation.City || ( newLocation.City == null && t.City == null ) ) &&
                ( t.State == newLocation.State || ( newLocation.State == null && t.State == null ) ) &&
                ( t.Zip == newLocation.Zip || ( newLocation.Zip == null && t.Zip == null ) ) );

            if ( existingLocation != null )
            {
                return existingLocation;
            }

            // Create a new context/service so that save does not affect calling method's context
            var rockContext = new RockContext();
            var locationService = new LocationService( rockContext );
            locationService.Add( newLocation );
            rockContext.SaveChanges();

            // refetch it from the database to make sure we get a valid .Id
            return Get(newLocation.Guid);
        }
        /// <summary>
        /// Handles the Click event of the btnStandardize 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 btnStandardize_Click( object sender, EventArgs e )
        {
            int locationId = hfLocationId.Value.AsInteger();

            var rockContext = new RockContext();
            var service = new LocationService( rockContext );
            var location = service.Get( locationId );
            if (location == null)
            {
                // if they are adding a new named location, there won't be a location record yet, so just make a new one for the verification
                location = new Location();
            }

            acAddress.GetValues( location );

            service.Verify( location, true );

            acAddress.SetValues( location );
            geopPoint.SetValue( location.GeoPoint );

            lStandardizationUpdate.Text = String.Format( "<div class='alert alert-info'>Standardization Result: {0}<br/>Geocoding Result: {1}</div>",
                location.StandardizeAttemptedResult.IfEmpty( "No Result" ),
                location.GeocodeAttemptedResult.IfEmpty( "No Result" ) );
        }
Example #28
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 #29
0
        /// <summary>
        /// Sets from payment information.
        /// </summary>
        /// <param name="paymentInfo">The payment information.</param>
        /// <param name="paymentGateway">The payment gateway.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="changes">The changes.</param>
        public void SetFromPaymentInfo(PaymentInfo paymentInfo, GatewayComponent paymentGateway, RockContext rockContext, List <string> changes = null)
        {
            if (changes != null)
            {
                if (!string.IsNullOrWhiteSpace(paymentInfo.MaskedNumber))
                {
                    History.EvaluateChange(changes, "Account Number", AccountNumberMasked, paymentInfo.MaskedNumber);
                }

                if (paymentInfo.CurrencyTypeValue != null)
                {
                    History.EvaluateChange(changes, "Currency Type", DefinedValueCache.GetName(CurrencyTypeValueId), paymentInfo.CurrencyTypeValue.Value);
                }

                if (paymentInfo.CreditCardTypeValue != null)
                {
                    History.EvaluateChange(changes, "Credit Card Type", DefinedValueCache.GetName(CreditCardTypeValueId), paymentInfo.CreditCardTypeValue.Value);
                }
            }

            if (!string.IsNullOrWhiteSpace(paymentInfo.MaskedNumber))
            {
                AccountNumberMasked = paymentInfo.MaskedNumber;
            }

            if (paymentInfo.CurrencyTypeValue != null)
            {
                CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;
            }

            if (paymentInfo.CreditCardTypeValue != null)
            {
                CreditCardTypeValueId = paymentInfo.CreditCardTypeValue.Id;
            }

            if (paymentInfo is CreditCardPaymentInfo)
            {
                var ccPaymentInfo = (CreditCardPaymentInfo)paymentInfo;

                string nameOnCard  = paymentGateway.SplitNameOnCard ? ccPaymentInfo.NameOnCard + " " + ccPaymentInfo.LastNameOnCard : ccPaymentInfo.NameOnCard;
                var    newLocation = new LocationService(rockContext).Get(
                    ccPaymentInfo.BillingStreet1, ccPaymentInfo.BillingStreet2, ccPaymentInfo.BillingCity, ccPaymentInfo.BillingState, ccPaymentInfo.BillingPostalCode, ccPaymentInfo.BillingCountry);

                if (changes != null)
                {
                    string oldNameOnCard = Encryption.DecryptString(NameOnCardEncrypted);
                    History.EvaluateChange(changes, "Name on Card", oldNameOnCard, nameOnCard);
                    History.EvaluateChange(changes, "Expiration Month", Encryption.DecryptString(ExpirationMonthEncrypted), ccPaymentInfo.ExpirationDate.Month.ToString());
                    History.EvaluateChange(changes, "Expiration Year", Encryption.DecryptString(ExpirationYearEncrypted), ccPaymentInfo.ExpirationDate.Year.ToString());
                    History.EvaluateChange(changes, "Billing Location", BillingLocation != null ? BillingLocation.ToString() : string.Empty, newLocation != null ? newLocation.ToString() : string.Empty);
                }

                NameOnCardEncrypted      = Encryption.EncryptString(nameOnCard);
                ExpirationMonthEncrypted = Encryption.EncryptString(ccPaymentInfo.ExpirationDate.Month.ToString());
                ExpirationYearEncrypted  = Encryption.EncryptString(ccPaymentInfo.ExpirationDate.Year.ToString());
                BillingLocationId        = newLocation != null ? newLocation.Id : (int?)null;
            }
            else if (paymentInfo is SwipePaymentInfo)
            {
                var swipePaymentInfo = (SwipePaymentInfo)paymentInfo;

                if (changes != null)
                {
                    string oldNameOnCard = Encryption.DecryptString(NameOnCardEncrypted);
                    History.EvaluateChange(changes, "Name on Card", oldNameOnCard, swipePaymentInfo.NameOnCard);
                    History.EvaluateChange(changes, "Expiration Month", Encryption.DecryptString(ExpirationMonthEncrypted), swipePaymentInfo.ExpirationDate.Month.ToString());
                    History.EvaluateChange(changes, "Expiration Year", Encryption.DecryptString(ExpirationYearEncrypted), swipePaymentInfo.ExpirationDate.Year.ToString());
                }

                NameOnCardEncrypted      = Encryption.EncryptString(swipePaymentInfo.NameOnCard);
                ExpirationMonthEncrypted = Encryption.EncryptString(swipePaymentInfo.ExpirationDate.Month.ToString());
                ExpirationYearEncrypted  = Encryption.EncryptString(swipePaymentInfo.ExpirationDate.Year.ToString());
            }
        }
Example #30
0
 /// <summary>
 /// Handles the Click event of the _btnSelect 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 _btnSelect_Click( object sender, EventArgs e )
 {
     LocationService locationService = new LocationService( new RockContext() );
     var location = locationService.Get( _acAddress.Street1, _acAddress.Street2, _acAddress.City, _acAddress.State, _acAddress.PostalCode, _acAddress.Country );
     Location = location;
     _btnPickerLabel.InnerHtml = string.Format( "<i class='fa fa-user'></i>{0}<b class='fa fa-caret-down pull-right'></b>", this.AddressSummaryText );
     ShowDropDown = false;
 }
Example #31
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 )
        {
            Location location = null;

            var rockContext = new RockContext();
            LocationService locationService = new LocationService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext );

            int locationId = int.Parse( hfLocationId.Value );

            if ( locationId != 0 )
            {
                location = locationService.Get( locationId );
                FlushCampus( locationId );
            }

            if ( location == null )
            {
                location = new Location();
                location.Name = string.Empty;
            }

            string previousName = location.Name;

            int? orphanedImageId = null;
            if ( location.ImageId != imgImage.BinaryFileId )
            {
                orphanedImageId = location.ImageId;
                location.ImageId = imgImage.BinaryFileId;
            }

            location.Name = tbName.Text;
            location.IsActive = cbIsActive.Checked;
            location.LocationTypeValueId = ddlLocationType.SelectedValueAsId();
            if ( gpParentLocation != null && gpParentLocation.Location != null )
            {
                location.ParentLocationId = gpParentLocation.Location.Id;
            }
            else
            {
                location.ParentLocationId = null;
            }

            location.PrinterDeviceId = ddlPrinter.SelectedValueAsInt();

            acAddress.GetValues(location);

            location.GeoPoint = geopPoint.SelectedValue;
            if ( geopPoint.SelectedValue != null )
            {
                location.IsGeoPointLocked = true;
            }
            location.GeoFence = geopFence.SelectedValue;

            location.IsGeoPointLocked = cbGeoPointLocked.Checked;

            location.SoftRoomThreshold = nbSoftThreshold.Text.AsIntegerOrNull();
            location.FirmRoomThreshold = nbFirmThreshold.Text.AsIntegerOrNull();

            location.LoadAttributes( rockContext );
            Rock.Attribute.Helper.GetEditValues( phAttributeEdits, location );

            if ( !Page.IsValid )
            {
                return;
            }

            // if the location IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of location didn't pass.
            // So, make sure a message is displayed in the validation summary
            cvLocation.IsValid = location.IsValid;

            if ( !cvLocation.IsValid )
            {
                cvLocation.ErrorMessage = location.ValidationResults.Select( a => a.ErrorMessage ).ToList().AsDelimited( "<br />" );
                return;
            }

            rockContext.WrapTransaction( () =>
            {
                if ( location.Id.Equals( 0 ) )
                {
                    locationService.Add( location );
                }
                rockContext.SaveChanges();

                if (orphanedImageId.HasValue)
                {
                    BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                    var binaryFile = binaryFileService.Get( orphanedImageId.Value );
                    if ( binaryFile != null )
                    {
                        // marked the old images as IsTemporary so they will get cleaned up later
                        binaryFile.IsTemporary = true;
                        rockContext.SaveChanges();
                    }
                }

                location.SaveAttributeValues( rockContext );

            } );

            // If this is a names location (or was previouisly)
            if ( !string.IsNullOrWhiteSpace( location.Name ) || ( previousName ?? string.Empty ) != (location.Name ?? string.Empty ) )
            {
                // flush the checkin config
                Rock.CheckIn.KioskDevice.FlushAll();
            }

            if ( _personId.HasValue )
            {
                NavigateToParentPage( new Dictionary<string, string> { { "PersonId", _personId.Value.ToString() } } );
            }
            else
            {
                Rock.CheckIn.KioskDevice.FlushAll();

                var qryParams = new Dictionary<string, string>();
                qryParams["LocationId"] = location.Id.ToString();
                qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" );

                NavigateToPage( RockPage.Guid, qryParams );
            }
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="locationId">The location identifier.</param>
        /// <param name="parentLocationId">The parent location identifier.</param>
        public void ShowDetail( int locationId, int? parentLocationId )
        {
            pnlDetails.Visible = false;

            bool editAllowed = true;

            Location location = null;

            if ( !locationId.Equals( 0 ) )
            {
                location = new LocationService( new RockContext() ).Get( locationId );
            }

            if ( location == null )
            {
                location = new Location { Id = 0, IsActive = true, ParentLocationId = parentLocationId };
            }

            editAllowed = location.IsAuthorized( Authorization.EDIT, CurrentPerson );

            pnlDetails.Visible = true;
            hfLocationId.Value = location.Id.ToString();

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !editAllowed || !IsUserAuthorized( Authorization.EDIT ) )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Location.FriendlyTypeName );
            }

            if ( readOnly )
            {
                btnEdit.Visible = false;
                btnDelete.Visible = false;
                ShowReadonlyDetails( location );
            }
            else
            {
                btnEdit.Visible = true;
                btnDelete.Visible = true;
                if ( location.Id > 0 )
                {
                    ShowReadonlyDetails( location );
                }
                else
                {
                    ShowEditDetails( location );
                }
            }
        }
Example #33
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            _personId = PageParameter( "PersonId" ).AsIntegerOrNull();

            if ( !Page.IsPostBack )
            {
                string locationId = PageParameter( "LocationId" );

                if ( !string.IsNullOrWhiteSpace( locationId ) )
                {
                    ShowDetail( locationId.AsInteger(), PageParameter( "ParentLocationId" ).AsIntegerOrNull() );
                }
                else
                {
                    pnlDetails.Visible = false;
                }
            }
            else
            {
                // Rebuild the attribute controls on postback based on group type
                if ( pnlDetails.Visible )
                {
                    int? locationId = PageParameter( "LocationId" ).AsIntegerOrNull();
                    if ( locationId.HasValue && locationId.Value > 0 )
                    {
                        var location = new LocationService(new RockContext()).Get( locationId.Value );
                        if ( location != null )
                        {
                            location.LoadAttributes();
                            BuildAttributeEdits( location, true );
                        }
                    }

                }
            }
        }
        /// <summary>
        /// Handles the Click event of the btnDelete 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 btnDelete_Click( object sender, EventArgs e )
        {
            int? parentLocationId = null;

            var rockContext = new RockContext();
            LocationService locationService = new LocationService( rockContext );
            Location location = locationService.Get( hfLocationId.Value.AsInteger() );

            if ( location != null )
            {
                parentLocationId = location.ParentLocationId;
                string errorMessage;
                if ( !locationService.CanDelete( location, out errorMessage ) )
                {
                    mdDeleteWarning.Show( errorMessage, ModalAlertType.Information );
                    return;
                }

                FlushCampus( location.Id );

                locationService.Delete( location );
                rockContext.SaveChanges();
            }

            // reload page, selecting the deleted location's parent
            var qryParams = new Dictionary<string, string>();
            if ( parentLocationId != null )
            {
                qryParams["LocationId"] = parentLocationId.ToString();
            }

            qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" );

            NavigateToPage( RockPage.Guid, qryParams );
        }
Example #35
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;
        }
        /// <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 )
        {
            Location location;

            var rockContext = new RockContext();
            LocationService locationService = new LocationService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext );

            int locationId = int.Parse( hfLocationId.Value );

            if ( locationId == 0 )
            {
                location = new Location();
                location.Name = string.Empty;
            }
            else
            {
                location = locationService.Get( locationId );
                FlushCampus( locationId );
            }

            int? orphanedImageId = null;
            if ( location.ImageId != imgImage.BinaryFileId )
            {
                orphanedImageId = location.ImageId;
                location.ImageId = imgImage.BinaryFileId;
            }

            location.Name = tbName.Text;
            location.IsActive = cbIsActive.Checked;
            location.LocationTypeValueId = ddlLocationType.SelectedValueAsId();
            if ( gpParentLocation != null && gpParentLocation.Location != null )
            {
                location.ParentLocationId = gpParentLocation.Location.Id;
            }
            else
            {
                location.ParentLocationId = null;
            }

            location.PrinterDeviceId = ddlPrinter.SelectedValueAsInt();

            acAddress.GetValues(location);

            location.GeoPoint = geopPoint.SelectedValue;
            if ( geopPoint.SelectedValue != null )
            {
                location.IsGeoPointLocked = true;
            }
            location.GeoFence = geopFence.SelectedValue;

            location.IsGeoPointLocked = cbGeoPointLocked.Checked;

            location.LoadAttributes( rockContext );
            Rock.Attribute.Helper.GetEditValues( phAttributeEdits, location );

            if ( !Page.IsValid )
            {
                return;
            }

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

            rockContext.WrapTransaction( () =>
            {
                if ( location.Id.Equals( 0 ) )
                {
                    locationService.Add( location );
                }
                rockContext.SaveChanges();

                if (orphanedImageId.HasValue)
                {
                    BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                    var binaryFile = binaryFileService.Get( orphanedImageId.Value );
                    if ( binaryFile != null )
                    {
                        // marked the old images as IsTemporary so they will get cleaned up later
                        binaryFile.IsTemporary = true;
                        rockContext.SaveChanges();
                    }
                }

                location.SaveAttributeValues( rockContext );

            } );

            var qryParams = new Dictionary<string, string>();
            qryParams["LocationId"] = location.Id.ToString();
            qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" );

            NavigateToPage( RockPage.Guid, qryParams );
        }
        /// <summary>
        /// Handles the Click event of the lbSave 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 lbSave_Click( object sender, EventArgs e )
        {
            if ( _group != null && _occurrence != null )
            {
                var rockContext = new RockContext();
                var attendanceService = new AttendanceService( rockContext );
                var personAliasService = new PersonAliasService( rockContext );
                var locationService = new LocationService( rockContext );

                bool dateAdjusted = false;

                DateTime startDate = _occurrence.Date;

                // If this is a manuall entered occurrence, check to see if date was changed
                if ( !_occurrence.ScheduleId.HasValue )
                {
                    DateTime? originalDate = PageParameter( "Date" ).AsDateTime();
                    if ( originalDate.HasValue && originalDate.Value.Date != startDate.Date )
                    {
                        startDate = originalDate.Value.Date;
                        dateAdjusted = true;
                    }
                }
                DateTime endDate = startDate.AddDays( 1 );

                var existingAttendees = attendanceService
                    .Queryable( "PersonAlias" )
                    .Where( a =>
                        a.GroupId == _group.Id &&
                        a.LocationId == _occurrence.LocationId &&
                        a.ScheduleId == _occurrence.ScheduleId &&
                        a.StartDateTime >= startDate &&
                        a.StartDateTime < endDate );

                if ( dateAdjusted )
                {
                    foreach ( var attendee in existingAttendees )
                    {
                        attendee.StartDateTime = _occurrence.Date;
                    }
                }

                // If did not meet was selected and this was a manually entered occurrence (not based on a schedule/location)
                // then just delete all the attendance records instead of tracking a 'did not meet' value
                if ( cbDidNotMeet.Checked && !_occurrence.ScheduleId.HasValue )
                {
                    foreach ( var attendance in existingAttendees )
                    {
                        attendanceService.Delete( attendance );
                    }
                }
                else
                {
                    int? campusId = locationService.GetCampusIdForLocation( _occurrence.LocationId );
                    if ( !campusId.HasValue )
                    {
                        campusId = _group.CampusId;
                    }
                    if ( !campusId.HasValue && _allowCampusFilter )
                    {
                        var campus = CampusCache.Read( bddlCampus.SelectedValueAsInt() ?? 0 );
                        if ( campus != null )
                        {
                            campusId = campus.Id;
                        }
                    }

                    if ( cbDidNotMeet.Checked )
                    {
                        // If the occurrence is based on a schedule, set the did not meet flags
                        foreach ( var attendance in existingAttendees )
                        {
                            attendance.DidAttend = null;
                            attendance.DidNotOccur = true;
                        }
                    }

                    foreach ( var attendee in _attendees )
                    {
                        var attendance = existingAttendees
                            .Where( a => a.PersonAlias.PersonId == attendee.PersonId )
                            .FirstOrDefault();

                        if ( attendance == null )
                        {
                            int? personAliasId = personAliasService.GetPrimaryAliasId( attendee.PersonId );
                            if ( personAliasId.HasValue )
                            {
                                attendance = new Attendance();
                                attendance.GroupId = _group.Id;
                                attendance.ScheduleId = _group.ScheduleId;
                                attendance.PersonAliasId = personAliasId;
                                attendance.StartDateTime = _occurrence.Date.Date.Add( _occurrence.StartTime );
                                attendance.LocationId = _occurrence.LocationId;
                                attendance.CampusId = campusId;
                                attendance.ScheduleId = _occurrence.ScheduleId;

                                // check that the attendance record is valid
                                cvAttendance.IsValid = attendance.IsValid;
                                if ( !cvAttendance.IsValid )
                                {
                                    cvAttendance.ErrorMessage = attendance.ValidationResults.Select( a => a.ErrorMessage ).ToList().AsDelimited( "<br />" );
                                    return;
                                }

                                attendanceService.Add( attendance );
                            }
                        }

                        if ( attendance != null )
                        {
                            if ( cbDidNotMeet.Checked )
                            {
                                attendance.DidAttend = null;
                                attendance.DidNotOccur = true;
                            }
                            else
                            {
                                attendance.DidAttend = attendee.Attended;
                                attendance.DidNotOccur = null;
                            }
                        }
                    }
                }

                if ( _occurrence.LocationId.HasValue )
                {
                    Rock.CheckIn.KioskLocationAttendance.Flush( _occurrence.LocationId.Value );
                }

                rockContext.SaveChanges();

                WorkflowType workflowType = null;
                Guid? workflowTypeGuid = GetAttributeValue( "Workflow" ).AsGuidOrNull();
                if ( workflowTypeGuid.HasValue )
                {
                    var workflowTypeService = new WorkflowTypeService( rockContext );
                    workflowType = workflowTypeService.Get( workflowTypeGuid.Value );
                    if ( workflowType != null )
                    {
                        try
                        {
                            var workflow = Workflow.Activate( workflowType, _group.Name );

                            workflow.SetAttributeValue( "StartDateTime", _occurrence.Date.ToString( "o" ) );
                            workflow.SetAttributeValue( "Schedule", _group.Schedule.Guid.ToString() );

                            List<string> workflowErrors;
                            new WorkflowService( rockContext ).Process( workflow, _group, out workflowErrors );
                        }
                        catch ( Exception ex )
                        {
                            ExceptionLogService.LogException( ex, this.Context );
                        }
                    }
                }

                var qryParams = new Dictionary<string, string> { { "GroupId", _group.Id.ToString() } };

                var groupTypeIds = PageParameter( "GroupTypeIds" );
                if ( !string.IsNullOrWhiteSpace( groupTypeIds ) )
                {
                    qryParams.Add( "GroupTypeIds", groupTypeIds );
                }

                NavigateToParentPage( qryParams );
            }
        }
        /// <summary>
        /// Handles the SelectedIndexChanged event of the ddlLocationType 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 ddlLocationType_SelectedIndexChanged( object sender, EventArgs e )
        {
            var location = new LocationService( new RockContext() ).Get( hfLocationId.Value.AsInteger() );
            if ( location == null )
            {
                location = new Location();
            }
            location.LocationTypeValueId = ddlLocationType.SelectedValueAsId();

            location.LoadAttributes();
            BuildAttributeEdits( location, true );
        }
        /// <summary>
        /// Loads the dropdowns.
        /// </summary>
        private void BindLocations()
        {
            var locations = new Dictionary<int, string> { { 0, "" } };

            if ( _group != null )
            {
                var locationPaths = new Dictionary<int, string>();
                var locationService = new LocationService( _rockContext );

                foreach ( var location in _group.GroupLocations
                    .Where( l =>
                        l.Location.Name != null &&
                        l.Location.Name != "" )
                    .Select( l => l.Location ) )
                {
                    // Get location path
                    string parentLocationPath = string.Empty;
                    if ( location.ParentLocationId.HasValue )
                    {
                        var locId = location.ParentLocationId.Value;
                        if ( !locationPaths.ContainsKey( locId ) )
                        {
                            locationPaths.Add( locId, locationService.GetPath( locId ) );
                        }
                        parentLocationPath = locationPaths[locId];
                    }

                    if ( !locations.ContainsKey( location.Id ) )
                    {
                        locations.Add( location.Id, new List<string> { parentLocationPath, location.Name }.AsDelimited( " > " ) );
                    }
                }
            }

            if ( locations.Any() )
            {
                ddlLocation.DataSource = locations;
                ddlLocation.DataBind();
            }
        }
Example #40
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void ShowResults()
        {
            // Get the group types that we're interested in
            Guid? groupTypeGuid = GetAttributeValue( "GroupType" ).AsGuidOrNull();
            if ( !groupTypeGuid.HasValue )
            {
                ShowError( "A valid Group Type is required." );
                return;
            }

            gGroups.Columns[1].Visible = GetAttributeValue( "ShowDescription" ).AsBoolean();
            gGroups.Columns[2].Visible = GetAttributeValue( "ShowSchedule" ).AsBoolean();
            gGroups.Columns[3].Visible = GetAttributeValue( "ShowCount" ).AsBoolean();
            gGroups.Columns[4].Visible = GetAttributeValue( "ShowAge" ).AsBoolean();

            bool showProximity = GetAttributeValue( "ShowProximity" ).AsBoolean();
            gGroups.Columns[5].Visible = showProximity;  // Distance

            // Get query of groups of the selected group type
            var rockContext = new RockContext();
            var groupService = new GroupService( rockContext );
            var groupQry = groupService
                .Queryable( "GroupLocations.Location" )
                .Where( g => g.IsActive && g.GroupType.Guid.Equals( groupTypeGuid.Value ) && g.IsPublic );

            var groupParameterExpression = groupService.ParameterExpression;
            var schedulePropertyExpression = Expression.Property( groupParameterExpression, "Schedule" );

            var dowFilterControl = phFilterControls.FindControl( "filter_dow" );
            if ( dowFilterControl != null )
            {
                var field = FieldTypeCache.Read( Rock.SystemGuid.FieldType.DAY_OF_WEEK ).Field;

                var filterValues = field.GetFilterValues( dowFilterControl, null, Rock.Reporting.FilterMode.SimpleFilter );
                var expression = field.PropertyFilterExpression( null, filterValues, schedulePropertyExpression, "WeeklyDayOfWeek", typeof( DayOfWeek? ) );
                groupQry = groupQry.Where( groupParameterExpression, expression, null );
            }

            var timeFilterControl = phFilterControls.FindControl( "filter_time" );
            if ( timeFilterControl != null )
            {
                var field = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TIME ).Field;

                var filterValues = field.GetFilterValues( timeFilterControl, null, Rock.Reporting.FilterMode.SimpleFilter );
                var expression = field.PropertyFilterExpression( null, filterValues, schedulePropertyExpression, "WeeklyTimeOfDay", typeof( TimeSpan? ) );
                groupQry = groupQry.Where( groupParameterExpression, expression, null );
            }

            // Filter query by any configured attribute filters
            if ( AttributeFilters != null && AttributeFilters.Any() )
            {
                var attributeValueService = new AttributeValueService( rockContext );
                var parameterExpression = attributeValueService.ParameterExpression;

                foreach ( var attribute in AttributeFilters )
                {
                    var filterControl = phFilterControls.FindControl( "filter_" + attribute.Id.ToString() );
                    if ( filterControl != null )
                    {
                        var filterValues = attribute.FieldType.Field.GetFilterValues( filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter );
                        var expression = attribute.FieldType.Field.AttributeFilterExpression( attribute.QualifierValues, filterValues, parameterExpression );
                        if ( expression != null )
                        {
                            var attributeValues = attributeValueService
                                .Queryable()
                                .Where( v => v.Attribute.Id == attribute.Id );

                            attributeValues = attributeValues.Where( parameterExpression, expression, null );

                            groupQry = groupQry.Where( w => attributeValues.Select( v => v.EntityId ).Contains( w.Id ) );
                        }
                    }
                }
            }

            List<GroupLocation> fences = null;
            List<Group> groups = null;

            // Run query to get list of matching groups
            SortProperty sortProperty = gGroups.SortProperty;
            if ( sortProperty != null )
            {
                groups = groupQry.Sort( sortProperty ).ToList();
            }
            else
            {
                groups = groupQry.OrderBy( g => g.Name ).ToList();
            }

            int? fenceGroupTypeId = GetGroupTypeId( GetAttributeValue( "GeofencedGroupType" ).AsGuidOrNull() );
            bool showMap = GetAttributeValue( "ShowMap" ).AsBoolean();
            bool showFences = showMap && GetAttributeValue( "ShowFence" ).AsBoolean();

            var distances = new Dictionary<int, double>();

            // If we care where these groups are located...
            if ( fenceGroupTypeId.HasValue || showMap || showProximity )
            {
                // Get the location for the address entered
                Location personLocation = null;
                if ( fenceGroupTypeId.HasValue || showProximity )
                {
                    personLocation = new LocationService( rockContext )
                        .Get( acAddress.Street1, acAddress.Street2, acAddress.City,
                            acAddress.State, acAddress.PostalCode, acAddress.Country );
                }

                // If showing a map, and person's location was found, save a mapitem for this location
                FinderMapItem personMapItem = null;
                if ( showMap && personLocation != null && personLocation.GeoPoint != null )
                {
                    var infoWindow = string.Format( @"
            <div style='width:250px'>
            <div class='clearfix'>
            <strong>Your Location</strong>
            <br/>{0}
            </div>
            </div>
            ", personLocation.FormattedHtmlAddress );

                    personMapItem = new FinderMapItem( personLocation );
                    personMapItem.Name = "Your Location";
                    personMapItem.InfoWindow = HttpUtility.HtmlEncode( infoWindow.Replace( Environment.NewLine, string.Empty ).Replace( "\n", string.Empty ).Replace( "\t", string.Empty ) );
                }

                // Get the locations, and optionally calculate the distance for each of the groups
                var groupLocations = new List<GroupLocation>();
                foreach ( var group in groups )
                {
                    foreach ( var groupLocation in group.GroupLocations
                        .Where( gl => gl.Location.GeoPoint != null ) )
                    {
                        groupLocations.Add( groupLocation );

                        if ( showProximity && personLocation != null && personLocation.GeoPoint != null )
                        {
                            double meters = groupLocation.Location.GeoPoint.Distance( personLocation.GeoPoint ) ?? 0.0D;
                            double miles = meters * Location.MilesPerMeter;

                            // If this group already has a distance calculated, see if this location is closer and if so, use it instead
                            if ( distances.ContainsKey( group.Id ) )
                            {
                                if ( distances[group.Id] < miles )
                                {
                                    distances[group.Id] = miles;
                                }
                            }
                            else
                            {
                                distances.Add( group.Id, miles );
                            }
                        }
                    }
                }

                // If groups should be limited by a geofence
                var fenceMapItems = new List<MapItem>();
                if ( fenceGroupTypeId.HasValue )
                {
                    fences = new List<GroupLocation>();
                    if ( personLocation != null && personLocation.GeoPoint != null )
                    {
                        fences = new GroupLocationService( rockContext )
                            .Queryable( "Group,Location" )
                            .Where( gl =>
                                gl.Group.GroupTypeId == fenceGroupTypeId &&
                                gl.Location.GeoFence != null &&
                                personLocation.GeoPoint.Intersects( gl.Location.GeoFence ) )
                            .ToList();
                    }

                    // Limit the group locations to only those locations inside one of the fences
                    groupLocations = groupLocations
                        .Where( gl =>
                            fences.Any( f => gl.Location.GeoPoint.Intersects( f.Location.GeoFence ) ) )
                        .ToList();

                    // Limit the groups to the those that still contain a valid location
                    groups = groups
                        .Where( g =>
                            groupLocations.Any( gl => gl.GroupId == g.Id ) )
                        .ToList();

                    // If the map and fences should be displayed, create a map item for each fence
                    if ( showMap && showFences )
                    {
                        foreach ( var fence in fences )
                        {
                            var mapItem = new FinderMapItem( fence.Location );
                            mapItem.EntityTypeId = EntityTypeCache.Read( "Rock.Model.Group" ).Id;
                            mapItem.EntityId = fence.GroupId;
                            mapItem.Name = fence.Group.Name;
                            fenceMapItems.Add( mapItem );
                        }
                    }
                }

                // if not sorting by ColumnClick and SortByDistance, then sort the groups by distance
                if ( gGroups.SortProperty == null && GetAttributeValue( "SortByDistance" ).AsBoolean() )
                {
                    // only show groups with a known location, and sort those by distance
                    groups = groups.Where( a => distances.Select( b => b.Key ).Contains( a.Id ) ).ToList();
                    groups = groups.OrderBy( a => distances[a.Id] ).ThenBy( a => a.Name ).ToList();
                }

                // if limiting by PageSize, limit to the top X groups
                int? pageSize = ddlPageSize.SelectedValue.AsIntegerOrNull();
                if ( pageSize.HasValue && pageSize > 0 )
                {
                    groups = groups.Take( pageSize.Value ).ToList();
                }

                // If a map is to be shown
                if ( showMap && groups.Any() )
                {

                    Template template = Template.Parse( GetAttributeValue( "MapInfo" ) );

                    bool showDebug = UserCanEdit && GetAttributeValue( "MapInfoDebug" ).AsBoolean();
                    lMapInfoDebug.Visible = showDebug;

                    // Add mapitems for all the remaining valid group locations
                    var groupMapItems = new List<MapItem>();
                    foreach ( var gl in groupLocations )
                    {
                        var group = groups.Where( g => g.Id == gl.GroupId ).FirstOrDefault();
                        if ( group != null )
                        {
                            // Resolve info window lava template
                            var linkedPageParams = new Dictionary<string, string> { { "GroupId", group.Id.ToString() } };
                            var mergeFields = new Dictionary<string, object>();
                            mergeFields.Add( "Group", gl.Group );
                            mergeFields.Add( "Location", gl.Location );

                            Dictionary<string, object> linkedPages = new Dictionary<string, object>();
                            linkedPages.Add( "GroupDetailPage", LinkedPageRoute( "GroupDetailPage" ) );

                            if ( _targetPersonGuid != Guid.Empty )
                            {
                                linkedPages.Add( "RegisterPage", LinkedPageUrl( "RegisterPage", _urlParms ) );
                            }
                            else
                            {
                                linkedPages.Add( "RegisterPage", LinkedPageUrl( "RegisterPage", null ) );
                            }

                            mergeFields.Add( "LinkedPages", linkedPages );

                            // add collection of allowed security actions
                            Dictionary<string, object> securityActions = new Dictionary<string, object>();
                            securityActions.Add( "View", group.IsAuthorized( Authorization.VIEW, CurrentPerson ) );
                            securityActions.Add( "Edit", group.IsAuthorized( Authorization.EDIT, CurrentPerson ) );
                            securityActions.Add( "Administrate", group.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson ) );
                            mergeFields.Add( "AllowedActions", securityActions );

                            string infoWindow = template.Render( Hash.FromDictionary( mergeFields ) );

                            if ( showDebug )
                            {
                                lMapInfoDebug.Text = mergeFields.lavaDebugInfo( null, "<span class='label label-info'>Lava used for the map window.</span>", "" );
                                showDebug = false;
                            }

                            // Add a map item for group
                            var mapItem = new FinderMapItem( gl.Location );
                            mapItem.EntityTypeId = EntityTypeCache.Read( "Rock.Model.Group" ).Id;
                            mapItem.EntityId = group.Id;
                            mapItem.Name = group.Name;
                            mapItem.InfoWindow = HttpUtility.HtmlEncode( infoWindow.Replace( Environment.NewLine, string.Empty ).Replace( "\n", string.Empty ).Replace( "\t", string.Empty ) );
                            groupMapItems.Add( mapItem );
                        }
                    }

                    // Show the map
                    Map( personMapItem, fenceMapItems, groupMapItems );
                    pnlMap.Visible = true;
                }
                else
                {
                    pnlMap.Visible = false;
                }
            }
            else
            {
                pnlMap.Visible = false;
            }

            // Should a lava output be displayed
            if ( GetAttributeValue( "ShowLavaOutput" ).AsBoolean() )
            {
                string template = GetAttributeValue( "LavaOutput" );

                var mergeFields = new Dictionary<string, object>();
                if ( fences != null )
                {
                    mergeFields.Add( "Fences", fences.Select( f => f.Group ).ToList() );
                }
                else
                {
                    mergeFields.Add( "Fences", new Dictionary<string, object>() );
                }

                mergeFields.Add( "Groups", groups );

                Dictionary<string, object> linkedPages = new Dictionary<string, object>();
                linkedPages.Add( "GroupDetailPage", LinkedPageUrl( "GroupDetailPage", null ) );

                if ( _targetPersonGuid != Guid.Empty )
                {
                    linkedPages.Add( "RegisterPage", LinkedPageUrl( "RegisterPage", _urlParms ) );
                }
                else
                {
                    linkedPages.Add( "RegisterPage", LinkedPageUrl( "RegisterPage", null ) );
                }

                mergeFields.Add( "LinkedPages", linkedPages );

                lLavaOverview.Text = template.ResolveMergeFields( mergeFields );

                bool showDebug = UserCanEdit && GetAttributeValue( "LavaOutputDebug" ).AsBoolean();
                lLavaOutputDebug.Visible = showDebug;
                if ( showDebug )
                {
                    lLavaOutputDebug.Text = mergeFields.lavaDebugInfo( null, "<span class='label label-info'>Lava used for the summary info.</span>" );
                }

                pnlLavaOutput.Visible = true;
            }
            else
            {
                pnlLavaOutput.Visible = false;
            }

            // Should a grid be displayed
            if ( GetAttributeValue( "ShowGrid" ).AsBoolean() )
            {
                pnlGrid.Visible = true;

                // Save the groups into the grid's object list since it is not being bound to actual group objects
                gGroups.ObjectList = new Dictionary<string, object>();
                groups.ForEach( g => gGroups.ObjectList.Add( g.Id.ToString(), g ) );

                // Bind the grid
                gGroups.DataSource = groups.Select( g =>
                {
                    var qryMembers = new GroupMemberService( rockContext ).Queryable().Where( a => a.GroupId == g.Id );
                    var groupType = GroupTypeCache.Read( g.GroupTypeId );

                    return new
                    {
                        Id = g.Id,
                        Name = g.Name,
                        GroupTypeName = groupType.Name,
                        GroupOrder = g.Order,
                        GroupTypeOrder = groupType.Order,
                        Description = g.Description,
                        IsSystem = g.IsSystem,
                        IsActive = g.IsActive,
                        GroupRole = string.Empty,
                        DateAdded = DateTime.MinValue,
                        Schedule = g.Schedule,
                        MemberCount = qryMembers.Count(),
                        AverageAge = Math.Round( qryMembers.Select( m => m.Person.BirthDate ).ToList().Select( a => Person.GetAge( a ) ).Average() ?? 0.0D ),
                        Distance = distances.Where( d => d.Key == g.Id )
                            .Select( d => d.Value ).FirstOrDefault()
                    };
                } ).ToList();
                gGroups.DataBind();
            }
            else
            {
                pnlGrid.Visible = false;
            }

            // Show the results
            pnlResults.Visible = true;
        }
Example #41
0
        /// <summary>
        /// Returns the first <see cref="Rock.Model.Location" /> where the address matches the provided address, otherwise the address will be saved as a new location.
        /// Note: The location search IS NOT constrained by the provided <seealso cref="GetLocationArgs.Group"></seealso>. Providing the group will cause this method to search that groups locations first, giving a faster result.
        /// </summary>
        /// <param name="street1">A <see cref="string" /> representing the Address Line 1 to search by.</param>
        /// <param name="street2">A <see cref="string" /> representing the Address Line 2 to search by.</param>
        /// <param name="city">A <see cref="string" /> representing the City to search by.</param>
        /// <param name="state">A <see cref="string" /> representing the State/Province to search by.</param>
        /// <param name="locality">A <see cref="string" /> representing the Locality/County to search by</param>
        /// <param name="postalCode">A <see cref="string" /> representing the Zip/Postal code to search by</param>
        /// <param name="country">A <see cref="string" /> representing the Country to search by</param>
        /// <param name="getLocationArgs">The <seealso cref="GetLocationArgs"/></param>
        /// <returns>
        /// The first <see cref="Rock.Model.Location" /> where an address match is found, if no match is found a new <see cref="Rock.Model.Location" /> is created and returned.
        /// </returns>
        /// <exception cref="System.Exception"></exception>
        public Location Get(string street1, string street2, string city, string state, string locality, string postalCode, string country, GetLocationArgs getLocationArgs)
        {
            Group group             = getLocationArgs?.Group;
            bool  verifyLocation    = getLocationArgs?.VerifyLocation ?? true;
            bool  createNewLocation = getLocationArgs?.CreateNewLocation ?? true;
            var   validateLocation  = getLocationArgs?.ValidateLocation ?? true;

            // Remove leading and trailing whitespace.
            street1    = street1.ToStringSafe().Trim();
            street2    = street2.ToStringSafe().Trim();
            city       = city.ToStringSafe().Trim();
            state      = state.ToStringSafe().Trim();
            locality   = locality.ToStringSafe().Trim();
            postalCode = postalCode.ToStringSafe().Trim();
            country    = country.ToStringSafe().Trim();

            // Make sure the address has some content.
            if (string.IsNullOrWhiteSpace(street1) &&
                string.IsNullOrWhiteSpace(street2) &&
                string.IsNullOrWhiteSpace(city) &&
                string.IsNullOrWhiteSpace(state) &&
                string.IsNullOrWhiteSpace(locality) &&
                string.IsNullOrWhiteSpace(postalCode) &&
                string.IsNullOrWhiteSpace(country))
            {
                return(null);
            }

            // Try to find a location that matches the values, this is not a case sensitive match
            var foundLocation = Search(new Location {
                Street1 = street1, Street2 = street2, City = city, State = state, County = locality, PostalCode = postalCode, Country = country
            }, group);

            if (foundLocation != null)
            {
                // Check for casing
                if (!String.Equals(street1, foundLocation.Street1) || !String.Equals(street2, foundLocation.Street2) || !String.Equals(city, foundLocation.City) || !String.Equals(state, foundLocation.State) || !String.Equals(postalCode, foundLocation.PostalCode) || !String.Equals(country, foundLocation.Country))
                {
                    var context  = new RockContext();
                    var location = new LocationService(context).Get(foundLocation.Id);
                    location.Street1    = street1;
                    location.Street2    = street2;
                    location.City       = city;
                    location.State      = state;
                    location.County     = locality;
                    location.PostalCode = postalCode;
                    location.Country    = country;
                    context.SaveChanges();
                    return(Get(location.Guid));
                }
                return(foundLocation);
            }

            // If existing location wasn't found with entered values, try standardizing the values, and search for an existing value again
            var newLocation = new Location
            {
                Street1    = street1.FixCase(),
                Street2    = street2.FixCase(),
                City       = city.FixCase(),
                State      = state,
                County     = locality,
                PostalCode = postalCode,
                Country    = country
            };

            if (verifyLocation)
            {
                Verify(newLocation, false);
            }

            foundLocation = Search(newLocation, group);
            if (foundLocation != null)
            {
                return(foundLocation);
            }

            if (createNewLocation)
            {
                if (validateLocation)
                {
                    // Verify that the new location has all of the required fields.
                    string validationError;

                    var isValid = ValidateAddressRequirements(newLocation, out validationError);

                    if (!isValid)
                    {
                        throw new Exception(validationError);
                    }
                }

                // Create a new context/service so that save does not affect calling method's context
                var rockContext     = new RockContext();
                var locationService = new LocationService(rockContext);
                locationService.Add(newLocation);
                rockContext.SaveChanges();
            }

            // refetch it from the database to make sure we get a valid .Id
            return(Get(newLocation.Guid));
        }