/// <summary> /// Handles the Delete event of the gOccurrences 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 gOccurrences_Delete(object sender, RowEventArgs e) { var rockContext = new RockContext(); var occurenceService = new AttendanceOccurrenceService(rockContext); var attendanceService = new AttendanceService(rockContext); var occurrence = occurenceService.Get(e.RowKeyId); if (occurrence != null) { var locationId = occurrence.LocationId; string errorMessage; if (!occurenceService.CanDelete(occurrence, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Alert); return; } // Delete the attendees for this occurrence since it is not a cascading delete var attendees = attendanceService.Queryable().Where(a => a.OccurrenceId == occurrence.Id); rockContext.BulkDelete <Attendance>(attendees); occurenceService.Delete(occurrence); rockContext.SaveChanges(); if (locationId.HasValue) { Rock.CheckIn.KioskLocationAttendance.Remove(locationId.Value); } } BindGrid(); }
/// <summary> /// Handles the DeleteClick event of the gCampaigns 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 gCampaigns_DeleteClick(object sender, RowEventArgs e) { var campaignConnectionItem = CampaignConnectionHelper.GetCampaignConfiguration(e.RowKeyValue.ToString().AsGuid()); if (campaignConnectionItem != null && campaignConnectionItem.EntitySetId != default(int)) { var rockContext = new RockContext(); var entitySetService = new EntitySetService(rockContext); var entitySet = entitySetService.Get(campaignConnectionItem.EntitySetId); string errorMessage; if (!entitySetService.CanDelete(entitySet, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } var entitySetItemQry = new EntitySetItemService(rockContext) .Queryable().AsNoTracking() .Where(i => i.EntitySetId == entitySet.Id); rockContext.BulkDelete(entitySetItemQry); entitySetService.Delete(entitySet); rockContext.SaveChanges(); CampaignConnectionHelper.RemoveCampaignConfiguration(e.RowKeyValue.ToString().AsGuid()); BindGrid(); } }
/// <summary> /// Deletes any connection request workflows tied to this workflow. /// </summary> private void DeleteConnectionRequestWorkflows() { var connectionRequestWorkflowService = new ConnectionRequestWorkflowService(RockContext); var connectionRequestWorkflows = connectionRequestWorkflowService.Queryable().Where(c => c.WorkflowId == this.Entity.Id); if (connectionRequestWorkflows.Any()) { RockContext.BulkDelete(connectionRequestWorkflows); } }
/// <summary> /// creates or updates the entity set on the basis of campaign connection configuration, and returns the Id of the entitySetId /// </summary> /// <param name="campaignConfiguration">The campaign configuration.</param> /// <returns></returns> public static int GetEntitySet(CampaignItem campaignConfiguration) { var rockContext = new RockContext(); var connectionOpportunityService = new ConnectionOpportunityService(rockContext); var connectionRequestService = new ConnectionRequestService(rockContext); var entitySetService = new Rock.Model.EntitySetService(rockContext); var connectionOpportunity = connectionOpportunityService.Get(campaignConfiguration.OpportunityGuid); // list of person on the basis of Dataview result and optout group. var filteredPersonIds = GetFilteredPersonIds(campaignConfiguration, rockContext); // get the last connection datetime. var lastConnectionDateTime = RockDateTime.Now.AddDays(-campaignConfiguration.DaysBetweenConnection); // if DaysBetweenConnection is 0 then check for connection request for any time period. if (campaignConfiguration.DaysBetweenConnection == default(int)) { lastConnectionDateTime = DateTime.MinValue; } // list of person that has active connection request OR has connection closed in the past number of days between connection. var excludedPersonIds = connectionRequestService .Queryable() .Where(a => a.ConnectionOpportunityId == connectionOpportunity.Id && ( a.ConnectionState == ConnectionState.Active || a.ConnectionState == ConnectionState.FutureFollowUp || ((a.ConnectionState == ConnectionState.Connected || a.ConnectionState == ConnectionState.Inactive) && a.ModifiedDateTime > lastConnectionDateTime))) .Select(a => a.PersonAlias.PersonId) .ToList(); // filtered list of person removing all the personIds found in excludedPersonIds List filteredPersonIds = filteredPersonIds.Where(a => !excludedPersonIds.Contains(a)).ToList(); // get the ordered list of personIds based on the oldest previous connection request and connection opportunity /* 2020-05-06 MDP * If there are many filteredPersonIds, we'll get a SQL Exception, so let's get *all* the Connected connection Requests first, * and then use C# to filter. */ var orderedLastCompletedRequestForPerson = connectionRequestService .Queryable() .Where(a => a.ConnectionOpportunityId == connectionOpportunity.Id && a.ConnectionState == ConnectionState.Connected) .GroupBy(a => a.PersonAlias.PersonId) .Select(a => new { PersonId = a.Key, LastConnectionDateTime = a.OrderByDescending(b => b.ModifiedDateTime).Select(b => b.ModifiedDateTime).FirstOrDefault() }) .OrderBy(a => a.LastConnectionDateTime) .Select(a => a.PersonId).ToList(); // Use C# to filter persons so we can avoid a SQL Exception orderedLastCompletedRequestForPerson = orderedLastCompletedRequestForPerson.Where(a => filteredPersonIds.Contains(a)).ToList(); var random = new Random(); //// get the final ordered list of personIds based on the oldest previous connection request and //// connection opportunity otherwise order randomly for the person who don't have any previous connection request. var orderedPersonIds = filteredPersonIds .OrderBy(a => { var index = orderedLastCompletedRequestForPerson.IndexOf(a); if (index == -1) { return(random.Next(orderedLastCompletedRequestForPerson.Count, int.MaxValue)); } else { return(index); } }).ToList(); EntitySet entitySet = null; if (campaignConfiguration.EntitySetId != default(int)) { entitySet = entitySetService.Get(campaignConfiguration.EntitySetId); } List <Rock.Model.EntitySetItem> entitySetItems = new List <Rock.Model.EntitySetItem>(); var personEntityTypeId = EntityTypeCache.Get <Rock.Model.Person>().Id; if (entitySet == null || entitySet.EntityTypeId != personEntityTypeId) { entitySet = new Rock.Model.EntitySet(); entitySet.EntityTypeId = personEntityTypeId; entitySet.ExpireDateTime = null; entitySetService.Add(entitySet); } else { var entitySetItemQry = new EntitySetItemService(rockContext) .Queryable().AsNoTracking() .Where(i => i.EntitySetId == entitySet.Id); rockContext.BulkDelete(entitySetItemQry); } // Update the EntitySet name entitySet.Name = campaignConfiguration.Name; var orderIndex = 0; foreach (var personId in orderedPersonIds) { try { var item = new Rock.Model.EntitySetItem(); item.Order = orderIndex++; item.EntityId = personId; entitySetItems.Add(item); } catch { // ignore } } rockContext.SaveChanges(); entitySetItems.ForEach(a => { a.EntitySetId = entitySet.Id; }); rockContext.BulkInsert(entitySetItems); return(entitySet.Id); }
/// <summary> /// Refresh the recipients list. /// </summary> /// <param name="rockContext">The rock context.</param> /// <returns></returns> public void RefreshCommunicationRecipientList(RockContext rockContext) { if (!ListGroupId.HasValue) { return; } var segmentDataViewGuids = this.Segments.SplitDelimitedValues().AsGuidList(); var segmentDataViewIds = new DataViewService(rockContext).GetByGuids(segmentDataViewGuids).Select(a => a.Id).ToList(); var qryCommunicationListMembers = GetCommunicationListMembers(rockContext, ListGroupId, this.SegmentCriteria, segmentDataViewIds); // NOTE: If this is scheduled communication, don't include Members that were added after the scheduled FutureSendDateTime. // However, don't exclude if the date added can't be determined or they will never be sent a scheduled communication. if (this.FutureSendDateTime.HasValue) { var memberAddedCutoffDate = this.FutureSendDateTime; qryCommunicationListMembers = qryCommunicationListMembers.Where(a => (a.DateTimeAdded.HasValue && a.DateTimeAdded.Value < memberAddedCutoffDate) || (a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < memberAddedCutoffDate) || (!a.DateTimeAdded.HasValue && !a.CreatedDateTime.HasValue)); } var communicationRecipientService = new CommunicationRecipientService(rockContext); var recipientsQry = GetRecipientsQry(rockContext); // Get all the List member which is not part of communication recipients yet var newMemberInList = qryCommunicationListMembers .Include(c => c.Person) .Where(a => !recipientsQry.Any(r => r.PersonAlias.PersonId == a.PersonId)) .AsNoTracking() .ToList(); var emailMediumEntityType = EntityTypeCache.Get(SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL.AsGuid()); var smsMediumEntityType = EntityTypeCache.Get(SystemGuid.EntityType.COMMUNICATION_MEDIUM_SMS.AsGuid()); var pushMediumEntityType = EntityTypeCache.Get(SystemGuid.EntityType.COMMUNICATION_MEDIUM_PUSH_NOTIFICATION.AsGuid()); var recipientsToAdd = newMemberInList.Select(m => new CommunicationRecipient { PersonAliasId = m.Person.PrimaryAliasId.Value, Status = CommunicationRecipientStatus.Pending, CommunicationId = Id, MediumEntityTypeId = DetermineMediumEntityTypeId( emailMediumEntityType.Id, smsMediumEntityType.Id, pushMediumEntityType.Id, CommunicationType, m.CommunicationPreference, m.Person.CommunicationPreference) }); rockContext.BulkInsert <CommunicationRecipient>(recipientsToAdd); // Get all pending communication recipients that are no longer part of the group list member, then delete them from the Recipients var missingMemberInList = recipientsQry.Where(a => a.Status == CommunicationRecipientStatus.Pending) .Where(a => !qryCommunicationListMembers.Any(r => r.PersonId == a.PersonAlias.PersonId)); rockContext.BulkDelete <CommunicationRecipient>(missingMemberInList); rockContext.SaveChanges(); }
/// <summary> /// Migrates the scheduled transaction notes to history. /// </summary> public void MigrateScheduledTransactionNotesToHistory() { var rockContext = new RockContext(); rockContext.Database.CommandTimeout = _commandTimeout; var noteService = new NoteService(rockContext); var historyCategoryId = CategoryCache.Get(Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid())?.Id; var entityTypeIdScheduledTransaction = EntityTypeCache.GetId(Rock.SystemGuid.EntityType.FINANCIAL_SCHEDULED_TRANSACTION.AsGuid()); var noteTypeIdScheduledTransaction = NoteTypeCache.GetId(Rock.SystemGuid.NoteType.SCHEDULED_TRANSACTION_NOTE.AsGuid()); if (!historyCategoryId.HasValue || !entityTypeIdScheduledTransaction.HasValue || !noteTypeIdScheduledTransaction.HasValue) { return; } var historyService = new HistoryService(rockContext); var historyQuery = historyService.Queryable().Where(a => a.EntityTypeId == entityTypeIdScheduledTransaction.Value); var captionsToConvert = new string[] { "Created Transaction" , "Updated Transaction" , "Cancelled Transaction" , "Reactivated Transaction" }; var notesToConvertToHistory = noteService.Queryable() .Where(a => a.NoteTypeId == noteTypeIdScheduledTransaction.Value && captionsToConvert.Contains(a.Caption) && a.EntityId.HasValue) .Where(a => !historyQuery.Any(h => h.EntityId == a.EntityId)); var notesToConvertToSummaryList = noteService.Queryable() .Where(a => a.NoteTypeId == noteTypeIdScheduledTransaction.Value && a.Caption == "Created Transaction" && !string.IsNullOrEmpty(a.Text) && a.EntityId.HasValue) .AsNoTracking().ToList(); List <History> historyRecordsToInsert = notesToConvertToHistory.AsNoTracking() .ToList() .Select(n => { var historyRecord = new History { CategoryId = historyCategoryId.Value, EntityTypeId = entityTypeIdScheduledTransaction.Value, EntityId = n.EntityId.Value, Guid = Guid.NewGuid(), CreatedByPersonAliasId = n.CreatedByPersonAliasId, ModifiedByPersonAliasId = n.ModifiedByPersonAliasId, CreatedDateTime = n.CreatedDateTime, ModifiedDateTime = n.ModifiedDateTime }; if (n.Caption == "Cancelled Transaction") { historyRecord.Verb = "MODIFY"; historyRecord.ChangeType = "Property"; historyRecord.ValueName = "Is Active"; historyRecord.NewValue = "False"; } else if (n.Caption == "Reactivated Transaction") { historyRecord.Verb = "MODIFY"; historyRecord.ChangeType = "Property"; historyRecord.ValueName = "Is Active"; historyRecord.NewValue = "True"; } else if (n.Caption == "Updated Transaction") { historyRecord.Verb = "MODIFY"; historyRecord.ValueName = "Transaction"; } else { historyRecord.Verb = "ADD"; historyRecord.ChangeType = "Record"; historyRecord.ValueName = "Transaction"; } return(historyRecord); }).ToList(); rockContext.BulkInsert(historyRecordsToInsert); var qryNotesToDelete = noteService.Queryable().Where(a => a.NoteTypeId == noteTypeIdScheduledTransaction && captionsToConvert.Contains(a.Caption)); rockContext.BulkDelete(qryNotesToDelete); foreach (var noteToConvertToSummary in notesToConvertToSummaryList) { using (var updatedSummaryContext = new RockContext()) { var scheduledTransactionService = new FinancialScheduledTransactionService(updatedSummaryContext); var scheduledTransaction = scheduledTransactionService.Get(noteToConvertToSummary.EntityId.Value); if (scheduledTransaction != null && scheduledTransaction.Summary.IsNullOrWhiteSpace()) { scheduledTransaction.Summary = noteToConvertToSummary.Text; updatedSummaryContext.SaveChanges(disablePrePostProcessing: true); } } } }
/// <summary> /// Saves the <see cref="MetricValue"/>s and updates the <see cref="IJobExecutionContext"/>'s Result property. /// </summary> /// <param name="context">The <see cref="IJobExecutionContext"/>.</param> /// <exception cref="Exception">Unable to find the "Hosting Metrics" Category ID.</exception> private void SaveMetricValues(IJobExecutionContext context) { var rockContext = new RockContext(); rockContext.Database.CommandTimeout = _commandTimeout; var hostingMetricsCategoryId = CategoryCache.GetId(SystemGuid.Category.METRIC_HOSTING_METRICS.AsGuid()); if (!hostingMetricsCategoryId.HasValue) { throw new Exception(@"Unable to find the ""Hosting Metrics"" Category ID."); } var metricIdsQuery = new MetricCategoryService(rockContext).Queryable() .Where(mc => mc.CategoryId == hostingMetricsCategoryId) .Select(mc => mc.MetricId); // Get all of the Metrics tied to the "Hosting Metrics" Category var metrics = new MetricService(rockContext).Queryable("MetricPartitions") .Where(m => metricIdsQuery.Contains(m.Id)) .ToList(); var metricValues = new List <MetricValue>(); foreach (var metric in metrics) { // Attempt to add any PerformanceCounter MetricValues TryAddPerformanceCounterMetricValue(metric, metricValues); } /* * 2020-04-22 - JPH * * The Metrics being collected by the first revision of this Job each have a single, default MetricPartition. * If we add Metrics to this Job in the future that are more complicated, we'll want to revisit the below logic. * */ var metricValueService = new MetricValueService(rockContext); var metricValuePartitionService = new MetricValuePartitionService(rockContext); foreach (var metricValue in metricValues) { foreach (var metricPartition in metricValue.Metric.MetricPartitions) { metricValue.MetricValuePartitions.Add(new MetricValuePartition { MetricPartitionId = metricPartition.Id }); } metricValueService.Add(metricValue); } rockContext.SaveChanges(); /* * 2020-05-19 - SK * Removing the old metrics based on Maximum Metric to Retain value * */ if (_maximumMetricsToRetain.HasValue) { foreach (var metric in metrics) { var deleteMetricValuesQry = metricValueService .Queryable() .AsNoTracking() .Where(a => a.MetricId == metric.Id) .OrderByDescending(a => a.MetricValueDateTime) .Skip(_maximumMetricsToRetain.Value); if (deleteMetricValuesQry.Any()) { var metricValuePartitionQry = metricValuePartitionService.Queryable().AsNoTracking().Where(a => deleteMetricValuesQry.Any(u => u.Id == a.MetricValueId)); rockContext.BulkDelete(metricValuePartitionQry); rockContext.BulkDelete(deleteMetricValuesQry); } } } context.Result = $"Calculated a total of {metricValues.Count} metric values for {metrics.Count} metrics"; }