public void Delete(int entityTypeId, int ownerId, Guid entityGuid, string name, string entityQualifier = null, string entityQualifierValue = null, Guid?categoryGuid = null, bool?includeInactive = null)
        {
            SetProxyCreation(true);

            var personAlias = GetPersonAlias();

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

            TaggedItem taggedItem = null;

            var tagService = new TagService((Rock.Data.RockContext)Service.Context);
            var tag        = tagService.Get(entityTypeId, entityQualifier, entityQualifierValue, ownerId, name, categoryGuid, includeInactive);

            if (tag != null)
            {
                taggedItem = tag.TaggedItems.Where(i => i.EntityGuid == entityGuid).FirstOrDefault();
            }

            if (taggedItem == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            if (!taggedItem.IsAuthorized("Tag", GetPerson()))
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            Service.Delete(taggedItem);

            Service.Context.SaveChanges();
        }
예제 #2
0
        public virtual TaggedItemEntity FromModel(TaggedItem taggedItem, PrimaryKeyResolvingMap pkMap)
        {
            if (taggedItem == null)
            {
                throw new ArgumentNullException(nameof(taggedItem));
            }
            if (pkMap == null)
            {
                throw new ArgumentNullException(nameof(pkMap));
            }

            pkMap.AddPair(taggedItem, this);

            Id = taggedItem.Id;

            CreatedBy    = taggedItem.CreatedBy;
            CreatedDate  = taggedItem.CreatedDate;
            ModifiedBy   = taggedItem.ModifiedBy;
            ModifiedDate = taggedItem.ModifiedDate;

            Label      = taggedItem.Label;
            ObjectType = taggedItem.EntityType;
            ObjectId   = taggedItem.EntityId;

            if (taggedItem.Tags != null)
            {
                Tags = new ObservableCollection <TagEntity>(taggedItem.Tags.Select(x => new TagEntity
                {
                    Tag = x
                }));
            }

            return(this);
        }
예제 #3
0
        public async Task <IActionResult> Add([FromBody] TagViewModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest());
            }

            var item = new TaggedItem()
            {
                ID           = model.ID,
                ImageUrl     = model.ImageUrl,
                Manufacturer = model.Manufacturer,
                Price        = model.Price,
                SalePrice    = model.SalePrice,
                Title        = model.Title
            };

            try
            {
                this.shopSightContext.TaggedItems.Add(item);
                await this.shopSightContext.SaveChangesAsync();

                return(this.CreatedAtRoute("GetTag", new { id = model.ID }, model));
            } catch (DbUpdateException)
            {
                return(this.StatusCode(500));
            }
        }
예제 #4
0
 private static TagViewModel ToTagViewModel(TaggedItem taggedItem)
 {
     return(new TagViewModel()
     {
         ID = taggedItem.ID,
         ImageUrl = taggedItem.ImageUrl,
         Manufacturer = taggedItem.Manufacturer,
         Price = taggedItem.Price,
         SalePrice = taggedItem.SalePrice,
         Title = taggedItem.Title
     });
 }
        public HttpResponseMessage Post(int entityTypeId, int ownerId, Guid entityGuid, string name, string entityQualifier = null, string entityQualifierValue = null, Guid?categoryGuid = null, bool?includeInactive = null)
        {
            SetProxyCreation(true);

            var person      = GetPerson();
            var personAlias = GetPersonAlias();

            var tagService = new TagService((Rock.Data.RockContext)Service.Context);

            var tag = tagService.Get(entityTypeId, entityQualifier, entityQualifierValue, ownerId, name, categoryGuid, includeInactive);

            if (tag == null || !tag.IsAuthorized("Tag", person))
            {
                int?categoryId = null;
                if (categoryGuid.HasValue)
                {
                    var category = CategoryCache.Get(categoryGuid.Value);
                    categoryId = category != null ? category.Id : (int?)null;
                }

                tag = new Tag();
                tag.EntityTypeId = entityTypeId;
                tag.CategoryId   = categoryId;
                tag.EntityTypeQualifierColumn = entityQualifier;
                tag.EntityTypeQualifierValue  = entityQualifierValue;
                tag.OwnerPersonAliasId        = new PersonAliasService((Rock.Data.RockContext)Service.Context).GetPrimaryAliasId(ownerId);
                tag.Name = name;
                tagService.Add(tag);
            }

            tag.TaggedItems = tag.TaggedItems ?? new Collection <TaggedItem>();

            var taggedItem = tag.TaggedItems.FirstOrDefault(i => i.EntityGuid.Equals(entityGuid));

            if (taggedItem == null)
            {
                taggedItem              = new TaggedItem();
                taggedItem.Tag          = tag;
                taggedItem.EntityTypeId = entityTypeId;
                taggedItem.EntityGuid   = entityGuid;
                tag.TaggedItems.Add(taggedItem);
            }

            System.Web.HttpContext.Current.Items.Add("CurrentPerson", person);
            Service.Context.SaveChanges();

            return(ControllerContext.Request.CreateResponse(HttpStatusCode.Created, tag.Id));
        }
