コード例 #1
0
        protected void BtnImportItem_OnClick(object sender, EventArgs e)
        {
            var importCounter = 0;
            var itemName      = string.Empty;

            Client = new GcConnectClient(_credentialsStore.First().ApiKey, _credentialsStore.First().Email);

            // This is to make sure we only fetch mappings associated with this GcAccount.
            _mappingsStore = GcDynamicUtilities.RetrieveStore <GcDynamicTemplateMappings>().
                             FindAll(i => i.AccountId == _credentialsStore.First().AccountId);

            // Fetch the mapping for current template.
            var currentMapping = _mappingsStore.First(i => i.TemplateId == Session["TemplateId"].ToString());

            // There is a duplicate value called 'Default' in the list of SaveActions. So, it needs to be removed.
            _saveActions.RemoveAt(1);

            // For all the items that were selected in the checkbox,
            foreach (var key in Request.Form)
            {
                // If the key is not of checkbox type, then continue.
                if (!key.ToString().Contains("chkImport"))
                {
                    continue;
                }

                // Set the  flag initially to 'true'.
                var importItemFlag = true;

                // The key consists of repeater Id in the first part. We only need the second part where 'chkImport' is present
                // and it is after '$'. So, we split the string on '$'.
                var itemSplitString = key.ToString().Split('$');

                // ItemId is extracted from the checkbox Id. The first part of it is always 'chkImport'. So, the Id to be extracted
                // from the 9th index.
                var itemId = itemSplitString[2].Substring(9);

                // Get the itemId from GatherContentConnect API with the Id we extracted in the previous step.
                var item = Client.GetItemById(itemId);

                // Get the item's name. This will be used for displaying the import message.
                itemName = item.Name;

                // We know that the item's parent path Id is in the drop down. And, both checkbox and drop down share the similar
                // naming convention. So, we just get the key that contains the value of that drop down's selected value.
                var parentId = Request.Form[key.ToString().Replace("chkImport", "ddl")];

                // Filtered files list contains only files that user wants to import.
                List <GcFile> filteredFiles;

                // Since the post type of the item is known beforehand, we can separate the import process for different post types.
                switch (currentMapping.PostType)
                {
                case "PageType":
                    var pageParent       = parentId.IsEmpty() ? ContentReference.RootPage : ContentReference.Parse(parentId);
                    var selectedPageType = currentMapping.EpiContentType;
                    var pageTypes        = _contentTypeRepository.List().OfType <PageType>().ToList();
                    foreach (var pageType in pageTypes)
                    {
                        if (selectedPageType.Substring(5) != pageType.Name)
                        {
                            continue;
                        }
                        var newPage = _contentRepository.GetDefault <PageData>(pageParent, pageType.ID);
                        foreach (var cs in _contentStore)
                        {
                            try
                            {
                                if (cs.ItemId != item.Id)
                                {
                                    continue;
                                }
                                Response.Write("<script> alert('Page Already Exists!') </script>");
                                importItemFlag = false;
                                importCounter  = 0;
                                break;
                            }
                            catch (TypeMismatchException ex)
                            {
                                Console.WriteLine(ex);
                            }
                        }
                        newPage.PageName = item.Name;
                        filteredFiles    = MapValuesFromGcToEpi(newPage, pageType, currentMapping, item);
                        if (!importItemFlag)
                        {
                            continue;
                        }
                        {
                            var saveAction = SaveContent(newPage, item, currentMapping);
                            filteredFiles.ForEach(async i =>
                            {
                                await GcEpiContentParser.FileParserAsync(i, "PageType", newPage.ContentLink, saveAction, "Import");
                            });
                            var dds = new GcDynamicImports(newPage.ContentGuid, item.Id, DateTime.Now.ToLocalTime());
                            GcDynamicUtilities.SaveStore(dds);
                            importCounter++;
                        }
                    }
                    break;

                case "BlockType":
                    var blockParent       = parentId.IsEmpty() ? ContentReference.GlobalBlockFolder : ContentReference.Parse(parentId);
                    var selectedBlockType = currentMapping.EpiContentType;
                    var blockTypes        = _contentTypeRepository.List().OfType <BlockType>().ToList();
                    foreach (var blockType in blockTypes)
                    {
                        if (selectedBlockType.Substring(6) != blockType.Name)
                        {
                            continue;
                        }
                        var newBlock = _contentRepository.GetDefault <BlockData>(blockParent, blockType.ID);
                        foreach (var cs in _contentStore)
                        {
                            try
                            {
                                if (cs.ItemId != item.Id)
                                {
                                    continue;
                                }
                                Response.Redirect("<script> alert('Block Already Exists!') </script>");
                                importItemFlag = false;
                                importCounter  = 0;
                                break;
                            }
                            catch (TypeMismatchException ex)
                            {
                                Console.WriteLine(ex);
                            }
                        }
                        // ReSharper disable once SuspiciousTypeConversion.Global
                        var content = newBlock as IContent;
                        // ReSharper disable once PossibleNullReferenceException
                        content.Name  = item.Name;
                        filteredFiles = MapValuesFromGcToEpi(content, blockType, currentMapping, item);
                        if (!importItemFlag)
                        {
                            continue;
                        }
                        {
                            var saveAction = SaveContent(content, item, currentMapping);
                            filteredFiles.ForEach(async i =>
                            {
                                await GcEpiContentParser.FileParserAsync(i, "BlockType", content.ContentLink, saveAction, "Import");
                            });
                            var dds = new GcDynamicImports(content.ContentGuid, item.Id, DateTime.Now.ToLocalTime());
                            GcDynamicUtilities.SaveStore(dds);
                            importCounter++;
                        }
                    }
                    break;
                }
            }
            string responseMessage;

            if (importCounter == 1)
            {
                responseMessage = $"alert('{itemName} successfully imported!');";
            }

            else if (importCounter > 1)
            {
                responseMessage = $"alert('{itemName} and {importCounter - 1} other items successfully imported!');";
            }

            else
            {
                responseMessage = "alert('No items selected! Please select the checkbox next to the item you would " +
                                  "like to import!');";
            }
            Response.Write($"<script> {responseMessage} window.location = '/modules/GcEpiPlugin/ReviewItemsForImport.aspx?" +
                           $"&TemplateId={Session["TemplateId"]}&ProjectId={Session["ProjectId"]}'</script>");
        }
