Exemplo n.º 1
0
        /// <summary>
        /// Finds any missing personal link section orders
        /// and <see cref="Rock.Data.Service{T}.Add(T)">adds</see> them  (but doesn't .SaveChanges)
        /// If this returns true, call SaveChanges to save them to the database.
        /// </summary>
        /// <param name="currentPerson">The current person.</param>
        /// <returns>List&lt;PersonalLinkSectionOrder&gt;.</returns>
        public bool AddMissingPersonalLinkSectionOrders(Person currentPerson)
        {
            var primaryAliasId = currentPerson.PrimaryAliasId;

            if (!primaryAliasId.HasValue)
            {
                // shouldn't happen, but just in case
                return(false);
            }

            var rockContext = this.Context as RockContext;

            var personalLinkSectionService = new PersonalLinkSectionService(rockContext);

            var personAliasQuery          = new PersonAliasService(rockContext).Queryable().Where(a => a.PersonId == currentPerson.Id);
            var personalLinkSectionsQuery = personalLinkSectionService
                                            .Queryable()
                                            .Where(a =>
                                                   a.IsShared ||
                                                   (a.PersonAliasId.HasValue && personAliasQuery.Any(aa => aa.Id == a.PersonAliasId.Value)));

            var missingSectionOrders = personalLinkSectionsQuery
                                       .Where(a => !a.PersonalLinkSectionOrders.Any(xx => personAliasQuery.Any(pa => pa.Id == xx.PersonAliasId)))
                                       .ToList()
                                       .OrderBy(a => a.Name)
                                       .Select(a => new PersonalLinkSectionOrder
            {
                PersonAliasId = primaryAliasId.Value,
                SectionId     = a.Id,
                Order         = 0
            }).ToList();

            if (missingSectionOrders.Any())
            {
                // add the new order for sections to the bottom of the list for that section (in order by name)
                var personalLinkSectionOrderService = new PersonalLinkSectionOrderService(rockContext);

                var lastSectionOrder = personalLinkSectionOrderService.Queryable().Where(a => a.PersonAlias.PersonId == currentPerson.Id).Max(a => ( int? )a.Order) ?? 0;
                foreach (var missingSectionOrder in missingSectionOrders)
                {
                    missingSectionOrder.Order = lastSectionOrder++;
                }

                personalLinkSectionOrderService.AddRange(missingSectionOrders);
                return(true);
            }
            else
            {
                return(false);
            }
        }