Exemplo n.º 1
0
        /// <summary>
        /// Updates the control with the current tags that exist for the current entity
        /// </summary>
        /// <param name="currentPersonId">The current person identifier.</param>
        public void GetTagValues(int?currentPersonId)
        {
            var sb = new StringBuilder();

            using (var rockContext = new RockContext())
            {
                var service = new TaggedItemService(rockContext);
                foreach (dynamic item in service.Get(
                             EntityTypeId, EntityQualifierColumn, EntityQualifierValue, currentPersonId, EntityGuid)
                         .Select(i => new
                {
                    OwnerId = (i.Tag.OwnerPersonAlias != null ? i.Tag.OwnerPersonAlias.PersonId : (int?)null),
                    Name = i.Tag.Name
                }))
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(',');
                    }
                    sb.Append(item.Name);
                    if (currentPersonId.HasValue && item.OwnerId == currentPersonId.Value)
                    {
                        sb.Append("^personal");
                    }
                }
            }

            this.Text = sb.ToString();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Handles the Delete event of the gReport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        protected void gReport_Delete(object sender, RowEventArgs e)
        {
            int id = int.MinValue;

            if (TagId.HasValue && int.TryParse(e.RowKeyValue.ToString(), out id))
            {
                object obj = InvokeServiceMethod("Get", new Type[] { typeof(int) }, new object[] { id });
                if (obj != null)
                {
                    Rock.Data.IEntity entity = obj as Rock.Data.IEntity;
                    if (entity != null)
                    {
                        var rockContext = new RockContext();
                        var service     = new TaggedItemService(rockContext);
                        var taggedItem  = service.Get(TagId.Value, entity.Guid);
                        if (taggedItem != null)
                        {
                            string errorMessage;
                            if (!service.CanDelete(taggedItem, out errorMessage))
                            {
                                mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                                return;
                            }

                            service.Delete(taggedItem);
                            rockContext.SaveChanges();
                        }
                    }
                }
            }

            BindGrid();
        }
Exemplo n.º 3
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var guids = new TaggedItemService(new RockContext()).Queryable().Where(t => t.TagId == TagId.Value)
                        .Select(t => new { t.EntityGuid, t.CreatedDateTime })
                        .ToDictionary(o => o.EntityGuid, o => o.CreatedDateTime);

            gReport.DataSource = InvokeServiceMethod("GetListByGuids", new Type[] { typeof(List <Guid>) }, new object[] { guids.Keys.ToList() });

            // Since we don't really know what is in the "obj" that was returned, we check if it's
            // enumerable then reuse the CreatedDateTime property of the DataSource if it has one.
            // In the future, perhaps consider creating a merged data source so the CreatedDateTime
            // property/column doesn't have to be hijacked.
            var enumerable = gReport.DataSource as System.Collections.IEnumerable;

            if (enumerable != null)
            {
                foreach (var entity in enumerable)
                {
                    var property = entity.GetType().GetProperty("CreatedDateTime");
                    var guid     = entity.GetType().GetProperty("Guid");
                    // Now re-set the CreatedDateTime with the tag's CreatedDateTime (if that property is in the entity)
                    if (property != null && guid != null)
                    {
                        var val = (Guid)guid.GetValue(entity, null);
                        property.SetValue(entity, guids[val], null);
                    }
                }
            }

            gReport.DataBind();
        }
Exemplo n.º 4
0
        /// <summary>
        /// Updates the control with the current tags that exist for the current entity
        /// </summary>
        /// <param name="currentPersonId">The current person identifier.</param>
        public void GetTagValues(int?currentPersonId)
        {
            var serializedTags = new List <string>();

            using (var rockContext = new RockContext())
            {
                var taggedItemService = new TaggedItemService(rockContext);
                var itemList          = taggedItemService.Get(EntityTypeId, EntityQualifierColumn, EntityQualifierValue, currentPersonId, EntityGuid, CategoryGuid, ShowInactiveTags)
                                        .Where(ti => ShowInactiveTags || ti.Tag.IsActive)
                                        .Select(ti => ti.Tag)
                                        .Include(t => t.OwnerPersonAlias)
                                        .OrderBy(t => t.Name)
                                        .AsNoTracking()
                                        .ToList();

                var person = GetCurrentPerson();

                foreach (var item in itemList)
                {
                    if (!item.IsAuthorized(Authorization.VIEW, person))
                    {
                        continue;
                    }

                    var isPersonal    = currentPersonId.HasValue && item.OwnerPersonAlias?.PersonId == currentPersonId.Value;
                    var tagCssClass   = isPersonal ? "personal" : string.Empty;
                    var serializedTag = SerializeTag(item.Name, tagCssClass, item.IconCssClass, item.BackgroundColor);
                    serializedTags.Add(serializedTag);
                }
            }

            Text = serializedTags.JoinStrings(",");
        }