예제 #6
0
        public virtual TaggedItem ToModel(TaggedItem taggedItem)
        {
            if (taggedItem == null)
            {
                throw new ArgumentNullException(nameof(taggedItem));
            }

            taggedItem.Id = Id;

            taggedItem.CreatedBy    = CreatedBy;
            taggedItem.CreatedDate  = CreatedDate;
            taggedItem.ModifiedBy   = ModifiedBy;
            taggedItem.ModifiedDate = ModifiedDate;

            taggedItem.Label      = Label;
            taggedItem.EntityType = ObjectType;
            taggedItem.EntityId   = ObjectId;
            taggedItem.Tags       = Tags.Select(x => x.Tag).ToList();

            return(taggedItem);
        }
        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);
        }
예제 #8
0
        public HttpResponseMessage Post(int entityTypeId, int ownerId, Guid entityGuid, string name, string entityQualifier, string entityQualifierValue)
        {
            SetProxyCreation(true);

            var personAlias = GetPersonAlias();

            var tagService = new TagService((Rock.Data.RockContext)Service.Context);

            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.OwnerPersonAliasId        = new PersonAliasService((Rock.Data.RockContext)Service.Context).GetPrimaryAliasId(ownerId);
                tag.Name = name;
                tagService.Add(tag);
            }

            tag.TaggedItems = tag.TaggedItems ?? new Collection <TaggedItem>();

            var taggedItem = tag.TaggedItems.FirstOrDefault(i => i.EntityGuid.Equals(entityGuid));

            if (taggedItem == null)
            {
                taggedItem            = new TaggedItem();
                taggedItem.Tag        = tag;
                taggedItem.EntityGuid = entityGuid;
                tag.TaggedItems.Add(taggedItem);
            }

            System.Web.HttpContext.Current.Items.Add("CurrentPerson", GetPerson());
            Service.Context.SaveChanges();

            return(ControllerContext.Request.CreateResponse(HttpStatusCode.Created, tag.Id));
        }
예제 #9
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);
            }
        }
예제 #10
0
        public void Delete(int entityTypeId, int ownerId, Guid entityGuid, string name, string entityQualifier = null, string entityQualifierValue = null, Guid?categoryGuid = null, bool?includeInactive = null)
        {
            SetProxyCreation(true);

            // Deserialize the tag properties
            // This logic needs to sync with C# code in TagList.SerializeTag:
            // $"{name}^{tagCssClass}^{iconCssClass}^{backgroundColor}";
            if (name.Contains('^'))
            {
                name = name.Split('^')[0];
            }

            TaggedItem taggedItem = null;

            var tagService = new TagService((Rock.Data.RockContext)Service.Context);
            var tag        = tagService.Get(entityTypeId, entityQualifier, entityQualifierValue, ownerId, name, categoryGuid, includeInactive);

            if (tag != null)
            {
                taggedItem = tag.TaggedItems.Where(i => i.EntityGuid == entityGuid).FirstOrDefault();
            }

            if (taggedItem == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            if (!taggedItem.IsAuthorized(Rock.Security.Authorization.TAG, GetPerson((Rock.Data.RockContext)Service.Context)))
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            Service.Delete(taggedItem);

            Service.Context.SaveChanges();
        }
예제 #11
0
파일: TagList.cs 프로젝트: waldo2590/Rock
        /// <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();
            }
        }
