private void PopulateForm()
        {
            _credentialsStore = GcDynamicUtilities.RetrieveStore <GcDynamicCredentials>();
            ddlGcAccounts.Items.Clear();
            txtApiKey.Text       = string.Empty;
            txtEmailAddress.Text = string.Empty;
            if (_credentialsStore.IsNullOrEmpty())
            {
                return;
            }
            var email  = _credentialsStore.ToList().First().Email;
            var apiKey = _credentialsStore.ToList().First().ApiKey;

            txtEmailAddress.Text = email;
            txtApiKey.Text       = apiKey;
            _client = new GcConnectClient(apiKey, email);
            var accounts = _client.GetAccounts();

            accounts.ToList().ForEach(i => ddlGcAccounts.Items.Add(new ListItem(i.Name, i.Id)));
            if (!_credentialsStore.ToList().First().AccountId.IsNullOrEmpty())
            {
                ddlGcAccounts.SelectedValue = _credentialsStore.ToList().First().AccountId;
                //txtPlatformUrl.Text = $"https://{_client.GetAccountById(Convert.ToInt32(credentialsStore.ToList().First().AccountId)).Slug}.gathercontent.com";
            }
            else
            {
                ddlGcAccounts.SelectedIndex = 0;
                //txtPlatformUrl.Text = $"https://{_client.GetAccountById(Convert.ToInt32(ddlGcAccounts.SelectedValue)).Slug}.gathercontent.com";
            }
        }
        protected void BtnSave_OnClick(object sender, EventArgs e)
        {
            _credentialsStore = GcDynamicUtilities.RetrieveStore <GcDynamicCredentials>();
            var apiKey       = txtApiKey.Text;
            var emailAddress = txtEmailAddress.Text;

            _client = new GcConnectClient(apiKey, emailAddress);

            if (!_client.GetAccounts().IsNullOrEmpty())
            {
                var selectedAccount = Request.Form["ddlGcAccounts"];
                if (selectedAccount.IsNullOrEmpty())
                {
                    selectedAccount = _client.GetAccounts().ToList().First().Id;
                }
                _credentials = new GcDynamicCredentials(emailAddress, apiKey, selectedAccount);
                GcDynamicUtilities.SaveStore(_credentials);
                Response.Write($"<script>alert('Hello {_client.GetMe().FirstName}! You have successfully connected to" +
                               " the GatherContent API')</script>");
            }
            else
            {
                Response.Write("<script>alert('Invalid Email Address or ApiKey! Try again!')</script>");
                //txtPlatformUrl.Text = "";
                GcDynamicUtilities.ClearStore <GcDynamicCredentials>();
            }
            PopulateForm();
        }
예제 #3
0
        private void PopulateForm()
        {
            if (_credentialsStore.IsNullOrEmpty())
            {
                Response.Write("<script>alert('Please setup your GatherContent config first!');" +
                               "window.location='/modules/GcEpiPlugin/GatherContentConfigSetup.aspx'</script>");
                Visible = false;
                return;
            }

            if (Session["ProjectId"] == null)
            {
                Response.Write("<script>alert('Please select the GatherContent Project!');" +
                               "window.location='/modules/GcEpiPlugin/NewGcMappingStep1.aspx'</script>");
                Visible = false;
                return;
            }
            _client = new GcConnectClient(_credentialsStore.ToList().First().ApiKey, _credentialsStore.ToList().First().Email);
            var projectId = Convert.ToInt32(Session["ProjectId"]);

            projectName.Text = _client.GetProjectById(projectId).Name;
            var templates = _client.GetTemplatesByProjectId(Session["ProjectId"].ToString());
            var mappings  = GcDynamicUtilities.RetrieveStore <GcDynamicTemplateMappings>();
            var rblTemp   = new RadioButtonList();

            rblGcTemplates.Items.Clear();
            foreach (var template in templates)
            {
                if (mappings.Any(mapping => mapping.TemplateId == template.Id.ToString()))
                {
                    rblTemp.Items.Add(new ListItem($"{template.Name} &nbsp; <a href='/modules/GcEpiPlugin/ReviewItemsForImport.aspx?" +
                                                   $"TemplateId={template.Id}&ProjectId={projectId}'> " +
                                                   $"Review Items for Import </a> <br>{template.Description}", template.Id.ToString())
                    {
                        Enabled = false
                    });
                }
                else
                {
                    rblGcTemplates.Items.Add(new ListItem(template.Name + "<br>" + template.Description, template.Id.ToString()));
                }
            }
            foreach (ListItem item in rblTemp.Items)
            {
                rblGcTemplates.Items.Add(item);
            }
            Session["PostType"]      = null;
            Session["Author"]        = null;
            Session["DefaultStatus"] = null;
        }
        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");
        }
