Ejemplo n.º 1
0
        /// <summary>
        /// Adds the new home location.
        /// </summary>
        /// <param name="ncoaHistory">The NCOA history.</param>
        /// <param name="locationService">The location service.</param>
        /// <param name="groupLocationService">The group location service.</param>
        /// <param name="homeValueId">The home value identifier.</param>
        /// <param name="changes">The changes.</param>
        /// <param name="isMailingLocation">Is the location a mailing location.</param>
        /// <param name="isMappedLocation">Is the location a mapped location.</param>
        /// <returns></returns>
        private bool AddNewHomeLocation(NcoaHistory ncoaHistory, LocationService locationService, GroupLocationService groupLocationService, int?homeValueId, History.HistoryChangeList changes, bool isMailingLocation, bool isMappedLocation)
        {
            if (homeValueId.HasValue)
            {
                var location = locationService.Get(
                    ncoaHistory.UpdatedStreet1,
                    ncoaHistory.UpdatedStreet2,
                    ncoaHistory.UpdatedCity,
                    ncoaHistory.UpdatedState,
                    ncoaHistory.UpdatedPostalCode,
                    ncoaHistory.UpdatedCountry);

                var groupLocation = new GroupLocation();
                groupLocation.Location                 = location;
                groupLocation.IsMailingLocation        = isMailingLocation;
                groupLocation.IsMappedLocation         = isMappedLocation;
                groupLocation.GroupId                  = ncoaHistory.FamilyId;
                groupLocation.GroupLocationTypeValueId = homeValueId.Value;
                groupLocation.IsMailingLocation        = true;
                groupLocationService.Add(groupLocation);

                changes.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Property, "Location").SetNewValue(groupLocation.Location.ToString()).SourceOfChange = "NCOA Request";

                return(true);
            }

            return(false);
        }
 /// <summary>
 /// Erzeugt eine neue Beschreibung.
 /// </summary>
 /// <param name="pipeline">Die zugehörige Gesamtliste aller Aktionen gleicher Art.</param>
 /// <param name="location">Der Ursprung für die angegebene Quellgruppe.</param>
 /// <param name="group">Die neue Quellgruppe.</param>
 private TuneToken(ActionPipeline <TuneToken> pipeline, GroupLocation location, SourceGroup group)
     : base(pipeline)
 {
     // Remember
     GroupLocation = location;
     SourceGroup   = group;
 }
            /// <summary>
            /// Erzeugt ein neue Zustandsinformation.
            /// </summary>
            /// <param name="pipeline">Die zugehörige Gesamtliste aller Aktionen gleicher Art.</param>
            /// <param name="location">Der Ursprung für die angegebene Quellgruppe.</param>
            /// <param name="group">Die neue Quellgruppe.</param>
            /// <returns>Die gewünschte Information.</returns>
            /// <exception cref="ArgumentNullException">Es wurde kein Graph übergeben.</exception>
            internal static TuneToken Create(ActionPipeline <TuneToken> pipeline, GroupLocation location, SourceGroup group)
            {
                // Create new
                var token = new TuneToken(pipeline, location, group);

                // Configure
                IDVBTuningSpace2  tuningSpace;
                Action <ILocator> initializer;

                switch (pipeline.Graph.DVBType)
                {
                case DVBSystemType.Terrestrial: tuningSpace = token.PrepareTerrestrial(out initializer); break;

                case DVBSystemType.Satellite: tuningSpace = token.PrepareSatellite(out initializer); break;

                case DVBSystemType.Cable: tuningSpace = token.PrepareCable(out initializer); break;

                default: throw new NotImplementedException(pipeline.Graph.DVBType.ToString());
                }

                // With cleanup
                try
                {
                    // Create a new tune request
                    token.CreateTuneRequest(tuningSpace, initializer);
                }
                finally
                {
                    // No longer used
                    BDAEnvironment.Release(ref tuningSpace);
                }

                // Report
                return(token);
            }