Exemplo n.º 5
0
 /// <summary>
 /// Handles the RowSelected event of the gReport control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param>
 protected void gReport_RowSelected(object sender, Rock.Web.UI.Controls.RowEventArgs e)
 {
     using (var rockContext = new RockContext())
     {
         var taggedItem = new TaggedItemService(rockContext).Get(e.RowKeyId);
         if (taggedItem != null)
         {
             var entityType = EntityTypeCache.Get(taggedItem.EntityTypeId);
             if (entityType != null)
             {
                 var entity = GetGenericEntity(entityType.GetEntityType(), taggedItem.EntityGuid) as IEntity;
                 if (entity != null)
                 {
                     string url = string.Format("~/{0}/{1}", entityType.FriendlyName.Replace(" ", ""), entity.Id);
                     if (entityType.LinkUrlLavaTemplate.IsNotNullOrWhiteSpace())
                     {
                         url = entityType.LinkUrlLavaTemplate.ResolveMergeFields(new Dictionary <string, object> {
                             { "Entity", entity }
                         });
                     }
                     Response.Redirect(url, false);
                 }
             }
         }
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var guids = new TaggedItemService(new RockContext()).Queryable().Where(t => t.TagId == TagId.Value).Select(t => t.EntityGuid).ToList();

            gReport.DataSource = InvokeServiceMethod("GetListByGuids", new Type[] { typeof(List <Guid>) }, new object[] { guids });
            gReport.DataBind();
        }
        private List <string> GetTags(ContentChannelItem contentChannelItem, RockContext rockContext)
        {
            TaggedItemService taggedItemService = new TaggedItemService(rockContext);
            var tags = taggedItemService.Queryable()
                       .Where(ti => ti.EntityGuid == contentChannelItem.Guid)
                       .Select(ti => ti.Tag.Name);

            return(tags.ToList());
        }
Exemplo n.º 8
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 2)
            {
                Guid tagGuid    = selectionValues[1].AsGuid();
                var  tagItemQry = new TaggedItemService((RockContext)serviceInstance.Context).Queryable()
                                  .Where(x => x.Tag.Guid == tagGuid);

                var qry = new PersonService((RockContext)serviceInstance.Context).Queryable()
                          .Where(p => tagItemQry.Any(x => x.EntityGuid == p.Guid));

                return(FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p"));
            }

            return(null);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            using (var rockContext = new RockContext())
            {
                var service = new TaggedItemService(rockContext);
                var people  = new PersonService(rockContext).Queryable().AsNoTracking();

                IQueryable <TaggedItemRow> results = null;

                if (TagEntityType != null && TagEntityType.Name == "Rock.Model.Person")
                {
                    results = service.Queryable().AsNoTracking()
                              .Where(t =>
                                     t.TagId == TagId.Value)
                              .Join(people, t => t.EntityGuid, p => p.Guid, (t, p) => new TaggedItemRow
                    {
                        Id              = t.Id,
                        EntityTypeId    = t.EntityTypeId,
                        EntityGuid      = t.EntityGuid,
                        CreatedDateTime = t.CreatedDateTime,
                        PersonId        = p.Id,
                    });
                }
                else
                {
                    results = service.Queryable().AsNoTracking()
                              .Where(t =>
                                     t.TagId == TagId.Value)
                              .Select(t => new TaggedItemRow
                    {
                        Id              = t.Id,
                        EntityTypeId    = t.EntityTypeId,
                        EntityGuid      = t.EntityGuid,
                        CreatedDateTime = t.CreatedDateTime
                    });
                }

                if (TagEntityType != null)
                {
                    gReport.EntityTypeId = TagEntityType.Id;
                }

                gReport.DataSource = results.ToList();
                gReport.DataBind();
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            if (TagEntityType == null)
            {
                return;
            }

            using (var rockContext = new RockContext())
            {
                var service = new TaggedItemService(rockContext);

                var tagEntityTypeType = TagEntityType.GetEntityType();

                // Join TaggedItemRow with whatever IEntity query is for the TagEntityType (PersonService.Queryable(), GroupService.Queryable(), etc)
                // That way we can get the Entity.Id and tell the Grid what the EntityId is for each item (Person, Group, etc)
                IService   serviceInstance = Reflection.GetServiceForEntityType(tagEntityTypeType, rockContext);
                MethodInfo qryMethod       = serviceInstance.GetType().GetMethod("Queryable", new Type[] { });
                var        entityQuery     = qryMethod.Invoke(serviceInstance, new object[] { }) as IQueryable <IEntity>;

                IQueryable <TaggedItemRow> results = service.Queryable().AsNoTracking()
                                                     .Where(t => t.TagId == TagId.Value)
                                                     .Join(entityQuery, t => t.EntityGuid, e => e.Guid, (t, e) => new TaggedItemRow
                {
                    Id              = t.Id,
                    EntityTypeId    = t.EntityTypeId,
                    EntityGuid      = t.EntityGuid,
                    CreatedDateTime = t.CreatedDateTime,
                    EntityId        = e.Id,
                });;

                // Tell the grid that it has a list of the EntityType for the Tag (Person, Group, etc).
                // Also tell it to get the Entities (Group, Person, etc) using EntityId (instead of Id)
                gReport.EntityTypeId  = TagEntityType.Id;
                gReport.EntityIdField = "EntityId";
                if (TagEntityType.Name == "Rock.Model.Person")
                {
                    gReport.PersonIdField = "EntityId";
                }

                gReport.DataSource = results.ToList();
                gReport.DataBind();
            }
        }
        public HttpResponseMessage Post(int entityTypeId, int ownerId, Guid entityGuid, string name, string entityQualifier, string entityQualifierValue)
        {
            var user = CurrentUser();

            if (user != null)
            {
                using (new Rock.Data.UnitOfWorkScope())
                {
                    var tagService        = new TagService();
                    var taggedItemService = new TaggedItemService();

                    var tag = tagService.Get(entityTypeId, entityQualifier, entityQualifierValue, ownerId, name);
                    if (tag == null)
                    {
                        tag = new Tag();
                        tag.EntityTypeId = entityTypeId;
                        tag.EntityTypeQualifierColumn = entityQualifier;
                        tag.EntityTypeQualifierValue  = entityQualifierValue;
                        tag.OwnerId = ownerId;
                        tag.Name    = name;
                        tagService.Add(tag, user.PersonId);
                        tagService.Save(tag, user.PersonId);
                    }

                    var taggedItem = taggedItemService.Get(tag.Id, entityGuid);
                    if (taggedItem == null)
                    {
                        taggedItem            = new TaggedItem();
                        taggedItem.TagId      = tag.Id;
                        taggedItem.EntityGuid = entityGuid;
                        taggedItemService.Add(taggedItem, user.PersonId);
                        taggedItemService.Save(taggedItem, user.PersonId);
                    }
                }

                return(ControllerContext.Request.CreateResponse(HttpStatusCode.Created));
            }

            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Handles the Delete event of the gReport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        protected void gReport_Delete(object sender, RowEventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                var taggedItemService = new TaggedItemService(rockContext);
                var taggedItem        = taggedItemService.Get(e.RowKeyId);
                if (taggedItem != null && taggedItem.IsAuthorized(Rock.Security.Authorization.TAG, CurrentPerson))
                {
                    string errorMessage;
                    if (!taggedItemService.CanDelete(taggedItem, out errorMessage))
                    {
                        mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }

                    taggedItemService.Delete(taggedItem);
                    rockContext.SaveChanges();
                }

                BindGrid();
            }
        }
        public void Delete(int entityTypeId, int ownerId, Guid entityGuid, string name, string entityQualifier, string entityQualifierValue)
        {
            var user = CurrentUser();

            if (user != null)
            {
                using (new Rock.Data.UnitOfWorkScope())
                {
                    var tagService        = new TagService();
                    var taggedItemService = new TaggedItemService();

                    if (name.Contains('^'))
                    {
                        name = name.Split('^')[0];
                    }

                    var tag = tagService.Get(entityTypeId, entityQualifier, entityQualifierValue, ownerId, name);
                    if (tag == null)
                    {
                        throw new HttpResponseException(HttpStatusCode.NotFound);
                    }

                    var taggedItem = taggedItemService.Get(tag.Id, entityGuid);
                    if (taggedItem == null)
                    {
                        throw new HttpResponseException(HttpStatusCode.NotFound);
                    }

                    taggedItemService.Delete(taggedItem, user.PersonId);
                    taggedItemService.Save(taggedItem, user.PersonId);
                }
            }
            else
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Handles the Delete event of the gReport control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        protected void gReport_Delete(object sender, RowEventArgs e)
        {
            Guid guid = Guid.Empty;

            if (TagId.HasValue && Guid.TryParse(e.RowKeyValue.ToString(), out guid))
            {
                var service    = new TaggedItemService();
                var taggedItem = service.Get(TagId.Value, guid);
                if (taggedItem != null)
                {
                    string errorMessage;
                    if (!service.CanDelete(taggedItem, out errorMessage))
                    {
                        mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }

                    service.Delete(taggedItem, CurrentPersonId);
                    service.Save(taggedItem, CurrentPersonId);
                }
            }

            BindGrid();
        }
Exemplo n.º 15
0
        /// <summary>
        /// Updates the control with the current tags that exist for the current entity
        /// </summary>
        /// <param name="currentPersonId">The current person identifier.</param>
        public void GetTagValues(int?currentPersonId)
        {
            var sb = new StringBuilder();

            using (var rockContext = new RockContext())
            {
                var service = new TaggedItemService(rockContext);
                var qry     = service.Get(
                    EntityTypeId, EntityQualifierColumn, EntityQualifierValue, currentPersonId, EntityGuid, CategoryGuid, ShowInActiveTags)
                              .Where(c => c.Tag.IsActive || (ShowInActiveTags));

                var items = qry
                            .Select(a => a.Tag)
                            .OrderBy(a => a.Name);

                var person = GetCurrentPerson();

                foreach (var item in items)
                {
                    if (item.IsAuthorized(Rock.Security.Authorization.VIEW, person))
                    {
                        if (sb.Length > 0)
                        {
                            sb.Append(',');
                        }
                        sb.Append(item.Name);
                        if (currentPersonId.HasValue && item?.OwnerPersonAlias?.PersonId == currentPersonId.Value)
                        {
                            sb.Append("^personal");
                        }
                    }
                }
            }

            this.Text = sb.ToString();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Add the person to the tag.
        /// </summary>
        /// <returns>True if the person was added, false if they already existed in the tag.</returns>
        private bool AddPerson(int personId)
        {
            using (var rockContext = new RockContext())
            {
                var taggedItemService = new TaggedItemService(rockContext);
                Tag tag    = new TagService(rockContext).Get(TagId.Value);
                var person = new PersonService(rockContext).Get(personId);

                if (taggedItemService.Get(tag.Id, person.Guid) != null)
                {
                    return(false);
                }

                var taggedItem = new TaggedItem();
                taggedItem.TagId        = TagId.Value;
                taggedItem.EntityTypeId = TagEntityType.Id;
                taggedItem.EntityGuid   = person.Guid;
                taggedItemService.Add(taggedItem);

                rockContext.SaveChanges();

                return(true);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Saves the tag values that user entered for the entity
        /// </summary>
        /// <param name="personAlias">The person alias.</param>
        public void SaveTagValues(PersonAlias personAlias)
        {
            int?currentPersonId = null;

            if (personAlias != null)
            {
                currentPersonId = personAlias.PersonId;
            }

            if (EntityGuid != Guid.Empty)
            {
                var rockContext       = new RockContext();
                var tagService        = new TagService(rockContext);
                var taggedItemService = new TaggedItemService(rockContext);
                var person            = currentPersonId.HasValue ? new PersonService(rockContext).Get(currentPersonId.Value) : null;

                // Get the existing tagged items for this entity
                var existingTaggedItems = new List <TaggedItem>();
                foreach (var taggedItem in taggedItemService.Get(EntityTypeId, EntityQualifierColumn, EntityQualifierValue, currentPersonId, EntityGuid, CategoryGuid, ShowInactiveTags))
                {
                    if (taggedItem.IsAuthorized(Authorization.VIEW, person))
                    {
                        existingTaggedItems.Add(taggedItem);
                    }
                }

                // Get tag values after user edit
                var currentTags = new List <Tag>();
                foreach (var serializedTag in Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var tagName = GetNameFromSerializedTag(serializedTag);

                    if (tagName.IsNullOrWhiteSpace())
                    {
                        continue;
                    }

                    // Only if this is a new tag, create it
                    var tag = tagService.Get(EntityTypeId, EntityQualifierColumn, EntityQualifierValue, currentPersonId, tagName, CategoryGuid, ShowInactiveTags);

                    if (personAlias != null && tag == null)
                    {
                        tag = new Tag();
                        tag.EntityTypeId = EntityTypeId;
                        tag.CategoryId   = CategoryId;
                        tag.EntityTypeQualifierColumn = EntityQualifierColumn;
                        tag.EntityTypeQualifierValue  = EntityQualifierValue;
                        tag.OwnerPersonAliasId        = personAlias.Id;
                        tag.Name = tagName;
                        tagService.Add(tag);
                    }

                    if (tag != null)
                    {
                        currentTags.Add(tag);
                    }
                }

                rockContext.SaveChanges();

                var currentNames  = currentTags.Select(t => t.Name).ToList();
                var existingNames = existingTaggedItems.Select(t => t.Tag.Name).ToList();

                // Delete any tagged items that user removed
                foreach (var taggedItem in existingTaggedItems)
                {
                    if (!currentNames.Contains(taggedItem.Tag.Name, StringComparer.OrdinalIgnoreCase) && taggedItem.IsAuthorized(Rock.Security.Authorization.TAG, person))
                    {
                        existingNames.Remove(taggedItem.Tag.Name);
                        taggedItemService.Delete(taggedItem);
                    }
                }
                rockContext.SaveChanges();

                // Add any tagged items that user added
                foreach (var tag in currentTags)
                {
                    // If the tagged item was not already there, and (it's their personal tag OR they are authorized to use it) then add it.
                    if (!existingNames.Contains(tag.Name, StringComparer.OrdinalIgnoreCase) &&
                        (
                            (tag.OwnerPersonAliasId != null && tag.OwnerPersonAliasId == personAlias?.Id) ||
                            tag.IsAuthorized(Rock.Security.Authorization.TAG, person)
                        )
                        )
                    {
                        var taggedItem = new TaggedItem();
                        taggedItem.TagId        = tag.Id;
                        taggedItem.EntityTypeId = this.EntityTypeId;
                        taggedItem.EntityGuid   = EntityGuid;
                        taggedItemService.Add(taggedItem);
                    }
                }
                rockContext.SaveChanges();
            }
        }
Exemplo n.º 18
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 the tag
            string tagName = GetAttributeValue(action, "OrganizationTag").ResolveMergeFields(GetMergeFields(action));;

            if (!string.IsNullOrEmpty(tagName))
            {
                // get person entity type
                var personEntityType = Rock.Web.Cache.EntityTypeCache.Read("Rock.Model.Person");

                // get tag
                TagService tagService = new TagService(rockContext);
                Tag        orgTag     = tagService.Queryable().Where(t => t.Name == tagName && t.EntityTypeId == personEntityType.Id && t.OwnerPersonAlias == null).FirstOrDefault();

                if (orgTag != null)
                {
                    // get person
                    string value = GetAttributeValue(action, "Person");
                    Guid   guidPersonAttribute = value.AsGuid();
                    if (!guidPersonAttribute.IsEmpty())
                    {
                        var attributePerson = AttributeCache.Read(guidPersonAttribute, rockContext);
                        if (attributePerson != null)
                        {
                            string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute);
                            if (!string.IsNullOrWhiteSpace(attributePersonValue))
                            {
                                if (attributePerson.FieldType.Class == "Rock.Field.Types.PersonFieldType")
                                {
                                    Guid personAliasGuid = attributePersonValue.AsGuid();
                                    if (!personAliasGuid.IsEmpty())
                                    {
                                        var person = new PersonAliasService(rockContext).Queryable()
                                                     .Where(a => a.Guid.Equals(personAliasGuid))
                                                     .Select(a => a.Person)
                                                     .FirstOrDefault();
                                        if (person != null)
                                        {
                                            var personAliasGuids        = person.Aliases.Select(a => a.AliasPersonGuid).ToList();
                                            TaggedItemService tiService = new TaggedItemService(rockContext);
                                            TaggedItem        personTag = tiService.Queryable().Where(t => t.TagId == orgTag.Id && personAliasGuids.Contains(t.EntityGuid)).FirstOrDefault();
                                            if (personTag != null)
                                            {
                                                tiService.Delete(personTag);
                                                rockContext.SaveChanges();
                                            }
                                            else
                                            {
                                                action.AddLogEntry(string.Format("{0} was not in the {1} tag.", person.FullName, orgTag.Name));
                                            }
                                        }
                                        else
                                        {
                                            errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    action.AddLogEntry(string.Format("{0} organization tag does not exist.", orgTag.Name));
                }
            }
            else
            {
                errorMessages.Add("No organization tag was provided");
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Saves the tag values that user entered for the entity (
        /// </summary>
        /// <param name="personAlias">The person alias.</param>
        public void SaveTagValues(PersonAlias personAlias)
        {
            int?currentPersonId = null;

            if (personAlias != null)
            {
                currentPersonId = personAlias.PersonId;
            }

            if (EntityGuid != Guid.Empty)
            {
                var rockContext       = new RockContext();
                var tagService        = new TagService(rockContext);
                var taggedItemService = new TaggedItemService(rockContext);

                // Get the existing tags for this entity type
                var existingTags = tagService.Get(EntityTypeId, EntityQualifierColumn, EntityQualifierValue, currentPersonId).ToList();

                // Get the existing tagged items for this entity
                var existingTaggedItems = taggedItemService.Get(EntityTypeId, EntityQualifierColumn, EntityQualifierValue, currentPersonId, EntityGuid);

                // Get tag values after user edit
                var currentTags = new List <Tag>();
                foreach (var value in this.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    string tagName = value;
                    if (tagName.Contains('^'))
                    {
                        tagName = tagName.Split(new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries)[0];
                    }

                    // If this is a new tag, create it
                    Tag tag = existingTags.FirstOrDefault(t => t.Name.Equals(tagName, StringComparison.OrdinalIgnoreCase));
                    if (tag == null && currentPersonId != null)
                    {
                        tag = new Tag();
                        tag.EntityTypeId = EntityTypeId;
                        tag.EntityTypeQualifierColumn = EntityQualifierColumn;
                        tag.EntityTypeQualifierValue  = EntityQualifierValue;
                        tag.OwnerPersonAliasId        = personAlias != null ? personAlias.Id : (int?)null;
                        tag.Name = tagName;
                    }

                    if (tag != null)
                    {
                        currentTags.Add(tag);
                    }
                }

                rockContext.SaveChanges();

                // Delete any tagged items that user removed
                var names = currentTags.Select(t => t.Name).ToList();
                foreach (var taggedItem in existingTaggedItems)
                {
                    if (!names.Contains(taggedItem.Tag.Name, StringComparer.OrdinalIgnoreCase))
                    {
                        taggedItemService.Delete(taggedItem);
                    }
                }

                rockContext.SaveChanges();

                // Add any tagged items that user added
                names = existingTaggedItems.Select(t => t.Tag.Name).ToList();
                foreach (var tag in currentTags)
                {
                    if (!names.Contains(tag.Name, StringComparer.OrdinalIgnoreCase))
                    {
                        var taggedItem = new TaggedItem();
                        taggedItem.TagId      = tag.Id;
                        taggedItem.EntityGuid = EntityGuid;
                        taggedItemService.Add(taggedItem);
                    }
                }

                rockContext.SaveChanges();
            }
        }
Exemplo n.º 20
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string entityQualifierColumn = GetAttributeValue("EntityQualifierColumn");

            if (string.IsNullOrWhiteSpace(entityQualifierColumn))
            {
                entityQualifierColumn = PageParameter("EntityQualifierColumn");
            }

            string entityQualifierValue = GetAttributeValue("EntityQualifierValue");

            if (string.IsNullOrWhiteSpace(entityQualifierValue))
            {
                entityQualifierValue = PageParameter("EntityQualifierValue");
            }

            var sb = new StringBuilder();

            // Get the context entity
            Rock.Data.IEntity contextEntity = this.ContextEntity();

            if (contextEntity != null)
            {
                var service = new TaggedItemService();
                foreach (dynamic item in service.Get(
                             contextEntity.TypeId, entityQualifierColumn, entityQualifierValue, CurrentPersonId, contextEntity.Guid)
                         .Select(i => new {
                    OwnerId = i.Tag.OwnerId,
                    Name = i.Tag.Name
                }))
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(',');
                    }
                    sb.Append(item.Name);
                    if (CurrentPersonId.HasValue && item.OwnerId == CurrentPersonId.Value)
                    {
                        sb.Append("^personal");
                    }
                }

                phTags.Controls.Add(new LiteralControl(string.Format(
                                                           "<input name=\"person-tags\" id=\"person-tags\" value=\"{0}\" />", sb.ToString())));

                string script = string.Format(@"
    $(document).ready(function () {{
        $('ul.ui-autocomplete').css('width', '300px');
        $('#person-tags').tagsInput({{
            'autocomplete_url': function( request, response ) {{
                $.ajax({{
                    url: Rock.settings.get('baseUrl') + 'api/tags/availablenames/{0}/{1}/{2}{3}{4}',
                    dataType: 'json',
                    success: function(data, status, xhr){{ 
                        response($.map(data, function (item) {{
                            return {{
                                value: item.Name,
                                class: item.OwnerId == null || item.OwnerId == '' ? 'system' : 'personal'
                            }}
                        }}))
                    }},
                    error: function(xhr, status, error) {{
                        alert('availablenames status: ' + status + ' [' + error + ']: ' + xhr.reponseText);
                    }}
                }});
            }},
            autoCompleteAppendTo: 'div.tag-wrap',
            autoCompleteMessages: {{
              noResults: function () {{ }},
              results: function () {{ }}
            }},
            'height': 'auto',
            'width': '100%',
            'interactive': true,
            'defaultText': 'add tag',
            'removeWithBackspace': false,
            'onAddTag': verifyTag,
            'onRemoveTag': RemoveTag,
            'enableDelete': true
        }});
    }});

    function verifyTag(tagName) {{
        $.ajax({{
            type: 'GET',
            url: Rock.settings.get('baseUrl') + 'api/tags/{0}/{1}/' + tagName + '{3}{4}',
            statusCode: {{
                404: function () {{
                        var r = confirm(""A tag called '"" + tagName + ""' does not exist. Do you want to create a new personal tag?"");
                        if (r == true) {{
                            AddTag(tagName);
                        }}
                        else {{
                            // remove tag
                            $('#person-tags').removeTag(tagName);
                        }}
                    }},
                200: function (data, status, xhr) {{
                        AddTag(tagName);
                    }}
            }},
        }});
    }}

    function AddTag(tagName) {{
        $.ajax({{
            type: 'POST',
            url: Rock.settings.get('baseUrl') + 'api/taggeditems/{0}/{1}/{2}/' + tagName + '{3}{4}',
            error: function (xhr, status, error) {{
                alert('AddTag() status: ' + status + ' [' + error + ']: ' + xhr.responseText);
            }}
        }});
    }}

    function RemoveTag(tagName) {{
        $.ajax({{
            type: 'DELETE',
            url: Rock.settings.get('baseUrl') + 'api/taggeditems/{0}/{1}/{2}/' + tagName + '{3}{4}',
            error: function (xhr, status, error) {{
                alert('RemoveTag() status: ' + status + ' [' + error + ']: ' + xhr.responseText);
            }}
        }});
    }}

",
                                              contextEntity.TypeId, CurrentPersonId, contextEntity.Guid.ToString(),
                                              string.IsNullOrWhiteSpace(entityQualifierColumn) ? "" : "/" + entityQualifierColumn,
                                              string.IsNullOrWhiteSpace(entityQualifierValue) ? "" : "/" + entityQualifierValue);
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "tags-" + this.BlockId.ToString(), script, true);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Saves the tag values that user entered for the entity (
        /// </summary>
        /// <param name="personAlias">The person alias.</param>
        public void SaveTagValues(PersonAlias personAlias)
        {
            int?currentPersonId = null;

            if (personAlias != null)
            {
                currentPersonId = personAlias.PersonId;
            }

            if (EntityGuid != Guid.Empty)
            {
                var rockContext       = new RockContext();
                var tagService        = new TagService(rockContext);
                var taggedItemService = new TaggedItemService(rockContext);
                var person            = currentPersonId.HasValue ? new PersonService(rockContext).Get(currentPersonId.Value) : null;

                // Get the existing tagged items for this entity
                var existingTaggedItems = new List <TaggedItem>();
                foreach (var taggedItem in taggedItemService.Get(EntityTypeId, EntityQualifierColumn, EntityQualifierValue, currentPersonId, EntityGuid, CategoryGuid, ShowInActiveTags))
                {
                    if (taggedItem.IsAuthorized(Authorization.VIEW, person))
                    {
                        existingTaggedItems.Add(taggedItem);
                    }
                }

                // Get tag values after user edit
                var currentTags = new List <Tag>();
                foreach (var value in this.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    string tagName = value;
                    if (tagName.Contains('^'))
                    {
                        tagName = tagName.Split(new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries)[0];
                    }

                    // If this is a new tag, create it
                    Tag tag = tagService.Get(EntityTypeId, EntityQualifierColumn, EntityQualifierValue, currentPersonId, tagName, CategoryGuid, ShowInActiveTags);
                    if ((tag == null || !tag.IsAuthorized("Tag", person)) && personAlias != null)
                    {
                        tag = new Tag();
                        tag.EntityTypeId = EntityTypeId;
                        tag.CategoryId   = CategoryId;
                        tag.EntityTypeQualifierColumn = EntityQualifierColumn;
                        tag.EntityTypeQualifierValue  = EntityQualifierValue;
                        tag.OwnerPersonAliasId        = personAlias.Id;
                        tag.Name = tagName;
                        tagService.Add(tag);
                    }

                    if (tag != null)
                    {
                        currentTags.Add(tag);
                    }
                }

                rockContext.SaveChanges();

                var currentNames  = currentTags.Select(t => t.Name).ToList();
                var existingNames = existingTaggedItems.Select(t => t.Tag.Name).ToList();

                // Delete any tagged items that user removed
                foreach (var taggedItem in existingTaggedItems)
                {
                    if (!currentNames.Contains(taggedItem.Tag.Name, StringComparer.OrdinalIgnoreCase) && taggedItem.IsAuthorized("Tag", person))
                    {
                        existingNames.Remove(taggedItem.Tag.Name);
                        taggedItemService.Delete(taggedItem);
                    }
                }
                rockContext.SaveChanges();

                // Add any tagged items that user added
                foreach (var tag in currentTags)
                {
                    if (tag.IsAuthorized("Tag", person) && !existingNames.Contains(tag.Name, StringComparer.OrdinalIgnoreCase))
                    {
                        var taggedItem = new TaggedItem();
                        taggedItem.TagId        = tag.Id;
                        taggedItem.EntityTypeId = this.EntityTypeId;
                        taggedItem.EntityGuid   = EntityGuid;
                        taggedItemService.Add(taggedItem);
                    }
                }
                rockContext.SaveChanges();
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Maps the Connect Groups.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapGroups(IQueryable <Row> tableData)  //Just mapping Connect Groups and not People Lists (Wonder if People lists could be Tags?)
        {
            var lookupContext           = new RockContext();
            int completedMembers        = 0;
            int completedGroups         = 0;
            int completedLifeStages     = 0;
            int completedTags           = 0;
            int completedIndividualTags = 0;
            int totalRows  = tableData.Count();
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying group import ({0:N0} found. Total may vary based on Group Type Name).", totalRows));


            foreach (var row in tableData)
            {
                var rockContext               = new RockContext();
                var lifeStageContext          = new RockContext();
                var connectGroupContext       = new RockContext();
                var connectGroupMemberContext = new RockContext();

                string groupTypeName = row["Group_Type_Name"] as string;
                if (groupTypeName.Trim() == "Connect Groups")              //Moves Connect Groups into Rock Groups
                {
                    var groupTypeIdSection    = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Name == "Event/Serving/Small Group Section").Select(a => a.Id).FirstOrDefault();
                    var connectGroupsId       = new GroupService(lookupContext).Queryable().Where(g => g.Name == "Connect Groups" && g.GroupTypeId == groupTypeIdSection).Select(a => a.Id).FirstOrDefault();
                    var groupTypeIdSmallGroup = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Name == "Small Group").Select(a => a.Id).FirstOrDefault();

                    string   groupName       = row["Group_Name"] as string;
                    int?     groupId         = row["Group_ID"] as int?;
                    int?     individualId    = row["Individual_ID"] as int?;
                    int?     personId        = GetPersonAliasId(individualId);
                    DateTime?createdDateTime = row["Created_Date"] as DateTime?;


                    //Check to see if Head of Connect Group Tree exists

                    //If it doesn't exist
                    if (connectGroupsId == 0)
                    {
                        //Create one.
                        var connectGroupTree = new Group();
                        connectGroupTree.IsSystem    = false;
                        connectGroupTree.GroupTypeId = groupTypeIdSection;
                        connectGroupTree.CampusId    = 1;
                        connectGroupTree.Name        = "Connect Groups";
                        connectGroupTree.Description = "Crossroads Connect Group Ministry";
                        connectGroupTree.IsActive    = true;
                        //connectGroupTree.Order = 0;
                        connectGroupTree.CreatedByPersonAliasId = 1;
                        connectGroupTree.CreatedDateTime        = DateTime.Now;

                        //save group
                        rockContext.WrapTransaction(() =>
                        {
                            rockContext.Configuration.AutoDetectChangesEnabled = false;
                            rockContext.Groups.Add(connectGroupTree);
                            rockContext.SaveChanges(DisableAudit);
                        });
                    }

                    //check to see if life stage exists
                    //getting the life stage name
                    string lifeStage = groupName;
                    int    index     = lifeStage.IndexOf("-");
                    if (index > 0)
                    {
                        lifeStage = lifeStage.Substring(0, index).Trim();
                    }

                    //checks to see if it exists
                    int existingLifeStage = new GroupService(lookupContext).Queryable().Where(g => g.Name == lifeStage).Select(a => a.Id).FirstOrDefault();
                    if (existingLifeStage == 0)
                    {
                        //Create one.
                        var connectGroupsLifeStage = new Group();
                        connectGroupsLifeStage.IsSystem      = false;
                        connectGroupsLifeStage.ParentGroupId = connectGroupsId;
                        connectGroupsLifeStage.GroupTypeId   = groupTypeIdSection;
                        connectGroupsLifeStage.CampusId      = 1;
                        connectGroupsLifeStage.Name          = lifeStage;
                        connectGroupsLifeStage.Description   = "";
                        connectGroupsLifeStage.IsActive      = true;
                        //connectGroupsLifeStage.Order = 0;
                        connectGroupsLifeStage.CreatedByPersonAliasId = 1;
                        connectGroupsLifeStage.CreatedDateTime        = DateTime.Now;

                        //save Life Stage

                        lifeStageContext.WrapTransaction(() =>
                        {
                            lifeStageContext.Configuration.AutoDetectChangesEnabled = false;
                            lifeStageContext.Groups.Add(connectGroupsLifeStage);
                            lifeStageContext.SaveChanges(DisableAudit);
                        });
                        completedLifeStages++;
                    }

                    int existingConnectGroup = new GroupService(lookupContext).Queryable().Where(g => g.Name == groupName).Select(a => a.Id).FirstOrDefault();
                    existingLifeStage = new GroupService(lookupContext).Queryable().Where(g => g.Name == lifeStage).Select(a => a.Id).FirstOrDefault();
                    //check to see if Connect Group exists.
                    if (existingConnectGroup == 0)
                    {
                        //Create one.
                        var connectGroups = new Group();
                        connectGroups.IsSystem      = false;
                        connectGroups.GroupTypeId   = groupTypeIdSmallGroup;
                        connectGroups.ParentGroupId = existingLifeStage;
                        connectGroups.CampusId      = 1;
                        connectGroups.Name          = groupName;
                        connectGroups.Description   = "";
                        connectGroups.IsActive      = true;
                        //connectGroups.Order = 0;
                        connectGroups.CreatedByPersonAliasId = 1;
                        connectGroups.CreatedDateTime        = createdDateTime;
                        connectGroups.ForeignId = groupId.ToString(); //Will use this for GroupsAttendance

                        //Save Group
                        connectGroupContext.WrapTransaction(() =>
                        {
                            connectGroupContext.Configuration.AutoDetectChangesEnabled = false;
                            connectGroupContext.Groups.Add(connectGroups);
                            connectGroupContext.SaveChanges(DisableAudit);
                        });
                        completedGroups++;
                    }

                    existingConnectGroup = new GroupService(lookupContext).Queryable().Where(g => g.Name == groupName).Select(a => a.Id).FirstOrDefault();

                    //Adds Group Member(s)
                    //makes sure Connect Group Exists
                    if (existingConnectGroup != 0)
                    {
                        int memberGroupTypeRoleId = new GroupTypeRoleService(lookupContext).Queryable().Where(g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member").Select(a => a.Id).FirstOrDefault();
                        int groupMemberExists     = new GroupMemberService(lookupContext).Queryable().Where(g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId).Select(a => a.Id).FirstOrDefault();
                        if (groupMemberExists == 0)
                        {
                            //adds member
                            var connectGroupMember = new GroupMember();
                            connectGroupMember.IsSystem    = false;
                            connectGroupMember.GroupId     = existingConnectGroup;
                            connectGroupMember.PersonId    = (int)personId;
                            connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member
                            // ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) );

                            //Save Member
                            connectGroupMemberContext.WrapTransaction(() =>
                            {
                                connectGroupMemberContext.Configuration.AutoDetectChangesEnabled = false;
                                connectGroupMemberContext.GroupMembers.Add(connectGroupMember);
                                connectGroupMemberContext.SaveChanges(DisableAudit);
                            });
                            completedMembers++;
                        }
                    }

                    if (completedMembers % percentage < 1)
                    {
                        int percentComplete = completedMembers / percentage;
                        //ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) );
                    }
                    else if (completedMembers % ReportingNumber < 1)
                    {
                        ReportPartialProgress();
                    }
                }


                if (groupTypeName.Trim() == "Care Ministries")              //Moves Care Ministries into Rock Groups
                {
                    var groupTypeIdSection    = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Name == "Event/Serving/Small Group Section").Select(a => a.Id).FirstOrDefault();
                    var careMinistriesId      = new GroupService(lookupContext).Queryable().Where(g => g.Name == "Care Ministries" && g.GroupTypeId == groupTypeIdSection).Select(a => a.Id).FirstOrDefault();
                    var groupTypeIdSmallGroup = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Name == "Small Group").Select(a => a.Id).FirstOrDefault();

                    string   groupName       = row["Group_Name"] as string;
                    int?     groupId         = row["Group_ID"] as int?;
                    int?     individualId    = row["Individual_ID"] as int?;
                    int?     personId        = GetPersonAliasId(individualId);
                    DateTime?createdDateTime = row["Created_Date"] as DateTime?;


                    //Check to see if Head of Care Ministries Tree exists

                    //If it doesn't exist
                    if (careMinistriesId == 0)
                    {
                        //Create one.
                        var connectGroupTree = new Group();
                        connectGroupTree.IsSystem    = false;
                        connectGroupTree.GroupTypeId = groupTypeIdSection;
                        connectGroupTree.CampusId    = 1;
                        connectGroupTree.Name        = "Care Ministries";
                        connectGroupTree.Description = "Crossroads Care Ministries";
                        connectGroupTree.IsActive    = true;
                        //connectGroupTree.Order = 0;
                        connectGroupTree.CreatedByPersonAliasId = 1;
                        connectGroupTree.CreatedDateTime        = DateTime.Now;

                        //save group
                        var careMinistryContext = new RockContext();
                        careMinistryContext.WrapTransaction(() =>
                        {
                            careMinistryContext.Configuration.AutoDetectChangesEnabled = false;
                            careMinistryContext.Groups.Add(connectGroupTree);
                            careMinistryContext.SaveChanges(DisableAudit);
                        });
                    }

                    int existingConnectGroup   = new GroupService(lookupContext).Queryable().Where(g => g.Name == groupName).Select(a => a.Id).FirstOrDefault();
                    int existingCareMinistries = new GroupService(lookupContext).Queryable().Where(g => g.Name == "Care Ministries").Select(a => a.Id).FirstOrDefault();

                    //check to see if Connect Group exists.
                    if (existingConnectGroup == 0)
                    {
                        //Create one.
                        var careGroup = new Group();
                        careGroup.IsSystem      = false;
                        careGroup.GroupTypeId   = groupTypeIdSmallGroup;
                        careGroup.ParentGroupId = existingCareMinistries;
                        careGroup.CampusId      = 1;
                        careGroup.Name          = groupName;
                        careGroup.Description   = "";
                        careGroup.IsActive      = true;
                        //connectGroups.Order = 0;
                        careGroup.CreatedByPersonAliasId = 1;
                        careGroup.CreatedDateTime        = createdDateTime;
                        careGroup.ForeignId = groupId.ToString(); //will use this later for GroupsAttendance

                        //Save Group
                        var careMinistryGroupContext = new RockContext();
                        careMinistryGroupContext.WrapTransaction(() =>
                        {
                            careMinistryGroupContext.Configuration.AutoDetectChangesEnabled = false;
                            careMinistryGroupContext.Groups.Add(careGroup);
                            careMinistryGroupContext.SaveChanges(DisableAudit);
                        });
                        completedGroups++;
                    }

                    existingConnectGroup = new GroupService(lookupContext).Queryable().Where(g => g.Name == groupName).Select(a => a.Id).FirstOrDefault();

                    //Adds Group Member(s)
                    //makes sure Connect Group Exists
                    if (existingConnectGroup != 0)
                    {
                        int memberGroupTypeRoleId = new GroupTypeRoleService(lookupContext).Queryable().Where(g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member").Select(a => a.Id).FirstOrDefault();
                        int groupMemberExists     = new GroupMemberService(lookupContext).Queryable().Where(g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId).Select(a => a.Id).FirstOrDefault();
                        if (groupMemberExists == 0)
                        {
                            //adds member
                            var connectGroupMember = new GroupMember();
                            connectGroupMember.IsSystem    = false;
                            connectGroupMember.GroupId     = existingConnectGroup;
                            connectGroupMember.PersonId    = (int)personId;
                            connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member
                            //ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) );

                            //Save Member
                            var careGroupMemberContext = new RockContext();
                            careGroupMemberContext.WrapTransaction(() =>
                            {
                                careGroupMemberContext.Configuration.AutoDetectChangesEnabled = false;
                                careGroupMemberContext.GroupMembers.Add(connectGroupMember);
                                careGroupMemberContext.SaveChanges(DisableAudit);
                            });
                            completedMembers++;
                        }
                    }

                    if (completedMembers % percentage < 1)
                    {
                        int percentComplete = completedMembers / percentage;
                        // ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) );
                    }
                    else if (completedMembers % ReportingNumber < 1)
                    {
                        ReportPartialProgress();
                    }
                }


                if (groupTypeName.Trim() == "Intro Connect Groups")              //Moves Intro Connect Groups into Rock Groups
                {
                    var groupTypeIdSection    = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Name == "Event/Serving/Small Group Section").Select(a => a.Id).FirstOrDefault();
                    var introConnectGroupsId  = new GroupService(lookupContext).Queryable().Where(g => g.Name == "Intro Connect Groups" && g.GroupTypeId == groupTypeIdSection).Select(a => a.Id).FirstOrDefault();
                    var groupTypeIdSmallGroup = new GroupTypeService(lookupContext).Queryable().Where(gt => gt.Name == "Small Group").Select(a => a.Id).FirstOrDefault();

                    string   groupName       = row["Group_Name"] as string;
                    int?     groupId         = row["Group_ID"] as int?;
                    int?     individualId    = row["Individual_ID"] as int?;
                    int?     personId        = GetPersonAliasId(individualId);
                    DateTime?createdDateTime = row["Created_Date"] as DateTime?;


                    //Check to see if Head of Care Ministries Tree exists

                    //If it doesn't exist
                    if (introConnectGroupsId == 0)
                    {
                        //Create one.
                        var connectGroupTree = new Group();
                        connectGroupTree.IsSystem    = false;
                        connectGroupTree.GroupTypeId = groupTypeIdSection;
                        connectGroupTree.CampusId    = 1;
                        connectGroupTree.Name        = "Intro Connect Groups";
                        connectGroupTree.Description = "Crossroads Intro Connect Groups";
                        connectGroupTree.IsActive    = true;
                        //connectGroupTree.Order = 0;
                        connectGroupTree.CreatedByPersonAliasId = 1;
                        connectGroupTree.CreatedDateTime        = DateTime.Now;

                        //save group
                        var introConnectGroupTreeContext = new RockContext();
                        introConnectGroupTreeContext.WrapTransaction(() =>
                        {
                            introConnectGroupTreeContext.Configuration.AutoDetectChangesEnabled = false;
                            introConnectGroupTreeContext.Groups.Add(connectGroupTree);
                            introConnectGroupTreeContext.SaveChanges(DisableAudit);
                        });
                    }

                    int existingConnectGroup      = new GroupService(lookupContext).Queryable().Where(g => g.Name == groupName).Select(a => a.Id).FirstOrDefault();
                    int existingIntroConnectGroup = new GroupService(lookupContext).Queryable().Where(g => g.Name == "Intro Connect Groups").Select(a => a.Id).FirstOrDefault();

                    //check to see if Connect Group exists.
                    if (existingConnectGroup == 0)
                    {
                        //Create one.
                        var introConnectGroup = new Group();
                        introConnectGroup.IsSystem      = false;
                        introConnectGroup.GroupTypeId   = groupTypeIdSmallGroup;
                        introConnectGroup.ParentGroupId = existingIntroConnectGroup;
                        introConnectGroup.CampusId      = 1;
                        introConnectGroup.Name          = groupName;
                        introConnectGroup.Description   = "";
                        introConnectGroup.IsActive      = true;
                        //connectGroups.Order = 0;
                        introConnectGroup.CreatedByPersonAliasId = 1;
                        introConnectGroup.CreatedDateTime        = createdDateTime;
                        introConnectGroup.ForeignId = groupId.ToString(); //will use this later for GroupsAttendance

                        //Save Group
                        var introConnectGroupConext = new RockContext();
                        introConnectGroupConext.WrapTransaction(() =>
                        {
                            introConnectGroupConext.Configuration.AutoDetectChangesEnabled = false;
                            introConnectGroupConext.Groups.Add(introConnectGroup);
                            introConnectGroupConext.SaveChanges(DisableAudit);
                        });
                        completedGroups++;
                    }

                    existingConnectGroup = new GroupService(lookupContext).Queryable().Where(g => g.Name == groupName).Select(a => a.Id).FirstOrDefault();

                    //Adds Group Member(s)
                    //makes sure Connect Group Exists
                    if (existingConnectGroup != 0)
                    {
                        int memberGroupTypeRoleId = new GroupTypeRoleService(lookupContext).Queryable().Where(g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member").Select(a => a.Id).FirstOrDefault();
                        int groupMemberExists     = new GroupMemberService(lookupContext).Queryable().Where(g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId).Select(a => a.Id).FirstOrDefault();
                        if (groupMemberExists == 0)
                        {
                            //adds member
                            var connectGroupMember = new GroupMember();
                            connectGroupMember.IsSystem    = false;
                            connectGroupMember.GroupId     = existingConnectGroup;
                            connectGroupMember.PersonId    = (int)personId;
                            connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member
                            //ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) );

                            //Save Member
                            var introConnectGroupMemberConext = new RockContext();
                            introConnectGroupMemberConext.WrapTransaction(() =>
                            {
                                introConnectGroupMemberConext.Configuration.AutoDetectChangesEnabled = false;
                                introConnectGroupMemberConext.GroupMembers.Add(connectGroupMember);
                                introConnectGroupMemberConext.SaveChanges(DisableAudit);
                            });
                            completedMembers++;
                        }
                    }

                    if (completedMembers % percentage < 1)
                    {
                        int percentComplete = completedMembers / percentage;
                        // ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) );
                    }
                    else if (completedMembers % ReportingNumber < 1)
                    {
                        ReportPartialProgress();
                    }
                }



                if (groupTypeName.Trim() == "People List")      //Places People Lists in tags
                {
                    var tagService        = new TagService(lookupContext);
                    var entityTypeService = new EntityTypeService(lookupContext);
                    var taggedItemService = new TaggedItemService(lookupContext);
                    var personService     = new PersonService(lookupContext);

                    //var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault();
                    //var connectGroupsId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Connect Groups" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault();
                    //var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault();


                    string   peopleListName  = row["Group_Name"] as string;
                    int?     groupId         = row["Group_ID"] as int?;
                    int?     individualId    = row["Individual_ID"] as int?;
                    int?     personId        = GetPersonAliasId(individualId);
                    DateTime?createdDateTime = row["Created_Date"] as DateTime?;

                    if (personId != null)
                    {
                        //check if tag exists
                        if (tagService.Queryable().Where(t => t.Name == peopleListName).FirstOrDefault() == null)
                        {
                            //create if it doesn't
                            var newTag = new Tag();
                            newTag.IsSystem = false;
                            newTag.Name     = peopleListName;
                            newTag.EntityTypeQualifierColumn = string.Empty;
                            newTag.EntityTypeQualifierValue  = string.Empty;
                            newTag.EntityTypeId = entityTypeService.Queryable().Where(e => e.Name == "Rock.Model.Person").FirstOrDefault().Id;

                            //Save tag
                            var tagContext = new RockContext();
                            tagContext.WrapTransaction(() =>
                            {
                                tagContext.Configuration.AutoDetectChangesEnabled = false;
                                tagContext.Tags.Add(newTag);
                                tagContext.SaveChanges(DisableAudit);
                            });

                            completedTags++;
                        }

                        var personAlias = new PersonAlias();
                        personAlias = null;

                        if (tagService.Queryable().Where(t => t.Name == peopleListName).FirstOrDefault() != null)     //Makes sure tag exists
                        {
                            //selects the ID of the current people list / tag
                            int tagId = tagService.Queryable().Where(t => t.Name == peopleListName).FirstOrDefault().Id;

                            //gets the person instance in order to use person's GUID later.
                            var personTagged = personService.Queryable().Where(p => p.Id == personId).FirstOrDefault();
                            if (personTagged == null)
                            {
                                var personAliasService = new PersonAliasService(lookupContext);
                                personAlias = personAliasService.Queryable().Where(p => p.PersonId == (int)personId).FirstOrDefault();
                                //ReportProgress( 0, string.Format( "Not able to tag person Id: {0} Tag Name: {1} F1 groupId: {2} Tag Id: {3}. ", personId, peopleListName, groupId, tagId ) );
                            }

                            //check if person already has this tag
                            if (personTagged != null && taggedItemService.Queryable().Where(t => t.EntityGuid == personTagged.Guid && t.TagId == tagId).FirstOrDefault() == null)
                            {
                                //add tag if one doesn't exist for person.
                                var taggedItem = new TaggedItem();
                                taggedItem.IsSystem        = false;
                                taggedItem.TagId           = tagId;
                                taggedItem.EntityGuid      = personTagged.Guid;
                                taggedItem.CreatedDateTime = createdDateTime;

                                //save tag
                                var tagContext = new RockContext();
                                tagContext.WrapTransaction(() =>
                                {
                                    tagContext.Configuration.AutoDetectChangesEnabled = false;
                                    tagContext.TaggedItems.Add(taggedItem);
                                    tagContext.SaveChanges(DisableAudit);
                                });

                                completedIndividualTags++;
                            }
                            if (personAlias != null && taggedItemService.Queryable().Where(t => t.EntityGuid == personAlias.AliasPersonGuid && t.TagId == tagId).FirstOrDefault() == null)
                            {
                                //add tag if one doesn't exist for person.
                                var taggedItem = new TaggedItem();
                                taggedItem.IsSystem        = false;
                                taggedItem.TagId           = tagId;
                                taggedItem.EntityGuid      = personAlias.AliasPersonGuid;
                                taggedItem.CreatedDateTime = createdDateTime;

                                //save tag
                                var tagContext = new RockContext();
                                tagContext.WrapTransaction(() =>
                                {
                                    tagContext.Configuration.AutoDetectChangesEnabled = false;
                                    tagContext.TaggedItems.Add(taggedItem);
                                    tagContext.SaveChanges(DisableAudit);
                                });

                                completedIndividualTags++;
                            }
                        }
                        //report Progress
                        if (completedIndividualTags != 0)
                        {
                            if (completedIndividualTags % percentage < 1)
                            {
                                int percentComplete = completedIndividualTags / percentage;
                                // ReportProgress( percentComplete, string.Format( "People Lists / Tags Imported: {0:N0}, Tagged Individuals: {1:N0} ({2:N0}% complete). ", completedTags, completedIndividualTags, percentComplete ) );
                            }
                            else if (completedMembers % ReportingNumber < 1)
                            {
                                ReportPartialProgress();
                            }
                        }
                    }
                }
            }
        }