예제 #1
0
        /// <summary>
        /// Gs the binary file attributes_ show edit.
        /// </summary>
        /// <param name="attributeGuid">The attribute GUID.</param>
        protected void gBinaryFileAttributes_ShowEdit(Guid attributeGuid)
        {
            pnlDetails.Visible             = false;
            pnlBinaryFileAttribute.Visible = true;

            Attribute attribute;

            if (attributeGuid.Equals(Guid.Empty))
            {
                attribute             = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT).Id;
                edtBinaryFileAttributes.ActionTitle = ActionTitle.Add("attribute for binary files of type " + tbName.Text);
            }
            else
            {
                attribute = BinaryFileAttributesState.First(a => a.Guid.Equals(attributeGuid));
                edtBinaryFileAttributes.ActionTitle = ActionTitle.Edit("attribute for binary files of type " + tbName.Text);
            }

            edtBinaryFileAttributes.ReservedKeyNames = BinaryFileAttributesState.Where(a => !a.Guid.Equals(attributeGuid)).Select(a => a.Key).ToList();

            edtBinaryFileAttributes.SetAttributeProperties(attribute, typeof(BinaryFile));
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Get the current person alias if possible
            PersonAlias personAlias = null;

            if (HttpContext.Current != null && HttpContext.Current.Items.Contains("CurrentPerson"))
            {
                var currentPerson = HttpContext.Current.Items["CurrentPerson"] as Person;
                if (currentPerson != null && currentPerson.PrimaryAlias != null)
                {
                    personAlias = currentPerson.PrimaryAlias;

                    // Get the attribute to set
                    Guid guid = GetAttributeValue(action, "PersonAttribute").AsGuid();
                    if (!guid.IsEmpty())
                    {
                        var personAttribute = AttributeCache.Read(guid, rockContext);
                        if (personAttribute != null)
                        {
                            // If this is a person type attribute
                            if (personAttribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id)
                            {
                                SetWorkflowAttributeValue(action, guid, personAlias.Guid.ToString());
                            }
                            else if (personAttribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.TEXT.AsGuid(), rockContext).Id)
                            {
                                SetWorkflowAttributeValue(action, guid, currentPerson.FullName);
                            }
                        }
                    }
                }
            }

            return(true);
        }
        /// <summary>
        /// Executes the specified workflow action.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Get the attribute's guid
            Guid guid = GetAttributeValue(action, "PersonAttribute").AsGuid();

            if (!guid.IsEmpty())
            {
                // Get the attribute
                var attribute = AttributeCache.Read(guid, rockContext);
                if (attribute != null)
                {
                    if (attribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id)
                    {
                        // If attribute type is a person, value should be person alias id
                        Guid?personAliasGuid = action.GetWorklowAttributeValue(guid).AsGuidOrNull();
                        if (personAliasGuid.HasValue)
                        {
                            var personAlias = new PersonAliasService(rockContext).Queryable("Person")
                                              .Where(a => a.Guid.Equals(personAliasGuid.Value))
                                              .FirstOrDefault();
                            if (personAlias != null)
                            {
                                action.Activity.Workflow.InitiatorPersonAlias   = personAlias;
                                action.Activity.Workflow.InitiatorPersonAliasId = personAlias.Id;
                                action.AddLogEntry(string.Format("Assigned initiator to '{0}' ({1})", personAlias.Person.FullName, personAlias.Person.Id));
                                return(true);
                            }
                        }
                    }
                }
            }

            return(false);
        }
예제 #4
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            if (action.Activity.Workflow.InitiatorPersonAliasId.HasValue)
            {
                var personAlias = new PersonAliasService(rockContext)
                                  .Queryable().AsNoTracking()
                                  .Where(a => a.Id == action.Activity.Workflow.InitiatorPersonAliasId.Value)
                                  .FirstOrDefault();

                if (personAlias != null)
                {
                    // Get the attribute to set
                    Guid guid = GetAttributeValue(action, "PersonAttribute").AsGuid();
                    if (!guid.IsEmpty())
                    {
                        var personAttribute = AttributeCache.Read(guid, rockContext);
                        if (personAttribute != null)
                        {
                            // If this is a person type attribute
                            if (personAttribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id)
                            {
                                SetWorkflowAttributeValue(action, guid, personAlias.Guid.ToString());
                            }
                            else if (personAttribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.TEXT.AsGuid(), rockContext).Id)
                            {
                                SetWorkflowAttributeValue(action, guid, personAlias.Person.FullName);
                            }
                        }
                    }
                }
            }

            return(true);
        }
예제 #5
0
        /// <summary>
        /// Sends a background request to Protect My Ministry
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="workflow">The Workflow initiating the request.</param>
        /// <param name="personAttribute">The person attribute.</param>
        /// <param name="ssnAttribute">The SSN attribute.</param>
        /// <param name="requestTypeAttribute">The request type attribute.</param>
        /// <param name="billingCodeAttribute">The billing code attribute.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns>
        /// True/False value of whether the request was successfully sent or not
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        /// <remarks>
        /// Note: If the associated workflow type does not have attributes with the following keys, they
        /// will automatically be added to the workflow type configuration in order to store the results
        /// of the PMM background check request
        ///     RequestStatus:          The request status returned by PMM request
        ///     RequestMessage:         Any error messages returned by PMM request
        ///     ReportStatus:           The report status returned by PMM
        ///     ReportLink:             The location of the background report on PMM server
        ///     ReportRecommendation:   PMM's recomendataion
        ///     Report (BinaryFile):    The downloaded background report
        /// </remarks>
        public override bool SendRequest(RockContext rockContext, Model.Workflow workflow,
                                         AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute,
                                         AttributeCache billingCodeAttribute, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            try
            {
                // Check to make sure workflow is not null
                if (workflow == null)
                {
                    errorMessages.Add("The 'Protect My Ministry' background check provider requires a valid workflow.");
                    return(false);
                }

                // Get the person that the request is for
                Person person = null;
                if (personAttribute != null)
                {
                    Guid?personAliasGuid = workflow.GetAttributeValue(personAttribute.Key).AsGuidOrNull();
                    if (personAliasGuid.HasValue)
                    {
                        person = new PersonAliasService(rockContext).Queryable()
                                 .Where(p => p.Guid.Equals(personAliasGuid.Value))
                                 .Select(p => p.Person)
                                 .FirstOrDefault();
                        person.LoadAttributes(rockContext);
                    }
                }

                if (person == null)
                {
                    errorMessages.Add("The 'Protect My Ministry' background check provider requires the workflow to have a 'Person' attribute that contains the person who the background check is for.");
                    return(false);
                }

                string password = Encryption.DecryptString(GetAttributeValue("Password"));

                XElement rootElement = new XElement("OrderXML",
                                                    new XElement("Method", "SEND ORDER"),
                                                    new XElement("Authentication",
                                                                 new XElement("Username", GetAttributeValue("UserName")),
                                                                 new XElement("Password", password)
                                                                 )
                                                    );

                if (GetAttributeValue("TestMode").AsBoolean())
                {
                    rootElement.Add(new XElement("TestMode", "YES"));
                }

                rootElement.Add(new XElement("ReturnResultURL", GetAttributeValue("ReturnURL")));

                XElement orderElement = new XElement("Order");
                rootElement.Add(orderElement);

                if (billingCodeAttribute != null)
                {
                    string billingCode = workflow.GetAttributeValue(billingCodeAttribute.Key);
                    Guid?  campusGuid  = billingCode.AsGuidOrNull();
                    if (campusGuid.HasValue)
                    {
                        var campus = CampusCache.Read(campusGuid.Value);
                        if (campus != null)
                        {
                            billingCode = campus.Name;
                        }
                    }
                    orderElement.Add(new XElement("BillingReferenceCode", billingCode));
                }

                XElement subjectElement = new XElement("Subject",
                                                       new XElement("FirstName", person.FirstName),
                                                       new XElement("MiddleName", person.MiddleName),
                                                       new XElement("LastName", person.LastName)
                                                       );
                orderElement.Add(subjectElement);

                if (person.SuffixValue != null)
                {
                    subjectElement.Add(new XElement("Generation", person.SuffixValue.Value));
                }
                if (person.BirthDate.HasValue)
                {
                    subjectElement.Add(new XElement("DOB", person.BirthDate.Value.ToString("MM/dd/yyyy")));
                }

                if (ssnAttribute != null)
                {
                    string ssn = Encryption.DecryptString(workflow.GetAttributeValue(ssnAttribute.Key)).AsNumeric();
                    if (!string.IsNullOrWhiteSpace(ssn) && ssn.Length == 9)
                    {
                        subjectElement.Add(new XElement("SSN", ssn.Insert(5, "-").Insert(3, "-")));
                    }
                }

                if (person.Gender == Gender.Male)
                {
                    subjectElement.Add(new XElement("Gender", "Male"));
                }
                if (person.Gender == Gender.Female)
                {
                    subjectElement.Add(new XElement("Gender", "Female"));
                }

                string dlNumber = person.GetAttributeValue("com.sparkdevnetwork.DLNumber");
                if (!string.IsNullOrWhiteSpace(dlNumber))
                {
                    subjectElement.Add(new XElement("DLNumber", dlNumber));
                }

                if (!string.IsNullOrWhiteSpace(person.Email))
                {
                    subjectElement.Add(new XElement("EmailAddress", person.Email));
                }

                var homelocation = person.GetHomeLocation();
                if (homelocation != null)
                {
                    subjectElement.Add(new XElement("CurrentAddress",
                                                    new XElement("StreetAddress", homelocation.Street1),
                                                    new XElement("City", homelocation.City),
                                                    new XElement("State", homelocation.State),
                                                    new XElement("Zipcode", homelocation.PostalCode)
                                                    ));
                }

                XElement aliasesElement = new XElement("Aliases");
                if (person.NickName != person.FirstName)
                {
                    aliasesElement.Add(new XElement("Alias", new XElement("FirstName", person.NickName)));
                }

                foreach (var previousName in person.GetPreviousNames())
                {
                    aliasesElement.Add(new XElement("Alias", new XElement("LastName", previousName.LastName)));
                }

                if (aliasesElement.HasElements)
                {
                    subjectElement.Add(aliasesElement);
                }

                DefinedValueCache pkgTypeDefinedValue = null;
                string            packageName         = "BASIC";
                string            county          = string.Empty;
                string            state           = string.Empty;
                string            mvrJurisdiction = string.Empty;
                string            mvrState        = string.Empty;

                if (requestTypeAttribute != null)
                {
                    pkgTypeDefinedValue = DefinedValueCache.Read(workflow.GetAttributeValue(requestTypeAttribute.Key).AsGuid());
                    if (pkgTypeDefinedValue != null)
                    {
                        if (pkgTypeDefinedValue.Attributes == null)
                        {
                            pkgTypeDefinedValue.LoadAttributes(rockContext);
                        }

                        packageName = pkgTypeDefinedValue.GetAttributeValue("PMMPackageName");
                        county      = pkgTypeDefinedValue.GetAttributeValue("DefaultCounty");
                        state       = pkgTypeDefinedValue.GetAttributeValue("DefaultState");
                        Guid?mvrJurisdictionGuid = pkgTypeDefinedValue.GetAttributeValue("MVRJurisdiction").AsGuidOrNull();
                        if (mvrJurisdictionGuid.HasValue)
                        {
                            var mvrJurisdictionDv = DefinedValueCache.Read(mvrJurisdictionGuid.Value);
                            if (mvrJurisdictionDv != null)
                            {
                                mvrJurisdiction = mvrJurisdictionDv.Value;
                                if (mvrJurisdiction.Length >= 2)
                                {
                                    mvrState = mvrJurisdiction.Left(2);
                                }
                            }
                        }

                        if (homelocation != null)
                        {
                            if (!string.IsNullOrWhiteSpace(homelocation.County) &&
                                pkgTypeDefinedValue.GetAttributeValue("SendHomeCounty").AsBoolean())
                            {
                                county = homelocation.County;
                            }

                            if (!string.IsNullOrWhiteSpace(homelocation.State))
                            {
                                if (pkgTypeDefinedValue.GetAttributeValue("SendHomeState").AsBoolean())
                                {
                                    state = homelocation.State;
                                }
                                if (pkgTypeDefinedValue.GetAttributeValue("SendHomeStateMVR").AsBoolean())
                                {
                                    mvrState = homelocation.State;
                                }
                            }
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(packageName))
                {
                    orderElement.Add(new XElement("PackageServiceCode", packageName,
                                                  new XAttribute("OrderId", workflow.Id.ToString())));

                    if (packageName.Trim().Equals("BASIC", StringComparison.OrdinalIgnoreCase) ||
                        packageName.Trim().Equals("PLUS", StringComparison.OrdinalIgnoreCase))
                    {
                        orderElement.Add(new XElement("OrderDetail",
                                                      new XAttribute("OrderId", workflow.Id.ToString()),
                                                      new XAttribute("ServiceCode", "combo")));
                    }
                }

                if (!string.IsNullOrWhiteSpace(county) ||
                    !string.IsNullOrWhiteSpace(state))
                {
                    orderElement.Add(new XElement("OrderDetail",
                                                  new XAttribute("OrderId", workflow.Id.ToString()),
                                                  new XAttribute("ServiceCode", string.IsNullOrWhiteSpace(county) ? "StateCriminal" : "CountyCrim"),
                                                  new XElement("County", county),
                                                  new XElement("State", state),
                                                  new XElement("YearsToSearch", 7),
                                                  new XElement("CourtDocsRequested", "NO"),
                                                  new XElement("RushRequested", "NO"),
                                                  new XElement("SpecialInstructions", ""))
                                     );
                }

                if (!string.IsNullOrWhiteSpace(mvrJurisdiction) && !string.IsNullOrWhiteSpace(mvrState))
                {
                    orderElement.Add(new XElement("OrderDetail",
                                                  new XAttribute("OrderId", workflow.Id.ToString()),
                                                  new XAttribute("ServiceCode", "MVR"),
                                                  new XElement("JurisdictionCode", mvrJurisdiction),
                                                  new XElement("State", mvrState))
                                     );
                }

                XDocument xdoc            = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), rootElement);
                var       requestDateTime = RockDateTime.Now;

                XDocument xResult          = PostToWebService(xdoc, GetAttributeValue("RequestURL"));
                var       responseDateTime = RockDateTime.Now;

                int?personAliasId = person.PrimaryAliasId;
                if (personAliasId.HasValue)
                {
                    // Create a background check file
                    using (var newRockContext = new RockContext())
                    {
                        var backgroundCheckService = new BackgroundCheckService(newRockContext);
                        var backgroundCheck        = backgroundCheckService.Queryable()
                                                     .Where(c =>
                                                            c.WorkflowId.HasValue &&
                                                            c.WorkflowId.Value == workflow.Id)
                                                     .FirstOrDefault();

                        if (backgroundCheck == null)
                        {
                            backgroundCheck = new Rock.Model.BackgroundCheck();
                            backgroundCheck.PersonAliasId = personAliasId.Value;
                            backgroundCheck.WorkflowId    = workflow.Id;
                            backgroundCheckService.Add(backgroundCheck);
                        }

                        backgroundCheck.RequestDate = RockDateTime.Now;

                        // Clear any SSN nodes before saving XML to record
                        foreach (var xSSNElement in xdoc.Descendants("SSN"))
                        {
                            xSSNElement.Value = "XXX-XX-XXXX";
                        }
                        foreach (var xSSNElement in xResult.Descendants("SSN"))
                        {
                            xSSNElement.Value = "XXX-XX-XXXX";
                        }

                        backgroundCheck.ResponseXml = string.Format(@"
Request XML ({0}): 
------------------------ 
{1}

Response XML ({2}): 
------------------------ 
{3}

", requestDateTime, xdoc.ToString(), responseDateTime, xResult.ToString());
                        newRockContext.SaveChanges();
                    }
                }

                using (var newRockContext = new RockContext())
                {
                    var handledErrorMessages = new List <string>();

                    bool createdNewAttribute = false;
                    if (_HTTPStatusCode == HttpStatusCode.OK)
                    {
                        var xOrderXML = xResult.Elements("OrderXML").FirstOrDefault();
                        if (xOrderXML != null)
                        {
                            var xStatus = xOrderXML.Elements("Status").FirstOrDefault();
                            if (xStatus != null)
                            {
                                if (SaveAttributeValue(workflow, "RequestStatus", xStatus.Value,
                                                       FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), newRockContext, null))
                                {
                                    createdNewAttribute = true;
                                }
                            }

                            handledErrorMessages.AddRange(xOrderXML.Elements("Message").Select(x => x.Value).ToList());
                            var xErrors = xOrderXML.Elements("Errors").FirstOrDefault();
                            if (xErrors != null)
                            {
                                handledErrorMessages.AddRange(xOrderXML.Elements("Message").Select(x => x.Value).ToList());
                            }

                            if (xResult.Root.Descendants().Count() > 0)
                            {
                                SaveResults(xResult, workflow, rockContext, false);
                            }
                        }
                    }
                    else
                    {
                        handledErrorMessages.Add("Invalid HttpStatusCode: " + _HTTPStatusCode.ToString());
                    }

                    if (handledErrorMessages.Any())
                    {
                        if (SaveAttributeValue(workflow, "RequestMessage", handledErrorMessages.AsDelimited(Environment.NewLine),
                                               FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), newRockContext, null))
                        {
                            createdNewAttribute = true;
                        }
                    }

                    newRockContext.SaveChanges();

                    if (createdNewAttribute)
                    {
                        AttributeCache.FlushEntityAttributes();
                    }

                    return(true);
                }
            }

            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, null);
                errorMessages.Add(ex.Message);
                return(false);
            }
        }