Ejemplo n.º 4
0
        /// <summary>
        /// Wählt eine Quellgruppe aus.
        /// </summary>
        /// <param name="group">Díe Daten der Quellgruppe.</param>
        /// <param name="location">Die Wahl des Ursprungs, über den die Quellgruppe empfangen werden kann.</param>
        /// <returns>Gesetzt, wenn es sich um eine DVB-S Quellgruppe handelt.</returns>
        public void SetChannel(SourceGroup group, GroupLocation location)
        {
            // Stop all filters
            StopFilters();

            // May repeat some times
            for (int nRetry = 3; nRetry-- > 0;)
            {
                // Supported types in order of importance
                if (!SendChannel(group as SatelliteGroup, location as SatelliteLocation))
                {
                    if (!SendChannel(group as CableGroup))
                    {
                        if (!SendChannel(group as TerrestrialGroup))
                        {
                            throw new DVBException("Unsupported Channel Type " + group.GetType().FullName);
                        }
                    }
                }

                // Wait for the signal
                for (int n = 10; n-- > 0; Thread.Sleep(50))
                {
                    if (SignalStatus.Locked)
                    {
                        return;
                    }
                }

                // Force to resend DiSEqC command
                m_lastMessage = null;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Wählt eine Quellgruppe aus.
        /// </summary>
        /// <param name="group">Díe Daten der Quellgruppe.</param>
        /// <param name="location">Die Wahl des Ursprungs, über den die Quellgruppe empfangen werden kann.</param>
        public void Tune(SourceGroup group, GroupLocation location)
        {
            // May repeat some times
            for (int retryCount = 3; retryCount-- > 0; Thread.Sleep(250))
            {
                // All supported in order of importance
                if (!Tune(group as SatelliteGroup, location as SatelliteLocation).HasValue)
                {
                    if (!Tune(group as CableGroup).HasValue)
                    {
                        if (!Tune(group as TerrestrialGroup).HasValue)
                        {
                            throw new DVBException("Unsupported channel type " + group.GetType().FullName);
                        }
                    }
                }

                // Done if locked
                if (SignalStatus.Locked)
                {
                    break;
                }

                // Enforce reset
                m_lastMessage = null;
            }
        }
        /// <summary>
        /// Wählt eine Quellgruppe (Transponder) an und prüft, ob ein Signal anliegt.
        /// </summary>
        /// <param name="device">Das aktuell verwendete DVB.NET Geräte.</param>
        /// <param name="location">Optional der Ursprung der Quellgruppe (Transponder).</param>
        /// <param name="group">Die gewünschte Quellgruppe (Transponder).</param>
        /// <param name="lastInversion">Bei DVB-C die zuletzt erfolgreich verwendete spektrale Inversion.</param>
        /// <returns>Die Informationen zu den Quellen oder <i>null</i>.</returns>
        private GroupInformation SelectGroup(Hardware device, GroupLocation location, SourceGroup group, ref SpectrumInversions lastInversion)
        {
            // See if this is a cable group
            var cableGroup = group as CableGroup;

            if (cableGroup != null)
            {
                if (cableGroup.SpectrumInversion == SpectrumInversions.Auto)
                {
                    cableGroup.SpectrumInversion = lastInversion;
                }
            }

            // Report
            if (ScannerTraceSwitch.Level >= TraceLevel.Verbose)
            {
                Trace.WriteLine(string.Format(Properties.Resources.Trace_Scanner_1stTune, location, group), ScannerTraceSwitch.DisplayName);
            }

            // Choose group
            device.SelectGroup(location, group);

            // Did it
            var info = device.GetGroupInformation(5000);

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

            // Report
            if (ScannerTraceSwitch.Level >= TraceLevel.Warning)
            {
                Trace.WriteLine(string.Format(Properties.Resources.Trace_Scanner_NoGroupInfo, location, group), ScannerTraceSwitch.DisplayName);
            }

            // Not cable
            if (cableGroup == null)
            {
                return(null);
            }

            // Swap inversion
            lastInversion = (lastInversion == SpectrumInversions.On) ? SpectrumInversions.Off : SpectrumInversions.On;

            // Put into group
            cableGroup.SpectrumInversion = lastInversion;

            // Report
            if (ScannerTraceSwitch.Level >= TraceLevel.Verbose)
            {
                Trace.WriteLine(string.Format(Properties.Resources.Trace_Scanner_2ndTune, location, group), ScannerTraceSwitch.DisplayName);
            }

            // Choose group
            device.SelectGroup(location, group);

            // Final try
            return(device.GetGroupInformation(5000));
        }
        /// <summary>
        /// Prüft auf den Abbruch des Suchlaufs nach der Ausführung eines Ursprungs.
        /// </summary>
        /// <param name="location">Der gerade besuchte Ursprung.</param>
        /// <returns>Gesetzt, wenn der Suchlauf fortgesetzt werden soll.</returns>
        private bool LocationDone(GroupLocation location)
        {
            // Report
            if (ScannerTraceSwitch.Level >= TraceLevel.Info)
            {
                Trace.WriteLine(string.Format(Properties.Resources.Trace_Scanner_DoneLocation, location), ScannerTraceSwitch.DisplayName);
            }

            // See if handler is provided
            Func <GroupLocation, TransponderScanner, bool> onDoneLocation = OnDoneLocation;

            if (null == onDoneLocation)
            {
                return(true);
            }

            // Ask caller
            if (onDoneLocation(location, this))
            {
                return(true);
            }

            // Mark stop
            m_Aborted = true;

            // Done
            return(false);
        }
Ejemplo n.º 8
0
        public FamilyAddress(GroupLocation groupLocation)
        {
            LocationIsDirty = false;
            if (groupLocation != null)
            {
                Id = groupLocation.Id;

                if (groupLocation.LocationTypeValue != null)
                {
                    LocationTypeId   = groupLocation.LocationTypeValue.Id;
                    LocationTypeName = groupLocation.LocationTypeValue.Name;
                }

                if (groupLocation.Location != null)
                {
                    LocationId = groupLocation.Location.Id;
                    Street1    = groupLocation.Location.Street1;
                    Street2    = groupLocation.Location.Street2;
                    City       = groupLocation.Location.City;
                    State      = groupLocation.Location.State;
                    Zip        = groupLocation.Location.Zip;
                }

                IsMailing  = groupLocation.IsMailing;
                IsLocation = groupLocation.IsLocation;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Wählt eine Quellgruppe aus.
        /// </summary>
        /// <param name="group">Díe Daten der Quellgruppe.</param>
        /// <param name="location">Die Wahl des Ursprungs, über den die Quellgruppe empfangen werden kann.</param>
        /// <returns>Gesetzt, wenn es sich um eine DVB-S Quellgruppe handelt.</returns>
        public void SetChannel(SourceGroup group, GroupLocation location)
        {
            // Always stop CI
            Decrypt(0);

            // Store
            Frontend.SetChannel(group, location);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Wählt eine Quellgruppe an.
        /// </summary>
        /// <param name="group">Die Quellgruppe.</param>
        /// <param name="location">Der Ursprung zur Quellgruppe.</param>
        public void Tune(SourceGroup group, GroupLocation location)
        {
            // Must register
            Register();

            // Forward
            Context.TheContext.SetChannel(group, location);
        }
Ejemplo n.º 11
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)
        {
            var rockContext = new RockContext();

            GroupLocationService groupLocationService = new GroupLocationService(rockContext);
            ScheduleService      scheduleService      = new ScheduleService(rockContext);

            var gridViewRows = gGroupLocationSchedule.Rows;

            foreach (GridViewRow row in gridViewRows.OfType <GridViewRow>())
            {
                int           groupLocationId = int.Parse(gGroupLocationSchedule.DataKeys[row.RowIndex].Value as string);
                GroupLocation groupLocation   = groupLocationService.Get(groupLocationId);
                if (groupLocation != null)
                {
                    foreach (var fieldCell in row.Cells.OfType <DataControlFieldCell>())
                    {
                        CheckBoxEditableField checkBoxTemplateField = fieldCell.ContainingField as CheckBoxEditableField;
                        if (checkBoxTemplateField != null)
                        {
                            CheckBox checkBox   = fieldCell.Controls[0] as CheckBox;
                            string   dataField  = (fieldCell.ContainingField as CheckBoxEditableField).DataField;
                            int      scheduleId = int.Parse(dataField.Replace("scheduleField_", string.Empty));

                            // update GroupLocationSchedule depending on if the Schedule is Checked or not
                            if (checkBox.Checked)
                            {
                                // This schedule is selected, so if GroupLocationSchedule doesn't already have this schedule, add it
                                if (!groupLocation.Schedules.Any(a => a.Id == scheduleId))
                                {
                                    var schedule = scheduleService.Get(scheduleId);
                                    groupLocation.Schedules.Add(schedule);
                                }
                            }
                            else
                            {
                                // This schedule is not selected, so if GroupLocationSchedule has this schedule, delete it
                                if (groupLocation.Schedules.Any(a => a.Id == scheduleId))
                                {
                                    groupLocation.Schedules.Remove(groupLocation.Schedules.FirstOrDefault(a => a.Id == scheduleId));
                                }
                            }
                        }
                    }
                }
            }

            rockContext.SaveChanges();

            Rock.CheckIn.KioskDevice.FlushAll();

            if (_groupTypeId.HasValue)
            {
                NavigateToParentPage(new Dictionary <string, string> {
                    { "CheckinTypeId", _groupTypeId.ToString() }
                });
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            using (new UnitOfWorkScope())
            {
                GroupLocationService groupLocationService = new GroupLocationService();
                ScheduleService      scheduleService      = new ScheduleService();

                RockTransactionScope.WrapTransaction(() =>
                {
                    var gridViewRows = gGroupLocationSchedule.Rows;
                    foreach (GridViewRow row in gridViewRows.OfType <GridViewRow>())
                    {
                        int groupLocationId         = int.Parse(gGroupLocationSchedule.DataKeys[row.RowIndex].Value as string);
                        GroupLocation groupLocation = groupLocationService.Get(groupLocationId);
                        if (groupLocation != null)
                        {
                            foreach (var fieldCell in row.Cells.OfType <DataControlFieldCell>())
                            {
                                CheckBoxEditableField checkBoxTemplateField = fieldCell.ContainingField as CheckBoxEditableField;
                                if (checkBoxTemplateField != null)
                                {
                                    CheckBox checkBox = fieldCell.Controls[0] as CheckBox;
                                    string dataField  = (fieldCell.ContainingField as CheckBoxEditableField).DataField;
                                    int scheduleId    = int.Parse(dataField.Replace("scheduleField_", string.Empty));

                                    // update GroupLocationSchedule depending on if the Schedule is Checked or not
                                    if (checkBox.Checked)
                                    {
                                        // This schedule is selected, so if GroupLocationSchedule doesn't already have this schedule, add it
                                        if (!groupLocation.Schedules.Any(a => a.Id == scheduleId))
                                        {
                                            var schedule = scheduleService.Get(scheduleId);
                                            groupLocation.Schedules.Add(schedule);
                                        }
                                    }
                                    else
                                    {
                                        // This schedule is not selected, so if GroupLocationSchedule has this schedule, delete it
                                        if (groupLocation.Schedules.Any(a => a.Id == scheduleId))
                                        {
                                            groupLocation.Schedules.Remove(groupLocation.Schedules.FirstOrDefault(a => a.Id == scheduleId));
                                        }
                                    }
                                }
                            }

                            groupLocationService.Save(groupLocation, this.CurrentPersonId);
                        }
                    }
                });
            }

            NavigateToParentPage();
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Wählt eine Quellgruppe an.
        /// </summary>
        /// <param name="group">Die Quellgruppe.</param>
        /// <param name="location">Der Ursprung zur Quellgruppe.</param>
        public void Tune(SourceGroup group, GroupLocation location)
        {
            // Attach to hardware
            Open();

            // Invalidate all filters
            StopFilters();

            // Send request
            m_Frontend.Tune(group, location);
        }
Ejemplo n.º 14
0
        protected void saveFamily(object sender, EventArgs e)
        {
            RockContext rContext = new RockContext();

            DefinedValueCache PreviousLocationType = DefinedValueCache.Get(GUID_PREV);
            DefinedValueCache HomeLocationType     = DefinedValueCache.Get(GUID_HOME);

            Group family = new GroupService(rContext).Get(PageParameter("GroupId").AsInteger());

            if (family == null || !checkPermissions(family))
            {
                showUnauthorized();
                return;
            }


            family.Name     = dtbFamilyName.Text;
            family.CampusId = cpFamilyCampus.SelectedCampusId;

            IEnumerable <GroupLocation> oldGroupLocations = GetFamilyLocations(family);
            List <GroupLocation>        newGroupLocations = GetNewGroupLocations(rContext, family);

            // First, go through the old locations and either modify it to match a new one or mark it as previous
            foreach (GroupLocation oldGroupLocation in oldGroupLocations)
            {
                // See if we can reuse it or if we have to replace it
                GroupLocation matchingNewLocation = newGroupLocations.FirstOrDefault(gl => gl.Location.Id == oldGroupLocation.Location.Id);
                if (matchingNewLocation != null)
                {
                    oldGroupLocation.IsMailingLocation = matchingNewLocation.IsMailingLocation;
                    oldGroupLocation.IsMappedLocation  = matchingNewLocation.IsMappedLocation;
                    newGroupLocations.Remove(matchingNewLocation);
                }
                else
                {
                    oldGroupLocation.GroupLocationTypeValueId = PreviousLocationType.Id;
                    oldGroupLocation.IsMailingLocation        = false;
                    oldGroupLocation.IsMappedLocation         = false;
                }
            }

            // Add the ones we couldn't match
            foreach (GroupLocation newGroupLocation in newGroupLocations)
            {
                family.GroupLocations.Add(newGroupLocation);
            }


            rContext.SaveChanges();
            showSuccess(family);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Gets or sets the group.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        /// <value>
        /// The group.
        /// </value>
        public Group GetGroup(RockContext rockContext)
        {
            EnsureChildControls();
            Group result = new Group();

            result.Id          = _hfGroupTypeId.ValueAsInt();
            result.Guid        = new Guid(_hfGroupGuid.Value);
            result.GroupTypeId = _hfGroupTypeId.ValueAsInt();

            // get the current InheritedGroupTypeId from the Parent Editor just in case it hasn't been saved to the database
            CheckinGroupTypeEditor checkinGroupTypeEditor = GetParentGroupTypeEditor(this.Parent);

            if (checkinGroupTypeEditor != null)
            {
                result.GroupType      = new GroupType();
                result.GroupType.Id   = result.GroupTypeId;
                result.GroupType.Guid = checkinGroupTypeEditor.GroupTypeGuid;
                result.GroupType.InheritedGroupTypeId = checkinGroupTypeEditor.InheritedGroupTypeId;
            }

            result.Name = _tbGroupName.Text;
            result.LoadAttributes(rockContext);

            // populate groupLocations with whatever is currently in the grid, with just enough info to repopulate it and save it later
            result.GroupLocations = new List <GroupLocation>();
            foreach (var item in this.Locations)
            {
                var groupLocation = new GroupLocation();
                groupLocation.LocationId = item.LocationId;
                groupLocation.Location   = new Location {
                    Id = item.LocationId, Name = item.Name, ParentLocationId = item.ParentLocationId
                };
                result.GroupLocations.Add(groupLocation);
            }

            result.Groups = new List <Group>();
            int childGroupOrder = 0;

            foreach (CheckinGroupEditor checkinGroupEditor in this.Controls.OfType <CheckinGroupEditor>())
            {
                Group childGroup = checkinGroupEditor.GetGroup(rockContext);
                childGroup.Order = childGroupOrder++;
                result.Groups.Add(childGroup);
            }

            Rock.Attribute.Helper.GetEditValues(_phGroupAttributes, result);
            return(result);
        }
Ejemplo n.º 16
0
        public int? SaveGroupLocation( int groupId, int locationId, int? groupLocationTypeValueId = null, int? groupMemberPersonAliasId = null, 
                bool isMailingLocation = false, bool isMappedLocation = false, string foreignId = null, int? groupLocationId = null )
        {
            GroupLocationController groupLocationController = new GroupLocationController( Service );
            GroupLocation groupLocation = null;

            if ( groupLocationId != null )
            {
                groupLocation = groupLocationController.GetById( (int)groupLocationId );

                if ( groupLocation == null )
                {
                    return null;
                }
            }
            else
            {
                groupLocation = new GroupLocation();
            }

            groupLocation.GroupId = groupId;
            groupLocation.LocationId = locationId;
            groupLocation.GroupLocationTypeValueId = groupLocationTypeValueId;
            groupLocation.IsMailingLocation = isMailingLocation;
            groupLocation.IsMappedLocation = isMappedLocation;
            groupLocation.GroupMemberPersonAliasId = groupMemberPersonAliasId;
            groupLocation.ForeignId = foreignId;

            int? personAliasId = Service.GetCurrentPersonAliasId();
            if ( groupLocationId == null )
            {
                groupLocation.CreatedByPersonAliasId = Service.LoggedInPerson.PrimaryAliasId;
                groupLocationController.Add( groupLocation );
            }
            else
            {
                groupLocation.ModifiedByPersonAliasId = Service.LoggedInPerson.PrimaryAliasId;
                groupLocationController.Update( groupLocation );
            }

            groupLocation = groupLocationController.GetByGuid( groupLocation.Guid );

            return groupLocation.Id;
        }
Ejemplo n.º 17
0
        public async Task <int> AddAsync(GroupLocationAddModel mGroupLocation)
        {
            var group = _context.Groups.FirstOrDefault(c => c.GroupId == mGroupLocation.GroupId);

            if (group == null)
            {
                throw new ExpectException("Could not find Group data which GroupId equal to " + mGroupLocation.GroupId);
            }

            var location = _context.Locations.FirstOrDefault(c => c.LocationId == mGroupLocation.LocationId);

            if (location == null)
            {
                throw new ExpectException("Could not find Location data which LocationId equal to " + mGroupLocation.LocationId);
            }

            //GroupId and LocationId must be unique
            var checkData = await _context.GroupLocations
                            .Where(c => c.GroupId == mGroupLocation.GroupId &&
                                   c.LocationId == mGroupLocation.LocationId).ToListAsync();

            if (checkData.Count > 0)
            {
                throw new ExpectException("There is already exist data which GroupId equal to "
                                          + mGroupLocation.GroupId + " and LocationId equal to " + mGroupLocation.LocationId);
            }


            var model = new GroupLocation
            {
                GroupId    = mGroupLocation.GroupId,
                LocationId = mGroupLocation.LocationId
            };

            _context.GroupLocations.Add(model);
            await _context.SaveChangesAsync();

            return(model.GroupLocationId);
        }
Ejemplo n.º 18
0
        protected void loadFamily()
        {
            Group family = new GroupService(new RockContext()).Get(PageParameter("GroupId").AsInteger());

            if (family == null || !checkPermissions(family))
            {
                showUnauthorized();
                return;
            }
            editPanel.Visible = true;

            dtbFamilyName.Text = family.Name;

            if (family.CampusId != null)
            {
                cpFamilyCampus.SelectedCampusId = family.CampusId;
            }

            GroupLocation mailingGroupLocation = GetFamilyMailingLocation(family);

            if (mailingGroupLocation != null)
            {
                acMailingAddress.SetValues(mailingGroupLocation.Location);
            }

            GroupLocation homeGroupLocation = GetFamilyHomeLocation(family);

            if (homeGroupLocation != null)
            {
                acHomeAddress.SetValues(homeGroupLocation.Location);
            }

            bool homeSameAsMailing = mailingGroupLocation != null && homeGroupLocation != null && mailingGroupLocation.Id == homeGroupLocation.Id;

            acHomeAddress.Visible = !(cbHomeIsMailing.Checked = homeSameAsMailing);
        }
        /// <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)
        {
            bool hasValidationErrors = false;

            var rockContext = new RockContext();

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

            int parentGroupTypeId = hfParentGroupTypeId.ValueAsInt();

            var groupTypeUIList = new List <GroupType>();

            foreach (var checkinGroupTypeEditor in phCheckinGroupTypes.Controls.OfType <CheckinGroupTypeEditor>().ToList())
            {
                var groupType = checkinGroupTypeEditor.GetCheckinGroupType();
                groupTypeUIList.Add(groupType);
            }

            var groupTypeDBList = new List <GroupType>();

            var groupTypesToDelete = new List <GroupType>();
            var groupsToDelete     = new List <Group>();

            var groupTypesToAddUpdate = new List <GroupType>();
            var groupsToAddUpdate     = new List <Group>();

            GroupType parentGroupTypeDB = groupTypeService.Get(parentGroupTypeId);
            GroupType parentGroupTypeUI = parentGroupTypeDB.Clone(false);

            parentGroupTypeUI.ChildGroupTypes = groupTypeUIList;

            PopulateDeleteLists(groupTypesToDelete, groupsToDelete, parentGroupTypeDB, parentGroupTypeUI);
            PopulateAddUpdateLists(groupTypesToAddUpdate, groupsToAddUpdate, parentGroupTypeUI);

            int binaryFileFieldTypeID = FieldTypeCache.Read(Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid()).Id;
            int binaryFileTypeId      = new BinaryFileTypeService(rockContext).Get(new Guid(Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL)).Id;

            RockTransactionScope.WrapTransaction(() =>
            {
                // delete in reverse order to get deepest child items first
                groupsToDelete.Reverse();
                foreach (var groupToDelete in groupsToDelete)
                {
                    groupService.Delete(groupToDelete);
                }

                // delete in reverse order to get deepest child items first
                groupTypesToDelete.Reverse();
                foreach (var groupTypeToDelete in groupTypesToDelete)
                {
                    groupTypeService.Delete(groupTypeToDelete);
                }

                rockContext.SaveChanges();

                // Add/Update grouptypes and groups that are in the UI
                // Note:  We'll have to save all the groupTypes without changing the DB value of ChildGroupTypes, then come around again and save the ChildGroupTypes
                // since the ChildGroupTypes may not exist in the database yet
                foreach (GroupType groupTypeUI in groupTypesToAddUpdate)
                {
                    GroupType groupTypeDB = groupTypeService.Get(groupTypeUI.Guid);
                    if (groupTypeDB == null)
                    {
                        groupTypeDB      = new GroupType();
                        groupTypeDB.Id   = 0;
                        groupTypeDB.Guid = groupTypeUI.Guid;
                    }

                    groupTypeDB.Name  = groupTypeUI.Name;
                    groupTypeDB.Order = groupTypeUI.Order;
                    groupTypeDB.InheritedGroupTypeId = groupTypeUI.InheritedGroupTypeId;

                    groupTypeDB.Attributes      = groupTypeUI.Attributes;
                    groupTypeDB.AttributeValues = groupTypeUI.AttributeValues;

                    if (groupTypeDB.Id == 0)
                    {
                        groupTypeService.Add(groupTypeDB);
                    }

                    if (!groupTypeDB.IsValid)
                    {
                        hasValidationErrors = true;
                        CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupTypeEditor>().First(a => a.GroupTypeGuid == groupTypeDB.Guid);
                        groupTypeEditor.ForceContentVisible    = true;

                        return;
                    }

                    rockContext.SaveChanges();

                    groupTypeDB.SaveAttributeValues();

                    // get fresh from database to make sure we have Id so we can update the CheckinLabel Attributes
                    groupTypeDB = groupTypeService.Get(groupTypeDB.Guid);

                    // rebuild the CheckinLabel attributes from the UI (brute-force)
                    foreach (var labelAttributeDB in CheckinGroupTypeEditor.GetCheckinLabelAttributes(groupTypeDB))
                    {
                        var attribute = attributeService.Get(labelAttributeDB.Value.Guid);
                        Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                        attributeService.Delete(attribute);
                    }
                    rockContext.SaveChanges();

                    foreach (var checkinLabelAttributeInfo in GroupTypeCheckinLabelAttributesState[groupTypeUI.Guid])
                    {
                        var attribute = new Rock.Model.Attribute();
                        attribute.AttributeQualifiers.Add(new AttributeQualifier {
                            Key = "binaryFileType", Value = binaryFileTypeId.ToString()
                        });
                        attribute.Guid         = Guid.NewGuid();
                        attribute.FieldTypeId  = binaryFileFieldTypeID;
                        attribute.EntityTypeId = EntityTypeCache.GetId(typeof(GroupType));
                        attribute.EntityTypeQualifierColumn = "Id";
                        attribute.EntityTypeQualifierValue  = groupTypeDB.Id.ToString();
                        attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileId.ToString();
                        attribute.Key          = checkinLabelAttributeInfo.AttributeKey;
                        attribute.Name         = checkinLabelAttributeInfo.FileName;

                        if (!attribute.IsValid)
                        {
                            hasValidationErrors = true;
                            CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupTypeEditor>().First(a => a.GroupTypeGuid == groupTypeDB.Guid);
                            groupTypeEditor.ForceContentVisible    = true;

                            return;
                        }

                        attributeService.Add(attribute);
                    }
                    rockContext.SaveChanges();
                }

                // Add/Update Groups
                foreach (var groupUI in groupsToAddUpdate)
                {
                    Group groupDB = groupService.Get(groupUI.Guid);
                    if (groupDB == null)
                    {
                        groupDB      = new Group();
                        groupDB.Guid = groupUI.Guid;
                    }

                    groupDB.Name = groupUI.Name;

                    // delete any GroupLocations that were removed in the UI
                    foreach (var groupLocationDB in groupDB.GroupLocations.ToList())
                    {
                        if (!groupUI.GroupLocations.Select(a => a.LocationId).Contains(groupLocationDB.LocationId))
                        {
                            groupLocationService.Delete(groupLocationDB);
                        }
                    }

                    // add any GroupLocations that were added in the UI
                    foreach (var groupLocationUI in groupUI.GroupLocations)
                    {
                        if (!groupDB.GroupLocations.Select(a => a.LocationId).Contains(groupLocationUI.LocationId))
                        {
                            GroupLocation groupLocationDB = new GroupLocation {
                                LocationId = groupLocationUI.LocationId
                            };
                            groupDB.GroupLocations.Add(groupLocationDB);
                        }
                    }

                    groupDB.Order = groupUI.Order;

                    // get GroupTypeId from database in case the groupType is new
                    groupDB.GroupTypeId     = groupTypeService.Get(groupUI.GroupType.Guid).Id;
                    groupDB.Attributes      = groupUI.Attributes;
                    groupDB.AttributeValues = groupUI.AttributeValues;

                    if (groupDB.Id == 0)
                    {
                        groupService.Add(groupDB);
                    }

                    if (!groupDB.IsValid)
                    {
                        hasValidationErrors             = true;
                        hasValidationErrors             = true;
                        CheckinGroupEditor groupEditor  = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupEditor>().First(a => a.GroupGuid == groupDB.Guid);
                        groupEditor.ForceContentVisible = true;

                        return;
                    }

                    rockContext.SaveChanges();

                    groupDB.SaveAttributeValues();
                }

                /* now that we have all the grouptypes saved, now lets go back and save them again with the current UI ChildGroupTypes */

                // save main parentGroupType with current UI ChildGroupTypes
                parentGroupTypeDB.ChildGroupTypes = new List <GroupType>();
                parentGroupTypeDB.ChildGroupTypes.Clear();
                foreach (var childGroupTypeUI in parentGroupTypeUI.ChildGroupTypes)
                {
                    var childGroupTypeDB = groupTypeService.Get(childGroupTypeUI.Guid);
                    parentGroupTypeDB.ChildGroupTypes.Add(childGroupTypeDB);
                }

                rockContext.SaveChanges();

                // loop thru all the other GroupTypes in the UI and save their childgrouptypes
                foreach (var groupTypeUI in groupTypesToAddUpdate)
                {
                    var groupTypeDB             = groupTypeService.Get(groupTypeUI.Guid);
                    groupTypeDB.ChildGroupTypes = new List <GroupType>();
                    groupTypeDB.ChildGroupTypes.Clear();
                    foreach (var childGroupTypeUI in groupTypeUI.ChildGroupTypes)
                    {
                        var childGroupTypeDB = groupTypeService.Get(childGroupTypeUI.Guid);
                        groupTypeDB.ChildGroupTypes.Add(childGroupTypeDB);
                    }
                }

                rockContext.SaveChanges();
            });

            if (!hasValidationErrors)
            {
                NavigateToParentPage();
            }
        }
Ejemplo n.º 20
0
        public object UpdateProfile(MobilePerson profile)
        {
            var user = UserLoginService.GetCurrentUser(false);

            if (user == null)
            {
                return(ActionStatusCode(System.Net.HttpStatusCode.Unauthorized));
            }

            var personId    = user.PersonId.Value;
            var rockContext = new Data.RockContext();

            var personService      = new PersonService(rockContext);
            var phoneNumberService = new PhoneNumberService(rockContext);
            var person             = personService.Get(personId);

            person.NickName  = person.NickName == person.FirstName ? profile.FirstName : person.NickName;
            person.FirstName = profile.FirstName;
            person.LastName  = profile.LastName;

            var gender = (Model.Gender)profile.Gender;

            if (GenderVisibility != VisibilityTriState.Hidden)
            {
                person.Gender = gender;
            }

            if (GetAttributeValue(AttributeKeys.BirthDateShow).AsBoolean())
            {
                person.SetBirthDate(profile.BirthDate?.Date);
            }

            if (GetAttributeValue(AttributeKeys.CampusShow).AsBoolean())
            {
                person.PrimaryFamily.CampusId = profile.CampusGuid.HasValue ? CampusCache.Get(profile.CampusGuid.Value)?.Id : null;
            }

            if (GetAttributeValue(AttributeKeys.EmailShow).AsBoolean())
            {
                person.Email = profile.Email;
            }

            if (GetAttributeValue(AttributeKeys.MobilePhoneShow).AsBoolean())
            {
                int phoneNumberTypeId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id;

                var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                if (phoneNumber == null)
                {
                    phoneNumber = new PhoneNumber {
                        NumberTypeValueId = phoneNumberTypeId
                    };
                    person.PhoneNumbers.Add(phoneNumber);
                }

                // TODO: What to do with country code?
                phoneNumber.CountryCode = PhoneNumber.CleanNumber("+1");
                phoneNumber.Number      = PhoneNumber.CleanNumber(profile.MobilePhone);

                if (string.IsNullOrWhiteSpace(phoneNumber.Number))
                {
                    person.PhoneNumbers.Remove(phoneNumber);
                    phoneNumberService.Delete(phoneNumber);
                }
            }

            if (GetAttributeValue(AttributeKeys.AddressShow).AsBoolean())
            {
                var addressTypeGuid = SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid();

                var groupLocationService = new GroupLocationService(rockContext);

                var dvHomeAddressType = DefinedValueCache.Get(addressTypeGuid);
                var familyAddress     = groupLocationService.Queryable().Where(l => l.GroupId == person.PrimaryFamily.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id).FirstOrDefault();

                if (familyAddress != null && string.IsNullOrWhiteSpace(profile.HomeAddress.Street1))
                {
                    // delete the current address
                    groupLocationService.Delete(familyAddress);
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(profile.HomeAddress.Street1))
                    {
                        if (familyAddress == null)
                        {
                            familyAddress = new GroupLocation();
                            groupLocationService.Add(familyAddress);
                            familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id;
                            familyAddress.GroupId           = person.PrimaryFamily.Id;
                            familyAddress.IsMailingLocation = true;
                            familyAddress.IsMappedLocation  = true;
                        }
                        else if (familyAddress.Location.Street1 != profile.HomeAddress.Street1)
                        {
                            // user clicked move so create a previous address
                            var previousAddress = new GroupLocation();
                            groupLocationService.Add(previousAddress);

                            var previousAddressValue = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                            if (previousAddressValue != null)
                            {
                                previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                previousAddress.GroupId = person.PrimaryFamily.Id;

                                Location previousAddressLocation = new Location
                                {
                                    Street1    = familyAddress.Location.Street1,
                                    Street2    = familyAddress.Location.Street2,
                                    City       = familyAddress.Location.City,
                                    State      = familyAddress.Location.State,
                                    PostalCode = familyAddress.Location.PostalCode,
                                    Country    = familyAddress.Location.Country
                                };

                                previousAddress.Location = previousAddressLocation;
                            }
                        }

                        // TODO: ???
                        // familyAddress.IsMailingLocation = cbIsMailingAddress.Checked;
                        // familyAddress.IsMappedLocation = cbIsPhysicalAddress.Checked;
                        familyAddress.Location = new LocationService(rockContext).Get(
                            profile.HomeAddress.Street1,
                            string.Empty,
                            profile.HomeAddress.City,
                            profile.HomeAddress.State,
                            profile.HomeAddress.PostalCode,
                            profile.HomeAddress.Country,
                            person.PrimaryFamily,
                            true);

                        // since there can only be one mapped location, set the other locations to not mapped
                        if (familyAddress.IsMappedLocation)
                        {
                            var groupLocations = groupLocationService.Queryable()
                                                 .Where(l => l.GroupId == person.PrimaryFamily.Id && l.Id != familyAddress.Id).ToList();

                            foreach (var groupLocation in groupLocations)
                            {
                                groupLocation.IsMappedLocation = false;
                            }
                        }

                        rockContext.SaveChanges();
                    }
                }
            }

            rockContext.SaveChanges();

            var mobilePerson = MobileHelper.GetMobilePerson(person, MobileHelper.GetCurrentApplicationSite());

            mobilePerson.AuthToken = MobileHelper.GetAuthenticationToken(user.UserName);

            return(ActionOk(mobilePerson));
        }
        /// <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)
        {
            if (GetAttributeValue(AttributeKeys.DisplayTerms).AsBoolean() && !cbTOS.Checked)
            {
                nbTOS.Visible = true;
                return;
            }

            var rockContext   = new RockContext();
            var personService = new PersonService(rockContext);

            var person = GetPerson(personService);

            var personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias));

            if (person.Id != 0)
            {
                var changeRequest = new ChangeRequest
                {
                    EntityTypeId     = personAliasEntityType.Id,
                    EntityId         = person.PrimaryAliasId ?? 0,
                    RequestorAliasId = CurrentPersonAliasId ?? 0
                };


                if (person.PhotoId != imgPhoto.BinaryFileId)
                {
                    changeRequest.EvaluatePropertyChange(person, "PhotoId", imgPhoto.BinaryFileId);
                    if (person.Photo != null)
                    {
                        changeRequest.EvaluatePropertyChange(person.Photo, "IsTemporary", true, true);
                    }
                }

                changeRequest.EvaluatePropertyChange(person, "TitleValue", DefinedValueCache.Get(ddlTitle.SelectedValueAsInt() ?? 0));
                changeRequest.EvaluatePropertyChange(person, "FirstName", tbFirstName.Text);
                changeRequest.EvaluatePropertyChange(person, "NickName", tbNickName.Text);
                changeRequest.EvaluatePropertyChange(person, "LastName", tbLastName.Text);
                changeRequest.EvaluatePropertyChange(person, "SuffixValue", DefinedValueCache.Get(ddlSuffix.SelectedValueAsInt() ?? 0));

                var birthMonth = person.BirthMonth;
                var birthDay   = person.BirthDay;
                var birthYear  = person.BirthYear;

                var birthday = bpBirthDay.SelectedDate;
                if (birthday.HasValue)
                {
                    // If setting a future birth date, subtract a century until birth date is not greater than today.
                    var today = RockDateTime.Today;
                    while (birthday.Value.CompareTo(today) > 0)
                    {
                        birthday = birthday.Value.AddYears(-100);
                    }

                    changeRequest.EvaluatePropertyChange(person, "BirthMonth", birthday.Value.Month);
                    changeRequest.EvaluatePropertyChange(person, "BirthDay", birthday.Value.Day);

                    if (birthday.Value.Year != DateTime.MinValue.Year)
                    {
                        changeRequest.EvaluatePropertyChange(person, "BirthYear", birthday.Value.Year);
                    }
                    else
                    {
                        changeRequest.EvaluatePropertyChange(person, "BirthYear", ( int? )null);
                    }
                }

                if (ddlGradePicker.Visible)
                {
                    changeRequest.EvaluatePropertyChange(person, "GraduationYear", ypGraduation.SelectedYear);
                }
                changeRequest.EvaluatePropertyChange(person, "Gender", rblGender.SelectedValue.ConvertToEnum <Gender>());

                var primaryFamilyMembers = person.GetFamilyMembers(true).Where(m => m.PersonId == person.Id).ToList();
                foreach (var member in primaryFamilyMembers)
                {
                    changeRequest.EvaluatePropertyChange(member, "GroupRoleId", rblRole.SelectedValue.AsInteger(), true);
                }

                var primaryFamily       = person.GetFamily(rockContext);
                var familyChangeRequest = new ChangeRequest
                {
                    EntityTypeId     = EntityTypeCache.Get(typeof(Group)).Id,
                    EntityId         = primaryFamily.Id,
                    RequestorAliasId = CurrentPersonAliasId ?? 0
                };

                // update campus
                bool showCampus = GetAttributeValue("ShowCampusSelector").AsBoolean();
                if (showCampus)
                {
                    // Only update campus for adults
                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);
                    var adultGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid();
                    var adultRole = groupTypeRoleService.Get(adultGuid);
                    if (rblRole.SelectedValue.AsInteger() == adultRole.Id)
                    {
                        familyChangeRequest.EvaluatePropertyChange(primaryFamily, "CampusId", cpCampus.SelectedCampusId);
                    }
                }

                //Evaluate PhoneNumbers
                bool showPhoneNumbers = GetAttributeValue("ShowPhoneNumbers").AsBoolean();
                if (showPhoneNumbers)
                {
                    var  phoneNumberTypeIds = new List <int>();
                    var  phoneNumbersScreen = new List <PhoneNumber>();
                    bool smsSelected        = false;
                    foreach (RepeaterItem item in rContactInfo.Items)
                    {
                        HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                        PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                        CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                        CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                        if (hfPhoneType != null &&
                            pnbPhone != null &&
                            cbSms != null &&
                            cbUnlisted != null)
                        {
                            int phoneNumberTypeId;
                            if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                            {
                                var    phoneNumberList = person.PhoneNumbers.Where(n => n.NumberTypeValueId == phoneNumberTypeId).ToList();
                                var    phoneNumber     = phoneNumberList.FirstOrDefault(pn => pn.Number == PhoneNumber.CleanNumber(pnbPhone.Number));
                                string oldPhoneNumber  = string.Empty;

                                if (phoneNumber == null && pnbPhone.Number.IsNotNullOrWhiteSpace())   //Add number
                                {
                                    phoneNumber = new PhoneNumber
                                    {
                                        PersonId           = person.Id,
                                        NumberTypeValueId  = phoneNumberTypeId,
                                        CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                        IsMessagingEnabled = !smsSelected && cbSms.Checked,
                                        Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                                    };
                                    var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number);
                                    changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment);
                                    phoneNumbersScreen.Add(phoneNumber);
                                }
                                else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace())   // update number
                                {
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true);
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true);
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true);
                                    phoneNumbersScreen.Add(phoneNumber);
                                }
                            }
                        }
                    }
                    //Remove old phone numbers or changed
                    var phoneNumbersToRemove = person.PhoneNumbers
                                               .Where(n => !phoneNumbersScreen.Any(n2 => n2.Number == n.Number && n2.NumberTypeValueId == n.NumberTypeValueId)).ToList();

                    foreach (var number in phoneNumbersToRemove)
                    {
                        var phoneComment = string.Format("{0}: {1}.", number.NumberTypeValue.Value, number.NumberFormatted);
                        changeRequest.DeleteEntity(number, true, phoneComment);
                    }
                }

                changeRequest.EvaluatePropertyChange(person, "Email", tbEmail.Text.Trim());
                changeRequest.EvaluatePropertyChange(person, "EmailPreference", rblEmailPreference.SelectedValueAsEnum <EmailPreference>());
                changeRequest.EvaluatePropertyChange(person, "CommunicationPreference", rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>());

                // if they used the ImageEditor, and cropped it, the non-cropped file is still in BinaryFile. So clean it up
                if (imgPhoto.CropBinaryFileId.HasValue)
                {
                    if (imgPhoto.CropBinaryFileId != person.PhotoId)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(imgPhoto.CropBinaryFileId.Value);
                        if (binaryFile != null && binaryFile.IsTemporary)
                        {
                            string errorMessage;
                            if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                            {
                                binaryFileService.Delete(binaryFile);
                                rockContext.SaveChanges();
                            }
                        }
                    }
                }


                // save family information
                if (pnlAddress.Visible)
                {
                    var      currentLocation = person.GetHomeLocation();
                    Location location        = new Location
                    {
                        Street1    = acAddress.Street1,
                        Street2    = acAddress.Street2,
                        City       = acAddress.City,
                        State      = acAddress.State,
                        PostalCode = acAddress.PostalCode,
                    };
                    var globalAttributesCache = GlobalAttributesCache.Get();
                    location.Country = globalAttributesCache.OrganizationCountry;
                    location.Country = string.IsNullOrWhiteSpace(location.Country) ? "US" : location.Country;

                    if ((currentLocation == null && location.Street1.IsNotNullOrWhiteSpace()) ||
                        (currentLocation != null && currentLocation.Street1 != location.Street1))
                    {
                        LocationService locationService = new LocationService(rockContext);
                        locationService.Add(location);
                        rockContext.SaveChanges();

                        var previousLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                        var homeLocationType     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());

                        GroupLocation groupLocation = new GroupLocation
                        {
                            CreatedByPersonAliasId  = CurrentPersonAliasId,
                            ModifiedByPersonAliasId = CurrentPersonAliasId,
                            GroupId    = primaryFamily.Id,
                            LocationId = location.Id,
                            GroupLocationTypeValueId = homeLocationType.Id,
                            IsMailingLocation        = true,
                            IsMappedLocation         = true
                        };

                        var newGroupLocation = familyChangeRequest.AddEntity(groupLocation, rockContext, true, location.ToString());

                        var homelocations = primaryFamily.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationType.Id);
                        foreach (var homelocation in homelocations)
                        {
                            familyChangeRequest.EvaluatePropertyChange(
                                homelocation,
                                "GroupLocationTypeValue",
                                previousLocationType,
                                true,
                                homelocation.Location.ToString());

                            familyChangeRequest.EvaluatePropertyChange(
                                homelocation,
                                "IsMailingLocation",
                                false,
                                true,
                                homelocation.Location.ToString());
                        }
                    }
                }

                // Handle both Child and Adult attributes together here
                var attributeGuids = GetAttributeValue(AttributeKeys.PersonAttributesAdult).SplitDelimitedValues().AsGuidList();
                attributeGuids.AddRange(GetAttributeValue(AttributeKeys.PersonAttributesChild).SplitDelimitedValues().AsGuidList());
                if (attributeGuids.Count > 0)
                {
                    person.LoadAttributes();
                    Helper.GetEditValues(phAttributes, person);
                    changeRequest.EvaluateAttributes(person);
                }

                List <string> errors;

                if (changeRequest.ChangeRecords.Any() ||
                    (!familyChangeRequest.ChangeRecords.Any() && tbComments.Text.IsNotNullOrWhiteSpace()))
                {
                    changeRequest.RequestorComment = tbComments.Text;
                    ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                    changeRequestService.Add(changeRequest);
                    rockContext.SaveChanges();

                    changeRequest.CompleteChanges(rockContext, out errors);
                }

                if (familyChangeRequest.ChangeRecords.Any())
                {
                    familyChangeRequest.RequestorComment = tbComments.Text;
                    ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                    changeRequestService.Add(familyChangeRequest);
                    rockContext.SaveChanges();
                    familyChangeRequest.CompleteChanges(rockContext, out errors);
                }
            }
            else
            {
                var primaryFamily = CurrentPerson.GetFamily(rockContext);

                person.PhotoId = imgPhoto.BinaryFileId;

                if (imgPhoto.BinaryFileId.HasValue)
                {
                    BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                    var binaryFile = binaryFileService.Get(imgPhoto.BinaryFileId.Value);
                    binaryFile.IsTemporary = false;
                }

                person.FirstName     = tbFirstName.Text;
                person.NickName      = tbNickName.Text;
                person.LastName      = tbLastName.Text;
                person.TitleValueId  = ddlTitle.SelectedValue.AsIntegerOrNull();
                person.SuffixValueId = ddlSuffix.SelectedValue.AsIntegerOrNull();
                var birthday = bpBirthDay.SelectedDate;
                if (birthday.HasValue)
                {
                    // If setting a future birth date, subtract a century until birth date is not greater than today.
                    var today = RockDateTime.Today;
                    while (birthday.Value.CompareTo(today) > 0)
                    {
                        birthday = birthday.Value.AddYears(-100);
                    }

                    person.BirthMonth = birthday.Value.Month;
                    person.BirthDay   = birthday.Value.Day;

                    if (birthday.Value.Year != DateTime.MinValue.Year)
                    {
                        person.BirthYear = birthday.Value.Year;
                    }
                    else
                    {
                        person.BirthYear = null;
                    }
                }

                person.Gender          = rblGender.SelectedValue.ConvertToEnum <Gender>();
                person.Email           = tbEmail.Text;
                person.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();

                if (ddlGradePicker.Visible)
                {
                    person.GraduationYear = ypGraduation.SelectedYear;
                }


                GroupMember groupMember = new GroupMember
                {
                    PersonId    = person.Id,
                    GroupId     = primaryFamily.Id,
                    GroupRoleId = rblRole.SelectedValue.AsInteger()
                };

                PersonService.AddPersonToFamily(person, true, primaryFamily.Id, rblRole.SelectedValue.AsInteger(), rockContext);

                PhoneNumberService phoneNumberService = new PhoneNumberService(rockContext);

                foreach (RepeaterItem item in rContactInfo.Items)
                {
                    HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                    PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                    CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                    CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                    if (hfPhoneType != null &&
                        pnbPhone != null &&
                        cbSms != null &&
                        cbUnlisted != null &&
                        pnbPhone.Number.IsNotNullOrWhiteSpace())
                    {
                        int phoneNumberTypeId;
                        if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                        {
                            var phoneNumber = new PhoneNumber
                            {
                                PersonId           = person.Id,
                                NumberTypeValueId  = phoneNumberTypeId,
                                CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                IsMessagingEnabled = cbSms.Checked,
                                Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                            };
                            phoneNumberService.Add(phoneNumber);
                        }
                    }
                }
                rockContext.SaveChanges();

                var changeRequest = new ChangeRequest
                {
                    EntityTypeId     = personAliasEntityType.Id,
                    EntityId         = person.PrimaryAliasId ?? 0,
                    RequestorAliasId = CurrentPersonAliasId ?? 0,
                    RequestorComment = "Added as new person from My Account."
                };

                if (tbComments.Text.IsNotNullOrWhiteSpace())
                {
                    changeRequest.RequestorComment += "<br><br>Comment: " + tbComments.Text;
                }

                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(changeRequest);
                rockContext.SaveChanges();

                List <string> errors;
                changeRequest.CompleteChanges(rockContext, out errors);
            }

            NavigateToParentPage();
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Creates the person.
        /// </summary>
        /// <returns></returns>
        private Person CreatePerson()
        {
            var rockContext = new RockContext();

            DefinedValueCache dvcConnectionStatus = DefinedValueCache.Read(GetAttributeValue("ConnectionStatus").AsGuid());
            DefinedValueCache dvcRecordStatus     = DefinedValueCache.Read(GetAttributeValue("RecordStatus").AsGuid());

            Person person = new Person();

            person.FirstName         = tbFirstName.Text;
            person.LastName          = tbLastName.Text;
            person.Email             = tbEmail.Text;
            person.IsEmailActive     = true;
            person.EmailPreference   = EmailPreference.EmailAllowed;
            person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
            if (dvcConnectionStatus != null)
            {
                person.ConnectionStatusValueId = dvcConnectionStatus.Id;
            }

            if (dvcRecordStatus != null)
            {
                person.RecordStatusValueId = dvcRecordStatus.Id;
            }

            switch (ddlGender.SelectedValue)
            {
            case "M":
                person.Gender = Gender.Male;
                break;

            case "F":
                person.Gender = Gender.Female;
                break;

            default:
                person.Gender = Gender.Unknown;
                break;
            }

            var birthday = bdaypBirthDay.SelectedDate;

            if (birthday.HasValue)
            {
                person.BirthMonth = birthday.Value.Month;
                person.BirthDay   = birthday.Value.Day;
                if (birthday.Value.Year != DateTime.MinValue.Year)
                {
                    person.BirthYear = birthday.Value.Year;
                }
            }

            bool smsSelected = false;

            foreach (RepeaterItem item in rPhoneNumbers.Items)
            {
                HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                {
                    int phoneNumberTypeId;
                    if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                    {
                        var phoneNumber = new PhoneNumber {
                            NumberTypeValueId = phoneNumberTypeId
                        };
                        person.PhoneNumbers.Add(phoneNumber);
                        phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                        phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);

                        // Only allow one number to have SMS selected
                        if (smsSelected)
                        {
                            phoneNumber.IsMessagingEnabled = false;
                        }
                        else
                        {
                            phoneNumber.IsMessagingEnabled = cbSms.Checked;
                            smsSelected = cbSms.Checked;
                        }

                        phoneNumber.IsUnlisted = cbUnlisted.Checked;
                    }
                }
            }

            PersonService.SaveNewPerson(person, rockContext, null, false);

            // save address
            if (pnlAddress.Visible)
            {
                if (acAddress.IsValid && !string.IsNullOrWhiteSpace(acAddress.Street1) && !string.IsNullOrWhiteSpace(acAddress.City) && !string.IsNullOrWhiteSpace(acAddress.PostalCode))
                {
                    Guid locationTypeGuid = GetAttributeValue("LocationType").AsGuid();
                    if (locationTypeGuid != Guid.Empty)
                    {
                        Guid                 familyGroupTypeGuid  = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
                        GroupService         groupService         = new GroupService(rockContext);
                        GroupLocationService groupLocationService = new GroupLocationService(rockContext);
                        var family = groupService.Queryable().Where(g => g.GroupType.Guid == familyGroupTypeGuid && g.Members.Any(m => m.PersonId == person.Id)).FirstOrDefault();

                        var groupLocation = new GroupLocation();
                        groupLocation.GroupId = family.Id;
                        groupLocationService.Add(groupLocation);

                        var location = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                        groupLocation.Location = location;

                        groupLocation.GroupLocationTypeValueId = DefinedValueCache.Read(locationTypeGuid).Id;
                        groupLocation.IsMailingLocation        = true;
                        groupLocation.IsMappedLocation         = true;

                        rockContext.SaveChanges();
                    }
                }
            }

            return(person);
        }
        /// <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 )
        {
            var rockContext = new RockContext();
            rockContext.WrapTransaction( () =>
            {
                var personService = new PersonService( rockContext );
                var changes = new List<string>();
                Person business = null;

                if ( int.Parse( hfBusinessId.Value ) != 0 )
                {
                    business = personService.Get( int.Parse( hfBusinessId.Value ) );
                }

                if ( business == null )
                {
                    business = new Person();
                    personService.Add( business );
                }

                // Business Name
                History.EvaluateChange( changes, "Last Name", business.LastName, tbBusinessName.Text );
                business.LastName = tbBusinessName.Text;

                // Phone Number
                var businessPhoneTypeId = new DefinedValueService( rockContext ).GetByGuid( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK ) ).Id;

                string oldPhoneNumber = string.Empty;
                string newPhoneNumber = string.Empty;

                var phoneNumber = business.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == businessPhoneTypeId );
                if ( phoneNumber != null )
                {
                    oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }

                if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) )
                {
                    if ( phoneNumber == null )
                    {
                        phoneNumber = new PhoneNumber { NumberTypeValueId = businessPhoneTypeId };
                        business.PhoneNumbers.Add( phoneNumber );
                    }
                    phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode );
                    phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number );
                    phoneNumber.IsMessagingEnabled = cbSms.Checked;
                    phoneNumber.IsUnlisted = cbUnlisted.Checked;

                    newPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }
                else
                {
                    if ( phoneNumber != null )
                    {
                        business.PhoneNumbers.Remove( phoneNumber );
                        new PhoneNumberService( rockContext ).Delete( phoneNumber );
                    }
                }

                History.EvaluateChange(
                    changes,
                    string.Format( "{0} Phone", DefinedValueCache.GetName( businessPhoneTypeId ) ),
                    oldPhoneNumber,
                    newPhoneNumber );

                // Record Type - this is always "business". it will never change.
                business.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid() ).Id;

                // Record Status
                int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( business.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) );
                business.RecordStatusValueId = newRecordStatusId;

                // Record Status Reason
                int? newRecordStatusReasonId = null;
                if ( business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id )
                {
                    newRecordStatusReasonId = ddlReason.SelectedValueAsInt();
                }

                History.EvaluateChange( changes, "Record Status Reason", DefinedValueCache.GetName( business.RecordStatusReasonValueId ), DefinedValueCache.GetName( newRecordStatusReasonId ) );
                business.RecordStatusReasonValueId = newRecordStatusReasonId;

                // Email
                business.IsEmailActive = true;
                History.EvaluateChange( changes, "Email", business.Email, tbEmail.Text );
                business.Email = tbEmail.Text.Trim();

                var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum<EmailPreference>();
                History.EvaluateChange( changes, "EmailPreference", business.EmailPreference, newEmailPreference );
                business.EmailPreference = newEmailPreference;

                if ( business.IsValid )
                {
                    if ( rockContext.SaveChanges() > 0 )
                    {
                        if ( changes.Any() )
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof( Person ),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                business.Id,
                                changes );
                        }
                    }
                }

                // Add/Update Family Group
                var familyGroupType = GroupTypeCache.GetFamilyGroupType();
                int adultRoleId = familyGroupType.Roles
                    .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) )
                    .Select( r => r.Id )
                    .FirstOrDefault();
                var adultFamilyMember = UpdateGroupMember( business.Id, familyGroupType, business.LastName + " Business", ddlCampus.SelectedValueAsInt(), adultRoleId, rockContext );
                business.GivingGroup = adultFamilyMember.Group;

                // Add/Update Known Relationship Group Type
                var knownRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid() );
                int knownRelationshipOwnerRoleId = knownRelationshipGroupType.Roles
                    .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid() ) )
                    .Select( r => r.Id )
                    .FirstOrDefault();
                var knownRelationshipOwner = UpdateGroupMember( business.Id, knownRelationshipGroupType, "Known Relationship", null, knownRelationshipOwnerRoleId, rockContext );

                // Add/Update Implied Relationship Group Type
                var impliedRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS.AsGuid() );
                int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles
                    .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid() ) )
                    .Select( r => r.Id )
                    .FirstOrDefault();
                var impliedRelationshipOwner = UpdateGroupMember( business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext );

                rockContext.SaveChanges();

                // Every business should have an alias record with same id.  If it's missing, create it
                if ( !business.Aliases.Any( a => a.AliasPersonId == business.Id ) )
                {
                    // refetch the business to make sure we have an Id
                    business = personService.Get( business.Id );
                    if ( business != null )
                    {
                        business.Aliases.Add( new PersonAlias { AliasPersonId = business.Id, AliasPersonGuid = business.Guid } );
                        rockContext.SaveChanges();
                    }
                }

                // Location
                int workLocationTypeId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK ).Id;

                var groupLocationService = new GroupLocationService( rockContext );
                var workLocation = groupLocationService.Queryable( "Location" )
                    .Where( gl =>
                        gl.GroupId == adultFamilyMember.Group.Id &&
                        gl.GroupLocationTypeValueId == workLocationTypeId )
                    .FirstOrDefault();

                if ( string.IsNullOrWhiteSpace( acAddress.Street1 ) )
                {
                    if ( workLocation != null )
                    {
                        groupLocationService.Delete( workLocation );
                        History.EvaluateChange( changes, "Address", workLocation.Location.ToString(), string.Empty );
                    }
                }
                else
                {
                    var oldValue = string.Empty;

                    var newLocation = new LocationService( rockContext ).Get(
                        acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country );

                    if ( workLocation != null )
                    {
                        oldValue = workLocation.Location.ToString();
                    }
                    else
                    {
                        workLocation = new GroupLocation();
                        groupLocationService.Add( workLocation );
                        workLocation.GroupId = adultFamilyMember.Group.Id;
                        workLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                    workLocation.Location = newLocation;

                    History.EvaluateChange( changes, "Address", oldValue, newLocation.ToString() );
                }

                rockContext.SaveChanges();

                hfBusinessId.Value = business.Id.ToString();
            } );

            ShowSummary( hfBusinessId.Value.AsInteger() );
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var attribute = AttributeCache.Read(GetAttributeValue(action, "PersonAttribute").AsGuid(), rockContext);

            if (attribute != null)
            {
                var      mergeFields        = GetMergeFields(action);
                string   firstName          = GetAttributeValue(action, "FirstName", true).ResolveMergeFields(mergeFields);
                string   lastName           = GetAttributeValue(action, "LastName", true).ResolveMergeFields(mergeFields);
                string   email              = GetAttributeValue(action, "Email", true).ResolveMergeFields(mergeFields);
                string   phone              = GetAttributeValue(action, "Phone", true).ResolveMergeFields(mergeFields);
                DateTime?dateofBirth        = GetAttributeValue(action, "DOB", true).AsDateTime();
                Guid?    addressGuid        = GetAttributeValue(action, "Address", true).AsGuidOrNull();
                Guid?    familyOrPersonGuid = GetAttributeValue(action, "FamilyAttribute", true).AsGuidOrNull();
                Location address            = null;
                // Set the street and postal code if we have an address
                if (addressGuid.HasValue)
                {
                    LocationService addressService = new LocationService(rockContext);
                    address = addressService.Get(addressGuid.Value);
                }


                if (string.IsNullOrWhiteSpace(firstName) ||
                    string.IsNullOrWhiteSpace(lastName) ||
                    (string.IsNullOrWhiteSpace(email) &&
                     string.IsNullOrWhiteSpace(phone) &&
                     !dateofBirth.HasValue &&
                     (address == null || address != null && string.IsNullOrWhiteSpace(address.Street1)))
                    )
                {
                    errorMessages.Add("First Name, Last Name, and one of Email, Phone, DoB, or Address Street are required. One or more of these values was not provided!");
                }
                else
                {
                    Rock.Model.Person person      = null;
                    PersonAlias       personAlias = null;
                    var personService             = new PersonService(rockContext);
                    var people = personService.GetByMatch(firstName, lastName, dateofBirth, email, phone, address?.Street1, address?.PostalCode).ToList();
                    if (people.Count == 1 &&
                        // Make sure their email matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (string.IsNullOrWhiteSpace(email) ||
                         (people.First().Email != null &&
                          email.ToLower().Trim() == people.First().Email.ToLower().Trim()))
                        )
                    {
                        person      = people.First();
                        personAlias = person.PrimaryAlias;
                    }
                    else if (!GetAttributeValue(action, "MatchOnly").AsBoolean())
                    {
                        // Add New Person
                        person               = new Rock.Model.Person();
                        person.FirstName     = firstName;
                        person.LastName      = lastName;
                        person.IsEmailActive = true;
                        person.Email         = email;
                        if (dateofBirth.HasValue)
                        {
                            person.BirthDay   = dateofBirth.Value.Day;
                            person.BirthMonth = dateofBirth.Value.Month;
                            person.BirthYear  = dateofBirth.Value.Year;
                        }
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;

                        var defaultConnectionStatus = DefinedValueCache.Read(GetAttributeValue(action, "DefaultConnectionStatus").AsGuid());
                        if (defaultConnectionStatus != null)
                        {
                            person.ConnectionStatusValueId = defaultConnectionStatus.Id;
                        }

                        var defaultRecordStatus = DefinedValueCache.Read(GetAttributeValue(action, "DefaultRecordStatus").AsGuid());
                        if (defaultRecordStatus != null)
                        {
                            person.RecordStatusValueId = defaultRecordStatus.Id;
                        }

                        var defaultCampus = CampusCache.Read(GetAttributeValue(action, "DefaultCampus", true).AsGuid());

                        // Get the default family if applicable
                        Group family = null;
                        if (familyOrPersonGuid.HasValue)
                        {
                            PersonAliasService personAliasService = new PersonAliasService(rockContext);
                            family = personAliasService.Get(familyOrPersonGuid.Value)?.Person?.GetFamily();
                            if (family == null)
                            {
                                GroupService groupService = new GroupService(rockContext);
                                family = groupService.Get(familyOrPersonGuid.Value);
                            }
                        }
                        var familyGroup = SaveNewPerson(person, family, (defaultCampus != null ? defaultCampus.Id : ( int? )null), rockContext);
                        if (familyGroup != null && familyGroup.Members.Any())
                        {
                            personAlias = person.PrimaryAlias;

                            // If we have an address, go ahead and save it here.
                            if (address != null)
                            {
                                GroupLocation location = new GroupLocation();
                                location.GroupLocationTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;
                                location.Location = address;
                                familyGroup.GroupLocations.Add(location);
                            }
                        }
                    }

                    // Save/update the phone number
                    if (!string.IsNullOrWhiteSpace(phone))
                    {
                        List <string> changes    = new List <string>();
                        var           numberType = DefinedValueCache.Read(GetAttributeValue(action, "DefaultPhoneNumberType").AsGuid());
                        if (numberType != null)
                        {
                            // gets value indicating if phone number is unlisted
                            string unlistedValue     = GetAttributeValue(action, "Unlisted");
                            Guid?  unlistedValueGuid = unlistedValue.AsGuidOrNull();
                            if (unlistedValueGuid.HasValue)
                            {
                                unlistedValue = action.GetWorklowAttributeValue(unlistedValueGuid.Value);
                            }
                            else
                            {
                                unlistedValue = unlistedValue.ResolveMergeFields(GetMergeFields(action));
                            }
                            bool unlisted = unlistedValue.AsBoolean();

                            // gets value indicating if messaging should be enabled for phone number
                            string smsEnabledValue     = GetAttributeValue(action, "MessagingEnabled");
                            Guid?  smsEnabledValueGuid = smsEnabledValue.AsGuidOrNull();
                            if (smsEnabledValueGuid.HasValue)
                            {
                                smsEnabledValue = action.GetWorklowAttributeValue(smsEnabledValueGuid.Value);
                            }
                            else
                            {
                                smsEnabledValue = smsEnabledValue.ResolveMergeFields(GetMergeFields(action));
                            }
                            bool smsEnabled = smsEnabledValue.AsBoolean();


                            var    phoneModel     = person.PhoneNumbers.FirstOrDefault(p => p.NumberTypeValueId == numberType.Id);
                            string oldPhoneNumber = phoneModel != null ? phoneModel.NumberFormattedWithCountryCode : string.Empty;
                            string newPhoneNumber = PhoneNumber.CleanNumber(phone);

                            if (newPhoneNumber != string.Empty && newPhoneNumber != oldPhoneNumber)
                            {
                                if (phoneModel == null)
                                {
                                    phoneModel = new PhoneNumber();
                                    person.PhoneNumbers.Add(phoneModel);
                                    phoneModel.NumberTypeValueId = numberType.Id;
                                }
                                else
                                {
                                    oldPhoneNumber = phoneModel.NumberFormattedWithCountryCode;
                                }
                                phoneModel.Number             = newPhoneNumber;
                                phoneModel.IsUnlisted         = unlisted;
                                phoneModel.IsMessagingEnabled = smsEnabled;

                                History.EvaluateChange(
                                    changes,
                                    string.Format("{0} Phone", numberType.Value),
                                    oldPhoneNumber,
                                    phoneModel.NumberFormattedWithCountryCode);
                            }
                        }
                    }

                    if (person != null && personAlias != null)
                    {
                        SetWorkflowAttributeValue(action, attribute.Guid, personAlias.Guid.ToString());
                        action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, person.FullName));
                        return(true);
                    }
                    else if (!GetAttributeValue(action, "MatchOnly").AsBoolean())
                    {
                        errorMessages.Add("Person or Primary Alias could not be determined!");
                    }
                }
            }
            else
            {
                errorMessages.Add("Person Attribute could not be found!");
            }

            if (errorMessages.Any())
            {
                errorMessages.ForEach(m => action.AddLogEntry(m, true));
                return(false);
            }

            return(true);
        }