コード例 #2
0
        protected void BtnUpdateItem_OnClick(object sender, EventArgs e)
        {
            var updateCounter = 0;

            _saveActions.RemoveAt(1);
            Client         = new GcConnectClient(_credentialsStore.First().ApiKey, _credentialsStore.First().Email);
            _mappingsStore = GcDynamicUtilities.RetrieveStore <GcDynamicTemplateMappings>().
                             FindAll(i => i.AccountId == _credentialsStore.First().AccountId);
            foreach (var key in Request.Form)
            {
                if (!key.ToString().Contains("chkUpdate"))
                {
                    continue;
                }
                var              itemSplitString = key.ToString().Split('$');
                var              itemId          = itemSplitString[2].Substring(9);
                var              gcItem          = Client.GetItemById(itemId);
                var              importedItem    = _contentStore.Find(x => x.ItemId.ToString() == itemId);
                var              currentMapping  = _mappingsStore.First(i => i.TemplateId == gcItem.TemplateId.ToString());
                SaveAction       saveAction;
                GcDynamicImports dds;

                // fetch all the GcFile collection for this item.
                List <GcFile> filteredFiles;
                switch (currentMapping.PostType)
                {
                case "PageType":
                    var pageToUpdate = _contentRepository.Get <PageData>(importedItem.ContentGuid);
                    var pageClone    = pageToUpdate.CreateWritableClone();
                    var pageType     = _contentTypeRepository.List().ToList()
                                       .Find(i => i.ID == pageClone.ContentTypeID);
                    filteredFiles = MapValuesFromGcToEpi(pageClone, pageType, currentMapping, gcItem);
                    GcDynamicUtilities.DeleteItem <GcDynamicImports>(_contentStore[_contentStore.FindIndex(i => i.ItemId.ToString() == itemId)].Id);
                    saveAction = SaveContent(pageClone, gcItem, currentMapping);
                    filteredFiles.ForEach(async i =>
                    {
                        await GcEpiContentParser.FileParserAsync(i, "PageType", pageClone.ContentLink, saveAction, "Update");
                    });
                    dds = new GcDynamicImports(pageClone.ContentGuid, gcItem.Id, DateTime.Now.ToLocalTime());
                    GcDynamicUtilities.SaveStore(dds);
                    updateCounter++;
                    break;

                case "BlockType":
                    var blockToUpdate = _contentRepository.Get <BlockData>(importedItem.ContentGuid);
                    // ReSharper disable once PossibleNullReferenceException
                    var blockClone = blockToUpdate.CreateWritableClone();
                    // ReSharper disable once SuspiciousTypeConversion.Global
                    var cloneContent = blockClone as IContent;
                    var blockType    = _contentTypeRepository.List().ToList()
                                       .Find(i => i.ID == cloneContent.ContentTypeID);
                    filteredFiles = MapValuesFromGcToEpi(cloneContent, blockType, currentMapping, gcItem);
                    GcDynamicUtilities.DeleteItem <GcDynamicImports>(_contentStore[_contentStore.FindIndex(i => i.ItemId.ToString() == itemId)].Id);
                    saveAction = SaveContent(cloneContent, gcItem, currentMapping);
                    filteredFiles.ForEach(async i =>
                    {
                        await GcEpiContentParser.FileParserAsync(i, "BlockType", cloneContent.ContentLink, saveAction, "Update");
                    });
                    dds = new GcDynamicImports(cloneContent.ContentGuid, gcItem.Id, DateTime.Now.ToLocalTime());
                    GcDynamicUtilities.SaveStore(dds);

                    updateCounter++;
                    break;
                }
                string responseMessage;
                if (updateCounter == 1)
                {
                    responseMessage = $"alert('{gcItem.Name} successfully updated!');";
                }

                else if (updateCounter > 1)
                {
                    responseMessage = $"alert('{gcItem.Name} and {updateCounter - 1} other items successfully updated!');";
                }

                else
                {
                    responseMessage = "alert('No items selected! Please select the checkbox in the Update Content column you would " +
                                      "like to update!');";
                }
                Response.Write($"<script> {responseMessage} window.location = '/modules/GcEpiPlugin/ReviewItemsForImport.aspx?" +
                               $"&TemplateId={Session["TemplateId"]}&ProjectId={Session["ProjectId"]}'</script>");
            }
        }