예제 #12
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 )
                {
                    // add tag first
                    orgTag = new Tag();
                    orgTag.Name = tagName;
                    orgTag.EntityTypeQualifierColumn = string.Empty;
                    orgTag.EntityTypeQualifierValue = string.Empty;

                    orgTag.EntityTypeId = personEntityType.Id;
                    tagService.Add( orgTag );
                    rockContext.SaveChanges();

                    // new up a list of items for later count
                    orgTag.TaggedItems = new List<TaggedItem>();
                }

                // get the person and add them to the tag
                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 )
                                    {
                                        // add person to tag if they are not already in it
                                        if ( orgTag.TaggedItems.Where( i => i.EntityGuid == person.PrimaryAlias.AliasPersonGuid && i.TagId == orgTag.Id ).Count() == 0 )
                                        {
                                            TaggedItem taggedPerson = new TaggedItem();
                                            taggedPerson.Tag = orgTag;
                                            taggedPerson.EntityGuid = person.PrimaryAlias.AliasPersonGuid;
                                            orgTag.TaggedItems.Add( taggedPerson );
                                            rockContext.SaveChanges();
                                        }
                                        else
                                        {
                                            action.AddLogEntry( string.Format( "{0} already tagged with {1}", person.FullName, orgTag.Name ) );
                                        }

                                        return true;
                                    }
                                    else
                                    {
                                        errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString() ) );
                                    }
                                }
                            }
                            else
                            {
                                errorMessages.Add( "The attribute used to provide the person was not of type 'Person'." );
                            }
                        }
                    }
                }
            } else {
                errorMessages.Add("No organization tag was provided");
            }

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

            return true;
        }
예제 #13
0
        public static void Initialize(ShopSightContext context)
        {
            context.Database.EnsureCreated();
            if (context.TaggedItems.Any())
            {
                return;
            }

            var items = new TaggedItem[]
            {
                new TaggedItem()
                {
                    ID           = "a001",
                    ImageUrl     = "/images/sample/a001.jpg",
                    Manufacturer = "Nordstrom",
                    Price        = (decimal)50.00,
                    SalePrice    = (decimal)48.00,
                    Title        = "Blue Shirt"
                },
                new TaggedItem()
                {
                    ID           = "a002",
                    ImageUrl     = "/images/sample/a002.jpg",
                    Manufacturer = "Giordano",
                    Price        = (decimal)60.00,
                    SalePrice    = (decimal)55.00,
                    Title        = "White Shirt"
                },
                new TaggedItem()
                {
                    ID           = "a003",
                    ImageUrl     = "/images/sample/a003.jpg",
                    Manufacturer = "Ralph Lauren",
                    Price        = (decimal)45.00,
                    SalePrice    = null,
                    Title        = "White Shirt"
                },
                new TaggedItem()
                {
                    ID           = "a004",
                    ImageUrl     = "/images/sample/a004.jpg",
                    Manufacturer = "Levis",
                    Price        = (decimal)30.00,
                    SalePrice    = (decimal)28.00,
                    Title        = "Blue Jeans"
                },
                new TaggedItem()
                {
                    ID           = "a005",
                    ImageUrl     = "/images/sample/a005.jpg",
                    Manufacturer = "Levis",
                    Price        = (decimal)40.00,
                    SalePrice    = (decimal)38.00,
                    Title        = "Tan Jeans"
                },
                new TaggedItem()
                {
                    ID           = "a006",
                    ImageUrl     = "/images/sample/a006.jpg",
                    Manufacturer = "Levis",
                    Price        = (decimal)999.00,
                    SalePrice    = (decimal)599.00,
                    Title        = "Coat"
                },
            };

            foreach (var item in items)
            {
                context.TaggedItems.Add(item);
            }

            context.SaveChanges();
        }