Ejemplo n.º 25
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            RockContext rockContext           = new RockContext();
            var         person                = GetPerson();
            var         personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias));
            var         changeRequest         = new ChangeRequest
            {
                EntityTypeId     = personAliasEntityType.Id,
                EntityId         = person.PrimaryAliasId ?? 0,
                RequestorAliasId = CurrentPersonAliasId ?? 0,
                RequestorComment = tbComments.Text
            };

            changeRequest.EvaluatePropertyChange(person, "PhotoId", iuPhoto.BinaryFileId);
            changeRequest.EvaluatePropertyChange(person, "TitleValue", DefinedValueCache.Get(ddlTitle.SelectedValueAsInt() ?? 0));
            changeRequest.EvaluatePropertyChange(person, "FirstName", tbFirstName.Text);
            changeRequest.EvaluatePropertyChange(person, "NickName", tbNickName.Text);
            changeRequest.EvaluatePropertyChange(person, "MiddleName", tbMiddleName.Text);
            changeRequest.EvaluatePropertyChange(person, "LastName", tbLastName.Text);
            changeRequest.EvaluatePropertyChange(person, "SuffixValue", DefinedValueCache.Get(ddlSuffix.SelectedValueAsInt() ?? 0));

            var families = person.GetFamilies();

            if (families.Count() == 1)
            {
                var groupMember = person.PrimaryFamily.Members.Where(gm => gm.PersonId == person.Id).FirstOrDefault();
                if (groupMember != null)
                {
                    GroupTypeRole        groupTypeRole        = null;
                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);
                    if (ddlFamilyRole.SelectedValue == "A")
                    {
                        groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid());
                    }
                    else if (ddlFamilyRole.SelectedValue == "C")
                    {
                        groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid());
                    }
                    changeRequest.EvaluatePropertyChange(groupMember, "GroupRole", groupTypeRole, true);
                }
            }

            //Evaluate PhoneNumbers
            var  phoneNumberTypeIds = new List <int>();
            bool smsSelected        = false;

            foreach (RepeaterItem item in rContactInfo.Items)
            {
                HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                if (hfPhoneType != null &&
                    pnbPhone != null &&
                    cbSms != null &&
                    cbUnlisted != null)
                {
                    int phoneNumberTypeId;
                    if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                    {
                        var    phoneNumber    = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                        string oldPhoneNumber = string.Empty;
                        if (phoneNumber == null && pnbPhone.Number.IsNotNullOrWhiteSpace())   //Add number
                        {
                            phoneNumber = new PhoneNumber
                            {
                                PersonId           = person.Id,
                                NumberTypeValueId  = phoneNumberTypeId,
                                CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                IsMessagingEnabled = !smsSelected && cbSms.Checked,
                                Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                            };
                            var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number);
                            changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNullOrWhiteSpace())   // delete number
                        {
                            var phoneComment = string.Format("{0}: {1}.", phoneNumber.NumberTypeValue.Value, phoneNumber.NumberFormatted);
                            changeRequest.DeleteEntity(phoneNumber, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace())   // update number
                        {
                            changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true);
                        }

                        if (hfPhoneType.Value.AsInteger() == DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()))
                        {
                            var validationInfo = ValidateMobilePhoneNumber(PhoneNumber.CleanNumber(pnbPhone.Number));
                            if (validationInfo.IsNotNullOrWhiteSpace())
                            {
                                changeRequest.RequestorComment += "<h4>Dynamically Generated Warnings:</h4>" + validationInfo;
                            }
                        }
                    }
                }
            }

            changeRequest.EvaluatePropertyChange(person, "Email", tbEmail.Text);
            changeRequest.EvaluatePropertyChange(person, "IsEmailActive", cbIsEmailActive.Checked);
            changeRequest.EvaluatePropertyChange(person, "EmailPreference", rblEmailPreference.SelectedValueAsEnum <EmailPreference>());
            changeRequest.EvaluatePropertyChange(person, "CommunicationPreference", rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>());


            var birthday = bpBirthday.SelectedDate;

            if (birthday.HasValue)
            {
                changeRequest.EvaluatePropertyChange(person, "BirthMonth", birthday.Value.Month);
                changeRequest.EvaluatePropertyChange(person, "BirthDay", birthday.Value.Day);
                if (birthday.Value.Year != DateTime.MinValue.Year)
                {
                    changeRequest.EvaluatePropertyChange(person, "BirthYear", birthday.Value.Year);
                }
                else
                {
                    int?year = null;
                    changeRequest.EvaluatePropertyChange(person, "BirthYear", year);
                }
            }

            changeRequest.EvaluatePropertyChange(person, "Gender", ddlGender.SelectedValueAsEnum <Gender>());
            changeRequest.EvaluatePropertyChange(person, "MaritalStatusValue", DefinedValueCache.Get(ddlMaritalStatus.SelectedValueAsInt() ?? 0));
            changeRequest.EvaluatePropertyChange(person, "AnniversaryDate", dpAnniversaryDate.SelectedDate);
            changeRequest.EvaluatePropertyChange(person, "GraduationYear", ypGraduation.SelectedYear);

            var groupEntity         = EntityTypeCache.Get(typeof(Group));
            var groupLocationEntity = EntityTypeCache.Get(typeof(GroupLocation));
            var family = person.GetFamily();

            var familyChangeRequest = new ChangeRequest()
            {
                EntityTypeId     = groupEntity.Id,
                EntityId         = family.Id,
                RequestorAliasId = CurrentPersonAliasId ?? 0
            };

            familyChangeRequest.EvaluatePropertyChange(family, "Campus", CampusCache.Get(ddlCampus.SelectedValueAsInt() ?? 0));

            var      currentLocation = person.GetHomeLocation();
            Location location        = new Location
            {
                Street1    = acAddress.Street1,
                Street2    = acAddress.Street2,
                City       = acAddress.City,
                State      = acAddress.State,
                PostalCode = acAddress.PostalCode,
            };
            var globalAttributesCache = GlobalAttributesCache.Get();

            location.Country = globalAttributesCache.OrganizationCountry;
            location.Country = string.IsNullOrWhiteSpace(location.Country) ? "US" : location.Country;

            if ((currentLocation == null && location.Street1.IsNotNullOrWhiteSpace()) ||
                (currentLocation != null && currentLocation.Street1 != location.Street1))
            {
                LocationService locationService = new LocationService(rockContext);
                locationService.Add(location);
                rockContext.SaveChanges();

                var previousLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                var homeLocationType     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());

                GroupLocation groupLocation = new GroupLocation
                {
                    CreatedByPersonAliasId  = CurrentPersonAliasId,
                    ModifiedByPersonAliasId = CurrentPersonAliasId,
                    GroupId    = family.Id,
                    LocationId = location.Id,
                    GroupLocationTypeValueId = homeLocationType.Id,
                    IsMailingLocation        = true,
                    IsMappedLocation         = true
                };

                var newGroupLocation = familyChangeRequest.AddEntity(groupLocation, rockContext, true, location.ToString());

                var homelocations = family.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationType.Id);
                foreach (var homelocation in homelocations)
                {
                    familyChangeRequest.EvaluatePropertyChange(
                        homelocation,
                        "GroupLocationTypeValue",
                        previousLocationType,
                        true,
                        homelocation.Location.ToString());

                    familyChangeRequest.EvaluatePropertyChange(
                        homelocation,
                        "IsMailingLocation",
                        false,
                        true,
                        homelocation.Location.ToString());
                }
            }

            //Adding a new family member
            if (pAddPerson.SelectedValue.HasValue)
            {
                PersonService personService = new PersonService(rockContext);
                var           insertPerson  = personService.Get(pAddPerson.SelectedValue.Value);
                if (insertPerson != null)
                {
                    GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                    var familyGroupTypeId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;

                    //Remove all other group members
                    if (cbRemovePerson.Checked)
                    {
                        var members = groupMemberService.Queryable()
                                      .Where(m => m.PersonId == pAddPerson.SelectedValue.Value && m.Group.GroupTypeId == familyGroupTypeId);
                        foreach (var member in members)
                        {
                            var comment = string.Format("Removed {0} from {1}", insertPerson.FullName, member.Group.Name);
                            familyChangeRequest.DeleteEntity(member, true, comment);
                        }
                    }

                    var personFamilies = person.GetFamilies().ToList();

                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);

                    var roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;
                    if (insertPerson.Age.HasValue && insertPerson.Age.Value < 18)
                    {
                        roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()).Id;
                    }

                    foreach (var personFamily in personFamilies)
                    {
                        //Make a new group member
                        GroupMember familyMember = new GroupMember
                        {
                            PersonId          = pAddPerson.SelectedValue.Value,
                            GroupId           = personFamily.Id,
                            GroupMemberStatus = GroupMemberStatus.Active,
                            Guid        = Guid.NewGuid(),
                            GroupRoleId = roleId
                        };
                        var insertComment = string.Format("Added {0} to {1}", insertPerson.FullName, personFamily.Name);
                        familyChangeRequest.AddEntity(familyMember, rockContext, true, insertComment);
                    }
                }
            }

            bool          autoApply = CanAutoApply(person);
            List <string> errors;

            if (changeRequest.ChangeRecords.Any() ||
                (!familyChangeRequest.ChangeRecords.Any() && tbComments.Text.IsNotNullOrWhiteSpace()))
            {
                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(changeRequest);
                rockContext.SaveChanges();
                if (autoApply)
                {
                    changeRequest.CompleteChanges(rockContext, out errors);
                }

                changeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull());
            }

            if (familyChangeRequest.ChangeRecords.Any())
            {
                familyChangeRequest.RequestorComment = tbComments.Text;
                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(familyChangeRequest);
                rockContext.SaveChanges();
                if (autoApply)
                {
                    familyChangeRequest.CompleteChanges(rockContext, out errors);
                }
                familyChangeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull());
            }

            if (autoApply)
            {
                NavigateToPerson();
            }
            else
            {
                pnlMain.Visible     = false;
                pnlNoPerson.Visible = false;
                pnlDone.Visible     = true;
            }
        }
Ejemplo n.º 26
0
 public HashSet<NcGroup> GetGroups(string name, GroupLocation location=GroupLocation.ChildrenGrps) {
     CheckNull();
     HashSet<NcGroup> retval = new HashSet<NcGroup>();
     foreach(KeyValuePair<string, NcGroup> k in GetGroups(location)) {
         if(name.Equals(k.Key))
             retval.Add(k.Value);
     }
     return retval;
 }
Ejemplo n.º 27
0
        public Dictionary<string, NcGroup> GetGroups(GroupLocation location=GroupLocation.ChildrenGrps) {
            CheckNull();
            Dictionary<string, NcGroup> ncGroups = new Dictionary<string, NcGroup>();

            // Record this group
            if(location == GroupLocation.ParentsAndCurrentGrps || location == GroupLocation.AllGrps) {
                ncGroups.Add(GetName(), this);
            }

            // the child groups of the current group
            if(location == GroupLocation.ChildrenGrps || location == GroupLocation.AllChildrenGrps 
                                                            || location == GroupLocation.AllGrps ) {
                int groupCount = GetGroupCount();
                int[] ncids = new int[groupCount];
                int numgrps=0;

                NcCheck.Check(NetCDF.nc_inq_grps(myId, ref numgrps, ncids));
                for(int i=0; i<groupCount; i++) {
                    NcGroup tmpGroup = new NcGroup(ncids[i]);
                    ncGroups.Add(tmpGroup.GetName(), tmpGroup);
                }
            }
            // search in parent groups.
            if(location == GroupLocation.ParentsGrps || location == GroupLocation.ParentsAndCurrentGrps
                                                            || location == GroupLocation.AllGrps) {
                NcGroup tmpGroup = GetParentGroup();
                while(tmpGroup != null && !tmpGroup.IsNull()) {
                    ncGroups.Add(tmpGroup.GetName(), tmpGroup);
                    tmpGroup = tmpGroup.GetParentGroup();
                }
            }

            // search in child groups of the children
            if(location == GroupLocation.ChildrenOfChildrenGrps || location == GroupLocation.AllChildrenGrps
                                                            || location == GroupLocation.AllGrps) { 
                Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.ChildrenGrps);
                foreach(KeyValuePair<string, NcGroup> k in groups) {
                    foreach(KeyValuePair<string, NcGroup> kchild in k.Value.GetGroups(GroupLocation.AllChildrenGrps)) {
                        ncGroups.Add(kchild.Key, kchild.Value);
                    }
                }
            }
            return ncGroups;
        }
