protected void BtnSaveMapping_OnClick(object sender, EventArgs e)
        {
            var epiFieldMaps = from string key in Request.Form.Keys
                               where key.StartsWith("meta-")
                               select Request.Form[key] + "~" + key.Substring(5);

            Session["EpiFieldMaps"] = epiFieldMaps.ToList();
            var mappingsStore = GcDynamicUtilities.RetrieveStore <GcDynamicTemplateMappings>();
            var newMapping    = new GcDynamicTemplateMappings(Session["AccountId"].ToString(), Session["ProjectId"].ToString(),
                                                              Session["TemplateId"].ToString(), Session["PostType"].ToString(), Session["Author"].ToString(),
                                                              Session["DefaultStatus"].ToString(), Session["EpiContentType"].ToString(), (List <GcEpiStatusMap>)Session["StatusMaps"],
                                                              (List <string>)Session["EpiFieldMaps"], $"{DateTime.Now.ToLocalTime():g}");
            var existingIndex = mappingsStore.FindIndex(i => i.TemplateId == Session["TemplateId"].ToString());

            if (existingIndex >= 0)
            {
                GcDynamicUtilities.DeleteItem <GcDynamicTemplateMappings>(mappingsStore[existingIndex].Id);
            }
            GcDynamicUtilities.SaveStore(newMapping);
            Session.Clear();
            Response.Redirect("~/modules/GcEpiPlugin/GcEpiTemplateMappings.aspx");
        }
示例#2
0
        protected void BtnDeleteTemplate_OnClick(object sender, EventArgs e)
        {
            var mappingCount = 0;

            foreach (var key in Request.Form)
            {
                if (!key.ToString().StartsWith("rptTableMappings"))
                {
                    continue;
                }
                var splitStrings = key.ToString().Split('$');
                var templateId   = splitStrings[2];

                var index = _mappingsStore.FindIndex(i => i.TemplateId == templateId);
                GcDynamicUtilities.DeleteItem <GcDynamicTemplateMappings>(_mappingsStore[index].Id);
                mappingCount++;
            }
            const string windowLocation = "window.location = '/modules/GcEpiPlugin/GcEpiTemplateMappings.aspx'";

            Response.Write(mappingCount > 0 ? $"<script>alert('{mappingCount} template mapping(s) successfully deleted!');" +
                           $"{windowLocation}</script>" :
                           "<script>alert('No mappings selected! Please select the checkbox next to the " +
                           $"mapping you would like to delete!');{windowLocation}</script>");
        }
示例#3
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>");
            }
        }
