/// <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 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 );
        }
Example #3
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>
        /// 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;

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

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

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

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

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

                campus.Location = location;
            }

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

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

            campus.ShortCode = tbCampusCode.Text;

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

            campus.ServiceTimes = kvlServiceTimes.Value;

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

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

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

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

            } );

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

            NavigateToParentPage();
        }
Example #7
0
        /// <summary>
        /// Loads the kiosk locations.
        /// </summary>
        /// <param name="kioskDevice">The kiosk device.</param>
        /// <param name="location">The location.</param>
        /// <param name="campusId">The campus identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        private static void LoadKioskLocations( KioskDevice kioskDevice, Location location, int? campusId, RockContext rockContext )
        {
            // Get the child locations and the selected location
            var allLocations = new LocationService( rockContext ).GetAllDescendentIds( location.Id ).ToList();
            allLocations.Add( location.Id );

            var activeSchedules = new Dictionary<int, KioskSchedule>();

            foreach ( var groupLocation in new GroupLocationService( rockContext ).GetActiveByLocations( allLocations ).OrderBy( l => l.Order ).AsNoTracking() )
            {
                var kioskLocation = new KioskLocation( groupLocation.Location );
                kioskLocation.CampusId = campusId;
                kioskLocation.Order = groupLocation.Order;

                // Populate each kioskLocation with its schedules (kioskSchedules)
                foreach ( var schedule in groupLocation.Schedules.Where( s => s.CheckInStartOffsetMinutes.HasValue ) )
                {
                    if ( activeSchedules.Keys.Contains( schedule.Id ) )
                    {
                        kioskLocation.KioskSchedules.Add( activeSchedules[schedule.Id] );
                    }
                    else
                    {
                        var kioskSchedule = new KioskSchedule( schedule );
                        kioskSchedule.CheckInTimes = schedule.GetCheckInTimes( RockDateTime.Now );
                        if ( kioskSchedule.IsCheckInActive || kioskSchedule.NextActiveDateTime.HasValue )
                        {
                            kioskLocation.KioskSchedules.Add( kioskSchedule );
                            activeSchedules.Add( schedule.Id, kioskSchedule );
                        }
                    }
                }

                // If the group location has any active OR future schedules, add the group's group type to the kiosk's
                // list of group types
                if ( kioskLocation.KioskSchedules.Count > 0 )
                {
                    KioskGroupType kioskGroupType = kioskDevice.KioskGroupTypes.Where( g => g.GroupType.Id == groupLocation.Group.GroupTypeId ).FirstOrDefault();
                    if ( kioskGroupType == null )
                    {
                        kioskGroupType = new KioskGroupType( groupLocation.Group.GroupTypeId );
                        kioskDevice.KioskGroupTypes.Add( kioskGroupType );
                    }

                    KioskGroup kioskGroup = kioskGroupType.KioskGroups.Where( g => g.Group.Id == groupLocation.GroupId ).FirstOrDefault();
                    if ( kioskGroup == null )
                    {
                        kioskGroup = new KioskGroup( groupLocation.Group );
                        kioskGroup.Group.LoadAttributes( rockContext );
                        kioskGroupType.KioskGroups.Add( kioskGroup );
                    }

                    kioskGroup.KioskLocations.Add( kioskLocation );
                }
            }
        }
Example #8
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,
                Street2    = street2,
                City       = city,
                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));
        }
        /// <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 );
            }

            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();

            var addrLocation = locapAddress.Location;
            if ( addrLocation != null )
            {
                location.Street1 = addrLocation.Street1;
                location.Street2 = addrLocation.Street2;
                location.City = addrLocation.City;
                location.State = addrLocation.State;
                location.Zip = addrLocation.Zip;
            }

            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;
            }

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

                location.SaveAttributeValues( rockContext );

            } );

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

            NavigateToPage( RockPage.Guid, qryParams );
        }
Example #10
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));
        }
        /// <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 );
        }
        /// <summary>
        /// Returns a <see cref="Rock.Model.Location"/> by GeoPoint. If a match is not found,
        /// a new Location will be added based on the Geopoint.
        /// </summary>
        /// <param name="point">A <see cref="System.Data.Entity.Spatial.DbGeography"/> object
        ///     representing the Geopoint for the location.</param>
        /// <returns>The first <see cref="Rock.Model.Location"/> that matches the specified GeoPoint.</returns>
        public Location GetByGeoPoint( DbGeography point )
        {
            // get the first address that has a GeoPoint the value
            // use the 'Where Max(ID)' trick instead of TOP 1 to optimize SQL performance
            var qryWhere = Queryable()
                .Where( a =>
                    a.GeoPoint != null &&
                    a.GeoPoint.SpatialEquals( point ) );

            var result = Queryable().Where( a => a.Id == qryWhere.Max( b => b.Id ) ).FirstOrDefault();

            if ( result == null )
            {
                // if the Location can't be found, save the new location to the database
                Location newLocation = new Location
                {
                    GeoPoint = point,
                    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 #13
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));
        }