Ejemplo n.º 28
0
        public int GetGroupCount(GroupLocation location=GroupLocation.ChildrenGrps) {
            CheckNull();
            int ngroups=0;
            // record this group
            if(location == GroupLocation.ParentsAndCurrentGrps || location == GroupLocation.AllGrps) {
                ngroups++;
            }

            // search in current group
            if(location == GroupLocation.ChildrenGrps || location == GroupLocation.AllChildrenGrps 
                                                            || location == GroupLocation.AllGrps)  {
                int numgrps=0;
                int[] ncids=null;
                NcCheck.Check(NetCDF.nc_inq_grps(myId, ref numgrps, ncids));
                ngroups += numgrps;
            }
            // search in parent groups
            if(location == GroupLocation.ParentsGrps || location == GroupLocation.ParentsAndCurrentGrps 
                                                            || location == GroupLocation.AllGrps) {
                Dictionary<string,NcGroup> groups = GetGroups(GroupLocation.ParentsGrps);
                ngroups += groups.Count;
            }

            // get the number of all children that are childreof children
            if(location == GroupLocation.ChildrenOfChildrenGrps || location == GroupLocation.AllChildrenGrps
                                                            || location == GroupLocation.AllGrps) {
                Dictionary<string, NcGroup> groups = GetGroups(GroupLocation.ChildrenOfChildrenGrps);
                ngroups += groups.Count;
            }
            return ngroups;
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Maps the family address.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapFamilyAddress( IQueryable<Row> tableData )
        {
            var locationService = new LocationService();

            int groupEntityTypeId = EntityTypeCache.Read( "Rock.Model.Group" ).Id;

            List<DefinedValue> groupLocationTypeList = new DefinedValueService().Queryable().Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.GROUP_LOCATION_TYPE ) ).ToList();

            List<GroupMember> groupMembershipList = new GroupMemberService().Queryable().Where( gm => gm.Group.GroupType.Guid == new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY ) ).ToList();

            int homeGroupLocationTypeId = groupLocationTypeList.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME ) ).Id;
            int workGroupLocationTypeId = groupLocationTypeList.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK ) ).Id;
            int previousGroupLocationTypeId = groupLocationTypeList.FirstOrDefault( dv => dv.Guid == new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS ) ).Id;

            var newGroupLocations = new List<GroupLocation>();

            int completed = 0;
            int totalRows = tableData.Count();
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Checking address import ({0:N0} found).", totalRows ) );

            foreach ( var row in tableData )
            {
                int? individualId = row["Individual_ID"] as int?;
                int? householdId = row["Household_ID"] as int?;
                int? associatedPersonId = GetPersonId( individualId, householdId );
                if ( associatedPersonId != null )
                {
                    var familyGroup = groupMembershipList.Where( gm => gm.PersonId == (int)associatedPersonId )
                        .Select( gm => gm.Group ).FirstOrDefault();

                    if ( familyGroup != null )
                    {
                        var groupLocation = new GroupLocation();

                        string address = row["Address_1"] as string;
                        string supplemental = row["Address_2"] as string;
                        string city = row["City"] as string;
                        string state = row["State"] as string;
                        string country = row["country"] as string; // NOT A TYPO: F1 has property in lower-case
                        string zip = row["Postal_Code"] as string;

                        // Get new or existing location and associate it with group
                        var familyAddress = locationService.Get( address, supplemental, city, state, zip );
                        familyAddress.CreatedByPersonAliasId = ImportPersonAlias.Id;
                        familyAddress.Name = familyGroup.Name;
                        familyAddress.IsActive = true;

                        groupLocation.GroupId = familyGroup.Id;
                        groupLocation.LocationId = familyAddress.Id;
                        groupLocation.IsMailingLocation = true;
                        groupLocation.IsMappedLocation = true;

                        string addressType = row["Address_Type"] as string;

                        if ( addressType.Equals( "Primary" ) )
                        {
                            groupLocation.GroupLocationTypeValueId = homeGroupLocationTypeId;
                        }
                        else if ( addressType.Equals( "Business" ) || addressType.Equals( "Org" ) )
                        {
                            groupLocation.GroupLocationTypeValueId = workGroupLocationTypeId;
                        }
                        else if ( addressType.Equals( "Previous" ) )
                        {
                            groupLocation.GroupLocationTypeValueId = previousGroupLocationTypeId;
                        }
                        else if ( !string.IsNullOrEmpty( addressType ) )
                        {
                            groupLocation.GroupLocationTypeValueId = groupLocationTypeList.Where( dv => dv.Name.Equals( addressType ) )
                                .Select( dv => (int?)dv.Id ).FirstOrDefault();
                        }

                        newGroupLocations.Add( groupLocation );
                        completed++;

                        if ( completed % percentage < 1 )
                        {
                            int percentComplete = completed / percentage;
                            ReportProgress( percentComplete, string.Format( "{0:N0} addresses imported ({1}% complete).", completed, percentComplete ) );
                        }
                        else if ( completed % ReportingNumber < 1 )
                        {
                            RockTransactionScope.WrapTransaction( () =>
                            {
                                var groupLocationService = new GroupLocationService();
                                groupLocationService.RockContext.GroupLocations.AddRange( newGroupLocations );
                                groupLocationService.RockContext.SaveChanges();
                            } );

                            ReportPartialProgress();
                        }
                    }
                }
            }

            RockTransactionScope.WrapTransaction( () =>
            {
                var groupLocationService = new GroupLocationService();
                groupLocationService.RockContext.GroupLocations.AddRange( newGroupLocations );
                groupLocationService.RockContext.SaveChanges();
            } );

            ReportProgress( 100, string.Format( "Finished address import: {0:N0} addresses imported.", completed ) );
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Handles adding groups from the given XML element snippet.
        /// </summary>
        /// <param name="elemGroups">The elem groups.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <exception cref="System.NotSupportedException"></exception>
        private void AddGroups( XElement elemGroups, RockContext rockContext )
        {
            // Add groups
            if ( elemGroups == null )
            {
                return;
            }

            GroupService groupService = new GroupService( rockContext );

            // Next create the group along with its members.
            foreach ( var elemGroup in elemGroups.Elements( "group" ) )
            {
                Guid guid = elemGroup.Attribute( "guid" ).Value.Trim().AsGuid();
                string type = elemGroup.Attribute( "type" ).Value;
                Group group = new Group()
                {
                    Guid = guid,
                    Name = elemGroup.Attribute( "name" ).Value.Trim()
                };

                // skip any where there is no group type given -- they are invalid entries.
                if ( string.IsNullOrEmpty( elemGroup.Attribute( "type" ).Value.Trim() ) )
                {
                    return;
                }

                int? roleId;
                GroupTypeCache groupType;
                switch ( elemGroup.Attribute( "type" ).Value.Trim() )
                {
                    case "serving":
                        groupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_SERVING_TEAM.AsGuid() );
                        group.GroupTypeId = groupType.Id;
                        roleId = groupType.DefaultGroupRoleId;
                        break;
                    case "smallgroup":
                        groupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_SMALL_GROUP.AsGuid() );
                        group.GroupTypeId = groupType.Id;
                        roleId = groupType.DefaultGroupRoleId;
                        break;
                    default:
                        throw new NotSupportedException( string.Format( "unknown group type {0}", elemGroup.Attribute( "type" ).Value.Trim() ) );
                }

                if ( elemGroup.Attribute( "description" ) != null )
                {
                    group.Description = elemGroup.Attribute( "description" ).Value;
                }

                if ( elemGroup.Attribute( "parentGroupGuid" ) != null )
                {
                    var parentGroup = groupService.Get( elemGroup.Attribute( "parentGroupGuid" ).Value.AsGuid() );
                    group.ParentGroupId = parentGroup.Id;
                }

                // Set the group's meeting location
                if ( elemGroup.Attribute( "meetsAtHomeOfFamily" ) != null )
                {
                    int meetingLocationValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION.AsGuid() ).Id;
                    var groupLocation = new GroupLocation()
                    {
                        IsMappedLocation = false,
                        IsMailingLocation = false,
                        GroupLocationTypeValueId = meetingLocationValueId,
                        LocationId = _familyLocationDictionary[elemGroup.Attribute( "meetsAtHomeOfFamily" ).Value.AsGuid()],
                    };

                    // Set the group location's GroupMemberPersonId if given (required?)
                    if ( elemGroup.Attribute( "meetsAtHomeOfPerson" ) != null )
                    {
                        groupLocation.GroupMemberPersonId = _peopleDictionary[elemGroup.Attribute( "meetsAtHomeOfPerson" ).Value.AsGuid()];
                    }

                    group.GroupLocations.Add( groupLocation );
                }

                group.LoadAttributes();

                // Set the study topic
                if ( elemGroup.Attribute( "studyTopic" ) != null )
                {
                    group.SetAttributeValue( "StudyTopic", elemGroup.Attribute( "studyTopic" ).Value );
                }

                // Set the meeting time
                if ( elemGroup.Attribute( "meetingTime" ) != null )
                {
                    group.SetAttributeValue( "MeetingTime", elemGroup.Attribute( "meetingTime" ).Value );
                }

                // Add each person as a member
                foreach ( var elemPerson in elemGroup.Elements( "person" ) )
                {
                    Guid personGuid = elemPerson.Attribute( "guid" ).Value.Trim().AsGuid();

                    GroupMember groupMember = new GroupMember();
                    groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                    groupMember.GroupRoleId = roleId ?? -1;
                    groupMember.PersonId = _peopleDictionary[personGuid];
                    group.Members.Add( groupMember );
                }

                groupService.Add( group );
                group.SaveAttributeValues( rockContext );
            }
        }
Ejemplo n.º 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 )
        {
            Group group;
            bool wasSecurityRole = false;

            RockContext rockContext = new RockContext();

            GroupService groupService = new GroupService( rockContext );
            GroupLocationService groupLocationService = new GroupLocationService( rockContext );
            ScheduleService scheduleService = new ScheduleService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext );
            CategoryService categoryService = new CategoryService( rockContext );

            if ( ( ddlGroupType.SelectedValueAsInt() ?? 0 ) == 0 )
            {
                ddlGroupType.ShowErrorMessage( Rock.Constants.WarningMessage.CannotBeBlank( GroupType.FriendlyTypeName ) );
                return;
            }

            int groupId = int.Parse( hfGroupId.Value );

            if ( groupId == 0 )
            {
                group = new Group();
                group.IsSystem = false;
                group.Name = string.Empty;
            }
            else
            {
                group = groupService.Queryable( "Schedule,GroupLocations.Schedules" ).Where( g => g.Id == groupId ).FirstOrDefault();
                wasSecurityRole = group.IsSecurityRole;

                var selectedLocations = GroupLocationsState.Select( l => l.Guid );
                foreach ( var groupLocation in group.GroupLocations.Where( l => !selectedLocations.Contains( l.Guid ) ).ToList() )
                {
                    group.GroupLocations.Remove( groupLocation );
                    groupLocationService.Delete( groupLocation );
                }
            }

            foreach ( var groupLocationState in GroupLocationsState )
            {
                GroupLocation groupLocation = group.GroupLocations.Where( l => l.Guid == groupLocationState.Guid ).FirstOrDefault();
                if ( groupLocation == null )
                {
                    groupLocation = new GroupLocation();
                    group.GroupLocations.Add( groupLocation );
                }
                else
                {
                    groupLocationState.Id = groupLocation.Id;
                    groupLocationState.Guid = groupLocation.Guid;

                    var selectedSchedules = groupLocationState.Schedules.Select( s => s.Guid ).ToList();
                    foreach( var schedule in groupLocation.Schedules.Where( s => !selectedSchedules.Contains( s.Guid)).ToList())
                    {
                        groupLocation.Schedules.Remove( schedule );
                    }
                }

                groupLocation.CopyPropertiesFrom( groupLocationState );

                var existingSchedules = groupLocation.Schedules.Select( s => s.Guid ).ToList();
                foreach ( var scheduleState in groupLocationState.Schedules.Where( s => !existingSchedules.Contains( s.Guid )).ToList())
                {
                    var schedule = scheduleService.Get( scheduleState.Guid );
                    if ( schedule != null )
                    {
                        groupLocation.Schedules.Add( schedule );
                    }
                }
            }

            group.Name = tbName.Text;
            group.Description = tbDescription.Text;
            group.CampusId = ddlCampus.SelectedValue.Equals( None.IdValue ) ? (int?)null : int.Parse( ddlCampus.SelectedValue );
            group.GroupTypeId = int.Parse( ddlGroupType.SelectedValue );
            group.ParentGroupId = gpParentGroup.SelectedValue.Equals( None.IdValue ) ? (int?)null : int.Parse( gpParentGroup.SelectedValue );
            group.IsSecurityRole = cbIsSecurityRole.Checked;
            group.IsActive = cbIsActive.Checked;

            string iCalendarContent = string.Empty;

            // If unique schedule option was selected, but a schedule was not defined, set option to 'None'
            var scheduleType = rblScheduleSelect.SelectedValueAsEnum<ScheduleType>( ScheduleType.None );
            if ( scheduleType == ScheduleType.Custom )
            {
                iCalendarContent = sbSchedule.iCalendarContent;
                var calEvent = ScheduleICalHelper.GetCalenderEvent( iCalendarContent );
                if ( calEvent == null || calEvent.DTStart == null )
                {
                    scheduleType = ScheduleType.None;
                }
            }

            if ( scheduleType == ScheduleType.Weekly )
            {
                if ( !dowWeekly.SelectedDayOfWeek.HasValue )
                {
                    scheduleType = ScheduleType.None;
                }
            }

            int? oldScheduleId = hfUniqueScheduleId.Value.AsIntegerOrNull();
            if ( scheduleType == ScheduleType.Custom || scheduleType == ScheduleType.Weekly )
            {
                if ( !oldScheduleId.HasValue || group.Schedule == null )
                {
                    group.Schedule = new Schedule();
                }

                if ( scheduleType == ScheduleType.Custom )
                {
                    group.Schedule.iCalendarContent = iCalendarContent;
                    group.Schedule.WeeklyDayOfWeek = null;
                    group.Schedule.WeeklyTimeOfDay = null;
                }
                else
                {
                    group.Schedule.iCalendarContent = null;
                    group.Schedule.WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek;
                    group.Schedule.WeeklyTimeOfDay = timeWeekly.SelectedTime;
                }
            }
            else
            {
                // If group did have a unique schedule, delete that schedule
                if ( oldScheduleId.HasValue )
                {
                    var schedule = scheduleService.Get( oldScheduleId.Value );
                    if ( schedule != null && string.IsNullOrEmpty(schedule.Name) )
                    {
                        scheduleService.Delete(schedule);
                    }
                }

                if ( scheduleType == ScheduleType.Named )
                {
                    group.ScheduleId = spSchedule.SelectedValueAsId();
                }
                else
                {
                    group.ScheduleId = null;
                }
            }

            if ( group.ParentGroupId == group.Id )
            {
                gpParentGroup.ShowErrorMessage( "Group cannot be a Parent Group of itself." );
                return;
            }

            group.LoadAttributes();

            Rock.Attribute.Helper.GetEditValues( phGroupAttributes, group );

            group.GroupType = new GroupTypeService( rockContext ).Get( group.GroupTypeId );
            if ( group.ParentGroupId.HasValue )
            {
                group.ParentGroup = groupService.Get( group.ParentGroupId.Value );
            }

            // Check to see if user is still allowed to edit with selected group type and parent group
            if ( !group.IsAuthorized( Authorization.EDIT, CurrentPerson ))
            {
                nbNotAllowedToEdit.Visible = true;
                return;
            }

            if ( !Page.IsValid )
            {
                return;
            }

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

            // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
            rockContext.WrapTransaction( () =>
            {
                var adding = group.Id.Equals( 0 );
                if ( adding )
                {
                    groupService.Add( group );
                }

                rockContext.SaveChanges();

                if (adding)
                {
                    // add ADMINISTRATE to the person who added the group
                    Rock.Security.Authorization.AllowPerson( group, Authorization.ADMINISTRATE, this.CurrentPerson, rockContext );
                }

                group.SaveAttributeValues( rockContext );

                /* Take care of Group Member Attributes */
                var entityTypeId = EntityTypeCache.Read( typeof( GroupMember ) ).Id;
                string qualifierColumn = "GroupId";
                string qualifierValue = group.Id.ToString();

                // Get the existing attributes for this entity type and qualifier value
                var attributes = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue );

                // Delete any of those attributes that were removed in the UI
                var selectedAttributeGuids = GroupMemberAttributesState.Select( a => a.Guid );
                foreach ( var attr in attributes.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) )
                {
                    Rock.Web.Cache.AttributeCache.Flush( attr.Id );

                    attributeService.Delete( attr );
                }

                // Update the Attributes that were assigned in the UI
                foreach ( var attributeState in GroupMemberAttributesState )
                {
                    Rock.Attribute.Helper.SaveAttributeEdits( attributeState, entityTypeId, qualifierColumn, qualifierValue, rockContext );
                }

                rockContext.SaveChanges();
            } );

            if ( group != null && wasSecurityRole )
            {
                if ( !group.IsSecurityRole )
                {
                    // if this group was a SecurityRole, but no longer is, flush
                    Rock.Security.Role.Flush( group.Id );
                    Rock.Security.Authorization.Flush();
                }
            }
            else
            {
                if ( group.IsSecurityRole )
                {
                    // new security role, flush
                    Rock.Security.Authorization.Flush();
                }
            }

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

            NavigateToPage( RockPage.Guid, qryParams );
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Handles the Click event of the btnRegister 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 btnRegister_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                var rockContext   = new RockContext();
                var personService = new PersonService(rockContext);

                Person        person       = null;
                Person        spouse       = null;
                Group         family       = null;
                GroupLocation homeLocation = null;

                var changes       = new List <string>();
                var spouseChanges = new List <string>();
                var familyChanges = new List <string>();

                // Only use current person if the name entered matches the current person's name and autofill mode is true
                if (_autoFill)
                {
                    if (CurrentPerson != null &&
                        tbFirstName.Text.Trim().Equals(CurrentPerson.FirstName.Trim(), StringComparison.OrdinalIgnoreCase) &&
                        tbLastName.Text.Trim().Equals(CurrentPerson.LastName.Trim(), StringComparison.OrdinalIgnoreCase))
                    {
                        person = personService.Get(CurrentPerson.Id);
                    }
                }

                // Try to find person by name/email
                if (person == null)
                {
                    var matches = personService.GetByMatch(tbFirstName.Text.Trim(), tbLastName.Text.Trim(), tbEmail.Text.Trim());
                    if (matches.Count() == 1)
                    {
                        person = matches.First();
                    }
                }

                // Check to see if this is a new person
                if (person == null)
                {
                    // If so, create the person and family record for the new person
                    person                         = new Person();
                    person.FirstName               = tbFirstName.Text.Trim();
                    person.LastName                = tbLastName.Text.Trim();
                    person.Email                   = tbEmail.Text.Trim();
                    person.IsEmailActive           = true;
                    person.EmailPreference         = EmailPreference.EmailAllowed;
                    person.RecordTypeValueId       = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    person.ConnectionStatusValueId = _dvcConnectionStatus.Id;
                    person.RecordStatusValueId     = _dvcRecordStatus.Id;
                    person.Gender                  = Gender.Unknown;

                    family = PersonService.SaveNewPerson(person, rockContext, _group.CampusId, false);
                }
                else
                {
                    // updating current existing person
                    History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text);
                    person.Email = tbEmail.Text;

                    // Get the current person's families
                    var families = person.GetFamilies(rockContext);

                    // If address can being entered, look for first family with a home location
                    if (!IsSimple)
                    {
                        foreach (var aFamily in families)
                        {
                            homeLocation = aFamily.GroupLocations
                                           .Where(l =>
                                                  l.GroupLocationTypeValueId == _homeAddressType.Id &&
                                                  l.IsMappedLocation)
                                           .FirstOrDefault();
                            if (homeLocation != null)
                            {
                                family = aFamily;
                                break;
                            }
                        }
                    }

                    // If a family wasn't found with a home location, use the person's first family
                    if (family == null)
                    {
                        family = families.FirstOrDefault();
                    }
                }

                // If using a 'Full' view, save the phone numbers and address
                if (!IsSimple)
                {
                    SetPhoneNumber(rockContext, person, pnHome, null, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid(), changes);
                    SetPhoneNumber(rockContext, person, pnCell, cbSms, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid(), changes);

                    string oldLocation = homeLocation != null?homeLocation.Location.ToString() : string.Empty;

                    string newLocation = string.Empty;

                    var location = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                    if (location != null)
                    {
                        if (homeLocation == null)
                        {
                            homeLocation = new GroupLocation();
                            homeLocation.GroupLocationTypeValueId = _homeAddressType.Id;
                            family.GroupLocations.Add(homeLocation);
                        }
                        else
                        {
                            oldLocation = homeLocation.Location.ToString();
                        }

                        homeLocation.Location = location;
                        newLocation           = location.ToString();
                    }
                    else
                    {
                        if (homeLocation != null)
                        {
                            homeLocation.Location = null;
                            family.GroupLocations.Remove(homeLocation);
                            new GroupLocationService(rockContext).Delete(homeLocation);
                        }
                    }

                    History.EvaluateChange(familyChanges, "Home Location", oldLocation, newLocation);

                    // Check for the spouse
                    if (IsFullWithSpouse && !string.IsNullOrWhiteSpace(tbSpouseFirstName.Text) && !string.IsNullOrWhiteSpace(tbSpouseLastName.Text))
                    {
                        spouse = person.GetSpouse();
                        if (spouse == null ||
                            !tbSpouseFirstName.Text.Trim().Equals(spouse.FirstName.Trim(), StringComparison.OrdinalIgnoreCase) ||
                            !tbSpouseLastName.Text.Trim().Equals(spouse.LastName.Trim(), StringComparison.OrdinalIgnoreCase))
                        {
                            spouse = new Person();

                            spouse.FirstName = tbSpouseFirstName.Text;
                            History.EvaluateChange(spouseChanges, "First Name", string.Empty, spouse.FirstName);

                            spouse.LastName = tbSpouseLastName.Text;
                            History.EvaluateChange(spouseChanges, "Last Name", string.Empty, spouse.LastName);

                            spouse.ConnectionStatusValueId = _dvcConnectionStatus.Id;
                            spouse.RecordStatusValueId     = _dvcRecordStatus.Id;
                            spouse.Gender = Gender.Unknown;

                            spouse.IsEmailActive   = true;
                            spouse.EmailPreference = EmailPreference.EmailAllowed;

                            var groupMember = new GroupMember();
                            groupMember.GroupRoleId = _adultRole.Id;
                            groupMember.Person      = spouse;

                            family.Members.Add(groupMember);

                            spouse.MaritalStatusValueId = _married.Id;
                            person.MaritalStatusValueId = _married.Id;
                        }

                        History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text);
                        spouse.Email = tbSpouseEmail.Text;

                        SetPhoneNumber(rockContext, spouse, pnHome, null, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid(), spouseChanges);
                        SetPhoneNumber(rockContext, spouse, pnSpouseCell, cbSpouseSms, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid(), spouseChanges);
                    }
                }

                // Save the person/spouse and change history
                rockContext.SaveChanges();
                HistoryService.SaveChanges(rockContext, typeof(Person),
                                           Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes);
                HistoryService.SaveChanges(rockContext, typeof(Person),
                                           Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), person.Id, familyChanges);
                if (spouse != null)
                {
                    HistoryService.SaveChanges(rockContext, typeof(Person),
                                               Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), spouse.Id, spouseChanges);
                    HistoryService.SaveChanges(rockContext, typeof(Person),
                                               Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), spouse.Id, familyChanges);
                }

                // Check to see if a workflow should be launched for each person
                WorkflowType workflowType     = null;
                Guid?        workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    var workflowTypeService = new WorkflowTypeService(rockContext);
                    workflowType = workflowTypeService.Get(workflowTypeGuid.Value);
                }

                // Save the registrations ( and launch workflows )
                var newGroupMembers = new List <GroupMember>();
                AddPersonToGroup(rockContext, person, workflowType, newGroupMembers);
                AddPersonToGroup(rockContext, spouse, workflowType, newGroupMembers);

                // Show the results
                pnlView.Visible   = false;
                pnlResult.Visible = true;

                // Show lava content
                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("Group", _group);
                mergeFields.Add("GroupMembers", newGroupMembers);

                bool showDebug = UserCanEdit && GetAttributeValue("EnableDebug").AsBoolean();
                lResultDebug.Visible = showDebug;
                if (showDebug)
                {
                    lResultDebug.Text = mergeFields.lavaDebugInfo(_rockContext);
                }

                string template = GetAttributeValue("ResultLavaTemplate");
                lResult.Text = template.ResolveMergeFields(mergeFields);

                // Will only redirect if a value is specifed
                NavigateToLinkedPage("ResultPage");
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Loads the group data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadGroup(CSVInstance csvData)
        {
            // Required variables
            var lookupContext    = new RockContext();
            var locationService  = new LocationService(lookupContext);
            var groupTypeService = new GroupTypeService(lookupContext);

            var topicTypes = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.SMALL_GROUP_TOPIC), lookupContext).DefinedValues;

            var numImportedGroups = ImportedGroups.Count();

            var newGroupLocations = new Dictionary <GroupLocation, string>();
            var currentGroup      = new Group();

            // Look for custom attributes in the Individual file
            var allFields        = csvData.TableNodes.FirstOrDefault().Children.Select((node, index) => new { node = node, index = index }).ToList();
            var customAttributes = allFields
                                   .Where(f => f.index > GroupCapacity)
                                   .ToDictionary(f => f.index, f => f.node.Name);

            var groupAttributes = new AttributeService(lookupContext).GetByEntityTypeId(new Group().TypeId).ToList();
            var completed       = 0;

            ReportProgress(0, $"Starting group import ({numImportedGroups:N0} already exist).");

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ((row = csvData.Database.FirstOrDefault()) != null)
            {
                var rowGroupKey = row[GroupId];

                //
                // Determine if we are still working with the same group or not.
                //
                if (rowGroupKey != null && rowGroupKey != currentGroup.ForeignKey)
                {
                    currentGroup = LoadGroupBasic(lookupContext, rowGroupKey, row[GroupName], row[GroupCreatedDate], row[GroupType], row[GroupParentGroupId], row[GroupActive], row[GroupDescription]);

                    //
                    // Set the group campus
                    //
                    var campusName = row[GroupCampus];
                    if (!string.IsNullOrWhiteSpace(campusName))
                    {
                        var groupCampus = CampusList.FirstOrDefault(c => c.Name.Equals(campusName, StringComparison.InvariantCultureIgnoreCase) ||
                                                                    c.ShortCode.Equals(campusName, StringComparison.InvariantCultureIgnoreCase));
                        if (groupCampus == null)
                        {
                            groupCampus = new Campus
                            {
                                IsSystem  = false,
                                Name      = campusName,
                                ShortCode = campusName.RemoveWhitespace(),
                                IsActive  = true
                            };
                            lookupContext.Campuses.Add(groupCampus);
                            lookupContext.SaveChanges(DisableAuditing);
                            CampusList.Add(groupCampus);
                        }

                        currentGroup.CampusId = groupCampus.Id;
                    }

                    //
                    // If the group type has one or more location types defined then import the
                    // primary address as the first location type.
                    //
                    var groupType = groupTypeService.Get(currentGroup.GroupTypeId);
                    if (groupType.LocationTypes.Count > 0 && (!string.IsNullOrWhiteSpace(row[GroupAddress]) || !string.IsNullOrWhiteSpace(row[GroupNamedLocation])) && currentGroup.GroupLocations.Count == 0)
                    {
                        var primaryLocationTypeId = groupType.LocationTypes.ToList()[0].LocationTypeValueId;

                        var grpAddress  = row[GroupAddress];
                        var grpAddress2 = row[GroupAddress2];
                        var grpCity     = row[GroupCity];
                        var grpState    = row[GroupState];
                        var grpZip      = row[GroupZip];
                        var grpCountry  = row[GroupCountry];

                        var namedLocation = row[GroupNamedLocation];

                        if (string.IsNullOrWhiteSpace(namedLocation))
                        {
                            var primaryAddress = locationService.Get(grpAddress, grpAddress2, grpCity, grpState, grpZip, grpCountry, verifyLocation: false);

                            if (primaryAddress != null)
                            {
                                var primaryLocation = new GroupLocation
                                {
                                    LocationId               = primaryAddress.Id,
                                    IsMailingLocation        = true,
                                    IsMappedLocation         = true,
                                    GroupLocationTypeValueId = primaryLocationTypeId
                                };
                                newGroupLocations.Add(primaryLocation, rowGroupKey);
                            }
                        }
                        else
                        {
                            var primaryAddress = locationService.Queryable().FirstOrDefault(l => l.Name.Equals(namedLocation) || l.ForeignKey.Equals(namedLocation));
                            if (primaryAddress != null)
                            {
                                var primaryLocation = new GroupLocation
                                {
                                    LocationId               = primaryAddress.Id,
                                    IsMailingLocation        = true,
                                    IsMappedLocation         = true,
                                    GroupLocationTypeValueId = primaryLocationTypeId
                                };
                                newGroupLocations.Add(primaryLocation, rowGroupKey);
                            }
                            else
                            {
                                LogException("Group Import", string.Format("The named location {0} was not found and will not be mapped.", namedLocation));
                            }
                        }
                    }

                    //
                    // If the group type has two or more location types defined then import the
                    // secondary address as the group type's second location type.
                    //
                    if (groupType.LocationTypes.Count > 1 && !string.IsNullOrWhiteSpace(row[GroupSecondaryAddress]) && currentGroup.GroupLocations.Count < 2)
                    {
                        var secondaryLocationTypeId = groupType.LocationTypes.ToList()[1].LocationTypeValueId;

                        var grpSecondAddress  = row[GroupSecondaryAddress];
                        var grpSecondAddress2 = row[GroupSecondaryAddress2];
                        var grpSecondCity     = row[GroupSecondaryCity];
                        var grpSecondState    = row[GroupSecondaryState];
                        var grpSecondZip      = row[GroupSecondaryZip];
                        var grpSecondCountry  = row[GroupSecondaryCountry];

                        var secondaryAddress = locationService.Get(grpSecondAddress, grpSecondAddress2, grpSecondCity, grpSecondState, grpSecondZip, grpSecondCountry, verifyLocation: false);

                        if (secondaryAddress != null)
                        {
                            var secondaryLocation = new GroupLocation
                            {
                                LocationId               = secondaryAddress.Id,
                                IsMailingLocation        = true,
                                IsMappedLocation         = true,
                                GroupLocationTypeValueId = secondaryLocationTypeId
                            };
                            newGroupLocations.Add(secondaryLocation, rowGroupKey);
                        }
                    }

                    //
                    // Set the group's sorting order.
                    //
                    var groupOrder = 9999;
                    int.TryParse(row[GroupOrder], out groupOrder);
                    currentGroup.Order = groupOrder;

                    //
                    // Set the group's capacity
                    //
                    var capacity = row[GroupCapacity].AsIntegerOrNull();
                    if (capacity.HasValue)
                    {
                        currentGroup.GroupCapacity = capacity;

                        if (groupType.GroupCapacityRule == GroupCapacityRule.None)
                        {
                            groupType.GroupCapacityRule = GroupCapacityRule.Hard;
                        }
                    }

                    //
                    // Set the group's schedule
                    //
                    if (!string.IsNullOrWhiteSpace(row[GroupDayOfWeek]))
                    {
                        DayOfWeek dayEnum;
                        if (Enum.TryParse(row[GroupDayOfWeek], true, out dayEnum))
                        {
                            if (groupType.AllowedScheduleTypes != ScheduleType.Weekly)
                            {
                                groupType.AllowedScheduleTypes = ScheduleType.Weekly;
                            }
                            var day  = dayEnum;
                            var time = row[GroupTime].AsDateTime();
                            currentGroup.ScheduleId = AddNamedSchedule(lookupContext, string.Empty, string.Empty, day, time, null, rowGroupKey).Id;
                        }
                    }

                    //
                    // Assign Attributes
                    //
                    if (customAttributes.Any())
                    {
                        lookupContext.SaveChanges();

                        foreach (var attributePair in customAttributes)
                        {
                            var pairs                  = attributePair.Value.Split('^');
                            var categoryName           = string.Empty;
                            var attributeName          = string.Empty;
                            var attributeTypeString    = string.Empty;
                            var attributeForeignKey    = string.Empty;
                            var definedValueForeignKey = string.Empty;
                            var fieldTypeId            = TextFieldTypeId;

                            if (pairs.Length == 1)
                            {
                                attributeName = pairs[0];
                            }
                            else if (pairs.Length == 2)
                            {
                                attributeName       = pairs[0];
                                attributeTypeString = pairs[1];
                            }
                            else if (pairs.Length >= 3)
                            {
                                categoryName  = pairs[1];
                                attributeName = pairs[2];
                                if (pairs.Length >= 4)
                                {
                                    attributeTypeString = pairs[3];
                                }
                                if (pairs.Length >= 5)
                                {
                                    attributeForeignKey = pairs[4];
                                }
                                if (pairs.Length >= 6)
                                {
                                    definedValueForeignKey = pairs[5];
                                }
                            }

                            var definedValueForeignId = definedValueForeignKey.AsType <int?>();

                            //
                            // Translate the provided attribute type into one we know about.
                            //
                            fieldTypeId = GetAttributeFieldType(attributeTypeString);

                            Rock.Model.Attribute currentAttribute = null;
                            if (string.IsNullOrEmpty(attributeName))
                            {
                                LogException("Group Attribute", string.Format("Group Attribute Name cannot be blank '{0}'.", attributePair.Value));
                            }
                            else
                            {
                                if (string.IsNullOrWhiteSpace(attributeForeignKey))
                                {
                                    attributeForeignKey = string.Format("Bulldozer_{0}_{1}_{2}", groupType.Id, categoryName.RemoveWhitespace(), attributeName.RemoveWhitespace()).Left(100);
                                }
                                currentAttribute = groupAttributes.FirstOrDefault(a =>
                                                                                  a.Name.Equals(attributeName, StringComparison.OrdinalIgnoreCase) &&
                                                                                  a.FieldTypeId == fieldTypeId &&
                                                                                  a.EntityTypeId == currentGroup.TypeId &&
                                                                                  a.EntityTypeQualifierValue == groupType.Id.ToString()
                                                                                  );
                                if (currentAttribute == null)
                                {
                                    currentAttribute = AddEntityAttribute(lookupContext, currentGroup.TypeId, "GroupTypeId", groupType.Id.ToString(), attributeForeignKey, categoryName, attributeName, string.Empty, fieldTypeId, true, definedValueForeignId, definedValueForeignKey, attributeTypeString: attributeTypeString);
                                    groupAttributes.Add(currentAttribute);
                                }

                                var attributeValue = row[attributePair.Key];
                                if (!string.IsNullOrEmpty(attributeValue))
                                {
                                    AddEntityAttributeValue(lookupContext, currentAttribute, currentGroup, row[attributePair.Key], null, true);
                                }
                            }
                        }
                    }

                    //
                    // Changes to groups need to be saved right away since one group
                    // will reference another group.
                    //
                    lookupContext.SaveChanges();

                    //
                    // Keep the user informed as to what is going on and save in batches.
                    //
                    completed++;
                    if (completed % (ReportingNumber * 10) < 1)
                    {
                        ReportProgress(0, $"{completed:N0} groups imported.");
                    }

                    if (completed % ReportingNumber < 1)
                    {
                        SaveGroupLocations(newGroupLocations);
                        ReportPartialProgress();

                        // Reset lookup context
                        lookupContext.SaveChanges();
                        lookupContext    = new RockContext();
                        locationService  = new LocationService(lookupContext);
                        groupTypeService = new GroupTypeService(lookupContext);
                        newGroupLocations.Clear();
                    }
                }
            }

            //
            // Check to see if any rows didn't get saved to the database
            //
            if (newGroupLocations.Any())
            {
                SaveGroupLocations(newGroupLocations);
            }

            lookupContext.SaveChanges();
            lookupContext.Dispose();

            ReportProgress(0, $"Finished group import: {completed:N0} groups added or updated.");

            return(completed);
        }