示例#4
0
        protected void RptGcItems_OnItemCreated(object sender, RepeaterItemEventArgs e)
        {
            // Initializing the local variables.
            Client = new GcConnectClient(_credentialsStore.First().ApiKey, _credentialsStore.First().Email);
            var gcItem = e.Item.DataItem as GcItem;
            var defaultParentIdFromQuery = Server.UrlDecode(Request.QueryString["DefaultParentId"]);
            var enableItemFlag           = true;
            var parentId = string.Empty;

            // 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());
            var recycleBin     = _contentRepository.GetDescendents(ContentReference.WasteBasket).ToList();

            if (gcItem == null)
            {
                return;
            }

            // Set the values of form components.
            if (e.Item.FindControl("statusName") is Label statusNameLabel)
            {
                statusNameLabel.Text = gcItem.CurrentStatus.Data.Name;
            }
            if (e.Item.FindControl("updatedAt") is Label updatedAtLabel)
            {
                updatedAtLabel.Text = gcItem.UpdatedAt.Date?.ToLocalTime().ToShortDateString();
            }
            if (e.Item.FindControl("lnkIsImported") is HyperLink linkIsImported)
            {
                linkIsImported.Text = "---------";
                _defaultParentId    = currentMapping.PostType == "PageType"
                    ? (defaultParentIdFromQuery ?? "1")
                    : (defaultParentIdFromQuery ?? "3");
                foreach (var cs in _contentStore)
                {
                    // Check if the item in the Gather Content items list is in the content store.
                    if (cs.ItemId != gcItem.Id)
                    {
                        /*
                         *  <summary>
                         *      We want to clear this list because we want the drop down to load from selected default parent and
                         *      if the previous item was already imported then the drop down would have all the options in them.
                         *      This helps in avoiding recursion-overhead. This also prevents data persistence on page reloads.
                         *  </summary>
                         */
                        _sortedContent.Clear();
                        continue;
                    }

                    // Item is already imported, so set the flag to false.
                    enableItemFlag = false;
                    if (currentMapping.PostType == "PageType")
                    {
                        try
                        {
                            var pageData = _contentRepository.Get <PageData>(cs.ContentGuid);

                            // Setting the parentId and making sure the drop down loads from Root Page.
                            _defaultParentId = "1";
                            parentId         = pageData.ParentLink.ID.ToString();

                            // If page is in trash, then set the import status to 'Page in Trash'.
                            if (recycleBin.Contains(pageData.ContentLink))
                            {
                                linkIsImported.Text = "Page in Trash";
                                parentId            = "2";
                                break;
                            }

                            // Set the import status to 'Page Imported' and add a link to the page.
                            linkIsImported.Text        = "Page Imported";
                            linkIsImported.NavigateUrl = pageData.LinkURL;
                            break;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                            if (ex is TypeMismatchException)
                            {
                                continue;
                            }

                            // This is in case the user moved the page to trash and deleted it permanently.
                            if (!(ex is ContentNotFoundException))
                            {
                                continue;
                            }
                            GcDynamicUtilities.DeleteItem <GcDynamicImports>(cs.Id);
                            enableItemFlag = true;
                        }
                    }
                    else
                    {
                        try
                        {
                            // ReSharper disable once SuspiciousTypeConversion.Global
                            var blockData = _contentRepository.Get <BlockData>(cs.ContentGuid) as IContent;
                            // ReSharper disable once PossibleNullReferenceException
                            // Setting the parentId and making sure the drop down loads from Root Folder.
                            parentId         = blockData.ParentLink.ID.ToString();
                            _defaultParentId = "3";

                            // If the block is in trash, then set the import status to 'Block in Trash'.
                            if (recycleBin.Contains(blockData.ContentLink))
                            {
                                linkIsImported.Text = "Block in Trash";
                                parentId            = "2";
                                break;
                            }

                            // Set the import status to 'Block Imported'.
                            linkIsImported.Text = "Block Imported";
                            break;
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                            if (ex is TypeMismatchException)
                            {
                                continue;
                            }

                            // This is in case the user moved the page to trash and deleted it permanently.
                            if (!(ex is ContentNotFoundException))
                            {
                                continue;
                            }
                            GcDynamicUtilities.DeleteItem <GcDynamicImports>(cs.Id);
                            enableItemFlag = true;
                        }
                    }
                }
            }
            if (e.Item.FindControl("ddlParentId") is DropDownList dropDownListParentId)
            {
                // This control sets the parent under which the items are imported.
                dropDownListParentId.ID = $"ddl{gcItem.Id}";
                if (currentMapping.PostType == "PageType")
                {
                    // Get the parent page data.
                    var parentData = _contentRepository.Get <PageData>(ContentReference.Parse(_defaultParentId));
                    dropDownListParentId.Items.Add(new ListItem(parentData.PageName, parentData.ContentLink.ID.ToString()));

                    // To reduce the recursion-overhead, we only sort the content once and store it in a global variable instead.
                    if (_sortedContent.IsNullOrEmpty())
                    {
                        SortContent <PageData>(_contentRepository.Get <PageData>(ContentReference.Parse(_defaultParentId)), _sortedContent);
                    }

                    foreach (var pageData in _sortedContent)
                    {
                        if (recycleBin.Contains(pageData.ContentLink) || pageData.ContentLink.ID == 2)
                        {
                            // If the page is in trash, then add recycle bin page to the drop down so that it can be shown as the parent.
                            if (parentId == "2")
                            {
                                dropDownListParentId.Items.Add(new ListItem(
                                                                   _contentRepository.Get <PageData>(ContentReference.WasteBasket).Name, "2"));
                            }
                        }
                        else
                        {
                            var parentPage = _contentRepository.Get <PageData>(pageData.ParentLink);
                            dropDownListParentId.Items.Add(new ListItem(parentPage.Name + " => " + pageData.Name,
                                                                        pageData.ContentLink.ID.ToString()));
                        }
                    }
                }
                else if (currentMapping.PostType == "BlockType")
                {
                    // Get the parent page data.
                    var parentData = _contentRepository.Get <ContentFolder>(ContentReference.Parse(_defaultParentId));
                    dropDownListParentId.Items.Add(new ListItem(parentData.Name, parentData.ContentLink.ID.ToString()));

                    // To reduce the recursion-overhead, we only sort the content once and store it in a global variable instead.
                    if (_sortedContent.IsNullOrEmpty())
                    {
                        SortContent <ContentFolder>(_contentRepository.Get <ContentFolder>(ContentReference.Parse(_defaultParentId)), _sortedContent);
                    }

                    if (parentId == "2")
                    {
                        // If the block is in trash, then add recycle bin page to the drop down so that it can be shown as the parent.
                        dropDownListParentId.Items.Add(new ListItem(
                                                           _contentRepository.Get <PageData>(ContentReference.WasteBasket).Name, "2"));
                    }

                    foreach (var contentFolder in _sortedContent)
                    {
                        var parentFolder = _contentRepository.Get <ContentFolder>(contentFolder.ParentLink);
                        dropDownListParentId.Items.Add(new ListItem(parentFolder.Name + " => " + contentFolder.Name, contentFolder.ContentLink.ID.ToString()));
                    }
                }

                // If item is enabled, then enable the drop down containing the parents. Else, set the drop down to the content's parent value.
                if (enableItemFlag)
                {
                    dropDownListParentId.Enabled = true;
                }
                else
                {
                    dropDownListParentId.SelectedValue = parentId;
                }
            }
            if (e.Item.FindControl("chkItem") is CheckBox checkBoxItemImport)
            {
                checkBoxItemImport.ID = $"chkImport{gcItem.Id}";
                if (enableItemFlag)
                {
                    checkBoxItemImport.Enabled = true;
                    checkBoxItemImport.Visible = true;
                    btnImportItem.Enabled      = true;
                }
            }

            if (e.Item.FindControl("chkUpdateContent") is CheckBox checkBoxItemUpdate)
            {
                if (!enableItemFlag)
                {
                    checkBoxItemUpdate.ID = $"chkUpdate{gcItem.Id}";
                    // ReSharper disable once PossibleInvalidOperationException
                    if (_contentStore.Any(i => i.ItemId == gcItem.Id &&
                                          gcItem.UpdatedAt.Date.Value.ToLocalTime() > i.ImportedAt))
                    {
                        var importedItem = _contentStore.Find(x => x.ItemId == gcItem.Id);
                        var content      = currentMapping.PostType == "PageType"
                            ? _contentRepository.Get <PageData>(importedItem.ContentGuid)
                                           // ReSharper disable once SuspiciousTypeConversion.Global
                            : _contentRepository.Get <BlockData>(importedItem.ContentGuid) as IContent;
                        // ReSharper disable once PossibleNullReferenceException
                        if (!recycleBin.Contains(content.ContentLink))
                        {
                            checkBoxItemUpdate.Enabled = true;
                            checkBoxItemUpdate.Visible = true;
                            btnUpdateItem.Enabled      = true;
                            btnUpdateItem.Visible      = true;
                        }
                    }
                }
            }

            if (e.Item.FindControl("importedOn") is Label importedOnLabel)
            {
                importedOnLabel.Text = enableItemFlag ? "---------"
                    : _contentStore.Find(x => x.ItemId == gcItem.Id).ImportedAt.ToShortDateString();
            }

            if (!(e.Item.FindControl("lnkItemName") is HyperLink linkItemName))
            {
                return;
            }
            linkItemName.Text        = gcItem.Name;
            linkItemName.NavigateUrl = $"https://{Client.GetAccountById(Convert.ToInt32(_credentialsStore.First().AccountId)).Slug}" +
                                       $".gathercontent.com/item/{gcItem.Id}";
        }