Example #1
0
        /// <summary>
        /// Loads the Content Channel data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadContentChannel(CSVInstance csvData)
        {
            var lookupContext             = new RockContext();
            var contentChannelService     = new ContentChannelService(lookupContext);
            var contentChannelTypeService = new ContentChannelTypeService(lookupContext);
            var groupService = new GroupService(lookupContext);

            // Look for custom attributes in the Content Channel file
            var allFields        = csvData.TableNodes.FirstOrDefault().Children.Select((node, index) => new { node = node, index = index }).ToList();
            var customAttributes = allFields
                                   .Where(f => f.index > ContentChannelParentId)
                                   .ToDictionary(f => f.index, f => f.node.Name);

            var completed            = 0;
            var importedCount        = 0;
            var alreadyImportedCount = contentChannelService.Queryable().AsNoTracking().Count(c => c.ForeignKey != null);

            ReportProgress(0, $"Starting Content Channel import ({alreadyImportedCount:N0} already exist).");

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ((row = csvData.Database.FirstOrDefault()) != null)
            {
                var rowContentChannelName             = row[ContentChannelName];
                var rowContentChannelTypeName         = row[ContentChannelTypeName];
                var rowContentChannelDescription      = row[ContentChannelDescription];
                var rowContentChannelId               = row[ContentChannelId];
                var rowContentChannelRequiresApproval = row[ContentChannelRequiresApproval];
                var rowContentChannelParentId         = row[ContentChannelParentId];

                var rowChannelId = rowContentChannelId.AsType <int?>();

                var requiresApproval = ( bool )ParseBoolOrDefault(rowContentChannelRequiresApproval, false);

                var contentChannelTypeId = 0;
                if (contentChannelTypeService.Queryable().AsNoTracking().FirstOrDefault(t => t.Name.ToLower() == rowContentChannelTypeName.ToLower()) != null)
                {
                    contentChannelTypeId = contentChannelTypeService.Queryable().AsNoTracking().FirstOrDefault(t => t.Name.ToLower() == rowContentChannelTypeName.ToLower()).Id;
                }

                //
                // Verify the Content Channel Type Exists
                //
                if (contentChannelTypeId < 1)
                {
                    var newConentChannelType = new ContentChannelType
                    {
                        Name            = rowContentChannelTypeName,
                        DateRangeType   = ContentChannelDateType.DateRange,
                        IncludeTime     = true,
                        DisablePriority = true,
                        CreatedDateTime = ImportDateTime
                    };

                    lookupContext.ContentChannelTypes.Add(newConentChannelType);
                    lookupContext.SaveChanges(DisableAuditing);

                    contentChannelTypeId = lookupContext.ContentChannelTypes.FirstOrDefault(t => t.Name == rowContentChannelTypeName).Id;
                }

                //
                // Check that this Content Channel doesn't already exist.
                //
                var exists = false;
                if (alreadyImportedCount > 0)
                {
                    exists = contentChannelService.Queryable().AsNoTracking().Any(c => c.ForeignKey == rowContentChannelId);
                }

                if (!exists)
                {
                    //
                    // Create and populate the new Content Channel.
                    //
                    var contentChannel = new ContentChannel
                    {
                        Name                 = rowContentChannelName,
                        Description          = rowContentChannelDescription,
                        ContentChannelTypeId = contentChannelTypeId,
                        ForeignKey           = rowContentChannelId,
                        ForeignId            = rowChannelId,
                        ContentControlType   = ContentControlType.HtmlEditor,
                        RequiresApproval     = requiresApproval
                    };

                    //
                    // Look for Parent Id and create appropriate objects.
                    //
                    if (!string.IsNullOrWhiteSpace(rowContentChannelParentId))
                    {
                        var ParentChannels = new List <ContentChannel>();
                        var parentChannel  = contentChannelService.Queryable().FirstOrDefault(p => p.ForeignKey == rowContentChannelParentId);
                        if (parentChannel.ForeignKey == rowContentChannelParentId)
                        {
                            ParentChannels.Add(parentChannel);
                            contentChannel.ParentContentChannels = ParentChannels;
                        }
                    }

                    // Save changes for context
                    lookupContext.WrapTransaction(() =>
                    {
                        lookupContext.ContentChannels.Add(contentChannel);
                        lookupContext.SaveChanges(DisableAuditing);
                    });

                    // Set security if needed
                    if (contentChannel.RequiresApproval)
                    {
                        var rockAdmins = groupService.Get(Rock.SystemGuid.Group.GROUP_ADMINISTRATORS.AsGuid());
                        contentChannel.AllowSecurityRole(Authorization.APPROVE, rockAdmins, lookupContext);

                        var communicationAdmins = groupService.Get(Rock.SystemGuid.Group.GROUP_COMMUNICATION_ADMINISTRATORS.AsGuid());
                        contentChannel.AllowSecurityRole(Authorization.APPROVE, communicationAdmins, lookupContext);

                        // Save security changes
                        lookupContext.WrapTransaction(() =>
                        {
                            lookupContext.SaveChanges(DisableAuditing);
                        });
                    }

                    //
                    // Process Attributes for Content Channels
                    //
                    if (customAttributes.Any())
                    {
                        // create content channel attributes
                        foreach (var newAttributePair in customAttributes)
                        {
                            var pairs                  = newAttributePair.Value.Split('^');
                            var categoryName           = string.Empty;
                            var attributeName          = string.Empty;
                            var attributeTypeString    = string.Empty;
                            var attributeForeignKey    = string.Empty;
                            var definedValueForeignKey = string.Empty;
                            var fieldTypeId            = TextFieldTypeId;

                            if (pairs.Length == 1)
                            {
                                attributeName = pairs[0];
                            }
                            else if (pairs.Length == 2)
                            {
                                attributeName       = pairs[0];
                                attributeTypeString = pairs[1];
                            }
                            else if (pairs.Length >= 3)
                            {
                                categoryName  = pairs[1];
                                attributeName = pairs[2];
                                if (pairs.Length >= 4)
                                {
                                    attributeTypeString = pairs[3];
                                }
                                if (pairs.Length >= 5)
                                {
                                    attributeForeignKey = pairs[4];
                                }
                                if (pairs.Length >= 6)
                                {
                                    definedValueForeignKey = pairs[5];
                                }
                            }

                            var definedValueForeignId = definedValueForeignKey.AsType <int?>();

                            //
                            // Translate the provided attribute type into one we know about.
                            //
                            fieldTypeId = GetAttributeFieldType(attributeTypeString);

                            if (string.IsNullOrEmpty(attributeName))
                            {
                                LogException("Content Channel Type", $"Content Channel Type Channel Attribute Name cannot be blank '{newAttributePair.Value}'.");
                            }
                            else
                            {
                                var fk = string.Empty;
                                if (string.IsNullOrWhiteSpace(attributeForeignKey))
                                {
                                    fk = $"Bulldozer_ContentChannelType_{contentChannelTypeId}_{categoryName.RemoveWhitespace()}_{attributeName.RemoveWhitespace()}".Left(100);
                                }
                                else
                                {
                                    fk = attributeForeignKey;
                                }

                                AddEntityAttribute(lookupContext, contentChannel.TypeId, "ContentChannelTypeId", contentChannelTypeId.ToString(), fk, categoryName, attributeName, string.Empty, fieldTypeId, true, definedValueForeignId, definedValueForeignKey, attributeTypeString: attributeTypeString);
                            }
                        }

                        //
                        // Add any Content Channel attribute values
                        //
                        foreach (var attributePair in customAttributes)
                        {
                            var newValue = row[attributePair.Key];

                            if (!string.IsNullOrWhiteSpace(newValue))
                            {
                                var pairs                  = attributePair.Value.Split('^');
                                var categoryName           = string.Empty;
                                var attributeName          = string.Empty;
                                var attributeTypeString    = string.Empty;
                                var attributeForeignKey    = string.Empty;
                                var definedValueForeignKey = string.Empty;

                                if (pairs.Length == 1)
                                {
                                    attributeName = pairs[0];
                                }
                                else if (pairs.Length == 2)
                                {
                                    attributeName       = pairs[0];
                                    attributeTypeString = pairs[1];
                                }
                                else if (pairs.Length >= 3)
                                {
                                    categoryName  = pairs[1];
                                    attributeName = pairs[2];
                                    if (pairs.Length >= 4)
                                    {
                                        attributeTypeString = pairs[3];
                                    }
                                    if (pairs.Length >= 5)
                                    {
                                        attributeForeignKey = pairs[4];
                                    }
                                    if (pairs.Length >= 6)
                                    {
                                        definedValueForeignKey = pairs[5];
                                    }
                                }

                                if (!string.IsNullOrEmpty(attributeName))
                                {
                                    string fk = string.Empty;
                                    if (string.IsNullOrWhiteSpace(attributeForeignKey))
                                    {
                                        fk = $"Bulldozer_ContentChannelType_{contentChannelTypeId}_{categoryName.RemoveWhitespace()}_{attributeName.RemoveWhitespace()}".Left(100);
                                    }
                                    else
                                    {
                                        fk = attributeForeignKey;
                                    }

                                    var attribute = FindEntityAttribute(lookupContext, categoryName, attributeName, contentChannel.TypeId, fk);
                                    AddEntityAttributeValue(lookupContext, attribute, contentChannel, newValue, null, true);
                                }
                            }
                        }
                    }

                    importedCount++;
                }

                //
                // Notify user of our status.
                //
                completed++;
                if (completed % (ReportingNumber * 10) < 1)
                {
                    ReportProgress(0, $"{completed:N0} Content Channel records processed, {importedCount:N0} imported.");
                }

                if (completed % ReportingNumber < 1)
                {
                    lookupContext.SaveChanges();
                    ReportPartialProgress();

                    // Clear out variables
                    contentChannelService = new ContentChannelService(lookupContext);
                }
            }

            //
            // Save any other changes to existing items.
            //
            lookupContext.SaveChanges();
            lookupContext.Dispose();

            ReportProgress(0, $"Finished Content Channel import: {importedCount:N0} records added.");

            return(completed);
        }