Ejemplo n.º 34
0
 public NcGroup GetGroup(string name, GroupLocation location=GroupLocation.ChildrenGrps) {
     CheckNull();
     Dictionary<string, NcGroup> groups = GetGroups(location);
     foreach(KeyValuePair<string, NcGroup> k in groups) {
         if(k.Key.Equals(name))
             return k.Value;
     }
     return new NcGroup(); // Null 
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Wählt eine Quellgruppe an.
        /// </summary>
        /// <param name="group">Die Quellgruppe.</param>
        /// <param name="location">Der Ursprung zur Quellgruppe.</param>
        public void Tune( SourceGroup group, GroupLocation location )
        {
            // Must register
            Register();

            // Forward
            Context.TheContext.SetChannel( group, location );
        }
        /// <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 )
        {
            var rockContext = new RockContext();
            Rock.Data.RockTransactionScope.WrapTransaction( () =>
            {
                var personService = new PersonService( rockContext );
                var changes = new List<string>();
                var business = new Person();
                if ( int.Parse( hfBusinessId.Value ) != 0 )
                {
                    business = personService.Get( int.Parse( hfBusinessId.Value ) );
                }

                // int? orphanedPhotoId = null;
                // if ( business.PhotoId != imgPhoto.BinaryFileId )
                // {
                // orphanedPhotoId = business.PhotoId;
                // business.PhotoId = imgPhoto.BinaryFileId;

                // if ( orphanedPhotoId.HasValue )
                // {
                // if ( business.PhotoId.HasValue )
                // {
                // changes.Add( "Modified the photo." );
                // }
                // else
                // {
                // changes.Add( "Deleted the photo." );
                // }
                // }
                // else if ( business.PhotoId.HasValue )
                // {
                // changes.Add( "Added a photo." );
                // }
                // }

                // Business Name
                History.EvaluateChange( changes, "First Name", business.FirstName, tbBusinessName.Text );
                business.FirstName = tbBusinessName.Text;

                // Phone Number
                var phoneNumberTypeIds = new List<int>();
                var homePhoneTypeId = new DefinedValueService( rockContext ).GetByGuid( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME ) ).Id;

                if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) )
                {
                    var phoneNumber = business.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == homePhoneTypeId );
                    string oldPhoneNumber = string.Empty;
                    if ( phoneNumber == null )
                    {
                        phoneNumber = new PhoneNumber { NumberTypeValueId = homePhoneTypeId };
                        business.PhoneNumbers.Add( phoneNumber );
                    }
                    else
                    {
                        oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                    }

                    phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode );
                    phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number );
                    phoneNumber.IsMessagingEnabled = cbSms.Checked;
                    phoneNumber.IsUnlisted = cbUnlisted.Checked;
                    phoneNumberTypeIds.Add( homePhoneTypeId );

                    History.EvaluateChange(
                        changes,
                        string.Format( "{0} Phone", DefinedValueCache.GetName( homePhoneTypeId ) ),
                        oldPhoneNumber,
                        phoneNumber.NumberFormattedWithCountryCode );
                }

                // Remove any blank numbers
                var phoneNumberService = new PhoneNumberService( rockContext );
                foreach ( var phoneNumber in business.PhoneNumbers
                    .Where( n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains( n.NumberTypeValueId.Value ) )
                    .ToList() )
                {
                    History.EvaluateChange(
                        changes,
                        string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumber.NumberTypeValueId ) ),
                        phoneNumber.NumberFormatted,
                        string.Empty );

                    business.PhoneNumbers.Remove( phoneNumber );
                    phoneNumberService.Delete( phoneNumber );
                }

                // Record Type - this is always "business". it will never change.
                business.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid() ).Id;

                // Record Status
                int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( business.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) );
                business.RecordStatusValueId = newRecordStatusId;

                // Record Status Reason
                int? newRecordStatusReasonId = null;
                if ( business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id )
                {
                    newRecordStatusReasonId = ddlReason.SelectedValueAsInt();
                }

                History.EvaluateChange( changes, "Record Status Reason", DefinedValueCache.GetName( business.RecordStatusReasonValueId ), DefinedValueCache.GetName( newRecordStatusReasonId ) );
                business.RecordStatusReasonValueId = newRecordStatusReasonId;

                // Email
                business.IsEmailActive = true;
                History.EvaluateChange( changes, "Email", business.Email, tbEmail.Text );
                business.Email = tbEmail.Text.Trim();

                var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum<EmailPreference>();
                History.EvaluateChange( changes, "EmailPreference", business.EmailPreference, newEmailPreference );
                business.EmailPreference = newEmailPreference;

                if ( business.IsValid )
                {
                    if ( rockContext.SaveChanges() > 0 )
                    {
                        if ( changes.Any() )
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof( Person ),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                business.Id,
                                changes );
                        }

                        // if ( orphanedPhotoId.HasValue )
                        // {
                        // BinaryFileService binaryFileService = new BinaryFileService( personService.RockContext );
                        // var binaryFile = binaryFileService.Get( orphanedPhotoId.Value );
                        // if ( binaryFile != null )
                        // {
                        // // marked the old images as IsTemporary so they will get cleaned up later
                        // binaryFile.IsTemporary = true;
                        // binaryFileService.Save( binaryFile, CurrentPersonAlias );
                        // }
                        // }

                        // Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false );
                    }
                }

                // Group
                var familyGroupType = GroupTypeCache.GetFamilyGroupType();
                var groupService = new GroupService( rockContext );
                var businessGroup = new Group();
                if ( business.GivingGroupId != null )
                {
                    businessGroup = groupService.Get( (int)business.GivingGroupId );
                }

                businessGroup.GroupTypeId = familyGroupType.Id;
                businessGroup.Name = tbBusinessName.Text + " Business";
                businessGroup.CampusId = ddlCampus.SelectedValueAsInt();
                var knownRelationshipGroup = new Group();
                var impliedRelationshipGroup = new Group();
                if ( business.GivingGroupId == null )
                {
                    groupService.Add( businessGroup );

                    // If there isn't a Giving Group then there aren't any other groups.
                    // We also need to add the Known Relationship and Implied Relationship groups for this business.
                    var knownRelationshipGroupTypeId = new GroupTypeService( rockContext ).Get( new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS ) ).Id;
                    knownRelationshipGroup.GroupTypeId = knownRelationshipGroupTypeId;
                    knownRelationshipGroup.Name = "Known Relationship";
                    groupService.Add( knownRelationshipGroup );

                    var impliedRelationshipGroupTypeId = new GroupTypeService( rockContext ).Get( new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS ) ).Id;
                    impliedRelationshipGroup.GroupTypeId = impliedRelationshipGroupTypeId;
                    impliedRelationshipGroup.Name = "Implied Relationship";
                    groupService.Add( impliedRelationshipGroup );
                }

                rockContext.SaveChanges();

                // Giving Group
                int? newGivingGroupId = ddlGivingGroup.SelectedValueAsId();
                if ( business.GivingGroupId != newGivingGroupId )
                {
                    string oldGivingGroupName = business.GivingGroup != null ? business.GivingGroup.Name : string.Empty;
                    string newGivingGroupName = newGivingGroupId.HasValue ? ddlGivingGroup.Items.FindByValue( newGivingGroupId.Value.ToString() ).Text : string.Empty;
                    History.EvaluateChange( changes, "Giving Group", oldGivingGroupName, newGivingGroupName );
                }

                business.GivingGroup = businessGroup;

                // GroupMember
                var groupMemberService = new GroupMemberService( rockContext );
                int? adultRoleId = new GroupTypeRoleService( rockContext ).Queryable()
                    .Where( r =>
                        r.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) )
                    .Select( r => r.Id )
                    .FirstOrDefault();
                var groupMember = businessGroup.Members.Where( role => role.GroupRoleId == adultRoleId ).FirstOrDefault();
                if ( groupMember == null )
                {
                    groupMember = new GroupMember();
                    businessGroup.Members.Add( groupMember );

                    // If we're in here, then this is a new business.
                    // Add the known relationship and implied relationship GroupMember entries.
                    var knownRelationshipGroupMember = new GroupMember();
                    knownRelationshipGroupMember.Person = business;
                    knownRelationshipGroupMember.GroupRoleId = new GroupTypeRoleService( rockContext ).Get( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid() ).Id;
                    knownRelationshipGroupMember.GroupId = knownRelationshipGroup.Id;
                    knownRelationshipGroup.Members.Add( knownRelationshipGroupMember );

                    var impliedRelationshipGroupMember = new GroupMember();
                    impliedRelationshipGroupMember.Person = business;
                    impliedRelationshipGroupMember.GroupRoleId = new GroupTypeRoleService( rockContext ).Get( Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid() ).Id;
                    impliedRelationshipGroupMember.GroupId = impliedRelationshipGroup.Id;
                    impliedRelationshipGroup.Members.Add( impliedRelationshipGroupMember );
                }

                groupMember.Person = business;
                groupMember.GroupRoleId = new GroupTypeRoleService( rockContext ).Get( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ).Id;
                groupMember.GroupMemberStatus = GroupMemberStatus.Active;

                // GroupLocation & Location
                var groupLocationService = new GroupLocationService( rockContext );
                var groupLocation = businessGroup.GroupLocations.FirstOrDefault();
                if ( groupLocation == null )
                {
                    groupLocation = new GroupLocation();
                    businessGroup.GroupLocations.Add( groupLocation );
                }

                groupLocation.GroupLocationTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME ).Id;

                var locationService = new LocationService( rockContext );
                var location = groupLocation.Location;
                if ( location == null )
                {
                    location = new Location();
                    groupLocation.Location = location;
                }

                location.Street1 = tbStreet1.Text.Trim();
                location.Street2 = tbStreet2.Text.Trim();
                location.City = tbCity.Text.Trim();
                location.State = ddlState.SelectedValue;
                location.Zip = tbZipCode.Text.Trim();

                rockContext.SaveChanges();

                hfBusinessId.Value = business.Id.ToString();

                // Set the Known Relationships between the Owner and the Business.
                if ( ppOwner.PersonId != null )
                {
                    SetOwner( business );
                }
            } );

            NavigateToParentPage();
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Handles the Click event of the btnSaveGroup 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 btnSaveGroup_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            GroupService groupService = new GroupService( rockContext );

            Group group = groupService.Get( _groupId );

            if ( group != null && group.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
            {
                group.Name = tbName.Text;
                group.Description = tbDescription.Text;
                group.IsActive = cbIsActive.Checked;

                if ( pnlSchedule.Visible )
                {
                    if ( group.Schedule == null )
                    {
                        group.Schedule = new Schedule();
                        group.Schedule.iCalendarContent = null;
                    }

                    group.Schedule.WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek;
                    group.Schedule.WeeklyTimeOfDay = timeWeekly.SelectedTime;
                }

                // set attributes
                group.LoadAttributes( rockContext );
                Rock.Attribute.Helper.GetEditValues( phAttributes, group );

                // configure locations
                if ( GetAttributeValue( "EnableLocationEdit" ).AsBoolean() )
                {
                    // get selected location
                    Location location = null;
                    int? memberPersonAliasId = null;

                    if ( LocationTypeTab.Equals( MEMBER_LOCATION_TAB_TITLE ) )
                    {
                        if ( ddlMember.SelectedValue != null )
                        {
                            var ids = ddlMember.SelectedValue.Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries );
                            if ( ids.Length == 2 )
                            {
                                var dbLocation = new LocationService( rockContext ).Get( int.Parse( ids[0] ) );
                                if ( dbLocation != null )
                                {
                                    location = dbLocation;
                                }

                                memberPersonAliasId = new PersonAliasService( rockContext ).GetPrimaryAliasId( int.Parse( ids[1] ) );
                            }
                        }
                    }
                    else
                    {
                        if ( locpGroupLocation.Location != null )
                        {
                            location = new LocationService( rockContext ).Get( locpGroupLocation.Location.Id );
                        }
                    }

                    if ( location != null )
                    {
                        GroupLocation groupLocation = group.GroupLocations.FirstOrDefault();

                        if ( groupLocation == null )
                        {
                            groupLocation = new GroupLocation();
                            group.GroupLocations.Add( groupLocation );
                        }

                        groupLocation.GroupMemberPersonAliasId = memberPersonAliasId;
                        groupLocation.Location = location;
                        groupLocation.LocationId = groupLocation.Location.Id;
                        groupLocation.GroupLocationTypeValueId = ddlLocationType.SelectedValueAsId();
                    }
                }

                rockContext.SaveChanges();
                group.SaveAttributeValues( rockContext );
            }

            this.IsEditingGroup = false;

            // reload the group info
            pnlGroupEdit.Visible = false;
            pnlGroupView.Visible = true;
            DisplayViewGroup();
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Loads the family data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadFamily(CSVInstance csvData)
        {
            // Required variables
            var lookupContext     = new RockContext();
            var locationService   = new LocationService(lookupContext);
            int familyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id;

            int numImportedFamilies = ImportedFamilies.Count();

            int homeLocationTypeId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME)).Id;
            int workLocationTypeId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK)).Id;

            var newGroupLocations  = new Dictionary <GroupLocation, string>();
            var currentFamilyGroup = new Group();
            var newFamilyList      = new List <Group>();
            var updatedFamilyList  = new List <Group>();

            var dateFormats = new[] { "yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy" };

            string currentFamilyKey = string.Empty;
            int    completed        = 0;

            ReportProgress(0, string.Format("Starting family import ({0:N0} already exist).", numImportedFamilies));

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ((row = csvData.Database.FirstOrDefault()) != null)
            {
                string rowFamilyKey  = row[FamilyId];
                int?   rowFamilyId   = rowFamilyKey.AsType <int?>();
                string rowFamilyName = row[FamilyName];

                if (rowFamilyKey != null && rowFamilyKey != currentFamilyGroup.ForeignKey)
                {
                    currentFamilyGroup = ImportedFamilies.FirstOrDefault(g => g.ForeignKey == rowFamilyKey);
                    if (currentFamilyGroup == null)
                    {
                        currentFamilyGroup                        = new Group();
                        currentFamilyGroup.ForeignKey             = rowFamilyKey;
                        currentFamilyGroup.ForeignId              = rowFamilyId;
                        currentFamilyGroup.Name                   = row[FamilyName];
                        currentFamilyGroup.CreatedByPersonAliasId = ImportPersonAliasId;
                        currentFamilyGroup.GroupTypeId            = familyGroupTypeId;
                        newFamilyList.Add(currentFamilyGroup);
                    }
                    else
                    {
                        lookupContext.Groups.Attach(currentFamilyGroup);
                    }

                    // Set the family campus
                    string campusName = row[Campus];
                    if (!string.IsNullOrWhiteSpace(campusName))
                    {
                        var familyCampus = CampusList.Where(c => c.Name.Equals(campusName, StringComparison.InvariantCultureIgnoreCase) ||
                                                            c.ShortCode.Equals(campusName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                        if (familyCampus == null)
                        {
                            familyCampus           = new Campus();
                            familyCampus.IsSystem  = false;
                            familyCampus.Name      = campusName;
                            familyCampus.ShortCode = campusName.RemoveWhitespace();
                            lookupContext.Campuses.Add(familyCampus);
                            lookupContext.SaveChanges(DisableAuditing);
                            CampusList.Add(familyCampus);
                        }

                        currentFamilyGroup.CampusId = familyCampus.Id;
                    }

                    // Add the family addresses since they exist in this file
                    string famAddress  = row[Address];
                    string famAddress2 = row[Address2];
                    string famCity     = row[City];
                    string famState    = row[State];
                    string famZip      = row[Zip];
                    string famCountry  = row[Country];

                    Location primaryAddress = locationService.Get(famAddress, famAddress2, famCity, famState, famZip, famCountry, verifyLocation: false);

                    if (primaryAddress != null)
                    {
                        var primaryLocation = new GroupLocation();
                        primaryLocation.LocationId               = primaryAddress.Id;
                        primaryLocation.IsMailingLocation        = true;
                        primaryLocation.IsMappedLocation         = true;
                        primaryLocation.GroupLocationTypeValueId = homeLocationTypeId;
                        newGroupLocations.Add(primaryLocation, rowFamilyKey);
                    }

                    string famSecondAddress  = row[SecondaryAddress];
                    string famSecondAddress2 = row[SecondaryAddress2];
                    string famSecondCity     = row[SecondaryCity];
                    string famSecondState    = row[SecondaryState];
                    string famSecondZip      = row[SecondaryZip];
                    string famSecondCountry  = row[SecondaryCountry];

                    Location secondaryAddress = locationService.Get(famSecondAddress, famSecondAddress2, famSecondCity, famSecondState, famSecondZip, famSecondCountry, verifyLocation: false);

                    if (secondaryAddress != null)
                    {
                        var secondaryLocation = new GroupLocation();
                        secondaryLocation.LocationId               = secondaryAddress.Id;
                        secondaryLocation.IsMailingLocation        = true;
                        secondaryLocation.IsMappedLocation         = true;
                        secondaryLocation.GroupLocationTypeValueId = workLocationTypeId;
                        newGroupLocations.Add(secondaryLocation, rowFamilyKey);
                    }

                    DateTime createdDateValue;
                    if (DateTime.TryParseExact(row[CreatedDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDateValue))
                    {
                        currentFamilyGroup.CreatedDateTime  = createdDateValue;
                        currentFamilyGroup.ModifiedDateTime = ImportDateTime;
                    }
                    else
                    {
                        currentFamilyGroup.CreatedDateTime  = ImportDateTime;
                        currentFamilyGroup.ModifiedDateTime = ImportDateTime;
                    }

                    completed++;
                    if (completed % (ReportingNumber * 10) < 1)
                    {
                        ReportProgress(0, string.Format("{0:N0} families imported.", completed));
                    }
                    else if (completed % ReportingNumber < 1)
                    {
                        SaveFamilies(newFamilyList, newGroupLocations);
                        ReportPartialProgress();

                        // Reset lookup context
                        lookupContext.SaveChanges();
                        lookupContext   = new RockContext();
                        locationService = new LocationService(lookupContext);
                        newFamilyList.Clear();
                        newGroupLocations.Clear();
                    }
                }
            }

            // Check to see if any rows didn't get saved to the database
            if (newGroupLocations.Any())
            {
                SaveFamilies(newFamilyList, newGroupLocations);
            }

            lookupContext.SaveChanges();
            DetachAllInContext(lookupContext);
            lookupContext.Dispose();

            ReportProgress(0, string.Format("Finished family import: {0:N0} families added or updated.", completed));
            return(completed);
        }
Ejemplo n.º 39
0
        public GroupAddressInfo( GroupLocation groupLocation )
        {
            LocationIsDirty = false;
            if ( groupLocation != null )
            {
                Id = groupLocation.Id;

                if ( groupLocation.GroupLocationTypeValue != null )
                {
                    LocationTypeId = groupLocation.GroupLocationTypeValue.Id;
                    LocationTypeName = groupLocation.GroupLocationTypeValue.Value;
                }

                if ( groupLocation.Location != null )
                {
                    LocationId = groupLocation.Location.Id;
                    Street1 = groupLocation.Location.Street1;
                    Street2 = groupLocation.Location.Street2;
                    City = groupLocation.Location.City;
                    State = groupLocation.Location.State;
                    PostalCode = groupLocation.Location.PostalCode;
                    Country = groupLocation.Location.Country;
                }

                IsMailing = groupLocation.IsMailingLocation;
                IsLocation = groupLocation.IsMappedLocation;
            }
        }
Ejemplo n.º 40
0
        public FamilyAddress( GroupLocation groupLocation )
        {
            LocationIsDirty = false;
            if ( groupLocation != null )
            {
                Id = groupLocation.Id;

                if ( groupLocation.GroupLocationTypeValue != null )
                {
                    LocationTypeId = groupLocation.GroupLocationTypeValue.Id;
                    LocationTypeName = groupLocation.GroupLocationTypeValue.Name;
                }

                if ( groupLocation.Location != null )
                {
                    LocationId = groupLocation.Location.Id;
                    Street1 = groupLocation.Location.Street1;
                    Street2 = groupLocation.Location.Street2;
                    City = groupLocation.Location.City;
                    State = groupLocation.Location.State;
                    Zip = groupLocation.Location.Zip;
                }

                IsMailing = groupLocation.IsMailingLocation;
                IsLocation = groupLocation.IsMappedLocation;
            }
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Creates the person.
        /// </summary>
        /// <returns></returns>
        private Person CreatePerson()
        {
            var rockContext = new RockContext();

            DefinedValueCache dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() );
            DefinedValueCache dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() );

            Person person = new Person();
            person.FirstName = tbFirstName.Text;
            person.LastName = tbLastName.Text;
            person.Email = tbEmail.Text;
            person.IsEmailActive = true;
            person.EmailPreference = EmailPreference.EmailAllowed;
            person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
            if ( dvcConnectionStatus != null )
            {
                person.ConnectionStatusValueId = dvcConnectionStatus.Id;
            }

            if ( dvcRecordStatus != null )
            {
                person.RecordStatusValueId = dvcRecordStatus.Id;
            }

            switch ( ddlGender.SelectedValue )
            {
                case "M":
                    person.Gender = Gender.Male;
                    break;
                case "F":
                    person.Gender = Gender.Female;
                    break;
                default:
                    person.Gender = Gender.Unknown;
                    break;
            }

            var birthday = bdaypBirthDay.SelectedDate;
            if ( birthday.HasValue )
            {
                person.BirthMonth = birthday.Value.Month;
                person.BirthDay = birthday.Value.Day;
                if ( birthday.Value.Year != DateTime.MinValue.Year )
                {
                    person.BirthYear = birthday.Value.Year;
                }
            }

            bool smsSelected = false;

            foreach ( RepeaterItem item in rPhoneNumbers.Items )
            {
                HiddenField hfPhoneType = item.FindControl( "hfPhoneType" ) as HiddenField;
                PhoneNumberBox pnbPhone = item.FindControl( "pnbPhone" ) as PhoneNumberBox;
                CheckBox cbUnlisted = item.FindControl( "cbUnlisted" ) as CheckBox;
                CheckBox cbSms = item.FindControl( "cbSms" ) as CheckBox;

                if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) )
                {
                    int phoneNumberTypeId;
                    if ( int.TryParse( hfPhoneType.Value, out phoneNumberTypeId ) )
                    {
                        var phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId };
                        person.PhoneNumbers.Add( phoneNumber );
                        phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode );
                        phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number );

                        // Only allow one number to have SMS selected
                        if ( smsSelected )
                        {
                            phoneNumber.IsMessagingEnabled = false;
                        }
                        else
                        {
                            phoneNumber.IsMessagingEnabled = cbSms.Checked;
                            smsSelected = cbSms.Checked;
                        }

                        phoneNumber.IsUnlisted = cbUnlisted.Checked;
                    }
                }
            }

            PersonService.SaveNewPerson( person, rockContext, null, false );

            // save address
            if ( pnlAddress.Visible )
            {
                if ( acAddress.IsValid && !string.IsNullOrWhiteSpace(acAddress.Street1) && !string.IsNullOrWhiteSpace( acAddress.City ) && !string.IsNullOrWhiteSpace( acAddress.PostalCode ) )
                {
                    Guid locationTypeGuid = GetAttributeValue( "LocationType" ).AsGuid();
                    if ( locationTypeGuid != Guid.Empty )
                    {
                        Guid familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
                        GroupService groupService = new GroupService( rockContext );
                        GroupLocationService groupLocationService = new GroupLocationService( rockContext );
                        var family = groupService.Queryable().Where( g => g.GroupType.Guid == familyGroupTypeGuid && g.Members.Any( m => m.PersonId == person.Id ) ).FirstOrDefault();

                        var groupLocation = new GroupLocation();
                        groupLocation.GroupId = family.Id;
                        groupLocationService.Add( groupLocation );

                        var location = new LocationService( rockContext ).Get( acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country );
                        groupLocation.Location = location;

                        groupLocation.GroupLocationTypeValueId = DefinedValueCache.Read( locationTypeGuid).Id;
                        groupLocation.IsMailingLocation = true;
                        groupLocation.IsMappedLocation = true;

                        rockContext.SaveChanges();
                    }
                }
            }

            return person;
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Handles the Click event of the btnSaveGroup 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 btnSaveGroup_Click(object sender, EventArgs e)
        {
            var          rockContext  = new RockContext();
            GroupService groupService = new GroupService(rockContext);

            Group group = groupService.Get(_groupId);

            if (group != null && group.IsAuthorized(Authorization.EDIT, CurrentPerson))
            {
                group.Name        = tbName.Text;
                group.Description = tbDescription.Text;
                group.IsActive    = cbIsActive.Checked;

                if (pnlSchedule.Visible)
                {
                    if (group.Schedule == null)
                    {
                        group.Schedule = new Schedule();
                        group.Schedule.iCalendarContent = null;
                    }

                    group.Schedule.WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek;
                    group.Schedule.WeeklyTimeOfDay = timeWeekly.SelectedTime;
                }

                // set attributes
                group.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributes, group);

                // configure locations
                if (GetAttributeValue("EnableLocationEdit").AsBoolean())
                {
                    // get selected location
                    Location location            = null;
                    int?     memberPersonAliasId = null;

                    if (LocationTypeTab.Equals(MEMBER_LOCATION_TAB_TITLE))
                    {
                        if (ddlMember.SelectedValue != null)
                        {
                            var ids = ddlMember.SelectedValue.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                            if (ids.Length == 2)
                            {
                                var dbLocation = new LocationService(rockContext).Get(int.Parse(ids[0]));
                                if (dbLocation != null)
                                {
                                    location = dbLocation;
                                }

                                memberPersonAliasId = new PersonAliasService(rockContext).GetPrimaryAliasId(int.Parse(ids[1]));
                            }
                        }
                    }
                    else
                    {
                        if (locpGroupLocation.Location != null)
                        {
                            location = new LocationService(rockContext).Get(locpGroupLocation.Location.Id);
                        }
                    }

                    if (location != null)
                    {
                        GroupLocation groupLocation = group.GroupLocations.FirstOrDefault();

                        if (groupLocation == null)
                        {
                            groupLocation = new GroupLocation();
                            group.GroupLocations.Add(groupLocation);
                        }

                        groupLocation.GroupMemberPersonAliasId = memberPersonAliasId;
                        groupLocation.Location   = location;
                        groupLocation.LocationId = groupLocation.Location.Id;
                        groupLocation.GroupLocationTypeValueId = ddlLocationType.SelectedValueAsId();
                    }
                }

                rockContext.SaveChanges();
                group.SaveAttributeValues(rockContext);
            }

            this.IsEditingGroup = false;

            // reload the group info
            pnlGroupEdit.Visible = false;
            pnlGroupView.Visible = true;
            DisplayViewGroup();
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Handles the Click event of the btnRegister 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 btnRegister_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid )
            {
                var rockContext = new RockContext();
                var personService = new PersonService( rockContext );

                Person person = null;
                Person spouse = null;
                Group family = null;
                GroupLocation homeLocation = null;

                var changes = new List<string>();
                var spouseChanges = new List<string>();
                var familyChanges = new List<string>();

                // Only use current person if the name entered matches the current person's name and autofill mode is true
                if ( _autoFill )
                {
                    if ( CurrentPerson != null &&
                        tbFirstName.Text.Trim().Equals( CurrentPerson.FirstName.Trim(), StringComparison.OrdinalIgnoreCase ) &&
                        tbLastName.Text.Trim().Equals( CurrentPerson.LastName.Trim(), StringComparison.OrdinalIgnoreCase ) )
                    {
                        person = personService.Get( CurrentPerson.Id );
                    }
                }

                // Try to find person by name/email
                if ( person == null )
                {
                    var matches = personService.GetByMatch( tbFirstName.Text.Trim(), tbLastName.Text.Trim(), tbEmail.Text.Trim() );
                    if ( matches.Count() == 1 )
                    {
                        person = matches.First();
                    }
                }

                // Check to see if this is a new person
                if ( person == null )
                {
                    // If so, create the person and family record for the new person
                    person = new Person();
                    person.FirstName = tbFirstName.Text.Trim();
                    person.LastName = tbLastName.Text.Trim();
                    person.Email = tbEmail.Text.Trim();
                    person.IsEmailActive = true;
                    person.EmailPreference = EmailPreference.EmailAllowed;
                    person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
                    person.ConnectionStatusValueId = _dvcConnectionStatus.Id;
                    person.RecordStatusValueId = _dvcRecordStatus.Id;
                    person.Gender = Gender.Unknown;

                    family = PersonService.SaveNewPerson( person, rockContext, _group.CampusId, false );
                }
                else
                {
                    // updating current existing person
                    History.EvaluateChange( changes, "Email", person.Email, tbEmail.Text );
                    person.Email = tbEmail.Text;

                    // Get the current person's families
                    var families = person.GetFamilies( rockContext );

                    // If address can being entered, look for first family with a home location
                    if ( !IsSimple )
                    {
                        foreach ( var aFamily in families )
                        {
                            homeLocation = aFamily.GroupLocations
                                .Where( l =>
                                    l.GroupLocationTypeValueId == _homeAddressType.Id &&
                                    l.IsMappedLocation )
                                .FirstOrDefault();
                            if ( homeLocation != null )
                            {
                                family = aFamily;
                                break;
                            }
                        }
                    }

                    // If a family wasn't found with a home location, use the person's first family
                    if ( family == null )
                    {
                        family = families.FirstOrDefault();
                    }
                }

                // If using a 'Full' view, save the phone numbers and address
                if ( !IsSimple )
                {
                    SetPhoneNumber( rockContext, person, pnHome, null, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid(), changes );
                    SetPhoneNumber( rockContext, person, pnCell, cbSms, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid(), changes );

                    string oldLocation = homeLocation != null ? homeLocation.Location.ToString() : string.Empty;
                    string newLocation = string.Empty;

                    var location = new LocationService( rockContext ).Get( acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country );
                    if ( location != null )
                    {
                        if ( homeLocation == null )
                        {
                            homeLocation = new GroupLocation();
                            homeLocation.GroupLocationTypeValueId = _homeAddressType.Id;
                            family.GroupLocations.Add( homeLocation );
                        }
                        else
                        {
                            oldLocation = homeLocation.Location.ToString();
                        }

                        homeLocation.Location = location;
                        newLocation = location.ToString();
                    }
                    else
                    {
                        if ( homeLocation != null )
                        {
                            homeLocation.Location = null;
                            family.GroupLocations.Remove( homeLocation );
                            new GroupLocationService( rockContext ).Delete( homeLocation );
                        }
                    }

                    History.EvaluateChange( familyChanges, "Home Location", oldLocation, newLocation );

                    // Check for the spouse
                    if ( IsFullWithSpouse && !string.IsNullOrWhiteSpace(tbSpouseFirstName.Text) && !string.IsNullOrWhiteSpace(tbSpouseLastName.Text) )
                    {
                        spouse = person.GetSpouse();
                        if ( spouse == null ||
                            !tbSpouseFirstName.Text.Trim().Equals( spouse.FirstName.Trim(), StringComparison.OrdinalIgnoreCase ) ||
                            !tbSpouseLastName.Text.Trim().Equals( spouse.LastName.Trim(), StringComparison.OrdinalIgnoreCase ) )
                        {
                            spouse = new Person();

                            spouse.FirstName = tbSpouseFirstName.Text;
                            History.EvaluateChange( spouseChanges, "First Name", string.Empty, spouse.FirstName );

                            spouse.LastName = tbSpouseLastName.Text;
                            History.EvaluateChange( spouseChanges, "Last Name", string.Empty, spouse.LastName );

                            spouse.ConnectionStatusValueId = _dvcConnectionStatus.Id;
                            spouse.RecordStatusValueId = _dvcRecordStatus.Id;
                            spouse.Gender = Gender.Unknown;

                            spouse.IsEmailActive = true;
                            spouse.EmailPreference = EmailPreference.EmailAllowed;

                            var groupMember = new GroupMember();
                            groupMember.GroupRoleId = _adultRole.Id;
                            groupMember.Person = spouse;

                            family.Members.Add( groupMember );

                            spouse.MaritalStatusValueId = _married.Id;
                            person.MaritalStatusValueId = _married.Id;
                        }

                        History.EvaluateChange( changes, "Email", person.Email, tbEmail.Text );
                        spouse.Email = tbSpouseEmail.Text;

                        SetPhoneNumber( rockContext, spouse, pnHome, null, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid(), spouseChanges );
                        SetPhoneNumber( rockContext, spouse, pnSpouseCell, cbSpouseSms, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid(), spouseChanges );
                    }
                }

                // Save the person/spouse and change history
                rockContext.SaveChanges();
                HistoryService.SaveChanges( rockContext, typeof( Person ),
                    Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes );
                HistoryService.SaveChanges( rockContext, typeof( Person ),
                    Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), person.Id, familyChanges );
                if ( spouse != null )
                {

                    HistoryService.SaveChanges( rockContext, typeof( Person ),
                        Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), spouse.Id, spouseChanges );
                    HistoryService.SaveChanges( rockContext, typeof( Person ),
                        Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), spouse.Id, familyChanges );
                }

                // Check to see if a workflow should be launched for each person
                WorkflowType workflowType = null;
                Guid? workflowTypeGuid = GetAttributeValue( "Workflow" ).AsGuidOrNull();
                if ( workflowTypeGuid.HasValue )
                {
                    var workflowTypeService = new WorkflowTypeService( rockContext );
                    workflowType = workflowTypeService.Get( workflowTypeGuid.Value );
                }

                // Save the registrations ( and launch workflows )
                var newGroupMembers = new List<GroupMember>();
                AddPersonToGroup( rockContext, person, workflowType, newGroupMembers );
                AddPersonToGroup( rockContext, spouse, workflowType, newGroupMembers );

                // Show the results
                pnlView.Visible = false;
                pnlResult.Visible = true;

                // Show lava content
                var mergeFields = new Dictionary<string, object>();
                mergeFields.Add( "Group", _group );
                mergeFields.Add( "GroupMembers", newGroupMembers );

                bool showDebug = UserCanEdit && GetAttributeValue( "EnableDebug" ).AsBoolean();
                lResultDebug.Visible = showDebug;
                if ( showDebug )
                {
                    lResultDebug.Text = mergeFields.lavaDebugInfo( _rockContext );
                }

                string template = GetAttributeValue( "ResultLavaTemplate" );
                lResult.Text = template.ResolveMergeFields( mergeFields );

                // Will only redirect if a value is specifed
                NavigateToLinkedPage( "ResultPage" );
            }
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            // get person
            Person person = null;

            string personAttributeValue = GetAttributeValue( action, "Person" );
            Guid? guidPersonAttribute = personAttributeValue.AsGuidOrNull();
            if ( guidPersonAttribute.HasValue )
            {
                var attributePerson = AttributeCache.Read( guidPersonAttribute.Value, rockContext );
                if ( attributePerson != null || attributePerson.FieldType.Class != "Rock.Field.Types.PersonFieldType" )
                {
                    string attributePersonValue = action.GetWorklowAttributeValue( guidPersonAttribute.Value );
                    if ( !string.IsNullOrWhiteSpace( attributePersonValue ) )
                    {
                        Guid personAliasGuid = attributePersonValue.AsGuid();
                        if ( !personAliasGuid.IsEmpty() )
                        {
                            person = new PersonAliasService( rockContext ).Queryable()
                                .Where( a => a.Guid.Equals( personAliasGuid ) )
                                .Select( a => a.Person )
                                .FirstOrDefault();
                            if ( person == null )
                            {
                                errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString() ) );
                                return false;
                            }
                        }
                    }
                }
            }

            if ( person == null )
            {
                errorMessages.Add( "The attribute used to provide the person was invalid, or not of type 'Person'." );
                return false;
            }

            // determine the location type to edit
            DefinedValueCache locationType = null;
            var locationTypeAttributeValue = action.GetWorklowAttributeValue( GetAttributeValue( action, "LocationTypeAttribute" ).AsGuid() );
            if ( locationTypeAttributeValue != null )
            {
                locationType = DefinedValueCache.Read( locationTypeAttributeValue.AsGuid() );
            }
            if ( locationType == null )
            {
                locationType = DefinedValueCache.Read( GetAttributeValue( action, "LocationType" ).AsGuid() );
            }
            if ( locationType == null )
            {
                errorMessages.Add( "The location type to be updated was not selected." );
                return false;
            }

            // get the new phone number value
            Location location = null;
            string locationValue = GetAttributeValue( action, "Location" );
            Guid? locationGuid = locationValue.AsGuidOrNull();
            if ( !locationGuid.HasValue || locationGuid.Value.IsEmpty() )
            {
                string locationAttributeValue = GetAttributeValue( action, "LocationAttribute" );
                Guid? locationAttributeValueGuid = locationAttributeValue.AsGuidOrNull();
                if ( locationAttributeValueGuid.HasValue )
                {
                    locationGuid = action.GetWorklowAttributeValue( locationAttributeValueGuid.Value ).AsGuidOrNull();
                }
            }

            if ( locationGuid.HasValue )
            {
                location = new LocationService( rockContext ).Get( locationGuid.Value );
            }

            if ( location == null )
            {
                errorMessages.Add( "The location value could not be determined." );
                return false;
            }

            // gets value indicating if location is a mailing location
            string mailingValue = GetAttributeValue( action, "IsMailing" );
            Guid? mailingValueGuid = mailingValue.AsGuidOrNull();
            if ( mailingValueGuid.HasValue )
            {
                mailingValue = action.GetWorklowAttributeValue( mailingValueGuid.Value );
            }
            else
            {
                mailingValue = mailingValue.ResolveMergeFields( GetMergeFields( action ) );
            }
            bool? mailing = mailingValue.AsBooleanOrNull();

            // gets value indicating if location is a mapped location
            string mappedValue = GetAttributeValue( action, "IsMapped" );
            Guid? mappedValueGuid = mappedValue.AsGuidOrNull();
            if ( mappedValueGuid.HasValue )
            {
                mappedValue = action.GetWorklowAttributeValue( mappedValueGuid.Value );
            }
            else
            {
                mappedValue = mappedValue.ResolveMergeFields( GetMergeFields( action ) );
            }
            bool? mapped = mappedValue.AsBooleanOrNull();

            var groupLocationService = new GroupLocationService( rockContext );
            foreach ( var family in person.GetFamilies( rockContext ).ToList() )
            {
                var groupLocation = family.GroupLocations.FirstOrDefault( l => l.GroupLocationTypeValueId == locationType.Id );
                string oldValue = string.Empty;
                if ( groupLocation == null )
                {
                    groupLocation = new GroupLocation();
                    groupLocation.GroupId = family.Id;
                    groupLocation.GroupLocationTypeValueId = locationType.Id;
                    groupLocationService.Add( groupLocation );
                }
                else
                {
                    oldValue = groupLocation.Location.ToString();
                }

                var groupChanges = new List<string>();

                History.EvaluateChange(
                    groupChanges,
                    locationType.Value + " Location",
                    oldValue,
                    location.ToString() );

                groupLocation.Location = location;

                if ( mailing.HasValue )
                {
                    History.EvaluateChange(
                        groupChanges,
                        locationType.Value + " Is Mailing",
                        groupLocation.IsMailingLocation.ToString(),
                        mailing.Value.ToString() );
                    groupLocation.IsMailingLocation = mailing.Value;
                }

                if ( mapped.HasValue )
                {
                    History.EvaluateChange(
                        groupChanges,
                        locationType.Value + " Is Map Location",
                        groupLocation.IsMappedLocation.ToString(),
                        mapped.Value.ToString() );
                    groupLocation.IsMappedLocation = mapped.Value;
                }

                if ( groupChanges.Any() )
                {
                    groupChanges.Add( string.Format( "<em>(Updated by the '{0}' workflow)</em>", action.ActionType.ActivityType.WorkflowType.Name ) );
                    foreach ( var fm in family.Members )
                    {
                        HistoryService.SaveChanges(
                            rockContext,
                            typeof( Person ),
                            Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            fm.PersonId,
                            groupChanges,
                            family.Name,
                            typeof( Group ),
                            family.Id,
                            false );
                    }
                }

                rockContext.SaveChanges();

                action.AddLogEntry( string.Format( "Updated the {0} location for {1} (family: {2}) to {3}", locationType.Value, person.FullName, family.Name, location.ToString() ) );
            }

            return true;
        }
        /// <summary>
        /// Adds the new family address.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="family">The family.</param>
        /// <param name="locationTypeGuid">The location type unique identifier.</param>
        /// <param name="street1">The street1.</param>
        /// <param name="street2">The street2.</param>
        /// <param name="city">The city.</param>
        /// <param name="state">The state.</param>
        /// <param name="postalCode">The postal code.</param>
        /// <param name="country">The country.</param>
        /// <param name="moveExistingToPrevious">if set to <c>true</c> [move existing to previous].</param>
        public static void AddNewFamilyAddress( RockContext rockContext, Group family, string locationTypeGuid,
            string street1, string street2, string city, string state, string postalCode, string country, bool moveExistingToPrevious = false )
        {
            if ( !String.IsNullOrWhiteSpace( street1 ) ||
                 !String.IsNullOrWhiteSpace( street2 ) ||
                 !String.IsNullOrWhiteSpace( city ) ||
                 !String.IsNullOrWhiteSpace( postalCode ) ||
                 !string.IsNullOrWhiteSpace( country ) )
            {
                var locationType = Rock.Web.Cache.DefinedValueCache.Read( locationTypeGuid.AsGuid() );
                if ( locationType != null )
                {
                    var location = new LocationService( rockContext ).Get( street1, street2, city, state, postalCode, country );
                    if ( location != null )
                    {
                        var groupLocationService = new GroupLocationService( rockContext );
                        if ( !groupLocationService.Queryable()
                            .Where( gl =>
                                gl.GroupId == family.Id &&
                                gl.GroupLocationTypeValueId == locationType.Id &&
                                gl.LocationId == location.Id )
                            .Any() )
                        {

                            var familyChanges = new List<string>();

                            if ( moveExistingToPrevious )
                            {
                                var prevLocationType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS );
                                if ( prevLocationType != null )
                                {
                                    foreach ( var prevLoc in groupLocationService.Queryable( "Location,GroupLocationTypeValue" )
                                        .Where( gl =>
                                            gl.GroupId == family.Id &&
                                            gl.GroupLocationTypeValueId == locationType.Id ) )
                                    {
                                        History.EvaluateChange( familyChanges, prevLoc.Location.ToString(), prevLoc.GroupLocationTypeValue.Value, prevLocationType.Value );
                                        prevLoc.GroupLocationTypeValueId = prevLocationType.Id;
                                        prevLoc.IsMailingLocation = false;
                                        prevLoc.IsMappedLocation = false;
                                    }
                                }
                            }

                            string addressChangeField = locationType.Value;

                            var groupLocation = groupLocationService.Queryable()
                                .Where( gl =>
                                    gl.GroupId == family.Id &&
                                    gl.LocationId == location.Id )
                                .FirstOrDefault();
                            if ( groupLocation == null )
                            {
                                groupLocation = new GroupLocation();
                                groupLocation.Location = location;
                                groupLocation.IsMailingLocation = true;
                                groupLocation.IsMappedLocation = true;
                                family.GroupLocations.Add( groupLocation );
                            }
                            groupLocation.GroupLocationTypeValueId = locationType.Id;

                            History.EvaluateChange( familyChanges, addressChangeField, string.Empty, groupLocation.Location.ToString() );
                            History.EvaluateChange( familyChanges, addressChangeField + " Is Mailing", string.Empty, groupLocation.IsMailingLocation.ToString() );
                            History.EvaluateChange( familyChanges, addressChangeField + " Is Map Location", string.Empty, groupLocation.IsMappedLocation.ToString() );

                            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 );
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Handles the SaveClick event of the dlgLocations 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 dlgLocations_SaveClick( object sender, EventArgs e )
        {
            Location location = null;
            int? memberPersonId = null;
            RockContext rockContext = new RockContext();

            if ( LocationTypeTab.Equals( MEMBER_LOCATION_TAB_TITLE ) )
            {
                if ( ddlMember.SelectedValue != null )
                {
                    var ids = ddlMember.SelectedValue.Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries );
                    if ( ids.Length == 2 )
                    {
                        var dbLocation = new LocationService( rockContext ).Get( int.Parse( ids[0] ) );
                        if ( dbLocation != null )
                        {
                            location = new Location();
                            location.CopyPropertiesFrom( dbLocation );
                        }

                        memberPersonId = int.Parse( ids[1] );
                    }
                }
            }
            else
            {
                if ( locpGroupLocation.Location != null )
                {
                    location = new Location();
                    location.CopyPropertiesFrom( locpGroupLocation.Location );
                }
            }

            if ( location != null )
            {
                GroupLocation groupLocation = null;

                Guid guid = hfAddLocationGroupGuid.Value.AsGuid();
                if ( !guid.IsEmpty() )
                {
                    groupLocation = GroupLocationsState.FirstOrDefault( l => l.Guid.Equals( guid ) );
                }

                if ( groupLocation == null )
                {
                    groupLocation = new GroupLocation();
                    GroupLocationsState.Add( groupLocation );
                }

                groupLocation.GroupMemberPersonId = memberPersonId;
                groupLocation.Location = location;
                groupLocation.LocationId = groupLocation.Location.Id;
                groupLocation.GroupLocationTypeValueId = ddlLocationType.SelectedValueAsId();

                if ( groupLocation.GroupLocationTypeValueId.HasValue )
                {
                    groupLocation.GroupLocationTypeValue = new DefinedValue();
                    var definedValue = new DefinedValueService( rockContext ).Get( groupLocation.GroupLocationTypeValueId.Value );
                    if ( definedValue != null )
                    {
                        groupLocation.GroupLocationTypeValue.CopyPropertiesFrom( definedValue );
                    }
                }
            }

            BindLocationsGrid();

            HideDialog();
        }
Ejemplo n.º 47
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 )
        {
            // if a Location is getting edited, validate and save it
            if ( gLocations.EditIndex >= 0 )
            {
                var row = gLocations.Rows[gLocations.EditIndex];
                AddressControl acAddress = row.FindControl( "acAddress" ) as AddressControl;
                if ( acAddress.IsValid )
                {
                    gLocations_RowUpdating( sender, new GridViewUpdateEventArgs( gLocations.EditIndex ) );
                }
                else
                {
                    // acAddress will render an error message
                    return;
                }
            }

            if ( !IsUserAuthorized( Rock.Security.Authorization.EDIT ) )
            {
                return;
            }

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

                var rockContext = new RockContext();
                rockContext.WrapTransaction( () =>
                {
                    var groupService = new GroupService( rockContext );
                    var groupMemberService = new GroupMemberService( rockContext );
                    var personService = new PersonService( rockContext );
                    var historyService = new HistoryService( rockContext );

                    var groupChanges = new List<string>();

                    // SAVE GROUP
                    _group = groupService.Get( _group.Id );

                    History.EvaluateChange( groupChanges, "Group Name", _group.Name, tbGroupName.Text );
                    _group.Name = tbGroupName.Text;

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

                        _group.CampusId = campusId;
                    }

                    rockContext.SaveChanges();

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

                    foreach ( var groupMemberInfo in GroupMembers )
                    {
                        var memberChanges = new List<string>();
                        var demographicChanges = new List<string>();

                        var role = _groupType.Roles.Where( r => r.Guid.Equals( groupMemberInfo.RoleGuid ) ).FirstOrDefault();
                        if ( role == null )
                        {
                            role = _groupType.Roles.FirstOrDefault();
                        }

                        bool isAdult = role != null && role.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT );

                        // People added to group (new or from other group )
                        if ( !groupMemberInfo.ExistingGroupMember )
                        {
                            Person person = null;
                            if ( groupMemberInfo.Id == -1 )
                            {
                                // added new person
                                demographicChanges.Add( "Created" );

                                person = new Person();

                                person.TitleValueId = groupMemberInfo.TitleValueId;
                                person.FirstName = groupMemberInfo.FirstName;
                                person.NickName = groupMemberInfo.NickName;
                                person.LastName = groupMemberInfo.LastName;
                                person.SuffixValueId = groupMemberInfo.SuffixValueId;
                                person.Gender = groupMemberInfo.Gender;

                                DateTime? birthdate = groupMemberInfo.BirthDate;
                                if ( birthdate.HasValue )
                                {
                                    // If setting a future birthdate, subtract a century until birthdate is not greater than today.
                                    var today = RockDateTime.Today;
                                    while ( birthdate.Value.CompareTo( today ) > 0 )
                                    {
                                        birthdate = birthdate.Value.AddYears( -100 );
                                    }
                                }

                                person.SetBirthDate( birthdate );

                                person.MaritalStatusValueId = groupMemberInfo.MaritalStatusValueId;
                                person.GradeOffset = groupMemberInfo.GradeOffset;
                                person.ConnectionStatusValueId = groupMemberInfo.ConnectionStatusValueId;
                                if ( isAdult )
                                {
                                    person.GivingGroupId = _group.Id;
                                }

                                person.IsEmailActive = true;
                                person.EmailPreference = EmailPreference.EmailAllowed;
                                person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
                            }
                            else
                            {
                                person = personService.Get( groupMemberInfo.Id );
                            }

                            if ( person == null )
                            {
                                // shouldn't happen
                                return;
                            }

                            if ( _isFamilyGroupType )
                            {
                                if ( person.RecordStatusValueId != recordStatusValueID )
                                {
                                    History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) );
                                    person.RecordStatusValueId = recordStatusValueID;
                                }

                                if ( person.RecordStatusValueId != recordStatusValueID )
                                {
                                    History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) );
                                    person.RecordStatusReasonValueId = reasonValueId;
                                }
                            }

                            PersonService.AddPersonToGroup( person, person.Id == 0, _group.Id, role.Id, rockContext );
                        }
                        else
                        {
                            // existing group members
                            var groupMember = groupMemberService.Queryable( "Person", true ).Where( m =>
                                m.PersonId == groupMemberInfo.Id &&
                                m.Group.GroupTypeId == _groupType.Id &&
                                m.GroupId == _group.Id ).FirstOrDefault();

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

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

                                        newGroup.GroupTypeId = _groupType.Id;

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

                                        newGroup.CampusId = _group.CampusId;

                                        groupService.Add( newGroup );
                                        rockContext.SaveChanges();

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

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

                                        var newMemberChanges = new List<string>();

                                        if ( _isFamilyGroupType )
                                        {
                                            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,
                                                newGroup.Name,
                                                typeof( Group ),
                                                newGroup.Id );
                                        }
                                        newGroups.Add( newGroup );

                                        History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole.Name, string.Empty );
                                    }
                                    else
                                    {
                                        History.EvaluateChange( groupChanges, "Family", groupMember.Group.Name, string.Empty );

                                        groupMemberService.Delete( groupMember );
                                        rockContext.SaveChanges();
                                    }
                                }
                                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 ( _isFamilyGroupType )
                                        {
                                            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 ( groupMemberInfo.RemoveFromOtherGroups )
                        {
                            PersonService.RemovePersonFromOtherFamilies( _group.Id, groupMemberInfo.Id, rockContext );
                        }

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

                        if ( _isFamilyGroupType )
                        {
                            HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), groupMemberInfo.Id, memberChanges, _group.Name, typeof( Group ), _group.Id );
                        }
                    }

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

                    // delete any group locations that were removed
                    var remainingLocationIds = GroupAddresses.Where( a => a.Id > 0 ).Select( a => a.Id ).ToList();
                    foreach ( var removedLocation in groupLocationService.Queryable( "GroupLocationTypeValue,Location" )
                        .Where( l => l.GroupId == _group.Id &&
                            !remainingLocationIds.Contains( l.Id ) ) )
                    {
                        History.EvaluateChange( groupChanges,
                            ( removedLocation.GroupLocationTypeValue != null ? removedLocation.GroupLocationTypeValue.Value : "Unknown" ) + " Location",
                            removedLocation.Location.ToString(), string.Empty );
                        groupLocationService.Delete( removedLocation );
                    }

                    rockContext.SaveChanges();

                    foreach ( var groupAddressInfo in GroupAddresses.Where( a => a.Id >= 0 ) )
                    {
                        Location updatedAddress = null;
                        if ( groupAddressInfo.LocationIsDirty )
                        {
                            updatedAddress = new LocationService( rockContext ).Get( groupAddressInfo.Street1, groupAddressInfo.Street2, groupAddressInfo.City, groupAddressInfo.State, groupAddressInfo.PostalCode, groupAddressInfo.Country );
                        }

                        GroupLocation groupLocation = null;
                        if ( groupAddressInfo.Id > 0 )
                        {
                            groupLocation = groupLocationService.Get( groupAddressInfo.Id );
                        }

                        if ( groupLocation == null )
                        {
                            groupLocation = new GroupLocation();
                            groupLocation.GroupId = _group.Id;
                            groupLocationService.Add( groupLocation );
                        }

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

                        History.EvaluateChange(
                            groupChanges,
                            groupAddressInfo.LocationTypeName + " Is Mailing",
                            groupLocation.IsMailingLocation.ToString(),
                            groupAddressInfo.IsMailing.ToString() );

                        groupLocation.IsMailingLocation = groupAddressInfo.IsMailing;

                        History.EvaluateChange(
                            groupChanges,
                            groupAddressInfo.LocationTypeName + " Is Map Location",
                            groupLocation.IsMappedLocation.ToString(),
                            groupAddressInfo.IsLocation.ToString() );

                        groupLocation.IsMappedLocation = groupAddressInfo.IsLocation;

                        if ( updatedAddress != null )
                        {
                            History.EvaluateChange(
                                groupChanges,
                                groupAddressInfo.LocationTypeName + " Location",
                                groupLocation.Location != null ? groupLocation.Location.ToString() : string.Empty,
                                updatedAddress.ToString() );
                            groupLocation.Location = updatedAddress;
                        }

                        rockContext.SaveChanges();

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

                            rockContext.SaveChanges();
                        }
                    }

                    _group.LoadAttributes();
                    Rock.Attribute.Helper.GetEditValues( phGroupAttributes, _group );
                    _group.SaveAttributeValues( rockContext );

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

                    Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false );

                } );
            }
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Wählt eine Quellgruppe aus.
        /// </summary>
        /// <param name="group">Díe Daten der Quellgruppe.</param>
        /// <param name="location">Die Wahl des Ursprungs, über den die Quellgruppe empfangen werden kann.</param>
        public void Tune( SourceGroup group, GroupLocation location )
        {
            // May repeat some times
            for (int retryCount = 3; retryCount-- > 0; Thread.Sleep( 250 ))
            {
                // All supported in order of importance
                if (!Tune( group as SatelliteGroup, location as SatelliteLocation ).HasValue)
                    if (!Tune( group as CableGroup ).HasValue)
                        if (!Tune( group as TerrestrialGroup ).HasValue)
                            throw new DVBException( "Unsupported channel type " + group.GetType().FullName );

                // Done if locked
                if (SignalStatus.Locked)
                    break;

                // Enforce reset
                m_lastMessage = null;
            }
        }
