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>"); } }
protected void BtnImportItem_OnClick(object sender, EventArgs e) { var contentStore = GcDynamicImports.RetrieveStore(); var importCount = 0; foreach (var key in Request.Form) { if (!key.ToString().Contains("chk")) { continue; } var importItem = true; var splitString = key.ToString().Split('$'); var credentialsStore = GcDynamicCredentials.RetrieveStore().ToList().First(); Client = new GcConnectClient(credentialsStore.ApiKey, credentialsStore.Email); var itemId = splitString[2].Substring(3); var item = Client.GetItemById(itemId); var currentMapping = GcDynamicTemplateMappings .RetrieveStore().First(i => i.TemplateId == Session["TemplateId"].ToString()); var parentId = Request.Form[key.ToString().Replace("chk", "ddl")]; var contentRepository = ServiceLocator.Current.GetInstance <IContentRepository>(); var contentTypeRepository = ServiceLocator.Current.GetInstance <IContentTypeRepository>(); switch (currentMapping.PostType) { case "PageType": var pageParent = parentId.IsEmpty() ? ContentReference.RootPage : ContentReference.Parse(parentId); var selectedPageType = currentMapping.EpiContentType; var pageTypeList = contentTypeRepository.List().OfType <PageType>(); var pageTypes = pageTypeList as List <PageType> ?? pageTypeList.ToList(); foreach (var pageType in pageTypes) { if (selectedPageType.Substring(5) != pageType.Name) { continue; } PageData myPage; try { myPage = contentRepository.GetDefault <PageData>(pageParent, pageType.ID); } catch (EPiServerException exception) { Console.WriteLine(exception); Response.Write("<script> alert('Invalid Parent Page ID! Try again!') </script>"); break; } foreach (var cs in contentStore) { try { if (cs.ItemId != item.Id) { continue; } var pageData = contentRepository.Get <PageData>(cs.ContentGuid); if (pageData.ParentLink.ID == 2) { GcDynamicImports.DeleteItem(cs.Id); } else { Response.Write("<script> alert('Page Already Exists!') </script>"); importItem = false; importCount = 0; break; } } catch (TypeMismatchException ex) { Console.WriteLine(ex); } } myPage.PageName = item.Name; foreach (var map in currentMapping.EpiFieldMaps) { var splitStrings = map.Split('~'); var fieldName = splitStrings[0]; var propDef = pageType.PropertyDefinitions.ToList().Find(p => p.Name == fieldName); if (propDef == null) { continue; } var configs = item.Config.ToList(); configs.ForEach(j => j.Elements.ForEach(x => { if (x.Name == splitStrings[1]) { myPage.Property[propDef.Name].Value = x.Value; } })); } if (!importItem) { continue; } { var saveActions = Enum.GetValues(typeof(SaveAction)).Cast <SaveAction>().ToList(); saveActions.RemoveAt(1); var gcStatusIdForThisItem = item.CurrentStatus.Data.Id; saveActions.ForEach(x => { if (x.ToString() == currentMapping.StatusMaps.Find(i => i.MappedEpiserverStatus.Split('~')[1] == gcStatusIdForThisItem).MappedEpiserverStatus.Split('~')[0]) { contentRepository.Save(myPage, x, AccessLevel.Administer); var dds = new GcDynamicImports(myPage.ContentGuid, item.Id, DateTime.Now); GcDynamicImports.SaveStore(dds); } else if (currentMapping.StatusMaps.Find(i => i.MappedEpiserverStatus.Split('~')[1] == gcStatusIdForThisItem) .MappedEpiserverStatus.Split('~')[0] == "Use Default Status") { if (x.ToString() != currentMapping.DefaultStatus) { return; } contentRepository.Save(myPage, x, AccessLevel.Administer); var dds = new GcDynamicImports(myPage.ContentGuid, item.Id, DateTime.Now); GcDynamicImports.SaveStore(dds); } }); importCount++; } } break; case "BlockType": var blockParent = parentId.IsEmpty() ? ContentReference.Parse("3") : ContentReference.Parse(parentId); var selectedBlockType = currentMapping.EpiContentType; var blockTypeList = contentTypeRepository.List().OfType <BlockType>(); var blockTypes = blockTypeList as IList <BlockType> ?? blockTypeList.ToList(); foreach (var blockType in blockTypes) { if (selectedBlockType.Substring(6) != blockType.Name) { continue; } BlockData myBlock; try { myBlock = contentRepository.GetDefault <BlockData>(blockParent, blockType.ID); } catch (EPiServerException exception) { Console.WriteLine(exception); Response.Write("<script> alert('Invalid Parent Block ID! Try again!') </script>"); break; } foreach (var cs in contentStore) { try { if (cs.ItemId != item.Id) { continue; } // ReSharper disable once SuspiciousTypeConversion.Global var blockData = contentRepository.Get <BlockData>(cs.ContentGuid) as IContent; // ReSharper disable once PossibleNullReferenceException if (blockData.ParentLink.ID == 2) { GcDynamicImports.DeleteItem(cs.Id); } else { Response.Write("<script> alert('Block Already Exists!') </script>"); importItem = false; break; } } catch (TypeMismatchException ex) { Console.WriteLine(ex); } } // ReSharper disable once SuspiciousTypeConversion.Global var content = myBlock as IContent; // ReSharper disable once PossibleNullReferenceException content.Name = item.Name; foreach (var map in currentMapping.EpiFieldMaps) { var splitStrings = map.Split('~'); var fieldName = splitStrings[0]; var propDef = blockType.PropertyDefinitions.ToList().Find(p => p.Name == fieldName); if (propDef == null) { continue; } var configs = item.Config.ToList(); configs.ForEach(j => j.Elements.ForEach(x => { if (x.Name == splitStrings[1]) { myBlock.Property[propDef.Name].Value = x.Value; } })); } if (!importItem) { continue; } { var saveActions = Enum.GetValues(typeof(SaveAction)).Cast <SaveAction>().ToList(); saveActions.RemoveAt(1); var gcStatusIdForThisItem = item.CurrentStatus.Data.Id; saveActions.ForEach(x => { if (x.ToString() == currentMapping.StatusMaps.Find(i => i.MappedEpiserverStatus.Split('~')[1] == gcStatusIdForThisItem).MappedEpiserverStatus.Split('~')[0]) { contentRepository.Save(content, x, AccessLevel.Administer); var dds = new GcDynamicImports(content.ContentGuid, item.Id, DateTime.Now); GcDynamicImports.SaveStore(dds); } else if (currentMapping.StatusMaps.Find(i => i.MappedEpiserverStatus.Split('~')[1] == gcStatusIdForThisItem) .MappedEpiserverStatus.Split('~')[0] == "Use Default Status") { if (x.ToString() != currentMapping.DefaultStatus) { return; } contentRepository.Save(content, x, AccessLevel.Administer); var dds = new GcDynamicImports(content.ContentGuid, item.Id, DateTime.Now); GcDynamicImports.SaveStore(dds); } }); importCount++; } } break; } } if (importCount == 1) { Response.Write("<script> alert('Item successfully imported!') </script>"); } else if (importCount > 1) { Response.Write($"<script> alert('{importCount} Items successfully imported!') </script>"); } else if (importCount == 0) { Response.Write("<script> alert('No items selected! Please select the checkbox next to the item you would " + "like to import!') </script>"); } PopulateForm(); }
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>"); }
protected void RptGcItems_OnItemCreated(object sender, RepeaterItemEventArgs e) { var gcItem = e.Item.DataItem as GcItem; var queryDefaultParentId = Server.UrlDecode(Request.QueryString["DefaultParentId"]); var enableItemFlag = true; var credentialsStore = GcDynamicCredentials.RetrieveStore().ToList().First(); var contentStore = GcDynamicImports.RetrieveStore(); var contentRepository = ServiceLocator.Current.GetInstance <IContentRepository>(); var parentId = ""; var recycleBin = contentRepository.GetDescendents(ContentReference.Parse("2")).ToList(); Client = new GcConnectClient(credentialsStore.ApiKey, credentialsStore.Email); var currentMapping = GcDynamicTemplateMappings .RetrieveStore().First(i => i.TemplateId == Session["TemplateId"].ToString()); if (gcItem == null) { return; } 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?.ToShortDateString(); } if (e.Item.FindControl("lnkIsImported") is HyperLink linkIsImported) { linkIsImported.Text = "---------"; if (currentMapping.PostType == "PageType") { _defaultParentId = queryDefaultParentId.IsNullOrEmpty() ? "1" : queryDefaultParentId; foreach (var cs in contentStore) { //Try to create page data of each page in the content store that matches the gcItemId. try { if (cs.ItemId != gcItem.Id) { continue; } var pageData = contentRepository.Get <PageData>(cs.ContentGuid); //Setting the parentId and making sure the drop down loads from Root Page. parentId = pageData.ParentLink.ID.ToString(); enableItemFlag = false; _defaultParentId = "1"; //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; } linkIsImported.Text = "Page Imported"; linkIsImported.NavigateUrl = pageData.LinkURL; break; } catch (Exception ex) { Console.WriteLine(ex); //This is in case the user moved the page to trash and deleted it permanently. if (ex is TypeMismatchException) { continue; } GcDynamicImports.DeleteItem(cs.Id); } } } else { _defaultParentId = queryDefaultParentId.IsNullOrEmpty() ? "3" : queryDefaultParentId; foreach (var cs in contentStore) { try { if (cs.ItemId != gcItem.Id) { continue; } // 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(); enableItemFlag = false; _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; } linkIsImported.Text = "Block Imported"; break; } catch (Exception ex) { Console.WriteLine(ex); //This is in case the user moved the block to trash and deleted it permanently. if (ex is TypeMismatchException) { continue; } GcDynamicImports.DeleteItem(cs.Id); } } } } if (e.Item.FindControl("ddlParentId") is DropDownList dropDownListParentId) { dropDownListParentId.ID = $"ddl{gcItem.Id}"; if (currentMapping.PostType == "PageType") { var parentData = contentRepository.Get <PageData>(ContentReference.Parse(_defaultParentId)); dropDownListParentId.Items.Add(new ListItem(parentData.PageName, parentData.ContentLink.ID.ToString())); foreach (var cr in contentRepository.GetDescendents(ContentReference.Parse(_defaultParentId))) { try { var pageData = contentRepository.Get <PageData>(cr); if (recycleBin.Contains(pageData.ContentLink) || pageData.ContentLink.ID == 2) { //if the page is in trash, then add recycle bin to the drop down. if (parentId == "2") { dropDownListParentId.Items.Add(new ListItem( contentRepository.Get <PageData>(ContentReference.WasteBasket).Name, "2")); } } else { dropDownListParentId.Items.Add(new ListItem(pageData.PageName, pageData.ContentLink.ID.ToString())); } } catch (TypeMismatchException ex) { Console.WriteLine(ex); } } } else { // ReSharper disable once SuspiciousTypeConversion.Global var parentData = contentRepository.Get <ContentFolder>(ContentReference.Parse(_defaultParentId)); // ReSharper disable once PossibleNullReferenceException dropDownListParentId.Items.Add(new ListItem(parentData.Name, parentData.ContentLink.ID.ToString())); foreach (var cr in contentRepository.GetDescendents(ContentReference.Parse(_defaultParentId))) { try { // ReSharper disable once SuspiciousTypeConversion.Global var contentFolder = contentRepository.Get <ContentFolder>(cr); // ReSharper disable once PossibleNullReferenceException if (parentId == "2") { dropDownListParentId.Items.Add(new ListItem( contentRepository.Get <PageData>(ContentReference.WasteBasket).Name, "2")); } dropDownListParentId.Items.Add(new ListItem(contentFolder.Name, contentFolder.ContentLink.ID.ToString())); } catch (TypeMismatchException ex) { Console.WriteLine(ex); } } } if (enableItemFlag) { dropDownListParentId.Enabled = true; } else { dropDownListParentId.SelectedValue = parentId; } } if (e.Item.FindControl("chkItem") is CheckBox checkBoxItem) { checkBoxItem.ID = $"chk{gcItem.Id}"; if (enableItemFlag) { checkBoxItem.Enabled = true; checkBoxItem.Visible = true; btnImportItem.Enabled = true; } } if (!(e.Item.FindControl("lnkItemName") is HyperLink linkItemName)) { return; } linkItemName.Text = gcItem.Name; linkItemName.NavigateUrl = $"https://{Client.GetAccountById(Convert.ToInt32(credentialsStore.AccountId)).Slug}" + $".gathercontent.com/item/{gcItem.Id}"; }