예제 #5
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>");
            }
        }
예제 #6
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>");
        }
예제 #7
0
        private void PopulateForm()
        {
            // Set the project and template Ids from query string.
            Session["TemplateId"] = Server.UrlDecode(Request.QueryString["TemplateId"]);
            Session["ProjectId"]  = Server.UrlDecode(Request.QueryString["ProjectId"]);

            // If the DDS for credentials is null or empty, turn off the page visibility and alert the user to set up the config.
            if (_credentialsStore.IsNullOrEmpty())
            {
                Response.Write("<script>alert('Please setup your GatherContent config first!');" +
                               "window.location='/modules/GcEpiPlugin/GatherContentConfigSetup.aspx'</script>");
                Visible = false;
                return;
            }

            // This is to validate the user to not access this page directly.
            if (Session["TemplateId"] == null || Session["ProjectId"] == null)
            {
                Response.Write("<script>alert('This page is not directly accessible! Review your GatherContent items from Template Mappings page!');" +
                               "window.location='/modules/GcEpiPlugin/GcEpiTemplateMappings.aspx'</script>");
                Visible = false;
                return;
            }

            // Local variables initialization and setting the values for some of the form components.
            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());

            // Make a usable templateId and projectId
            var templateId = Convert.ToInt32(Session["TemplateId"]);
            var projectId  = Convert.ToInt32(Session["ProjectId"]);

            // Fetch Template details from GatherContentConnect.
            var gcTemplate = Client.GetTemplateById(templateId);

            // Set the labels with the gathered values.
            templateName.Text        = gcTemplate.Name;
            projectName.Text         = Client.GetProjectById(projectId).Name;
            templateDescription.Text = gcTemplate.Description;

            // Fetch the items (if there are any) from trash.
            var recycleBin = _contentRepository.GetDescendents(ContentReference.WasteBasket).ToList();

            // This is to make sure that the drop down doesn't persist previous values upon page refresh.
            ddlDefaultParent.Items.Clear();

            // Create an empty list to store all the content descendants.
            List <IContent> sortedDescendants = new EditableList <IContent>();

            // Populating the default parent selection drop down based on the type of the post type.
            switch (currentMapping.PostType)
            {
            case "PageType":
                // Add the root parent before everything else.
                ddlDefaultParent.Items.Add(new ListItem("Root", "1"));

                SortContent <PageData>(_contentRepository.Get <PageData>(ContentReference.RootPage), sortedDescendants);
                foreach (var pageData in sortedDescendants)
                {
                    // If the page is in recycle bin or if the page itself is recycle bin,
                    // Then do not add it to the drop down.
                    if (recycleBin.Contains(pageData.ContentLink) || pageData.ContentLink.ID == 2)
                    {
                        continue;
                    }

                    // Fetch the page data of its immediate parent.
                    var parentPage = _contentRepository.Get <PageData>(pageData.ParentLink);

                    // Add the parent's name along with the page name to avoid the confusion between the same page names.
                    ddlDefaultParent.Items.Add(new ListItem(parentPage.Name + " => " + pageData.Name, pageData.ContentLink.ID.ToString()));
                }
                break;

            case "BlockType":
                // Add the root parent before everything else.
                ddlDefaultParent.Items.Add(new ListItem("SysGlobalAssets", "3"));

                SortContent <ContentFolder>(_contentRepository.Get <ContentFolder>(ContentReference.GlobalBlockFolder), sortedDescendants);
                foreach (var contentFolder in sortedDescendants)
                {
                    // If the block is in recycle bin,
                    // Then do not add it to the drop down.
                    if (recycleBin.Contains(contentFolder.ContentLink))
                    {
                        continue;
                    }

                    // Fetch the block data of its immediate parent.
                    var parentFolder = _contentRepository.Get <ContentFolder>(contentFolder.ParentLink);
                    // Add the parent's name along with the block name to avoid the confusion between the same block names.
                    ddlDefaultParent.Items.Add(new ListItem(parentFolder.Name + " => " + contentFolder.Name,
                                                            contentFolder.ContentLink.ID.ToString()));
                }
                break;
            }
            // Add the data source to the repeater and bind it.
            rptGcItems.DataSource = Client.GetItemsByTemplateId(templateId, projectId);
            rptGcItems.DataBind();
        }
