/// <summary> /// Gets the tags. /// </summary> /// <returns></returns> private IQueryable <Tag> GetTags() { int?entityTypeId = rFilter.GetUserPreference("EntityType").AsInteger(false); if (entityTypeId.HasValue) { var queryable = new Rock.Model.TagService().Queryable(). Where(t => t.EntityTypeId == entityTypeId.Value); if (rFilter.GetUserPreference("Scope") == "Public") { // Only allow sorting of public tags if authorized to Administer rGrid.Columns[0].Visible = _canConfigure; queryable = queryable.Where(t => t.OwnerId == null); } else { int?personId = rFilter.GetUserPreference("Owner").AsInteger(false); if (_canConfigure && personId.HasValue) { queryable = queryable.Where(t => t.OwnerId == personId.Value); } else { queryable = queryable.Where(t => t.OwnerId == CurrentPersonId); } } return(queryable.OrderBy(t => t.Order)); } return(null); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var tagService = new Rock.Model.TagService(rockContext); Tag tag = null; int tagId = int.Parse(hfId.Value); if (tagId != 0) { tag = tagService.Get(tagId); } if (tag == null) { tag = new Tag(); tag.IsSystem = false; tagService.Add(tag); } string name = tbName.Text; int? ownerId = ppOwner.PersonId; int entityTypeId = ddlEntityType.SelectedValueAsId().Value; string qualifierCol = tbEntityTypeQualifierColumn.Text; string qualifierVal = tbEntityTypeQualifierValue.Text; // Verify tag with same name does not already exist if (tagService.Queryable() .Where(t => t.Id != tagId && t.Name == name && t.OwnerId.Equals(ownerId) && t.EntityTypeId == entityTypeId && t.EntityTypeQualifierColumn == qualifierCol && t.EntityTypeQualifierValue == qualifierVal) .Any()) { nbEditError.Heading = "Tag Already Exists"; nbEditError.Text = string.Format("A '{0}' tag already exists for the selected scope, owner, and entity type.", name); nbEditError.Visible = true; } else { tag.Name = name; tag.Description = tbDescription.Text; tag.OwnerId = ownerId; tag.EntityTypeId = entityTypeId; tag.EntityTypeQualifierColumn = qualifierCol; tag.EntityTypeQualifierValue = qualifierVal; rockContext.SaveChanges(); var qryParams = new Dictionary <string, string>(); qryParams["tagId"] = tag.Id.ToString(); NavigateToPage(RockPage.Guid, qryParams); } }
public Tag Get( int entityTypeId, int ownerId, string name, string entityQualifier, string entityQualifierValue ) { var service = new TagService(); var tag = service.Get( entityTypeId, entityQualifier, entityQualifierValue, ownerId ).FirstOrDefault(t => t.Name == name); if ( tag != null ) return tag; else throw new HttpResponseException( HttpStatusCode.NotFound ); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit( EventArgs e ) { base.OnInit( e ); gReport.DataKeyNames = new string[] { "Guid" }; gReport.GridRebind += gReport_GridRebind; int tagId = int.MinValue; if ( int.TryParse( PageParameter( "tagId" ), out tagId ) && tagId > 0 ) { Tag _tag = new TagService().Get( tagId ); if ( _tag != null ) { TagId = tagId; TagEntityType = EntityTypeCache.Read( _tag.EntityTypeId ); if ( TagEntityType != null ) { Type modelType = TagEntityType.GetEntityType(); lTaggedTitle.Text = "Tagged " + modelType.Name.Pluralize(); if ( modelType != null ) { Dictionary<string, BoundField> boundFields = gReport.Columns.OfType<BoundField>().ToDictionary( a => a.DataField ); foreach ( var column in gReport.GetPreviewColumns( modelType ) ) { int insertPos = gReport.Columns.IndexOf( gReport.Columns.OfType<DeleteField>().First() ); gReport.Columns.Insert( insertPos, column ); } if ( TagEntityType.Name == "Rock.Model.Person" ) { gReport.PersonIdField = "Id"; } BindGrid(); } } } } }
/// <summary> /// Handles the Click event of the btnDelete control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnDelete_Click(object sender, EventArgs e) { var tagService = new Rock.Model.TagService(); var tag = tagService.Get(int.Parse(hfId.Value)); if (tag != null) { string errorMessage; if (!tagService.CanDelete(tag, out errorMessage)) { mdDeleteWarning.Show(errorMessage, ModalAlertType.Information); return; } tagService.Delete(tag, CurrentPersonId); tagService.Save(tag, CurrentPersonId); NavigateToParentPage(); } }
/// <summary> /// Handles the Delete event of the rGrid control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void rGrid_Delete(object sender, RowEventArgs e) { var tagService = new Rock.Model.TagService(); var tag = tagService.Get((int)rGrid.DataKeys[e.RowIndex]["id"]); if (tag != null) { string errorMessage; if (!tagService.CanDelete(tag, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } tagService.Delete(tag, CurrentPersonId); tagService.Save(tag, CurrentPersonId); } BindGrid(); }
/// <summary> /// Handles the Delete event of the rGrid control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void rGrid_Delete(object sender, RowEventArgs e) { var rockContext = new RockContext(); var tagService = new Rock.Model.TagService(rockContext); var tag = tagService.Get(e.RowKeyId); if (tag != null) { string errorMessage; if (!tagService.CanDelete(tag, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } tagService.Delete(tag); rockContext.SaveChanges(); } BindGrid(); }
public override List<Rock.Web.UI.BreadCrumb> GetBreadCrumbs( Rock.Web.PageReference pageReference ) { var breadCrumbs = new List<BreadCrumb>(); string pageTitle = "New Tag"; int? tagId = PageParameter( "tagId" ).AsIntegerOrNull(); if (tagId.HasValue) { Tag tag = new TagService( new RockContext() ).Get( tagId.Value ); if (tag != null) { pageTitle = tag.Name; breadCrumbs.Add( new BreadCrumb( tag.Name, pageReference ) ); } } RockPage.Title = pageTitle; return breadCrumbs; }
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 ); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { Tag tag; using (new Rock.Data.UnitOfWorkScope()) { var tagService = new Rock.Model.TagService(); int tagId = int.Parse(hfId.Value); if (tagId == 0) { tag = new Tag(); tag.IsSystem = false; tagService.Add(tag, CurrentPersonId); } else { tag = tagService.Get(tagId); } tag.Name = tbName.Text; tag.OwnerId = ppOwner.PersonId; tag.EntityTypeId = ddlEntityType.SelectedValueAsId().Value; tag.EntityTypeQualifierColumn = tbEntityTypeQualifierColumn.Text; tag.EntityTypeQualifierValue = tbEntityTypeQualifierValue.Text; tagService.Save(tag, CurrentPersonId); } var qryParams = new Dictionary <string, string>(); qryParams["tagId"] = tag.Id.ToString(); NavigateToPage(this.CurrentPage.Guid, qryParams); }
private void DisplayTags(int? ownerId, int entityId) { // get tags var qry = new TagService( new RockContext() ) .Queryable() .Where(t => t.EntityTypeId == entityId && ( ( t.OwnerPersonAlias == null && !ownerId.HasValue ) || ( t.OwnerPersonAlias != null && ownerId.HasValue && t.OwnerPersonAlias.PersonId == ownerId.Value ) ) ) .Select(t => new { Id = t.Id, Name = t.Name, Count = t.TaggedItems.Count() }) .OrderBy(t => t.Name); // create dictionary to group by first letter of name Dictionary<char, List<TagSummary>> tagAlphabit = new Dictionary<char, List<TagSummary>>(); // load alphabit into dictionary for (char c = 'A'; c <= 'Z'; c++) { tagAlphabit.Add(c, new List<TagSummary>()); } tagAlphabit.Add('#', new List<TagSummary>()); tagAlphabit.Add( '*', new List<TagSummary>() ); // load tags var tags = qry.ToList(); foreach ( var tag in tags ) { var tagSummary = new TagSummary { Id = tag.Id, Name = tag.Name, Count = tag.Count }; char key = (char)tag.Name.Substring( 0, 1 ).ToUpper()[0]; if ( Char.IsNumber( key ) ) { key = '#'; } else { if ( !Char.IsLetter( key ) ) { key = '*'; } } tagAlphabit[key].Add(tagSummary); } // display tags StringBuilder tagOutput = new StringBuilder(); StringBuilder letterOutput = new StringBuilder(); letterOutput.Append("<ul class='list-inline tag-letterlist'>"); tagOutput.Append("<ul class='list-unstyled taglist'>"); foreach (var letterItem in tagAlphabit) { if (letterItem.Value.Count > 0) { letterOutput.Append(String.Format("<li><a href='#{0}'>{0}</a></li>", letterItem.Key.ToString())); // add tags to display tagOutput.Append(String.Format("<li class='clearfix'><h3><a name='{0}'></a>{1}</h3><ul class='list-inline'>", letterItem.Key.ToString(), letterItem.Key.ToString())); foreach (TagSummary tag in letterItem.Value) { Dictionary<string, string> queryString = new Dictionary<string, string>(); queryString.Add("tagId", tag.Id.ToString()); var detailPageUrl = LinkedPageUrl("DetailPage", queryString); tagOutput.Append(string.Format("<a href='{0}'><span class='tag'>{1} <small>({2})</small></span></a>", detailPageUrl, tag.Name, tag.Count)); } tagOutput.Append("</ul></li>"); } else { letterOutput.Append(String.Format("<li>{0}</li>", letterItem.Key.ToString())); } } tagOutput.Append("</ul>"); letterOutput.Append("</ul>"); // if no tags add message instead if ( tags.Count() == 0 ) { tagOutput.Clear(); tagOutput.Append("<div class='alert alert-info'><h4>Note</h4>No personal tags exist.</div>"); } lTagList.Text = tagOutput.ToString(); lLetters.Text = letterOutput.ToString(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); var tagService = new Rock.Model.TagService( rockContext ); Tag tag = null; int tagId = int.Parse( hfId.Value ); if ( tagId != 0 ) { tag = tagService.Get( tagId ); } if ( tag == null ) { tag = new Tag(); tag.IsSystem = false; tagService.Add( tag ); } string name = tbName.Text; int? ownerId = ppOwner.PersonId; int entityTypeId = ddlEntityType.SelectedValueAsId().Value; string qualifierCol = tbEntityTypeQualifierColumn.Text; string qualifierVal = tbEntityTypeQualifierValue.Text; // Verify tag with same name does not already exist if (tagService.Queryable() .Where( t => t.Id != tagId && t.Name == name && ( ( t.OwnerPersonAlias == null && !ownerId.HasValue ) || ( t.OwnerPersonAlias != null && ownerId.HasValue && t.OwnerPersonAlias.PersonId == ownerId.Value ) ) && t.EntityTypeId == entityTypeId && t.EntityTypeQualifierColumn == qualifierCol && t.EntityTypeQualifierValue == qualifierVal ) .Any()) { nbEditError.Heading = "Tag Already Exists"; nbEditError.Text = string.Format("A '{0}' tag already exists for the selected scope, owner, and entity type.", name); nbEditError.Visible = true; } else { int? ownerPersonAliasId = null; if (ownerId.HasValue) { ownerPersonAliasId = new PersonAliasService( rockContext ).GetPrimaryAliasId( ownerId.Value ); } tag.Name = name; tag.Description = tbDescription.Text; tag.OwnerPersonAliasId = ownerPersonAliasId; tag.EntityTypeId = entityTypeId; tag.EntityTypeQualifierColumn = qualifierCol; tag.EntityTypeQualifierValue = qualifierVal; rockContext.SaveChanges(); var qryParams = new Dictionary<string, string>(); qryParams["tagId"] = tag.Id.ToString(); NavigateToPage( RockPage.Guid, qryParams ); } }
public void Delete( int entityTypeId, int ownerId, Guid entityGuid, string name, string entityQualifier, string entityQualifierValue ) { var user = CurrentUser(); if ( user != null ) { using ( new Rock.Data.UnitOfWorkScope() ) { var tagService = new TagService(); var taggedItemService = new TaggedItemService(); if ( name.Contains( '^' ) ) name = name.Split( '^' )[0]; var tag = tagService.Get( entityTypeId, entityQualifier, entityQualifierValue, ownerId, name ); if ( tag == null ) throw new HttpResponseException( HttpStatusCode.NotFound ); var taggedItem = taggedItemService.Get( tag.Id, entityGuid ); if ( taggedItem == null ) throw new HttpResponseException( HttpStatusCode.NotFound ); taggedItemService.Delete( taggedItem, user.PersonId ); taggedItemService.Save( taggedItem, user.PersonId ); } } else throw new HttpResponseException( HttpStatusCode.Unauthorized ); }
public IQueryable<Tag> AvailableNames( int entityTypeId, int ownerId, Guid entityGuid, string entityQualifier, string entityQualifierValue ) { var service = new TagService(); return service.Get( entityTypeId, entityQualifier, entityQualifierValue, ownerId ) .Where( t => t.TaggedItems.Select( i => i.EntityGuid ).Contains( entityGuid ) == false ) .OrderBy( t => t.Name ); }
/// <summary> /// Handles the GridReorder event of the rGrid control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param> protected void rGrid_GridReorder( object sender, GridReorderEventArgs e ) { var tags = GetTags(); if ( tags != null ) { var rockContext = new RockContext(); var tagService = new TagService( rockContext ); tagService.Reorder( tags.ToList(), e.OldIndex, e.NewIndex ); rockContext.SaveChanges(); } BindGrid(); }
//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(); } } } } } }
/// <summary> /// Populates the tag list. /// </summary> private void PopulateTagList() { int entityTypePersonId = EntityTypeCache.GetId( typeof( Rock.Model.Person ) ) ?? 0; var tagQry = new TagService( new RockContext() ).Queryable( "OwnerPersonAlias" ).Where( a => a.EntityTypeId == entityTypePersonId ); RockPage rockPage = _rblTagType.Page as RockPage; if ( _rblTagType.SelectedValueAsInt() == 1 ) { // Personal tags - tags where the ownerid is the current person id tagQry = tagQry.Where( a => a.OwnerPersonAlias.PersonId == rockPage.CurrentPersonId ).OrderBy( a => a.Name ); } else { // Organizational tags - tags where the ownerid is null tagQry = tagQry.Where( a => a.OwnerPersonAlias == null ).OrderBy( a => a.Name ); } _ddlTagList.Items.Clear(); var tempTagList = tagQry.ToList(); foreach ( var tag in tagQry.Select( a => new { a.Guid, a.Name } ) ) { _ddlTagList.Items.Add( new ListItem( tag.Name, tag.Guid.ToString() ) ); } }
/// <summary> /// Formats the selection. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override string FormatSelection( Type entityType, string selection ) { string result = "Person Tag"; string[] selectionValues = selection.Split( '|' ); if ( selectionValues.Length >= 2 ) { Guid selectedTagGuid = selectionValues[1].AsGuid(); var selectedTag = new TagService( new RockContext() ).Get( selectedTagGuid ); if ( selectedTag != null ) { result = string.Format( "Tagged as {0}", selectedTag.Name ); } } return result; }
/// <summary> /// Shows the detail. /// </summary> /// <param name="tagId">The tag identifier.</param> /// <param name="entityTypeId">The entity type identifier.</param> public void ShowDetail( int tagId, int? entityTypeId ) { pnlDetails.Visible = false; Tag tag = null; if ( !tagId.Equals( 0 ) ) { tag = new TagService( new RockContext() ).Get( tagId ); } if ( tag == null ) { tag = new Tag { Id = 0, OwnerPersonAliasId = CurrentPersonAliasId, OwnerPersonAlias = CurrentPersonAlias }; if ( entityTypeId.HasValue ) { tag.EntityTypeId = entityTypeId.Value; } } pnlDetails.Visible = true; hfId.Value = tag.Id.ToString(); bool readOnly = false; if ( !_canConfigure && ( tag.OwnerPersonAlias == null || tag.OwnerPersonAlias.PersonId != CurrentPersonId ) ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Tag.FriendlyTypeName ); } if ( tag.IsSystem ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem( Group.FriendlyTypeName ); } if ( readOnly ) { btnEdit.Visible = false; btnDelete.Visible = false; ShowReadonlyDetails( tag ); } else { btnEdit.Visible = true; btnDelete.Visible = true; if ( tag.Id > 0 ) { ShowReadonlyDetails( tag ); } else { ShowEditDetails( tag ); } } }
/// <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(); } }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit( EventArgs e ) { base.OnInit( e ); gReport.DataKeyNames = new string[] { "Id" }; gReport.GridRebind += gReport_GridRebind; int tagId = int.MinValue; if ( int.TryParse( PageParameter( "tagId" ), out tagId ) && tagId > 0 ) { Tag _tag = new TagService( new RockContext() ).Get( tagId ); if ( _tag != null ) { TagId = tagId; TagEntityType = EntityTypeCache.Read( _tag.EntityTypeId ); if ( TagEntityType != null ) { Type modelType = TagEntityType.GetEntityType(); gReport.RowItemText = modelType.Name + " Tag"; lTaggedTitle.Text = "Tagged " + modelType.Name.Pluralize(); if ( modelType != null ) { // If displaying people, set the person id fiels so that merge and communication icons are displayed if ( TagEntityType.Name == "Rock.Model.Person" ) { gReport.PersonIdField = "Id"; } foreach ( var column in gReport.GetPreviewColumns( modelType ) ) { gReport.Columns.Add( column ); } // Add a CreatedDateTime if one does not exist var gridBoundColumns = gReport.Columns.OfType<BoundField>(); if ( gridBoundColumns.Any( c => c.DataField.Equals( "CreatedDateTime" ) ) == false ) { BoundField addedDateTime = new DateField(); addedDateTime.DataField = "CreatedDateTime"; addedDateTime.SortExpression = "CreatedDateTime"; addedDateTime.HeaderText = "Date Tagged"; gReport.Columns.Add( addedDateTime ); } // Add delete column var deleteField = new DeleteField(); gReport.Columns.Add( deleteField ); deleteField.Click += gReport_Delete; if ( !Page.IsPostBack ) { BindGrid(); } } } } } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="itemKey">The item key.</param> /// <param name="itemKeyValue">The group id.</param> public void ShowDetail( string itemKey, int itemKeyValue, int? entityTypeId ) { pnlDetails.Visible = false; if ( !itemKey.Equals( "tagId" ) ) { return; } Tag tag = null; if ( !itemKeyValue.Equals( 0 ) ) { tag = new TagService().Get( itemKeyValue ); } else { tag = new Tag { Id = 0, OwnerId = CurrentPersonId }; if ( entityTypeId.HasValue ) { tag.EntityTypeId = entityTypeId.Value; } } if ( tag == null ) { return; } pnlDetails.Visible = true; hfId.Value = tag.Id.ToString(); bool readOnly = false; if ( !_canConfigure && tag.OwnerId != CurrentPersonId ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Tag.FriendlyTypeName ); } if ( tag.IsSystem ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem( Group.FriendlyTypeName ); } if ( readOnly ) { btnEdit.Visible = false; btnDelete.Visible = false; ShowReadonlyDetails( tag ); } else { btnEdit.Visible = true; btnDelete.Visible = true; if ( tag.Id > 0 ) { ShowReadonlyDetails( tag ); } else { ShowEditDetails( tag ); } } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var tagService = new Rock.Model.TagService(rockContext); Tag tag = null; int tagId = int.Parse(hfId.Value); if (tagId != 0) { tag = tagService.Get(tagId); } if (tag == null) { tag = new Tag(); tag.IsSystem = false; tagService.Add(tag); } string name = tbName.Text; int? ownerId = ppOwner.PersonId; int? entityTypeId = ddlEntityType.SelectedValueAsId(); string qualifierCol = tbEntityTypeQualifierColumn.Text; string qualifierVal = tbEntityTypeQualifierValue.Text; // Verify tag with same name does not already exist if (tagService.Queryable() .Where(t => t.Id != tagId && t.Name == name && ( (t.OwnerPersonAlias == null && !ownerId.HasValue) || (t.OwnerPersonAlias != null && ownerId.HasValue && t.OwnerPersonAlias.PersonId == ownerId.Value) ) && (!t.EntityTypeId.HasValue || ( t.EntityTypeId.Value == entityTypeId && t.EntityTypeQualifierColumn == qualifierCol && t.EntityTypeQualifierValue == qualifierVal) )) .Any()) { nbEditError.Heading = "Tag Already Exists"; nbEditError.Text = string.Format("A '{0}' tag already exists for the selected scope, owner, and entity type.", name); nbEditError.Visible = true; } else { int?ownerPersonAliasId = null; if (ownerId.HasValue) { ownerPersonAliasId = new PersonAliasService(rockContext).GetPrimaryAliasId(ownerId.Value); } tag.Name = name; tag.Description = tbDescription.Text; tag.IsActive = cbIsActive.Checked; tag.IconCssClass = tbIconCssClass.Text; tag.BackgroundColor = cpBackground.Value; if (_canConfigure) { tag.CategoryId = cpCategory.SelectedValueAsInt(); tag.OwnerPersonAliasId = ownerPersonAliasId; tag.EntityTypeId = entityTypeId; tag.EntityTypeQualifierColumn = qualifierCol; tag.EntityTypeQualifierValue = qualifierVal; } avcAttributes.GetEditValues(tag); // only save if everything saves: rockContext.WrapTransaction(() => { rockContext.SaveChanges(); tag.SaveAttributeValues(); }); var qryParams = new Dictionary <string, string>(); qryParams["TagId"] = tag.Id.ToString(); NavigateToPage(RockPage.Guid, qryParams); } }
/// <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; }
/// <summary> /// Sets the selection. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="controls">The controls.</param> /// <param name="selection">The selection.</param> public override void SetSelection( Type entityType, Control[] controls, string selection ) { string[] selectionValues = selection.Split( '|' ); if ( selectionValues.Length >= 2 ) { int tagType = selectionValues[0].AsInteger(); Guid selectedTagGuid = selectionValues[1].AsGuid(); ( controls[0] as RadioButtonList ).SelectedValue = tagType.ToString(); rblTagType_SelectedIndexChanged( this, new EventArgs() ); RockDropDownList ddlTagList = controls[1] as RockDropDownList; if ( ddlTagList.Items.FindByValue( selectedTagGuid.ToString() ) != null ) { ddlTagList.SelectedValue = selectedTagGuid.ToString(); } else { // if the selectedTag is a personal tag, but for a different Owner than the current logged in person, include it in the list var selectedTag = new TagService( new RockContext() ).Get( selectedTagGuid ); if ( selectedTag != null ) { if ( selectedTag.OwnerPersonAliasId.HasValue ) { foreach ( var listItem in ddlTagList.Items.OfType<ListItem>() ) { listItem.Attributes["OptionGroup"] = "Personal"; } string tagText = string.Format( "{0} ( {1} )", selectedTag.Name, selectedTag.OwnerPersonAlias.Person ); ListItem currentTagListItem = new ListItem( tagText, selectedTagGuid.ToString() ); currentTagListItem.Attributes["OptionGroup"] = "Current"; ddlTagList.Items.Insert( 0, currentTagListItem ); } } } } }
/// <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; }
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 ); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit( EventArgs e ) { base.OnInit( e ); gReport.DataKeyNames = new string[] { "Id" }; gReport.GridRebind += gReport_GridRebind; int tagId = int.MinValue; if ( int.TryParse( PageParameter( "tagId" ), out tagId ) && tagId > 0 ) { Tag _tag = new TagService( new RockContext() ).Get( tagId ); if ( _tag != null ) { TagId = tagId; TagEntityType = EntityTypeCache.Read( _tag.EntityTypeId ); if ( TagEntityType != null ) { Type modelType = TagEntityType.GetEntityType(); gReport.RowItemText = modelType.Name + " Tag"; lTaggedTitle.Text = "Tagged " + modelType.Name.Pluralize(); if ( modelType != null ) { // If displaying people, set the person id fiels so that merge and communication icons are displayed if ( TagEntityType.Name == "Rock.Model.Person" ) { gReport.PersonIdField = "Id"; } foreach ( var column in gReport.GetPreviewColumns( modelType ) ) { gReport.Columns.Add( column ); } // Add delete column var deleteField = new DeleteField(); gReport.Columns.Add( deleteField ); deleteField.Click += gReport_Delete; BindGrid(); } } } } }
/// <summary> /// Handles the Delete event of the rGrid control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void rGrid_Delete( object sender, RowEventArgs e ) { var rockContext = new RockContext(); var tagService = new Rock.Model.TagService( rockContext ); var tag = tagService.Get( (int)rGrid.DataKeys[e.RowIndex]["id"] ); if ( tag != null ) { string errorMessage; if ( !tagService.CanDelete( tag, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } tagService.Delete( tag ); rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { Tag tag; using ( new Rock.Data.UnitOfWorkScope() ) { var tagService = new Rock.Model.TagService(); int tagId = int.Parse( hfId.Value ); if ( tagId == 0 ) { tag = new Tag(); tag.IsSystem = false; tagService.Add( tag, CurrentPersonId ); } else { tag = tagService.Get( tagId ); } tag.Name = tbName.Text; tag.OwnerId = ppOwner.PersonId; tag.EntityTypeId = ddlEntityType.SelectedValueAsId().Value; tag.EntityTypeQualifierColumn = tbEntityTypeQualifierColumn.Text; tag.EntityTypeQualifierValue = tbEntityTypeQualifierValue.Text; tagService.Save( tag, CurrentPersonId ); } var qryParams = new Dictionary<string, string>(); qryParams["tagId"] = tag.Id.ToString(); NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Gets the tags. /// </summary> /// <returns></returns> private IQueryable<Tag> GetTags() { int? entityTypeId = rFilter.GetUserPreference( "EntityType" ).AsInteger( false ); if ( entityTypeId.HasValue ) { var queryable = new Rock.Model.TagService( new RockContext() ).Queryable(). Where( t => t.EntityTypeId == entityTypeId.Value ); if ( rFilter.GetUserPreference( "Scope" ) == "Organization" ) { // Only allow sorting of public tags if authorized to Administer rGrid.Columns[0].Visible = _canConfigure; queryable = queryable.Where( t => !t.OwnerId.HasValue ); } else { int? personId = rFilter.GetUserPreference( "Owner" ).AsInteger( false ); if ( _canConfigure && personId.HasValue ) { queryable = queryable.Where( t => t.OwnerId == personId.Value ); } else { queryable = queryable.Where( t => t.OwnerId == CurrentPersonId ); } } return queryable.OrderBy( t => t.Order ); } return null; }
/// <summary> /// Handles the Click event of the btnDelete control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnDelete_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); var tagService = new Rock.Model.TagService( rockContext ); var tag = tagService.Get( int.Parse( hfId.Value ) ); if ( tag != null ) { string errorMessage; if ( !tagService.CanDelete( tag, out errorMessage ) ) { mdDeleteWarning.Show( errorMessage, ModalAlertType.Information ); return; } tagService.Delete( tag ); rockContext.SaveChanges(); NavigateToParentPage(); } }
/// <summary> /// Handles the Click event of the btnCancel control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnCancel_Click( object sender, EventArgs e ) { if ( hfId.Value.Equals( "0" ) ) { NavigateToParentPage(); } else { var tag = new TagService( new RockContext() ).Get( int.Parse( hfId.Value ) ); ShowReadonlyDetails( tag ); } }
/// <summary> /// Handles the Click event of the btnEdit control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnEdit_Click( object sender, EventArgs e ) { var tag = new TagService( new RockContext() ).Get( int.Parse( hfId.Value ) ); ShowEditDetails( tag ); }