Ejemplo n.º 49
0
        /// <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)
        {
            var rockContext = new RockContext();

            var    personService = new PersonService(rockContext);
            Person business      = null;

            if (int.Parse(hfBusinessId.Value) != 0)
            {
                business = personService.Get(int.Parse(hfBusinessId.Value));
            }

            if (business == null)
            {
                business = new Person();
                personService.Add(business);
                tbBusinessName.Text = tbBusinessName.Text.FixCase();
            }

            // Business Name
            business.LastName = tbBusinessName.Text;

            // Phone Number
            var businessPhoneTypeId = new DefinedValueService(rockContext).GetByGuid(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK)).Id;

            var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == businessPhoneTypeId);

            if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
            {
                if (phoneNumber == null)
                {
                    phoneNumber = new PhoneNumber {
                        NumberTypeValueId = businessPhoneTypeId
                    };
                    business.PhoneNumbers.Add(phoneNumber);
                }
                phoneNumber.CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                phoneNumber.Number             = PhoneNumber.CleanNumber(pnbPhone.Number);
                phoneNumber.IsMessagingEnabled = cbSms.Checked;
                phoneNumber.IsUnlisted         = cbUnlisted.Checked;
            }
            else
            {
                if (phoneNumber != null)
                {
                    business.PhoneNumbers.Remove(phoneNumber);
                    new PhoneNumberService(rockContext).Delete(phoneNumber);
                }
            }

            // Record Type - this is always "business". it will never change.
            business.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id;

            // Record Status
            business.RecordStatusValueId = dvpRecordStatus.SelectedValueAsInt();;

            // Record Status Reason
            int?newRecordStatusReasonId = null;

            if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id)
            {
                newRecordStatusReasonId = dvpReason.SelectedValueAsInt();
            }
            business.RecordStatusReasonValueId = newRecordStatusReasonId;

            // Email
            business.IsEmailActive   = true;
            business.Email           = tbEmail.Text.Trim();
            business.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();

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

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

                // Add/Update Family Group
                var familyGroupType = GroupTypeCache.GetFamilyGroupType();
                int adultRoleId     = familyGroupType.Roles
                                      .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()))
                                      .Select(r => r.Id)
                                      .FirstOrDefault();
                var adultFamilyMember = UpdateGroupMember(business.Id, familyGroupType, business.LastName + " Business", ddlCampus.SelectedValueAsInt(), adultRoleId, rockContext);
                business.GivingGroup  = adultFamilyMember.Group;

                // Add/Update Known Relationship Group Type
                var knownRelationshipGroupType   = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid());
                int knownRelationshipOwnerRoleId = knownRelationshipGroupType.Roles
                                                   .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()))
                                                   .Select(r => r.Id)
                                                   .FirstOrDefault();
                var knownRelationshipOwner = UpdateGroupMember(business.Id, knownRelationshipGroupType, "Known Relationship", null, knownRelationshipOwnerRoleId, rockContext);

                // Add/Update Implied Relationship Group Type
                var impliedRelationshipGroupType   = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_PEER_NETWORK.AsGuid());
                int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles
                                                     .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_PEER_NETWORK_OWNER.AsGuid()))
                                                     .Select(r => r.Id)
                                                     .FirstOrDefault();
                var impliedRelationshipOwner = UpdateGroupMember(business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext);

                rockContext.SaveChanges();

                // Location
                int workLocationTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK).Id;

                var groupLocationService = new GroupLocationService(rockContext);
                var workLocation         = groupLocationService.Queryable("Location")
                                           .Where(gl =>
                                                  gl.GroupId == adultFamilyMember.Group.Id &&
                                                  gl.GroupLocationTypeValueId == workLocationTypeId)
                                           .FirstOrDefault();

                if (string.IsNullOrWhiteSpace(acAddress.Street1))
                {
                    if (workLocation != null)
                    {
                        groupLocationService.Delete(workLocation);
                    }
                }
                else
                {
                    var newLocation = new LocationService(rockContext).Get(
                        acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                    if (workLocation == null)
                    {
                        workLocation = new GroupLocation();
                        groupLocationService.Add(workLocation);
                        workLocation.GroupId = adultFamilyMember.Group.Id;
                        workLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                    workLocation.Location          = newLocation;
                    workLocation.IsMailingLocation = true;
                }

                rockContext.SaveChanges();

                hfBusinessId.Value = business.Id.ToString();
            });

            var queryParams = new Dictionary <string, string>();

            queryParams.Add("BusinessId", hfBusinessId.Value);
            NavigateToCurrentPage(queryParams);
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Handles adding groups from the given XML element snippet.
        /// </summary>
        /// <param name="elemGroups">The elem groups.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <exception cref="System.NotSupportedException"></exception>
        private void AddGroups( XElement elemGroups, RockContext rockContext )
        {
            // Add groups
            if ( elemGroups == null )
            {
                return;
            }

            GroupService groupService = new GroupService( rockContext );
            DefinedTypeCache smallGroupTopicType = DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.SMALL_GROUP_TOPIC.AsGuid() );

            // Next create the group along with its members.
            foreach ( var elemGroup in elemGroups.Elements( "group" ) )
            {
                Guid guid = elemGroup.Attribute( "guid" ).Value.Trim().AsGuid();
                string type = elemGroup.Attribute( "type" ).Value;
                Group group = new Group()
                {
                    Guid = guid,
                    Name = elemGroup.Attribute( "name" ).Value.Trim(),
                    IsActive = true,
                    IsPublic = true
                };

                // skip any where there is no group type given -- they are invalid entries.
                if ( string.IsNullOrEmpty( elemGroup.Attribute( "type" ).Value.Trim() ) )
                {
                    return;
                }

                int? roleId;
                GroupTypeCache groupType;
                switch ( elemGroup.Attribute( "type" ).Value.Trim() )
                {
                    case "serving":
                        groupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_SERVING_TEAM.AsGuid() );
                        group.GroupTypeId = groupType.Id;
                        roleId = groupType.DefaultGroupRoleId;
                        break;
                    case "smallgroup":
                        groupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_SMALL_GROUP.AsGuid() );
                        group.GroupTypeId = groupType.Id;
                        roleId = groupType.DefaultGroupRoleId;
                        break;
                    default:
                        throw new NotSupportedException( string.Format( "unknown group type {0}", elemGroup.Attribute( "type" ).Value.Trim() ) );
                }

                if ( elemGroup.Attribute( "description" ) != null )
                {
                    group.Description = elemGroup.Attribute( "description" ).Value;
                }

                if ( elemGroup.Attribute( "parentGroupGuid" ) != null )
                {
                    var parentGroup = groupService.Get( elemGroup.Attribute( "parentGroupGuid" ).Value.AsGuid() );
                    if ( parentGroup != null )
                    {
                        group.ParentGroupId = parentGroup.Id;
                    }
                }

                // Set the group's meeting location
                if ( elemGroup.Attribute( "meetsAtHomeOfFamily" ) != null )
                {
                    int meetingLocationValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION.AsGuid() ).Id;
                    var groupLocation = new GroupLocation()
                    {
                        IsMappedLocation = false,
                        IsMailingLocation = false,
                        GroupLocationTypeValueId = meetingLocationValueId,
                        LocationId = _familyLocationDictionary[elemGroup.Attribute( "meetsAtHomeOfFamily" ).Value.AsGuid()],
                    };

                    // Set the group location's GroupMemberPersonId if given (required?)
                    if ( elemGroup.Attribute( "meetsAtHomeOfPerson" ) != null )
                    {
                        groupLocation.GroupMemberPersonAliasId = _peopleAliasDictionary[elemGroup.Attribute( "meetsAtHomeOfPerson" ).Value.AsGuid()];
                    }

                    group.GroupLocations.Add( groupLocation );
                }

                group.LoadAttributes( rockContext );

                // Set the study topic
                if ( elemGroup.Attribute( "studyTopic" ) != null )
                {
                    var topic = elemGroup.Attribute( "studyTopic" ).Value;
                    DefinedValue smallGroupTopicDefinedValue = _smallGroupTopicDefinedType.DefinedValues.FirstOrDefault( a => a.Value == topic );

                    // add it as new if we didn't find it.
                    if ( smallGroupTopicDefinedValue == null )
                    {
                        smallGroupTopicDefinedValue = AddDefinedTypeValue( topic, _smallGroupTopicDefinedType, rockContext );
                    }

                    group.SetAttributeValue( "Topic", smallGroupTopicDefinedValue.Guid.ToString() );
                }

                // Set the schedule and meeting time
                if ( elemGroup.Attribute( "groupSchedule" ) != null )
                {
                    string[] schedule = elemGroup.Attribute( "groupSchedule" ).Value.SplitDelimitedValues( whitespace: false );

                    if ( schedule[0] == "weekly" )
                    {
                        var dow = schedule[1];
                        var time = schedule[2];
                        AddWeeklySchedule( group, dow, time );
                    }
                }

                // Add each person as a member
                foreach ( var elemPerson in elemGroup.Elements( "person" ) )
                {
                    Guid personGuid = elemPerson.Attribute( "guid" ).Value.Trim().AsGuid();

                    GroupMember groupMember = new GroupMember();
                    groupMember.GroupMemberStatus = GroupMemberStatus.Active;

                    if ( elemPerson.Attribute( "isLeader" ) != null )
                    {
                        bool isLeader = elemPerson.Attribute( "isLeader" ).Value.Trim().AsBoolean();
                        if ( isLeader )
                        {
                            var gtLeaderRole = groupType.Roles.Where( r => r.IsLeader ).FirstOrDefault();
                            if ( gtLeaderRole != null )
                            {
                                groupMember.GroupRoleId = gtLeaderRole.Id;
                            }
                        }
                    }
                    else
                    {
                        groupMember.GroupRoleId = roleId ?? -1;
                    }

                    groupMember.PersonId = _peopleDictionary[personGuid];
                    group.Members.Add( groupMember );
                }

                groupService.Add( group );
                // Now we have to save changes in order for the attributes to be saved correctly.
                rockContext.SaveChanges();
                group.SaveAttributeValues( rockContext );

                if ( !_groupDictionary.ContainsKey( group.Guid ) )
                {
                    _groupDictionary.Add( group.Guid, group.Id );
                }

                // Now add any group location schedules
                LocationService locationService = new LocationService( rockContext );
                ScheduleService scheduleService = new ScheduleService( rockContext );
                Guid locationTypeMeetingLocationGuid = new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION );
                var locationTypeMeetingLocationId = Rock.Web.Cache.DefinedValueCache.Read( locationTypeMeetingLocationGuid ).Id;

                foreach ( var elemLocation in elemGroup.Elements( "location" ) )
                {
                    Guid locationGuid = elemLocation.Attribute( "guid" ).Value.Trim().AsGuid();
                    Location location = locationService.Get( locationGuid );
                    GroupLocation groupLocation = new GroupLocation();
                    groupLocation.Location = location;
                    groupLocation.GroupLocationTypeValueId = locationTypeMeetingLocationId;
                    group.GroupLocations.Add( groupLocation );

                    foreach ( var elemSchedule in elemLocation.Elements( "schedule" ) )
                    {
                        try
                        {
                            Guid scheduleGuid = elemSchedule.Attribute( "guid" ).Value.Trim().AsGuid();
                            Schedule schedule = scheduleService.Get( scheduleGuid );
                            groupLocation.Schedules.Add( schedule );
                        }
                        catch
                        { }
                    }
                    TimeSpan ts = _stopwatch.Elapsed;
                    AppendFormat( "{0:00}:{1:00}.{2:00} group location schedules added<br/>", ts.Minutes, ts.Seconds, ts.Milliseconds / 10 );
                }
             }
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Loads the polygon group data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadGroupPolygon(CSVInstance csvData)
        {
            // Required variables
            var lookupContext        = new RockContext();
            var numImportedGroups    = ImportedGroups.Count();
            var newGroupLocations    = new Dictionary <GroupLocation, string>();
            var currentGroup         = new Group();
            var coordinateString     = string.Empty;
            var startCoordinate      = string.Empty;
            var endCoordinate        = string.Empty;
            var geographicAreaTypeId = DefinedValueCache.Get("44990C3F-C45B-EDA3-4B65-A238A581A26F").Id;

            var completed = 0;

            ReportProgress(0, $"Starting polygon group import ({numImportedGroups:N0} already exist).");

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ((row = csvData.Database.FirstOrDefault()) != null)
            {
                var rowGroupKey = row[GroupId];
                var rowGroupId  = rowGroupKey.AsType <int?>();
                var rowLat      = row[Latitude];
                var rowLong     = row[Longitude];

                //
                // Determine if we are still working with the same group or not.
                //
                if (!string.IsNullOrWhiteSpace(rowGroupKey) && rowGroupKey != currentGroup.ForeignKey)
                {
                    if (!string.IsNullOrWhiteSpace(coordinateString))
                    {
                        if (startCoordinate != endCoordinate)
                        {
                            coordinateString = $"{coordinateString}|{startCoordinate}";
                        }

                        var coords = coordinateString.Split('|');
                        if (coords.Length > 3)
                        {
                            var polygon = CreatePolygonLocation(coordinateString, row[GroupCreatedDate], rowGroupKey, rowGroupId);

                            if (polygon != null)
                            {
                                var geographicArea = new GroupLocation
                                {
                                    LocationId               = polygon.Id,
                                    IsMailingLocation        = true,
                                    IsMappedLocation         = true,
                                    GroupLocationTypeValueId = geographicAreaTypeId,
                                    GroupId = currentGroup.Id
                                };
                                newGroupLocations.Add(geographicArea, currentGroup.ForeignKey);
                            }
                        }
                    }

                    currentGroup = LoadGroupBasic(lookupContext, rowGroupKey, row[GroupName], row[GroupCreatedDate], row[GroupType], row[GroupParentGroupId], row[GroupActive]);

                    // reset coordinateString
                    coordinateString = string.Empty;

                    if (!string.IsNullOrWhiteSpace(rowLat) && !string.IsNullOrWhiteSpace(rowLong) && rowLat.AsType <double>() != 0 && rowLong.AsType <double>() != 0)
                    {
                        coordinateString = $"{rowLat},{rowLong}";
                        startCoordinate  = $"{rowLat},{rowLong}";
                    }

                    //
                    // Set the group campus
                    //
                    var campusName = row[GroupCampus];
                    if (!string.IsNullOrWhiteSpace(campusName))
                    {
                        var groupCampus = CampusList.FirstOrDefault(c => c.Name.Equals(campusName, StringComparison.InvariantCultureIgnoreCase) ||
                                                                    c.ShortCode.Equals(campusName, StringComparison.InvariantCultureIgnoreCase));
                        if (groupCampus == null)
                        {
                            groupCampus = new Campus
                            {
                                IsSystem  = false,
                                Name      = campusName,
                                ShortCode = campusName.RemoveWhitespace(),
                                IsActive  = true
                            };
                            lookupContext.Campuses.Add(groupCampus);
                            lookupContext.SaveChanges(DisableAuditing);
                            CampusList.Add(groupCampus);
                        }

                        currentGroup.CampusId = groupCampus.Id;
                    }

                    //
                    // Set the group's sorting order.
                    //
                    var groupOrder = 9999;
                    int.TryParse(row[GroupOrder], out groupOrder);
                    currentGroup.Order = groupOrder;

                    //
                    // Changes to groups need to be saved right away since one group
                    // will reference another group.
                    //
                    lookupContext.SaveChanges();

                    completed++;

                    if (completed % (ReportingNumber * 10) < 1)
                    {
                        ReportProgress(0, $"{completed:N0} groups imported.");
                    }

                    if (completed % ReportingNumber < 1)
                    {
                        ReportPartialProgress();
                    }
                }
                else if (rowGroupKey == currentGroup.ForeignKey && (!string.IsNullOrWhiteSpace(rowLat) && !string.IsNullOrWhiteSpace(rowLong) && rowLat.AsType <double>() != 0 && rowLong.AsType <double>() != 0))
                {
                    coordinateString = $"{coordinateString}|{rowLat},{rowLong}";
                    endCoordinate    = $"{rowLat},{rowLong}";
                }
            }

            if (!string.IsNullOrWhiteSpace(coordinateString))
            {
                if (startCoordinate != endCoordinate)
                {
                    coordinateString = coordinateString + $"|{startCoordinate}";
                }

                var coords = coordinateString.Split('|');
                if (coords.Length > 3)
                {
                    var polygon = CreatePolygonLocation(coordinateString, currentGroup.CreatedDateTime.ToString(), currentGroup.ForeignKey, currentGroup.ForeignId);

                    if (polygon != null)
                    {
                        var geographicArea = new GroupLocation
                        {
                            LocationId               = polygon.Id,
                            IsMailingLocation        = true,
                            IsMappedLocation         = true,
                            GroupLocationTypeValueId = geographicAreaTypeId,
                            GroupId = currentGroup.Id
                        };
                        newGroupLocations.Add(geographicArea, currentGroup.ForeignKey);
                    }
                }
            }

            //
            // Save rows to the database
            //
            ReportProgress(0, $"Saving {newGroupLocations.Count} polygons.");
            if (newGroupLocations.Any())
            {
                SaveGroupLocations(newGroupLocations);
            }

            lookupContext.SaveChanges();
            DetachAllInContext(lookupContext);
            lookupContext.Dispose();

            ReportProgress(0, $"Finished polygon group import: {completed:N0} groups added or updated.");

            return(completed);
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Adds the new family address.
        /// </summary>
        /// <param name="family">The family.</param>
        /// <param name="locationTypeGuid">The location type unique identifier.</param>
        /// <param name="street1">The street1.</param>
        /// <param name="street2">The street2.</param>
        /// <param name="city">The city.</param>
        /// <param name="state">The state.</param>
        /// <param name="postalCode">The zip.</param>
        /// <param name="rockContext">The rock context.</param>
        public void AddNewFamilyAddress( Group family, string locationTypeGuid, 
            string street1, string street2, string city, string state, string postalCode, string country,
            RockContext rockContext )
        {
            if ( !string.IsNullOrWhiteSpace( street1 ) ||
                 !string.IsNullOrWhiteSpace( street2 ) ||
                 !string.IsNullOrWhiteSpace( city ) ||
                 !string.IsNullOrWhiteSpace( postalCode ) ||
                 !string.IsNullOrWhiteSpace( country ) )
            {
                var groupLocation = new GroupLocation();

                // Get new or existing location and associate it with group
                var location = new LocationService( rockContext ).Get( street1, street2, city, state, postalCode, country );
                groupLocation.Location = location;
                groupLocation.IsMailingLocation = true;
                groupLocation.IsMappedLocation = true;

                Guid guid = Guid.Empty;
                if ( Guid.TryParse( locationTypeGuid, out guid ) )
                {
                    var locationType = Rock.Web.Cache.DefinedValueCache.Read( guid );
                    if ( locationType != null )
                    {
                        groupLocation.GroupLocationTypeValueId = locationType.Id;
                    }
                }

                family.GroupLocations.Add( groupLocation );
            }
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Gets or sets the group.
        /// </summary>
        /// <value>
        /// The group.
        /// </value>
        public Group GetGroup()
        {
            EnsureChildControls();
            Group result = new Group();

            result.Id = _hfGroupTypeId.ValueAsInt();
            result.Guid = new Guid( _hfGroupGuid.Value );
            result.GroupTypeId = _hfGroupTypeId.ValueAsInt();

            // get the current InheritedGroupTypeId from the Parent Editor just in case it hasn't been saved to the database
            CheckinGroupTypeEditor checkinGroupTypeEditor = this.Parent as CheckinGroupTypeEditor;
            if ( checkinGroupTypeEditor != null )
            {
                result.GroupType = new GroupType();
                result.GroupType.Id = result.GroupTypeId;
                result.GroupType.Guid = checkinGroupTypeEditor.GroupTypeGuid;
                result.GroupType.InheritedGroupTypeId = checkinGroupTypeEditor.InheritedGroupTypeId;
            }

            result.Name = _tbGroupName.Text;
            result.LoadAttributes();

            // populate groupLocations with whatever is currently in the grid, with just enough info to repopulate it and save it later
            result.GroupLocations = new List<GroupLocation>();
            foreach ( var item in this.Locations )
            {
                var groupLocation = new GroupLocation();
                groupLocation.LocationId = item.LocationId;
                groupLocation.Location = new Location { Id = item.LocationId, Name = item.Name };
                result.GroupLocations.Add( groupLocation );
            }

            Rock.Attribute.Helper.GetEditValues( _phGroupAttributes, result );
            return result;
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Wählt eine Quellgruppe aus.
        /// </summary>
        /// <param name="group">Díe Daten der Quellgruppe.</param>
        /// <param name="location">Die Wahl des Ursprungs, über den die Quellgruppe empfangen werden kann.</param>
        /// <returns>Gesetzt, wenn es sich um eine DVB-S Quellgruppe handelt.</returns>
        public void SetChannel( SourceGroup group, GroupLocation location )
        {
            // Always stop CI
            Decrypt( 0 );

            // Store
            Frontend.SetChannel( group, location );
        }
Ejemplo n.º 55
0
        /// <summary>
        /// Maps the family address.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="totalRows">The total rows.</param>
        private void MapFamilyAddress(IQueryable <Row> tableData, long totalRows = 0)
        {
            var lookupContext   = new RockContext();
            var locationService = new LocationService(lookupContext);

            var familyGroupMemberList = new GroupMemberService(lookupContext).Queryable().AsNoTracking()
                                        .Where(gm => gm.Group.GroupType.Guid.Equals(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY))).ToList();

            var customLocationTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.GROUP_LOCATION_TYPE), lookupContext).DefinedValues;

            const string otherGroupLocationName   = "Other (Imported)";
            var          otherGroupLocationTypeId = customLocationTypes.Where(dv => dv.TypeName == otherGroupLocationName)
                                                    .Select(v => (int?)v.Id).FirstOrDefault();

            if (!otherGroupLocationTypeId.HasValue)
            {
                var otherGroupLocationType = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.GROUP_LOCATION_TYPE, otherGroupLocationName);
                customLocationTypes.Add(otherGroupLocationType);
                otherGroupLocationTypeId = otherGroupLocationType.Id;
            }

            var newGroupLocations = new List <GroupLocation>();

            if (totalRows == 0)
            {
                totalRows = tableData.Count();
            }

            var completed  = 0;
            var percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, $"Verifying address import ({totalRows:N0} found).");

            foreach (var row in tableData.Where(r => r != null))
            {
                var individualId = row["Individual_ID"] as int?;
                var householdId  = row["Household_ID"] as int?;
                var personKeys   = GetPersonKeys(individualId, householdId, includeVisitors: false);
                if (personKeys != null)
                {
                    var familyGroup = familyGroupMemberList.Where(gm => gm.PersonId == personKeys.PersonId)
                                      .Select(gm => gm.Group).FirstOrDefault();

                    if (familyGroup != null)
                    {
                        var groupLocation = new GroupLocation();

                        var street1 = row["Address_1"] as string;
                        var street2 = row["Address_2"] as string;
                        var city    = row["City"] as string;
                        var state   = row["State"] as string;
                        var country = row["country"] as string; // NOT A TYPO: F1 has property in lower-case
                        var zip     = row["Postal_Code"] as string ?? string.Empty;

                        // restrict zip to 5 places to prevent duplicates
                        var familyAddress = locationService.Get(street1, street2, city, state, zip.Left(5), country, verifyLocation: false);

                        if (familyAddress != null)
                        {
                            familyAddress.CreatedByPersonAliasId = ImportPersonAliasId;
                            familyAddress.Name     = familyGroup.Name;
                            familyAddress.IsActive = true;

                            groupLocation.GroupId           = familyGroup.Id;
                            groupLocation.LocationId        = familyAddress.Id;
                            groupLocation.IsMailingLocation = false;
                            groupLocation.IsMappedLocation  = false;

                            var addressType = row["Address_Type"].ToString();
                            if (addressType.Equals("Primary", StringComparison.CurrentCultureIgnoreCase))
                            {
                                groupLocation.GroupLocationTypeValueId = HomeLocationTypeId;
                                groupLocation.IsMailingLocation        = true;
                                groupLocation.IsMappedLocation         = true;
                            }
                            else if (addressType.Equals("Business", StringComparison.CurrentCultureIgnoreCase) || addressType.StartsWith("Org", StringComparison.CurrentCultureIgnoreCase))
                            {
                                groupLocation.GroupLocationTypeValueId = WorkLocationTypeId;
                            }
                            else if (addressType.Equals("Previous", StringComparison.CurrentCultureIgnoreCase))
                            {
                                groupLocation.GroupLocationTypeValueId = PreviousLocationTypeId;
                            }
                            else if (!string.IsNullOrWhiteSpace(addressType))
                            {
                                // look for existing group location types, otherwise mark as imported
                                var customTypeId = customLocationTypes.Where(dv => dv.Value.Equals(addressType, StringComparison.CurrentCultureIgnoreCase))
                                                   .Select(dv => (int?)dv.Id).FirstOrDefault();
                                groupLocation.GroupLocationTypeValueId = customTypeId ?? otherGroupLocationTypeId;
                            }

                            newGroupLocations.Add(groupLocation);
                            completed++;

                            if (completed % percentage < 1)
                            {
                                var percentComplete = completed / percentage;
                                ReportProgress(percentComplete, $"{completed:N0} addresses imported ({percentComplete}% complete).");
                            }
                            else if (completed % ReportingNumber < 1)
                            {
                                SaveFamilyAddress(newGroupLocations);

                                // Reset context
                                newGroupLocations.Clear();
                                lookupContext   = new RockContext();
                                locationService = new LocationService(lookupContext);

                                ReportPartialProgress();
                            }
                        }
                    }
                }
            }

            if (newGroupLocations.Any())
            {
                SaveFamilyAddress(newGroupLocations);
            }

            ReportProgress(100, $"Finished address import: {completed:N0} addresses imported.");
        }
        /// <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 )
        {
            bool hasValidationErrors = false;

            var rockContext = new RockContext();

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

            int parentGroupTypeId = hfParentGroupTypeId.ValueAsInt();

            var groupTypeUIList = new List<GroupType>();

            foreach ( var checkinGroupTypeEditor in phCheckinGroupTypes.Controls.OfType<CheckinGroupTypeEditor>().ToList() )
            {
                var groupType = checkinGroupTypeEditor.GetCheckinGroupType( rockContext );
                groupTypeUIList.Add( groupType );
            }

            var groupTypeDBList = new List<GroupType>();

            var groupTypesToDelete = new List<GroupType>();
            var groupsToDelete = new List<Group>();

            var groupTypesToAddUpdate = new List<GroupType>();
            var groupsToAddUpdate = new List<Group>();

            GroupType parentGroupTypeDB = groupTypeService.Get( parentGroupTypeId );
            GroupType parentGroupTypeUI = parentGroupTypeDB.Clone( false );
            parentGroupTypeUI.ChildGroupTypes = groupTypeUIList;

            PopulateDeleteLists( groupTypesToDelete, groupsToDelete, parentGroupTypeDB, parentGroupTypeUI );
            PopulateAddUpdateLists( groupTypesToAddUpdate, groupsToAddUpdate, parentGroupTypeUI );

            int binaryFileFieldTypeID = FieldTypeCache.Read( Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid() ).Id;

            rockContext.WrapTransaction( () =>
            {
                // delete in reverse order to get deepest child items first
                groupsToDelete.Reverse();
                foreach ( var groupToDelete in groupsToDelete )
                {
                    groupService.Delete( groupToDelete );
                }

                // delete in reverse order to get deepest child items first
                groupTypesToDelete.Reverse();
                foreach ( var groupTypeToDelete in groupTypesToDelete )
                {
                    groupTypeService.Delete( groupTypeToDelete );
                }

                rockContext.SaveChanges();

                // Add/Update grouptypes and groups that are in the UI
                // Note:  We'll have to save all the groupTypes without changing the DB value of ChildGroupTypes, then come around again and save the ChildGroupTypes
                // since the ChildGroupTypes may not exist in the database yet
                foreach ( GroupType groupTypeUI in groupTypesToAddUpdate )
                {
                    GroupType groupTypeDB = groupTypeService.Get( groupTypeUI.Guid );
                    if ( groupTypeDB == null )
                    {
                        groupTypeDB = new GroupType();
                        groupTypeDB.Id = 0;
                        groupTypeDB.Guid = groupTypeUI.Guid;
                        groupTypeDB.IsSystem = false;
                        groupTypeDB.ShowInNavigation = false;
                        groupTypeDB.ShowInGroupList = false;
                        groupTypeDB.TakesAttendance = true;
                        groupTypeDB.AttendanceRule = AttendanceRule.None;
                        groupTypeDB.AttendancePrintTo = PrintTo.Default;
                        groupTypeDB.AllowMultipleLocations = true;
                        groupTypeDB.EnableLocationSchedules = true;
                    }

                    groupTypeDB.Name = groupTypeUI.Name;
                    groupTypeDB.Order = groupTypeUI.Order;
                    groupTypeDB.InheritedGroupTypeId = groupTypeUI.InheritedGroupTypeId;

                    groupTypeDB.Attributes = groupTypeUI.Attributes;
                    groupTypeDB.AttributeValues = groupTypeUI.AttributeValues;

                    if ( groupTypeDB.Id == 0 )
                    {
                        groupTypeService.Add( groupTypeDB );
                    }

                    if ( !groupTypeDB.IsValid )
                    {
                        hasValidationErrors = true;
                        CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupTypeEditor>().First( a => a.GroupTypeGuid == groupTypeDB.Guid );
                        groupTypeEditor.Expanded = true;

                        return;
                    }

                    rockContext.SaveChanges();

                    groupTypeDB.SaveAttributeValues( rockContext );

                    // get fresh from database to make sure we have Id so we can update the CheckinLabel Attributes
                    groupTypeDB = groupTypeService.Get( groupTypeDB.Guid );

                    // rebuild the CheckinLabel attributes from the UI (brute-force)
                    foreach ( var labelAttributeDB in CheckinGroupTypeEditor.GetCheckinLabelAttributes( groupTypeDB.Attributes, rockContext ) )
                    {
                        var attribute = attributeService.Get( labelAttributeDB.Value.Guid );
                        Rock.Web.Cache.AttributeCache.Flush( attribute.Id );
                        attributeService.Delete( attribute );
                    }

                    rockContext.SaveChanges();

                    foreach ( var checkinLabelAttributeInfo in GroupTypeCheckinLabelAttributesState[groupTypeUI.Guid] )
                    {
                        var attribute = new Rock.Model.Attribute();
                        attribute.AttributeQualifiers.Add( new AttributeQualifier { Key = "binaryFileType", Value = Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL } );
                        attribute.Guid = Guid.NewGuid();
                        attribute.FieldTypeId = binaryFileFieldTypeID;
                        attribute.EntityTypeId = EntityTypeCache.GetId( typeof( GroupType ) );
                        attribute.EntityTypeQualifierColumn = "Id";
                        attribute.EntityTypeQualifierValue = groupTypeDB.Id.ToString();
                        attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileGuid.ToString();
                        attribute.Key = checkinLabelAttributeInfo.AttributeKey;
                        attribute.Name = checkinLabelAttributeInfo.FileName;

                        if ( !attribute.IsValid )
                        {
                            hasValidationErrors = true;
                            CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupTypeEditor>().First( a => a.GroupTypeGuid == groupTypeDB.Guid );
                            groupTypeEditor.Expanded = true;

                            return;
                        }

                        attributeService.Add( attribute );
                    }

                    rockContext.SaveChanges();
                }

                // Add/Update Groups
                foreach ( var groupUI in groupsToAddUpdate )
                {
                    Group groupDB = groupService.Get( groupUI.Guid );
                    if ( groupDB == null )
                    {
                        groupDB = new Group();
                        groupDB.Guid = groupUI.Guid;
                    }

                    groupDB.Name = groupUI.Name;

                    // delete any GroupLocations that were removed in the UI
                    foreach ( var groupLocationDB in groupDB.GroupLocations.ToList() )
                    {
                        if ( !groupUI.GroupLocations.Select( a => a.LocationId ).Contains( groupLocationDB.LocationId ) )
                        {
                            groupLocationService.Delete( groupLocationDB );
                        }
                    }

                    // add any GroupLocations that were added in the UI
                    foreach ( var groupLocationUI in groupUI.GroupLocations )
                    {
                        if ( !groupDB.GroupLocations.Select( a => a.LocationId ).Contains( groupLocationUI.LocationId ) )
                        {
                            GroupLocation groupLocationDB = new GroupLocation { LocationId = groupLocationUI.LocationId };
                            groupDB.GroupLocations.Add( groupLocationDB );
                        }
                    }

                    groupDB.Order = groupUI.Order;

                    // get GroupTypeId from database in case the groupType is new
                    groupDB.GroupTypeId = groupTypeService.Get( groupUI.GroupType.Guid ).Id;
                    groupDB.Attributes = groupUI.Attributes;
                    groupDB.AttributeValues = groupUI.AttributeValues;

                    if ( groupDB.Id == 0 )
                    {
                        groupService.Add( groupDB );
                    }

                    if ( !groupDB.IsValid )
                    {
                        hasValidationErrors = true;
                        hasValidationErrors = true;
                        CheckinGroupEditor groupEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupEditor>().First( a => a.GroupGuid == groupDB.Guid );
                        groupEditor.Expanded = true;

                        return;
                    }

                    rockContext.SaveChanges();

                    groupDB.SaveAttributeValues();
                }

                /* now that we have all the grouptypes saved, now lets go back and save them again with the current UI ChildGroupTypes */

                // save main parentGroupType with current UI ChildGroupTypes
                parentGroupTypeDB.ChildGroupTypes = new List<GroupType>();
                parentGroupTypeDB.ChildGroupTypes.Clear();
                foreach ( var childGroupTypeUI in parentGroupTypeUI.ChildGroupTypes )
                {
                    var childGroupTypeDB = groupTypeService.Get( childGroupTypeUI.Guid );
                    parentGroupTypeDB.ChildGroupTypes.Add( childGroupTypeDB );
                }

                rockContext.SaveChanges();

                // loop thru all the other GroupTypes in the UI and save their childgrouptypes
                foreach ( var groupTypeUI in groupTypesToAddUpdate )
                {
                    var groupTypeDB = groupTypeService.Get( groupTypeUI.Guid );
                    groupTypeDB.ChildGroupTypes = new List<GroupType>();
                    groupTypeDB.ChildGroupTypes.Clear();
                    foreach ( var childGroupTypeUI in groupTypeUI.ChildGroupTypes )
                    {
                        var childGroupTypeDB = groupTypeService.Get( childGroupTypeUI.Guid );
                        groupTypeDB.ChildGroupTypes.Add( childGroupTypeDB );
                    }
                }

                rockContext.SaveChanges();
            } );

            if ( !hasValidationErrors )
            {
                NavigateToParentPage();
            }
        }