예제 #6
0
        /// <summary>
        /// Create an EntityField for an Attribute.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="limitToFilterableAttributes"></param>
        public static EntityField GetEntityFieldForAttribute(AttributeCache attribute, bool limitToFilterableAttributes = true)
        {
            // Ensure field name only has Alpha, Numeric and underscore chars
            string fieldName = attribute.Key.RemoveSpecialCharacters().Replace(".", "");

            EntityField entityField = null;

            // Make sure that the attributes field type actually renders a filter control if limitToFilterableAttributes
            var fieldType = FieldTypeCache.Read(attribute.FieldTypeId);

            if (fieldType != null && (!limitToFilterableAttributes || fieldType.Field.HasFilterControl()))
            {
                entityField       = new EntityField(fieldName, FieldKind.Attribute, typeof(string), attribute.Guid, fieldType);
                entityField.Title = attribute.Name.SplitCase();
                entityField.TitleWithoutQualifier = entityField.Title;

                foreach (var config in attribute.QualifierValues)
                {
                    entityField.FieldConfig.Add(config.Key, config.Value);
                }

                // Special processing for Entity Type "Group" to handle sub-types that are distinguished by GroupTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Group)) && attribute.EntityTypeQualifierColumn == "GroupTypeId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var groupType = GroupTypeCache.Read(attribute.EntityTypeQualifierValue.AsInteger(), rockContext);
                        if (groupType != null)
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = groupType.Name;
                            entityField.Title = string.Format("{0} ({1})", attribute.Name, groupType.Name);
                        }
                    }
                }

                // Special processing for Entity Type "ContentChannelItem" to handle sub-types that are distinguished by ContentChannelTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(ContentChannelItem)) && attribute.EntityTypeQualifierColumn == "ContentChannelTypeId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var contentChannelType = new ContentChannelTypeService(rockContext).Get(attribute.EntityTypeQualifierValue.AsInteger());
                        if (contentChannelType != null)
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = contentChannelType.Name;
                            entityField.Title = string.Format("{0} (ChannelType: {1})", attribute.Name, contentChannelType.Name);
                        }
                    }
                }

                // Special processing for Entity Type "ContentChannelItem" to handle sub-types that are distinguished by ContentChannelId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(ContentChannelItem)) && attribute.EntityTypeQualifierColumn == "ContentChannelId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var contentChannel = new ContentChannelService(rockContext).Get(attribute.EntityTypeQualifierValue.AsInteger());
                        if (contentChannel != null)
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = contentChannel.Name;
                            entityField.Title = string.Format("{0} (Channel: {1})", attribute.Name, contentChannel.Name);
                        }
                    }
                }

                // Special processing for Entity Type "Workflow" to handle sub-types that are distinguished by WorkflowTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Rock.Model.Workflow)) && attribute.EntityTypeQualifierColumn == "WorkflowTypeId")
                {
                    using (var rockContext = new RockContext())
                    {
                        int workflowTypeId = attribute.EntityTypeQualifierValue.AsInteger();
                        if (_workflowTypeNameLookup == null)
                        {
                            _workflowTypeNameLookup = new WorkflowTypeService(rockContext).Queryable().ToDictionary(k => k.Id, v => v.Name);
                        }

                        var workflowTypeName = _workflowTypeNameLookup.ContainsKey(workflowTypeId) ? _workflowTypeNameLookup[workflowTypeId] : null;
                        if (workflowTypeName != null)
                        {
                            // Append the Qualifier to the title for Workflow Attributes
                            entityField.AttributeEntityTypeQualifierName = workflowTypeName;
                            entityField.Title = string.Format("({1}) {0} ", attribute.Name, workflowTypeName);
                        }
                    }
                }
            }

            return(entityField);
        }
