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();
        }
        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";
            }
        }
Example #3
0
        public void GetTemplateByProjectId_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        _configData.Email);
            var templateObject = invalidCredential.GetTemplatesByProjectId(_configData.TemplateId.ToString());

            Assert.IsNull(templateObject);
        }
Example #4
0
        public void GetFilesByItemId_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        _configData.Email);
            var fileObject = invalidCredential.GetFilesByItemId(_configData.ItemId);

            Assert.IsNull(fileObject);
        }
Example #5
0
        public void GetStatusById_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        "*****@*****.**");
            var statusObject = invalidCredential.GetStatusById(103613, 558644);

            Assert.IsNull(statusObject);
        }
Example #6
0
        public void GetProjectsByAccountId_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        "*****@*****.**");
            var projectObject = invalidCredential.GetProjectsByAccountId(30982);

            Assert.IsNull(projectObject);
        }
Example #7
0
        public void GetAccounts_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        _configData.Email);
            var accountObject = invalidCredential.GetAccounts();

            Assert.IsNull(accountObject);
        }
Example #8
0
        public void GetItemById_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        _configData.Email);
            var itemObject = invalidCredential.GetItemById("3891577");

            Assert.IsNull(itemObject);
        }
Example #9
0
        public void GetMe_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        "*****@*****.**");
            var meObject = invalidCredential.GetMe();

            Assert.IsNull(meObject);
        }
Example #10
0
        public void GetItemsByProjectId_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        _configData.Email);
            var itemObject = invalidCredential.GetItemsByProjectId(103614);

            Assert.IsNull(itemObject);
        }
Example #11
0
        public void GetStatusesByProjectId_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        "*****@*****.**");
            var statusObject = invalidCredential.GetStatusesByProjectId(1231);

            Assert.IsNull(statusObject);
        }
Example #12
0
        public void GetItemsByTemplateId_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        _configData.Email);
            var itemObject = invalidCredential.GetItemsByTemplateId(0000, 14041);

            Assert.IsNotNull(itemObject);
            Assert.AreEqual(itemObject.Count, 0);
        }
Example #13
0
        public void GetTemplatesByIds_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        _configData.Email);
            var templateIds = new List <int> {
                _configData.TemplateId
            };
            var templateObject = invalidCredential.GetTemplatesByIds(templateIds);

            Assert.IsNotNull(templateObject);
            Assert.AreEqual(templateObject.ToList()[0].Data, null);
            Assert.AreEqual(templateObject.ToList().Count, 1);
        }
Example #14
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;
        }
Example #15
0
        public void GetStatusesByIds_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        _configData.Email);
            var idList = new List <int>()
            {
                558644, 558649
            };
            var statusObject = invalidCredential.GetStatusesByIds(103613, idList);

            Assert.AreEqual(statusObject.ToList()[0].Data, null);
            Assert.AreEqual(statusObject.ToList()[1].Data, null);
            Assert.AreEqual(statusObject.ToList().Count, 2);
        }
Example #16
0
        public void GetAccountsByIds_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        "*****@*****.**");
            var idList = new List <int>()
            {
                _configData.AccountId
            };
            var accountObject = invalidCredential.GetAccountsByIds(idList);

            Assert.IsNotNull(accountObject);
            Assert.AreEqual(accountObject.ToList()[0].Data, null);
            Assert.AreEqual(accountObject.ToList().Count, 1);
        }
Example #17
0
        public void GetItemsByIds_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        _configData.Email);
            var itemIds = new List <int> {
                1577, 333333
            };
            var itemObject = invalidCredential.GetItemsByIds(itemIds);

            Assert.IsNotNull(itemObject);
            Assert.AreEqual(itemObject.ToList()[0].Data, null);
            Assert.AreEqual(itemObject.ToList()[1].Data, null);
            Assert.AreEqual(itemObject.ToList().Count, 2);
        }