Ejemplo n.º 57
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 )
        {
            // 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 );
                        }
                    }

                } );
            }
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="group">The group.</param>
        private void ShowEditDetails( Group group )
        {
            if ( group.Id == 0 )
            {
                lReadOnlyTitle.Text = ActionTitle.Add( Group.FriendlyTypeName ).FormatAsHtmlTitle();
                hlInactive.Visible = false;
            }
            else
            {
                lReadOnlyTitle.Text = group.Name.FormatAsHtmlTitle();
            }

            SetEditMode( true );

            tbName.Text = group.Name;
            tbDescription.Text = group.Description;
            cbIsSecurityRole.Checked = group.IsSecurityRole;
            cbIsActive.Checked = group.IsActive;

            var rockContext = new RockContext();

            var groupService = new GroupService( rockContext );
            var attributeService = new AttributeService( rockContext );

            LoadDropDowns();

            gpParentGroup.SetValue( group.ParentGroup ?? groupService.Get( group.ParentGroupId ?? 0 ) );

            // GroupType depends on Selected ParentGroup
            ddlParentGroup_SelectedIndexChanged( null, null );
            gpParentGroup.Label = "Parent Group";

            if ( group.Id == 0 && ddlGroupType.Items.Count > 1 )
            {
                if ( GetAttributeValue( "LimittoSecurityRoleGroups" ).AsBoolean() )
                {
                    // default GroupType for new Group to "Security Roles"  if LimittoSecurityRoleGroups
                    var securityRoleGroupType = GroupTypeCache.GetSecurityRoleGroupType();
                    if ( securityRoleGroupType != null )
                    {
                        ddlGroupType.SetValue( securityRoleGroupType.Id );
                    }
                    else
                    {
                        ddlGroupType.SelectedIndex = 0;
                    }
                }
                else
                {
                    // if this is a new group (and not "LimitToSecurityRoleGroups", and there is more than one choice for GroupType, default to no selection so they are forced to choose (vs unintentionallly choosing the default one)
                    ddlGroupType.SelectedIndex = 0;
                }
            }
            else
            {
                ddlGroupType.SetValue( group.GroupTypeId );
            }

            ddlCampus.SetValue( group.CampusId );

            var groupLocations = new List<GroupLocation>();
            foreach ( var groupLocation in group.GroupLocations )
            {
                var groupLocationState = new GroupLocation();
                groupLocationState.CopyPropertiesFrom( groupLocation );
                if ( groupLocation.Location != null )
                {
                    groupLocationState.Location = new Location();
                    groupLocationState.Location.CopyPropertiesFrom( groupLocation.Location );
                }

                if ( groupLocation.GroupLocationTypeValue != null )
                {
                    groupLocationState.GroupLocationTypeValue = new DefinedValue();
                    groupLocationState.GroupLocationTypeValue.CopyPropertiesFrom( groupLocation.GroupLocationTypeValue );
                }
                groupLocations.Add( groupLocationState );
            }
            GroupLocationsState = new ViewStateList<GroupLocation>();
            GroupLocationsState.AddAll( groupLocations );

            ShowGroupTypeEditDetails( GroupTypeCache.Read( group.GroupTypeId ), group, true );

            // if this block's attribute limit group to SecurityRoleGroups, don't let them edit the SecurityRole checkbox value
            if ( GetAttributeValue( "LimittoSecurityRoleGroups" ).AsBoolean() )
            {
                cbIsSecurityRole.Enabled = false;
                cbIsSecurityRole.Checked = true;
            }

            string qualifierValue = group.Id.ToString();
            GroupMemberAttributesState = new ViewStateList<Attribute>();
            GroupMemberAttributesState.AddAll( attributeService.GetByEntityTypeId( new GroupMember().TypeId ).AsQueryable()
                    .Where( a =>
                        a.EntityTypeQualifierColumn.Equals( "GroupId", StringComparison.OrdinalIgnoreCase ) &&
                        a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                    .OrderBy( a => a.Order )
                    .ThenBy( a => a.Name )
                    .ToList() );
            BindGroupMemberAttributesGrid();

            BindInheritedAttributes( group.GroupTypeId, attributeService );
        }
Ejemplo n.º 59
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 )
        {
            var rockContext = new RockContext();
            rockContext.WrapTransaction( () =>
            {
                var personService = new PersonService( rockContext );

                var changes = new List<string>();

                var person = personService.Get( CurrentPersonId ?? 0 );
                if ( person != null )
                {
                    int? orphanedPhotoId = null;
                    if ( person.PhotoId != imgPhoto.BinaryFileId )
                    {
                        orphanedPhotoId = person.PhotoId;
                        person.PhotoId = imgPhoto.BinaryFileId;

                        if ( orphanedPhotoId.HasValue )
                        {
                            if ( person.PhotoId.HasValue )
                            {
                                changes.Add( "Modified the photo." );
                            }
                            else
                            {
                                changes.Add( "Deleted the photo." );
                            }
                        }
                        else if ( person.PhotoId.HasValue )
                        {
                            changes.Add( "Added a photo." );
                        }
                    }

                    int? newTitleId = ddlTitle.SelectedValueAsInt();
                    History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) );
                    person.TitleValueId = newTitleId;

                    History.EvaluateChange( changes, "First Name", person.FirstName, tbFirstName.Text );
                    person.FirstName = tbFirstName.Text;

                    History.EvaluateChange(changes, "Nick Name", person.NickName, tbNickName.Text);
                    person.NickName = tbNickName.Text;

                    History.EvaluateChange( changes, "Last Name", person.LastName, tbLastName.Text );
                    person.LastName = tbLastName.Text;

                    int? newSuffixId = ddlSuffix.SelectedValueAsInt();
                    History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) );
                    person.SuffixValueId = newSuffixId;

                    var birthMonth = person.BirthMonth;
                    var birthDay = person.BirthDay;
                    var birthYear = person.BirthYear;

                    var birthday = bpBirthDay.SelectedDate;
                    if ( birthday.HasValue )
                    {
                        // If setting a future birthdate, subtract a century until birthdate is not greater than today.
                        var today = RockDateTime.Today;
                        while ( birthday.Value.CompareTo( today ) > 0 )
                        {
                            birthday = birthday.Value.AddYears( -100 );
                        }

                        person.BirthMonth = birthday.Value.Month;
                        person.BirthDay = birthday.Value.Day;
                        if ( birthday.Value.Year != DateTime.MinValue.Year )
                        {
                            person.BirthYear = birthday.Value.Year;
                        }
                        else
                        {
                            person.BirthYear = null;
                        }
                    }
                    else
                    {
                        person.SetBirthDate( null );
                    }

                    History.EvaluateChange( changes, "Birth Month", birthMonth, person.BirthMonth );
                    History.EvaluateChange( changes, "Birth Day", birthDay, person.BirthDay );
                    History.EvaluateChange( changes, "Birth Year", birthYear, person.BirthYear );

                    var newGender = rblGender.SelectedValue.ConvertToEnum<Gender>();
                    History.EvaluateChange( changes, "Gender", person.Gender, newGender );
                    person.Gender = newGender;

                    var phoneNumberTypeIds = new List<int>();

                    bool smsSelected = false;

                    foreach ( RepeaterItem item in rContactInfo.Items )
                    {
                        HiddenField hfPhoneType = item.FindControl( "hfPhoneType" ) as HiddenField;
                        PhoneNumberBox pnbPhone = item.FindControl( "pnbPhone" ) as PhoneNumberBox;
                        CheckBox cbUnlisted = item.FindControl( "cbUnlisted" ) as CheckBox;
                        CheckBox cbSms = item.FindControl( "cbSms" ) as CheckBox;

                        if ( hfPhoneType != null &&
                            pnbPhone != null &&
                            cbSms != null &&
                            cbUnlisted != null )
                        {
                            if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) )
                            {
                                int phoneNumberTypeId;
                                if ( int.TryParse( hfPhoneType.Value, out phoneNumberTypeId ) )
                                {
                                    var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberTypeId );
                                    string oldPhoneNumber = string.Empty;
                                    if ( phoneNumber == null )
                                    {
                                        phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId };
                                        person.PhoneNumbers.Add( phoneNumber );
                                    }
                                    else
                                    {
                                        oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                                    }

                                    phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode );
                                    phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number );

                                    // Only allow one number to have SMS selected
                                    if ( smsSelected )
                                    {
                                        phoneNumber.IsMessagingEnabled = false;
                                    }
                                    else
                                    {
                                        phoneNumber.IsMessagingEnabled = cbSms.Checked;
                                        smsSelected = cbSms.Checked;
                                    }

                                    phoneNumber.IsUnlisted = cbUnlisted.Checked;
                                    phoneNumberTypeIds.Add( phoneNumberTypeId );

                                    History.EvaluateChange(
                                        changes,
                                        string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumberTypeId ) ),
                                        oldPhoneNumber,
                                        phoneNumber.NumberFormattedWithCountryCode );
                                }
                            }
                        }
                    }

                    // Remove any blank numbers
                    var phoneNumberService = new PhoneNumberService( rockContext );
                    foreach ( var phoneNumber in person.PhoneNumbers
                        .Where( n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains( n.NumberTypeValueId.Value ) )
                        .ToList() )
                    {
                        History.EvaluateChange(
                            changes,
                            string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumber.NumberTypeValueId ) ),
                            phoneNumber.ToString(),
                            string.Empty );

                        person.PhoneNumbers.Remove( phoneNumber );
                        phoneNumberService.Delete( phoneNumber );
                    }

                    History.EvaluateChange( changes, "Email", person.Email, tbEmail.Text );
                    person.Email = tbEmail.Text.Trim();

                    var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum<EmailPreference>();
                    History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference );
                    person.EmailPreference = newEmailPreference;

                    if ( person.IsValid )
                    {
                        if ( rockContext.SaveChanges() > 0 )
                        {
                            if ( changes.Any() )
                            {
                                HistoryService.SaveChanges(
                                    rockContext,
                                    typeof( Person ),
                                    Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                    person.Id,
                                    changes );
                            }

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

                            // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up
                            if ( imgPhoto.CropBinaryFileId.HasValue )
                            {
                                if ( imgPhoto.CropBinaryFileId != person.PhotoId )
                                {
                                    BinaryFileService binaryFileService = new BinaryFileService( rockContext );
                                    var binaryFile = binaryFileService.Get( imgPhoto.CropBinaryFileId.Value );
                                    if ( binaryFile != null && binaryFile.IsTemporary )
                                    {
                                        string errorMessage;
                                        if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) )
                                        {
                                            binaryFileService.Delete( binaryFile );
                                            rockContext.SaveChanges();
                                        }
                                    }
                                }
                            }
                        }

                        // save address
                        if ( pnlAddress.Visible )
                        {
                            Guid? familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();
                            if ( familyGroupTypeGuid.HasValue )
                            {
                                var familyGroup = new GroupService( rockContext ).Queryable()
                                                .Where( f => f.GroupType.Guid == familyGroupTypeGuid.Value
                                                    && f.Members.Any( m => m.PersonId == person.Id ) )
                                                .FirstOrDefault();
                                if ( familyGroup != null )
                                {
                                    Guid? addressTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull();
                                    if ( addressTypeGuid.HasValue )
                                    {
                                        var groupLocationService = new GroupLocationService( rockContext );

                                        var dvHomeAddressType = DefinedValueCache.Read( addressTypeGuid.Value );
                                        var familyAddress = groupLocationService.Queryable().Where( l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id ).FirstOrDefault();
                                        if ( familyAddress != null && string.IsNullOrWhiteSpace( acAddress.Street1 ) )
                                        {
                                            // delete the current address
                                            History.EvaluateChange( changes, familyAddress.GroupLocationTypeValue.Value + " Location", familyAddress.Location.ToString(), string.Empty );
                                            groupLocationService.Delete( familyAddress );
                                            rockContext.SaveChanges();
                                        }
                                        else
                                        {
                                            if ( !string.IsNullOrWhiteSpace( acAddress.Street1 ) )
                                            {
                                                if ( familyAddress == null )
                                                {
                                                    familyAddress = new GroupLocation();
                                                    groupLocationService.Add( familyAddress );
                                                    familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id;
                                                    familyAddress.GroupId = familyGroup.Id;
                                                    familyAddress.IsMailingLocation = true;
                                                    familyAddress.IsMappedLocation = true;
                                                }
                                                else if ( hfStreet1.Value != string.Empty ) {

                                                    // user clicked move so create a previous address
                                                    var previousAddress = new GroupLocation();
                                                    groupLocationService.Add( previousAddress );

                                                    var previousAddressValue = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid() );
                                                    if ( previousAddressValue  != null )
                                                    {
                                                        previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                                        previousAddress.GroupId = familyGroup.Id;

                                                        Location previousAddressLocation = new Location();
                                                        previousAddressLocation.Street1 = hfStreet1.Value;
                                                        previousAddressLocation.Street2 = hfStreet2.Value;
                                                        previousAddressLocation.City = hfCity.Value;
                                                        previousAddressLocation.State = hfState.Value;
                                                        previousAddressLocation.PostalCode = hfPostalCode.Value;
                                                        previousAddressLocation.Country = hfCountry.Value;

                                                        previousAddress.Location = previousAddressLocation;
                                                    }
                                                }

                                                familyAddress.IsMailingLocation = cbIsMailingAddress.Checked;
                                                familyAddress.IsMappedLocation = cbIsPhysicalAddress.Checked;

                                                var updatedHomeAddress = new Location();
                                                acAddress.GetValues( updatedHomeAddress );

                                                History.EvaluateChange( changes, dvHomeAddressType.Value + " Location", familyAddress.Location != null ? familyAddress.Location.ToString() : string.Empty, updatedHomeAddress.ToString() );

                                                familyAddress.Location = updatedHomeAddress;
                                                rockContext.SaveChanges();
                                            }
                                        }

                                        HistoryService.SaveChanges(
                                            rockContext,
                                            typeof( Person ),
                                            Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                            person.Id,
                                            changes );
                                    }
                                }
                            }
                        }

                        NavigateToParentPage();
                    }
                }
            } );
        }