예제 #14
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();
                            }
                        }
                    }
                }
            }
        }
예제 #15
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)
                {
                    // add tag first
                    orgTag      = new Tag();
                    orgTag.Name = tagName;
                    orgTag.EntityTypeQualifierColumn = string.Empty;
                    orgTag.EntityTypeQualifierValue  = string.Empty;

                    orgTag.EntityTypeId = personEntityType.Id;
                    tagService.Add(orgTag);
                    rockContext.SaveChanges();

                    // new up a list of items for later count
                    orgTag.TaggedItems = new List <TaggedItem>();
                }

                // get the person and add them to the tag
                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)
                                    {
                                        // add person to tag if they are not already in it
                                        if (orgTag.TaggedItems.Where(i => i.EntityGuid == person.PrimaryAlias.AliasPersonGuid && i.TagId == orgTag.Id).Count() == 0)
                                        {
                                            TaggedItem taggedPerson = new TaggedItem();
                                            taggedPerson.Tag        = orgTag;
                                            taggedPerson.EntityGuid = person.PrimaryAlias.AliasPersonGuid;
                                            orgTag.TaggedItems.Add(taggedPerson);
                                            rockContext.SaveChanges();
                                        }
                                        else
                                        {
                                            action.AddLogEntry(string.Format("{0} already tagged with {1}", person.FullName, orgTag.Name));
                                        }

                                        return(true);
                                    }
                                    else
                                    {
                                        errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
                                    }
                                }
                            }
                            else
                            {
                                errorMessages.Add("The attribute used to provide the person was not of type 'Person'.");
                            }
                        }
                    }
                }
            }
            else
            {
                errorMessages.Add("No organization tag was provided");
            }

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

            return(true);
        }
예제 #16
0
        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 );
        }
예제 #17
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);
        }
예제 #18
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();
            }
        }
예제 #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();
            }
        }
예제 #20
0
 public IHttpActionResult UpdateTaggedItem(TaggedItem taggedItem)
 {
     _taggedItemService.SaveTaggedItems(new[] { taggedItem });
     return(StatusCode(HttpStatusCode.NoContent));
 }
예제 #21
0
        //Just mapping Connect Groups and not People Lists (Wonder if People lists could be Tags?)
        /// <summary>
        /// Maps the Connect Groups.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapGroups( IQueryable<Row> tableData )
        {
            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();
                            }
                        }
                    }
                }
            }
        }
        public HttpResponseMessage Post( int entityTypeId, int ownerId, Guid entityGuid, string name, string entityQualifier, string entityQualifierValue )
        {
            SetProxyCreation( true );

            var personAlias = GetPersonAlias();

            var tagService = new TagService( (Rock.Data.RockContext)Service.Context );

            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.OwnerPersonAliasId = new PersonAliasService( (Rock.Data.RockContext)Service.Context ).GetPrimaryAliasId( ownerId );
                tag.Name = name;
                tagService.Add( tag );
            }

            tag.TaggedItems = tag.TaggedItems ?? new Collection<TaggedItem>();

            var taggedItem = tag.TaggedItems.FirstOrDefault( i => i.EntityGuid.Equals( entityGuid ) );
            if ( taggedItem == null )
            {
                taggedItem = new TaggedItem();
                taggedItem.Tag = tag;
                taggedItem.EntityGuid = entityGuid;
                tag.TaggedItems.Add( taggedItem );
            }

            System.Web.HttpContext.Current.Items.Add( "CurrentPerson", GetPerson() );
            Service.Context.SaveChanges();

            return ControllerContext.Request.CreateResponse( HttpStatusCode.Created );
        }
예제 #23
0
파일: TagList.cs 프로젝트: sjison/Rock
        /// <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();
            }
        }