Example #18
0
        public void GetProjectsByIds_InvalidCredential()
        {
            var invalidCredential = new GcConnectClient("abc",
                                                        "*****@*****.**");
            var idList = new List <int>()
            {
                100013, 003614
            };
            var projectObject = invalidCredential.GetProjectsByIds(idList);

            Assert.IsNotNull(projectObject);
            Assert.AreEqual(projectObject.ToList()[0].Data, null);
            Assert.AreEqual(projectObject.ToList()[1].Data, null);
            Assert.AreEqual(projectObject.ToList().Count, 2);
        }
Example #19
0
        private void PopulateForm()
        {
            if (_credentialsStore.IsNullOrEmpty())
            {
                Response.Write("<script>alert('Please setup the GatherContent config first!');" +
                               "window.location='/modules/GcEpiPlugin/GatherContentConfigSetup.aspx'</script>");
                Visible = false;
                return;
            }

            Client = new GcConnectClient(_credentialsStore.ToList().First().ApiKey, _credentialsStore.ToList().First().Email);
            var mappings = _mappingsStore.FindAll
                               (i => i.AccountId == _credentialsStore.ToList().First().AccountId);

            rptTableMappings.DataSource = mappings;
            rptTableMappings.DataBind();
        }
Example #20
0
        private void PopulateForm()
        {
            var credentialsStore = GcDynamicCredentials.RetrieveStore();

            if (credentialsStore.IsNullOrEmpty())
            {
                Response.Write("<script>alert('Please setup the GatherContent config first!');window.location='/modules/GatherContentImport/GatherContent.aspx'</script>");
                Visible = false;
                return;
            }
            Client = new GcConnectClient(credentialsStore.ToList().First().ApiKey,
                                         credentialsStore.ToList().First().Email);
            var mappings = GcDynamicTemplateMappings.RetrieveStore().FindAll
                               (i => i.AccountId == credentialsStore.ToList().First().AccountId);

            rptTableMappings.DataSource = mappings;
            rptTableMappings.DataBind();
        }
Example #21
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;
            }

            _client = new GcConnectClient(_credentialsStore.ToList().First().ApiKey, _credentialsStore.ToList().First().Email);
            var accountId = Convert.ToInt32(_credentialsStore.ToList().First().AccountId);

            Session["AccountId"] = accountId;
            accountName.Text     = _client.GetAccountById(accountId).Name;
            var projects = _client.GetProjectsByAccountId(accountId);

            projects.ToList().ForEach(i => rblGcProjects.Items.Add(new ListItem(i.Name, i.Id.ToString())));
            rblGcProjects.SelectedIndex = 0;
            Session["ProjectId"]        = rblGcProjects.SelectedValue;
            Session["PostType"]         = null;
            Session["Author"]           = null;
            Session["DefaultStatus"]    = null;
        }
Example #22
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>");
            }
        }
Example #23
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>");
        }
Example #24
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();
        }
Example #25
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}";
        }
Example #26
0
        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();
        }