예제 #8
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}";
        }
        public static async Task <bool> FileParserAsync(GcFile gcFile, string postType, ContentReference contentLink, SaveAction saveAction, string action)
        {
            // Initialize fileExtensions dictionary with all the supported audio, video and generic files.
            var fileExtensions = new Dictionary <string, List <string> >
            {
                { "Video", new List <string> {
                      "flv", "mp4", "webm", "avi", "wmv", "mpeg", "ogg", "mov", "ogv", "qt", "mp3", "pcm", "aac", "wma", "flac", "alac", "wav", "aiff"
                  } },
                { "Image", new List <string> {
                      "jpg", "jpeg", "jpe", "ico", "gif", "bmp", "png", "tga", "tiff", "eps", "svg", "webp"
                  } },
                { "Generic", new List <string> {
                      "pdf", "doc", "docx", "txt", "xsl", "xslx", "html", "css", "zip", "rtf", "rar", "csv", "xml", "log"
                  } }
            };

            // Get an instance of ContentAssetHelper class.
            var contentAssetHelper = ServiceLocator.Current.GetInstance <ContentAssetHelper>();

            // Get an existing content asset folder or create a new one
            contentLink = contentAssetHelper.GetOrCreateAssetFolder(contentLink).ContentLink;

            // Get an instance of IContentRepository.
            var contentRepository = ServiceLocator.Current.GetInstance <IContentRepository>();

            // Extract the file extension of the file by its name.
            var fileExtension = Path.GetExtension(gcFile.FileName).Replace(".", "");

            // Initialize a new MediaData object.
            MediaData file;

            if (fileExtensions["Image"].Contains(fileExtension))
            {
                file = contentRepository.GetDefault <GcEpiImageFile>(contentLink);
            }

            else if (fileExtensions["Generic"].Contains(fileExtension))
            {
                file = contentRepository.GetDefault <GcEpiGenericFile>(contentLink);
            }

            else if (fileExtensions["Video"].Contains(fileExtension))
            {
                file = contentRepository.GetDefault <GcEpiVideoFile>(contentLink);
            }

            else
            {
                return(false);
            }

            file.Name = gcFile.FileName;
            file.Property["GcFileInfo"].Value = gcFile.Id + "~" + gcFile.FileName + "~" + gcFile.ItemId;

            if (action == "Update")
            {
                // Check if the file is already imported.
                var importedFiles = ContentRepository.GetChildren <MediaData>(contentLink, CultureInfo.InvariantCulture).ToList();
                foreach (var importedFile in importedFiles)
                {
                    var propSubStrings           = importedFile.Property["GcFileInfo"].Value.ToString().Split('~');
                    var importedFileGcFileId     = Convert.ToInt32(propSubStrings[0]);
                    var importedFileGcFileName   = propSubStrings[1];
                    var importedFileGcFileItemId = Convert.ToInt32(propSubStrings[2]);
                    if (importedFileGcFileName != gcFile.FileName ||
                        importedFileGcFileItemId != gcFile.ItemId)
                    {
                        continue;
                    }
                    if (importedFileGcFileId == gcFile.Id)
                    {
                        return(false);
                    }
                    contentRepository.Delete(importedFile.ContentLink, true, AccessLevel.Administer);
                }
            }

            var blobFactory = ServiceLocator.Current.GetInstance <IBlobFactory>();

            try
            {
                using (var client = new HttpClient())
                {
                    using (var request = new HttpRequestMessage(new HttpMethod("GET"), $"https://api.gathercontent.com/files/{gcFile.Id}/download"))
                    {
                        request.Headers.TryAddWithoutValidation("Accept", "application/vnd.gathercontent.v0.5+json");

                        var creds = GcDynamicUtilities.RetrieveStore <GcDynamicCredentials>();

                        var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{creds.ToList().First().Email}:{creds.ToList().First().ApiKey}"));
                        request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");

                        var response = await client.SendAsync(request);

                        var byteArrayData = await response.Content.ReadAsByteArrayAsync();

                        var blob = blobFactory.CreateBlob(file.BinaryDataContainer, Path.GetExtension(gcFile.FileName));
                        using (var s = blob.OpenWrite())
                        {
                            var w = new StreamWriter(s);
                            w.BaseStream.Write(byteArrayData, 0, byteArrayData.Length);
                            w.Flush();
                        }
                        file.BinaryData = blob;
                        contentRepository.Save(file, saveAction, AccessLevel.Administer);
                        return(true);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }
        }