예제 #7
0
        /// <summary>
        /// Maps the specified folder.
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="ministryFileType">Type of the ministry file.</param>
        /// <param name="storageProvider">The storage provider.</param>
        public void Map(ZipArchive folder, BinaryFileType ministryFileType, ProviderComponent storageProvider)
        {
            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 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);
                var fileMimeType  = Extensions.GetMIMEType(file.Name);
                if (BinaryFileComponent.FileTypeBlackList.Contains(fileExtension))
                {
                    LogException("Binary File Import", string.Format("{0} filetype not allowed ({1})", fileExtension, file.Name));
                    continue;
                }
                else if (fileMimeType == null)
                {
                    LogException("Binary File Import", string.Format("{0} filetype not recognized ({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.MimeType         = fileMimeType;
                    rockFile.BinaryFileTypeId = ministryFileType.Id;
                    rockFile.CreatedDateTime  = file.LastWriteTime.DateTime;
                    rockFile.ModifiedDateTime = ImportDateTime;
                    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-z0-9-]+";
                    var attributeName    = Regex.Match(parsedFileName[3].RemoveWhitespace(), attributePattern);
                    var attributeKey     = attributeName.Value.RemoveWhitespace();

                    // change key to default key for Background Check Documents
                    if (attributeKey == "BackgroundCheck")
                    {
                        attributeKey = "BackgroundCheckDocument";
                    }

                    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.CreatedDateTime  = ImportDateTime;
                        newAttribute.ModifiedDateTime = ImportDateTime;
                        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>
        /// 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;

            var rockContext = new RockContext();

            GroupTypeService     groupTypeService     = new GroupTypeService(rockContext);
            GroupService         groupService         = new GroupService(rockContext);
            AttributeService     attributeService     = new AttributeService(rockContext);
            GroupLocationService groupLocationService = new GroupLocationService(rockContext);

            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 = FieldTypeCache.Read(Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid()).Id;
            int binaryFileTypeId      = new BinaryFileTypeService(rockContext).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);
                }

                // delete in reverse order to get deepest child items first
                groupTypesToDelete.Reverse();
                foreach (var groupTypeToDelete in groupTypesToDelete)
                {
                    groupTypeService.Delete(groupTypeToDelete);
                }

                rockContext.SaveChanges();

                // 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);
                    }

                    if (!groupTypeDB.IsValid)
                    {
                        hasValidationErrors = true;
                        CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupTypeEditor>().First(a => a.GroupTypeGuid == groupTypeDB.Guid);
                        groupTypeEditor.ForceContentVisible    = true;

                        return;
                    }

                    rockContext.SaveChanges();

                    groupTypeDB.SaveAttributeValues();

                    // 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);
                    }
                    rockContext.SaveChanges();

                    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);
                    }
                    rockContext.SaveChanges();
                }

                // 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))
                        {
                            groupLocationService.Delete(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);
                    }

                    if (!groupDB.IsValid)
                    {
                        hasValidationErrors             = true;
                        hasValidationErrors             = true;
                        CheckinGroupEditor groupEditor  = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupEditor>().First(a => a.GroupGuid == groupDB.Guid);
                        groupEditor.ForceContentVisible = true;

                        return;
                    }

                    rockContext.SaveChanges();

                    groupDB.SaveAttributeValues();
                }

                /* 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);
                }

                rockContext.SaveChanges();

                // 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);
                    }
                }

                rockContext.SaveChanges();
            });

            if (!hasValidationErrors)
            {
                NavigateToParentPage();
            }
        }
예제 #9
0
        public static void SaveResults(RockContext rockContext, BackgroundCheck bgCheck, XElement xResult)
        {
            bool createdNewAttribute = false;

            if (xResult != null)
            {
                var xOrder = xResult.Elements("Order").FirstOrDefault();
                if (xOrder != null)
                {
                    bool resultFound = false;

                    // Find any order details with a status element
                    string reportStatus = "Pass";
                    foreach (var xOrderDetail in xOrder.Elements("OrderDetail"))
                    {
                        var goodStatus = (xOrderDetail.Attribute("ServiceCode")?.Value == "SSNTrace") ? "COMPLETE" : "NO RECORD";

                        var xStatus = xOrderDetail.Elements("Status").FirstOrDefault();
                        if (xStatus != null)
                        {
                            resultFound = true;
                            if (xStatus.Value != goodStatus)
                            {
                                reportStatus = "Review";
                                break;
                            }
                        }
                    }

                    if (resultFound)
                    {
                        // If no records found, still double-check for any alerts
                        if (reportStatus != "Review")
                        {
                            var xAlerts = xOrder.Elements("Alerts").FirstOrDefault();
                            if (xAlerts != null)
                            {
                                if (xAlerts.Elements("OrderId").Any())
                                {
                                    reportStatus = "Review";
                                }
                            }
                        }

                        // Save the recommendation
                        string recommendation = (from o in xOrder.Elements("Recommendation") select o.Value).FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(recommendation))
                        {
                            if (SaveAttributeValue(bgCheck.Workflow, "ReportRecommendation", recommendation,
                                                   FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext,
                                                   new Dictionary <string, string> {
                                { "ispassword", "false" }
                            }))
                            {
                                createdNewAttribute = true;
                            }
                        }

                        // Save the report link
                        Guid?  binaryFileGuid = null;
                        string reportLink     = (from o in xOrder.Elements("ReportLink") select o.Value).FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(reportLink))
                        {
                            if (SaveAttributeValue(bgCheck.Workflow, "ReportLink", reportLink,
                                                   FieldTypeCache.Read(Rock.SystemGuid.FieldType.URL_LINK.AsGuid()), rockContext))
                            {
                                createdNewAttribute = true;
                            }

                            // Save the report
                            binaryFileGuid = SaveFile(bgCheck.Workflow.Attributes["Report"], reportLink, bgCheck.Workflow.Id.ToString() + ".pdf");
                            if (binaryFileGuid.HasValue)
                            {
                                if (SaveAttributeValue(bgCheck.Workflow, "Report", binaryFileGuid.Value.ToString(),
                                                       FieldTypeCache.Read(Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid()), rockContext,
                                                       new Dictionary <string, string> {
                                    { "binaryFileType", "" }
                                }))
                                {
                                    createdNewAttribute = true;
                                }
                            }
                        }

                        // Save the status
                        if (SaveAttributeValue(bgCheck.Workflow, "ReportStatus", reportStatus,
                                               FieldTypeCache.Read(Rock.SystemGuid.FieldType.SINGLE_SELECT.AsGuid()), rockContext,
                                               new Dictionary <string, string> {
                            { "fieldtype", "ddl" }, { "values", "Pass,Fail,Review" }
                        }))
                        {
                            createdNewAttribute = true;
                        }

                        // Update the background check file
                        if (bgCheck != null)
                        {
                            bgCheck.ResponseDate = RockDateTime.Now;
                            bgCheck.RecordFound  = reportStatus == "Review";

                            if (binaryFileGuid.HasValue)
                            {
                                var binaryFile = new BinaryFileService(rockContext).Get(binaryFileGuid.Value);
                                if (binaryFile != null)
                                {
                                    bgCheck.ResponseDocumentId = binaryFile.Id;
                                }
                            }
                        }
                    }
                }
            }

            rockContext.SaveChanges();

            if (createdNewAttribute)
            {
                AttributeCache.FlushEntityAttributes();
            }
        }
예제 #10
0
        /// <summary>
        /// Loads the individual data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadIndividuals(CsvDataModel 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;

            // Timeline note type id
            var noteTimelineTypeId = new NoteTypeService(lookupContext).Get(new Guid("7E53487C-D650-4D85-97E2-350EB8332763")).Id;

            // School defined type
            var schoolDefinedType = DefinedTypeCache.Read(new Guid("576FF1E2-6225-4565-A16D-230E26167A3D"));

            // Look up additional Person attributes (existing)
            var personAttributes = new AttributeService(lookupContext).GetByEntityTypeId(PersonEntityTypeId).ToList();

            // Core attributes: PreviousChurch, Position, Employer, School, etc
            var previousChurchAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "PreviousChurch"));
            var employerAttribute       = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Employer"));
            var positionAttribute       = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Position"));
            var firstVisitAttribute     = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "FirstVisit"));
            var schoolAttribute         = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "School"));
            var membershipDateAttribute = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "MembershipDate"));
            var baptismDateAttribute    = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "BaptismDate"));
            var facebookAttribute       = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Facebook"));
            var twitterAttribute        = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Twitter"));
            var instagramAttribute      = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "Instagram"));

            // Text field type id
            int textFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT), 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();

            // Add a Secondary Email attribute if it doesn't exist
            var secondaryEmail = personAttributes.FirstOrDefault(a => a.Key == "SecondaryEmail");

            if (secondaryEmail == null)
            {
                secondaryEmail                           = new Rock.Model.Attribute();
                secondaryEmail.Key                       = "SecondaryEmail";
                secondaryEmail.Name                      = "Secondary Email";
                secondaryEmail.FieldTypeId               = textFieldTypeId;
                secondaryEmail.EntityTypeId              = PersonEntityTypeId;
                secondaryEmail.EntityTypeQualifierValue  = string.Empty;
                secondaryEmail.EntityTypeQualifierColumn = string.Empty;
                secondaryEmail.Description               = "The secondary email for this person";
                secondaryEmail.DefaultValue              = string.Empty;
                secondaryEmail.IsMultiValue              = false;
                secondaryEmail.IsRequired                = false;
                secondaryEmail.Order                     = 0;

                lookupContext.Attributes.Add(secondaryEmail);
                secondaryEmail.Categories.Add(visitInfoCategory);
                lookupContext.SaveChanges(true);
            }

            var secondaryEmailAttribute = AttributeCache.Read(secondaryEmail.Id, lookupContext);

            // Add a former name attribute
            var formerName = personAttributes.FirstOrDefault(a => a.Key == "FormerName");

            if (formerName == null)
            {
                formerName                           = new Rock.Model.Attribute();
                formerName.Key                       = "FormerName";
                formerName.Name                      = "Former Name";
                formerName.FieldTypeId               = textFieldTypeId;
                formerName.EntityTypeId              = PersonEntityTypeId;
                formerName.EntityTypeQualifierValue  = string.Empty;
                formerName.EntityTypeQualifierColumn = string.Empty;
                formerName.Description               = "The former name for this person";
                formerName.DefaultValue              = string.Empty;
                formerName.IsMultiValue              = false;
                formerName.IsRequired                = false;
                formerName.Order                     = 0;

                lookupContext.Attributes.Add(formerName);
                secondaryEmail.Categories.Add(visitInfoCategory);
                lookupContext.SaveChanges(true);
            }

            var formerNameAttribute = AttributeCache.Read(formerName.Id, lookupContext);

            // Look for custom attributes in the Individual file
            var allFields = csvData.TableNodes.FirstOrDefault().Columns.Select((node, index) => new { node = node, index = index }).ToList();
            Dictionary <int, string> customAttributes = allFields.Where(f => f.index > Twitter).ToDictionary(f => f.index, f => f.node.Name);

            // Add any 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.Name == 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(true);
                personAttributes.AddRange(newAttributes);
            }

            var dateFormats = new[] { "MM/dd/yyyy", "MM/dd/yy" };

            var currentFamilyGroup = new Group();
            var newFamilyList      = new List <Group>();
            var newVisitorList     = new List <Group>();
            var importDate         = DateTime.Now;

            int completed = 0;

            ReportProgress(0, string.Format("Starting Individual import ({0:N0} already exist).", ImportedPeople.Count(p => p.Members.Any(m => m.Person.ForeignId != 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 rowFamilyId   = row[FamilyId];
                string rowPersonId   = row[PersonId];
                string rowFamilyName = row[FamilyName];

                if (!string.IsNullOrWhiteSpace(rowFamilyId) && rowFamilyId != currentFamilyGroup.ForeignId)
                {
                    currentFamilyGroup = ImportedPeople.FirstOrDefault(p => p.ForeignId == rowFamilyId);
                    if (currentFamilyGroup == null)
                    {
                        currentFamilyGroup           = new Group();
                        currentFamilyGroup.ForeignId = rowFamilyId;
                        currentFamilyGroup.Name      = row[FamilyName];
                        currentFamilyGroup.CreatedByPersonAliasId = ImportPersonAlias.Id;
                        currentFamilyGroup.GroupTypeId            = FamilyGroupTypeId;
                    }
                }

                // Verify this person isn't already in our data
                var personExists = ImportedPeople.Any(p => p.Members.Any(m => m.Person.ForeignId == rowPersonId));
                if (!personExists)
                {
                    var person = new Person();
                    person.ForeignId              = rowPersonId;
                    person.SystemNote             = string.Format("Imported via Excavator on {0}", importDate.ToString());
                    person.RecordTypeValueId      = personRecordTypeId;
                    person.CreatedByPersonAliasId = ImportPersonAlias.Id;
                    string firstName = row[FirstName];
                    person.FirstName  = firstName;
                    person.NickName   = row[NickName] ?? firstName;
                    person.MiddleName = row[MiddleName];
                    person.LastName   = row[LastName];

                    #region Assign values to the Person record

                    DateTime birthDate;
                    if (DateTime.TryParseExact(row[DateOfBirth], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate))
                    {
                        person.BirthDate = birthDate;
                    }

                    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 if (connectionStatus == "Deceased")
                        {
                            person.IsDeceased = true;
                            person.RecordStatusReasonValueId = recordStatusDeceasedId;
                        }
                        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())
                        {
                        case "Active":
                            person.RecordStatusValueId = recordStatusActiveId;
                            break;

                        case "Inactive":
                            person.RecordStatusValueId = recordStatusInactiveId;
                            break;

                        default:
                            person.RecordStatusValueId = recordStatusPendingId;
                            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();
                            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 = ImportPersonAlias.Id;
                            currentNumber.Extension         = extension.Left(20);
                            currentNumber.Number            = normalizedNumber.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, AttributeValue>();

                    string formerNameValue = row[FormerName];
                    if (!string.IsNullOrWhiteSpace(formerNameValue))
                    {
                        AddPersonAttribute(formerNameAttribute, person, formerNameValue);
                    }

                    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;
                    }

                    string primaryEmail = row[Email];
                    if (!string.IsNullOrWhiteSpace(primaryEmail))
                    {
                        person.Email           = primaryEmail;
                        person.IsEmailActive   = isEmailActive;
                        person.EmailPreference = emailPreference;
                    }

                    string secondaryEmailValue = row[SecondaryEmail];
                    if (!string.IsNullOrWhiteSpace(secondaryEmailValue))
                    {
                        AddPersonAttribute(secondaryEmailAttribute, person, secondaryEmailValue);
                    }

                    DateTime membershipDateValue;
                    if (DateTime.TryParseExact(row[MembershipDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out membershipDateValue))
                    {
                        AddPersonAttribute(membershipDateAttribute, person, membershipDateValue.ToString());
                    }

                    DateTime baptismDateValue;
                    if (DateTime.TryParseExact(row[BaptismDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out baptismDateValue))
                    {
                        AddPersonAttribute(baptismDateAttribute, person, baptismDateValue.ToString());
                    }

                    DateTime firstVisitValue;
                    if (DateTime.TryParseExact(row[FirstVisit], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out firstVisitValue))
                    {
                        AddPersonAttribute(firstVisitAttribute, person, firstVisitValue.ToString());
                    }

                    string previousChurchValue = row[PreviousChurch];
                    if (!string.IsNullOrWhiteSpace(previousChurchValue))
                    {
                        AddPersonAttribute(previousChurchAttribute, person, previousChurchValue);
                    }

                    string positionValue = row[Occupation];
                    if (!string.IsNullOrWhiteSpace(positionValue))
                    {
                        AddPersonAttribute(positionAttribute, person, positionValue);
                    }

                    string employerValue = row[Employer];
                    if (!string.IsNullOrWhiteSpace(employerValue))
                    {
                        AddPersonAttribute(employerAttribute, person, employerValue);
                    }

                    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());
                    }

                    string facebookValue = row[Facebook];
                    if (!string.IsNullOrWhiteSpace(facebookValue))
                    {
                        AddPersonAttribute(facebookAttribute, person, facebookValue);
                    }

                    string twitterValue = row[Twitter];
                    if (!string.IsNullOrWhiteSpace(twitterValue))
                    {
                        AddPersonAttribute(twitterAttribute, person, twitterValue);
                    }

                    string instagramValue = row[Instagram];
                    if (!string.IsNullOrWhiteSpace(instagramValue))
                    {
                        AddPersonAttribute(instagramAttribute, person, instagramValue);
                    }

                    foreach (var attributePair in customAttributes)
                    {
                        string newAttributeValue = row[attributePair.Key];
                        if (!string.IsNullOrWhiteSpace(newAttributeValue))
                        {
                            int?newAttributeId = personAttributes.Where(a => a.Key == attributePair.Value)
                                                 .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]);

                    var newNoteList = new List <Note>();
                    foreach (var notePair in notePairs.Where(n => !string.IsNullOrWhiteSpace(n.Value)))
                    {
                        var newNote = new Note();
                        newNote.CreatedByPersonAliasId = ImportPersonAlias.Id;
                        newNote.CreatedDateTime        = importDate;
                        newNote.EntityId   = person.Id;
                        newNote.Text       = notePair.Value;
                        newNote.NoteTypeId = noteTimelineTypeId;
                        newNote.Caption    = string.Format("{0} Note", notePair.Key);

                        if (!notePair.Key.Equals("General"))
                        {
                            newNote.IsAlert = true;
                        }

                        newNoteList.Add(newNote);
                    }

                    if (newNoteList.Any())
                    {
                        lookupContext.Notes.AddRange(newNoteList);
                        lookupContext.SaveChanges(true);
                    }

                    #endregion

                    var groupMember = new GroupMember();
                    groupMember.Person            = person;
                    groupMember.GroupRoleId       = groupRoleId;
                    groupMember.GroupMemberStatus = GroupMemberStatus.Active;

                    if (isFamilyRelationship || currentFamilyGroup.Members.Count() < 1)
                    {
                        currentFamilyGroup.Members.Add(groupMember);
                        newFamilyList.Add(currentFamilyGroup);
                        completed++;
                    }
                    else
                    {
                        var visitorGroup = new Group();
                        visitorGroup.ForeignId = rowFamilyId.ToString();
                        visitorGroup.Members.Add(groupMember);
                        visitorGroup.GroupTypeId = FamilyGroupTypeId;
                        visitorGroup.Name        = person.LastName + " Family";
                        newFamilyList.Add(visitorGroup);
                        completed++;

                        newVisitorList.Add(visitorGroup);
                    }

                    if (completed % (ReportingNumber * 10) < 1)
                    {
                        ReportProgress(0, string.Format("{0:N0} people imported.", completed));
                    }
                    else if (completed % ReportingNumber < 1)
                    {
                        SaveIndividuals(newFamilyList, newVisitorList);
                        ReportPartialProgress();
                        newFamilyList.Clear();
                    }
                }
            }

            if (newFamilyList.Any())
            {
                SaveIndividuals(newFamilyList, newVisitorList);
            }

            ReportProgress(0, string.Format("Finished individual import: {0:N0} people imported.", completed));
            return(completed);
        }
예제 #11
0
        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";
        }
예제 #12
0
        /// <summary>
        /// Gets the entity fields.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <returns></returns>
        public static List <EntityField> GetEntityFields(Type entityType)
        {
            var entityFields = new List <EntityField>();

            // Get Properties
            foreach (var property in entityType.GetProperties())
            {
                if (!property.GetGetMethod().IsVirtual || property.Name == "Id" || property.Name == "Guid" || property.Name == "Order")
                {
                    EntityField entityProperty = null;

                    // Enum Properties
                    if (property.PropertyType.IsEnum)
                    {
                        entityProperty = new EntityField(property.Name, FieldKind.Property, property.PropertyType, 1);
                        entityProperty.FilterFieldType = SystemGuid.FieldType.MULTI_SELECT;
                    }

                    // Boolean properties
                    if (property.PropertyType == typeof(bool) || property.PropertyType == typeof(bool?))
                    {
                        entityProperty = new EntityField(property.Name, FieldKind.Property, property.PropertyType, 1);
                        entityProperty.FilterFieldType = SystemGuid.FieldType.SINGLE_SELECT;
                    }

                    // Date properties
                    if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime? ))
                    {
                        entityProperty = new EntityField(property.Name, FieldKind.Property, property.PropertyType, 2);
                        entityProperty.FilterFieldType = SystemGuid.FieldType.DATE;
                    }

                    // Text Properties
                    else if (property.PropertyType == typeof(string))
                    {
                        entityProperty = new EntityField(property.Name, FieldKind.Property, property.PropertyType, 2);
                        entityProperty.FilterFieldType = SystemGuid.FieldType.TEXT;
                    }

                    // Integer Properties
                    else if (property.PropertyType == typeof(int) || property.PropertyType == typeof(int?))
                    {
                        var definedValueAttribute = property.GetCustomAttributes(typeof(Rock.Data.DefinedValueAttribute), true).FirstOrDefault();

                        if (definedValueAttribute != null)
                        {
                            // Defined Value Properties
                            entityProperty = new EntityField(property.Name, FieldKind.Property, property.PropertyType, 1);
                            var definedType = DefinedTypeCache.Read(((Rock.Data.DefinedValueAttribute)definedValueAttribute).DefinedTypeGuid);
                            entityProperty.Title           = definedType != null ? definedType.Name : property.Name.Replace("ValueId", string.Empty).SplitCase();
                            entityProperty.FilterFieldType = SystemGuid.FieldType.MULTI_SELECT;
                            entityProperty.DefinedTypeId   = definedType.Id;
                        }
                        else
                        {
                            entityProperty = new EntityField(property.Name, FieldKind.Property, property.PropertyType, 2);
                            entityProperty.FilterFieldType = SystemGuid.FieldType.INTEGER;
                        }
                    }

                    if (entityProperty != null)
                    {
                        entityProperty.IsPreviewable = property.GetCustomAttributes(typeof(PreviewableAttribute), true).Any();
                        entityFields.Add(entityProperty);
                    }
                }
            }

            // Get Attributes
            int entityTypeId = EntityTypeCache.Read(entityType).Id;

            foreach (var attribute in new AttributeService().Get(entityTypeId, string.Empty, string.Empty))
            {
                // Ensure prop name is unique
                string propName = attribute.Name;
                int    i        = 1;
                while (entityFields.Any(p => p.Name.Equals(propName, StringComparison.CurrentCultureIgnoreCase)))
                {
                    propName = attribute.Name + (i++).ToString();
                }

                EntityField entityProperty = null;

                switch (FieldTypeCache.Read(attribute.FieldTypeId).Guid.ToString().ToUpper())
                {
                case SystemGuid.FieldType.BOOLEAN:
                    entityProperty = new EntityField(attribute.Name, FieldKind.Attribute, null, 1, attribute.Id);
                    entityProperty.FilterFieldType = SystemGuid.FieldType.SINGLE_SELECT;
                    break;

                case SystemGuid.FieldType.DATE:
                    entityProperty = new EntityField(attribute.Name, FieldKind.Attribute, null, 2, attribute.Id);
                    entityProperty.FilterFieldType = SystemGuid.FieldType.DATE;
                    break;

                case SystemGuid.FieldType.INTEGER:
                    entityProperty = new EntityField(attribute.Name, FieldKind.Attribute, null, 2, attribute.Id);
                    entityProperty.FilterFieldType = SystemGuid.FieldType.INTEGER;
                    break;

                case SystemGuid.FieldType.MULTI_SELECT:
                    entityProperty = new EntityField(attribute.Name, FieldKind.Attribute, null, 1, attribute.Id);
                    entityProperty.FilterFieldType = SystemGuid.FieldType.MULTI_SELECT;
                    break;

                case SystemGuid.FieldType.SINGLE_SELECT:
                    entityProperty = new EntityField(attribute.Name, FieldKind.Attribute, null, 1, attribute.Id);
                    entityProperty.FilterFieldType = SystemGuid.FieldType.MULTI_SELECT;
                    break;

                case SystemGuid.FieldType.TEXT:
                    entityProperty = new EntityField(attribute.Name, FieldKind.Attribute, null, 2, attribute.Id);
                    entityProperty.FilterFieldType = SystemGuid.FieldType.TEXT;
                    break;
                }

                if (entityProperty != null)
                {
                    entityFields.Add(entityProperty);
                }
            }

            int index = 1;
            List <EntityField> result = new List <EntityField>();

            foreach (var entityProperty in entityFields.OrderBy(p => p.Title).ThenBy(p => p.Name))
            {
                entityProperty.Index = index;
                index += entityProperty.ControlCount;
                result.Add(entityProperty);
            }

            return(result);
        }
예제 #13
0
        /// <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 binaryFileTypeService = new BinaryFileTypeService(lookupContext);
            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);

            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)
            {
                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 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      = ImportedPeople.FirstOrDefault(p => p.PersonForeignId == personForeignId);
                if (personKeys != null)
                {
                    var nameWithoutExtension = parsedFileName[3].ReplaceLastOccurrence(fileExtension, string.Empty);
                    var attributeName        = Regex.Replace(nameWithoutExtension, "\\d{4,}[.\\w]+$", string.Empty);

                    // append "Document" to attribute name to create unique attributes
                    // this matches core attribute "Background Check Document"
                    attributeName = !attributeName.EndsWith("Document", StringComparison.CurrentCultureIgnoreCase) ? 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
                    {
                        // 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 documentForeignId = Regex.Match(nameWithoutExtension, "\\d+$");
                    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.Value,
                        ForeignId              = documentForeignId.Value.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));
                    }
                    else if (completedItems % ReportingNumber < 1)
                    {
                        SaveFiles(newFileList);

                        // Reset list
                        newFileList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            if (newFileList.Any())
            {
                SaveFiles(newFileList);
            }

            ReportProgress(100, string.Format("Finished files import: {0:N0} ministry documents imported.", completedItems));
        }
예제 #14
0
        /// <summary>
        /// Cleanups the orphaned attributes.
        /// </summary>
        /// <param name="dataMap">The data map.</param>
        /// <returns></returns>
        private int CleanupOrphanedAttributes(JobDataMap dataMap)
        {
            int recordsDeleted = 0;

            // Cleanup AttributeMatrix records that are no longer associated with an attribute value
            using (RockContext rockContext = new RockContext())
            {
                AttributeMatrixService     attributeMatrixService     = new AttributeMatrixService(rockContext);
                AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext);

                var matrixFieldTypeId = FieldTypeCache.Read <MatrixFieldType>().Id;
                // get a list of attribute Matrix Guids that are actually in use
                var usedAttributeMatrices = new AttributeValueService(rockContext).Queryable().Where(a => a.Attribute.FieldTypeId == matrixFieldTypeId).Select(a => a.Value).ToList().AsGuidList();

                // clean up any orphaned attribute matrices
                var dayAgo = RockDateTime.Now.AddDays(-1);
                var orphanedAttributeMatrices = attributeMatrixService.Queryable().Where(a => (a.CreatedDateTime < dayAgo) && !usedAttributeMatrices.Contains(a.Guid)).ToList();
                if (orphanedAttributeMatrices.Any())
                {
                    recordsDeleted += orphanedAttributeMatrices.Count;
                    attributeMatrixItemService.DeleteRange(orphanedAttributeMatrices.SelectMany(a => a.AttributeMatrixItems));
                    attributeMatrixService.DeleteRange(orphanedAttributeMatrices);
                    rockContext.SaveChanges();
                }
            }

            // clean up other orphaned entity attributes
            Type rockContextType = typeof(Rock.Data.RockContext);

            foreach (var cachedType in EntityTypeCache.All().Where(e => e.IsEntity))
            {
                Type entityType = cachedType.GetEntityType();
                if (entityType != null &&
                    typeof(IEntity).IsAssignableFrom(entityType) &&
                    typeof(IHasAttributes).IsAssignableFrom(entityType) &&
                    !entityType.Namespace.Equals("Rock.Rest.Controllers"))
                {
                    try
                    {
                        bool ignore = false;
                        if (entityType.Assembly != rockContextType.Assembly)
                        {
                            // If the model is from a custom project, verify that it is using RockContext, if not, ignore it since an
                            // exception will occur due to the AttributeValue query using RockContext.
                            var entityContextType = Reflection.SearchAssembly(entityType.Assembly, typeof(System.Data.Entity.DbContext));
                            ignore = (entityContextType.Any() && !entityContextType.First().Value.Equals(rockContextType));
                        }

                        if (!ignore)
                        {
                            var classMethod = this.GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic)
                                              .First(m => m.Name == "CleanupOrphanedAttributeValuesForEntityType");
                            var genericMethod = classMethod.MakeGenericMethod(entityType);
                            var result        = genericMethod.Invoke(this, null) as int?;
                            if (result.HasValue)
                            {
                                recordsDeleted += (int)result;
                            }
                        }
                    }
                    catch { }
                }
            }

            return(recordsDeleted);
        }
예제 #15
0
        /// <summary>
        /// Gets the attribute value.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="key">The key.</param>
        /// <param name="checkWorflowAttributeValue">if set to <c>true</c> and the returned value is a guid, check to see if the workflow
        /// or activity contains an attribute with that guid. This is useful when using the WorkflowTextOrAttribute field types to get the
        /// actual value or workflow value.</param>
        /// <returns></returns>
        protected string GetAttributeValue(WorkflowAction action, string key, bool checkWorflowAttributeValue)
        {
            string value = GetActionAttributeValue(action, key);

            if (checkWorflowAttributeValue)
            {
                Guid?attributeGuid = value.AsGuidOrNull();
                if (attributeGuid.HasValue)
                {
                    var attribute = AttributeCache.Read(attributeGuid.Value);
                    if (attribute != null)
                    {
                        value = action.GetWorklowAttributeValue(attributeGuid.Value);
                        if (!string.IsNullOrWhiteSpace(value) && attribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.ENCRYPTED_TEXT.AsGuid()).Id)
                        {
                            value = Security.Encryption.DecryptString(value);
                        }
                    }
                }
            }

            return(value);
        }
예제 #16
0
        public static void handleTransaction(RockContext rockContext, BackgroundCheck bgCheck, XElement xTransaction)
        {
            bool createdNewAttribute = false;
            // Handle transaction status
            XElement xOrderResponse = null;

            if (xTransaction.Attribute("TransactionType").Value == "REQUEST")
            {
                xOrderResponse = xTransaction.Elements().Last();

                XElement xResponseStatus = xOrderResponse.Element("Status");
                if (xResponseStatus != null)
                {
                    string status = xResponseStatus.Value;
                    createdNewAttribute = SaveAttributeValue(bgCheck.Workflow, "RequestStatus", status, FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext, null) || createdNewAttribute;

                    if (status == "ERROR")
                    {
                        createdNewAttribute = SaveAttributeValue(bgCheck.Workflow, "RequestMessage", xOrderResponse.Elements("Message").Select(x => x.Value).ToList().AsDelimited(Environment.NewLine), FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext, null) || createdNewAttribute;
                    }
                }

                XElement xResponseErrors = xOrderResponse.Elements("Errors").FirstOrDefault();
                if (xResponseErrors != null)
                {
                    createdNewAttribute = SaveAttributeValue(bgCheck.Workflow, "RequestMessage", xResponseErrors.Elements("Message").Select(x => x.Value).ToList().AsDelimited(Environment.NewLine), FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext, null) || createdNewAttribute;
                }
            }
            else if (xTransaction.Attribute("TransactionType").Value == "RESPONSE")
            {
                xOrderResponse = xTransaction.Elements().First();
            }

            // Handle request status
            if (xOrderResponse != null)
            {
                XElement xOrder = xOrderResponse.Element("Order");

                if (xOrder != null && xOrder.Elements("OrderDetail").Any(x => x.Elements("Status").Any()))
                {
                    SaveResults(rockContext, bgCheck, xOrderResponse);
                }
            }
        }
예제 #17
0
        /// <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;
            int newPeople   = 0;

            ReportProgress(0, string.Format("Starting Individual import ({0:N0} already exist).", ImportedPeopleKeys.Count()));

            string[] row;
            row = csvData.Database.FirstOrDefault();
            while (row != 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 = ImportedFamilies.Any(g => g.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.NumberFormatted   = PhoneNumber.FormattedNumber(currentNumber.CountryCode, currentNumber.Number);
                            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 = lookupContext.DefinedValues.Any(s => s.DefinedTypeId == schoolDefinedType.Id && 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 = lookupContext.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 = ImportedFamilies.FirstOrDefault(g => g.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++;
                        }
                    }

                    // look ahead 1 row
                    string rowNextFamilyKey = "-1";
                    if ((row = csvData.Database.FirstOrDefault()) != null)
                    {
                        rowNextFamilyKey = row[FamilyId];
                    }

                    newPeople++;
                    completed++;
                    if (completed % (ReportingNumber * 10) < 1)
                    {
                        ReportProgress(0, string.Format("{0:N0} people imported.", completed));
                    }

                    if (newPeople >= ReportingNumber && rowNextFamilyKey != currentFamilyGroup.ForeignKey)
                    {
                        SaveIndividuals(newFamilyList, newVisitorList, newNoteList);
                        lookupContext.SaveChanges();
                        ReportPartialProgress();

                        // Clear out variables
                        currentFamilyGroup = new Group();
                        newFamilyList.Clear();
                        newVisitorList.Clear();
                        newNoteList.Clear();
                        newPeople = 0;
                    }
                }
                else
                {
                    row = csvData.Database.FirstOrDefault();
                }
            }

            // Save any changes to new families
            if (newFamilyList.Any())
            {
                SaveIndividuals(newFamilyList, newVisitorList, newNoteList);
            }

            // Save any changes to existing families
            lookupContext.SaveChanges();
            DetachAllInContext(lookupContext);
            lookupContext.Dispose();

            ReportProgress(0, string.Format("Finished individual import: {0:N0} families and {1:N0} people added.", newFamilies, completed));
            return(completed);
        }
예제 #18
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Get the number of minutes to delay
            int?minutes = GetAttributeValue(action, "MinutesToDelay").AsIntegerOrNull();

            if (!minutes.HasValue || minutes.Value <= 0)
            {
                return(true);
            }

            // Use the current action type' guid as the key for a 'Delay Activated' attribute
            string AttrKey = action.ActionType.Guid.ToString();

            // Check to see if the action's activity does not yet have the the 'Delay Activated' attribute.
            // The first time this action runs on any workflow instance using this action instance, the
            // attribute will not exist and need to be created
            if (!action.Activity.Attributes.ContainsKey(AttrKey))
            {
                var attribute = new Rock.Model.Attribute();
                attribute.EntityTypeId = action.Activity.TypeId;
                attribute.EntityTypeQualifierColumn = "ActivityTypeId";
                attribute.EntityTypeQualifierValue  = action.Activity.ActivityTypeId.ToString();
                attribute.Name        = "Delay Activated";
                attribute.Key         = AttrKey;
                attribute.FieldTypeId = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()).Id;

                // Need to save the attribute now (using different context) so that an attribute id is returned.
                var newRockContext = new RockContext();
                new AttributeService(newRockContext).Add(attribute);
                newRockContext.SaveChanges();

                action.Activity.Attributes.Add(AttrKey, AttributeCache.Read(attribute));
                var attributeValue = new Rock.Model.AttributeValue();
                attributeValue.AttributeId = attribute.Id;
                attributeValue.Value       = RockDateTime.Now.ToString("o");
                action.Activity.AttributeValues.Add(AttrKey, attributeValue);

                action.AddLogEntry(string.Format("{0:N0} Minute Delay Activated.", minutes.Value), true);
            }
            else
            {
                // Check to see if this action instance has a value for the 'Delay Activated' attrbute
                DateTime?activated = action.Activity.GetAttributeValue(AttrKey).AsDateTime();
                if (!activated.HasValue)
                {
                    // If no value exists, set the value to the current time
                    action.Activity.SetAttributeValue(AttrKey, RockDateTime.Now.ToString("o"));
                    action.AddLogEntry(string.Format("{0:N0} Minute Delay Activated.", minutes.Value), true);
                }
                else
                {
                    // If a value does exist, check to see if the number of minutes to delay has passed
                    // since the value was saved
                    if (activated.Value.AddMinutes(minutes.Value).CompareTo(RockDateTime.Now) < 0)
                    {
                        // If delay has elapsed, return True ( so that processing of activity will continue )
                        action.AddLogEntry(string.Format("{0:N0} Minute Delay Completed.", minutes.Value), true);
                        return(true);
                    }
                }
            }

            // If delay has not elapsed, return false so that processing of activity stops
            return(false);
        }
예제 #19
0
        /// <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)
        {
            using (new UnitOfWorkScope())
            {
                var attributeService          = new AttributeService();
                var attributeQualifierService = new AttributeQualifierService();

                Rock.Model.Attribute attribute;

                int attributeId = 0;
                if (hfId.Value != string.Empty && !int.TryParse(hfId.Value, out attributeId))
                {
                    attributeId = 0;
                }

                if (attributeId == 0)
                {
                    attribute              = new Rock.Model.Attribute();
                    attribute.IsSystem     = false;
                    attribute.EntityTypeId = _entityTypeId;
                    attribute.EntityTypeQualifierColumn = _entityQualifierColumn;
                    attribute.EntityTypeQualifierValue  = _entityQualifierValue;
                    attributeService.Add(attribute, CurrentPersonId);
                }
                else
                {
                    AttributeCache.Flush(attributeId);
                    attribute = attributeService.Get(attributeId);
                }

                attribute.Key         = tbKey.Text;
                attribute.Name        = tbName.Text;
                attribute.Category    = tbCategory.Text;
                attribute.Description = tbDescription.Text;
                attribute.FieldTypeId = int.Parse(ddlFieldType.SelectedValue);

                var fieldType = FieldTypeCache.Read(attribute.FieldTypeId);

                foreach (var oldQualifier in attribute.AttributeQualifiers.ToList())
                {
                    attributeQualifierService.Delete(oldQualifier, CurrentPersonId);
                }

                attribute.AttributeQualifiers.Clear();

                List <Control> configControls = new List <Control>();
                foreach (var key in fieldType.Field.ConfigurationKeys())
                {
                    configControls.Add(phFieldTypeQualifiers.FindControl("configControl_" + key));
                }

                foreach (var configValue in fieldType.Field.ConfigurationValues(configControls))
                {
                    AttributeQualifier qualifier = new AttributeQualifier();
                    qualifier.IsSystem = false;
                    qualifier.Key      = configValue.Key;
                    qualifier.Value    = configValue.Value.Value ?? string.Empty;
                    attribute.AttributeQualifiers.Add(qualifier);
                }

                attribute.DefaultValue = tbDefaultValue.Text;
                attribute.IsMultiValue = cbMultiValue.Checked;
                attribute.IsRequired   = cbRequired.Checked;

                attributeService.Save(attribute, CurrentPersonId);
            }

            BindGrid();

            pnlDetails.Visible = false;
            pnlList.Visible    = true;
        }
예제 #20
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            if (entity != null && entity is IEntity)
            {
                Guid guid = GetAttributeValue(action, "Attribute").AsGuid();
                if (!guid.IsEmpty())
                {
                    var attribute = AttributeCache.Read(guid, rockContext);
                    if (attribute != null)
                    {
                        // Person is handled special since it needs the person alias id
                        if (entity is Person && attribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id)
                        {
                            var person = (Person)entity;

                            var primaryAlias = new PersonAliasService(rockContext).Queryable().FirstOrDefault(a => a.AliasPersonId == person.Id);
                            if (primaryAlias != null)
                            {
                                SetWorkflowAttributeValue(action, guid, primaryAlias.Guid.ToString());
                                return(true);
                            }
                            else
                            {
                                errorMessages.Add("Could not determine person primary alias!");
                            }
                        }
                        else
                        {
                            string lavaTemplate = GetAttributeValue(action, "LavaTemplate");
                            if (string.IsNullOrWhiteSpace(lavaTemplate))
                            {
                                if (GetAttributeValue(action, "UseId").AsBoolean())
                                {
                                    SetWorkflowAttributeValue(action, guid, ((IEntity)entity).Id.ToString());
                                }
                                else
                                {
                                    SetWorkflowAttributeValue(action, guid, ((IEntity)entity).Guid.ToString());
                                }
                            }
                            else
                            {
                                var mergeFields = GetMergeFields(action);
                                mergeFields.Add("Entity", entity);

                                string parsedValue;

                                if (lavaTemplate.HasMergeFields())
                                {
                                    var template = Template.Parse(lavaTemplate);

                                    parsedValue = template.Render(Hash.FromDictionary(mergeFields));

                                    if (template.Errors.Any())
                                    {
                                        errorMessages.AddRange(template.Errors.Select(error => error.Message));
                                    }
                                }
                                else
                                {
                                    parsedValue = lavaTemplate;
                                }

                                if (!errorMessages.Any())
                                {
                                    SetWorkflowAttributeValue(action, guid, parsedValue);
                                }
                            }
                        }
                    }
                    else
                    {
                        errorMessages.Add("Invalid attribute!");
                    }
                }
                else
                {
                    errorMessages.Add("Invalid attribute!");
                }
            }
            else
            {
                if (!GetAttributeValue(action, "EntityIsRequired").AsBoolean(true))
                {
                    return(true);
                }

                errorMessages.Add("The entity is null or not a Rock IEntity.");
            }

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

            return(!errorMessages.Any());
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="metricValueId">The metric value identifier.</param>
        /// <param name="metricId">The metric identifier.</param>
        public void ShowDetail(int metricValueId, int?metricId)
        {
            pnlDetails.Visible = true;

            // Load depending on Add(0) or Edit
            MetricValue metricValue = null;

            if (!metricValueId.Equals(0))
            {
                metricValue       = new MetricValueService(new RockContext()).Get(metricValueId);
                lActionTitle.Text = ActionTitle.Edit(MetricValue.FriendlyTypeName).FormatAsHtmlTitle();
            }

            if (metricValue == null && metricId.HasValue)
            {
                metricValue = new MetricValue {
                    Id = 0, MetricId = metricId.Value
                };
                metricValue.Metric = metricValue.Metric ?? new MetricService(new RockContext()).Get(metricValue.MetricId);
                lActionTitle.Text  = ActionTitle.Add(MetricValue.FriendlyTypeName).FormatAsHtmlTitle();
            }

            hfMetricValueId.Value = metricValue.Id.ToString();

            LoadDropDowns();

            ddlMetricValueType.SelectedValue = metricValue.MetricValueType.ConvertToInt().ToString();
            tbXValue.Text    = metricValue.XValue;
            tbYValue.Text    = metricValue.YValue.ToString();
            hfMetricId.Value = metricValue.MetricId.ToString();
            tbNote.Text      = metricValue.Note;
            dpMetricValueDateTime.SelectedDate = metricValue.MetricValueDateTime;

            var metricEntityType = EntityTypeCache.Read(metricValue.Metric.EntityTypeId ?? 0);

            // Setup EntityType UI controls
            Control entityTypeEditControl = null;

            if (metricEntityType != null && metricEntityType.SingleValueFieldType != null)
            {
                hfSingleValueFieldTypeId.Value = metricEntityType.SingleValueFieldType.Id.ToString();
                FieldTypeCache fieldType = FieldTypeCache.Read(hfSingleValueFieldTypeId.Value.AsInteger());
                entityTypeEditControl = fieldType.Field.EditControl(new Dictionary <string, Rock.Field.ConfigurationValue>(), "entityTypeEditControl");

                if (entityTypeEditControl is IRockControl)
                {
                    (entityTypeEditControl as IRockControl).Label = fieldType.Name;
                }

                phEntityTypeEntityIdValue.Controls.Add(entityTypeEditControl);
                IEntityFieldType entityFieldType = metricEntityType.SingleValueFieldType.Field as IEntityFieldType;
                if (entityFieldType != null)
                {
                    entityFieldType.SetEditValueFromEntityId(entityTypeEditControl, new Dictionary <string, ConfigurationValue>(), metricValue.EntityId);
                }
            }

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;

            bool canEdit = UserCanEdit;

            if (!canEdit && metricId.HasValue && metricId.Value > 0)
            {
                var metric = new MetricService(new RockContext()).Get(metricId.Value);
                if (metric != null && metric.IsAuthorized(Authorization.EDIT, CurrentPerson))
                {
                    canEdit = true;
                }
            }

            if (!canEdit)
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(MetricValue.FriendlyTypeName);
            }

            if (readOnly)
            {
                lActionTitle.Text = ActionTitle.View(MetricValue.FriendlyTypeName);
                btnCancel.Text    = "Close";
            }

            ddlMetricValueType.Enabled    = !readOnly;
            tbXValue.ReadOnly             = readOnly;
            tbYValue.ReadOnly             = readOnly;
            tbNote.ReadOnly               = readOnly;
            dpMetricValueDateTime.Enabled = !readOnly;
            if (entityTypeEditControl is WebControl)
            {
                (entityTypeEditControl as WebControl).Enabled = !readOnly;
            }

            btnSave.Visible = !readOnly;
        }
예제 #22
0
        /// <summary>
        /// Displays the edit list.
        /// </summary>
        private void DisplayEditList()
        {
            lEditHeader.Text = GetAttributeValue("EditHeader");
            lEditFooter.Text = GetAttributeValue("EditFooter");

            if (_definedType != null)
            {
                using (var rockContext = new RockContext())
                {
                    var entityType  = EntityTypeCache.Read("Rock.Model.DefinedValue");
                    var definedType = new DefinedTypeService(rockContext).Get(_definedType.Id);
                    if (definedType != null && entityType != null)
                    {
                        var attributeService = new AttributeService(rockContext);
                        var attributes       = new AttributeService(rockContext)
                                               .Get(entityType.Id, "DefinedTypeId", definedType.Id.ToString())
                                               .ToList();

                        // Verify (and create if neccessary) the "Is Link" attribute
                        if (!attributes.Any(a => a.Key == "IsLink"))
                        {
                            var fieldType = FieldTypeCache.Read(Rock.SystemGuid.FieldType.BOOLEAN);
                            if (entityType != null && fieldType != null)
                            {
                                var attribute = new Rock.Model.Attribute();
                                attributeService.Add(attribute);
                                attribute.EntityTypeId = entityType.Id;
                                attribute.EntityTypeQualifierColumn = "DefinedTypeId";
                                attribute.EntityTypeQualifierValue  = definedType.Id.ToString();
                                attribute.FieldTypeId  = fieldType.Id;
                                attribute.Name         = "Is Link";
                                attribute.Key          = "IsLink";
                                attribute.Description  = "Flag indicating if value is a link (vs Header)";
                                attribute.IsGridColumn = true;
                                attribute.DefaultValue = true.ToString();

                                var qualifier1 = new AttributeQualifier();
                                qualifier1.Key   = "truetext";
                                qualifier1.Value = "Yes";
                                attribute.AttributeQualifiers.Add(qualifier1);

                                var qualifier2 = new AttributeQualifier();
                                qualifier2.Key   = "falsetext";
                                qualifier2.Value = "No";
                                attribute.AttributeQualifiers.Add(qualifier2);

                                rockContext.SaveChanges();

                                DefinedTypeCache.Flush(definedType.Id);
                                foreach (var dv in definedType.DefinedValues)
                                {
                                    DefinedValueCache.Flush(dv.Id);
                                }
                            }
                        }
                    }
                }

                BindGrid();

                pnlView.Visible = false;
                pnlEdit.Visible = true;
            }
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Guid?  groupGuid   = null;
            string filterValue = string.Empty;
            string filterKey   = string.Empty;

            // get the group attribute
            groupGuid = GetAttributeValue(action, "SelectionGroup").AsGuid();

            if (!groupGuid.HasValue)
            {
                errorMessages.Add("The selection group could not be found!");
            }

            // get filter key
            filterKey = GetAttributeValue(action, "GroupMemberAttributeKey");

            // get the filter value
            filterValue = GetAttributeValue(action, "FilterValue");
            Guid?filterValueGuid = filterValue.AsGuidOrNull();

            if (filterValueGuid.HasValue)
            {
                filterValue = action.GetWorklowAttributeValue(filterValueGuid.Value);
            }
            else
            {
                filterValue = filterValue.ResolveMergeFields(GetMergeFields(action));
            }

            // get group members
            var qry = new GroupMemberService(rockContext).Queryable().AsNoTracking()
                      .Where(g => g.Group.Guid == groupGuid);

            if (!string.IsNullOrWhiteSpace(filterKey))
            {
                qry = qry.WhereAttributeValue(rockContext, filterKey, filterValue);
            }

            var groupMembers = qry.Select(g => new {
                g.Person.NickName,
                g.Person.LastName,
                g.Person.SuffixValueId,
                PrimaryAliasGuid = g.Person.Aliases.FirstOrDefault().Guid
            })
                               .ToList();

            if (groupMembers.Count() > 0)
            {
                // get random group member from options
                Random rnd = new Random();
                int    r   = rnd.Next(groupMembers.Count);

                var selectedGroupMember = groupMembers[r];

                // set value
                Guid selectPersonGuid = GetAttributeValue(action, "SelectedPerson").AsGuid();
                if (!selectPersonGuid.IsEmpty())
                {
                    var selectedPersonAttribute = AttributeCache.Read(selectPersonGuid, rockContext);
                    if (selectedPersonAttribute != null)
                    {
                        // If this is a person type attribute
                        if (selectedPersonAttribute.FieldTypeId == FieldTypeCache.Read(Rock.SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id)
                        {
                            SetWorkflowAttributeValue(action, selectPersonGuid, selectedGroupMember.PrimaryAliasGuid.ToString());
                        }
                        else if (selectedPersonAttribute.FieldTypeId == FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid(), rockContext).Id)
                        {
                            SetWorkflowAttributeValue(action, selectPersonGuid, Person.FormatFullName(selectedGroupMember.NickName, selectedGroupMember.LastName, selectedGroupMember.SuffixValueId));
                        }
                    }
                }
            }
            else
            {
                errorMessages.Add("No group member for the selected campus could be found.");
            }

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

            return(true);
        }
예제 #24
0
        /// <summary>
        /// Gets the entity fields.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="includeOnlyReportingFields">if set to <c>true</c> [include only reporting fields].</param>
        /// <param name="limitToFilterableFields">if set to <c>true</c> [limit to filterable fields].</param>
        /// <returns></returns>
        public static List <EntityField> GetEntityFields(Type entityType, bool includeOnlyReportingFields = true, bool limitToFilterableFields = true)
        {
            List <EntityField> entityFields = null;

            _workflowTypeNameLookup = null;

            if (HttpContext.Current != null)
            {
                entityFields = HttpContext.Current.Items[string.Format("EntityHelper:GetEntityFields:{0}", entityType.FullName)] as List <EntityField>;
                if (entityFields != null)
                {
                    return(entityFields);
                }
            }

            if (entityFields == null)
            {
                entityFields = new List <EntityField>();
            }

            // Find all non-virtual properties or properties that have the [IncludeForReporting] attribute
            var entityProperties         = entityType.GetProperties().ToList();
            var filteredEntityProperties = entityProperties
                                           .Where(p =>
                                                  !p.GetGetMethod().IsVirtual ||
                                                  p.GetCustomAttributes(typeof(IncludeForReportingAttribute), true).Any() ||
                                                  p.Name == "Order")
                                           .ToList();

            // Get Properties
            foreach (var property in filteredEntityProperties)
            {
                bool isReportable = !property.GetCustomAttributes(typeof(HideFromReportingAttribute), true).Any();
                if (!includeOnlyReportingFields || isReportable)
                {
                    EntityField entityField = new EntityField(property.Name, FieldKind.Property, property);
                    entityField.IsPreviewable = property.GetCustomAttributes(typeof(PreviewableAttribute), true).Any();
                    var fieldTypeAttribute = property.GetCustomAttribute <Rock.Data.FieldTypeAttribute>();

                    // check if we can set it from the fieldTypeAttribute
                    if ((fieldTypeAttribute != null) && SetEntityFieldFromFieldTypeAttribute(entityField, fieldTypeAttribute))
                    {
                        // intentially blank, entity field is already setup
                    }

                    // Enum Properties
                    else if (property.PropertyType.IsEnum)
                    {
                        entityField.FieldType = FieldTypeCache.Read(SystemGuid.FieldType.SINGLE_SELECT.AsGuid());

                        var list = new List <string>();
                        foreach (var value in Enum.GetValues(property.PropertyType))
                        {
                            list.Add(string.Format("{0}^{1}", value, value.ToString().SplitCase()));
                        }

                        var listSource = string.Join(",", list);
                        entityField.FieldConfig.Add("values", new Field.ConfigurationValue(listSource));
                        entityField.FieldConfig.Add("fieldtype", new Field.ConfigurationValue("rb"));
                    }

                    // Boolean properties
                    else if (property.PropertyType == typeof(bool) || property.PropertyType == typeof(bool?))
                    {
                        entityField.FieldType = FieldTypeCache.Read(SystemGuid.FieldType.BOOLEAN.AsGuid());
                    }

                    // Datetime properties
                    else if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime? ))
                    {
                        var colAttr = property.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault();
                        if (colAttr != null && ((ColumnAttribute)colAttr).TypeName == "Date")
                        {
                            entityField.FieldType = FieldTypeCache.Read(SystemGuid.FieldType.DATE.AsGuid());
                        }
                        else
                        {
                            entityField.FieldType = FieldTypeCache.Read(SystemGuid.FieldType.DATE_TIME.AsGuid());
                        }
                    }

                    // Decimal properties
                    else if (property.PropertyType == typeof(decimal) || property.PropertyType == typeof(decimal? ))
                    {
                        entityField.FieldType = FieldTypeCache.Read(SystemGuid.FieldType.DECIMAL.AsGuid());
                    }

                    // Text Properties
                    else if (property.PropertyType == typeof(string))
                    {
                        entityField.FieldType = FieldTypeCache.Read(SystemGuid.FieldType.TEXT.AsGuid());
                    }

                    // Integer Properties (which may be a DefinedValue)
                    else if (property.PropertyType == typeof(int) || property.PropertyType == typeof(int?))
                    {
                        entityField.FieldType = FieldTypeCache.Read(SystemGuid.FieldType.INTEGER.AsGuid());

                        var definedValueAttribute = property.GetCustomAttribute <Rock.Data.DefinedValueAttribute>();
                        if (definedValueAttribute != null)
                        {
                            // Defined Value Properties
                            Guid?definedTypeGuid = ((Rock.Data.DefinedValueAttribute)definedValueAttribute).DefinedTypeGuid;
                            if (definedTypeGuid.HasValue)
                            {
                                var definedType = DefinedTypeCache.Read(definedTypeGuid.Value);
                                entityField.Title = definedType != null ? definedType.Name : property.Name.Replace("ValueId", string.Empty).SplitCase();
                                if (definedType != null)
                                {
                                    entityField.FieldType = FieldTypeCache.Read(SystemGuid.FieldType.DEFINED_VALUE.AsGuid());
                                    entityField.FieldConfig.Add("definedtype", new Field.ConfigurationValue(definedType.Id.ToString()));
                                }
                            }
                        }
                    }

                    if (entityField != null && entityField.FieldType != null)
                    {
                        entityFields.Add(entityField);
                    }
                }
            }

            // Get Attributes
            var entityTypeCache = EntityTypeCache.Read(entityType, true);

            if (entityTypeCache != null)
            {
                int entityTypeId = entityTypeCache.Id;
                using (var rockContext = new RockContext())
                {
                    var qryAttributes = new AttributeService(rockContext).Queryable().Where(a => a.EntityTypeId == entityTypeId);
                    if (entityType == typeof(Group))
                    {
                        // in the case of Group, show attributes that are entity global, but also ones that are qualified by GroupTypeId
                        qryAttributes = qryAttributes
                                        .Where(a =>
                                               a.EntityTypeQualifierColumn == null ||
                                               a.EntityTypeQualifierColumn == string.Empty ||
                                               a.EntityTypeQualifierColumn == "GroupTypeId");
                    }
                    else if (entityType == typeof(ContentChannelItem))
                    {
                        // in the case of ContentChannelItem, show attributes that are entity global, but also ones that are qualified by ContentChannelTypeId or ContentChannelId
                        qryAttributes = qryAttributes
                                        .Where(a =>
                                               a.EntityTypeQualifierColumn == null ||
                                               a.EntityTypeQualifierColumn == string.Empty ||
                                               a.EntityTypeQualifierColumn == "ContentChannelTypeId" ||
                                               a.EntityTypeQualifierColumn == "ContentChannelId"
                                               );
                    }
                    else if (entityType == typeof(Rock.Model.Workflow))
                    {
                        // in the case of Workflow, show attributes that are entity global, but also ones that are qualified by WorkflowTypeId (and have a valid WorkflowTypeId)
                        var validWorkflowTypeIds = new WorkflowTypeService(rockContext).Queryable().Select(a => a.Id).ToList().Select(a => a.ToString()).ToList();
                        qryAttributes = qryAttributes
                                        .Where(a =>
                                               a.EntityTypeQualifierColumn == null ||
                                               a.EntityTypeQualifierColumn == string.Empty ||
                                               (a.EntityTypeQualifierColumn == "WorkflowTypeId" && validWorkflowTypeIds.Contains(a.EntityTypeQualifierValue)));
                    }
                    else
                    {
                        qryAttributes = qryAttributes.Where(a => a.EntityTypeQualifierColumn == string.Empty && a.EntityTypeQualifierValue == string.Empty);
                    }

                    var attributeIdList = qryAttributes.Select(a => a.Id).ToList();

                    foreach (var attributeId in attributeIdList)
                    {
                        AddEntityFieldForAttribute(entityFields, AttributeCache.Read(attributeId), limitToFilterableFields);
                    }
                }
            }

            // Order the fields by title, name
            int index        = 0;
            var sortedFields = new List <EntityField>();

            foreach (var entityField in entityFields.OrderBy(p => !string.IsNullOrEmpty(p.AttributeEntityTypeQualifierName)).ThenBy(p => p.Title).ThenBy(p => p.Name))
            {
                entityField.Index = index;
                index++;
                sortedFields.Add(entityField);
            }

            if (HttpContext.Current != null)
            {
                HttpContext.Current.Items[string.Format("EntityHelper:GetEntityFields:{0}", entityType.FullName)] = sortedFields;
            }

            return(sortedFields);
        }
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        private void LoadExistingRockData()
        {
            var lookupContext         = new RockContext();
            var attributeValueService = new AttributeValueService(lookupContext);
            var attributeService      = new AttributeService(lookupContext);

            IntegerFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.INTEGER)).Id;
            TextFieldTypeId    = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT)).Id;
            PersonEntityTypeId = EntityTypeCache.Read("Rock.Model.Person").Id;
            CampusList         = CampusCache.All();

            int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id;
            int batchEntityTypeId     = EntityTypeCache.Read("Rock.Model.FinancialBatch").Id;
            int userLoginTypeId       = EntityTypeCache.Read("Rock.Model.UserLogin").Id;

            int visitInfoCategoryId = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId)
                                      .Where(c => c.Name == "Visit Information").Select(c => c.Id).FirstOrDefault();

            // Look up and create attributes for F1 unique identifiers if they don't exist
            var personAttributes = attributeService.GetByEntityTypeId(PersonEntityTypeId).AsNoTracking().ToList();

            var householdAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("F1HouseholdId", StringComparison.InvariantCultureIgnoreCase));

            if (householdAttribute == null)
            {
                householdAttribute                           = new Rock.Model.Attribute();
                householdAttribute.Key                       = "F1HouseholdId";
                householdAttribute.Name                      = "F1 Household Id";
                householdAttribute.FieldTypeId               = IntegerFieldTypeId;
                householdAttribute.EntityTypeId              = PersonEntityTypeId;
                householdAttribute.EntityTypeQualifierValue  = string.Empty;
                householdAttribute.EntityTypeQualifierColumn = string.Empty;
                householdAttribute.Description               = "The FellowshipOne household identifier for the person that was imported";
                householdAttribute.DefaultValue              = string.Empty;
                householdAttribute.IsMultiValue              = false;
                householdAttribute.IsRequired                = false;
                householdAttribute.Order                     = 0;

                lookupContext.Attributes.Add(householdAttribute);
                lookupContext.SaveChanges(DisableAuditing);
                personAttributes.Add(householdAttribute);
            }

            var individualAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("F1IndividualId", StringComparison.InvariantCultureIgnoreCase));

            if (individualAttribute == null)
            {
                individualAttribute                           = new Rock.Model.Attribute();
                individualAttribute.Key                       = "F1IndividualId";
                individualAttribute.Name                      = "F1 Individual Id";
                individualAttribute.FieldTypeId               = IntegerFieldTypeId;
                individualAttribute.EntityTypeId              = PersonEntityTypeId;
                individualAttribute.EntityTypeQualifierValue  = string.Empty;
                individualAttribute.EntityTypeQualifierColumn = string.Empty;
                individualAttribute.Description               = "The FellowshipOne individual identifier for the person that was imported";
                individualAttribute.DefaultValue              = string.Empty;
                individualAttribute.IsMultiValue              = false;
                individualAttribute.IsRequired                = false;
                individualAttribute.Order                     = 0;

                lookupContext.Attributes.Add(individualAttribute);
                lookupContext.SaveChanges(DisableAuditing);
                personAttributes.Add(individualAttribute);
            }

            var secondaryEmailAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("SecondaryEmail", StringComparison.InvariantCultureIgnoreCase));

            if (secondaryEmailAttribute == null)
            {
                secondaryEmailAttribute                           = new Rock.Model.Attribute();
                secondaryEmailAttribute.Key                       = "SecondaryEmail";
                secondaryEmailAttribute.Name                      = "Secondary Email";
                secondaryEmailAttribute.FieldTypeId               = TextFieldTypeId;
                secondaryEmailAttribute.EntityTypeId              = PersonEntityTypeId;
                secondaryEmailAttribute.EntityTypeQualifierValue  = string.Empty;
                secondaryEmailAttribute.EntityTypeQualifierColumn = string.Empty;
                secondaryEmailAttribute.Description               = "The secondary email for this person";
                secondaryEmailAttribute.DefaultValue              = string.Empty;
                secondaryEmailAttribute.IsMultiValue              = false;
                secondaryEmailAttribute.IsRequired                = false;
                secondaryEmailAttribute.Order                     = 0;

                lookupContext.Attributes.Add(secondaryEmailAttribute);
                var visitInfoCategory = new CategoryService(lookupContext).Get(visitInfoCategoryId);
                secondaryEmailAttribute.Categories.Add(visitInfoCategory);
                lookupContext.SaveChanges(DisableAuditing);
            }

            var infellowshipLoginAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("InFellowshipLogin", StringComparison.InvariantCultureIgnoreCase));

            if (infellowshipLoginAttribute == null)
            {
                infellowshipLoginAttribute                           = new Rock.Model.Attribute();
                infellowshipLoginAttribute.Key                       = "InFellowshipLogin";
                infellowshipLoginAttribute.Name                      = "InFellowship Login";
                infellowshipLoginAttribute.FieldTypeId               = TextFieldTypeId;
                infellowshipLoginAttribute.EntityTypeId              = PersonEntityTypeId;
                infellowshipLoginAttribute.EntityTypeQualifierValue  = string.Empty;
                infellowshipLoginAttribute.EntityTypeQualifierColumn = string.Empty;
                infellowshipLoginAttribute.Description               = "The InFellowship login for this person";
                infellowshipLoginAttribute.DefaultValue              = string.Empty;
                infellowshipLoginAttribute.IsMultiValue              = false;
                infellowshipLoginAttribute.IsRequired                = false;
                infellowshipLoginAttribute.Order                     = 0;

                // don't add a category as this attribute is only used via the API
                lookupContext.Attributes.Add(infellowshipLoginAttribute);
                lookupContext.SaveChanges(DisableAuditing);
            }

            IndividualIdAttribute      = AttributeCache.Read(individualAttribute.Id);
            HouseholdIdAttribute       = AttributeCache.Read(householdAttribute.Id);
            InFellowshipLoginAttribute = AttributeCache.Read(infellowshipLoginAttribute.Id);
            SecondaryEmailAttribute    = AttributeCache.Read(secondaryEmailAttribute.Id);

            // Set AuthProviderEntityTypeId if Apollos/Infellowship provider exists
            var f1AuthProvider = "cc.newspring.F1.Security.Authentication.F1Migrator";
            var cache          = EntityTypeCache.Read(f1AuthProvider);

            AuthProviderEntityTypeId = cache == null ? (int?)null : cache.Id;

            var aliasIdList = new PersonAliasService(lookupContext).Queryable().AsNoTracking()
                              .Select(pa => new
            {
                PersonAliasId = pa.Id,
                PersonId      = pa.PersonId,
                IndividualId  = pa.ForeignId,
                FamilyRole    = pa.Person.ReviewReasonNote
            }).ToList();
            var householdIdList = attributeValueService.GetByAttributeId(householdAttribute.Id).AsNoTracking()
                                  .Select(av => new
            {
                PersonId    = (int)av.EntityId,
                HouseholdId = av.Value
            }).ToList();

            ImportedPeople = householdIdList.GroupJoin(aliasIdList,
                                                       household => household.PersonId,
                                                       aliases => aliases.PersonId,
                                                       (household, aliases) => new PersonKeys
            {
                PersonAliasId = aliases.Select(a => a.PersonAliasId).FirstOrDefault(),
                PersonId      = household.PersonId,
                IndividualId  = aliases.Select(a => a.IndividualId).FirstOrDefault(),
                HouseholdId   = household.HouseholdId.AsType <int?>(),
                FamilyRoleId  = aliases.Select(a => a.FamilyRole.ConvertToEnum <FamilyRole>(0)).FirstOrDefault()
            }
                                                       ).ToList();

            ImportedBatches = new FinancialBatchService(lookupContext).Queryable().AsNoTracking()
                              .Where(b => b.ForeignId != null)
                              .ToDictionary(t => (int)t.ForeignId, t => (int?)t.Id);
        }
예제 #26
0
        /// <summary>
        /// Saves the results.
        /// </summary>
        /// <param name="xResult">The x result.</param>
        /// <param name="workflow">The workflow.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="saveResponse">if set to <c>true</c> [save response].</param>
        public static void SaveResults(XDocument xResult, Rock.Model.Workflow workflow, RockContext rockContext, bool saveResponse = true)
        {
            bool createdNewAttribute = false;

            var newRockContext  = new RockContext();
            var service         = new BackgroundCheckService(newRockContext);
            var backgroundCheck = service.Queryable()
                                  .Where(c =>
                                         c.WorkflowId.HasValue &&
                                         c.WorkflowId.Value == workflow.Id)
                                  .FirstOrDefault();

            if (backgroundCheck != null && saveResponse)
            {
                // Clear any SSN nodes before saving XML to record
                foreach (var xSSNElement in xResult.Descendants("SSN"))
                {
                    xSSNElement.Value = "XXX-XX-XXXX";
                }

                backgroundCheck.ResponseXml = backgroundCheck.ResponseXml + string.Format(@"
Response XML ({0}): 
------------------------ 
{1}

", RockDateTime.Now.ToString(), xResult.ToString());
            }

            var xOrderXML = xResult.Elements("OrderXML").FirstOrDefault();

            if (xOrderXML != null)
            {
                var xOrder = xOrderXML.Elements("Order").FirstOrDefault();
                if (xOrder != null)
                {
                    bool resultFound = false;

                    // Find any order details with a status element
                    string reportStatus = "Pass";
                    foreach (var xOrderDetail in xOrder.Elements("OrderDetail"))
                    {
                        var xStatus = xOrderDetail.Elements("Status").FirstOrDefault();
                        if (xStatus != null)
                        {
                            resultFound = true;
                            if (xStatus.Value != "NO RECORD")
                            {
                                reportStatus = "Review";
                                break;
                            }
                        }
                    }

                    if (resultFound)
                    {
                        // If no records found, still double-check for any alerts
                        if (reportStatus != "Review")
                        {
                            var xAlerts = xOrder.Elements("Alerts").FirstOrDefault();
                            if (xAlerts != null)
                            {
                                if (xAlerts.Elements("OrderId").Any())
                                {
                                    reportStatus = "Review";
                                }
                            }
                        }

                        // Save the recommendation
                        string recommendation = (from o in xOrder.Elements("Recommendation") select o.Value).FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(recommendation))
                        {
                            if (SaveAttributeValue(workflow, "ReportRecommendation", recommendation,
                                                   FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid()), rockContext,
                                                   new Dictionary <string, string> {
                                { "ispassword", "false" }
                            }))
                            {
                                createdNewAttribute = true;
                            }
                        }

                        // Save the report link
                        Guid?  binaryFileGuid = null;
                        string reportLink     = (from o in xOrder.Elements("ReportLink") select o.Value).FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(reportLink))
                        {
                            if (SaveAttributeValue(workflow, "ReportLink", reportLink,
                                                   FieldTypeCache.Read(Rock.SystemGuid.FieldType.URL_LINK.AsGuid()), rockContext))
                            {
                                createdNewAttribute = true;
                            }

                            // Save the report
                            binaryFileGuid = SaveFile(workflow.Attributes["Report"], reportLink, workflow.Id.ToString() + ".pdf");
                            if (binaryFileGuid.HasValue)
                            {
                                if (SaveAttributeValue(workflow, "Report", binaryFileGuid.Value.ToString(),
                                                       FieldTypeCache.Read(Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid()), rockContext,
                                                       new Dictionary <string, string> {
                                    { "binaryFileType", "" }
                                }))
                                {
                                    createdNewAttribute = true;
                                }
                            }
                        }

                        // Save the status
                        if (SaveAttributeValue(workflow, "ReportStatus", reportStatus,
                                               FieldTypeCache.Read(Rock.SystemGuid.FieldType.SINGLE_SELECT.AsGuid()), rockContext,
                                               new Dictionary <string, string> {
                            { "fieldtype", "ddl" }, { "values", "Pass,Fail,Review" }
                        }))
                        {
                            createdNewAttribute = true;
                        }

                        // Update the background check file
                        if (backgroundCheck != null)
                        {
                            backgroundCheck.ResponseDate = RockDateTime.Now;
                            backgroundCheck.RecordFound  = reportStatus == "Review";

                            if (binaryFileGuid.HasValue)
                            {
                                var binaryFile = new BinaryFileService(newRockContext).Get(binaryFileGuid.Value);
                                if (binaryFile != null)
                                {
                                    backgroundCheck.ResponseDocumentId = binaryFile.Id;
                                }
                            }
                        }
                    }
                }
            }

            newRockContext.SaveChanges();

            if (createdNewAttribute)
            {
                AttributeCache.FlushEntityAttributes();
            }
        }
예제 #27
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        protected void ShowEdit(int attributeId)
        {
            var rockContext      = new RockContext();
            var attributeService = new AttributeService(rockContext);
            var attributeModel   = attributeService.Get(attributeId);

            if (attributeModel == null)
            {
                mdAttribute.Title = "Add Attribute".FormatAsHtmlTitle();

                attributeModel             = new Rock.Model.Attribute();
                attributeModel.FieldTypeId = FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT).Id;

                if (!_configuredType)
                {
                    int entityTypeId = int.MinValue;
                    if (int.TryParse(rFilter.GetUserPreference("Entity Type"), out entityTypeId) && entityTypeId > 0)
                    {
                        attributeModel.EntityTypeId = entityTypeId;
                    }
                }
                else
                {
                    attributeModel.EntityTypeId = _entityTypeId;
                    attributeModel.EntityTypeQualifierColumn = _entityQualifierColumn;
                    attributeModel.EntityTypeQualifierValue  = _entityQualifierValue;
                }

                List <int> selectedCategoryIds = cpCategoriesFilter.SelectedValuesAsInt().ToList();
                new CategoryService(rockContext).Queryable().Where(c => selectedCategoryIds.Contains(c.Id)).ToList().ForEach(c =>
                                                                                                                             attributeModel.Categories.Add(c));
                edtAttribute.ActionTitle = Rock.Constants.ActionTitle.Add(Rock.Model.Attribute.FriendlyTypeName);
            }
            else
            {
                edtAttribute.ActionTitle = Rock.Constants.ActionTitle.Edit(Rock.Model.Attribute.FriendlyTypeName);
                mdAttribute.Title        = ("Edit " + attributeModel.Name).FormatAsHtmlTitle();
            }

            Type type = null;

            if (attributeModel.EntityTypeId.HasValue)
            {
                type = EntityTypeCache.Read(attributeModel.EntityTypeId.Value).GetEntityType();
                edtAttribute.ReservedKeyNames = attributeService.Get(attributeModel.EntityTypeId, attributeModel.EntityTypeQualifierColumn, attributeModel.EntityTypeQualifierValue)
                                                .Where(a => a.Id != attributeId)
                                                .Select(a => a.Key)
                                                .Distinct()
                                                .ToList();
            }

            edtAttribute.SetAttributeProperties(attributeModel, type);
            edtAttribute.AttributeEntityTypeId = attributeModel.EntityTypeId;

            if (_configuredType)
            {
                pnlEntityTypeQualifier.Visible = false;
            }
            else
            {
                pnlEntityTypeQualifier.Visible = true;

                ddlAttrEntityType.SetValue(attributeModel.EntityTypeId.HasValue ? attributeModel.EntityTypeId.Value.ToString() : "0");
                tbAttrQualifierField.Text = attributeModel.EntityTypeQualifierColumn;
                tbAttrQualifierValue.Text = attributeModel.EntityTypeQualifierValue;
            }

            ShowDialog("Attribute", true);
        }
예제 #28
0
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        private void LoadExistingRockData()
        {
            var lookupContext         = new RockContext();
            var attributeValueService = new AttributeValueService(lookupContext);
            var attributeService      = new AttributeService(lookupContext);

            IntegerFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.INTEGER)).Id;
            TextFieldTypeId    = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT)).Id;
            PersonEntityTypeId = EntityTypeCache.Read("Rock.Model.Person").Id;
            CampusList         = CampusCache.All(lookupContext);

            int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id;
            int batchEntityTypeId     = EntityTypeCache.Read("Rock.Model.FinancialBatch").Id;
            int userLoginTypeId       = EntityTypeCache.Read("Rock.Model.UserLogin").Id;

            int visitInfoCategoryId = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId)
                                      .Where(c => c.Name == "Visit Information").Select(c => c.Id).FirstOrDefault();

            // Look up and create attributes for F1 unique identifiers if they don't exist
            var personAttributes = attributeService.GetByEntityTypeId(PersonEntityTypeId).ToList();

            var householdAttribute = personAttributes.FirstOrDefault(a => a.Key == "F1HouseholdId");

            if (householdAttribute == null)
            {
                householdAttribute                           = new Rock.Model.Attribute();
                householdAttribute.Key                       = "F1HouseholdId";
                householdAttribute.Name                      = "F1 Household Id";
                householdAttribute.FieldTypeId               = IntegerFieldTypeId;
                householdAttribute.EntityTypeId              = PersonEntityTypeId;
                householdAttribute.EntityTypeQualifierValue  = string.Empty;
                householdAttribute.EntityTypeQualifierColumn = string.Empty;
                householdAttribute.Description               = "The FellowshipOne household identifier for the person that was imported";
                householdAttribute.DefaultValue              = string.Empty;
                householdAttribute.IsMultiValue              = false;
                householdAttribute.IsRequired                = false;
                householdAttribute.Order                     = 0;

                lookupContext.Attributes.Add(householdAttribute);
                lookupContext.SaveChanges(DisableAudit);
                personAttributes.Add(householdAttribute);
            }

            var individualAttribute = personAttributes.FirstOrDefault(a => a.Key == "F1IndividualId");

            if (individualAttribute == null)
            {
                individualAttribute                           = new Rock.Model.Attribute();
                individualAttribute.Key                       = "F1IndividualId";
                individualAttribute.Name                      = "F1 Individual Id";
                individualAttribute.FieldTypeId               = IntegerFieldTypeId;
                individualAttribute.EntityTypeId              = PersonEntityTypeId;
                individualAttribute.EntityTypeQualifierValue  = string.Empty;
                individualAttribute.EntityTypeQualifierColumn = string.Empty;
                individualAttribute.Description               = "The FellowshipOne individual identifier for the person that was imported";
                individualAttribute.DefaultValue              = string.Empty;
                individualAttribute.IsMultiValue              = false;
                individualAttribute.IsRequired                = false;
                individualAttribute.Order                     = 0;

                lookupContext.Attributes.Add(individualAttribute);
                lookupContext.SaveChanges(DisableAudit);
                personAttributes.Add(individualAttribute);
            }

            var secondaryEmailAttribute = personAttributes.FirstOrDefault(a => a.Key == "SecondaryEmail");

            if (secondaryEmailAttribute == null)
            {
                secondaryEmailAttribute                           = new Rock.Model.Attribute();
                secondaryEmailAttribute.Key                       = "SecondaryEmail";
                secondaryEmailAttribute.Name                      = "Secondary Email";
                secondaryEmailAttribute.FieldTypeId               = TextFieldTypeId;
                secondaryEmailAttribute.EntityTypeId              = PersonEntityTypeId;
                secondaryEmailAttribute.EntityTypeQualifierValue  = string.Empty;
                secondaryEmailAttribute.EntityTypeQualifierColumn = string.Empty;
                secondaryEmailAttribute.Description               = "The secondary email for this person";
                secondaryEmailAttribute.DefaultValue              = string.Empty;
                secondaryEmailAttribute.IsMultiValue              = false;
                secondaryEmailAttribute.IsRequired                = false;
                secondaryEmailAttribute.Order                     = 0;

                lookupContext.Attributes.Add(secondaryEmailAttribute);
                var visitInfoCategory = new CategoryService(lookupContext).Get(visitInfoCategoryId);
                secondaryEmailAttribute.Categories.Add(visitInfoCategory);
                lookupContext.SaveChanges(DisableAudit);
            }

            IndividualAttributeId     = individualAttribute.Id;
            HouseholdAttributeId      = householdAttribute.Id;
            SecondaryEmailAttributeId = secondaryEmailAttribute.Id;

            ReportProgress(0, "Checking for existing data...");
            var listHouseholdId  = attributeValueService.GetByAttributeId(householdAttribute.Id).Select(av => new { PersonId = av.EntityId, HouseholdId = av.Value }).ToList();
            var listIndividualId = attributeValueService.GetByAttributeId(individualAttribute.Id).Select(av => new { PersonId = av.EntityId, IndividualId = av.Value }).ToList();

            // var listHouseholdId = new PersonService().Queryable().Select( )

            ImportedPeople = listHouseholdId.GroupJoin(listIndividualId,
                                                       household => household.PersonId,
                                                       individual => individual.PersonId,
                                                       (household, individual) => new ImportedPerson
            {
                PersonAliasId = household.PersonId,
                HouseholdId   = household.HouseholdId.AsType <int?>(),
                IndividualId  = individual.Select(i => i.IndividualId.AsType <int?>()).FirstOrDefault()
            }
                                                       ).ToList();

            ImportedBatches = new FinancialBatchService(lookupContext).Queryable()
                              .Where(b => b.ForeignId != null)
                              .Select(b => new { F1Id = b.ForeignId, BatchId = b.Id })
                              .ToDictionary(t => t.F1Id.AsType <int>(), t => (int?)t.BatchId);
        }
예제 #29
0
        /// <summary>
        /// Gets the entity fields.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="includeOnlyReportingFields">if set to <c>true</c> [include only reporting fields].</param>
        /// <returns></returns>
        public static List <EntityField> GetEntityFields(Type entityType, bool includeOnlyReportingFields = true)
        {
            List <EntityField> entityFields = null;

            if (HttpContext.Current != null)
            {
                entityFields = HttpContext.Current.Items[string.Format("EntityHelper:GetEntityFields:{0}", entityType.FullName)] as List <EntityField>;
                if (entityFields != null)
                {
                    return(entityFields);
                }
            }

            entityFields = new List <EntityField>();

            // Find all non-virtual properties or properties that have the [IncludeForReporting] attribute
            var entityProperties         = entityType.GetProperties().ToList();
            var filteredEntityProperties = entityProperties
                                           .Where(p =>
                                                  !p.GetGetMethod().IsVirtual ||
                                                  p.GetCustomAttributes(typeof(IncludeForReportingAttribute), true).Any() ||
                                                  p.Name == "Order")
                                           .ToList();

            // Get Properties
            foreach (var property in filteredEntityProperties)
            {
                bool isReportable = !property.GetCustomAttributes(typeof(HideFromReportingAttribute), true).Any();
                if (!includeOnlyReportingFields || isReportable)
                {
                    //
                    // Determine the appropriate Field Type for this Property.
                    //

                    // Check if the Field Type has been explicitly set using an Attribute.
                    string fieldTypeGuidText = null;

                    var reportingFieldAttribute = property.GetCustomAttributes(typeof(Rock.Data.ReportingFieldAttribute), true).FirstOrDefault() as ReportingFieldAttribute;

                    if (reportingFieldAttribute != null)
                    {
                        fieldTypeGuidText = reportingFieldAttribute.FilterFieldTypeGuid.AsGuidOrNull().ToStringSafe();
                    }
                    else
                    {
                        // Infer the Field Type from the Property Type.
                        // Enum Properties
                        if (property.PropertyType.IsEnum)
                        {
                            fieldTypeGuidText = SystemGuid.FieldType.SINGLE_SELECT;
                        }
                        // Boolean properties
                        else if (property.PropertyType == typeof(bool) || property.PropertyType == typeof(bool?))
                        {
                            fieldTypeGuidText = SystemGuid.FieldType.BOOLEAN;
                        }
                        // Datetime properties
                        else if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime? ))
                        {
                            var colAttr = property.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault();
                            if (colAttr != null && ((ColumnAttribute)colAttr).TypeName == "Date")
                            {
                                fieldTypeGuidText = SystemGuid.FieldType.DATE;
                            }
                            else
                            {
                                fieldTypeGuidText = SystemGuid.FieldType.DATE_TIME;
                            }
                        }
                        // Decimal properties
                        else if (property.PropertyType == typeof(decimal) || property.PropertyType == typeof(decimal? ))
                        {
                            fieldTypeGuidText = SystemGuid.FieldType.DECIMAL;
                        }
                        // Text Properties
                        else if (property.PropertyType == typeof(string))
                        {
                            fieldTypeGuidText = SystemGuid.FieldType.TEXT;
                        }
                        // Integer Properties
                        else if (property.PropertyType == typeof(int) || property.PropertyType == typeof(int?))
                        {
                            var definedValueAttribute = property.GetCustomAttributes(typeof(Rock.Data.DefinedValueAttribute), true).FirstOrDefault();
                            if (definedValueAttribute != null)
                            {
                                fieldTypeGuidText = SystemGuid.FieldType.DEFINED_VALUE;
                            }
                            else
                            {
                                fieldTypeGuidText = SystemGuid.FieldType.INTEGER;
                            }
                        }
                    }

                    EntityField entityField = new EntityField(property.Name, FieldKind.Property, property.PropertyType);
                    entityField.IsPreviewable = property.GetCustomAttributes(typeof(PreviewableAttribute), true).Any();

                    entityField.FieldType = FieldTypeCache.Read(fieldTypeGuidText.AsGuid());

                    entityField.IsPreviewable = property.GetCustomAttributes(typeof(ReportingFieldAttribute), true).Any();

                    //
                    // Set additional configuration for some Field Types.
                    //

                    // Single Select Field
                    if (fieldTypeGuidText == SystemGuid.FieldType.SINGLE_SELECT)
                    {
                        var list = new List <string>();
                        foreach (var value in Enum.GetValues(property.PropertyType))
                        {
                            list.Add(string.Format("{0}^{1}", value, value.ToString().SplitCase()));
                        }

                        var listSource = string.Join(",", list);
                        entityField.FieldConfig.Add("values", new Field.ConfigurationValue(listSource));
                        entityField.FieldConfig.Add("fieldtype", new Field.ConfigurationValue("rb"));
                    }
                    // Defined Value Field
                    else if (fieldTypeGuidText == SystemGuid.FieldType.DEFINED_VALUE)
                    {
                        var definedValueAttribute = property.GetCustomAttributes(typeof(Rock.Data.DefinedValueAttribute), true).FirstOrDefault();

                        if (definedValueAttribute != null)
                        {
                            Guid?definedTypeGuid = ((Rock.Data.DefinedValueAttribute)definedValueAttribute).DefinedTypeGuid;
                            if (definedTypeGuid.HasValue)
                            {
                                var definedType = DefinedTypeCache.Read(definedTypeGuid.Value);
                                entityField.Title = definedType != null ? definedType.Name : property.Name.Replace("ValueId", string.Empty).SplitCase();
                                if (definedType != null)
                                {
                                    entityField.FieldConfig.Add("definedtype", new Field.ConfigurationValue(definedType.Id.ToString()));
                                }
                            }
                        }
                    }

                    if (entityField.FieldType != null)
                    {
                        entityFields.Add(entityField);
                    }
                }
            }

            // Get Attributes
            var entityTypeCache = EntityTypeCache.Read(entityType, true);

            if (entityTypeCache != null)
            {
                int entityTypeId = entityTypeCache.Id;
                using (var rockContext = new RockContext())
                {
                    var qryAttributes = new AttributeService(rockContext).Queryable().Where(a => a.EntityTypeId == entityTypeId);
                    if (entityType == typeof(Group))
                    {
                        // in the case of Group, show attributes that are entity global, but also ones that are qualified by GroupTypeId
                        qryAttributes = qryAttributes
                                        .Where(a =>
                                               a.EntityTypeQualifierColumn == null ||
                                               a.EntityTypeQualifierColumn == string.Empty ||
                                               a.EntityTypeQualifierColumn == "GroupTypeId");
                    }
                    else
                    {
                        qryAttributes = qryAttributes.Where(a => a.EntityTypeQualifierColumn == string.Empty && a.EntityTypeQualifierValue == string.Empty);
                    }

                    var attributeIdList = qryAttributes.Select(a => a.Id).ToList();

                    foreach (var attributeId in attributeIdList)
                    {
                        AddEntityFieldForAttribute(entityFields, AttributeCache.Read(attributeId));
                    }
                }
            }

            // Order the fields by title, name
            int index        = 0;
            var sortedFields = new List <EntityField>();

            foreach (var entityField in entityFields.OrderBy(p => p.Title).ThenBy(p => p.Name))
            {
                entityField.Index = index;
                index++;
                sortedFields.Add(entityField);
            }

            if (HttpContext.Current != null)
            {
                HttpContext.Current.Items[string.Format("EntityHelper:GetEntityFields:{0}", entityType.FullName)] = sortedFields;
            }

            return(sortedFields);
        }