public IProcessInstance StartProcessInstance(long processDefinitionId, IDictionary attributeValues = null, string transitionName = null, Relations relations = null) { ProcessInstanceImpl processInstance = null; IOrganisationService organisationService = null; using (ISession session = NHibernateHelper.OpenSession()) { using (var tran = session.BeginTransaction()) { DbSession dbSession = new DbSession(session); ProcessDefinitionImpl processDefinition = myProcessDefinitionService.GetProcessDefinition(processDefinitionId, dbSession); processInstance = new ProcessInstanceImpl(ActorId, processDefinition); processInstanceRepository.Save(processInstance, dbSession);//到這裏應該存了ProcessInstance,RootFlow ExecutionContext executionContext = new ExecutionContext(); //logRepository.CreateLog(); processDefinition.StartState.CheckAccess(attributeValues); attributeService = new AttributeService((FlowImpl)processInstance.RootFlow, dbSession); attributeService.StoreAttributeValue(attributeValues);//儲存傳入的欄位值 attributeService.StoreRole(organisationService.FindActorById(ActorId), (ActivityStateImpl)processDefinition.StartState); //flow的node推進到下一關卡 //flow的actor=解析出來的actor.Id transitionService = new TransitionService(ActorId, dbSession); TransitionImpl transitionTo = transitionService.GetTransition(transitionName, processDefinition.StartState, dbSession); transitionService.ProcessTransition(transitionTo, (FlowImpl)processInstance.RootFlow, dbSession); session.Flush(); tran.Commit(); } } return processInstance; }
/// <summary> /// Maps the authorizations to an attribute. /// </summary> /// <param name="tableData">The table data.</param> private void MapAuthorizations(IQueryable <Row> tableData) { var lookupContext = new RockContext(); var rockContext = new RockContext(); var categoryService = new CategoryService(lookupContext); var personService = new PersonService(lookupContext); var noteList = new List <Note>(); int completed = 0; int totalRows = tableData.Count(); int percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying Authorization import ({0:N0} found).", totalRows)); var attributeList = new AttributeService(lookupContext).Queryable().ToList(); int authorizationAttributeId = 0; if (attributeList.Find(a => a.Key == "PickupAuthorization") != null) { authorizationAttributeId = attributeList.Find(a => a.Key == "PickupAuthorization").Id; } var authorizationAttributeValueList = new List <AttributeValue>(); authorizationAttributeValueList = new AttributeValueService(rockContext).Queryable().Where(av => av.AttributeId == authorizationAttributeId).ToList(); int f1HouseholdIdAttributeId = attributeList.Find(a => a.Key == "F1HouseholdId").Id; //places all household attributes in a dictionary where the key is the personId and the houshold is the value. var householdDictionary = new AttributeValueService(lookupContext).Queryable() .Where(av => av.AttributeId == f1HouseholdIdAttributeId) .Select(av => new { PersonId = av.EntityId, HouseholdId = av.Value }) .ToDictionary(t => t.PersonId, t => t.HouseholdId); foreach (var row in tableData) { //var rockContext = new RockContext(); var categoryList = new CategoryService(rockContext).Queryable().ToList(); //check if category exists //If it doesn't (though it should), it will create a new category called Authorization if (categoryList.Find(c => c.Name == "Childhood Information") == null) { var entityType = new EntityTypeService(rockContext); //creates if category doesn't exist var newCategory = new Category(); newCategory.IsSystem = false; newCategory.EntityTypeId = entityType.Queryable().Where(e => e.Name == "Rock.Model.Attribute").Select(e => e.Id).FirstOrDefault(); newCategory.EntityTypeQualifierColumn = "EntityTypeId"; newCategory.EntityTypeQualifierValue = Convert.ToString(PersonEntityTypeId); newCategory.Name = "Authorization"; newCategory.Description = "Contains the pickup authorization"; //var newCategoryContext = new RockContext(); //newCategoryContext.WrapTransaction( () => //{ // newCategoryContext.Configuration.AutoDetectChangesEnabled = false; // newCategoryContext.Categories.Add( newCategory ); // newCategoryContext.SaveChanges( DisableAudit ); //} ); rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Categories.Add(newCategory); rockContext.SaveChanges(DisableAudit); }); } attributeList = new AttributeService(lookupContext).Queryable().ToList(); //Check if Attribute exists //If it doesn't it creates the attribute if (attributeList.Find(a => a.Key == "PickupAuthorization") == null) { var fieldType = new FieldTypeService(rockContext); //var newAttributeList = new List<Rock.Model.Attribute>(); var fieldTypeId = fieldType.Queryable().Where(e => e.Name == "Memo").FirstOrDefault().Id; var category2 = new CategoryService(rockContext).Queryable().Where(gt => gt.Name == "Childhood Information").FirstOrDefault(); var category3 = new CategoryService(rockContext).Queryable().Where(gt => gt.Name == "Authorization").FirstOrDefault(); //Creates if attribute doesn't exist //The attribute is a memo attribute var newAttribute = new Rock.Model.Attribute(); newAttribute.Key = "PickupAuthorization"; newAttribute.Name = "Pickup Authorization"; newAttribute.FieldTypeId = fieldTypeId; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.Description = "Lists who is authorized to pickup this child along with their current phone number."; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; if (categoryList.Find(c => c.Name == "Childhood Information") != null) { newAttribute.Categories = new List <Category>(); newAttribute.Categories.Add(category2); } //If authorization category was create, this is where the attribute is set to that category. else { newAttribute.Categories = new List <Category>(); newAttribute.Categories.Add(category3); //Sets to Authorization Attribute Category. } //saves the attribute rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Attributes.Add(newAttribute); rockContext.SaveChanges(DisableAudit); }); } //Adding to the person's attributes int? householdId = row["HouseholdID"] as int?; string personName = row["PersonName"] as string; DateTime?authorizationDate = row["AuthorizationDate"] as DateTime?; attributeList = new AttributeService(rockContext).Queryable().ToList(); //Gets the Attribute Id for Pickup Authorization. authorizationAttributeId = attributeList.Find(a => a.Key == "PickupAuthorization").Id; //since F1 authorization applies to the household id and not individual I have to apply it to all members in that household. //Value in F1 is a text entry and not a person select. Discuss with staff that we need to break away from this and start using known relationships for authorization foreach (var household in householdDictionary.Where(h => h.Value == Convert.ToString(householdId))) { //checks if a record already exists in the list if (authorizationAttributeValueList.Find(a => a.AttributeId == authorizationAttributeId && a.EntityId == household.Key) == null) { var person = new PersonService(rockContext).Queryable().Where(p => p.Id == household.Key).FirstOrDefault(); //trying to keep from adding this attribute to adult records if (person != null && (person.Age <= 18 || person.Age == null)) { //creates new attribute record if it does not exist. var newAuthorizationAttribute = new AttributeValue(); newAuthorizationAttribute.IsSystem = false; newAuthorizationAttribute.AttributeId = authorizationAttributeId; newAuthorizationAttribute.EntityId = household.Key; //the key is the person ID newAuthorizationAttribute.Value = personName + ", "; //text field newAuthorizationAttribute.CreatedDateTime = authorizationDate; //adds the new record to the list authorizationAttributeValueList.Add(newAuthorizationAttribute); } } //if a record already exists else { //adds to the current value. authorizationAttributeValueList.Find(a => a.AttributeId == authorizationAttributeId && a.EntityId == household.Key).Value = personName + ", "; } } completed++; if (completed % percentage < 1) { int percentComplete = completed / percentage; ReportProgress(percentComplete, string.Format("{0:N0} authorizations imported ({1}% complete).", completed, percentComplete)); } else if (completed % ReportingNumber < 1) { //rockContext.WrapTransaction( () => // { // rockContext.Configuration.AutoDetectChangesEnabled = false; // rockContext.AttributeValues.AddRange( authorizationAttributeValueList ); // rockContext.SaveChanges( DisableAudit ); //I get can't insert duplicate entry error // } ); ReportPartialProgress(); } } if (authorizationAttributeValueList.Any()) { //var rockContext = new RockContext(); rockContext.WrapTransaction(() => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.AttributeValues.AddRange(authorizationAttributeValueList); rockContext.SaveChanges(DisableAudit); }); } ReportProgress(100, string.Format("Finished authorization import: {0:N0} notes imported.", completed)); }
/// <summary> /// Shows the edit. /// </summary> /// <param name="binaryFileTypeId">The binary file type identifier.</param> public void ShowDetail(int binaryFileTypeId) { pnlDetails.Visible = true; BinaryFileType binaryFileType = null; var rockContext = new RockContext(); if (!binaryFileTypeId.Equals(0)) { binaryFileType = new BinaryFileTypeService(rockContext).Get(binaryFileTypeId); lActionTitle.Text = ActionTitle.Edit(BinaryFileType.FriendlyTypeName).FormatAsHtmlTitle(); } if (binaryFileType == null) { binaryFileType = new BinaryFileType { Id = 0 }; lActionTitle.Text = ActionTitle.Add(BinaryFileType.FriendlyTypeName).FormatAsHtmlTitle(); } BinaryFileAttributesState = new ViewStateList <Attribute>(); hfBinaryFileTypeId.Value = binaryFileType.Id.ToString(); tbName.Text = binaryFileType.Name; tbDescription.Text = binaryFileType.Description; tbIconCssClass.Text = binaryFileType.IconCssClass; cbAllowCaching.Checked = binaryFileType.AllowCaching; cbRequiresViewSecurity.Checked = binaryFileType.RequiresViewSecurity; nbMaxWidth.Text = binaryFileType.MaxWidth.ToString(); nbMaxHeight.Text = binaryFileType.MaxHeight.ToString(); ddlPreferredFormat.BindToEnum <PreferredFormat>(); ddlPreferredFormat.SetValue((int)binaryFileType.PreferredFormat); ddlPreferredResolution.BindToEnum <PreferredResolution>(); ddlPreferredResolution.SetValue((int)binaryFileType.PreferredResolution); ddlPreferredColorDepth.BindToEnum <PreferredColorDepth>(); ddlPreferredColorDepth.SetValue((int)binaryFileType.PreferredColorDepth); cbPreferredRequired.Checked = binaryFileType.PreferredRequired; if (binaryFileType.StorageEntityType != null) { cpStorageType.SelectedValue = binaryFileType.StorageEntityType.Guid.ToString().ToUpper(); } AttributeService attributeService = new AttributeService(rockContext); string qualifierValue = binaryFileType.Id.ToString(); var qryBinaryFileAttributes = attributeService.GetByEntityTypeId(new BinaryFile().TypeId).AsQueryable() .Where(a => a.EntityTypeQualifierColumn.Equals("BinaryFileTypeId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(qualifierValue)); BinaryFileAttributesState.AddAll(qryBinaryFileAttributes.ToList()); BindBinaryFileAttributesGrid(); // render UI based on Authorized and IsSystem bool readOnly = false; bool restrictedEdit = false; nbEditModeMessage.Text = string.Empty; if (!IsUserAuthorized(Authorization.EDIT)) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(BinaryFileType.FriendlyTypeName); } if (binaryFileType.IsSystem) { restrictedEdit = true; nbEditModeMessage.Text = EditModeMessage.System(BinaryFileType.FriendlyTypeName); } phAttributes.Controls.Clear(); binaryFileType.LoadAttributes(); if (readOnly) { lActionTitle.Text = ActionTitle.View(BinaryFileType.FriendlyTypeName).FormatAsHtmlTitle(); btnCancel.Text = "Close"; } if (readOnly) { Rock.Attribute.Helper.AddDisplayControls(binaryFileType, phAttributes); } else { Rock.Attribute.Helper.AddEditControls(binaryFileType, phAttributes, true); } // the only thing we'll restrict for restrictedEdit is the Name (plus they won't be able to remove Attributes that are marked as IsSystem tbName.ReadOnly = readOnly || restrictedEdit; gBinaryFileAttributes.Enabled = !readOnly; gBinaryFileAttributes.Columns.OfType <EditField>().First().Visible = !readOnly; gBinaryFileAttributes.Actions.ShowAdd = !readOnly; // allow these to be edited in restricted edit mode if not readonly tbDescription.ReadOnly = readOnly; tbIconCssClass.ReadOnly = readOnly; cbAllowCaching.Enabled = !readOnly; cbRequiresViewSecurity.Enabled = !readOnly; cpStorageType.Enabled = !readOnly; nbMaxWidth.ReadOnly = readOnly; nbMaxHeight.ReadOnly = readOnly; ddlPreferredFormat.Enabled = !readOnly; ddlPreferredResolution.Enabled = !readOnly; ddlPreferredColorDepth.Enabled = !readOnly; cbPreferredRequired.Enabled = !readOnly; btnSave.Visible = !readOnly; }
/// <summary> /// Handles the Click event of the btnConfirm 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 btnConfirm_Click(object sender, EventArgs e) { // send signalR message to start progress indicator int progress = 0; _hubContext.Clients.All.receiveNotification(signalREventName, "0"); XDocument xml = null; int? total = null; int? batchId = null; string batchName = string.Empty; int?attributeId = null; int?binaryFileTypeId = null; using (var rockContext = new RockContext()) { // Get the XML var binaryFile = new BinaryFileService(rockContext).Get(_binaryFileId.Value); if (binaryFile != null) { using (var stream = binaryFile.ContentStream) { xml = XDocument.Load(stream); } } // Get the number of transactions if (xml != null) { total = xml.Root.Descendants().Where(n => n.Name == "Gift").Count(); } if (xml != null && total.HasValue && total.Value > 0) { var batchService = new FinancialBatchService(rockContext); FinancialBatch batch = null; // Load (or create) the batch batchId = ddlBatch.SelectedValueAsInt(); if (batchId.HasValue) { batch = batchService.Get(batchId.Value); } if (batch == null) { batch = new FinancialBatch(); batch.Guid = Guid.NewGuid(); batch.Name = Path.GetFileNameWithoutExtension(binaryFile.FileName); batch.Status = BatchStatus.Open; batch.BatchStartDateTime = RockDateTime.Today; batch.BatchEndDateTime = batch.BatchStartDateTime.Value.AddDays(1); batch.ControlAmount = 0; batchService.Add(batch); rockContext.SaveChanges(); batchId = batch.Id; } batchName = batch.Name; // Get the attribute id for the envelop number attribute int?personEntityTypeId = EntityTypeCache.GetId <Rock.Model.Person>(); attributeId = new AttributeService(rockContext) .Queryable().AsNoTracking() .Where(a => a.EntityTypeId == personEntityTypeId && a.Key == "GivingEnvelopeNumber") .Select(a => a.Id) .FirstOrDefault(); // Get the binary file type for contribution images var binaryFileType = new BinaryFileTypeService(rockContext).Get(Rock.SystemGuid.BinaryFiletype.CONTRIBUTION_IMAGE.AsGuid()); if (binaryFileType != null) { binaryFileTypeId = binaryFileType.Id; } } } // Initialize the status variables int matchCount = 0; int unmatchCount = 0; int errorCount = 0; var allErrorMessages = new List <string>(); // Process each transaction foreach (var node in xml.Root.Descendants().Where(n => n.Name == "Gift")) { var errorMessages = new List <string>(); var status = ProcessTransaction(node, batchId, attributeId, binaryFileTypeId, out errorMessages); switch (status) { case ProcessStatus.Matched: matchCount++; break; case ProcessStatus.Unmatched: unmatchCount++; break; case ProcessStatus.Error: errorCount++; break; } allErrorMessages.AddRange(errorMessages); // Update progress using signalR progress++; int percentage = (progress * 100) / total.Value; _hubContext.Clients.All.receiveNotification(signalREventName, percentage.ToString("N0")); } // update success message to indicate the txns that were updated StringBuilder sb = new StringBuilder(); sb.AppendFormat("<li>{0:N0} {1} processed.</li>", total.Value, "transaction".PluralizeIf(total.Value > 1)); sb.AppendFormat("<li>{0:N0} {1} matched to an existing person.</li>", matchCount, (matchCount == 1 ? "transaction was" : "transactions were")); sb.AppendFormat("<li>{0:N0} {1} NOT matched to an existing person.</li>", unmatchCount, (unmatchCount == 1 ? "transaction was" : "transactions were")); if (errorCount > 0) { sb.AppendFormat("<li>{0:N0} {1} NOT imported due to error during import (see errors below).</li>", errorCount, (errorCount == 1 ? "transaction was" : "transactions were")); } using (var rockContext = new RockContext()) { var batch = new FinancialBatchService(rockContext).Get(batchId.Value); if (batch != null) { // update batch control amount batch.ControlAmount += _totalAmount; rockContext.SaveChanges(); // Add link to batch var qryParam = new Dictionary <string, string>(); qryParam.Add("batchId", batchId.ToString()); string batchUrl = LinkedPageUrl("BatchDetailPage", qryParam); string batchLink = string.Format("<a href='{0}'>{1}</a>", batchUrl, batch.Name); int totalTransactions = matchCount + unmatchCount; string summaryformat = totalTransactions == 1 ? "<li>{0} transaction of {1} was added to the {2} batch.</li>" : "<li>{0} transactions totaling {1} were added to the {2} batch</li>"; sb.AppendFormat(summaryformat, totalTransactions.ToString("N0"), _totalAmount.FormatAsCurrency(), batchLink); } } nbSuccess.Text = string.Format("<ul>{0}</ul>", sb.ToString()); // Display any errors that occurred if (allErrorMessages.Any()) { StringBuilder sbErrors = new StringBuilder(); foreach (var errorMsg in allErrorMessages) { sbErrors.AppendFormat("<li>{0}</li>", errorMsg); } nbErrors.Text = string.Format("<ul>{0}</ul>", sbErrors.ToString()); nbErrors.Visible = true; } else { nbErrors.Visible = false; } ShowResults(); }
/// <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) { WorkflowTrigger workflowTrigger; var rockContext = new RockContext(); WorkflowTriggerService WorkflowTriggerService = new WorkflowTriggerService(rockContext); AttributeService attributeService = new AttributeService(rockContext); int WorkflowTriggerId = int.Parse(hfWorkflowTriggerId.Value); if (WorkflowTriggerId == 0) { workflowTrigger = new WorkflowTrigger(); WorkflowTriggerService.Add(workflowTrigger); } else { workflowTrigger = WorkflowTriggerService.Get(WorkflowTriggerId); } workflowTrigger.WorkflowTypeId = ddlWorkflowType.SelectedValueAsInt().Value; workflowTrigger.WorkflowTriggerType = (WorkflowTriggerType)System.Enum.Parse(typeof(WorkflowTriggerType), rblTriggerType.SelectedValue); workflowTrigger.EntityTypeId = ddlEntityType.SelectedValueAsInt().Value; workflowTrigger.EntityTypeQualifierColumn = ddlQualifierColumn.SelectedValue; // If the trigger type is PreSave and the tbQualifierValue does not exist, // use the previous and alt qualifier value if (workflowTrigger.WorkflowTriggerType == WorkflowTriggerType.PreSave) { if (!string.IsNullOrEmpty(tbQualifierValue.Text)) { // in this case, use the same value as the previous and current qualifier value workflowTrigger.EntityTypeQualifierValue = tbQualifierValue.Text; workflowTrigger.EntityTypeQualifierValuePrevious = tbQualifierValue.Text; } else { workflowTrigger.EntityTypeQualifierValue = tbQualifierValueAlt.Text; workflowTrigger.EntityTypeQualifierValuePrevious = tbPreviousQualifierValue.Text; } } else { // use the regular qualifier and clear the previous value qualifier since it does not apply. workflowTrigger.EntityTypeQualifierValue = tbQualifierValue.Text; workflowTrigger.EntityTypeQualifierValuePrevious = string.Empty; } workflowTrigger.IsActive = cbIsActive.Checked; if (string.IsNullOrWhiteSpace(tbWorkflowName.Text)) { workflowTrigger.WorkflowName = null; } else { workflowTrigger.WorkflowName = tbWorkflowName.Text; } if (!workflowTrigger.IsValid) { // Controls will render the error messages return; } rockContext.SaveChanges(); Rock.Workflow.TriggerCache.Refresh(); NavigateToParentPage(); }
/// <summary> /// Adds or Updates a <see cref="Rock.Model.Attribute" /> item for the attribute. /// </summary> /// <param name="property">The property.</param> /// <param name="entityTypeId">The entity type id.</param> /// <param name="entityQualifierColumn">The entity qualifier column.</param> /// <param name="entityQualifierValue">The entity qualifier value.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> /// <remarks> /// If a rockContext value is included, this method will save any previous changes made to the context /// </remarks> private static bool UpdateAttribute(FieldAttribute property, int?entityTypeId, string entityQualifierColumn, string entityQualifierValue, RockContext rockContext = null) { bool updated = false; rockContext = rockContext ?? new RockContext(); var attributeService = new AttributeService(rockContext); var attributeQualifierService = new AttributeQualifierService(rockContext); var fieldTypeService = new FieldTypeService(rockContext); var categoryService = new CategoryService(rockContext); var propertyCategories = property.Category.SplitDelimitedValues(false).ToList(); // Look for an existing attribute record based on the entity, entityQualifierColumn and entityQualifierValue Model.Attribute attribute = attributeService.Get(entityTypeId, entityQualifierColumn, entityQualifierValue, property.Key); if (attribute == null) { // If an existing attribute record doesn't exist, create a new one updated = true; attribute = new Model.Attribute(); attribute.EntityTypeId = entityTypeId; attribute.EntityTypeQualifierColumn = entityQualifierColumn; attribute.EntityTypeQualifierValue = entityQualifierValue; attribute.Key = property.Key; attribute.IconCssClass = string.Empty; attribute.IsGridColumn = false; } else { // Check to see if the existing attribute record needs to be updated if (attribute.Name != property.Name || attribute.DefaultValue != property.DefaultValue || attribute.Description != property.Description || attribute.Order != property.Order || attribute.FieldType.Assembly != property.FieldTypeAssembly || attribute.FieldType.Class != property.FieldTypeClass || attribute.IsRequired != property.IsRequired) { updated = true; } // Check category else if (attribute.Categories.Select(c => c.Name).Except(propertyCategories).Any() || propertyCategories.Except(attribute.Categories.Select(c => c.Name)).Any()) { updated = true; } // Check the qualifier values else if (attribute.AttributeQualifiers.Select(q => q.Key).Except(property.FieldConfigurationValues.Select(c => c.Key)).Any() || property.FieldConfigurationValues.Select(c => c.Key).Except(attribute.AttributeQualifiers.Select(q => q.Key)).Any()) { updated = true; } else { foreach (var attributeQualifier in attribute.AttributeQualifiers) { if (!property.FieldConfigurationValues.ContainsKey(attributeQualifier.Key) || property.FieldConfigurationValues[attributeQualifier.Key].Value != attributeQualifier.Value) { updated = true; break; } } } } if (updated) { // Update the attribute attribute.Name = property.Name; attribute.Description = property.Description; attribute.DefaultValue = property.DefaultValue; attribute.Order = property.Order; attribute.IsRequired = property.IsRequired; attribute.Categories.Clear(); if (propertyCategories.Any()) { foreach (string propertyCategory in propertyCategories) { int attributeEntityTypeId = EntityTypeCache.Read(typeof(Rock.Model.Attribute)).Id; var category = categoryService.Get(propertyCategory, attributeEntityTypeId, "EntityTypeId", entityTypeId.ToString()).FirstOrDefault(); if (category == null) { category = new Category(); category.Name = propertyCategory; category.EntityTypeId = attributeEntityTypeId; category.EntityTypeQualifierColumn = "EntityTypeId"; category.EntityTypeQualifierValue = entityTypeId.ToString(); category.Order = 0; } attribute.Categories.Add(category); } } foreach (var qualifier in attribute.AttributeQualifiers.ToList()) { attributeQualifierService.Delete(qualifier); } attribute.AttributeQualifiers.Clear(); foreach (var configValue in property.FieldConfigurationValues) { var qualifier = new Model.AttributeQualifier(); qualifier.Key = configValue.Key; qualifier.Value = configValue.Value.Value; attribute.AttributeQualifiers.Add(qualifier); } // Try to set the field type by searching for an existing field type with the same assembly and class name if (attribute.FieldType == null || attribute.FieldType.Assembly != property.FieldTypeAssembly || attribute.FieldType.Class != property.FieldTypeClass) { attribute.FieldType = fieldTypeService.Queryable().FirstOrDefault(f => f.Assembly == property.FieldTypeAssembly && f.Class == property.FieldTypeClass); } // If this is a new attribute, add it, otherwise remove the exiting one from the cache if (attribute.Id == 0) { attributeService.Add(attribute); } else { AttributeCache.Flush(attribute.Id); } rockContext.SaveChanges(); return(true); } else { return(false); } }
protected void btnSave_Click(object sender, EventArgs e) { using (var rockContext = new RockContext()) { var attributeService = new AttributeService(rockContext); if (checkinArea.Visible) { var groupTypeService = new GroupTypeService(rockContext); var groupType = groupTypeService.Get(checkinArea.GroupTypeGuid); if (groupType != null) { groupType.LoadAttributes(rockContext); checkinArea.GetGroupTypeValues(groupType); if (groupType.IsValid) { rockContext.SaveChanges(); groupType.SaveAttributeValues(rockContext); bool AttributesUpdated = false; // rebuild the CheckinLabel attributes from the UI (brute-force) foreach (var labelAttribute in CheckinArea.GetCheckinLabelAttributes(groupType.Attributes)) { var attribute = attributeService.Get(labelAttribute.Value.Guid); Rock.Web.Cache.AttributeCache.Flush(attribute.Id); attributeService.Delete(attribute); AttributesUpdated = true; } // Make sure default role is set if (!groupType.DefaultGroupRoleId.HasValue && groupType.Roles.Any()) { groupType.DefaultGroupRoleId = groupType.Roles.First().Id; } rockContext.SaveChanges(); int labelOrder = 0; int binaryFileFieldTypeID = FieldTypeCache.Read(Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid()).Id; foreach (var checkinLabelAttributeInfo in checkinArea.CheckinLabels) { var attribute = new Rock.Model.Attribute(); attribute.AttributeQualifiers.Add(new AttributeQualifier { Key = "binaryFileType", Value = Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL }); attribute.Guid = Guid.NewGuid(); attribute.FieldTypeId = binaryFileFieldTypeID; attribute.EntityTypeId = EntityTypeCache.GetId(typeof(GroupType)); attribute.EntityTypeQualifierColumn = "Id"; attribute.EntityTypeQualifierValue = groupType.Id.ToString(); attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileGuid.ToString(); attribute.Key = checkinLabelAttributeInfo.AttributeKey; attribute.Name = checkinLabelAttributeInfo.FileName; attribute.Order = labelOrder++; if (!attribute.IsValid) { return; } attributeService.Add(attribute); AttributesUpdated = true; } rockContext.SaveChanges(); GroupTypeCache.Flush(groupType.Id); Rock.CheckIn.KioskDevice.FlushAll(); if (AttributesUpdated) { AttributeCache.FlushEntityAttributes(); } nbSaveSuccess.Visible = true; BuildRows(); } } } if (checkinGroup.Visible) { var groupService = new GroupService(rockContext); var groupLocationService = new GroupLocationService(rockContext); var group = groupService.Get(checkinGroup.GroupGuid); if (group != null) { group.LoadAttributes(rockContext); checkinGroup.GetGroupValues(group); // populate groupLocations with whatever is currently in the grid, with just enough info to repopulate it and save it later var newLocationIds = checkinGroup.Locations.Select(l => l.LocationId).ToList(); foreach (var groupLocation in group.GroupLocations.Where(l => !newLocationIds.Contains(l.LocationId)).ToList()) { groupLocationService.Delete(groupLocation); group.GroupLocations.Remove(groupLocation); } var existingLocationIds = group.GroupLocations.Select(g => g.LocationId).ToList(); foreach (var item in checkinGroup.Locations.Where(l => !existingLocationIds.Contains(l.LocationId)).ToList()) { var groupLocation = new GroupLocation(); groupLocation.LocationId = item.LocationId; group.GroupLocations.Add(groupLocation); } if (group.IsValid) { rockContext.SaveChanges(); group.SaveAttributeValues(rockContext); Rock.CheckIn.KioskDevice.FlushAll(); nbSaveSuccess.Visible = true; BuildRows(); } } } } hfIsDirty.Value = "false"; }
public IQueryable <NursingHomeRow> GetQuery(RockContext rockContext) { var contextEntity = this.ContextEntity(); var workflowService = new WorkflowService(rockContext); var workflowActivityService = new WorkflowActivityService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personAliasService = new PersonAliasService(rockContext); var definedValueService = new DefinedValueService(rockContext); var entityTypeService = new EntityTypeService(rockContext); Guid nursingHomeAdmissionWorkflow = GetAttributeValue("NursingHomeResidentWorkflow").AsGuid(); Guid nursingHomeList = GetAttributeValue("NursingHomeList").AsGuid(); List <DefinedValueCache> facilities = DefinedTypeCache.Get(nursingHomeList).DefinedValues; int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Workflow).FullName).FirstOrDefault().Id; string status = (contextEntity != null ? "Completed" : "Active"); var workflowType = new WorkflowTypeService(rockContext).Get(nursingHomeAdmissionWorkflow); var workflowTypeIdAsString = workflowType.Id.ToString(); var attributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeIdAsString) .Select(a => a.Id).ToList(); // Look up the activity type for "Visitation" var visitationActivityIdAsString = workflowType.ActivityTypes.Where(at => at.Name == "Visitation Info").Select(at => at.Id.ToString()).FirstOrDefault(); var activityAttributeIds = attributeService.Queryable() .Where(a => a.EntityTypeQualifierColumn == "ActivityTypeId" && a.EntityTypeQualifierValue == visitationActivityIdAsString) .Select(a => a.Id).ToList(); var wfTmpqry = workflowService.Queryable().AsNoTracking() .Where(w => (w.WorkflowType.Guid == nursingHomeAdmissionWorkflow) && (w.Status == "Active" || w.Status == status)); var visitQry = workflowActivityService.Queryable() .Join( attributeValueService.Queryable(), wa => wa.Id, av => av.EntityId.Value, (wa, av) => new { WorkflowActivity = wa, AttributeValue = av }) .Where(a => activityAttributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(wa => wa.WorkflowActivity) .Select(obj => new { WorkflowActivity = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }); if (contextEntity != null) { var personGuid = (( Person )contextEntity).Aliases.Select(a => a.Guid.ToString()).ToList(); var validWorkflowIds = new AttributeValueService(rockContext).Queryable() .Where(av => av.Attribute.Key == "PersonToVisit" && personGuid.Contains(av.Value)).Select(av => av.EntityId); wfTmpqry = wfTmpqry.Where(w => validWorkflowIds.Contains(w.Id)); visitQry = visitQry.Where(w => validWorkflowIds.Contains(w.WorkflowActivity.WorkflowId)); gReport.Columns[10].Visible = true; } var visits = visitQry.ToList(); var workflows = wfTmpqry.Join( attributeValueService.Queryable(), obj => obj.Id, av => av.EntityId.Value, (obj, av) => new { Workflow = obj, AttributeValue = av }) .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId)) .GroupBy(obj => obj.Workflow) .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) }) .ToList(); var qry = workflows.AsQueryable().GroupJoin(visits.AsQueryable(), wf => wf.Workflow.Id, wa => wa.WorkflowActivity.WorkflowId, (Workflow, wa) => new { Workflow = Workflow, WorkflowActivities = wa }) .Select(obj => new { Workflow = obj.Workflow.Workflow, AttributeValues = obj.Workflow.AttributeValues, VisitationActivities = obj.WorkflowActivities }).ToList(); if (contextEntity == null) { // Make sure they aren't deceased qry = qry.AsQueryable().Where(w => ! (personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()) != null ? personAliasService.Get(w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").Select(av => av.Value).FirstOrDefault().AsGuid()).Person.IsDeceased : false)).ToList(); } var newQry = qry.Select(w => new NursingHomeRow { Id = w.Workflow.Id, Workflow = w.Workflow, NursingHome = new Func <string>(() => { if (w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).Any()) { return(facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).Select(dv => dv.Value).FirstOrDefault()); } return("N/A"); })(), Person = new Func <Person>(() => { AttributeValue personAliasAV = w.AttributeValues.Where(av => av.AttributeKey == "PersonToVisit").FirstOrDefault(); if (personAliasAV != null) { PersonAlias pa = personAliasService.Get(personAliasAV.Value.AsGuid()); return(pa != null ? pa.Person : new Person()); } return(new Person()); })(), Address = new Func <string>(() => { DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault(); if (dv != null) { return(dv.AttributeValues["Qualifier1"].ValueFormatted + " " + dv.AttributeValues["Qualifier2"].ValueFormatted + " " + dv.AttributeValues["Qualifier3"].ValueFormatted + ", " + dv.AttributeValues["Qualifier4"].ValueFormatted); } return(""); })(), PastoralMinister = new Func <string>(() => { DefinedValueCache dv = facilities.Where(h => h.Guid == w.AttributeValues.Where(av => av.AttributeKey == "NursingHome").Select(av => av.Value).FirstOrDefault().AsGuid()).FirstOrDefault(); if (dv != null && (dv.AttributeValues.ContainsKey("PastoralMinister") || dv.AttributeValues.ContainsKey("Qualifier6"))) { return(dv.AttributeValues.ContainsKey("PastoralMinister")?dv.AttributeValues["PastoralMinister"].ValueFormatted:dv.AttributeValues["Qualifier6"].ValueFormatted); } return(""); })(), Room = w.AttributeValues.Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(), AdmitDate = w.AttributeValues.Where(av => av.AttributeKey == "AdmitDate").Select(av => av.ValueAsDateTime).FirstOrDefault(), Description = w.AttributeValues.Where(av => av.AttributeKey == "VisitationRequestDescription").Select(av => av.ValueFormatted).FirstOrDefault(), Visits = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Count(), LastVisitor = new Func <string>(() => { var visitor = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "Visitor").LastOrDefault()).LastOrDefault(); if (visitor != null) { return(visitor.ValueFormatted); } return("N/A"); })(), LastVisitDate = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitDate").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), LastVisitNotes = w.VisitationActivities.Where(a => a.AttributeValues != null && a.AttributeValues.Where(av => av.AttributeKey == "VisitDate" && !string.IsNullOrWhiteSpace(av.Value)).Any()).Select(va => va.AttributeValues.Where(av => av.AttributeKey == "VisitNote").LastOrDefault()).Select(av => av == null ? "N/A" : av.ValueFormatted).DefaultIfEmpty("N/A").LastOrDefault(), DischargeDate = w.AttributeValues.Where(av => av.AttributeKey == "DischargeDate").Select(av => av.ValueFormatted).FirstOrDefault(), Status = w.Workflow.Status, Communion = w.AttributeValues.Where(av => av.AttributeKey == "Communion").Select(av => av.ValueFormatted).FirstOrDefault(), Actions = "" }).ToList().AsQueryable().OrderBy(p => p.NursingHome).ThenBy(p => p.Person.FullName); return(newQry); }
protected override void OnInit(EventArgs e) { base.OnInit(e); string entity = AttributeValue("Entity"); if (string.IsNullOrWhiteSpace(entity)) { entity = PageParameter("Entity"); } string entityQualifierColumn = AttributeValue("EntityQualifierColumn"); if (string.IsNullOrWhiteSpace(entityQualifierColumn)) { entityQualifierColumn = PageParameter("EntityQualifierColumn"); } string entityQualifierValue = AttributeValue("EntityQualifierValue"); if (string.IsNullOrWhiteSpace(entityQualifierValue)) { entityQualifierValue = PageParameter("EntityQualifierValue"); } _category = AttributeValue("AttributeCategory"); if (string.IsNullOrWhiteSpace(_category)) { _category = PageParameter("AttributeCategory"); } ObjectCache cache = MemoryCache.Default; string cacheKey = string.Format("Attributes:{0}:{1}:{2}", entity, entityQualifierColumn, entityQualifierValue); Dictionary <string, List <int> > cachedAttributes = cache[cacheKey] as Dictionary <string, List <int> >; if (cachedAttributes == null) { cachedAttributes = new Dictionary <string, List <int> >(); AttributeService attributeService = new AttributeService(); foreach (var item in attributeService.Queryable(). Where(a => a.Entity == entity && (a.EntityQualifierColumn ?? string.Empty) == entityQualifierColumn && (a.EntityQualifierValue ?? string.Empty) == entityQualifierValue). OrderBy(a => a.Category). ThenBy(a => a.Order). Select(a => new { a.Category, a.Id })) { if (!cachedAttributes.ContainsKey(item.Category)) { cachedAttributes.Add(item.Category, new List <int>()); } cachedAttributes[item.Category].Add(item.Id); } CacheItemPolicy cacheItemPolicy = null; cache.Set(cacheKey, cachedAttributes, cacheItemPolicy); } Rock.Attribute.IHasAttributes model = PageInstance.GetCurrentContext(entity) as Rock.Attribute.IHasAttributes; if (model != null) { if (cachedAttributes.ContainsKey(_category)) { foreach (var attributeId in cachedAttributes[_category]) { var attribute = Rock.Web.Cache.Attribute.Read(attributeId); if (attribute != null) { phAttributes.Controls.Add(( AttributeInstanceValues )this.LoadControl("~/Blocks/Core/AttributeInstanceValues.ascx", model, attribute, CurrentPersonId)); } } } } string script = @" Sys.Application.add_load(function () { $('div.context-attribute-values .delete').click(function(){ return confirm('Are you sure?'); }); }); "; Page.ClientScript.RegisterStartupScript(this.GetType(), "ConfirmDelete", script, true); }
private void CreateControls(bool setSelection) { // Load all the attribute controls attributeControls.Clear(); pnlAttributes.Controls.Clear(); phDuplicates.Controls.Clear(); var rockContext = new RockContext(); var attributeService = new AttributeService(rockContext); var locationService = new LocationService(rockContext); foreach (string categoryGuid in GetAttributeValue("AttributeCategories").SplitDelimitedValues(false)) { Guid guid = Guid.Empty; if (Guid.TryParse(categoryGuid, out guid)) { var category = CategoryCache.Read(guid); if (category != null) { var attributeControl = new NewGroupAttributes(); attributeControl.ClearRows(); pnlAttributes.Controls.Add(attributeControl); attributeControls.Add(attributeControl); attributeControl.ID = "groupAttributes_" + category.Id.ToString(); attributeControl.CategoryId = category.Id; foreach (var attribute in attributeService.GetByCategoryId(category.Id)) { if (attribute.IsAuthorized(Authorization.EDIT, CurrentPerson)) { attributeControl.AttributeList.Add(AttributeCache.Read(attribute)); } } } } } nfmMembers.ClearRows(); nfciContactInfo.ClearRows(); var groupMemberService = new GroupMemberService(rockContext); int defaultRoleId = _groupType.DefaultGroupRoleId ?? _groupType.Roles.Select(r => r.Id).FirstOrDefault(); var location = new Location(); acAddress.GetValues(location); foreach (var groupMember in GroupMembers) { string groupMemberGuidString = groupMember.Person.Guid.ToString().Replace("-", "_"); var groupMemberRow = new NewGroupMembersRow(); groupMemberRow.GroupTypeId = _groupType.Id; nfmMembers.Controls.Add(groupMemberRow); groupMemberRow.ID = string.Format("row_{0}", groupMemberGuidString); groupMemberRow.RoleUpdated += groupMemberRow_RoleUpdated; groupMemberRow.DeleteClick += groupMemberRow_DeleteClick; groupMemberRow.PersonGuid = groupMember.Person.Guid; groupMemberRow.RequireGender = nfmMembers.RequireGender; groupMemberRow.RequireGrade = nfmMembers.RequireGrade; groupMemberRow.RoleId = groupMember.GroupRoleId; groupMemberRow.ShowGradeColumn = _isFamilyGroupType; groupMemberRow.ShowGradePicker = groupMember.GroupRoleId == _childRoleId; groupMemberRow.ValidationGroup = BlockValidationGroup; var contactInfoRow = new NewGroupContactInfoRow(); nfciContactInfo.Controls.Add(contactInfoRow); contactInfoRow.ID = string.Format("ci_row_{0}", groupMemberGuidString); contactInfoRow.PersonGuid = groupMember.Person.Guid; contactInfoRow.IsMessagingEnabled = _SMSEnabled; contactInfoRow.PersonName = groupMember.Person.FullName; if (_homePhone != null) { var homePhoneNumber = groupMember.Person.PhoneNumbers.Where(p => p.NumberTypeValueId == _homePhone.Id).FirstOrDefault(); if (homePhoneNumber != null) { contactInfoRow.HomePhoneNumber = PhoneNumber.FormattedNumber(homePhoneNumber.CountryCode, homePhoneNumber.Number); contactInfoRow.HomePhoneCountryCode = homePhoneNumber.CountryCode; } else { contactInfoRow.HomePhoneNumber = string.Empty; contactInfoRow.HomePhoneCountryCode = string.Empty; } } if (_cellPhone != null) { var cellPhoneNumber = groupMember.Person.PhoneNumbers.Where(p => p.NumberTypeValueId == _cellPhone.Id).FirstOrDefault(); if (cellPhoneNumber != null) { contactInfoRow.CellPhoneNumber = PhoneNumber.FormattedNumber(cellPhoneNumber.CountryCode, cellPhoneNumber.Number); contactInfoRow.CellPhoneCountryCode = cellPhoneNumber.CountryCode; } else { contactInfoRow.CellPhoneNumber = string.Empty; contactInfoRow.CellPhoneCountryCode = string.Empty; } } contactInfoRow.Email = groupMember.Person.Email; if (setSelection) { if (groupMember.Person != null) { groupMemberRow.TitleValueId = groupMember.Person.TitleValueId; groupMemberRow.FirstName = groupMember.Person.FirstName; groupMemberRow.LastName = groupMember.Person.LastName; groupMemberRow.SuffixValueId = groupMember.Person.SuffixValueId; groupMemberRow.Gender = groupMember.Person.Gender; groupMemberRow.BirthDate = groupMember.Person.BirthDate; groupMemberRow.ConnectionStatusValueId = groupMember.Person.ConnectionStatusValueId; groupMemberRow.GradeOffset = groupMember.Person.GradeOffset; } } foreach (var attributeControl in attributeControls) { var attributeRow = new NewGroupAttributesRow(); attributeControl.Controls.Add(attributeRow); attributeRow.ID = string.Format("{0}_{1}", attributeControl.ID, groupMemberGuidString); attributeRow.AttributeList = attributeControl.AttributeList; attributeRow.PersonGuid = groupMember.Person.Guid; attributeRow.PersonName = groupMember.Person.FullName; if (setSelection) { attributeRow.SetEditValues(groupMember.Person); } } if (Duplicates.ContainsKey(groupMember.Person.Guid)) { var dupRow = new HtmlGenericControl("div"); dupRow.AddCssClass("row"); dupRow.ID = string.Format("dupRow_{0}", groupMemberGuidString); phDuplicates.Controls.Add(dupRow); var newPersonCol = new HtmlGenericControl("div"); newPersonCol.AddCssClass("col-md-6"); newPersonCol.ID = string.Format("newPersonCol_{0}", groupMemberGuidString); dupRow.Controls.Add(newPersonCol); newPersonCol.Controls.Add(PersonHtmlPanel( groupMemberGuidString, groupMember.Person, groupMember.GroupRole, location, rockContext)); LinkButton lbRemoveMember = new LinkButton(); lbRemoveMember.ID = string.Format("lbRemoveMember_{0}", groupMemberGuidString); lbRemoveMember.AddCssClass("btn btn-danger btn-xs"); lbRemoveMember.Text = "Remove"; lbRemoveMember.Click += lbRemoveMember_Click; newPersonCol.Controls.Add(lbRemoveMember); var dupPersonCol = new HtmlGenericControl("div"); dupPersonCol.AddCssClass("col-md-6"); dupPersonCol.ID = string.Format("dupPersonCol_{0}", groupMemberGuidString); dupRow.Controls.Add(dupPersonCol); var duplicateHeader = new HtmlGenericControl("h4"); duplicateHeader.InnerText = "Possible Duplicate Records"; dupPersonCol.Controls.Add(duplicateHeader); foreach (var duplicate in Duplicates[groupMember.Person.Guid]) { GroupTypeRole groupTypeRole = null; Location duplocation = null; var dupGroupMember = groupMemberService.Queryable() .Where(a => a.PersonId == duplicate.Id) .Where(a => a.Group.GroupTypeId == _groupType.Id) .Select(s => new { s.GroupRole, GroupLocation = s.Group.GroupLocations.Where(a => a.GroupLocationTypeValue.Guid.Equals(_locationType.Guid)).Select(a => a.Location).FirstOrDefault() }) .FirstOrDefault(); if (dupGroupMember != null) { groupTypeRole = dupGroupMember.GroupRole; duplocation = dupGroupMember.GroupLocation; } dupPersonCol.Controls.Add(PersonHtmlPanel( groupMemberGuidString, duplicate, groupTypeRole, duplocation, rockContext)); } } } ShowPage(); }
/// <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) { Location location; var rockContext = new RockContext(); LocationService locationService = new LocationService(rockContext); AttributeService attributeService = new AttributeService(rockContext); AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext); int locationId = int.Parse(hfLocationId.Value); if (locationId == 0) { location = new Location(); location.Name = string.Empty; } else { location = locationService.Get(locationId); } location.Name = tbName.Text; location.IsActive = cbIsActive.Checked; location.LocationTypeValueId = ddlLocationType.SelectedValueAsId(); if (gpParentLocation != null && gpParentLocation.Location != null) { location.ParentLocationId = gpParentLocation.Location.Id; } else { location.ParentLocationId = null; } location.PrinterDeviceId = ddlPrinter.SelectedValueAsInt(); var addrLocation = locapAddress.Location; if (addrLocation != null) { location.Street1 = addrLocation.Street1; location.Street2 = addrLocation.Street2; location.City = addrLocation.City; location.State = addrLocation.State; location.Zip = addrLocation.Zip; } location.GeoPoint = geopPoint.SelectedValue; if (geopPoint.SelectedValue != null) { location.IsGeoPointLocked = true; } location.GeoFence = geopFence.SelectedValue; location.IsGeoPointLocked = cbGeoPointLocked.Checked; location.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributeEdits, location); if (!Page.IsValid) { return; } if (!location.IsValid) { // Controls will render the error messages return; } RockTransactionScope.WrapTransaction(() => { if (location.Id.Equals(0)) { locationService.Add(location); } rockContext.SaveChanges(); location.SaveAttributeValues(rockContext); }); var qryParams = new Dictionary <string, string>(); qryParams["LocationId"] = location.Id.ToString(); NavigateToPage(RockPage.Guid, qryParams); }
public AttributesController(AttributeService attrService) { _attrService = attrService; }
/// <summary> /// Maps the specified folder. /// </summary> /// <param name="folder">The folder.</param> /// <param name="ministryFileType">Type of the ministry file.</param> public void Map(ZipArchive folder, BinaryFileType ministryFileType) { var lookupContext = new RockContext(); var personEntityTypeId = EntityTypeCache.GetId <Person>(); var fileFieldTypeId = FieldTypeCache.Read(Rock.SystemGuid.FieldType.FILE.AsGuid(), lookupContext).Id; var existingAttributes = new AttributeService(lookupContext).GetByFieldTypeId(fileFieldTypeId) .Where(a => a.EntityTypeId == personEntityTypeId) .ToDictionary(a => a.Key, a => a.Id); var storageProvider = ministryFileType.StorageEntityTypeId == DatabaseProvider.EntityType.Id ? (ProviderComponent)DatabaseProvider : (ProviderComponent)FileSystemProvider; var emptyJsonObject = "{}"; var newFileList = new List <DocumentKeys>(); int completed = 0; int totalRows = folder.Entries.Count; int percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying files import ({0:N0} found.", totalRows)); foreach (var file in folder.Entries) { var fileExtension = Path.GetExtension(file.Name); if (BinaryFileComponent.FileTypeBlackList.Contains(fileExtension)) { LogException("Binary File Import", string.Format("{0} filetype not allowed ({1})", fileExtension, file.Name)); continue; } string[] parsedFileName = file.Name.Split('_'); // Ministry docs should follow this pattern: // 0. Firstname // 1. Lastname // 2. ForeignId // 3. Filename var personForeignId = parsedFileName[2].AsType <int?>(); var personKeys = BinaryFileComponent.ImportedPeople.FirstOrDefault(p => p.IndividualId == personForeignId); if (personKeys != null) { var rockFile = new Rock.Model.BinaryFile(); rockFile.IsSystem = false; rockFile.IsTemporary = false; rockFile.FileName = file.Name; rockFile.BinaryFileTypeId = ministryFileType.Id; rockFile.CreatedDateTime = file.LastWriteTime.DateTime; rockFile.MimeType = Extensions.GetMIMEType(file.Name); rockFile.Description = string.Format("Imported as {0}", file.Name); rockFile.SetStorageEntityTypeId(ministryFileType.StorageEntityTypeId); rockFile.StorageEntitySettings = emptyJsonObject; if (ministryFileType.AttributeValues.Any()) { rockFile.StorageEntitySettings = ministryFileType.AttributeValues .ToDictionary(a => a.Key, v => v.Value.Value).ToJson(); } // use base stream instead of file stream to keep the byte[] // NOTE: if byte[] converts to a string it will corrupt the stream using (var fileContent = new StreamReader(file.Open())) { rockFile.ContentStream = new MemoryStream(fileContent.BaseStream.ReadBytesToEnd()); } var attributePattern = "[A-Za-z]+"; var attributeName = Regex.Match(parsedFileName[3], attributePattern); var attributeKey = attributeName.Value.RemoveWhitespace(); if (!existingAttributes.ContainsKey(attributeKey)) { var newAttribute = new Attribute(); newAttribute.FieldTypeId = fileFieldTypeId; newAttribute.EntityTypeId = personEntityTypeId; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.Key = attributeKey; newAttribute.Name = attributeName.Value; newAttribute.Description = attributeName.Value + " created by binary file import"; newAttribute.IsGridColumn = false; newAttribute.IsMultiValue = false; newAttribute.IsRequired = false; newAttribute.AllowSearch = false; newAttribute.IsSystem = false; newAttribute.Order = 0; newAttribute.AttributeQualifiers.Add(new AttributeQualifier() { Key = "binaryFileType", Value = ministryFileType.Guid.ToString() }); lookupContext.Attributes.Add(newAttribute); lookupContext.SaveChanges(); existingAttributes.Add(newAttribute.Key, newAttribute.Id); } newFileList.Add(new DocumentKeys() { PersonId = personKeys.PersonId, AttributeId = existingAttributes[attributeKey], File = rockFile }); completed++; if (completed % percentage < 1) { int percentComplete = completed / percentage; ReportProgress(percentComplete, string.Format("{0:N0} files imported ({1}% complete).", completed, percentComplete)); } else if (completed % ReportingNumber < 1) { SaveFiles(newFileList, storageProvider); // Reset list newFileList.Clear(); ReportPartialProgress(); } } } if (newFileList.Any()) { SaveFiles(newFileList, storageProvider); } ReportProgress(100, string.Format("Finished files import: {0:N0} addresses imported.", completed)); }
/// <summary> /// Gets the Attributes for a Group Member of a specific Group Type. /// </summary> /// <returns></returns> private List <EntityField> GetGroupMemberAttributes() { if (_GroupMemberAttributes == null) { var entityAttributeFields = new Dictionary <string, EntityField>(); var context = new RockContext(); var attributeService = new AttributeService(context); var groupTypeService = new GroupTypeService(context); var groupMemberEntityTypeId = EntityTypeCache.GetId(typeof(Model.GroupMember)); var groupMemberAttributes = attributeService.Queryable() .AsNoTracking() .Where(a => a.EntityTypeId == groupMemberEntityTypeId) .Join(groupTypeService.Queryable(), a => a.EntityTypeQualifierValue, gt => gt.Id.ToString(), (a, gt) => new { Attribute = a, AttributeKey = a.Key, FieldTypeName = a.FieldType.Name, a.FieldTypeId, AttributeName = a.Name, GroupTypeName = gt.Name }) .GroupBy(x => x.AttributeName) .ToList(); foreach (var attributesByName in groupMemberAttributes) { var attributeNameAndTypeGroups = attributesByName.GroupBy(x => x.FieldTypeId).ToList(); bool requiresTypeQualifier = (attributeNameAndTypeGroups.Count > 1); foreach (var attributeNameAndTypeGroup in attributeNameAndTypeGroups) { foreach (var attribute in attributeNameAndTypeGroup) { string fieldKey; string fieldName; if (requiresTypeQualifier) { fieldKey = attribute.AttributeName + "_" + attribute.FieldTypeId; fieldName = string.Format("{0} [{1}]", attribute.AttributeName, attribute.FieldTypeName); } else { fieldName = attribute.AttributeName; fieldKey = attribute.AttributeName; } if (entityAttributeFields.ContainsKey(fieldKey)) { continue; } var attributeCache = AttributeCache.Get(attribute.Attribute); var entityField = EntityHelper.GetEntityFieldForAttribute(attributeCache); entityField.Title = fieldName; entityField.AttributeGuid = null; entityAttributeFields.Add(fieldKey, entityField); } } } int index = 0; var sortedFields = new List <EntityField>(); foreach (var entityProperty in entityAttributeFields.Values.OrderBy(p => p.Title).ThenBy(p => p.Name)) { entityProperty.Index = index; index++; sortedFields.Add(entityProperty); } _GroupMemberAttributes = sortedFields; } return(_GroupMemberAttributes); }
/// <summary> /// Loads the individual data. /// </summary> /// <param name="csvData">The CSV data.</param> private int LoadIndividuals(CSVInstance csvData) { var lookupContext = new RockContext(); var groupTypeRoleService = new GroupTypeRoleService(lookupContext); var groupMemberService = new GroupMemberService(lookupContext); // Marital statuses: Married, Single, Separated, etc var maritalStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS), lookupContext).DefinedValues; // Connection statuses: Member, Visitor, Attendee, etc var connectionStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS), lookupContext).DefinedValues; int memberConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER)).Id; int visitorConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR)).Id; int attendeeConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_ATTENDEE)).Id; // Suffix type: Dr., Jr., II, etc var suffixTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_SUFFIX), lookupContext).DefinedValues; // Title type: Mr., Mrs. Dr., etc var titleTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_TITLE), lookupContext).DefinedValues; // Record statuses: Active, Inactive, Pending int?recordStatusActiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE), lookupContext).Id; int?recordStatusInactiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE), lookupContext).Id; int?recordStatusPendingId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING), lookupContext).Id; // Deceased record status reason (others available: No Activity, Moved, etc) var recordStatusDeceasedId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_REASON_DECEASED)).Id; // Record type: Person int?personRecordTypeId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON), lookupContext).Id; // Group roles: Owner, Adult, Child, others GroupTypeRole ownerRole = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER)); int adultRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id; int childRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD)).Id; // Phone types: Home, Work, Mobile var numberTypeValues = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE), lookupContext).DefinedValues; // Personal note type id var personalNoteTypeId = new NoteTypeService(lookupContext).Get(new Guid(Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE)).Id; // School defined type var schoolDefinedType = DefinedTypeCache.Read(new Guid("576FF1E2-6225-4565-A16D-230E26167A3D")); // Look up existing Person attributes var personAttributes = new AttributeService(lookupContext).GetByEntityTypeId(PersonEntityTypeId).ToList(); var schoolAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "School")); // Text field type id int textFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT), lookupContext).Id; int dateFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.DATE), lookupContext).Id; // Attribute entity type id int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id; // Visit info category var visitInfoCategory = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId) .Where(c => c.Name == "Visit Information").FirstOrDefault(); // Look for custom attributes in the Individual file var allFields = csvData.TableNodes.FirstOrDefault().Children.Select((node, index) => new { node = node, index = index }).ToList(); Dictionary <int, string> customAttributes = allFields .Where(f => f.index > SecurityNote) .ToDictionary(f => f.index, f => f.node.Name.RemoveWhitespace()); // Add any attributes if they don't already exist if (customAttributes.Any()) { var newAttributes = new List <Rock.Model.Attribute>(); foreach (var newAttributePair in customAttributes.Where(ca => !personAttributes.Any(a => a.Key == ca.Value))) { var newAttribute = new Rock.Model.Attribute(); newAttribute.Name = newAttributePair.Value; newAttribute.Key = newAttributePair.Value.RemoveWhitespace(); newAttribute.Description = newAttributePair.Value + " created by CSV import"; newAttribute.EntityTypeQualifierValue = string.Empty; newAttribute.EntityTypeQualifierColumn = string.Empty; newAttribute.EntityTypeId = PersonEntityTypeId; newAttribute.FieldTypeId = textFieldTypeId; newAttribute.DefaultValue = string.Empty; newAttribute.IsMultiValue = false; newAttribute.IsGridColumn = false; newAttribute.IsRequired = false; newAttribute.Order = 0; newAttributes.Add(newAttribute); } lookupContext.Attributes.AddRange(newAttributes); lookupContext.SaveChanges(DisableAuditing); personAttributes.AddRange(newAttributes); } // Set the supported date formats var dateFormats = new[] { "yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy" }; var currentFamilyGroup = new Group(); var newFamilyList = new List <Group>(); var newVisitorList = new List <Group>(); var newNoteList = new List <Note>(); int completed = 0; int newFamilies = 0; ReportProgress(0, string.Format("Starting Individual import ({0:N0} already exist).", ImportedPeople.Count(p => p.Members.Any(m => m.Person.ForeignKey != null)))); string[] row; // Uses a look-ahead enumerator: this call will move to the next record immediately while ((row = csvData.Database.FirstOrDefault()) != null) { int groupRoleId = adultRoleId; bool isFamilyRelationship = true; string rowFamilyName = row[FamilyName]; string rowFamilyKey = row[FamilyId]; string rowPersonKey = row[PersonId]; int? rowFamilyId = rowFamilyKey.AsType <int?>(); int? rowPersonId = rowPersonKey.AsType <int?>(); // Check that this person isn't already in our data var personExists = ImportedPeople.Any(p => p.Members.Any(m => m.Person.ForeignKey == rowPersonKey)); if (!personExists) { #region person create var person = new Person(); person.ForeignKey = rowPersonKey; person.ForeignId = rowPersonId; person.SystemNote = string.Format("Imported via Excavator on {0}", ImportDateTime); person.RecordTypeValueId = personRecordTypeId; person.CreatedByPersonAliasId = ImportPersonAliasId; string firstName = row[FirstName].Left(50); string nickName = row[NickName].Left(50); person.FirstName = firstName; person.NickName = string.IsNullOrWhiteSpace(nickName) ? firstName : nickName; person.MiddleName = row[MiddleName].Left(50); person.LastName = row[LastName].Left(50); DateTime createdDateValue; if (DateTime.TryParseExact(row[CreatedDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDateValue)) { person.CreatedDateTime = createdDateValue; person.ModifiedDateTime = ImportDateTime; } else { person.CreatedDateTime = ImportDateTime; person.ModifiedDateTime = ImportDateTime; } DateTime birthDate; if (DateTime.TryParseExact(row[DateOfBirth], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate)) { person.BirthDay = birthDate.Day; person.BirthMonth = birthDate.Month; person.BirthYear = birthDate.Year; } DateTime graduationDate; if (DateTime.TryParseExact(row[GraduationDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out graduationDate)) { person.GraduationYear = graduationDate.Year; } DateTime anniversary; if (DateTime.TryParseExact(row[Anniversary], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out anniversary)) { person.AnniversaryDate = anniversary; } string gender = row[Gender]; if (gender != null) { switch (gender.Trim().ToLower()) { case "m": case "male": person.Gender = Rock.Model.Gender.Male; break; case "f": case "female": person.Gender = Rock.Model.Gender.Female; break; default: person.Gender = Rock.Model.Gender.Unknown; break; } } string prefix = row[Prefix]; if (!string.IsNullOrWhiteSpace(prefix)) { prefix = prefix.RemoveSpecialCharacters().Trim(); person.TitleValueId = titleTypes.Where(s => prefix == s.Value.RemoveSpecialCharacters()) .Select(s => (int?)s.Id).FirstOrDefault(); } string suffix = row[Suffix]; if (!string.IsNullOrWhiteSpace(suffix)) { suffix = suffix.RemoveSpecialCharacters().Trim(); person.SuffixValueId = suffixTypes.Where(s => suffix == s.Value.RemoveSpecialCharacters()) .Select(s => (int?)s.Id).FirstOrDefault(); } string maritalStatus = row[MaritalStatus]; if (!string.IsNullOrWhiteSpace(maritalStatus)) { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == maritalStatus) .Select(dv => (int?)dv.Id).FirstOrDefault(); } else { person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == "Unknown") .Select(dv => (int?)dv.Id).FirstOrDefault(); } string familyRole = row[FamilyRole]; if (!string.IsNullOrWhiteSpace(familyRole)) { if (familyRole == "Visitor") { isFamilyRelationship = false; } if (familyRole == "Child" || person.Age < 18) { groupRoleId = childRoleId; } } string connectionStatus = row[ConnectionStatus]; if (!string.IsNullOrWhiteSpace(connectionStatus)) { if (connectionStatus == "Member") { person.ConnectionStatusValueId = memberConnectionStatusId; } else if (connectionStatus == "Visitor") { person.ConnectionStatusValueId = visitorConnectionStatusId; } else { // look for user-defined connection type or default to Attendee var customConnectionType = connectionStatusTypes.Where(dv => dv.Value == connectionStatus) .Select(dv => (int?)dv.Id).FirstOrDefault(); person.ConnectionStatusValueId = customConnectionType ?? attendeeConnectionStatusId; person.RecordStatusValueId = recordStatusActiveId; } } string recordStatus = row[RecordStatus]; if (!string.IsNullOrWhiteSpace(recordStatus)) { switch (recordStatus.Trim().ToLower()) { case "active": person.RecordStatusValueId = recordStatusActiveId; break; case "inactive": person.RecordStatusValueId = recordStatusInactiveId; break; default: person.RecordStatusValueId = recordStatusPendingId; break; } } string isDeceasedValue = row[IsDeceased]; if (!string.IsNullOrWhiteSpace(isDeceasedValue)) { switch (isDeceasedValue.Trim().ToLower()) { case "y": case "yes": person.IsDeceased = true; person.RecordStatusReasonValueId = recordStatusDeceasedId; person.RecordStatusValueId = recordStatusInactiveId; break; default: person.IsDeceased = false; break; } } var personNumbers = new Dictionary <string, string>(); personNumbers.Add("Home", row[HomePhone]); personNumbers.Add("Mobile", row[MobilePhone]); personNumbers.Add("Work", row[WorkPhone]); string smsAllowed = row[AllowSMS]; foreach (var numberPair in personNumbers.Where(n => !string.IsNullOrWhiteSpace(n.Value))) { var extension = string.Empty; var countryCode = Rock.Model.PhoneNumber.DefaultCountryCode(); var normalizedNumber = string.Empty; var countryIndex = numberPair.Value.IndexOf('+'); int extensionIndex = numberPair.Value.LastIndexOf('x') > 0 ? numberPair.Value.LastIndexOf('x') : numberPair.Value.Length; if (countryIndex >= 0) { countryCode = numberPair.Value.Substring(countryIndex, countryIndex + 3).AsNumeric(); normalizedNumber = numberPair.Value.Substring(countryIndex + 3, extensionIndex - 3).AsNumeric().TrimStart(new Char[] { '0' }); extension = numberPair.Value.Substring(extensionIndex); } else if (extensionIndex > 0) { normalizedNumber = numberPair.Value.Substring(0, extensionIndex).AsNumeric(); extension = numberPair.Value.Substring(extensionIndex).AsNumeric(); } else { normalizedNumber = numberPair.Value.AsNumeric(); } if (!string.IsNullOrWhiteSpace(normalizedNumber)) { var currentNumber = new PhoneNumber(); currentNumber.CountryCode = countryCode; currentNumber.CreatedByPersonAliasId = ImportPersonAliasId; currentNumber.Extension = extension.Left(20); currentNumber.Number = normalizedNumber.TrimStart(new Char[] { '0' }).Left(20); currentNumber.NumberTypeValueId = numberTypeValues.Where(v => v.Value.Equals(numberPair.Key)) .Select(v => (int?)v.Id).FirstOrDefault(); if (numberPair.Key == "Mobile") { switch (smsAllowed.Trim().ToLower()) { case "y": case "yes": case "active": currentNumber.IsMessagingEnabled = true; break; default: currentNumber.IsMessagingEnabled = false; break; } } person.PhoneNumbers.Add(currentNumber); } } // Map Person attributes person.Attributes = new Dictionary <string, AttributeCache>(); person.AttributeValues = new Dictionary <string, AttributeValueCache>(); bool isEmailActive; switch (row[IsEmailActive].Trim().ToLower()) { case "n": case "no": case "inactive": isEmailActive = false; break; default: isEmailActive = true; break; } EmailPreference emailPreference; switch (row[AllowBulkEmail].Trim().ToLower()) { case "n": case "no": case "inactive": emailPreference = EmailPreference.NoMassEmails; break; default: emailPreference = EmailPreference.EmailAllowed; break; } person.EmailPreference = emailPreference; string primaryEmail = row[Email].Trim().Left(75); if (!string.IsNullOrWhiteSpace(primaryEmail)) { if (primaryEmail.IsEmail()) { person.Email = primaryEmail; person.IsEmailActive = isEmailActive; } else { LogException("InvalidPrimaryEmail", string.Format("PersonId: {0} - Email: {1}", rowPersonKey, primaryEmail)); } } string schoolName = row[School]; if (!string.IsNullOrWhiteSpace(schoolName)) { // Add school if it doesn't exist Guid schoolGuid; var schoolExists = schoolDefinedType.DefinedValues.Any(s => s.Value.Equals(schoolName)); if (!schoolExists) { var newSchool = new DefinedValue(); newSchool.DefinedTypeId = schoolDefinedType.Id; newSchool.Value = schoolName; newSchool.Order = 0; lookupContext.DefinedValues.Add(newSchool); lookupContext.SaveChanges(); schoolGuid = newSchool.Guid; } else { schoolGuid = schoolDefinedType.DefinedValues.FirstOrDefault(s => s.Value.Equals(schoolName)).Guid; } AddPersonAttribute(schoolAttribute, person, schoolGuid.ToString().ToUpper()); } foreach (var attributePair in customAttributes) { string newAttributeValue = row[attributePair.Key]; if (!string.IsNullOrWhiteSpace(newAttributeValue)) { // check if this attribute value is a date DateTime valueAsDateTime; if (DateTime.TryParseExact(newAttributeValue, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out valueAsDateTime)) { newAttributeValue = valueAsDateTime.ToString("yyyy-MM-dd"); } int?newAttributeId = personAttributes.Where(a => a.Key == attributePair.Value.RemoveWhitespace()) .Select(a => (int?)a.Id).FirstOrDefault(); if (newAttributeId != null) { var newAttribute = AttributeCache.Read((int)newAttributeId); AddPersonAttribute(newAttribute, person, newAttributeValue); } } } // Add notes to timeline var notePairs = new Dictionary <string, string>(); notePairs.Add("General", row[GeneralNote]); notePairs.Add("Medical", row[MedicalNote]); notePairs.Add("Security", row[SecurityNote]); foreach (var notePair in notePairs.Where(n => !string.IsNullOrWhiteSpace(n.Value))) { var newNote = new Note(); newNote.NoteTypeId = personalNoteTypeId; newNote.CreatedByPersonAliasId = ImportPersonAliasId; newNote.CreatedDateTime = ImportDateTime; newNote.Text = notePair.Value; newNote.ForeignKey = rowPersonKey; newNote.ForeignId = rowPersonId; newNote.Caption = string.Format("{0} Note", notePair.Key); if (!notePair.Key.Equals("General")) { newNote.IsAlert = true; } newNoteList.Add(newNote); } #endregion person create var groupMember = new GroupMember(); groupMember.Person = person; groupMember.GroupRoleId = groupRoleId; groupMember.CreatedDateTime = ImportDateTime; groupMember.ModifiedDateTime = ImportDateTime; groupMember.CreatedByPersonAliasId = ImportPersonAliasId; groupMember.GroupMemberStatus = GroupMemberStatus.Active; if (rowFamilyKey != currentFamilyGroup.ForeignKey) { // person not part of the previous family, see if that family exists or create a new one currentFamilyGroup = ImportedPeople.FirstOrDefault(p => p.ForeignKey == rowFamilyKey); if (currentFamilyGroup == null) { currentFamilyGroup = CreateFamilyGroup(row[FamilyName], rowFamilyKey); newFamilyList.Add(currentFamilyGroup); newFamilies++; } else { lookupContext.Groups.Attach(currentFamilyGroup); lookupContext.Entry(currentFamilyGroup).State = EntityState.Modified; } currentFamilyGroup.Members.Add(groupMember); } else { // person is part of this family group, check if they're a visitor if (isFamilyRelationship || currentFamilyGroup.Members.Count() < 1) { currentFamilyGroup.Members.Add(groupMember); } else { var visitorFamily = CreateFamilyGroup(person.LastName + " Family", rowFamilyKey); visitorFamily.Members.Add(groupMember); newFamilyList.Add(visitorFamily); newVisitorList.Add(visitorFamily); newFamilies++; } } completed++; if (completed % (ReportingNumber * 10) < 1) { ReportProgress(0, string.Format("{0:N0} people imported.", completed)); } else if (completed % ReportingNumber < 1) { SaveIndividuals(newFamilyList, newVisitorList, newNoteList); lookupContext.SaveChanges(); ReportPartialProgress(); // Clear out variables currentFamilyGroup = new Group(); newFamilyList.Clear(); newVisitorList.Clear(); newNoteList.Clear(); } } } // Save any changes to new families if (newFamilyList.Any()) { SaveIndividuals(newFamilyList, newVisitorList, newNoteList); } // Save any changes to existing families lookupContext.SaveChanges(); lookupContext.Dispose(); ReportProgress(0, string.Format("Finished individual import: {0:N0} families and {1:N0} people added.", newFamilies, completed)); return(completed); }
public AttributeController() { _attributeService = new AttributeService(); }
private void BindGrid() { string type = PageParameter("SearchType"); string term = PageParameter("SearchTerm"); if (!string.IsNullOrWhiteSpace(type) && !string.IsNullOrWhiteSpace(term)) { term = term.Trim(); type = type.Trim(); var rockContext = new RockContext(); var personService = new PersonService(rockContext); IQueryable <Person> people = null; switch (type.ToLower()) { case ("name"): { bool allowFirstNameOnly = false; if (!bool.TryParse(PageParameter("allowFirstNameOnly"), out allowFirstNameOnly)) { allowFirstNameOnly = false; } people = personService.GetByFullName(term, allowFirstNameOnly, true); break; } case ("phone"): { var phoneService = new PhoneNumberService(rockContext); var personIds = phoneService.GetPersonIdsByNumber(term); people = personService.Queryable().Where(p => personIds.Contains(p.Id)); break; } case ("address"): { var personIds2 = GetPersonIdsByHomePrevAddress(rockContext, term); people = personService.Queryable().Where(p => personIds2.Contains(p.Id)); break; } case ("email"): { people = personService.Queryable().Where(p => p.Email.Contains(term)); break; } case ("envelope"): { var aService = new AttributeService(rockContext); var avService = new AttributeValueService(rockContext); var personEntityTypeId = EntityTypeCache.Read(Rock.SystemGuid.EntityType.PERSON.AsGuid()).Id; var attribute = aService.Queryable().Where(a => a.Key == "GivingEnvelopeNumber" && a.EntityTypeId == personEntityTypeId).FirstOrDefault(); if (attribute != null) { var personIds = avService.Queryable().Where(av => av.AttributeId == attribute.Id && av.Value.Equals(term)).Select(av => av.EntityId); people = personService.Queryable().Where(p => personIds.Contains(p.Id)); } break; } case ("dob"): { term = term.ToLower(); List <DateTime?> birthDateList = new List <DateTime?>(); var birthDates = personService.Queryable().Where(p => p.BirthDate.HasValue).Select(p => p.BirthDate).Distinct().AsEnumerable(); var shortDateSearch = birthDates.Where(p => p.Value.ToString("d").ToLower().Contains(term) || p.Value.ToString("MM/dd/yyyy").ToLower().Contains(term)); var longDateSearch = birthDates.Where(p => p.Value.ToString("MMMM d, yyyy").ToLower().Contains(term)); if (shortDateSearch.Union(longDateSearch).Any()) { birthDateList = shortDateSearch.Union(longDateSearch).Distinct().ToList(); } else { // Just get crazy with things (Yep, you can find out who was born on a Tuesday) var longestDateSearch = birthDates.Where(p => p.Value.ToString("D").ToLower().Contains(term)); birthDateList = longestDateSearch.Distinct().ToList(); } gPeople.Columns[3].Visible = true; people = personService.Queryable().Where(p => birthDateList.Contains(p.BirthDate)); break; } } SortProperty sortProperty = gPeople.SortProperty; if (sortProperty != null) { people = people.Sort(sortProperty); } else { people = people.OrderBy(p => p.LastName).ThenBy(p => p.FirstName); } Guid familyGuid = new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY); Guid homeAddressTypeGuid = new Guid(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME); var personList = people.Select(p => new PersonSearchResult { Id = p.Id, FirstName = p.FirstName, NickName = p.NickName, LastName = p.LastName, BirthDate = p.BirthDate, BirthYear = p.BirthYear, BirthMonth = p.BirthMonth, BirthDay = p.BirthDay, ConnectionStatusValueId = p.ConnectionStatusValueId, RecordStatusValueId = p.RecordStatusValueId, RecordTypeValueId = p.RecordTypeValueId, SuffixValueId = p.SuffixValueId, IsDeceased = p.IsDeceased, Email = p.Email, Gender = p.Gender, PhotoId = p.PhotoId, CampusIds = p.Members .Where(m => m.Group.GroupType.Guid.Equals(familyGuid) && m.Group.CampusId.HasValue) .Select(m => m.Group.CampusId.Value) .ToList(), HomeAddresses = p.Members .Where(m => m.Group.GroupType.Guid == familyGuid) .SelectMany(m => m.Group.GroupLocations) .Where(gl => gl.GroupLocationTypeValue.Guid.Equals(homeAddressTypeGuid)) .Select(gl => gl.Location) }).ToList(); if (personList.Count == 1) { Response.Redirect(string.Format("~/Person/{0}", personList[0].Id), false); Context.ApplicationInstance.CompleteRequest(); } else { if (type.ToLower() == "name") { var similarNames = personService.GetSimilarNames(term, personList.Select(p => p.Id).ToList(), true); if (similarNames.Any()) { var hyperlinks = new List <string>(); foreach (string name in similarNames.Distinct()) { var pageRef = CurrentPageReference; pageRef.Parameters["SearchTerm"] = name; hyperlinks.Add(string.Format("<a href='{0}'>{1}</a>", pageRef.BuildUrl(), name)); } string altNames = string.Join(", ", hyperlinks); nbNotice.Text = string.Format("Other Possible Matches: {0}", altNames); nbNotice.Visible = true; } } _inactiveStatus = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE); gPeople.EntityTypeId = EntityTypeCache.GetId <Person>(); gPeople.DataSource = personList; gPeople.DataBind(); } } }
/// <summary> /// Maps the activity ministry. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapActivityMinistry(IQueryable <Row> tableData) { var lookupContext = new RockContext(); // Add an Attribute for the unique F1 Ministry Id int groupEntityTypeId = EntityTypeCache.Read("Rock.Model.Group").Id; var ministryAttributeId = new AttributeService(lookupContext).Queryable().Where(a => a.EntityTypeId == groupEntityTypeId && a.Key == "F1MinistryId").Select(a => a.Id).FirstOrDefault(); if (ministryAttributeId == 0) { var newMinistryAttribute = new Rock.Model.Attribute(); newMinistryAttribute.Key = "F1MinistryId"; newMinistryAttribute.Name = "F1 Ministry Id"; newMinistryAttribute.FieldTypeId = IntegerFieldTypeId; newMinistryAttribute.EntityTypeId = groupEntityTypeId; newMinistryAttribute.EntityTypeQualifierValue = string.Empty; newMinistryAttribute.EntityTypeQualifierColumn = string.Empty; newMinistryAttribute.Description = "The FellowshipOne identifier for the ministry that was imported"; newMinistryAttribute.DefaultValue = string.Empty; newMinistryAttribute.IsMultiValue = false; newMinistryAttribute.IsRequired = false; newMinistryAttribute.Order = 0; lookupContext.Attributes.Add(newMinistryAttribute); lookupContext.SaveChanges(DisableAudit); ministryAttributeId = newMinistryAttribute.Id; } // Get previously imported Ministries var importedMinistries = new AttributeValueService(lookupContext).GetByAttributeId(ministryAttributeId) .ToDictionary(t => t.Value.AsType <int?>(), t => t.EntityId); var newGroups = new List <Group>(); int completed = 0; int totalRows = tableData.Count(); int percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying ministry import ({0:N0} found).", totalRows)); foreach (var row in tableData) { int?ministryId = row["Ministry_ID"] as int?; if (ministryId != null && !importedMinistries.ContainsKey(ministryId)) { string ministryName = row["Ministry_Name"] as string; bool? ministryIsActive = row["Ministry_Active"] as bool?; int? activityId = row["Activity_ID"] as int?; string activityName = row["Activity_Name"] as string; bool? activityIsActive = row["Activity_Active"] as bool?; if (ministryName != null) { var ministry = new Group(); ministry.Name = ministryName.Trim(); ministry.IsActive = ministryIsActive ?? false; ministry.CampusId = CampusList.Where(c => ministryName.StartsWith(c.Name) || ministryName.StartsWith(c.ShortCode)) .Select(c => (int?)c.Id).FirstOrDefault(); // create new group for activity with ministry as parent group newGroups.Add(ministry); completed++; if (completed % percentage < 1) { int percentComplete = completed / percentage; ReportProgress(percentComplete, string.Format("{0:N0} ministries imported ({1}% complete).", completed, percentComplete)); } else if (completed % ReportingNumber < 1) { SaveActivityMinistry(newGroups); ReportPartialProgress(); newGroups.Clear(); } } } } if (newGroups.Any()) { SaveActivityMinistry(newGroups); } ReportProgress(100, string.Format("Finished ministry import: {0:N0} ministries imported.", completed)); }
/// <summary> /// Saves any attribute edits made to an attribute /// </summary> /// <param name="newAttribute">The new attribute.</param> /// <param name="entityTypeId">The entity type identifier.</param> /// <param name="entityTypeQualifierColumn">The entity type qualifier column.</param> /// <param name="entityTypeQualifierValue">The entity type qualifier value.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> /// <remarks> /// If a rockContext value is included, this method will save any previous changes made to the context /// </remarks> public static Rock.Model.Attribute SaveAttributeEdits(Rock.Model.Attribute newAttribute, int?entityTypeId, string entityTypeQualifierColumn, string entityTypeQualifierValue, RockContext rockContext = null) { rockContext = rockContext ?? new RockContext(); var internalAttributeService = new AttributeService(rockContext); var attributeQualifierService = new AttributeQualifierService(rockContext); var categoryService = new CategoryService(rockContext); // If attribute is not valid, return null if (!newAttribute.IsValid) { return(null); } // Create a attribute model that will be saved Rock.Model.Attribute attribute = null; // Check to see if this was an existing or new attribute if (newAttribute.Id > 0) { // If editing an existing attribute, remove all the old qualifiers in case they were changed foreach (var oldQualifier in attributeQualifierService.GetByAttributeId(newAttribute.Id).ToList()) { attributeQualifierService.Delete(oldQualifier); } rockContext.SaveChanges(); // Then re-load the existing attribute attribute = internalAttributeService.Get(newAttribute.Id); } if (attribute == null) { // If the attribute didn't exist, create it attribute = new Rock.Model.Attribute(); internalAttributeService.Add(attribute); } else { // If it did exist, set the new attribute ID and GUID since we're copying all properties in the next step newAttribute.Id = attribute.Id; newAttribute.Guid = attribute.Guid; } // Copy all the properties from the new attribute to the attribute model attribute.CopyPropertiesFrom(newAttribute); // Add any qualifiers foreach (var qualifier in newAttribute.AttributeQualifiers) { attribute.AttributeQualifiers.Add(new AttributeQualifier { Key = qualifier.Key, Value = qualifier.Value, IsSystem = qualifier.IsSystem }); } // Add any categories attribute.Categories.Clear(); foreach (var category in newAttribute.Categories) { attribute.Categories.Add(categoryService.Get(category.Id)); } attribute.EntityTypeId = entityTypeId; attribute.EntityTypeQualifierColumn = entityTypeQualifierColumn; attribute.EntityTypeQualifierValue = entityTypeQualifierValue; rockContext.SaveChanges(); if (attribute != null) { Rock.Web.Cache.AttributeCache.Flush(attribute.Id); // If this is a global attribute, flush all global attributes if (!entityTypeId.HasValue && entityTypeQualifierColumn == string.Empty && entityTypeQualifierValue == string.Empty) { Rock.Web.Cache.GlobalAttributesCache.Flush(); } } return(attribute); }
/// <summary> /// Generate the list of entities that reference this parent entity. These are entities that /// must be created after this entity has been created. /// </summary> /// <param name="parentEntity">The parent entity to find reverse-references to.</param> /// <param name="path">The property path that led us to this final property.</param> /// <param name="exporter">The object that handles filtering during an export process.</param> /// <returns>A list of KeyValuePairs that identify the property names and entites to be followed.</returns> protected List <KeyValuePair <string, IEntity> > FindChildEntities(IEntity parentEntity, EntityPath path, IExporter exporter) { List <KeyValuePair <string, IEntity> > children = new List <KeyValuePair <string, IEntity> >(); var properties = GetEntityProperties(parentEntity); // // Take a stab at any properties that are an ICollection<IEntity> and treat those // as child entities. // foreach (var property in properties) { if (property.PropertyType.GetInterface("IEnumerable") != null && property.PropertyType.GetGenericArguments().Length == 1) { if (typeof(IEntity).IsAssignableFrom(property.PropertyType.GetGenericArguments()[0]) && exporter.ShouldFollowPathProperty(path + new EntityPathComponent(parentEntity, property.Name))) { IEnumerable childEntities = ( IEnumerable )property.GetValue(parentEntity); foreach (IEntity childEntity in childEntities) { children.Add(new KeyValuePair <string, IEntity>(property.Name, childEntity)); } } } } // // We also need to pull in any attribute values. We have to pull attributes as well // since we might not have an actual value for that attribute yet and would need // it to pull the default value and definition. // if (parentEntity is IHasAttributes attributedEntity) { if (attributedEntity.Attributes == null) { attributedEntity.LoadAttributes(RockContext); } foreach (var item in attributedEntity.Attributes) { var attrib = new AttributeService(RockContext).Get(item.Value.Guid); children.Add(new KeyValuePair <string, IEntity>("Attributes", attrib)); var value = new AttributeValueService(RockContext).Queryable() .Where(v => v.AttributeId == attrib.Id && v.EntityId == attributedEntity.Id) .FirstOrDefault(); if (value != null) { children.Add(new KeyValuePair <string, IEntity>("AttributeValues", value)); } } } // // Allow for processors to adjust the list of children. // foreach (var processor in FindEntityProcessors(GetEntityType(parentEntity))) { processor.EvaluateChildEntities(parentEntity, children, this); } return(children); }
/// <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) { if (!Page.IsValid) { return; } GroupType groupType = null; var rockContext = new RockContext(); GroupTypeService groupTypeService = new GroupTypeService(rockContext); AttributeService attributeService = new AttributeService(rockContext); AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext); int?groupTypeId = hfGroupTypeId.ValueAsInt(); if (groupTypeId.HasValue && groupTypeId.Value > 0) { groupType = groupTypeService.Get(groupTypeId.Value); } bool newGroupType = false; if (groupType == null) { groupType = new GroupType(); groupTypeService.Add(groupType); var templatePurpose = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE.AsGuid()); if (templatePurpose != null) { groupType.GroupTypePurposeValueId = templatePurpose.Id; } newGroupType = true; } if (groupType != null) { groupType.Name = tbName.Text; groupType.Description = tbDescription.Text; groupType.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributeEdits, groupType); groupType.SetAttributeValue("core_checkin_AgeRequired", cbAgeRequired.Checked.ToString()); groupType.SetAttributeValue("core_checkin_GradeRequired", cbGradeRequired.Checked.ToString()); groupType.SetAttributeValue("core_checkin_CheckInType", ddlType.SelectedValue); groupType.SetAttributeValue("core_checkin_DisplayLocationCount", cbDisplayLocCount.Checked.ToString()); groupType.SetAttributeValue("core_checkin_EnableManagerOption", cbEnableManager.Checked.ToString()); groupType.SetAttributeValue("core_checkin_EnableOverride", cbEnableOverride.Checked.ToString()); groupType.SetAttributeValue("core_checkin_MaximumPhoneSearchLength", nbMaxPhoneLength.Text); groupType.SetAttributeValue("core_checkin_MaxSearchResults", nbMaxResults.Text); groupType.SetAttributeValue("core_checkin_MinimumPhoneSearchLength", nbMinPhoneLength.Text); groupType.SetAttributeValue("core_checkin_UseSameOptions", cbUseSameOptions.Checked.ToString()); groupType.SetAttributeValue("core_checkin_PhoneSearchType", ddlPhoneSearchType.SelectedValue); groupType.SetAttributeValue("core_checkin_RefreshInterval", nbRefreshInterval.Text); groupType.SetAttributeValue("core_checkin_RegularExpressionFilter", tbSearchRegex.Text); groupType.SetAttributeValue("core_checkin_ReuseSameCode", cbReuseCode.Checked.ToString()); var searchType = DefinedValueCache.Read(ddlSearchType.SelectedValueAsInt() ?? 0); if (searchType != null) { groupType.SetAttributeValue("core_checkin_SearchType", searchType.Guid.ToString()); } else { groupType.SetAttributeValue("core_checkin_SearchType", Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER); } groupType.SetAttributeValue("core_checkin_SecurityCodeLength", nbSecurityCodeLength.Text); groupType.SetAttributeValue("core_checkin_AutoSelectDaysBack", nbAutoSelectDaysBack.Text); rockContext.WrapTransaction(() => { rockContext.SaveChanges(); groupType.SaveAttributeValues(rockContext); }); if (newGroupType) { var pageRef = new PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId); pageRef.Parameters.Add("CheckinTypeId", groupType.Id.ToString()); NavigateToPage(pageRef); } else { groupType = groupTypeService.Get(groupType.Id); ShowReadonlyDetails(groupType); } GroupTypeCache.Flush(groupType.Id); Rock.CheckIn.KioskDevice.FlushAll(); } }
/// <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) { Device Device = null; var rockContext = new RockContext(); var deviceService = new DeviceService(rockContext); var attributeService = new AttributeService(rockContext); var locationService = new LocationService(rockContext); int DeviceId = int.Parse(hfDeviceId.Value); if (DeviceId != 0) { Device = deviceService.Get(DeviceId); } if (Device == null) { // Check for existing var existingDevice = deviceService.Queryable() .Where(d => d.Name == tbName.Text) .FirstOrDefault(); if (existingDevice != null) { nbDuplicateDevice.Text = string.Format("A device already exists with the name '{0}'. Please use a different device name.", existingDevice.Name); nbDuplicateDevice.Visible = true; } else { Device = new Device(); deviceService.Add(Device); } } if (Device != null) { Device.Name = tbName.Text; Device.Description = tbDescription.Text; Device.IPAddress = tbIpAddress.Text; Device.DeviceTypeValueId = ddlDeviceType.SelectedValueAsInt().Value; Device.PrintToOverride = (PrintTo)System.Enum.Parse(typeof(PrintTo), ddlPrintTo.SelectedValue); Device.PrinterDeviceId = ddlPrinter.SelectedValueAsInt(); Device.PrintFrom = (PrintFrom)System.Enum.Parse(typeof(PrintFrom), ddlPrintFrom.SelectedValue); if (Device.Location == null) { Device.Location = new Location(); } Device.Location.GeoPoint = geopPoint.SelectedValue; Device.Location.GeoFence = geopFence.SelectedValue; if (!Device.IsValid || !Page.IsValid) { // Controls will render the error messages return; } // Remove any deleted locations foreach (var location in Device.Locations .Where(l => !Locations.Keys.Contains(l.Id)) .ToList()) { Device.Locations.Remove(location); } // Add any new locations var existingLocationIDs = Device.Locations.Select(l => l.Id).ToList(); foreach (var location in locationService.Queryable() .Where(l => Locations.Keys.Contains(l.Id) && !existingLocationIDs.Contains(l.Id))) { Device.Locations.Add(location); } rockContext.SaveChanges(); Rock.CheckIn.KioskDevice.Flush(Device.Id); NavigateToParentPage(); } }
/// <summary> /// Shows the edit. /// </summary> public void ShowEdit() { int?filterId = hfDataFilterId.Value.AsIntegerOrNull(); if (ChannelGuid.HasValue) { var rockContext = new RockContext(); var channel = new ContentChannelService(rockContext).Queryable("ContentChannelType") .FirstOrDefault(c => c.Guid.Equals(ChannelGuid.Value)); if (channel != null) { cblStatus.Visible = channel.RequiresApproval && !channel.ContentChannelType.DisableStatus; var filterService = new DataViewFilterService(rockContext); DataViewFilter filter = null; if (filterId.HasValue) { filter = filterService.Get(filterId.Value); } if (filter == null || filter.ExpressionType == FilterExpressionType.Filter) { filter = new DataViewFilter(); filter.Guid = new Guid(); filter.ExpressionType = FilterExpressionType.GroupAll; } CreateFilterControl(channel, filter, true, rockContext); kvlOrder.CustomKeys = new Dictionary <string, string>(); kvlOrder.CustomKeys.Add("", ""); kvlOrder.CustomKeys.Add("Title", "Title"); kvlOrder.CustomKeys.Add("Priority", "Priority"); kvlOrder.CustomKeys.Add("Status", "Status"); kvlOrder.CustomKeys.Add("StartDateTime", "Start"); kvlOrder.CustomKeys.Add("ExpireDateTime", "Expire"); kvlOrder.CustomKeys.Add("Order", "Order"); string currentMetaDescriptionAttribute = GetAttributeValue("MetaDescriptionAttribute") ?? string.Empty; string currentMetaImageAttribute = GetAttributeValue("MetaImageAttribute") ?? string.Empty; // add channel attributes channel.LoadAttributes(); foreach (var attribute in channel.Attributes) { var field = attribute.Value.FieldType.Field; string computedKey = "C^" + attribute.Key; } // add item attributes AttributeService attributeService = new AttributeService(rockContext); var itemAttributes = attributeService.GetByEntityTypeId(new ContentChannelItem().TypeId).AsQueryable() .Where(a => ( a.EntityTypeQualifierColumn.Equals("ContentChannelTypeId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(channel.ContentChannelTypeId.ToString()) ) || ( a.EntityTypeQualifierColumn.Equals("ContentChannelId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(channel.Id.ToString()) )) .OrderByDescending(a => a.EntityTypeQualifierColumn) .ThenBy(a => a.Order) .ToList(); foreach (var attribute in itemAttributes) { string attrKey = "Attribute:" + attribute.Key; if (!kvlOrder.CustomKeys.ContainsKey(attrKey)) { kvlOrder.CustomKeys.Add("Attribute:" + attribute.Key, attribute.Name); string computedKey = "I^" + attribute.Key; var field = attribute.FieldType.Name; } } } } }
private List <Rock.Model.Workflow> GetWorkflows(RockContext rockContext) { EntitySetService entitySetService = new EntitySetService(rockContext); var entitySet = entitySetService.Get(PageParameter("EntitySetId").AsInteger()); var workflowEntityId = EntityTypeCache.GetId(typeof(Rock.Model.Workflow)); if (entitySet == null || entitySet.EntityTypeId != workflowEntityId) { return(null); } WorkflowService workflowService = new WorkflowService(rockContext); var workflowQueryable = workflowService.Queryable(); var qry = entitySet.Items .Join(workflowQueryable, i => i.EntityId, w => w.Id, (i, w) => w); var firstWorkflow = qry.FirstOrDefault(); if (firstWorkflow == null) { return(null); } var workflowTypeId = firstWorkflow.WorkflowTypeId; AttributeService attributeService = new AttributeService(rockContext); AttributeValueService attributeValueService = new AttributeValueService(rockContext); var attributeQueryable = attributeService.Queryable() .Where(a => a.EntityTypeId == workflowEntityId && a.EntityTypeQualifierColumn == "WorkflowTypeId" && a.EntityTypeQualifierValue == workflowTypeId.ToString()) .Select(a => a.Id); var attributeValueQueryable = attributeValueService.Queryable() .Where(av => attributeQueryable.Contains(av.AttributeId)); var mixedItems = qry.GroupJoin(attributeValueQueryable, w => w.Id, av => av.EntityId, (w, av) => new { Workflow = w, AttributeValues = av }) .ToList(); Dictionary <string, AttributeCache> attributes = new Dictionary <string, AttributeCache>(); foreach (var id in attributeQueryable.ToList()) { var attributeCache = AttributeCache.Get(id); if (attributeCache != null) { attributes[attributeCache.Key] = attributeCache; } } var workflows = new List <Rock.Model.Workflow>(); foreach (var item in mixedItems) { var workflow = item.Workflow; workflow.Attributes = attributes; workflow.AttributeValues = new Dictionary <string, AttributeValueCache>(); foreach (var attribute in attributes) { var attributeValue = item.AttributeValues.Where(av => av.AttributeKey == attribute.Key).FirstOrDefault(); workflow.AttributeValues[attribute.Key] = attributeValue != null ? new AttributeValueCache(attributeValue) : new AttributeValueCache(); } workflows.Add(workflow); } return(workflows); }
/// <summary> /// Shows the edit details. /// </summary> /// <param name="site">The site.</param> private void ShowEditDetails(Rock.Model.Site site) { if (site.Id == 0) { nbDefaultPageNotice.Visible = true; lReadOnlyTitle.Text = ActionTitle.Add(Rock.Model.Site.FriendlyTypeName).FormatAsHtmlTitle(); } else { nbDefaultPageNotice.Visible = false; lReadOnlyTitle.Text = site.Name.FormatAsHtmlTitle(); } SetEditMode(true); LoadDropDowns(); tbSiteName.ReadOnly = site.IsSystem; tbSiteName.Text = site.Name; tbDescription.ReadOnly = site.IsSystem; tbDescription.Text = site.Description; ddlTheme.Enabled = !site.IsSystem; ddlTheme.SetValue(site.Theme); imgSiteIcon.BinaryFileId = site.FavIconBinaryFileId; imgSiteLogo.BinaryFileId = site.SiteLogoBinaryFileId; cbIsActive.Checked = site.IsActive; if (site.DefaultPageRoute != null) { ppDefaultPage.SetValue(site.DefaultPageRoute); } else { ppDefaultPage.SetValue(site.DefaultPage); } if (site.LoginPageRoute != null) { ppLoginPage.SetValue(site.LoginPageRoute); } else { ppLoginPage.SetValue(site.LoginPage); } if (site.ChangePasswordPageRoute != null) { ppChangePasswordPage.SetValue(site.ChangePasswordPageRoute); } else { ppChangePasswordPage.SetValue(site.ChangePasswordPage); } if (site.CommunicationPageRoute != null) { ppCommunicationPage.SetValue(site.CommunicationPageRoute); } else { ppCommunicationPage.SetValue(site.CommunicationPage); } if (site.RegistrationPageRoute != null) { ppRegistrationPage.SetValue(site.RegistrationPageRoute); } else { ppRegistrationPage.SetValue(site.RegistrationPage); } if (site.PageNotFoundPageRoute != null) { ppPageNotFoundPage.SetValue(site.PageNotFoundPageRoute); } else { ppPageNotFoundPage.SetValue(site.PageNotFoundPage); } tbErrorPage.Text = site.ErrorPage; tbSiteDomains.Text = string.Join("\n", site.SiteDomains.OrderBy(d => d.Order).Select(d => d.Domain).ToArray()); tbGoogleAnalytics.Text = site.GoogleAnalyticsCode; cbRequireEncryption.Checked = site.RequiresEncryption; cbEnableForShortening.Checked = site.EnabledForShortening; cbEnableMobileRedirect.Checked = site.EnableMobileRedirect; ppMobilePage.SetValue(site.MobilePage); tbExternalURL.Text = site.ExternalUrl; tbAllowedFrameDomains.Text = site.AllowedFrameDomains; cbRedirectTablets.Checked = site.RedirectTablets; cbEnablePageViews.Checked = site.EnablePageViews; int channelMediumWebsiteValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id; var interactionChannelForSite = new InteractionChannelService(new RockContext()).Queryable() .Where(a => a.ChannelTypeMediumValueId == channelMediumWebsiteValueId && a.ChannelEntityId == site.Id).FirstOrDefault(); if (interactionChannelForSite != null) { nbPageViewRetentionPeriodDays.Text = interactionChannelForSite.RetentionDuration.ToString(); } cbEnableIndexing.Checked = site.IsIndexEnabled; tbIndexStartingLocation.Text = site.IndexStartingLocation; cbEnableExclusiveRoutes.Checked = site.EnableExclusiveRoutes; // disable the indexing features if indexing on site is disabled var siteEntityType = EntityTypeCache.Get("Rock.Model.Site"); if (siteEntityType != null && !siteEntityType.IsIndexingEnabled) { cbEnableIndexing.Visible = false; } var attributeService = new AttributeService(new RockContext()); var siteIdQualifierValue = site.Id.ToString(); PageAttributesState = attributeService.GetByEntityTypeId(new Page().TypeId, true).AsQueryable() .Where(a => a.EntityTypeQualifierColumn.Equals("SiteId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(siteIdQualifierValue)) .OrderBy(a => a.Order) .ThenBy(a => a.Name) .ToList(); BindPageAttributesGrid(); SetControlsVisiblity(); site.LoadAttributes(); avcAttributes.AddEditControls(site, Rock.Security.Authorization.EDIT, CurrentPerson); }
/// <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) { BinaryFile binaryFile; var rockContext = new RockContext(); BinaryFileService binaryFileService = new BinaryFileService(rockContext); AttributeService attributeService = new AttributeService(rockContext); int?prevBinaryFileTypeId = null; int binaryFileId = int.Parse(hfBinaryFileId.Value); if (binaryFileId == 0) { binaryFile = new BinaryFile(); binaryFileService.Add(binaryFile); } else { binaryFile = binaryFileService.Get(binaryFileId); prevBinaryFileTypeId = binaryFile != null ? binaryFile.BinaryFileTypeId : (int?)null; } // if a new file was uploaded, copy the uploaded file to this binaryFile (uploaded files are always new temporary binaryFiles) if (fsFile.BinaryFileId != binaryFile.Id) { var uploadedBinaryFile = binaryFileService.Get(fsFile.BinaryFileId ?? 0); if (uploadedBinaryFile != null) { binaryFile.BinaryFileTypeId = uploadedBinaryFile.BinaryFileTypeId; binaryFile.FileSize = uploadedBinaryFile.FileSize; var memoryStream = new MemoryStream(); uploadedBinaryFile.ContentStream.CopyTo(memoryStream); binaryFile.ContentStream = memoryStream; } } binaryFile.IsTemporary = false; binaryFile.FileName = tbName.Text; binaryFile.Description = tbDescription.Text; binaryFile.MimeType = tbMimeType.Text; binaryFile.BinaryFileTypeId = ddlBinaryFileType.SelectedValueAsInt(); binaryFile.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFile); if (!Page.IsValid) { return; } if (!binaryFile.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { foreach (var id in OrphanedBinaryFileIdList) { var tempBinaryFile = binaryFileService.Get(id); if (tempBinaryFile != null && tempBinaryFile.IsTemporary) { binaryFileService.Delete(tempBinaryFile); } } rockContext.SaveChanges(); binaryFile.SaveAttributeValues(rockContext); }); Rock.CheckIn.KioskLabel.Flush(binaryFile.Guid); if (!prevBinaryFileTypeId.Equals(binaryFile.BinaryFileTypeId)) { var checkInBinaryFileType = new BinaryFileTypeService(rockContext) .Get(Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL.AsGuid()); if (checkInBinaryFileType != null && ( (prevBinaryFileTypeId.HasValue && prevBinaryFileTypeId.Value == checkInBinaryFileType.Id) || (binaryFile.BinaryFileTypeId.HasValue && binaryFile.BinaryFileTypeId.Value == checkInBinaryFileType.Id))) { Rock.CheckIn.KioskDevice.FlushAll(); } } NavigateToParentPage(); }
/// <summary>Process all leagues (programs) from LeagueApps.</summary> /// <param name="message">The message that is returned depending on the result.</param> /// <param name="state">The state of the process.</param> /// <returns><see cref="WorkerResultStatus"/></returns> public void Execute(IJobExecutionContext context) { RockContext dbContext = new RockContext(); GroupService groupService = new GroupService(dbContext); AttributeService attributeService = new AttributeService(dbContext); AttributeValueService attributeValueService = new AttributeValueService(dbContext); GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(dbContext); DefinedValueService definedValueService = new DefinedValueService(dbContext); DefinedTypeService definedTypeService = new DefinedTypeService(dbContext); BinaryFileService binaryFileService = new BinaryFileService(dbContext); // Get the datamap for loading attributes JobDataMap dataMap = context.JobDetail.JobDataMap; var warnings = string.Empty; var processed = 0; try { var apiClient = new APIClient(); var settings = SettingsComponent.GetComponent <LeagueAppsSettings>(); //Group Attributes var parentGroup = groupService.Get(settings.GetAttributeValue(Constants.ParentGroup).AsGuid()); var yearGroupType = GroupTypeCache.Get(settings.GetAttributeValue(Constants.YearGroupType).AsGuid()); var categoryGroupType = GroupTypeCache.Get(settings.GetAttributeValue(Constants.CategoryGroupType).AsGuid()); var leagueGroupType = GroupTypeCache.Get(settings.GetAttributeValue(Constants.LeagueGroupType).AsGuid()); var sportsType = DefinedTypeCache.Get(Constants.SPORTS_TYPE.AsGuid()); var seasonsType = DefinedTypeCache.Get(Constants.SEASONS_TYPE.AsGuid()); var gendersType = DefinedTypeCache.Get(Constants.GENDERS_TYPE.AsGuid()); var groupMemberAttribute = AttributeCache.Get(settings.GetAttributeValue(Constants.LeagueGroupTeam).AsGuid()); //Person Attribute var personattribute = AttributeCache.Get(Constants.ATTRIBUTE_PERSON_USER_ID.AsGuid()); var connectionStatus = DefinedValueCache.Get(settings.GetAttributeValue(Constants.DefaultConnectionStatus).AsGuid()); var groupEntityType = EntityTypeCache.Get(typeof(Group)).Id; var programs = apiClient.GetPublic <List <Programs> >("/v1/sites/{siteid}/programs/current"); var groups = groupService.Queryable().Where(g => g.GroupTypeId == leagueGroupType.Id).ToList(); foreach (Contracts.Programs program in programs) { // Process the program Group league = null; Group league2 = null; Group league3 = null; var startdate = program.startTime; var mode = program.mode.ToLower(); mode = mode.First().ToString().ToUpper() + mode.Substring(1); var grandparentgroup = string.Format("{0}", startdate.Year); if (program.programId > 0) { league = groupService.Queryable().Where(l => l.Name == grandparentgroup && l.ParentGroupId == parentGroup.Id).FirstOrDefault(); if (league != null) { league2 = groupService.Queryable().Where(l => l.Name == mode && l.ParentGroupId == league.Id).FirstOrDefault(); if (league2 != null) { league3 = groupService.Queryable().Where(l => l.ForeignId == program.programId && l.GroupTypeId == leagueGroupType.Id && l.ParentGroupId == league2.Id).FirstOrDefault(); } } } Guid guid = Guid.NewGuid(); Guid guid2 = Guid.NewGuid(); Guid guid3 = Guid.NewGuid(); if (league == null) { // Create league grandparent Group Group leagueGPG = new Group(); leagueGPG.Name = grandparentgroup; leagueGPG.GroupTypeId = yearGroupType.Id; leagueGPG.ParentGroupId = parentGroup.Id; leagueGPG.IsSystem = false; leagueGPG.IsActive = true; leagueGPG.IsSecurityRole = false; leagueGPG.Order = 0; leagueGPG.Guid = guid; groupService.Add(leagueGPG); // Now save the league grandparent group dbContext.SaveChanges(); league = leagueGPG; } if (league2 == null) { // Create league parent Group Group leaguePG = new Group(); leaguePG.Name = mode; leaguePG.GroupTypeId = categoryGroupType.Id; leaguePG.ParentGroupId = league.Id; leaguePG.IsSystem = false; leaguePG.IsActive = true; leaguePG.IsSecurityRole = false; leaguePG.Order = 0; leaguePG.Guid = guid2; groupService.Add(leaguePG); // Now save the league parent group dbContext.SaveChanges(); league2 = leaguePG; } if (league3 == null) { // Create the league Group leagueG = new Group(); leagueG.Name = program.name; leagueG.GroupTypeId = leagueGroupType.Id; leagueG.ParentGroupId = league2.Id; leagueG.IsSystem = false; leagueG.IsActive = true; leagueG.IsSecurityRole = false; leagueG.Order = 0; leagueG.Description = HTMLConvertor.Convert(program.description); leagueG.ForeignId = program.programId; groupService.Add(leagueG); // Now save the league dbContext.SaveChanges(); league3 = leagueG; } else { groups.Remove(league3); } league3.LoadAttributes(); var sport = definedValueService.Queryable().Where(d => d.Value == program.sport && d.DefinedTypeId == sportsType.Id).FirstOrDefault(); var season = definedValueService.Queryable().Where(d => d.Value == program.season && d.DefinedTypeId == seasonsType.Id).FirstOrDefault(); var groupgender = definedValueService.Queryable().Where(d => d.Value == program.gender && d.DefinedTypeId == gendersType.Id).FirstOrDefault(); if (!sport.IsNull()) { league3.SetAttributeValue("Sport", sport.Guid); } if (!season.IsNull()) { league3.SetAttributeValue("Season", season.Guid); } league3.SetAttributeValue("ExperienceLevel", program.experienceLevel); if (!groupgender.IsNull()) { league3.SetAttributeValue("Gender", groupgender.Guid); } if (startdate != DateTime.MinValue) { league3.SetAttributeValue("StartTime", startdate); } if (program.publicRegistrationTime != DateTime.MinValue) { league3.SetAttributeValue("PublicRegistrationTime", program.publicRegistrationTime); } if (program.ageLimitEffectiveDate != DateTime.MinValue) { league3.SetAttributeValue("AgeLimitDate", program.ageLimitEffectiveDate.Date.ToString("d")); } league3.SetAttributeValue("ProgramURL", program.programUrlHtml); league3.SetAttributeValue("RegisterURL", program.registerUrlHtml); league3.SetAttributeValue("ScheduleURL", program.scheduleUrlHtml); league3.SetAttributeValue("StandingsURL", program.standingsUrlHtml); league3.SetAttributeValue("ProgramLogo", program.programLogo150); league3.SaveAttributeValues(); dbContext.SaveChanges(); var applicants = apiClient.GetPrivate <List <Registrations> >("/v2/sites/{siteid}/export/registrations-2?last-updated=0&last-id=0&program-id=" + program.programId); context.UpdateLastStatusMessage("Processing league " + (processed + 1) + " of " + programs.Count + ": " + program.startTime.Year + " > " + program.mode + " > " + program.name + " (" + applicants.Count + " members)."); foreach (Contracts.Registrations applicant in applicants) { // Use a fresh RockContext on every person/groupmember to keep things moving quickly using (var rockContext = new RockContext()) { PersonService personService = new PersonService(rockContext); GroupMemberService groupMemberService = new GroupMemberService(rockContext); LocationService locationService = new LocationService(rockContext); Person person = null; // 1. Try to load the person using the LeagueApps UserId var attributevalue = applicant.userId.ToString(); var personIds = attributeValueService.Queryable().Where(av => av.AttributeId == personattribute.Id && (av.Value == attributevalue || av.Value.Contains("|" + attributevalue + "|") || av.Value.StartsWith(attributevalue + "|"))).Select(av => av.EntityId); if (personIds.Count() == 1) { person = personService.Get(personIds.FirstOrDefault().Value); } // 2. If we don't have a person match then // just use the standard person match/create logic if (person == null) { var member = apiClient.GetPrivate <Member>("/v2/sites/{siteid}/members/" + applicant.userId); person = LeagueAppsHelper.CreatePersonFromMember(member, connectionStatus); } // Check to see if the group member already exists var groupmember = groupMemberService.GetByGroupIdAndPersonId(league3.Id, person.Id).FirstOrDefault(); if (groupmember == null) { Guid guid5 = Guid.NewGuid(); groupmember = new GroupMember(); groupmember.PersonId = person.Id; groupmember.GroupId = league3.Id; groupmember.IsSystem = false; groupmember.Guid = guid5; if (!String.IsNullOrEmpty(applicant.role)) { var role = applicant.role.Split('(')[0].Trim(); if (role == "FREEAGENT" || role == "PLAYER") { role = "Member"; } else if (role == "CAPTAIN") { role = "Captain"; } else if (role == "HEAD COACH" || role == "Head Coach") { role = "Head Coach"; } else if (role == "ASST. COACH" || role == "Asst. Coach") { role = "Asst. Coach"; } else { role = "Member"; } var grouprole = groupTypeRoleService.Queryable().Where(r => r.GroupTypeId == leagueGroupType.Id && r.Name == role).FirstOrDefault().Id; groupmember.GroupRoleId = grouprole; } else { groupmember.GroupRoleId = leagueGroupType.DefaultGroupRoleId.Value; } groupmember.GroupMemberStatus = GroupMemberStatus.Active; groupMemberService.Add(groupmember); rockContext.SaveChanges(); } // Make sure we update the team if necessary groupmember.LoadAttributes(); groupmember.SetAttributeValue(groupMemberAttribute.Key, applicant.team); groupmember.SaveAttributeValues(rockContext); } } processed++; } foreach (Group sportsleague in groups) { sportsleague.IsActive = false; dbContext.SaveChanges(); } } catch (Exception ex) { throw new Exception("LeagueApps Job Failed", ex); } finally { dbContext.SaveChanges(); } if (warnings.Length > 0) { throw new Exception(warnings); } context.Result = "Successfully imported " + processed + " leagues."; }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { RockContext rockContext = new RockContext(); var groupMemberService = new GroupMemberService(rockContext); var groupService = new GroupService(rockContext); var groupTypeService = new GroupTypeService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personService = new PersonService(rockContext); var personAliasService = new PersonAliasService(rockContext); var entityTypeService = new EntityTypeService(rockContext); var registrationRegistrantService = new RegistrationRegistrantService(rockContext); var eiogmService = new EventItemOccurrenceGroupMapService(rockContext); var groupLocationService = new GroupLocationService(rockContext); var locationService = new LocationService(rockContext); var signatureDocumentServce = new SignatureDocumentService(rockContext); var phoneNumberService = new PhoneNumberService(rockContext); int[] signatureDocumentIds = { }; if (!string.IsNullOrWhiteSpace(GetAttributeValue("SignatureDocumentTemplates"))) { signatureDocumentIds = Array.ConvertAll(GetAttributeValue("SignatureDocumentTemplates").Split(','), int.Parse); } Guid bbGroup = GetAttributeValue("Group").AsGuid(); Guid hsmGroupTypeGuid = GetAttributeValue("HSMGroupType").AsGuid(); int? hsmGroupTypeId = groupTypeService.Queryable().Where(gt => gt.Guid == hsmGroupTypeGuid).Select(gt => gt.Id).FirstOrDefault(); int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Rock.Model.Group).FullName).FirstOrDefault().Id; var group = new GroupService(rockContext).Get(bbGroup); var registrationTemplateIds = eiogmService.Queryable().Where(r => r.GroupId == group.Id).Select(m => m.RegistrationInstance.RegistrationTemplateId.ToString()).ToList(); hlGroup.NavigateUrl = "/group/" + group.Id; var attributeIds = attributeService.Queryable() .Where(a => (a.EntityTypeQualifierColumn == "GroupId" && a.EntityTypeQualifierValue == group.Id.ToString()) || (a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeQualifierValue == group.GroupTypeId.ToString()) || (a.EntityTypeQualifierColumn == "RegistrationTemplateId" && registrationTemplateIds.Contains(a.EntityTypeQualifierValue))) .Select(a => a.Id).ToList(); var gmTmpqry = groupMemberService.Queryable() .Where(gm => (gm.GroupId == group.Id)); var qry = gmTmpqry .Join(registrationRegistrantService.Queryable(), obj => obj.Id, rr => rr.GroupMemberId, (obj, rr) => new { GroupMember = obj, Person = obj.Person, RegistrationRegistrant = rr }) .GroupJoin(attributeValueService.Queryable(), obj => obj.GroupMember.Id, av => av.EntityId.Value, (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)) /*, Location = obj.Location */ }) .GroupJoin(attributeValueService.Queryable(), obj => obj.RegistrationRegistrant.Id, av => av.EntityId.Value, (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = obj.GroupMemberAttributeValues, RegistrationAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)) /*, Location = obj.Location */ }); var qry2 = gmTmpqry .GroupJoin( groupMemberService.Queryable() .Join(groupService.Queryable(), gm => new { Id = gm.GroupId, GroupTypeId = 10 }, g => new { g.Id, g.GroupTypeId }, (gm, g) => new { GroupMember = gm, Group = g }) .Join(groupLocationService.Queryable(), obj => new { GroupId = obj.Group.Id, GroupLocationTypeValueId = ( int? )19 }, gl => new { gl.GroupId, gl.GroupLocationTypeValueId }, (g, gl) => new { GroupMember = g.GroupMember, GroupLocation = gl }) .Join(locationService.Queryable(), obj => obj.GroupLocation.LocationId, l => l.Id, (obj, l) => new { GroupMember = obj.GroupMember, Location = l }), gm => gm.PersonId, glgm => glgm.GroupMember.PersonId, (obj, l) => new { GroupMember = obj, Location = l.Select(loc => loc.Location).FirstOrDefault() } ) .GroupJoin(signatureDocumentServce.Queryable() .Join(personAliasService.Queryable(), sd => sd.AppliesToPersonAliasId, pa => pa.Id, (sd, pa) => new { SignatureDocument = sd, Alias = pa }), obj => obj.GroupMember.PersonId, sd => sd.Alias.PersonId, (obj, sds) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = sds }) .GroupJoin(phoneNumberService.Queryable(), obj => obj.GroupMember.PersonId, p => p.PersonId, (obj, pn) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = obj.SignatureDocuments, PhoneNumbers = pn }); if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}PersonName", keyPrefix)))) { string personName = GetUserPreference(string.Format("{0}PersonName", keyPrefix)).ToLower(); qry = qry.ToList().Where(q => q.GroupMember.Person.FullName.ToLower().Contains(personName)).AsQueryable(); } decimal?lowerVal = GetUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix)).AsDecimalOrNull(); decimal?upperVal = GetUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix)).AsDecimalOrNull(); if (lowerVal != null && upperVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue >= lowerVal && q.RegistrationRegistrant.Registration.BalanceDue <= upperVal).AsQueryable(); } else if (lowerVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue >= lowerVal).AsQueryable(); } else if (upperVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue <= upperVal).AsQueryable(); } var stopwatch = new Stopwatch(); stopwatch.Start(); var tmp = qry.ToList(); var tmp2 = qry2.ToList(); lStats.Text = "Query Runtime: " + stopwatch.Elapsed; stopwatch.Reset(); stopwatch.Start(); var newQry = tmp.Select(g => new { Id = g.GroupMember.Id, RegisteredBy = new ModelValue <Person>(g.RegistrationRegistrant.Registration.PersonAlias.Person), person = g.Person, Registrant = new ModelValue <Person>(g.Person), Age = g.Person.Age, GraduationYear = g.Person.GraduationYear, RegistrationId = g.RegistrationRegistrant.RegistrationId, Group = new ModelValue <Rock.Model.Group>((Rock.Model.Group)g.GroupMember.Group), DOB = g.Person.BirthDate.HasValue ? g.Person.BirthDate.Value.ToShortDateString() : "", Address = new ModelValue <Location>(tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location).FirstOrDefault()), Email = g.Person.Email, Gender = g.Person.Gender, // (B & B Registration) GraduationYearProfile = g.Person.GraduationYear, // (Person Profile) HomePhone = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(), CellPhone = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(), GroupMemberData = new Func <GroupMemberAttributes>(() => { GroupMemberAttributes gma = new GroupMemberAttributes(g.GroupMember, g.Person, g.GroupMemberAttributeValues); return(gma); })(), RegistrantData = new Func <RegistrantAttributes>(() => { RegistrantAttributes row = new RegistrantAttributes(g.RegistrationRegistrant, g.RegistrationAttributeValues); return(row); })(), LegalRelease = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.SignatureDocuments).OrderByDescending(sd => sd.SignatureDocument.CreatedDateTime).Where(sd => signatureDocumentIds.Contains(sd.SignatureDocument.SignatureDocumentTemplateId)).Select(sd => sd.SignatureDocument.SignatureDocumentTemplate.Name.Contains("MINOR") ? "MINOR (" + sd.SignatureDocument.Status.ToString() + ")" : sd.SignatureDocument.SignatureDocumentTemplate.Name.Contains("ADULT") ? "ADULT (" + sd.SignatureDocument.Status.ToString() + ")" : "").FirstOrDefault(), // (highest level form on record, pulled from forms page in Rock) Departure = "TBD", // (hopefully based on bus, otherwise a dropdown with 1-4) Campus = group.Campus, // Role = group.ParentGroup.GroupType.Name.Contains("Serving") ? "Leader" : "Student", // HSMGroup = String.Join(", ", groupMemberService.Queryable().Where(gm => gm.PersonId == g.GroupMember.PersonId && gm.Group.GroupTypeId == hsmGroupTypeId && gm.GroupMemberStatus == GroupMemberStatus.Active).Select(gm => gm.Group.Name).ToList()) }).OrderBy(w => w.Registrant.Model.LastName).ToList().AsQueryable(); lStats.Text += "<br />Object Build Runtime: " + stopwatch.Elapsed; stopwatch.Stop(); gReport.GetRecipientMergeFields += GReport_GetRecipientMergeFields; var mergeFields = new List <String>(); mergeFields.Add("Id"); mergeFields.Add("RegisteredBy"); mergeFields.Add("Group"); mergeFields.Add("Registrant"); mergeFields.Add("Age"); mergeFields.Add("GraduationYear"); mergeFields.Add("DOB"); mergeFields.Add("Address"); mergeFields.Add("Email"); mergeFields.Add("Gender"); mergeFields.Add("GraduationYearProfile"); mergeFields.Add("HomePhone"); mergeFields.Add("CellPhone"); mergeFields.Add("GroupMemberData"); mergeFields.Add("RegistrantData"); mergeFields.Add("LegalRelease"); mergeFields.Add("Departure"); mergeFields.Add("Campus"); mergeFields.Add("Role"); mergeFields.Add("HSMGroup"); gReport.CommunicateMergeFields = mergeFields; if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}POA", keyPrefix)))) { string poa = GetUserPreference(string.Format("{0}POA", keyPrefix)); if (poa == "[Blank]") { poa = ""; } newQry = newQry.Where(q => q.GroupMemberData.POA == poa); } SortProperty sortProperty = gReport.SortProperty; if (sortProperty != null) { gReport.SetLinqDataSource(newQry.Sort(sortProperty)); } else { gReport.SetLinqDataSource(newQry.OrderBy(p => p.Registrant.Model.LastName)); } gReport.DataBind(); }
/// <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) { BinaryFileType binaryFileType; var rockContext = new RockContext(); BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService(rockContext); AttributeService attributeService = new AttributeService(rockContext); AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext); CategoryService categoryService = new CategoryService(rockContext); int binaryFileTypeId = int.Parse(hfBinaryFileTypeId.Value); if (binaryFileTypeId == 0) { binaryFileType = new BinaryFileType(); binaryFileTypeService.Add(binaryFileType); } else { binaryFileType = binaryFileTypeService.Get(binaryFileTypeId); } binaryFileType.Name = tbName.Text; binaryFileType.Description = tbDescription.Text; binaryFileType.IconCssClass = tbIconCssClass.Text; binaryFileType.AllowCaching = cbAllowCaching.Checked; binaryFileType.RequiresViewSecurity = cbRequiresViewSecurity.Checked; binaryFileType.MaxWidth = nbMaxWidth.Text.AsInteger(); binaryFileType.MaxHeight = nbMaxHeight.Text.AsInteger(); binaryFileType.PreferredFormat = ddlPreferredFormat.SelectedValueAsEnum <PreferredFormat>(); binaryFileType.PreferredResolution = ddlPreferredResolution.SelectedValueAsEnum <PreferredResolution>(); binaryFileType.PreferredColorDepth = ddlPreferredColorDepth.SelectedValueAsEnum <PreferredColorDepth>(); binaryFileType.PreferredRequired = cbPreferredRequired.Checked; if (!string.IsNullOrWhiteSpace(cpStorageType.SelectedValue)) { var entityTypeService = new EntityTypeService(rockContext); var storageEntityType = entityTypeService.Get(new Guid(cpStorageType.SelectedValue)); if (storageEntityType != null) { binaryFileType.StorageEntityTypeId = storageEntityType.Id; } } binaryFileType.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFileType); if (!binaryFileType.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); // get it back to make sure we have a good Id for it for the Attributes binaryFileType = binaryFileTypeService.Get(binaryFileType.Guid); /* Take care of Binary File Attributes */ var entityTypeId = Rock.Web.Cache.EntityTypeCache.Read(typeof(BinaryFile)).Id; // delete BinaryFileAttributes that are no longer configured in the UI var attributes = attributeService.Get(entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString()); var selectedAttributeGuids = BinaryFileAttributesState.Select(a => a.Guid); foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid))) { Rock.Web.Cache.AttributeCache.Flush(attr.Id); attributeService.Delete(attr); } rockContext.SaveChanges(); // add/update the BinaryFileAttributes that are assigned in the UI foreach (var attributeState in BinaryFileAttributesState) { Rock.Attribute.Helper.SaveAttributeEdits(attributeState, entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), rockContext); } // SaveAttributeValues for the BinaryFileType binaryFileType.SaveAttributeValues(rockContext); }); NavigateToParentPage(); }
/// <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) { bool hasValidationErrors = false; using (new UnitOfWorkScope()) { GroupTypeService groupTypeService = new GroupTypeService(); GroupService groupService = new GroupService(); AttributeService attributeService = new AttributeService(); int parentGroupTypeId = hfParentGroupTypeId.ValueAsInt(); var groupTypeUIList = new List <GroupType>(); foreach (var checkinGroupTypeEditor in phCheckinGroupTypes.Controls.OfType <CheckinGroupTypeEditor>().ToList()) { var groupType = checkinGroupTypeEditor.GetCheckinGroupType(); groupTypeUIList.Add(groupType); } var groupTypeDBList = new List <GroupType>(); var groupTypesToDelete = new List <GroupType>(); var groupsToDelete = new List <Group>(); var groupTypesToAddUpdate = new List <GroupType>(); var groupsToAddUpdate = new List <Group>(); GroupType parentGroupTypeDB = groupTypeService.Get(parentGroupTypeId); GroupType parentGroupTypeUI = parentGroupTypeDB.Clone(false); parentGroupTypeUI.ChildGroupTypes = groupTypeUIList; PopulateDeleteLists(groupTypesToDelete, groupsToDelete, parentGroupTypeDB, parentGroupTypeUI); PopulateAddUpdateLists(groupTypesToAddUpdate, groupsToAddUpdate, parentGroupTypeUI); int binaryFileFieldTypeID = new FieldTypeService().Get(new Guid(Rock.SystemGuid.FieldType.BINARY_FILE)).Id; int binaryFileTypeId = new BinaryFileTypeService().Get(new Guid(Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL)).Id; RockTransactionScope.WrapTransaction(() => { // delete in reverse order to get deepest child items first groupsToDelete.Reverse(); foreach (var groupToDelete in groupsToDelete) { groupService.Delete(groupToDelete, this.CurrentPersonId); groupService.Save(groupToDelete, this.CurrentPersonId); } // delete in reverse order to get deepest child items first groupTypesToDelete.Reverse(); foreach (var groupTypeToDelete in groupTypesToDelete) { groupTypeService.Delete(groupTypeToDelete, this.CurrentPersonId); groupTypeService.Save(groupTypeToDelete, this.CurrentPersonId); } // Add/Update grouptypes and groups that are in the UI // Note: We'll have to save all the groupTypes without changing the DB value of ChildGroupTypes, then come around again and save the ChildGroupTypes // since the ChildGroupTypes may not exist in the database yet foreach (GroupType groupTypeUI in groupTypesToAddUpdate) { GroupType groupTypeDB = groupTypeService.Get(groupTypeUI.Guid); if (groupTypeDB == null) { groupTypeDB = new GroupType(); groupTypeDB.Id = 0; groupTypeDB.Guid = groupTypeUI.Guid; } groupTypeDB.Name = groupTypeUI.Name; groupTypeDB.Order = groupTypeUI.Order; groupTypeDB.InheritedGroupTypeId = groupTypeUI.InheritedGroupTypeId; groupTypeDB.Attributes = groupTypeUI.Attributes; groupTypeDB.AttributeValues = groupTypeUI.AttributeValues; if (groupTypeDB.Id == 0) { groupTypeService.Add(groupTypeDB, this.CurrentPersonId); } if (!groupTypeDB.IsValid) { hasValidationErrors = true; CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupTypeEditor>().First(a => a.GroupTypeGuid == groupTypeDB.Guid); groupTypeEditor.ForceContentVisible = true; return; } groupTypeService.Save(groupTypeDB, this.CurrentPersonId); Rock.Attribute.Helper.SaveAttributeValues(groupTypeDB, this.CurrentPersonId); // get fresh from database to make sure we have Id so we can update the CheckinLabel Attributes groupTypeDB = groupTypeService.Get(groupTypeDB.Guid); // rebuild the CheckinLabel attributes from the UI (brute-force) foreach (var labelAttributeDB in CheckinGroupTypeEditor.GetCheckinLabelAttributes(groupTypeDB)) { var attribute = attributeService.Get(labelAttributeDB.Value.Guid); Rock.Web.Cache.AttributeCache.Flush(attribute.Id); attributeService.Delete(attribute, this.CurrentPersonId); } foreach (var checkinLabelAttributeInfo in GroupTypeCheckinLabelAttributesState[groupTypeUI.Guid]) { var attribute = new Rock.Model.Attribute(); attribute.AttributeQualifiers.Add(new AttributeQualifier { Key = "binaryFileType", Value = binaryFileTypeId.ToString() }); attribute.Guid = Guid.NewGuid(); attribute.FieldTypeId = binaryFileFieldTypeID; attribute.EntityTypeId = EntityTypeCache.GetId(typeof(GroupType)); attribute.EntityTypeQualifierColumn = "Id"; attribute.EntityTypeQualifierValue = groupTypeDB.Id.ToString(); attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileId.ToString(); attribute.Key = checkinLabelAttributeInfo.AttributeKey; attribute.Name = checkinLabelAttributeInfo.FileName; if (!attribute.IsValid) { hasValidationErrors = true; CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupTypeEditor>().First(a => a.GroupTypeGuid == groupTypeDB.Guid); groupTypeEditor.ForceContentVisible = true; return; } attributeService.Add(attribute, this.CurrentPersonId); attributeService.Save(attribute, this.CurrentPersonId); } } // Add/Update Groups foreach (var groupUI in groupsToAddUpdate) { Group groupDB = groupService.Get(groupUI.Guid); if (groupDB == null) { groupDB = new Group(); groupDB.Guid = groupUI.Guid; } groupDB.Name = groupUI.Name; // delete any GroupLocations that were removed in the UI foreach (var groupLocationDB in groupDB.GroupLocations.ToList()) { if (!groupUI.GroupLocations.Select(a => a.LocationId).Contains(groupLocationDB.LocationId)) { groupDB.GroupLocations.Remove(groupLocationDB); } } // add any GroupLocations that were added in the UI foreach (var groupLocationUI in groupUI.GroupLocations) { if (!groupDB.GroupLocations.Select(a => a.LocationId).Contains(groupLocationUI.LocationId)) { GroupLocation groupLocationDB = new GroupLocation { LocationId = groupLocationUI.LocationId }; groupDB.GroupLocations.Add(groupLocationDB); } } groupDB.Order = groupUI.Order; // get GroupTypeId from database in case the groupType is new groupDB.GroupTypeId = groupTypeService.Get(groupUI.GroupType.Guid).Id; groupDB.Attributes = groupUI.Attributes; groupDB.AttributeValues = groupUI.AttributeValues; if (groupDB.Id == 0) { groupService.Add(groupDB, this.CurrentPersonId); } if (!groupDB.IsValid) { hasValidationErrors = true; hasValidationErrors = true; CheckinGroupEditor groupEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupEditor>().First(a => a.GroupGuid == groupDB.Guid); groupEditor.ForceContentVisible = true; return; } groupService.Save(groupDB, this.CurrentPersonId); Rock.Attribute.Helper.SaveAttributeValues(groupDB, this.CurrentPersonId); } /* now that we have all the grouptypes saved, now lets go back and save them again with the current UI ChildGroupTypes */ // save main parentGroupType with current UI ChildGroupTypes parentGroupTypeDB.ChildGroupTypes = new List <GroupType>(); parentGroupTypeDB.ChildGroupTypes.Clear(); foreach (var childGroupTypeUI in parentGroupTypeUI.ChildGroupTypes) { var childGroupTypeDB = groupTypeService.Get(childGroupTypeUI.Guid); parentGroupTypeDB.ChildGroupTypes.Add(childGroupTypeDB); } groupTypeService.Save(parentGroupTypeDB, this.CurrentPersonId); // loop thru all the other GroupTypes in the UI and save their childgrouptypes foreach (var groupTypeUI in groupTypesToAddUpdate) { var groupTypeDB = groupTypeService.Get(groupTypeUI.Guid); groupTypeDB.ChildGroupTypes = new List <GroupType>(); groupTypeDB.ChildGroupTypes.Clear(); foreach (var childGroupTypeUI in groupTypeUI.ChildGroupTypes) { var childGroupTypeDB = groupTypeService.Get(childGroupTypeUI.Guid); groupTypeDB.ChildGroupTypes.Add(childGroupTypeDB); } groupTypeService.Save(groupTypeDB, this.CurrentPersonId); } }); } if (!hasValidationErrors) { NavigateToParentPage(); } }
public IList PerformActivity(long flowId, IDictionary attributeValues = null, String transitionName=null, Relations relations=null) { if (string.IsNullOrEmpty(ActorId)) { throw new AuthorizationException("you can't perform an activity because you are not authenticated"); } IList flows = null; try { using (ISession session = NHibernateHelper.OpenSession()) { DbSession dbSession = new DbSession(session); FlowImpl flow = flowRepository.GetFlow(flowId,dbSession); ActivityStateImpl activityState = (ActivityStateImpl)flow.Node; ExecutionContext executionContext = new ExecutionContext(); activityState.CheckAccess(attributeValues); attributeService = new AttributeService(flow,dbSession); attributeService.StoreAttributeValue(attributeValues); transitionService = new TransitionService(ActorId, dbSession); TransitionImpl transitionTo = transitionService.GetTransition(transitionName, activityState, dbSession); transitionService.ProcessTransition(transitionTo, flow, dbSession); session.Flush(); } } catch (ExecutionException e) { throw e; } catch (Exception e) { throw new SystemException("uncaught exception : " + e.Message, e); } finally { //ServiceLocator.Instance.Release(organisationComponent); } return flows; }
/// <summary> /// Maps the specified folder. /// </summary> /// <param name="folder">The folder.</param> /// <param name="ministryFileType">Type of the ministry file.</param> public int Map(ZipArchive folder, BinaryFileType ministryFileType) { var lookupContext = new RockContext(); var personEntityTypeId = EntityTypeCache.GetId <Person>(); var binaryFileTypeService = new BinaryFileTypeService(lookupContext); var fileFieldTypeId = FieldTypeCache.Get(Rock.SystemGuid.FieldType.FILE.AsGuid(), lookupContext).Id; var backgroundFieldTypeId = FieldTypeCache.Get(Rock.SystemGuid.FieldType.BACKGROUNDCHECK.AsGuid(), lookupContext).Id; var existingAttributes = new AttributeService(lookupContext).GetByFieldTypeId(fileFieldTypeId) .Where(a => a.EntityTypeId == personEntityTypeId) .ToDictionary(a => a.Key, a => a); var backgroundCheckFileAttributes = new AttributeService(lookupContext).GetByFieldTypeId(backgroundFieldTypeId) .Where(a => a.EntityTypeId == personEntityTypeId) .ToDictionary(a => a.Key, a => a); foreach (var backgroundCheckFileAttribute in backgroundCheckFileAttributes) { if (!existingAttributes.ContainsKey(backgroundCheckFileAttribute.Key)) { existingAttributes.Add(backgroundCheckFileAttribute.Key, backgroundCheckFileAttribute.Value); } } var emptyJsonObject = "{}"; var newFileList = new List <DocumentKeys>(); var completedItems = 0; var totalRows = folder.Entries.Count; var percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, string.Format("Verifying ministry document import ({0:N0} found)", totalRows)); foreach (var file in folder.Entries.OrderBy(f => f.Name)) { var fileExtension = Path.GetExtension(file.Name); if (FileTypeBlackList.Contains(fileExtension)) { LogException("Binary File Import", string.Format("{0} filetype not allowed ({1})", fileExtension, file.Name)); continue; } var nameWithoutExtension = file.Name.ReplaceLastOccurrence(fileExtension, string.Empty); var parsedFileName = nameWithoutExtension.Split('_'); // Ministry docs should follow this pattern: // 0. Firstname // 1. Lastname // 2. ForeignId // 3. Filename // 4. Doc Id if (parsedFileName.Length < 3) { break; } var personForeignId = parsedFileName[2].AsType <int?>(); var personKeys = ImportedPeople.FirstOrDefault(p => p.PersonForeignId == personForeignId); if (personKeys != null) { var attributeName = string.Empty; var documentForeignId = string.Empty; if (parsedFileName.Count() > 4) { attributeName = parsedFileName[3]; documentForeignId = parsedFileName[4]; } else { var filename = parsedFileName[3].ReplaceLastOccurrence(fileExtension, string.Empty); attributeName = Regex.Replace(filename, "\\d{4,}[.\\w]+$", string.Empty); documentForeignId = Regex.Match(filename, "\\d+$").Value; } // append "Document" to attribute name to create unique attributes // this matches core attribute "Background Check Document" attributeName = !attributeName.EndsWith("Document", StringComparison.OrdinalIgnoreCase) ? string.Format("{0} Document", attributeName) : attributeName; var attributeKey = attributeName.RemoveSpecialCharacters(); Attribute fileAttribute = null; var attributeBinaryFileType = ministryFileType; if (!existingAttributes.ContainsKey(attributeKey)) { fileAttribute = new Attribute { FieldTypeId = fileFieldTypeId, EntityTypeId = personEntityTypeId, EntityTypeQualifierColumn = string.Empty, EntityTypeQualifierValue = string.Empty, Key = attributeKey, Name = attributeName, Description = string.Format("{0} created by binary file import", attributeName), IsGridColumn = false, IsMultiValue = false, IsRequired = false, AllowSearch = false, IsSystem = false, Order = 0 }; fileAttribute.AttributeQualifiers.Add(new AttributeQualifier() { Key = "binaryFileType", Value = ministryFileType.Guid.ToString() }); lookupContext.Attributes.Add(fileAttribute); lookupContext.SaveChanges(); existingAttributes.Add(fileAttribute.Key, fileAttribute); } else { // if attribute already exists in Rock, override default file type with the Rock-specified file type fileAttribute = existingAttributes[attributeKey]; var attributeBinaryFileTypeGuid = fileAttribute.AttributeQualifiers.FirstOrDefault(q => q.Key.Equals("binaryFileType")); if (attributeBinaryFileTypeGuid != null) { attributeBinaryFileType = binaryFileTypeService.Get(attributeBinaryFileTypeGuid.Value.AsGuid()); } } var rockFile = new Rock.Model.BinaryFile { IsSystem = false, IsTemporary = false, MimeType = GetMIMEType(file.Name), BinaryFileTypeId = attributeBinaryFileType.Id, FileName = file.Name, Description = string.Format("Imported as {0}", file.Name), CreatedDateTime = file.LastWriteTime.DateTime, ModifiedDateTime = file.LastWriteTime.DateTime, CreatedByPersonAliasId = ImportPersonAliasId, ForeignKey = documentForeignId, ForeignId = documentForeignId.AsIntegerOrNull() }; rockFile.SetStorageEntityTypeId(attributeBinaryFileType.StorageEntityTypeId); rockFile.StorageEntitySettings = emptyJsonObject; if (attributeBinaryFileType.AttributeValues != null) { rockFile.StorageEntitySettings = attributeBinaryFileType.AttributeValues .ToDictionary(a => a.Key, v => v.Value.Value).ToJson(); } // use base stream instead of file stream to keep the byte[] // NOTE: if byte[] converts to a string it will corrupt the stream using (var fileContent = new StreamReader(file.Open())) { rockFile.ContentStream = new MemoryStream(fileContent.BaseStream.ReadBytesToEnd()); } newFileList.Add(new DocumentKeys() { PersonId = personKeys.PersonId, AttributeId = fileAttribute.Id, File = rockFile }); completedItems++; if (completedItems % percentage < 1) { var percentComplete = completedItems / percentage; ReportProgress(percentComplete, string.Format("{0:N0} ministry document files imported ({1}% complete).", completedItems, percentComplete)); } if (completedItems % ReportingNumber < 1) { SaveFiles(newFileList); // Reset list newFileList.Clear(); ReportPartialProgress(); } } } if (newFileList.Any()) { SaveFiles(newFileList); } ReportProgress(100, string.Format("Finished documents import: {0:N0} ministry documents imported.", completedItems)); return(completedItems); }