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> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression( Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection ) { string[] selectionValues = selection.Split( '|' ); if ( selectionValues.Length >= 2 ) { Guid tagGuid = selectionValues[1].AsGuid(); var tagItemQry = new TaggedItemService( (RockContext)serviceInstance.Context ).Queryable() .Where( x => x.Tag.Guid == tagGuid ); var qry = new PersonService( (RockContext)serviceInstance.Context ).Queryable() .Where( p => tagItemQry.Any( x => x.EntityGuid == p.Guid ) ); return FilterExpressionExtractor.Extract<Rock.Model.Person>( qry, parameterExpression, "p" ); } return null; }
/// <summary> /// Handles the Delete event of the gReport control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void gReport_Delete( object sender, RowEventArgs e ) { int id = int.MinValue; if ( TagId.HasValue && int.TryParse( e.RowKeyValue.ToString(), out id ) ) { object obj = InvokeServiceMethod( "Get", new Type[] { typeof( int ) }, new object[] { id } ); if ( obj != null ) { Rock.Data.IEntity entity = obj as Rock.Data.IEntity; if ( entity != null ) { var rockContext = new RockContext(); var service = new TaggedItemService( rockContext ); var taggedItem = service.Get( TagId.Value, entity.Guid ); if ( taggedItem != null ) { string errorMessage; if ( !service.CanDelete( taggedItem, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } service.Delete( taggedItem ); rockContext.SaveChanges(); } } } } BindGrid(); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var guids = new TaggedItemService( new RockContext() ).Queryable().Where( t => t.TagId == TagId.Value ).Select( t => t.EntityGuid ).ToList(); gReport.DataSource = InvokeServiceMethod( "GetByGuids", new Type[] { typeof( List<Guid> ) }, new object[] { guids } ); gReport.DataBind(); }
protected void Page_Load( object sender, EventArgs e ) { string entityQualifierColumn = AttributeValue( "EntityQualifierColumn" ); if ( string.IsNullOrWhiteSpace( entityQualifierColumn ) ) entityQualifierColumn = PageParameter( "EntityQualifierColumn" ); string entityQualifierValue = AttributeValue( "EntityQualifierValue" ); if ( string.IsNullOrWhiteSpace( entityQualifierValue ) ) entityQualifierValue = PageParameter( "EntityQualifierValue" ); var sb = new StringBuilder(); // Get the context entity int? contextTypeId = null; Rock.Data.IEntity contextEntity = null; foreach ( KeyValuePair<string, Rock.Data.IEntity> entry in ContextEntities ) { contextTypeId = entry.Value.TypeId; contextEntity = entry.Value; // Should only be one. break; } if ( contextTypeId.HasValue && contextEntity != null ) { var service = new TaggedItemService(); foreach ( dynamic item in service.Get( contextTypeId.Value, entityQualifierColumn, entityQualifierValue, CurrentPersonId, contextEntity.Id ) .Select( i => new { OwnerId = i.Tag.OwnerId, Name = i.Tag.Name })) { if ( sb.Length > 0 ) sb.Append( ',' ); sb.Append( item.Name ); if ( CurrentPersonId.HasValue && item.OwnerId == CurrentPersonId.Value ) sb.Append( "^personal" ); } phTags.Controls.Add( new LiteralControl( string.Format( "<input name=\"person-tags\" id=\"person-tags\" value=\"{0}\" />", sb.ToString() ) ) ); string script = string.Format( @" $(document).ready(function () {{ $('ul.ui-autocomplete').css('width', '300px'); $('#person-tags').tagsInput({{ 'autocomplete_url': function( request, response ) {{ $.ajax({{ url: rock.baseUrl + 'api/tags/availablenames/{0}/{1}/{2}{3}{4}', dataType: 'json', success: function(data, status, xhr){{ response($.map(data, function (item) {{ return {{ value: item.Name, class: item.OwnerId == null || item.OwnerId == '' ? 'system' : 'personal' }} }})) }}, error: function(xhr, status, error) {{ alert(status + ' [' + error + ']: ' + xhr.reponseText); }} }}); }}, autoCompleteAppendTo: 'div.tag-wrap', 'height': 'auto', 'width': '100%', 'interactive': true, 'defaultText': 'add tag', 'removeWithBackspace': false, 'onAddTag': verifyTag, 'onRemoveTag': RemoveTag, 'enableDelete': true }}); }}); function verifyTag(tagName) {{ $.ajax({{ type: 'GET', url: rock.baseUrl + 'api/tags/{0}/{1}/' + tagName + '{3}{4}', statusCode: {{ 404: function () {{ var r = confirm(""A tag called '"" + tagName + ""' does not exist. Do you want to create a new personal tag?""); if (r == true) {{ AddTag(tagName); }} else {{ // remove tag $('#person-tags').removeTag(tagName); }} }}, 200: function (data, status, xhr) {{ AddTag(tagName); }} }}, }}); }} function AddTag(tagName) {{ $.ajax({{ type: 'POST', url: rock.baseUrl + 'api/taggeditems/{0}/{1}/{2}/' + tagName + '{3}{4}', error: function (xhr, status, error) {{ alert(status + ' [' + error + ']: ' + xhr.responseText); }} }}); }} function RemoveTag(tagName) {{ $.ajax({{ type: 'DELETE', url: rock.baseUrl + 'api/taggeditems/{0}/{1}/{2}/' + tagName + '{3}{4}', error: function (xhr, status, error) {{ alert(status + ' [' + error + ']: ' + xhr.responseText); }} }}); }} ", contextTypeId.Value, CurrentPersonId, contextEntity.Id, string.IsNullOrWhiteSpace( entityQualifierColumn ) ? "" : "/" + entityQualifierColumn, string.IsNullOrWhiteSpace( entityQualifierValue ) ? "" : "/" + entityQualifierValue ); this.Page.ClientScript.RegisterStartupScript( this.GetType(), "tags-" + this.CurrentBlock.Id.ToString(), script, true ); } }
/// <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; }
/// <summary> /// Handles the Click event of the lbMerge 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 lbMerge_Click( object sender, EventArgs e ) { if ( MergeData.People.Count < 2 ) { nbPeople.Visible = true; return; } bool reconfirmRequired = ( MergeData.People.Select( p => p.Email ).Distinct().Count() > 1 && MergeData.People.Where( p => p.HasLogins ).Any() ); GetValuesSelection(); int? primaryPersonId = null; var oldPhotos = new List<int>(); var rockContext = new RockContext(); rockContext.WrapTransaction( () => { var personService = new PersonService( rockContext ); var userLoginService = new UserLoginService( rockContext ); var groupService = new GroupService( rockContext ); var groupMemberService = new GroupMemberService( rockContext ); var binaryFileService = new BinaryFileService( rockContext ); var phoneNumberService = new PhoneNumberService( rockContext ); var taggedItemService = new TaggedItemService( rockContext ); Person primaryPerson = personService.Get( MergeData.PrimaryPersonId ?? 0 ); if ( primaryPerson != null ) { primaryPersonId = primaryPerson.Id; var changes = new List<string>(); foreach ( var p in MergeData.People.Where( p => p.Id != primaryPerson.Id ) ) { changes.Add( string.Format( "Merged <span class='field-value'>{0} [ID: {1}]</span> with this record.", p.FullName, p.Id ) ); } // Photo Id int? newPhotoId = MergeData.GetSelectedValue( MergeData.GetProperty( "Photo" ) ).Value.AsIntegerOrNull(); if ( !primaryPerson.PhotoId.Equals( newPhotoId ) ) { changes.Add( "Modified the photo." ); primaryPerson.PhotoId = newPhotoId; } primaryPerson.TitleValueId = GetNewIntValue( "Title", changes ); primaryPerson.FirstName = GetNewStringValue( "FirstName", changes ); primaryPerson.NickName = GetNewStringValue( "NickName", changes ); primaryPerson.MiddleName = GetNewStringValue( "MiddleName", changes ); primaryPerson.LastName = GetNewStringValue( "LastName", changes ); primaryPerson.SuffixValueId = GetNewIntValue( "Suffix", changes ); primaryPerson.RecordTypeValueId = GetNewIntValue( "RecordType", changes ); primaryPerson.RecordStatusValueId = GetNewIntValue( "RecordStatus", changes ); primaryPerson.RecordStatusReasonValueId = GetNewIntValue( "RecordStatusReason", changes ); primaryPerson.ConnectionStatusValueId = GetNewIntValue( "ConnectionStatus", changes ); primaryPerson.IsDeceased = GetNewBoolValue( "Deceased", changes ) ?? false; primaryPerson.Gender = (Gender)GetNewEnumValue( "Gender", typeof( Gender ), changes ); primaryPerson.MaritalStatusValueId = GetNewIntValue( "MaritalStatus", changes ); primaryPerson.SetBirthDate( GetNewDateTimeValue( "BirthDate", changes ) ); primaryPerson.AnniversaryDate = GetNewDateTimeValue( "AnniversaryDate", changes ); primaryPerson.GraduationYear = GetNewIntValue( "GraduationYear", changes ); primaryPerson.Email = GetNewStringValue( "Email", changes ); primaryPerson.IsEmailActive = GetNewBoolValue( "EmailActive", changes ) ?? true; primaryPerson.EmailNote = GetNewStringValue( "EmailNote", changes ); primaryPerson.EmailPreference = (EmailPreference)GetNewEnumValue( "EmailPreference", typeof( EmailPreference ), changes ); primaryPerson.SystemNote = GetNewStringValue( "InactiveReasonNote", changes ); primaryPerson.SystemNote = GetNewStringValue( "SystemNote", changes ); // Update phone numbers var phoneTypes = DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE.AsGuid() ).DefinedValues; foreach ( var phoneType in phoneTypes ) { var phoneNumber = primaryPerson.PhoneNumbers.Where( p => p.NumberTypeValueId == phoneType.Id ).FirstOrDefault(); string oldValue = phoneNumber != null ? phoneNumber.Number : string.Empty; string key = "phone_" + phoneType.Id.ToString(); string newValue = GetNewStringValue( key, changes ); bool phoneNumberDeleted = false; if ( !oldValue.Equals( newValue, StringComparison.OrdinalIgnoreCase ) ) { // New phone doesn't match old if ( !string.IsNullOrWhiteSpace( newValue ) ) { // New value exists if ( phoneNumber == null ) { // Old value didn't exist... create new phone record phoneNumber = new PhoneNumber { NumberTypeValueId = phoneType.Id }; primaryPerson.PhoneNumbers.Add( phoneNumber ); } // Update phone number phoneNumber.Number = newValue; } else { // New value doesn't exist if ( phoneNumber != null ) { // old value existed.. delete it primaryPerson.PhoneNumbers.Remove( phoneNumber ); phoneNumberService.Delete( phoneNumber ); phoneNumberDeleted = true; } } } // check to see if IsMessagingEnabled is true for any of the merged people for this number/numbertype if ( phoneNumber != null && !phoneNumberDeleted && !phoneNumber.IsMessagingEnabled ) { var personIds = MergeData.People.Select( a => a.Id ).ToList(); var isMessagingEnabled = phoneNumberService.Queryable().Where( a => personIds.Contains( a.PersonId ) && a.Number == phoneNumber.Number && a.NumberTypeValueId == phoneNumber.NumberTypeValueId ).Any( a => a.IsMessagingEnabled ); if ( isMessagingEnabled ) { phoneNumber.IsMessagingEnabled = true; } } } // Save the new record rockContext.SaveChanges(); // Update the attributes primaryPerson.LoadAttributes( rockContext ); foreach ( var property in MergeData.Properties.Where( p => p.Key.StartsWith( "attr_" ) ) ) { string attributeKey = property.Key.Substring( 5 ); string oldValue = primaryPerson.GetAttributeValue( attributeKey ) ?? string.Empty; string newValue = GetNewStringValue( property.Key, changes ) ?? string.Empty; if ( !oldValue.Equals( newValue ) ) { var attribute = primaryPerson.Attributes[attributeKey]; Rock.Attribute.Helper.SaveAttributeValue( primaryPerson, attribute, newValue, rockContext ); } } HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), primaryPerson.Id, changes ); // Delete the unselected photos string photoKeeper = primaryPerson.PhotoId.HasValue ? primaryPerson.PhotoId.Value.ToString() : string.Empty; foreach ( var photoValue in MergeData.Properties .Where( p => p.Key == "Photo" ) .SelectMany( p => p.Values ) .Where( v => v.Value != "" && v.Value != photoKeeper ) .Select( v => v.Value ) ) { int photoId = 0; if ( int.TryParse( photoValue, out photoId ) ) { var photo = binaryFileService.Get( photoId ); if ( photo != null ) { string errorMessages; if ( binaryFileService.CanDelete( photo, out errorMessages ) ) { binaryFileService.Delete( photo ); } } } } rockContext.SaveChanges(); // Delete merged person's family records and any families that would be empty after merge foreach ( var p in MergeData.People.Where( p => p.Id != primaryPersonId.Value ) ) { // Delete the merged person's phone numbers (we've already updated the primary persons values) foreach ( var phoneNumber in phoneNumberService.GetByPersonId( p.Id ) ) { phoneNumberService.Delete( phoneNumber ); } // If there was more than one email address and user has logins, then set any of the local // logins ( database & AD ) to require a reconfirmation if ( reconfirmRequired ) { foreach ( var login in userLoginService.GetByPersonId( p.Id ) ) { var component = Rock.Security.AuthenticationContainer.GetComponent( login.EntityType.Name ); if ( component != null && !component.RequiresRemoteAuthentication ) { login.IsConfirmed = false; } } } rockContext.SaveChanges(); // Delete the merged person's other family member records and the family if they were the only one in the family Guid familyGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid(); foreach ( var familyMember in groupMemberService.Queryable().Where( m => m.PersonId == p.Id && m.Group.GroupType.Guid == familyGuid ) ) { groupMemberService.Delete( familyMember ); rockContext.SaveChanges(); // Get the family var family = groupService.Queryable( "Members" ).Where( f => f.Id == familyMember.GroupId ).FirstOrDefault(); if ( !family.Members.Any() ) { // If there are not any other family members, delete the family record. // If theres any people that have this group as a giving group, set it to null (the person being merged should be the only one) foreach ( Person gp in personService.Queryable().Where( g => g.GivingGroupId == family.Id ) ) { gp.GivingGroupId = null; } // save to the database prior to doing groupService.Delete since .Delete quietly might not delete if thinks the Family is used for a GivingGroupId rockContext.SaveChanges(); // Delete the family string errorMessage; if ( groupService.CanDelete( family, out errorMessage ) ) { var oldFamilyChanges = new List<string>(); History.EvaluateChange( oldFamilyChanges, "Family", family.Name, string.Empty ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), primaryPersonId.Value, oldFamilyChanges, family.Name, typeof( Group ), family.Id ); groupService.Delete( family ); rockContext.SaveChanges(); } } } } // Flush any security roles that the merged person's other records were a part of foreach ( var p in MergeData.People.Where( p => p.Id != primaryPersonId.Value ) ) { foreach ( var groupMember in groupMemberService.Queryable().Where( m => m.PersonId == p.Id ) ) { Group group = new GroupService( rockContext ).Get( groupMember.GroupId ); if ( group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) ) { Rock.Security.Role.Flush( group.Id ); Rock.Security.Authorization.Flush(); } } } // now that the Merge is complete, the EntitySet can be marked to be deleted by the RockCleanup job var entitySetService = new EntitySetService( rockContext ); var entitySet = entitySetService.Get( MergeData.EntitySetId ); if ( entitySet != null ) { entitySet.ExpireDateTime = RockDateTime.Now.AddMinutes(-1); entitySet.EntitySetPurposeValueId = null; rockContext.SaveChanges(); } } } ); foreach ( var p in MergeData.People.Where( p => p.Id != primaryPersonId.Value ) ) { // Run merge proc to merge all associated data var parms = new Dictionary<string, object>(); parms.Add( "OldId", p.Id ); parms.Add( "NewId", primaryPersonId.Value ); DbService.ExecuteCommand( "spCrm_PersonMerge", CommandType.StoredProcedure, parms ); } NavigateToLinkedPage( "PersonDetailPage", "PersonId", primaryPersonId.Value ); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var guids = new TaggedItemService( new RockContext() ).Queryable().Where( t => t.TagId == TagId.Value ) .Select( t => new { t.EntityGuid, t.CreatedDateTime } ) .ToDictionary( o => o.EntityGuid, o => o.CreatedDateTime ); var enumerable = InvokeServiceMethod( "GetListByGuids", new Type[] { typeof( List<Guid> ) }, new object[] { guids.Keys.ToList() } ) as System.Collections.IEnumerable; // Since we don't really know what is in the "obj" that was returned, we check if it's // enumerable then reuse the CreatedDateTime property of the DataSource if it has one. // In the future, perhaps consider creating a merged data source so the CreatedDateTime // property/column doesn't have to be hijacked. if ( enumerable != null ) { if ( enumerable is IEnumerable<Person> ) { enumerable = ( enumerable as IEnumerable<Person> ).AsQueryable().Sort( gReport.SortProperty ?? new SortProperty { Property = "Id" } ).ToList(); gReport.AllowSorting = true; } else { gReport.AllowSorting = false; } foreach ( var entity in enumerable ) { var property = entity.GetType().GetProperty( "CreatedDateTime" ); var guid = entity.GetType().GetProperty( "Guid" ); // Now re-set the CreatedDateTime with the tag's CreatedDateTime (if that property is in the entity) if ( property != null && guid != null ) { var val = (Guid)guid.GetValue( entity, null ); property.SetValue( entity, guids[val], null ); } } } gReport.DataSource = enumerable; gReport.DataBind(); }
/// <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> /// Updates the control with the current tags that exist for the current entity /// </summary> /// <param name="currentPersonId">The current person identifier.</param> public void GetTagValues(int? currentPersonId) { var sb = new StringBuilder(); using ( var rockContext = new RockContext() ) { var service = new TaggedItemService( rockContext ); foreach ( dynamic item in service.Get( EntityTypeId, EntityQualifierColumn, EntityQualifierValue, currentPersonId, EntityGuid ) .Select( i => new { OwnerId = ( i.Tag.OwnerPersonAlias != null ? i.Tag.OwnerPersonAlias.PersonId : (int?)null ), Name = i.Tag.Name } ) ) { if ( sb.Length > 0 ) sb.Append( ',' ); sb.Append( item.Name ); if ( currentPersonId.HasValue && item.OwnerId == currentPersonId.Value ) sb.Append( "^personal" ); } } this.Text = sb.ToString(); }
//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 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 ); }
/// <summary> /// Handles the Delete event of the gReport control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void gReport_Delete( object sender, RowEventArgs e ) { Guid guid = Guid.Empty; if ( TagId.HasValue && Guid.TryParse( e.RowKeyValue.ToString(), out guid ) ) { var service = new TaggedItemService(); var taggedItem = service.Get( TagId.Value, guid ); if ( taggedItem != null ) { string errorMessage; if ( !service.CanDelete( taggedItem, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } service.Delete( taggedItem, CurrentPersonId ); service.Save( taggedItem, CurrentPersonId ); } } BindGrid(); }