Ejemplo n.º 60
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 )
        {
            Group group;
            bool wasSecurityRole = false;

            RockContext rockContext = new RockContext();

            GroupService groupService = new GroupService( rockContext );
            GroupLocationService groupLocationService = new GroupLocationService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext );
            CategoryService categoryService = new CategoryService( rockContext );

            if ( ( ddlGroupType.SelectedValueAsInt() ?? 0 ) == 0 )
            {
                ddlGroupType.ShowErrorMessage( Rock.Constants.WarningMessage.CannotBeBlank( GroupType.FriendlyTypeName ) );
                return;
            }

            int groupId = int.Parse( hfGroupId.Value );

            if ( groupId == 0 )
            {
                group = new Group();
                group.IsSystem = false;
                group.Name = string.Empty;
            }
            else
            {
                group = groupService.Get( groupId );
                wasSecurityRole = group.IsSecurityRole;

                var selectedLocations = GroupLocationsState.Select( l => l.Guid );
                foreach ( var groupLocation in group.GroupLocations.Where( l => !selectedLocations.Contains( l.Guid ) ).ToList() )
                {
                    group.GroupLocations.Remove( groupLocation );
                    groupLocationService.Delete( groupLocation );
                }
            }

            foreach ( var groupLocationState in GroupLocationsState )
            {
                GroupLocation groupLocation = group.GroupLocations.Where( l => l.Guid == groupLocationState.Guid ).FirstOrDefault();
                if ( groupLocation == null )
                {
                    groupLocation = new GroupLocation();
                    group.GroupLocations.Add( groupLocation );
                }
                else
                {
                    groupLocationState.Id = groupLocation.Id;
                    groupLocationState.Guid = groupLocation.Guid;
                }

                groupLocation.CopyPropertiesFrom( groupLocationState );
            }

            group.Name = tbName.Text;
            group.Description = tbDescription.Text;
            group.CampusId = ddlCampus.SelectedValue.Equals( None.IdValue ) ? (int?)null : int.Parse( ddlCampus.SelectedValue );
            group.GroupTypeId = int.Parse( ddlGroupType.SelectedValue );
            group.ParentGroupId = gpParentGroup.SelectedValue.Equals( None.IdValue ) ? (int?)null : int.Parse( gpParentGroup.SelectedValue );
            group.IsSecurityRole = cbIsSecurityRole.Checked;
            group.IsActive = cbIsActive.Checked;

            if ( group.ParentGroupId == group.Id )
            {
                gpParentGroup.ShowErrorMessage( "Group cannot be a Parent Group of itself." );
                return;
            }

            group.LoadAttributes();

            Rock.Attribute.Helper.GetEditValues( phGroupAttributes, group );

            if ( !Page.IsValid )
            {
                return;
            }

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

            // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
            RockTransactionScope.WrapTransaction( () =>
            {
                if ( group.Id.Equals( 0 ) )
                {
                    groupService.Add( group );
                }
                rockContext.SaveChanges();

                group.SaveAttributeValues( rockContext );

                /* Take care of Group Member Attributes */
                var entityTypeId = EntityTypeCache.Read( typeof( GroupMember ) ).Id;
                string qualifierColumn = "GroupId";
                string qualifierValue = group.Id.ToString();

                // Get the existing attributes for this entity type and qualifier value
                var attributes = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue );

                // Delete any of those attributes that were removed in the UI
                var selectedAttributeGuids = GroupMemberAttributesState.Select( a => a.Guid );
                foreach ( var attr in attributes.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) )
                {
                    Rock.Web.Cache.AttributeCache.Flush( attr.Id );

                    attributeService.Delete( attr );
                }

                // Update the Attributes that were assigned in the UI
                foreach ( var attributeState in GroupMemberAttributesState )
                {
                    Rock.Attribute.Helper.SaveAttributeEdits( attributeState, entityTypeId, qualifierColumn, qualifierValue, rockContext );
                }

                rockContext.SaveChanges();
            } );

            if ( group != null && wasSecurityRole )
            {
                if ( !group.IsSecurityRole )
                {
                    // if this group was a SecurityRole, but no longer is, flush
                    Rock.Security.Role.Flush( group.Id );
                    Rock.Security.Authorization.Flush();
                }
            }
            else
            {
                if ( group.IsSecurityRole )
                {
                    // new security role, flush
                    Rock.Security.Authorization.Flush();
                }
            }

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

            NavigateToPage( RockPage.Guid, qryParams );
        }