Example #27
0
        private void PopulateForm()
        {
            var credentialsStore = GcDynamicCredentials.RetrieveStore();

            Session["TemplateId"] = Server.UrlDecode(Request.QueryString["TemplateId"]);
            Session["ProjectId"]  = Server.UrlDecode(Request.QueryString["ProjectId"]);
            if (credentialsStore.IsNullOrEmpty())
            {
                Response.Write("<script>alert('Please setup your GatherContent config first!');window.location='/modules/GatherContentImport/GatherContent.aspx'</script>");
                Visible = false;
                return;
            }

            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/GatherContentImport/GcEpiTemplateMappings.aspx'</script>");
                Visible = false;
                return;
            }
            var currentMapping = GcDynamicTemplateMappings
                                 .RetrieveStore().First(i => i.TemplateId == Session["TemplateId"].ToString());

            Client = new GcConnectClient(credentialsStore.ToList().First().ApiKey, credentialsStore.ToList().First().Email);
            var templateId = Convert.ToInt32(Session["TemplateId"]);
            var gcTemplate = Client.GetTemplateById(templateId);

            templateName.Text = gcTemplate.Name;
            var projectId = Convert.ToInt32(Session["ProjectId"]);

            projectName.Text         = Client.GetProjectById(projectId).Name;
            templateDescription.Text = gcTemplate.Description;
            var contentRepository = ServiceLocator.Current.GetInstance <IContentRepository>();
            var recycleBin        = contentRepository.GetDescendents(ContentReference.Parse("2")).ToList();

            switch (currentMapping.PostType)
            {
            case "PageType":
                ddlDefaultParent.Items.Add(new ListItem("Root Page", "1"));
                foreach (var cr in contentRepository.GetDescendents(ContentReference.RootPage))
                {
                    try
                    {
                        var pageData = contentRepository.Get <PageData>(cr);
                        if (recycleBin.Contains(pageData.ContentLink) || pageData.ContentLink.ID == 2)
                        {
                            continue;
                        }
                        ddlDefaultParent.Items.Add(new ListItem(pageData.PageName, pageData.ContentLink.ID.ToString()));
                    }
                    catch (TypeMismatchException ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
                break;

            case "BlockType":

                // Add the root parent before everything else.
                ddlDefaultParent.Items.Add(new ListItem("SysGlobalAssets", "3"));
                foreach (var cr in contentRepository.GetDescendents(ContentReference.Parse("3")))
                {
                    try
                    {
                        var blockData = contentRepository.Get <ContentFolder>(cr);
                        // ReSharper disable once SuspiciousTypeConversion.Global
                        var content = blockData as IContent;

                        // If the block is in recycle bin,
                        // Then do not add it to the drop down.
                        if (recycleBin.Contains(content.ContentLink))
                        {
                            continue;
                        }


                        // ReSharper disable once PossibleNullReferenceException
                        if (recycleBin.Contains(content.ContentLink) || content.ContentLink.ID == 2)
                        {
                            continue;
                        }
                        ddlDefaultParent.Items.Add(new ListItem(content.Name, content.ContentLink.ID.ToString()));
                    }
                    catch (TypeMismatchException ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
                break;
            }
            rptGcItems.DataSource = Client.GetItemsByTemplateId(templateId, projectId);
            rptGcItems.DataBind();
        }
        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 || Session["TemplateId"] == null ||
                Session["PostType"] == null || (string)Session["PostType"] == "-1")
            {
                Response.Write("<script>alert('Please set the MetaDataProducer Defaults!');" +
                               "window.location='/modules/GcEpiPlugin/NewGcMappingStep3.aspx'</script>");
                Visible = false;
                return;
            }
            // Variables initialization.
            _client = new GcConnectClient(_credentialsStore.ToList().First().ApiKey, _credentialsStore.ToList().First().Email);
            var projectId  = Convert.ToInt32(Session["ProjectId"]);
            var templateId = Convert.ToInt32(Session["TemplateId"]);
            var gcFields   = _client.GetTemplateById(templateId).Config.ToList();

            gcFields.ForEach(i => _elements.AddRange(i.Elements));

            // Setting the mark-up labels.
            projectName.Text         = _client.GetProjectById(projectId).Name;
            templateName.Text        = _client.GetTemplateById(templateId).Name;
            templateDescription.Text = _client.GetTemplateById(templateId).Description;

            // Table rows instantiation and updating.
            var tHeadRow = new TableRow {
                Height = 42
            };

            tHeadRow.Cells.Add(new TableCell {
                Text = "GatherContent Field"
            });
            tHeadRow.Cells.Add(new TableCell {
                Text = "Mapped EPiServer Field"
            });
            tableMappings.Rows.Add(tHeadRow);
            foreach (var element in _elements.OrderByDescending(i => i.Type))
            {
                var tRow = new TableRow();
                tableMappings.Rows.Add(tRow);
                for (var cellIndex = 1; cellIndex <= 2; cellIndex++)
                {
                    var tCell = new TableCell {
                        Width = 500
                    };
                    if (cellIndex is 1)
                    {
                        tCell.Text =
                            $"<span style='font-weight: Bold;'>{element.Label + element.Title}</span><br>Type: {element.Type}<br>Limit: " +
                            $"{element.Limit}<br>Description: {element.MicroCopy}<br>";
                    }
                    else
                    {
                        if (Session["EpiContentType"].ToString().StartsWith("block-"))
                        {
                            var blockTypes = _contentTypeRepository.List().OfType <BlockType>();
                            tCell.Controls.Add(MetaDataProducer(blockTypes, element, 6));
                        }

                        else if (Session["EpiContentType"].ToString().StartsWith("page-"))
                        {
                            var pageTypes = _contentTypeRepository.List().OfType <PageType>();
                            tCell.Controls.Add(MetaDataProducer(pageTypes, element, 5));
                        }

                        else
                        {
                            var gcEpiMisc    = new GcEpiMiscUtility();
                            var dropDownList = MetaDataProducer(gcEpiMisc.GetMediaTypes(), element, 6);
                            tCell.Controls.Add(dropDownList);
                        }
                    }
                    tRow.Cells.Add(tCell);
                }
            }
        }
Example #29
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 || Session["TemplateId"] == null)
            {
                Response.Write("<script>alert('Please select the GatherContent Template!');" +
                               "window.location='/modules/GcEpiPlugin/NewGcMappingStep2.aspx'</script>");
                Visible = false;
                return;
            }
            EnableDdl();

            // Clear all the statically created drop down items to avoid data persistence on post-back.
            ddlAuthors.Items.Clear();
            ddlStatuses.Items.Clear();

            _client = new GcConnectClient(_credentialsStore.ToList().First().ApiKey, _credentialsStore.ToList().First().Email);
            var projectId  = Convert.ToInt32(Session["ProjectId"]);
            var templateId = Convert.ToInt32(Session["TemplateId"]);

            projectName.Text         = _client.GetProjectById(projectId).Name;
            templateName.Text        = _client.GetTemplateById(templateId).Name;
            templateDescription.Text = _client.GetTemplateById(templateId).Description;
            var userProvider = ServiceLocator.Current.GetInstance <UIUserProvider>();
            var epiUsers     = userProvider.GetAllUsers(0, 200, out int _);

            epiUsers.ToList().ForEach(epiUser => ddlAuthors.Items.Add(new ListItem(epiUser.Username, epiUser.Username)));
            var saveActions = Enum.GetValues(typeof(SaveAction)).Cast <SaveAction>().ToList();

            saveActions.RemoveAt(1);
            saveActions.ToList().ForEach(i => ddlStatuses.Items.Add(new ListItem(i.ToString(), i.ToString())));

            if (Session["PostType"] == null || Session["Author"] == null || Session["DefaultStatus"] == null)
            {
                ddlPostTypes.SelectedIndex = 0;
                ddlAuthors.SelectedIndex   = 0;
                ddlStatuses.SelectedIndex  = 0;
                Session["PostType"]        = ddlPostTypes.SelectedValue;
                Session["Author"]          = ddlAuthors.SelectedValue;
                Session["DefaultStatus"]   = ddlStatuses.SelectedValue;
            }
            else
            {
                ddlPostTypes.Items.Remove(ddlPostTypes.Items.FindByValue("-1"));
                ddlPostTypes.SelectedValue = Session["PostType"].ToString();
                ddlAuthors.SelectedValue   = Session["Author"].ToString();
                ddlStatuses.SelectedValue  = Session["DefaultStatus"].ToString();

                // Clear all the statically created drop down items to avoid data persistence on post-back.
                ddlEpiContentTypes.Items.Clear();

                if (Session["PostType"].ToString() is "PageType")
                {
                    var contentTypeList = _contentTypeRepository.List().OfType <PageType>();
                    var pageTypes       = contentTypeList as IList <PageType> ?? contentTypeList.ToList();
                    pageTypes.ToList().ForEach(i =>
                    {
                        if (i.ID != 1 && i.ID != 2)
                        {
                            ddlEpiContentTypes.Items.Add(new ListItem(i.DisplayName, "page-" + i.Name));
                        }
                    });
                    ddlEpiContentTypes.Enabled = true;
                    btnNextStep.Enabled        = true;
                }
                else if (Session["PostType"].ToString() is "BlockType")
                {
                    var contentTypeList = _contentTypeRepository.List().OfType <BlockType>();
                    var blockTypes      = contentTypeList as IList <BlockType> ?? contentTypeList.ToList();
                    blockTypes.ToList().ForEach(i => ddlEpiContentTypes.Items.Add(new ListItem(i.DisplayName, "block-" + i.Name)));
                    ddlEpiContentTypes.Enabled = true;
                    btnNextStep.Enabled        = true;
                }
                else
                {
                    var gcEpiMisc = new GcEpiMiscUtility();
                    gcEpiMisc.GetMediaTypes().ToList().
                    ForEach(i => ddlEpiContentTypes.Items.Add(new ListItem(i.DisplayName, "media-" + i.Name)));
                    ddlEpiContentTypes.Enabled = true;
                    btnNextStep.Enabled        = true;
                }
                if (Session["EpiContentType"] != null)
                {
                    ddlEpiContentTypes.SelectedValue = Session["EpiContentType"].ToString();
                }
            }
            var gcStatuses = _client.GetStatusesByProjectId(projectId);
            var tHeadRow   = new TableRow {
                Height = 42
            };

            tHeadRow.Cells.Add(new TableCell {
                Text = "GatherContent Status"
            });
            tHeadRow.Cells.Add(new TableCell {
                Text = "Mapped EPiServer Status"
            });
            //tHeadRow.Cells.Add(new TableCell { Text = "On Import, Change GatherContent Status" });
            tableGcStatusesMap.Rows.Add(tHeadRow);
            foreach (var status in gcStatuses)
            {
                var tRow = new TableRow();
                tableGcStatusesMap.Rows.Add(tRow);
                for (var cellIndex = 1; cellIndex <= 2; cellIndex++)//Need to make it the highest index, 3 in the next version.
                {
                    var tCell = new TableCell();
                    if (cellIndex is 3)
                    {
                        var ddlOnImportGcStatuses = new DropDownList {
                            Height = 30, Width = 250, CssClass = "chosen-select"
                        };
                        ddlOnImportGcStatuses.Items.Add(new ListItem("Do Not Change", "1"));
                        gcStatuses.ToList().ForEach(i => ddlOnImportGcStatuses.Items.Add(new ListItem(i.Name, i.Id)));
                        ddlOnImportGcStatuses.ID = "onImportGc-" + status.Id;
                        tCell.Controls.Add(ddlOnImportGcStatuses);
                    }
                    else if (cellIndex is 2)
                    {
                        var ddlEpiStatuses = new DropDownList {
                            Height = 30, Width = 250, CssClass = "chosen-select"
                        };
                        ddlEpiStatuses.Items.Add(new ListItem("Use Default Status", "Use Default Status"));
                        saveActions.ToList().ForEach(i => ddlEpiStatuses.Items.Add(new ListItem(i.ToString(), i.ToString())));
                        ddlEpiStatuses.ID = "mappedEPi-" + status.Id;
                        tCell.Controls.Add(ddlEpiStatuses);
                    }
                    else if (cellIndex is 1)
                    {
                        tCell.Text = status.Name;
                    }
                    tRow.Cells.Add(tCell);
                }
            }
        }
Example #30
0
 public void InitializeTests()
 {
     _configData   = new GcTestConfigData();
     _clientObject = new GcConnectClient(_configData.ApiKey, _configData.Email);
 }