コード例 #3
0
        private List <GcFile> MapValuesFromGcToEpi(IContentData content, ContentType contentType, GcDynamicTemplateMappings currentMapping,
                                                   IGcItem gcItem)
        {
            // fetch all the GcFile collection for this item.
            var gcFiles = Client.GetFilesByItemId(gcItem.Id).ToList();

            // This list contains the fields of the attachments for which the media has to be imported.
            var mediaFieldsToImport = new List <string>();

            // Get all the configs of this item.
            var gcConfigs = gcItem.Config.ToList();

            foreach (var map in currentMapping.EpiFieldMaps)
            {
                // First part of the string contains Epi field name and second part contains the Gc field name.
                var fieldSplitStrings = map.Split('~');
                var epiFieldName      = fieldSplitStrings[0];
                var gcFieldName       = fieldSplitStrings[1];

                // Add the fields to 'mediaFieldsToImport' list whose Epi counter part is 'Import-Attachments'.
                if (!gcFiles.IsNullOrEmpty())
                {
                    if (gcFiles.Any(i => i.Field == gcFieldName && epiFieldName == "Import-Attachments"))
                    {
                        mediaFieldsToImport.Add(gcFieldName);
                    }
                }

                /*
                 *  <summary>
                 *      For the field name that matches the field name of Epi content type, find the GcElement whose name is
                 *      the extracted gcFieldName. Call a parser based on the GcElement type. (Files gets imported differently.)
                 *  </summary>
                 */
                var propDef = contentType.PropertyDefinitions.ToList().Find(p => p.Name == epiFieldName);
                if (propDef == null)
                {
                    continue;
                }
                foreach (var gcConfig in gcConfigs)
                {
                    foreach (var gcElement in gcConfig.Elements.ToList())
                    {
                        if (gcElement.Name != gcFieldName)
                        {
                            continue;
                        }
                        if (gcElement.Type == "text")
                        {
                            content.Property[propDef.Name].Value =
                                GcEpiContentParser.TextParser(gcElement.Value, propDef.Type.Name);
                        }
                        else if (gcElement.Type == "section")
                        {
                            content.Property[propDef.Name].Value =
                                GcEpiContentParser.TextParser(gcElement.Subtitle, propDef.Type.Name);
                        }

                        /*else if (gcElement.Type == "choice_radio" || gcElement.Type == "choice_checkbox")
                         *  content.Property[propDef.Name].Value =
                         *      GcEpiContentParser.ChoiceParser(gcElement.Options, gcElement.Type, propDef);*/
                    }
                }
            }

            // Return all the files if the selected value of that
            // field is 'Import-Attachments' and is in 'mediaFieldsToImport' list.
            return(gcFiles.Where(i => mediaFieldsToImport.Contains(i.Field)).ToList());
        }