Ejemplo n.º 1
0
        public static void ReplaceStaticTokens(
            StringBuilder stringBuilder,
            ModuleConfiguration config,
            bool isEditable,
            SuperFlexiDisplaySettings displaySettings,
            int moduleId,
            PageSettings pageSettings,
            SiteSettings siteSettings,
            out StringBuilder sb)
        {
            sb = stringBuilder;
            string featuredImageUrl       = String.IsNullOrWhiteSpace(config.InstanceFeaturedImage) ? string.Empty : WebUtils.GetRelativeSiteRoot() + config.InstanceFeaturedImage;
            string jsonObjName            = "sflexi" + moduleId.ToString() + (config.IsGlobalView ? "Modules" : "Items");
            string currentSkin            = string.Empty;
            string siteRoot               = WebUtils.GetRelativeSiteRoot();
            bool   publishedOnCurrentPage = true;

            if (HttpContext.Current != null && HttpContext.Current.Request.Params.Get("skin") != null)
            {
                currentSkin = SiteUtils.SanitizeSkinParam(HttpContext.Current.Request.Params.Get("skin")) + "/";
            }

            if (isEditable)
            {
                var pageModules = PageModule.GetPageModulesByModule(moduleId);
                if (pageModules.Where(pm => pm.PageId == pageSettings.PageId).ToList().Count() == 0)
                {
                    publishedOnCurrentPage = false;
                }
            }

            Module module = new Module(moduleId);

            if (module != null)
            {
                sb.Replace("$_ModuleTitle_$", module.ShowTitle ? String.Format(displaySettings.ModuleTitleFormat, module.ModuleTitle) : string.Empty);
                sb.Replace("$_RawModuleTitle_$", module.ModuleTitle);
                sb.Replace("$_ModuleGuid_$", module.ModuleGuid.ToString());
                if (String.IsNullOrWhiteSpace(config.ModuleFriendlyName))
                {
                    sb.Replace("$_FriendlyName_$", module.ModuleTitle);
                }

                siteSettings = new SiteSettings(module.SiteGuid);
            }
            if (!String.IsNullOrWhiteSpace(config.ModuleFriendlyName))
            {
                sb.Replace("$_FriendlyName_$", config.ModuleFriendlyName);
            }
            sb.Replace("$_FeaturedImageUrl_$", featuredImageUrl);
            sb.Replace("$_ModuleID_$", moduleId.ToString());
            sb.Replace("$_PageID_$", pageSettings.PageId.ToString());
            sb.Replace("$_PageUrl_$", siteRoot + pageSettings.Url.Replace("~/", ""));
            sb.Replace("$_PageName_$", siteRoot + pageSettings.PageName);
            //sb.Replace("$_ModuleLinks_$", isEditable ? SuperFlexiHelpers.GetModuleLinks(config, displaySettings, moduleId, pageSettings.PageId) : string.Empty);
            sb.Replace("$_ModuleLinks_$", isEditable ? SuperFlexiHelpers.GetModuleLinks(config, displaySettings, moduleId, publishedOnCurrentPage ? pageSettings.PageId : -1) : string.Empty);
            sb.Replace("$_JSONNAME_$", jsonObjName);
            sb.Replace("$_ModuleClass_$", SiteUtils.IsMobileDevice() && !String.IsNullOrWhiteSpace(config.MobileInstanceCssClass) ? config.MobileInstanceCssClass : config.InstanceCssClass);
            sb.Replace("$_ModuleTitleElement_$", module.HeadElement);
            sb.Replace("$_SiteID_$", siteSettings.SiteId.ToString());
            sb.Replace("$_SiteRoot_$", String.IsNullOrWhiteSpace(siteRoot) ? "/" : siteRoot);
            sb.Replace("$_SitePath_$", String.IsNullOrWhiteSpace(siteRoot) ? "/" : WebUtils.GetApplicationRoot() + "/Data/Sites/" + CacheHelper.GetCurrentSiteSettings().SiteId.ToInvariantString());
            sb.Replace("$_SkinPath_$", SiteUtils.DetermineSkinBaseUrl(currentSkin));
            sb.Replace("$_CustomSettings_$", config.CustomizableSettings); //this needs to be enhanced, a lot, right now we just dump the 'settings' where ever this token exists.
            sb.Replace("$_EditorType_$", siteSettings.EditorProviderName);
            sb.Replace("$_EditorSkin_$", siteSettings.EditorSkin.ToString());
            sb.Replace("$_EditorBasePath_$", WebUtils.ResolveUrl(ConfigurationManager.AppSettings["CKEditor:BasePath"]));
            sb.Replace("$_EditorConfigPath_$", WebUtils.ResolveUrl(ConfigurationManager.AppSettings["CKEditor:ConfigPath"]));
            sb.Replace("$_EditorToolbarSet_$", mojoPortal.Web.Editor.ToolBar.FullWithTemplates.ToString());
            sb.Replace("$_EditorTemplatesUrl_$", siteRoot + "/Services/CKeditorTemplates.ashx?cb=" + Guid.NewGuid().ToString());
            sb.Replace("$_EditorStylesUrl_$", siteRoot + "/Services/CKeditorStyles.ashx?cb=" + Guid.NewGuid().ToString().Replace("-", string.Empty));
            sb.Replace("$_DropFileUploadUrl_$", siteRoot + "/Services/FileService.ashx?cmd=uploadfromeditor&rz=true&ko=" + WebConfigSettings.KeepFullSizeImagesDroppedInEditor.ToString().ToLower()
                       + "&t=" + Global.FileSystemToken.ToString());
            sb.Replace("$_FileBrowserUrl_$", siteRoot + WebConfigSettings.FileDialogRelativeUrl);
            sb.Replace("$_HeaderContent_$", config.HeaderContent);
            sb.Replace("$_FooterContent_$", config.FooterContent);
        }
Ejemplo n.º 2
0
        private void LoadSettings()
        {
            Module module = new Module(ModuleGuid);

            config = new ModuleConfiguration(module);
            PageSettings currentPage = CacheHelper.GetCurrentPage();

            if (config.MarkupDefinition != null)
            {
                displaySettings = config.MarkupDefinition;
            }

            if (config.UseRazor)
            {
                widgetRazor.Config        = config;
                widgetRazor.PageId        = PageId;
                widgetRazor.ModuleId      = ModuleId;
                widgetRazor.IsEditable    = IsEditable;
                widgetRazor.SiteRoot      = SiteRoot;
                widgetRazor.ImageSiteRoot = ImageSiteRoot;

                widgetRazor.Visible = widgetRazor.Enabled = true;
                theWidget.Visible   = false;
                //pnlOuterWrap.Visible = false;
            }
            else
            {
                widgetRazor.Visible = widgetRazor.Enabled = false;

                if (ModuleConfiguration != null)
                {
                    Title       = ModuleConfiguration.ModuleTitle;
                    Description = ModuleConfiguration.FeatureName;
                }
                StringBuilder moduleTitle = new StringBuilder();

                moduleTitle.Append(displaySettings.ModuleTitleMarkup);
                SuperFlexiHelpers.ReplaceStaticTokens(moduleTitle, config, IsEditable, displaySettings, module, currentPage, siteSettings, out moduleTitle);
                litModuleTitle.Text = moduleTitle.ToString();

                if (config.InstanceCssClass.Length > 0 && !config.HideOuterWrapperPanel)
                {
                    pnlOuterWrap.SetOrAppendCss(config.InstanceCssClass.Replace("$_ModuleID_$", ModuleId.ToString()));
                }

                if (SiteUtils.IsMobileDevice() && config.MobileInstanceCssClass.Length > 0 && !config.HideOuterWrapperPanel)
                {
                    pnlOuterWrap.SetOrAppendCss(config.MobileInstanceCssClass.Replace("$_ModuleID_$", ModuleId.ToString()));
                }

                theWidget.Config = config;
                if (currentPage != null)
                {
                    theWidget.PageId      = currentPage.PageId;
                    theWidget.CurrentPage = currentPage;
                }
                theWidget.ModuleId      = ModuleId;
                theWidget.IsEditable    = IsEditable;
                theWidget.SiteRoot      = SiteRoot;
                theWidget.ImageSiteRoot = ImageSiteRoot;

                theWidget.Visible = true;

                if (config.UseHeader && config.HeaderLocation != "InnerBodyPanel" && !String.IsNullOrWhiteSpace(config.HeaderContent) && !String.Equals(config.HeaderContent, "<p>&nbsp;</p>"))
                {
                    StringBuilder headerContent = new StringBuilder();
                    headerContent.AppendFormat(displaySettings.HeaderContentFormat, config.HeaderContent);
                    SuperFlexiHelpers.ReplaceStaticTokens(headerContent, config, IsEditable, displaySettings, module, currentPage, siteSettings, out headerContent);
                    LiteralControl litHeaderContent = new LiteralControl(headerContent.ToString());
                    //if HeaderLocation is set to a hidden panel the header will be added to the Outside.
                    switch (config.HeaderLocation)
                    {
                    default:
                        break;

                    case "OuterBodyPanel":
                        if (config.HideOuterBodyPanel)
                        {
                            goto case "Outside";
                        }
                        pnlOuterBody.Controls.AddAt(0, litHeaderContent);
                        break;

                    case "InnerWrapperPanel":
                        if (config.HideInnerWrapperPanel)
                        {
                            goto case "Outside";
                        }
                        pnlInnerWrap.Controls.AddAt(0, litHeaderContent);
                        break;

                    case "OuterWrapperPanel":
                        if (config.HideOuterWrapperPanel)
                        {
                            goto case "Outside";
                        }
                        pnlOuterWrap.Controls.AddAt(0, litHeaderContent);
                        break;

                    case "Outside":
                        litHead.Text = headerContent.ToString();
                        break;
                    }
                }

                if (config.UseFooter && config.FooterLocation != "InnerBodyPanel" && !String.IsNullOrWhiteSpace(config.FooterContent) && !String.Equals(config.FooterContent, "<p>&nbsp;</p>"))
                {
                    StringBuilder footerContent = new StringBuilder();
                    footerContent.AppendFormat(displaySettings.FooterContentFormat, config.FooterContent);
                    SuperFlexiHelpers.ReplaceStaticTokens(footerContent, config, IsEditable, displaySettings, module, currentPage, siteSettings, out footerContent);
                    LiteralControl litFooterContent = new LiteralControl(footerContent.ToString());
                    //if FooterLocation is set to a hidden panel the footer will be added to the Outside.
                    switch (config.FooterLocation)
                    {
                    default:
                        break;

                    case "OuterBodyPanel":
                        if (config.HideOuterBodyPanel)
                        {
                            goto case "Outside";
                        }
                        pnlOuterBody.Controls.Add(litFooterContent);
                        break;

                    case "InnerWrapperPanel":
                        if (config.HideInnerWrapperPanel)
                        {
                            goto case "Outside";
                        }
                        pnlInnerWrap.Controls.Add(litFooterContent);
                        break;

                    case "OuterWrapperPanel":
                        if (config.HideOuterWrapperPanel)
                        {
                            goto case "Outside";
                        }
                        pnlOuterWrap.Controls.Add(litFooterContent);
                        break;

                    case "Outside":
                        litFoot.Text = footerContent.ToString();
                        break;
                    }
                }

                pnlOuterWrap.RenderContentsOnly = config.HideOuterWrapperPanel;
                pnlInnerWrap.RenderContentsOnly = config.HideInnerWrapperPanel;
                pnlOuterBody.RenderContentsOnly = config.HideOuterBodyPanel;
                pnlInnerBody.RenderContentsOnly = config.HideInnerBodyPanel;
            }
        }
Ejemplo n.º 3
0
        public static string GetHelpText(string helpKey, ModuleConfiguration config)
        {
            FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider];

            if (p == null)
            {
                log.Error("File System Provider Could Not Be Loaded.");
                return(string.Empty);
            }
            IFileSystem fileSystem = p.GetFileSystem();

            if (fileSystem == null)
            {
                log.Error("File System Could Not Be Loaded.");
                return(string.Empty);
            }

            string  helpText = string.Empty;
            WebFile helpFile = new WebFile();

            if (helpKey.ToLower().EndsWith(".sfhelp") ||
                helpKey.ToLower().EndsWith(".config") ||
                helpKey.ToLower().EndsWith(".html"))
            {
                if (helpKey.IndexOf("$_FlexiHelp_$") >= 0)
                {
                    string path = fileSystem.CombinePath("~/Data/SuperFlexi/Help/", helpKey.Replace("$_FlexiHelp_$", string.Empty));
                    helpFile = fileSystem.RetrieveFile(path);
                }
                else if (helpKey.IndexOf("$_SitePath_$") >= 0)
                {
                    string path = helpKey.Replace("$_SitePath_$", "~/Data/Sites/" + CacheHelper.GetCurrentSiteSettings().SiteId.ToInvariantString());
                    helpFile = fileSystem.RetrieveFile(path);
                }
                else if (helpKey.IndexOf("$_Data_$") >= 0)
                {
                    string path = helpKey.Replace("$_Data_$", "~/Data");
                    helpFile = fileSystem.RetrieveFile(path);
                }
                else if (helpKey.IndexOf("~/") >= 0)
                {
                    helpFile = fileSystem.RetrieveFile(helpKey);
                }
                else
                {
                    string path = fileSystem.CombinePath(config.RelativeSolutionLocation, helpKey);
                    helpFile = fileSystem.RetrieveFile(path);
                }
            }
            else
            {
                helpText = ResourceHelper.GetHelpFileText(helpKey);
                helpFile = null;
            }

            if (helpFile != null && fileSystem.FileExists(helpFile.VirtualPath))
            {
                //FileInfo file = new FileInfo(helpFilePath);
                //fileSystem.GetAsStream(helpFile.VirtualPath);
                //StreamReader sr = file.OpenText();

                StreamReader sr = new StreamReader(fileSystem.GetAsStream(helpFile.VirtualPath));
                helpText = sr.ReadToEnd();
                sr.Close();
            }

            return(helpText);
        }
Ejemplo n.º 4
0
        public static void ParseSearchDefinition(XmlNode searchNode, Guid fieldDefinitionGuid, Guid siteGuid)
        {
            ModuleConfiguration config = new ModuleConfiguration();

            if (searchNode != null)
            {
                //XmlAttributeCollection attrCollection = node.Attributes;
                //if (attrCollection["fieldDefinitionGuid"] != null) fieldDefinitionGuid = Guid.Parse(attrCollection["fieldDefinitionGuid"].Value);
                //if (fieldDefinitionGuid == Guid.Empty) return;

                bool      emptySearchDef  = false;
                bool      searchDefExists = true;
                SearchDef searchDef       = SearchDef.GetByFieldDefinition(fieldDefinitionGuid);
                if (searchDef == null)
                {
                    searchDefExists = false;
                    emptySearchDef  = true;

                    searchDef = new SearchDef();
                    searchDef.FieldDefinitionGuid = fieldDefinitionGuid;
                    searchDef.SiteGuid            = siteGuid;
                    searchDef.FeatureGuid         = config.FeatureGuid;
                }

                foreach (XmlNode childNode in searchNode)
                {
                    //need to find a way to clear out the searchdef if needed
                    switch (childNode.Name)
                    {
                    case "Title":
                        searchDef.Title = childNode.InnerText.Trim();
                        emptySearchDef  = false;
                        break;

                    case "Keywords":
                        searchDef.Keywords = childNode.InnerText.Trim();
                        emptySearchDef     = false;
                        break;

                    case "Description":
                        searchDef.Description = childNode.InnerText.Trim();
                        emptySearchDef        = false;
                        break;

                    case "Link":
                        searchDef.Link = childNode.InnerText.Trim();
                        emptySearchDef = false;
                        break;

                    case "LinkQueryAddendum":
                        searchDef.LinkQueryAddendum = childNode.InnerText.Trim();
                        emptySearchDef = false;
                        break;
                    }

                    //}
                }
                if (searchDefExists && emptySearchDef)
                {
                    SearchDef.DeleteByFieldDefinition(fieldDefinitionGuid);
                }
                else if (!emptySearchDef)
                {
                    searchDef.Save();
                }
                //if (!emptySearchDef) searchDef.Save();
            }
        }
Ejemplo n.º 5
0
        //public static List<MarkupScript> ParseScriptsFromXml(ModuleConfiguration config)
        //{
        //    List<MarkupScript> scripts = new List<MarkupScript>();
        //    string fullPath = string.Empty;
        //    XmlDocument doc = new XmlDocument();
        //    if (DefinitionExists(config.FieldDefinitionSrc, out doc))
        //    {
        //        XmlNode node = doc.DocumentElement.SelectSingleNode("/Fields/Scripts");

        //        if (node == null) return scripts;

        //        try
        //        {
        //            scripts = SuperFlexiHelpers.ParseScriptsFromXmlNode(node);
        //        }
        //        catch (System.Xml.XmlException ex)
        //        {
        //            log.Error(ex);
        //        }
        //    }
        //    return scripts;
        //}



        /// <summary>
        /// Creates a list of Field from field definition xml file.
        /// </summary>
        /// <param name="fieldDefinitionSrc"></param>
        /// <returns>IList</returns>
        public static List <Field> ParseFieldDefinitionXml(ModuleConfiguration config, Guid siteGuid)
        {
            List <Field> fields   = new List <Field>();
            string       fullPath = string.Empty;
            XmlDocument  doc      = new XmlDocument();

            FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider];

            if (p == null)
            {
                log.Error("File System Provider Could Not Be Loaded.");
                return(fields);
            }
            IFileSystem fileSystem = p.GetFileSystem();

            if (fileSystem == null)
            {
                log.Error("File System Could Not Be Loaded.");
                return(fields);
            }



            //implemented "solutions" on 9/13/2017 (mojoPortal 2.6.0.0) which allows for markup definitions and field definitions to be wrapped up in a single folder
            //b/c of this, we added the ability to pull the field definition file from the location of the markup definition (.sfmarkup) file w/o needing to use the full path in the fieldDefinitionSrc property

            string solutionFieldDefSrc = string.Empty;

            if (config.FieldDefinitionSrc.StartsWith("~/"))
            {
                solutionFieldDefSrc = config.FieldDefinitionSrc;
            }
            else if (config.FieldDefinitionSrc.StartsWith("/"))
            {
                solutionFieldDefSrc = "~" + config.FieldDefinitionSrc;
            }
            //else if (File.Exists(System.Web.Hosting.HostingEnvironment.MapPath(config.MarkupDefinitionFile)))
            else
            {
                var    sfMarkupFile = fileSystem.RetrieveFile(config.MarkupDefinitionFile);
                string sfFieldPath  = fileSystem.CombinePath(sfMarkupFile.FolderVirtualPath, config.FieldDefinitionSrc);
                var    sfFieldFile  = fileSystem.RetrieveFile(sfFieldPath);

                //FileInfo fileInfo = new FileInfo(System.Web.Hosting.HostingEnvironment.MapPath(config.MarkupDefinitionFile));

                //solutionFieldDefSrc = fileInfo.DirectoryName + "/" + config.FieldDefinitionSrc;

                solutionFieldDefSrc = sfFieldFile.VirtualPath;
            }



            if (DefinitionExists(solutionFieldDefSrc, out doc))
            {
                XmlNode node = doc.DocumentElement.SelectSingleNode("/Fields");
                if (node != null)
                {
                    XmlAttributeCollection attribs = node.Attributes;

                    string definitionName = string.Empty;
                    Guid   definitionGuid = Guid.NewGuid();
                    if (attribs["definitionName"] != null)
                    {
                        definitionName = attribs["definitionName"].Value;
                    }
                    if (attribs["definitionGuid"] != null)
                    {
                        definitionGuid = Guid.Parse(attribs["definitionGuid"].Value);
                    }

                    if (definitionGuid != config.FieldDefinitionGuid)
                    {
                        log.ErrorFormat(@"
							SuperFlexi Solution [{0}] located at [{1}] uses fieldDefinitionGuid = [{2}]
							but the field definition at [{3}] uses definitionGuid = [{4}]. Items will not display properly and may end up corrupted.
							"                            ,
                                        config.MarkupDefinitionName, config.MarkupDefinitionFile, config.FieldDefinitionGuid.ToString(),
                                        solutionFieldDefSrc, definitionGuid);

                        return(null);
                    }

                    foreach (XmlNode childNode in node)
                    {
                        if (childNode.Name == "Field")
                        {
                            try
                            {
                                Field field = new Field();
                                XmlAttributeCollection itemDefAttribs = childNode.Attributes;

                                field.DefinitionName = definitionName;
                                field.DefinitionGuid = definitionGuid;
                                if (itemDefAttribs["name"] != null)
                                {
                                    field.Name = itemDefAttribs["name"].Value;
                                }
                                if (itemDefAttribs["label"] != null)
                                {
                                    field.Label = itemDefAttribs["label"].Value;
                                }
                                if (itemDefAttribs["defaultValue"] != null)
                                {
                                    field.DefaultValue = itemDefAttribs["defaultValue"].Value;
                                }
                                if (itemDefAttribs["controlType"] != null)
                                {
                                    field.ControlType = itemDefAttribs["controlType"].Value;
                                }
                                if (itemDefAttribs["controlSrc"] != null)
                                {
                                    field.ControlSrc = itemDefAttribs["controlSrc"].Value;
                                }
                                field.SortOrder = XmlUtils.ParseInt32FromAttribute(itemDefAttribs, "sortOrder", field.SortOrder);
                                if (itemDefAttribs["helpKey"] != null)
                                {
                                    field.HelpKey = itemDefAttribs["helpKey"].Value;
                                }
                                field.Required = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "required", field.Required);
                                if (itemDefAttribs["requiredMessageFormat"] != null)
                                {
                                    field.RequiredMessageFormat = itemDefAttribs["requiredMessageFormat"].Value;
                                }
                                if (itemDefAttribs["regex"] != null)
                                {
                                    field.Regex = itemDefAttribs["regex"].Value;
                                }
                                if (itemDefAttribs["regexMessageFormat"] != null)
                                {
                                    field.RegexMessageFormat = itemDefAttribs["regexMessageFormat"].Value;
                                }
                                if (itemDefAttribs["token"] != null && !String.IsNullOrWhiteSpace(itemDefAttribs["token"].Value))
                                {
                                    field.Token = itemDefAttribs["token"].Value;
                                }

                                field.Searchable = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "isSearchable", field.Searchable);
                                if (itemDefAttribs["editPageControlWrapperCssClass"] != null)
                                {
                                    field.EditPageControlWrapperCssClass = itemDefAttribs["editPageControlWrapperCssClass"].Value;
                                }
                                if (itemDefAttribs["editPageLabelCssClass"] != null)
                                {
                                    field.EditPageLabelCssClass = itemDefAttribs["editPageLabelCssClass"].Value;
                                }
                                if (itemDefAttribs["editPageControlCssClass"] != null)
                                {
                                    field.EditPageControlCssClass = itemDefAttribs["editPageControlCssClass"].Value;
                                }
                                field.DatePickerIncludeTimeForDate = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "datePickerIncludeTimeForDate", field.DatePickerIncludeTimeForDate);
                                field.DatePickerShowMonthList      = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "datePickerShowMonthList", field.DatePickerShowMonthList);
                                field.DatePickerShowYearList       = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "datePickerShowYearList", field.DatePickerShowYearList);
                                if (itemDefAttribs["datePickerYearRange"] != null)
                                {
                                    field.DatePickerYearRange = itemDefAttribs["datePickerYearRange"].Value;
                                }
                                if (itemDefAttribs["imageBrowserEmptyUrl"] != null)
                                {
                                    field.ImageBrowserEmptyUrl = itemDefAttribs["imageBrowserEmptyUrl"].Value;
                                }
                                field.CheckBoxReturnBool = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "checkBoxReturnBool", field.CheckBoxReturnBool);
                                if (itemDefAttribs["checkBoxReturnValueWhenTrue"] != null)
                                {
                                    field.CheckBoxReturnValueWhenTrue = itemDefAttribs["checkBoxReturnValueWhenTrue"].Value;
                                }
                                if (itemDefAttribs["checkBoxReturnValueWhenFalse"] != null)
                                {
                                    field.CheckBoxReturnValueWhenFalse = itemDefAttribs["checkBoxReturnValueWhenFalse"].Value;
                                }
                                if (itemDefAttribs["dateFormat"] != null)
                                {
                                    field.DateFormat = itemDefAttribs["dateFormat"].Value;
                                }
                                if (itemDefAttribs["textBoxMode"] != null)
                                {
                                    field.TextBoxMode = itemDefAttribs["textBoxMode"].Value;
                                }
                                field.IsDeleted = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "isDeleted", field.IsDeleted);
                                field.IsGlobal  = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "isGlobal", field.IsGlobal);

                                StringBuilder options    = new StringBuilder();
                                StringBuilder attributes = new StringBuilder();
                                foreach (XmlNode subNode in childNode)
                                {
                                    switch (subNode.Name)
                                    {
                                    case "Options":
                                        options = XmlHelper.GetKeyValuePairsAsStringBuilder(subNode.ChildNodes);
                                        //GetKeyValuePairs(subNode.ChildNodes, out options);
                                        break;

                                    case "Attributes":
                                        attributes = XmlHelper.GetKeyValuePairsAsStringBuilder(subNode.ChildNodes);
                                        //GetKeyValuePairs(subNode.ChildNodes, out attributes);
                                        break;

                                    case "PreTokenString":
                                        field.PreTokenString = subNode.InnerText.Trim();
                                        break;

                                    case "PostTokenString":
                                        field.PostTokenString = subNode.InnerText.Trim();
                                        break;
                                    }
                                }

                                if (options.Length > 0)
                                {
                                    field.Options = options.ToString();
                                }

                                if (attributes.Length > 0)
                                {
                                    field.Attributes = attributes.ToString();
                                }

                                fields.Add(field);
                            }
                            catch (System.Xml.XmlException ex)
                            {
                                log.Error(ex);
                            }
                        }
                        else if (childNode.Name == "Scripts")
                        {
                            try
                            {
                                config.EditPageScripts = SuperFlexiHelpers.ParseScriptsFromXmlNode(childNode);
                            }
                            catch (System.Xml.XmlException ex)
                            {
                                log.Error(ex);
                            }
                        }
                        else if (childNode.Name == "Styles")
                        {
                            try
                            {
                                config.EditPageCSS = SuperFlexiHelpers.ParseCssFromXmlNode(childNode);
                            }
                            catch (System.Xml.XmlException ex)
                            {
                                log.Error(ex);
                            }
                        }
                        else if (childNode.Name == "SearchDefinition")
                        {
                            try
                            {
                                SuperFlexiHelpers.ParseSearchDefinition(childNode, definitionGuid, siteGuid);
                            }
                            catch (XmlException ex)
                            {
                                log.Error(ex);
                            }
                        }
                    }
                }
            }

            fields.Sort();
            return(fields);
        }
Ejemplo n.º 6
0
        public static void SetupScripts(
            List <MarkupScript> markupScripts,
            ModuleConfiguration config,
            SuperFlexiDisplaySettings displaySettings,
            bool isEditable,
            bool isPostBack,
            string clientID,
            int moduleID,
            int pageID,
            Page page,
            Control control)
        {
            string scriptRefFormat = "\n<script type=\"text/javascript\" src=\"{0}\" data-name=\"{1}\"></script>";
            string rawScriptFormat = "\n<script type=\"text/javascript\" data-name=\"{1}\">\n{0}\n</script>";

            foreach (MarkupScript script in markupScripts)
            {
                StringBuilder sbScriptText = new StringBuilder();
                StringBuilder sbScriptName = new StringBuilder();

                sbScriptName.Append(String.IsNullOrWhiteSpace(script.ScriptName) ? clientID + "flexiScript_" + markupScripts.IndexOf(script) : "flexiScript_" + script.ScriptName);
                SuperFlexiHelpers.ReplaceStaticTokens(sbScriptName, config, isEditable, displaySettings, moduleID, pageID, out sbScriptName);
                string scriptName = sbScriptName.ToString();
                if (!String.IsNullOrWhiteSpace(script.Url))
                {
                    string scriptUrl = string.Empty;
                    if (script.Url.StartsWith("/") ||
                        script.Url.StartsWith("http://") ||
                        script.Url.StartsWith("https://"))
                    {
                        scriptUrl = script.Url;
                    }
                    else if (script.Url.StartsWith("~/"))
                    {
                        scriptUrl = WebUtils.ResolveServerUrl(script.Url);
                    }
                    else if (script.Url.StartsWith("$_SitePath_$"))
                    {
                        scriptUrl = script.Url.Replace("$_SitePath_$", "/Data/Sites/" + CacheHelper.GetCurrentSiteSettings().SiteId.ToString() + "/");
                    }
                    else
                    {
                        scriptUrl = new Uri(config.SolutionLocationUrl, script.Url).ToString();
                    }
                    //else if (File.Exists(System.Web.Hosting.HostingEnvironment.MapPath(config.MarkupDefinitionFile)))
                    //{
                    //	FileInfo fileInfo = new FileInfo(System.Web.Hosting.HostingEnvironment.MapPath(config.MarkupDefinitionFile));
                    //	scriptUrl = WebUtils.ResolveServerUrl(Path.Combine(fileInfo.DirectoryName.Replace(System.Web.Hosting.HostingEnvironment.MapPath("~"), "~/"), script.Url));
                    //}

                    sbScriptText.Append(string.Format(scriptRefFormat, scriptUrl, scriptName));
                }
                else if (!String.IsNullOrWhiteSpace(script.RawScript))
                {
                    sbScriptText.Append(string.Format(rawScriptFormat, script.RawScript, scriptName));
                }

                SuperFlexiHelpers.ReplaceStaticTokens(sbScriptText, config, isEditable, displaySettings, moduleID, pageID, out sbScriptText);

                // script position options
                // inHead
                // inBody (register script) (default)
                // aboveMarkupDefinition
                // belowMarkupDefinition
                // bottomStartup (register startup script)
                switch (script.Position)
                {
                case "inHead":
                    if (!isPostBack && !page.IsCallback)
                    {
                        if (page.Header.FindControl(scriptName) == null)
                        {
                            LiteralControl headLit = new LiteralControl();
                            headLit.ID              = scriptName;
                            headLit.Text            = sbScriptText.ToString();
                            headLit.ClientIDMode    = System.Web.UI.ClientIDMode.Static;
                            headLit.EnableViewState = false;
                            page.Header.Controls.Add(headLit);
                        }
                    }
                    break;

                case "aboveMarkupDefinition":
                    if (control == null)
                    {
                        goto case "bottomStartup";
                    }
                    if (control.FindControlRecursive(scriptName) == null)
                    {
                        Control aboveMarkupDefinitionScripts = control.FindControlRecursive("aboveMarkupDefinitionScripts");
                        if (aboveMarkupDefinitionScripts != null)
                        {
                            LiteralControl aboveLit = new LiteralControl();
                            aboveLit.ID   = scriptName;
                            aboveLit.Text = sbScriptText.ToString();
                            aboveMarkupDefinitionScripts.Controls.Add(aboveLit);
                        }
                        else
                        {
                            goto case "bottomStartup";
                        }
                    }
                    break;

                case "belowMarkupDefinition":
                    if (control == null)
                    {
                        goto case "bottomStartup";
                    }
                    if (control.FindControlRecursive(scriptName) == null)
                    {
                        Control belowMarkupDefinitionScripts = control.FindControlRecursive("belowMarkupDefinitionScripts");
                        if (belowMarkupDefinitionScripts != null)
                        {
                            LiteralControl belowLit = new LiteralControl();
                            belowLit.ID   = scriptName;
                            belowLit.Text = sbScriptText.ToString();
                            belowMarkupDefinitionScripts.Controls.Add(belowLit);
                        }
                        else
                        {
                            goto case "bottomStartup";
                        }
                    }
                    //strBelowMarkupScripts.AppendLine(scriptText);
                    break;

                case "bottomStartup":
                    if (!page.ClientScript.IsStartupScriptRegistered(scriptName))
                    {
                        ScriptManager.RegisterStartupScript(
                            page,
                            typeof(Page),
                            scriptName,
                            sbScriptText.ToString(),
                            false);
                    }
                    break;

                case "inBody":
                default:
                    if (!page.ClientScript.IsClientScriptBlockRegistered(scriptName))
                    {
                        ScriptManager.RegisterClientScriptBlock(
                            page,
                            typeof(Page),
                            scriptName,
                            sbScriptText.ToString(),
                            false);
                    }
                    break;
                }
            }
        }
Ejemplo n.º 7
0
        public static void SetupStyle(
            List <MarkupCss> markupCss,
            ModuleConfiguration config,
            SuperFlexiDisplaySettings displaySettings,
            string clientID,
            int moduleID,
            int pageID,
            Page page,
            Control control)
        {
            string styleLinkFormat = "\n<link rel=\"stylesheet\" href=\"{0}\" media=\"{2}\" data-name=\"{1}\">";
            string rawCSSFormat    = "\n<style type=\"text/css\" data-name=\"{1}\" media=\"{2}\">\n{0}\n</style>";

            foreach (MarkupCss style in markupCss)
            {
                StringBuilder sbStyleText = new StringBuilder();
                StringBuilder sbStyleName = new StringBuilder();

                sbStyleName.Append(String.IsNullOrWhiteSpace(style.Name) ? clientID + "flexiStyle_" + markupCss.IndexOf(style) : "flexiStyle_" + style.Name);
                SuperFlexiHelpers.ReplaceStaticTokens(sbStyleName, config, false, displaySettings, moduleID, pageID, out sbStyleName);
                string styleName = sbStyleName.ToString();
                if (!String.IsNullOrWhiteSpace(style.Url))
                {
                    string styleUrl = string.Empty;

                    if (style.Url.StartsWith("/") ||
                        style.Url.StartsWith("http://") ||
                        style.Url.StartsWith("https://"))
                    {
                        styleUrl = style.Url;
                    }
                    else if (style.Url.StartsWith("~/"))
                    {
                        styleUrl = WebUtils.ResolveServerUrl(style.Url);
                    }
                    else if (style.Url.StartsWith("$_SitePath_$"))
                    {
                        styleUrl = style.Url.Replace("$_SitePath_$", "/Data/Sites/" + CacheHelper.GetCurrentSiteSettings().SiteId.ToString() + "/");
                    }
                    else
                    {
                        styleUrl = new Uri(config.SolutionLocationUrl, style.Url).ToString();
                    }
                    //else if (File.Exists(System.Web.Hosting.HostingEnvironment.MapPath(config.MarkupDefinitionFile)))
                    //{
                    //	FileInfo fileInfo = new FileInfo(System.Web.Hosting.HostingEnvironment.MapPath(config.MarkupDefinitionFile));
                    //	styleUrl = WebUtils.ResolveServerUrl(Path.Combine(fileInfo.DirectoryName.Replace(System.Web.Hosting.HostingEnvironment.MapPath("~"), "~/"), style.Url));
                    //}

                    sbStyleText.Append(string.Format(styleLinkFormat, styleUrl, styleName, style.Media));
                }
                else if (!String.IsNullOrWhiteSpace(style.CSS))
                {
                    sbStyleText.Append(string.Format(rawCSSFormat, style.CSS, styleName, style.Media));
                }

                SuperFlexiHelpers.ReplaceStaticTokens(sbStyleText, config, false, displaySettings, moduleID, pageID, out sbStyleText);

                LiteralControl theLiteral = new LiteralControl();
                theLiteral.Text = sbStyleText.ToString();

                StyleSheetCombiner ssc = (StyleSheetCombiner)page.Header.FindControl("StyleSheetCombiner");

                if (ssc != null)
                {
                    int sscIndex = page.Header.Controls.IndexOf(ssc);
                    if (style.RenderAboveSSC)
                    {
                        page.Header.Controls.AddAt(sscIndex, theLiteral);
                    }
                    else
                    {
                        page.Header.Controls.AddAt(sscIndex + 1, theLiteral);
                    }
                }
                else
                {
                    page.Header.Controls.AddAt(0, theLiteral);
                }
            }
        }
Ejemplo n.º 8
0
        public ReturnObject GetFieldValues(RequestObject r)
        {
            siteSettings = CacheHelper.GetCurrentSiteSettings();
            currentPage  = new PageSettings(siteSettings.SiteId, r.PageId);
            bool allowed = false;

            if (currentPage != null)
            {
                allowed = WebUser.IsInRoles(currentPage.AuthorizedRoles);
            }
            module = new Module(r.ModuleId);
            if (module != null)
            {
                allowed = WebUser.IsInRoles(module.ViewRoles);
            }
            if (!allowed)
            {
                return(new ReturnObject()
                {
                    Status = "error",
                    ExtraData = new Dictionary <string, string>
                    {
                        ["ErrorCode"] = "100",
                        ["ErrorMessage"] = "Not Allowed"
                    }
                });
            }

            config = new ModuleConfiguration(module);

            int totalPages = 0;
            int totalRows  = 0;

            var fieldValues = ItemFieldValue.GetPageOfValues(
                module.ModuleGuid,
                config.FieldDefinitionGuid,
                r.Field,
                r.PageNumber,
                r.PageSize,
                out totalPages,
                out totalRows);

            //much of the below is temporary, we needed to implement in a hurry
            //to-do: implement distinct on sql side
            List <string> values = new List <string>();

            var dbField = new Field(fieldValues.Select(fv => fv.FieldGuid).FirstOrDefault());

            switch (dbField.ControlType)
            {
            case "DynamicCheckBoxList":
                foreach (var val in fieldValues)
                {
                    values.AddRange(val.FieldValue.SplitOnCharAndTrim(';'));
                }
                break;

            default:
                values = fieldValues.Select(fv => fv.FieldValue).ToList();
                break;
                //we will add the other cases later
            }

            values = values.Distinct().OrderBy(v => v).ToList();

            totalRows = values.Count();

            return(new ReturnObject()
            {
                Status = "success",
                Data = values,
                TotalPages = totalPages,
                TotalRows = totalRows
            });
        }
Ejemplo n.º 9
0
        public static string GetModuleLinks(ModuleConfiguration config, SuperFlexiDisplaySettings displaySettings, int moduleId, int pageId)
        {
            StringBuilder litExtraMarkup = new StringBuilder();
            string        settings       = string.Empty;
            string        add            = string.Empty;
            string        header         = string.Empty;
            string        footer         = string.Empty;
            string        import         = string.Empty;
            string        export         = string.Empty;

            try
            {
                settings = String.Format(
                    displaySettings.ModuleSettingsLinkFormat,
                    WebUtils.GetSiteRoot() + "/Admin/ModuleSettings.aspx?pageid=" + pageId.ToString() + "&amp;mid=" + moduleId.ToString(),
                    SuperFlexiResources.SettingsLinkLabel);

                if (!String.IsNullOrWhiteSpace(config.MarkupDefinitionName) && config.MarkupDefinitionName != "Please Select")
                {
                    if (!config.IsGlobalView)
                    {
                        add = String.Format(
                            displaySettings.AddItemLinkFormat,
                            WebUtils.GetSiteRoot() + "/SuperFlexi/Edit.aspx?pageid=" + pageId.ToString() + "&amp;mid=" + moduleId.ToString(),
                            SuperFlexiResources.AddItem);
                    }

                    if (config.UseHeader)
                    {
                        header = String.Format(
                            displaySettings.EditHeaderLinkFormat,
                            WebUtils.GetSiteRoot() + "/SuperFlexi/EditHeader.aspx?pageid=" + pageId.ToString() + "&amp;mid=" + moduleId.ToString(),
                            SuperFlexiResources.EditHeader);
                    }

                    if (config.UseFooter)
                    {
                        footer = String.Format(
                            displaySettings.EditFooterLinkFormat,
                            WebUtils.GetSiteRoot() + "/SuperFlexi/EditHeader.aspx?f=true&pageid=" + pageId.ToString() + "&amp;mid=" + moduleId.ToString(),
                            SuperFlexiResources.EditFooter);
                    }

                    if (config.AllowImport)
                    {
                        import = String.Format(
                            displaySettings.ImportLinkFormat,
                            WebUtils.GetSiteRoot() + "/SuperFlexi/Import.aspx?pageid=" + pageId.ToString() + "&amp;mid=" + moduleId.ToString(),
                            SuperFlexiResources.ImportTitle);
                    }

                    if (config.AllowExport)
                    {
                        export = String.Format(
                            displaySettings.ExportLinkFormat,
                            WebUtils.GetSiteRoot() + "/SuperFlexi/Export.aspx?pageid=" + pageId.ToString() + "&amp;mid=" + moduleId.ToString(),
                            SuperFlexiResources.ExportTitle);
                    }
                }

                litExtraMarkup.AppendFormat(displaySettings.ModuleLinksFormat, settings, add, header, footer, import, export);
            }
            catch (System.FormatException ex)
            {
                Module module      = new Module(moduleId);
                string moduleTitle = "unknown";
                if (module != null)
                {
                    moduleTitle = module.ModuleTitle;
                }
                log.ErrorFormat("Error rendering \"{0}\", with moduleID={1}, pageid={2}. Error was:\r\n{3}", moduleTitle, moduleId.ToString(), pageId.ToString(), ex);
            }
            return(litExtraMarkup.ToString());
        }
Ejemplo n.º 10
0
        private void PopulateControls()
        {
            string featuredImageUrl = string.Empty;
            string markupTop        = string.Empty;
            string markupBottom     = string.Empty;

            featuredImageUrl = String.IsNullOrWhiteSpace(Config.InstanceFeaturedImage) ? featuredImageUrl : SiteUtils.GetNavigationSiteRoot() + Config.InstanceFeaturedImage;
            markupTop        = displaySettings.ModuleInstanceMarkupTop;
            markupBottom     = displaySettings.ModuleInstanceMarkupBottom;

            strOutput.Append(markupTop);

            if (Config.UseHeader && Config.HeaderLocation == "InnerBodyPanel" && !String.IsNullOrWhiteSpace(Config.HeaderContent) && !String.Equals(Config.HeaderContent, "<p>&nbsp;</p>"))
            {
                try
                {
                    strOutput.Append(string.Format(displaySettings.HeaderContentFormat, Config.HeaderContent));
                }
                catch (FormatException ex)
                {
                    log.ErrorFormat(markupErrorFormat, "HeaderContentFormat", moduleTitle, ex);
                }
            }
            StringBuilder  jsonString   = new StringBuilder();
            StringWriter   stringWriter = new StringWriter(jsonString);
            JsonTextWriter jsonWriter   = new JsonTextWriter(stringWriter);

            // http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateTimeZoneHandling.htm
            jsonWriter.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            // http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DateFormatHandling.htm
            jsonWriter.DateFormatHandling = DateFormatHandling.IsoDateFormat;

            string jsonObjName = "sflexi" + module.ModuleId.ToString() + (Config.IsGlobalView ? "Modules" : "Items");

            if (Config.RenderJSONOfData)
            {
                jsonWriter.WriteRaw("var " + jsonObjName + " = ");
                if (Config.JsonLabelObjects || Config.IsGlobalView)
                {
                    jsonWriter.WriteStartObject();
                }
                else
                {
                    jsonWriter.WriteStartArray();
                }
            }

            List <IndexedStringBuilder> itemsMarkup = new List <IndexedStringBuilder>();
            //List<Item> categorizedItems = new List<Item>();
            bool usingGlobalViewMarkup = !String.IsNullOrWhiteSpace(displaySettings.GlobalViewMarkup);
            int  currentModuleID       = -1;

            foreach (Item item in items)
            {
                bool itemIsEditable = IsEditable || WebUser.IsInRoles(item.EditRoles);
                bool itemIsViewable = itemIsEditable || WebUser.IsAdminOrContentAdminOrContentPublisherOrContentAuthor || WebUser.IsInRoles(item.ViewRoles);
                if (!itemIsViewable)
                {
                    continue;
                }

                //int itemCount = 0;
                //StringBuilder content = new StringBuilder();
                IndexedStringBuilder content = new IndexedStringBuilder();

                ModuleConfiguration itemModuleConfig = Config;

                if (Config.IsGlobalView)
                {
                    itemModuleConfig   = new ModuleConfiguration(module);
                    content.SortOrder1 = itemModuleConfig.GlobalViewSortOrder;
                    content.SortOrder2 = item.SortOrder;
                }
                else
                {
                    content.SortOrder1 = item.SortOrder;
                }

                item.ModuleFriendlyName = itemModuleConfig.ModuleFriendlyName;
                if (String.IsNullOrWhiteSpace(itemModuleConfig.ModuleFriendlyName))
                {
                    Module itemModule = new Module(item.ModuleGuid);
                    if (itemModule != null)
                    {
                        item.ModuleFriendlyName = itemModule.ModuleTitle;
                    }
                }

                //List<ItemFieldValue> fieldValues = ItemFieldValue.GetItemValues(item.ItemGuid);

                //using item.ModuleID here because if we are using a 'global view' we need to be sure the item edit link uses the correct module id.
                string itemEditUrl  = SiteUtils.GetNavigationSiteRoot() + "/SuperFlexi/Edit.aspx?pageid=" + PageId + "&mid=" + item.ModuleID + "&itemid=" + item.ItemID;
                string itemEditLink = itemIsEditable ? String.Format(displaySettings.ItemEditLinkFormat, itemEditUrl) : string.Empty;

                if (Config.RenderJSONOfData)
                {
                    if (Config.IsGlobalView)
                    {
                        if (currentModuleID != item.ModuleID)
                        {
                            if (currentModuleID != -1)
                            {
                                jsonWriter.WriteEndObject();
                                jsonWriter.WriteEndObject();
                            }

                            currentModuleID = item.ModuleID;

                            //always label objects in globalview
                            jsonWriter.WritePropertyName("m" + currentModuleID.ToString());
                            jsonWriter.WriteStartObject();
                            jsonWriter.WritePropertyName("Module");
                            jsonWriter.WriteValue(item.ModuleFriendlyName);
                            jsonWriter.WritePropertyName("Items");
                            jsonWriter.WriteStartObject();
                        }
                    }
                    if (Config.JsonLabelObjects || Config.IsGlobalView)
                    {
                        jsonWriter.WritePropertyName("i" + item.ItemID.ToString());
                    }
                    jsonWriter.WriteStartObject();
                    jsonWriter.WritePropertyName("ItemId");
                    jsonWriter.WriteValue(item.ItemID.ToString());
                    jsonWriter.WritePropertyName("SortOrder");
                    jsonWriter.WriteValue(item.SortOrder.ToString());
                    if (IsEditable)
                    {
                        jsonWriter.WritePropertyName("EditUrl");
                        jsonWriter.WriteValue(itemEditUrl);
                    }
                }
                content.Append(displaySettings.ItemMarkup);


                foreach (Field field in fields)
                {
                    //if (!WebUser.IsInRoles(field.ViewRoles))
                    //{
                    //	continue;
                    //}

                    if (String.IsNullOrWhiteSpace(field.Token))
                    {
                        field.Token = "$_NONE_$";                                                             //just in case someone has loaded the database with fields without using a source file.
                    }
                    bool fieldValueFound = false;

                    var itemFieldValues = fieldValues.Where(fv => fv.ItemGuid == item.ItemGuid);
                    var tokens          = fields.Select(x => new { x.Token, x.FieldGuid });


                    foreach (ItemFieldValue fieldValue in itemFieldValues)
                    {
                        if (field.FieldGuid == fieldValue.FieldGuid)
                        {
                            fieldValueFound = true;

                            if (String.IsNullOrWhiteSpace(fieldValue.FieldValue) ||
                                fieldValue.FieldValue.StartsWith("&deleted&") ||
                                fieldValue.FieldValue.StartsWith("&amp;deleted&amp;") ||
                                fieldValue.FieldValue.StartsWith("<p>&deleted&</p>") ||
                                fieldValue.FieldValue.StartsWith("<p>&amp;deleted&amp;</p>") ||
                                (!WebUser.IsAdminOrContentAdminOrContentPublisherOrContentAuthor &&
                                 !WebUser.IsInRoles(field.ViewRoles)))
                            {
                                content.Replace("^" + field.Token + "^", string.Empty);
                                content.Replace("^" + field.Token, string.Empty);
                                content.Replace(field.Token + "^", string.Empty);
                                content.Replace(field.Token, string.Empty);
                            }
                            else
                            {
                                if (IsDateField(field))
                                {
                                    DateTime dateTime = new DateTime();
                                    if (DateTime.TryParse(fieldValue.FieldValue, out dateTime))
                                    {
                                        /// ^field.Token is used when we don't want the preTokenString and postTokenString to be used
                                        content.Replace("^" + field.Token + "^", dateTime.ToString(field.DateFormat));
                                        content.Replace("^" + field.Token, dateTime.ToString(field.DateFormat) + field.PostTokenString);
                                        content.Replace(field.Token + "^", field.PreTokenString + dateTime.ToString(field.DateFormat));
                                        content.Replace(field.Token, field.PreTokenString + dateTime.ToString(field.DateFormat) + field.PostTokenString);
                                    }
                                }

                                if (IsCheckBoxListField(field) || IsRadioButtonListField(field))
                                {
                                    foreach (CheckBoxListMarkup cblm in Config.CheckBoxListMarkups)
                                    {
                                        if (cblm.Field == field.Name)
                                        {
                                            StringBuilder cblmContent = new StringBuilder();

                                            List <string> values = fieldValue.FieldValue.SplitOnCharAndTrim(';');
                                            if (values.Count > 0)
                                            {
                                                foreach (string value in values)
                                                {
                                                    //why did we use _ValueItemID_ here instead of _ItemID_?
                                                    cblmContent.Append(cblm.Markup.Replace(field.Token, value).Replace("$_ValueItemID_$", item.ItemID.ToString()) + cblm.Separator);
                                                    cblm.SelectedValues.Add(new CheckBoxListMarkup.SelectedValue {
                                                        Value = value, ItemID = item.ItemID
                                                    });
                                                    //cblm.SelectedValues.Add(fieldValue);
                                                }
                                            }
                                            cblmContent.Length -= cblm.Separator.Length;
                                            content.Replace(cblm.Token, cblmContent.ToString());
                                        }
                                    }
                                }

                                if (field.ControlType == "CheckBox")
                                {
                                    string checkBoxContent = string.Empty;

                                    if (fieldValue.FieldValue == field.CheckBoxReturnValueWhenTrue)
                                    {
                                        content.Replace("^" + field.Token + "^", fieldValue.FieldValue);
                                        content.Replace("^" + field.Token, fieldValue.FieldValue + field.PostTokenString + field.PostTokenStringWhenTrue);
                                        content.Replace(field.Token + "^", field.PreTokenString + field.PreTokenStringWhenTrue + fieldValue.FieldValue);
                                        content.Replace(field.Token, field.PreTokenString + field.PreTokenStringWhenTrue + fieldValue.FieldValue + field.PostTokenString + field.PostTokenStringWhenTrue);
                                    }

                                    else if (fieldValue.FieldValue == field.CheckBoxReturnValueWhenFalse)
                                    {
                                        content.Replace("^" + field.Token + "^", fieldValue.FieldValue);
                                        content.Replace("^" + field.Token, fieldValue.FieldValue + field.PostTokenString + field.PostTokenStringWhenFalse);
                                        content.Replace(field.Token + "^", field.PreTokenString + field.PreTokenStringWhenFalse + fieldValue.FieldValue);
                                        content.Replace(field.Token, field.PreTokenString + field.PreTokenStringWhenFalse + fieldValue.FieldValue + field.PostTokenString + field.PostTokenStringWhenFalse);
                                    }
                                }

                                // ^field.Token^ is used when we don't want the preTokenString and postTokenString to be used
                                content.Replace("^" + field.Token + "^", fieldValue.FieldValue);
                                content.Replace("^" + field.Token, fieldValue.FieldValue + field.PostTokenString);
                                content.Replace(field.Token + "^", field.PreTokenString + fieldValue.FieldValue);
                                content.Replace(field.Token, field.PreTokenString + fieldValue.FieldValue + field.PostTokenString);

                                //We want any tokens used in our pre or post token strings to be replaced.
                                //todo: add controlType specific logic to be sure tokens used in pre and post are replaced with proper formatting (i.e.: date field)
                                List <string> prePostTokenStrings = new List <string>();

                                if (!String.IsNullOrWhiteSpace(field.PreTokenString))
                                {
                                    prePostTokenStrings.Add(field.PreTokenString);
                                }

                                if (!String.IsNullOrWhiteSpace(field.PostTokenString))
                                {
                                    prePostTokenStrings.Add(field.PostTokenString);
                                }

                                if (!String.IsNullOrWhiteSpace(field.PreTokenStringWhenTrue))
                                {
                                    prePostTokenStrings.Add(field.PreTokenStringWhenTrue);
                                }

                                if (!String.IsNullOrWhiteSpace(field.PreTokenStringWhenFalse))
                                {
                                    prePostTokenStrings.Add(field.PreTokenStringWhenFalse);
                                }

                                if (!String.IsNullOrWhiteSpace(field.PostTokenStringWhenTrue))
                                {
                                    prePostTokenStrings.Add(field.PostTokenStringWhenTrue);
                                }

                                if (!String.IsNullOrWhiteSpace(field.PostTokenStringWhenFalse))
                                {
                                    prePostTokenStrings.Add(field.PostTokenStringWhenFalse);
                                }

                                var sharedTokens = tokens.Where(token => prePostTokenStrings.Any(tokenString => tokenString.Contains(token.Token))).ToList();

                                //foreach (var token in tokens)
                                //{
                                //	if (prePostTokenStrings.Contains(token.Token))
                                //	{
                                //		sharedTokens.Add(token);
                                //	}
                                //}

                                foreach (var token in sharedTokens)
                                {
                                    content.Replace(token.Token, fieldValues.Where(x => x.FieldGuid == token.FieldGuid && x.ItemGuid == item.ItemGuid).Select(y => y.FieldValue).Single());
                                }
                            }
                            //if (!String.IsNullOrWhiteSpace(field.LinkedField))
                            //{
                            //    Field linkedField = fields.Find(delegate(Field f) { return f.Name == field.LinkedField; });
                            //    if (linkedField != null)
                            //    {
                            //        ItemFieldValue linkedValue = fieldValues.Find(delegate(ItemFieldValue fv) { return fv.FieldGuid == linkedField.FieldGuid; });
                            //        content.Replace(linkedField.Token, linkedValue.FieldValue);
                            //    }
                            //}

                            if (Config.RenderJSONOfData &&
                                (WebUser.IsAdminOrContentAdminOrContentPublisherOrContentAuthor || WebUser.IsInRoles(field.ViewRoles)))
                            {
                                jsonWriter.WritePropertyName(field.Name);
                                //if (IsDateField(field))
                                //{
                                //    DateTime dateTime = new DateTime();
                                //    if (DateTime.TryParse(fieldValue.FieldValue, out dateTime))
                                //    {
                                //        jsonWriter.WriteValue(dateTime);
                                //    }

                                //}
                                //else
                                //{
                                if (field.ControlType == "CheckBox" && field.CheckBoxReturnBool == true)
                                {
                                    jsonWriter.WriteValue(Convert.ToBoolean(fieldValue.FieldValue));
                                }
                                else
                                {
                                    jsonWriter.WriteValue(fieldValue.FieldValue);
                                }
                                //}
                            }
                        }
                    }

                    if (!fieldValueFound)
                    {
                        if (WebUser.IsAdminOrContentAdminOrContentPublisherOrContentAuthor || WebUser.IsInRoles(field.ViewRoles))
                        {
                            content.Replace(field.Token, field.DefaultValue);
                            if (Config.RenderJSONOfData)
                            {
                                jsonWriter.WritePropertyName(field.Name);
                                if (field.ControlType == "CheckBox" && field.CheckBoxReturnBool == true)
                                {
                                    jsonWriter.WriteValue(Convert.ToBoolean(field.DefaultValue));
                                }
                                else
                                {
                                    jsonWriter.WriteValue(field.DefaultValue);
                                }
                            }
                        }
                        else
                        {
                            content.Replace(field.Token, string.Empty);
                        }
                    }
                }

                if (Config.RenderJSONOfData)
                {
                    //if (config.IsGlobalView)
                    //{
                    //    jsonWriter.WriteEndObject();
                    //}
                    jsonWriter.WriteEndObject();
                }

                content.Replace("$_EditLink_$", itemEditLink);
                content.Replace("$_ItemID_$", item.ItemID.ToString());
                content.Replace("$_SortOrder_$", item.SortOrder.ToString());

                if (!String.IsNullOrWhiteSpace(content))
                {
                    itemsMarkup.Add(content);
                }
            }
            if (Config.DescendingSort)
            {
                itemsMarkup.Sort(delegate(IndexedStringBuilder a, IndexedStringBuilder b)
                {
                    int xdiff = b.SortOrder1.CompareTo(a.SortOrder1);
                    if (xdiff != 0)
                    {
                        return(xdiff);
                    }
                    else
                    {
                        return(b.SortOrder2.CompareTo(a.SortOrder2));
                    }
                });
            }
            else
            {
                itemsMarkup.Sort(delegate(IndexedStringBuilder a, IndexedStringBuilder b)
                {
                    int xdiff = a.SortOrder1.CompareTo(b.SortOrder1);
                    if (xdiff != 0)
                    {
                        return(xdiff);
                    }
                    else
                    {
                        return(a.SortOrder2.CompareTo(b.SortOrder2));
                    }
                });
            }
            StringBuilder allItems = new StringBuilder();

            if (displaySettings.ItemsPerGroup == -1)
            {
                foreach (IndexedStringBuilder sb in itemsMarkup)
                {
                    //allItems.Append(displaySettings.GlobalViewModuleGroupMarkup.Replace("$_ModuleGroupName_$", sb.GroupName));
                    allItems.Append(sb.ToString());
                }
                if (usingGlobalViewMarkup)
                {
                    strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, displaySettings.GlobalViewMarkup.Replace("$_ModuleGroups_$", allItems.ToString()));
                }
                else
                {
                    strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, allItems.ToString());
                }
            }
            else
            {
                int itemIndex = 0;

                decimal totalGroupCount = Math.Ceiling(itemsMarkup.Count / Convert.ToDecimal(displaySettings.ItemsPerGroup));

                if (totalGroupCount < 1 && itemsMarkup.Count > 0)
                {
                    totalGroupCount = 1;
                }

                int currentGroup            = 1;
                List <StringBuilder> groups = new List <StringBuilder>();
                while (currentGroup <= totalGroupCount && itemIndex < itemsMarkup.Count)
                {
                    StringBuilder group = new StringBuilder();
                    group.Append(displaySettings.ItemsRepeaterMarkup);
                    //group.SortOrder1 = itemsMarkup[itemIndex].SortOrder1;
                    //group.SortOrder2 = itemsMarkup[itemIndex].SortOrder2;
                    //group.GroupName = itemsMarkup[itemIndex].GroupName;
                    for (int i = 0; i < displaySettings.ItemsPerGroup; i++)
                    {
                        if (itemIndex < itemsMarkup.Count)
                        {
                            group.Replace("$_Items[" + i.ToString() + "]_$", itemsMarkup[itemIndex].ToString());
                            itemIndex++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    groups.Add(group);
                    currentGroup++;
                }

                //groups.Sort(delegate (IndexedStringBuilder a, IndexedStringBuilder b) {
                //    int xdiff = a.SortOrder1.CompareTo(b.SortOrder1);
                //    if (xdiff != 0) return xdiff;
                //    else return a.SortOrder2.CompareTo(b.SortOrder2);
                //});

                foreach (StringBuilder group in groups)
                {
                    allItems.Append(group.ToString());
                }

                strOutput.AppendFormat(displaySettings.ItemsWrapperFormat, Regex.Replace(allItems.ToString(), @"(\$_Items\[[0-9]+\]_\$)", string.Empty, RegexOptions.Multiline));
            }



            //strOutput.Append(displaySettings.ItemListMarkupBottom);
            if (Config.RenderJSONOfData)
            {
                if (Config.JsonLabelObjects || Config.IsGlobalView)
                {
                    jsonWriter.WriteEndObject();

                    if (Config.IsGlobalView)
                    {
                        jsonWriter.WriteEndObject();
                        jsonWriter.WriteEnd();
                    }
                }
                else
                {
                    jsonWriter.WriteEndArray();
                }

                MarkupScript jsonScript = new MarkupScript();

                jsonWriter.Close();
                stringWriter.Close();

                jsonScript.RawScript  = stringWriter.ToString();
                jsonScript.Position   = Config.JsonRenderLocation;
                jsonScript.ScriptName = "sflexi" + module.ModuleId.ToString() + Config.MarkupDefinitionName.ToCleanFileName() + "-JSON";

                List <MarkupScript> scripts = new List <MarkupScript>();
                scripts.Add(jsonScript);

                SuperFlexiHelpers.SetupScripts(scripts, Config, displaySettings, siteSettings.UseSslOnAllPages, IsEditable, IsPostBack, ClientID, ModuleId, PageId, Page, this);
            }

            if (Config.UseFooter && Config.FooterLocation == "InnerBodyPanel" && !String.IsNullOrWhiteSpace(Config.FooterContent) && !String.Equals(Config.FooterContent, "<p>&nbsp;</p>"))
            {
                try
                {
                    strOutput.AppendFormat(displaySettings.FooterContentFormat, Config.FooterContent);
                }
                catch (System.FormatException ex)
                {
                    log.ErrorFormat(markupErrorFormat, "FooterContentFormat", moduleTitle, ex);
                }
            }

            strOutput.Append(markupBottom);

            SuperFlexiHelpers.ReplaceStaticTokens(strOutput, Config, IsEditable, displaySettings, module.ModuleId, pageSettings, siteSettings, out strOutput);

            //this is for displaying all of the selected values from the items outside of the items themselves
            foreach (CheckBoxListMarkup cblm in Config.CheckBoxListMarkups)
            {
                StringBuilder cblmContent = new StringBuilder();

                if (fields.Count > 0 && cblm.SelectedValues.Count > 0)
                {
                    Field theField = fields.Where(field => field.Name == cblm.Field).Single();
                    if (theField != null)
                    {
                        List <CheckBoxListMarkup.SelectedValue> distinctSelectedValues = new List <CheckBoxListMarkup.SelectedValue>();
                        foreach (CheckBoxListMarkup.SelectedValue selectedValue in cblm.SelectedValues)
                        {
                            CheckBoxListMarkup.SelectedValue match = distinctSelectedValues.Find(i => i.Value == selectedValue.Value);
                            if (match == null)
                            {
                                distinctSelectedValues.Add(selectedValue);
                            }
                            else
                            {
                                match.Count++;
                            }
                        }
                        //var selectedValues = cblm.SelectedValues.GroupBy(selectedValue => selectedValue.Value)
                        //    .Select(distinctSelectedValue => new { Value = distinctSelectedValue.Key, Count = distinctSelectedValue.Count(), ItemID = distinctSelectedValue.ItemID })
                        //    .OrderBy(x => x.Value);
                        foreach (CheckBoxListMarkup.SelectedValue value in distinctSelectedValues)
                        {
                            cblmContent.Append(cblm.Markup.Replace(theField.Token, value.Value).Replace("$_ValueItemID_$", value.ItemID.ToString()) + cblm.Separator);
                            cblmContent.Replace("$_CBLValueCount_$", value.Count.ToString());
                        }
                    }

                    if (cblmContent.Length >= cblm.Separator.Length)
                    {
                        cblmContent.Length -= cblm.Separator.Length;
                    }

                    strOutput.Replace(cblm.Token, cblmContent.ToString());
                }

                strOutput.Replace(cblm.Token, string.Empty);
            }
            theLit.Text = strOutput.ToString();
        }
Ejemplo n.º 11
0
        public ReturnObject GetModuleItems(RequestObject r)
        {
            siteSettings = CacheHelper.GetCurrentSiteSettings();
            currentPage  = new PageSettings(siteSettings.SiteId, r.PageId);
            bool allowed = false;
            bool canEdit = false;

            if (currentPage != null)
            {
                allowed = WebUser.IsInRoles(currentPage.AuthorizedRoles);
            }
            module = new Module(r.ModuleId);
            if (module != null)
            {
                allowed = WebUser.IsInRoles(module.ViewRoles);
            }
            if (!allowed)
            {
                return(new ReturnObject()
                {
                    Status = "error",
                    ExtraData = new Dictionary <string, string>
                    {
                        ["ErrorCode"] = "100",
                        ["ErrorMessage"] = "Not Allowed"
                    }
                });
            }

            config = new ModuleConfiguration(module);

            int         totalPages = 0;
            int         totalRows  = 0;
            List <Item> items      = new List <Item>();

            if (r.SearchObject != null && r.SearchObject.Count > 0)
            {
                foreach (var set in r.SearchObject)
                {
                    if (set.Value.Contains(";"))
                    {
                        foreach (var setA in set.Value.SplitOnCharAndTrim(';'))
                        {
                            items.AddRange(GetItems(
                                               module.ModuleGuid,
                                               1,
                                               99999,
                                               out totalPages,
                                               out totalRows,
                                               setA,
                                               set.Key,
                                               r.GetAllForSolution
                                               ));
                        }
                    }
                    else
                    {
                        items.AddRange(GetItems(
                                           module.ModuleGuid,
                                           1,
                                           99999,
                                           out totalPages,
                                           out totalRows,
                                           set.Value,
                                           set.Key,
                                           r.GetAllForSolution
                                           ));
                    }
                    //we have to figure out paging with this
                }
                items = items.Distinct(new SimpleItemComparer()).ToList();
            }
            else
            {
                items.AddRange(GetItems(
                                   module.ModuleGuid,
                                   r.PageNumber,
                                   r.PageSize,
                                   out totalPages,
                                   out totalRows,
                                   r.SearchTerm,
                                   r.SearchField,
                                   r.GetAllForSolution,
                                   r.SortDescending));
            }

            List <PopulatedItem> popItems = new List <PopulatedItem>();
            SuperFlexiObject     sfObject = new SuperFlexiObject()
            {
                FriendlyName    = config.ModuleFriendlyName,
                ModuleTitle     = module.ModuleTitle,
                GlobalSortOrder = config.GlobalViewSortOrder,
                Items           = popItems
            };

            if (items != null && items.Count > 0)
            {
                List <Field>          fields            = Field.GetAllForDefinition(config.FieldDefinitionGuid);
                var                   itemGuids         = items.Select(x => x.ItemGuid).ToList();
                List <ItemFieldValue> values            = ItemFieldValue.GetByItemGuids(itemGuids);
                Module                itemModule        = null;
                Guid                  currentModuleGuid = Guid.Empty;
                foreach (Item item in items.OrderBy(x => x.ModuleID).ToList())
                {
                    if (item.ModuleGuid != currentModuleGuid)
                    {
                        currentModuleGuid = item.ModuleGuid;
                        itemModule        = new Module(item.ModuleGuid);
                    }
                    if (itemModule == null)
                    {
                        continue;
                    }
                    if (!WebUser.IsInRoles(itemModule.ViewRoles))
                    {
                        continue;
                    }
                    var populatedItem = new PopulatedItem(item, fields, values.Where(v => v.ItemGuid == item.ItemGuid).ToList(), canEdit);
                    if (populatedItem != null)
                    {
                        if (r.SearchObject != null && r.SearchObject.Count > 0)
                        {
                            int matchCount = 0;
                            foreach (var searchItem in r.SearchObject)
                            {
                                var           value              = populatedItem.Values[searchItem.Key];
                                List <string> itemValArray       = value as List <string>;
                                List <string> searchItemValArray = searchItem.Value.SplitOnCharAndTrim(';');
                                //log.Info($"[{searchItem.Key}]={searchItem.Value}");

                                /*  Check if itemValArray == null because if it is, that means the value is just a plain value, not a List<string>.
                                 *  If we try to do a comparison on value.ToString() when value is a List<string>, .ToString() returns System.Collections.Generic...
                                 *  and then our comparison is actually looking for matches in "System.Collections.Generic...". We had that happen with the word
                                 *  "Collections". Oops.
                                 */

                                if ((itemValArray == null && value.ToString().ToLower().IndexOf(searchItem.Value.ToLower()) >= 0) ||
                                    (itemValArray != null && itemValArray.Any(s => s.Equals(searchItem.Value, StringComparison.OrdinalIgnoreCase))) ||
                                    (searchItemValArray != null && searchItemValArray.Any(s => s.Equals(value.ToString(), StringComparison.OrdinalIgnoreCase))))
                                {
                                    matchCount++;
                                }
                            }

                            if (matchCount == r.SearchObject.Count)
                            {
                                popItems.Add(populatedItem);
                            }
                        }
                        else
                        {
                            popItems.Add(populatedItem);
                        }
                    }
                }
            }

            return(new ReturnObject()
            {
                Status = "success",
                Data = sfObject,
                TotalPages = totalPages,
                TotalRows = totalRows == popItems.Count ? totalRows : popItems.Count,
                AllowEdit = ShouldAllowEdit(),
                CmsModuleId = module.ModuleId,
                CmsPageId = module.PageId
            });
        }
Ejemplo n.º 12
0
        public override void DeleteContent(int moduleId, Guid moduleGuid)
        {
            ItemFieldValue.DeleteByModule(moduleGuid);
            Item.DeleteByModule(moduleGuid);

            Module module = new Module(moduleGuid);
            ModuleConfiguration config = new ModuleConfiguration(module);

            //having field definitions in the database when the fields aren't used by any module is just clutter.
            //we'll delete the field definitions from the database when they aren't used but of course we don't touch the actual field definition XML files.
            bool deleteOrphanFields = ConfigHelper.GetBoolProperty("SuperFlexi:DeleteFieldDefinitionsWhenNotUsed", true);

            //we didn't implement the delete handler for a year or so after building superflexi so we have a lot of instances in the wild that probably have orphaned items
            //if we upgrade those to this version, create a module instance, and then delete it, these orphaned items will be removed
            bool deleteOrphanItems = ConfigHelper.GetBoolProperty("SuperFlexi:DeleteOrphanedItemsWhenDeletingModules", true);

            //clean up search definitions
            bool deleteOrphanSearchDefinitions = ConfigHelper.GetBoolProperty("SuperFlexi:DeleteOrphanedSearchDefinitions", true);

            if (deleteOrphanFields || deleteOrphanItems || deleteOrphanSearchDefinitions)
            {
                List <Item> sflexiItems     = Item.GetForModule(module.ModuleId);
                List <Guid> definitionGuids = new List <Guid>();


                foreach (Item item in sflexiItems)
                {
                    //add definitionGuids here b/c we'll need them for all three checks
                    definitionGuids.Add(item.DefinitionGuid);

                    if (deleteOrphanItems)
                    {
                        Module checkModule = new Module(item.ModuleGuid);
                        if (checkModule == null)
                        {
                            ItemFieldValue.DeleteByModule(item.ModuleGuid);
                            Item.DeleteByModule(item.ModuleGuid);
                        }
                    }
                }

                if (deleteOrphanFields)
                {
                    definitionGuids = definitionGuids.Distinct().ToList();

                    foreach (Guid guid in definitionGuids)
                    {
                        List <Item> definitionItems = Item.GetForDefinition(guid, module.SiteGuid);
                        if (definitionItems.Count == 0)
                        {
                            //delete field definitions when there are no more modules using them
                            Field.DeleteByDefinition(guid);

                            if (deleteOrphanSearchDefinitions)
                            {
                                //delete search definitions when there are no more modules using their definition
                                SearchDef.DeleteByFieldDefinition(guid);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 13
0
        public static void SetupStyle(
            List <MarkupCss> markupCss,
            ModuleConfiguration config,
            SuperFlexiDisplaySettings displaySettings,
            bool isEditable,
            string clientID,
            SiteSettings siteSettings,
            Module module,
            PageSettings pageSettings,
            Page page,
            Control control)
        {
            string styleLinkFormat = "\n<link rel=\"stylesheet\" href=\"{0}\" media=\"{2}\" data-name=\"{1}\">";
            string rawCSSFormat    = "\n<style type=\"text/css\" data-name=\"{1}\" media=\"{2}\">\n{0}\n</style>";

            foreach (MarkupCss style in markupCss)
            {
                StringBuilder sbStyleText = new StringBuilder();
                StringBuilder sbStyleName = new StringBuilder();

                sbStyleName.Append(string.IsNullOrWhiteSpace(style.Name) ? clientID + "flexiStyle_" + markupCss.IndexOf(style) : "flexiStyle_" + style.Name);
                ReplaceStaticTokens(sbStyleName, config, false, displaySettings, module, pageSettings, siteSettings, out sbStyleName);
                string styleName = sbStyleName.ToString();
                if (!string.IsNullOrWhiteSpace(style.Url))
                {
                    string styleUrl = string.Empty;

                    if (style.Url.StartsWith("/") ||
                        style.Url.StartsWith("http://") ||
                        style.Url.StartsWith("https://"))
                    {
                        styleUrl = style.Url;
                    }
                    else if (style.Url.StartsWith("~/"))
                    {
                        styleUrl = WebUtils.ResolveServerUrl(style.Url, siteSettings.UseSslOnAllPages);
                    }
                    else if (style.Url.StartsWith("$_SitePath_$"))
                    {
                        styleUrl = style.Url.Replace("$_SitePath_$", "/Data/Sites/" + CacheHelper.GetCurrentSiteSettings().SiteId.ToString() + "/");
                    }
                    else
                    {
                        styleUrl = new Uri(config.SolutionLocationUrl, style.Url).ToString();
                    }

                    sbStyleText.Append(string.Format(styleLinkFormat, styleUrl, styleName, style.Media));
                }
                else if (!string.IsNullOrWhiteSpace(style.CSS))
                {
                    sbStyleText.Append(string.Format(rawCSSFormat, style.CSS, styleName, style.Media));
                }

                ReplaceStaticTokens(sbStyleText, config, false, displaySettings, module, pageSettings, siteSettings, out sbStyleText);

                LiteralControl theLiteral = new LiteralControl();
                theLiteral.Text = sbStyleText.ToString();

                StyleSheetCombiner ssc = (StyleSheetCombiner)page.Header.FindControl("StyleSheetCombiner");

                if (ssc != null)
                {
                    int sscIndex = page.Header.Controls.IndexOf(ssc);
                    if (style.RenderAboveSSC)
                    {
                        page.Header.Controls.AddAt(sscIndex, theLiteral);
                    }
                    else
                    {
                        page.Header.Controls.AddAt(sscIndex + 1, theLiteral);
                    }
                }
                else
                {
                    page.Header.Controls.AddAt(0, theLiteral);
                }
            }
        }
Ejemplo n.º 14
0
        public static void SetupScripts(
            List <MarkupScript> markupScripts,
            ModuleConfiguration config,
            SuperFlexiDisplaySettings displaySettings,
            bool isEditable,
            bool isPostBack,
            string clientID,
            SiteSettings siteSettings,
            Module module,
            PageSettings pageSettings,
            Page page,
            Control control)
        {
            string scriptRefFormat = "\n<script type=\"text/javascript\" src=\"{0}\" data-name=\"{1}\"></script>";
            string rawScriptFormat = "\n<script type=\"text/javascript\" data-name=\"{1}\">\n{0}\n</script>";

            foreach (MarkupScript script in markupScripts)
            {
                StringBuilder sbScriptText = new StringBuilder();
                StringBuilder sbScriptName = new StringBuilder();

                sbScriptName.Append(string.IsNullOrWhiteSpace(script.ScriptName) ? clientID + "flexiScript_" + markupScripts.IndexOf(script) : "flexiScript_" + script.ScriptName);
                ReplaceStaticTokens(sbScriptName, config, isEditable, displaySettings, module, pageSettings, siteSettings, out sbScriptName);

                string scriptName = sbScriptName.ToString();
                if (!string.IsNullOrWhiteSpace(script.Url))
                {
                    string scriptUrl = GetPathToFile(config, script.Url, WebConfigSettings.SslisAvailable);
                    sbScriptText.Append(string.Format(scriptRefFormat, scriptUrl, scriptName));
                }
                else if (!string.IsNullOrWhiteSpace(script.RawScript))
                {
                    sbScriptText.Append(string.Format(rawScriptFormat, script.RawScript, scriptName));
                }

                ReplaceStaticTokens(sbScriptText, config, isEditable, displaySettings, module, pageSettings, siteSettings, out sbScriptName);

                // script position options
                // inHead
                // inBody (register script) (default)
                // aboveMarkupDefinition
                // belowMarkupDefinition
                // bottomStartup (register startup script)
                switch (script.Position)
                {
                case "inHead":
                    if (!isPostBack && !page.IsCallback)
                    {
                        if (page.Header.FindControl(scriptName) == null)
                        {
                            LiteralControl headLit = new LiteralControl();
                            headLit.ID              = scriptName;
                            headLit.Text            = sbScriptText.ToString();
                            headLit.ClientIDMode    = ClientIDMode.Static;
                            headLit.EnableViewState = false;
                            page.Header.Controls.Add(headLit);
                        }
                    }
                    break;

                case "aboveMarkupDefinition":
                    if (control == null)
                    {
                        goto case "bottomStartup";
                    }
                    if (control.FindControlRecursive(scriptName) == null)
                    {
                        Control aboveMarkupDefinitionScripts = control.FindControlRecursive("aboveMarkupDefinitionScripts");
                        if (aboveMarkupDefinitionScripts != null)
                        {
                            LiteralControl aboveLit = new LiteralControl();
                            aboveLit.ID   = scriptName;
                            aboveLit.Text = sbScriptText.ToString();
                            aboveMarkupDefinitionScripts.Controls.Add(aboveLit);
                        }
                        else
                        {
                            goto case "bottomStartup";
                        }
                    }
                    break;

                case "belowMarkupDefinition":
                    if (control == null)
                    {
                        goto case "bottomStartup";
                    }
                    if (control.FindControlRecursive(scriptName) == null)
                    {
                        Control belowMarkupDefinitionScripts = control.FindControlRecursive("belowMarkupDefinitionScripts");
                        if (belowMarkupDefinitionScripts != null)
                        {
                            LiteralControl belowLit = new LiteralControl();
                            belowLit.ID   = scriptName;
                            belowLit.Text = sbScriptText.ToString();
                            belowMarkupDefinitionScripts.Controls.Add(belowLit);
                        }
                        else
                        {
                            goto case "bottomStartup";
                        }
                    }
                    //strBelowMarkupScripts.AppendLine(scriptText);
                    break;

                case "bottomStartup":
                    if (!page.ClientScript.IsStartupScriptRegistered(scriptName))
                    {
                        ScriptManager.RegisterStartupScript(
                            page,
                            typeof(Page),
                            scriptName,
                            sbScriptText.ToString(),
                            false);
                    }
                    break;

                case "inBody":
                default:
                    if (!page.ClientScript.IsClientScriptBlockRegistered(scriptName))
                    {
                        ScriptManager.RegisterClientScriptBlock(
                            page,
                            typeof(Page),
                            scriptName,
                            sbScriptText.ToString(),
                            false);
                    }
                    break;
                }
            }
        }
Ejemplo n.º 15
0
        //public static List<MarkupScript> ParseScriptsFromXml(ModuleConfiguration config)
        //{
        //    List<MarkupScript> scripts = new List<MarkupScript>();
        //    string fullPath = string.Empty;
        //    XmlDocument doc = new XmlDocument();
        //    if (DefinitionExists(config.FieldDefinitionSrc, out doc))
        //    {
        //        XmlNode node = doc.DocumentElement.SelectSingleNode("/Fields/Scripts");

        //        if (node == null) return scripts;

        //        try
        //        {
        //            scripts = SuperFlexiHelpers.ParseScriptsFromXmlNode(node);
        //        }
        //        catch (System.Xml.XmlException ex)
        //        {
        //            log.Error(ex);
        //        }
        //    }
        //    return scripts;
        //}



        /// <summary>
        /// Creates a list of Field from field definition xml file.
        /// </summary>
        /// <param name="fieldDefinitionSrc"></param>
        /// <returns>IList</returns>
        public static List <Field> ParseFieldDefinitionXml(ModuleConfiguration config, Guid siteGuid)
        {
            List <Field> fields   = new List <Field>();
            string       fullPath = string.Empty;
            XmlDocument  doc      = new XmlDocument();

            if (DefinitionExists(config.FieldDefinitionSrc, out doc))
            {
                XmlNode node = doc.DocumentElement.SelectSingleNode("/Fields");
                if (node != null)
                {
                    XmlAttributeCollection attribs = node.Attributes;

                    string definitionName = string.Empty;
                    Guid   definitionGuid = Guid.NewGuid();
                    if (attribs["definitionName"] != null)
                    {
                        definitionName = attribs["definitionName"].Value;
                    }
                    if (attribs["definitionGuid"] != null)
                    {
                        definitionGuid = Guid.Parse(attribs["definitionGuid"].Value);
                    }

                    foreach (XmlNode childNode in node)
                    {
                        if (childNode.Name == "Field")
                        {
                            try
                            {
                                Field field = new Field();
                                XmlAttributeCollection itemDefAttribs = childNode.Attributes;

                                field.DefinitionName = definitionName;
                                field.DefinitionGuid = definitionGuid;
                                if (itemDefAttribs["name"] != null)
                                {
                                    field.Name = itemDefAttribs["name"].Value;
                                }
                                if (itemDefAttribs["label"] != null)
                                {
                                    field.Label = itemDefAttribs["label"].Value;
                                }
                                if (itemDefAttribs["defaultValue"] != null)
                                {
                                    field.DefaultValue = itemDefAttribs["defaultValue"].Value;
                                }
                                if (itemDefAttribs["controlType"] != null)
                                {
                                    field.ControlType = itemDefAttribs["controlType"].Value;
                                }
                                if (itemDefAttribs["controlSrc"] != null)
                                {
                                    field.ControlSrc = itemDefAttribs["controlSrc"].Value;
                                }
                                field.SortOrder = XmlUtils.ParseInt32FromAttribute(itemDefAttribs, "sortOrder", field.SortOrder);
                                if (itemDefAttribs["helpKey"] != null)
                                {
                                    field.HelpKey = itemDefAttribs["helpKey"].Value;
                                }
                                field.Required = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "required", field.Required);
                                if (itemDefAttribs["requiredMessageFormat"] != null)
                                {
                                    field.RequiredMessageFormat = itemDefAttribs["requiredMessageFormat"].Value;
                                }
                                if (itemDefAttribs["regex"] != null)
                                {
                                    field.Regex = itemDefAttribs["regex"].Value;
                                }
                                if (itemDefAttribs["regexMessageFormat"] != null)
                                {
                                    field.RegexMessageFormat = itemDefAttribs["regexMessageFormat"].Value;
                                }
                                if (itemDefAttribs["token"] != null && !String.IsNullOrWhiteSpace(itemDefAttribs["token"].Value))
                                {
                                    field.Token = itemDefAttribs["token"].Value;
                                }

                                field.Searchable = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "isSearchable", field.Searchable);
                                if (itemDefAttribs["editPageControlWrapperCssClass"] != null)
                                {
                                    field.EditPageControlWrapperCssClass = itemDefAttribs["editPageControlWrapperCssClass"].Value;
                                }
                                if (itemDefAttribs["editPageLabelCssClass"] != null)
                                {
                                    field.EditPageLabelCssClass = itemDefAttribs["editPageLabelCssClass"].Value;
                                }
                                if (itemDefAttribs["editPageControlCssClass"] != null)
                                {
                                    field.EditPageControlCssClass = itemDefAttribs["editPageControlCssClass"].Value;
                                }
                                field.DatePickerIncludeTimeForDate = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "datePickerIncludeTimeForDate", field.DatePickerIncludeTimeForDate);
                                field.DatePickerShowMonthList      = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "datePickerShowMonthList", field.DatePickerShowMonthList);
                                field.DatePickerShowYearList       = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "datePickerShowYearList", field.DatePickerShowYearList);
                                if (itemDefAttribs["datePickerYearRange"] != null)
                                {
                                    field.DatePickerYearRange = itemDefAttribs["datePickerYearRange"].Value;
                                }
                                if (itemDefAttribs["imageBrowserEmptyUrl"] != null)
                                {
                                    field.ImageBrowserEmptyUrl = itemDefAttribs["imageBrowserEmptyUrl"].Value;
                                }
                                field.CheckBoxReturnBool = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "checkBoxReturnBool", field.CheckBoxReturnBool);
                                if (itemDefAttribs["checkBoxReturnValueWhenTrue"] != null)
                                {
                                    field.CheckBoxReturnValueWhenTrue = itemDefAttribs["checkBoxReturnValueWhenTrue"].Value;
                                }
                                if (itemDefAttribs["checkBoxReturnValueWhenFalse"] != null)
                                {
                                    field.CheckBoxReturnValueWhenFalse = itemDefAttribs["checkBoxReturnValueWhenFalse"].Value;
                                }
                                if (itemDefAttribs["dateFormat"] != null)
                                {
                                    field.DateFormat = itemDefAttribs["dateFormat"].Value;
                                }
                                if (itemDefAttribs["textBoxMode"] != null)
                                {
                                    field.TextBoxMode = itemDefAttribs["textBoxMode"].Value;
                                }
                                field.IsDeleted = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "isDeleted", field.IsDeleted);
                                field.IsGlobal  = XmlUtils.ParseBoolFromAttribute(itemDefAttribs, "isGlobal", field.IsGlobal);

                                StringBuilder options    = new StringBuilder();
                                StringBuilder attributes = new StringBuilder();
                                foreach (XmlNode subNode in childNode)
                                {
                                    switch (subNode.Name)
                                    {
                                    case "Options":
                                        GetKeyValuePairs(subNode.ChildNodes, out options);
                                        break;

                                    case "Attributes":
                                        GetKeyValuePairs(subNode.ChildNodes, out attributes);
                                        break;

                                    case "PreTokenString":
                                        field.PreTokenString = subNode.InnerText.Trim();
                                        break;

                                    case "PostTokenString":
                                        field.PostTokenString = subNode.InnerText.Trim();
                                        break;
                                    }
                                }

                                if (options.Length > 0)
                                {
                                    field.Options = options.ToString();
                                }

                                if (attributes.Length > 0)
                                {
                                    field.Attributes = attributes.ToString();
                                }

                                fields.Add(field);
                            }
                            catch (System.Xml.XmlException ex)
                            {
                                log.Error(ex);
                            }
                        }
                        else if (childNode.Name == "Scripts")
                        {
                            try
                            {
                                config.EditPageScripts = SuperFlexiHelpers.ParseScriptsFromXmlNode(childNode);
                            }
                            catch (System.Xml.XmlException ex)
                            {
                                log.Error(ex);
                            }
                        }
                        else if (childNode.Name == "Styles")
                        {
                            try
                            {
                                config.EditPageCSS = SuperFlexiHelpers.ParseCssFromXmlNode(childNode);
                            }
                            catch (System.Xml.XmlException ex)
                            {
                                log.Error(ex);
                            }
                        }
                        else if (childNode.Name == "SearchDefinition")
                        {
                            try
                            {
                                SuperFlexiHelpers.ParseSearchDefinition(childNode, definitionGuid, siteGuid);
                            }
                            catch (XmlException ex)
                            {
                                log.Error(ex);
                            }
                        }
                    }
                }
            }

            fields.Sort();
            return(fields);
        }
Ejemplo n.º 16
0
        private IndexItem GetIndexItem(PageSettings pageSettings, int moduleID, Item item)
        {
            Module module = new Module(moduleID);
            ModuleConfiguration config = new ModuleConfiguration(module);

            if (!config.IncludeInSearch)
            {
                return(null);
            }
            SuperFlexiDisplaySettings displaySettings = new SuperFlexiDisplaySettings();
            ModuleDefinition          flexiFeature    = new ModuleDefinition(config.FeatureGuid);
            IndexItem indexItem = new IndexItem();

            indexItem.SiteId              = pageSettings.SiteId;
            indexItem.PageId              = pageSettings.PageId;
            indexItem.PageName            = pageSettings.PageName;
            indexItem.ViewRoles           = pageSettings.AuthorizedRoles;
            indexItem.FeatureId           = flexiFeature.FeatureGuid.ToString();
            indexItem.FeatureName         = String.IsNullOrWhiteSpace(config.ModuleFriendlyName) ? module.ModuleTitle : config.ModuleFriendlyName;
            indexItem.FeatureResourceFile = flexiFeature.ResourceFile;
            indexItem.ItemId              = item.ItemID;
            indexItem.CreatedUtc          = item.CreatedUtc;
            indexItem.LastModUtc          = item.LastModUtc;
            if (pageSettings.UseUrl)
            {
                if (pageSettings.UrlHasBeenAdjustedForFolderSites)
                {
                    indexItem.ViewPage = pageSettings.UnmodifiedUrl.Replace("~/", string.Empty);
                }
                else
                {
                    indexItem.ViewPage = pageSettings.Url.Replace("~/", string.Empty);
                }
                indexItem.UseQueryStringParams = false;
            }

            SearchDef searchDef = SearchDef.GetByFieldDefinition(item.DefinitionGuid);

            bool hasSearchDef = true;

            if (searchDef == null)
            {
                searchDef    = new SearchDef();
                hasSearchDef = false;
            }
            System.Text.StringBuilder sbTitle             = new System.Text.StringBuilder(searchDef.Title);
            System.Text.StringBuilder sbKeywords          = new System.Text.StringBuilder(searchDef.Keywords);
            System.Text.StringBuilder sbDescription       = new System.Text.StringBuilder(searchDef.Description);
            System.Text.StringBuilder sbLink              = new System.Text.StringBuilder(searchDef.Link);
            System.Text.StringBuilder sbLinkQueryAddendum = new System.Text.StringBuilder(searchDef.LinkQueryAddendum);
            SiteSettings siteSettings = new SiteSettings(pageSettings.SiteGuid);

            SuperFlexiHelpers.ReplaceStaticTokens(sbTitle, config, false, displaySettings, moduleID, pageSettings, siteSettings, out sbTitle);
            SuperFlexiHelpers.ReplaceStaticTokens(sbKeywords, config, false, displaySettings, moduleID, pageSettings, siteSettings, out sbKeywords);
            SuperFlexiHelpers.ReplaceStaticTokens(sbDescription, config, false, displaySettings, moduleID, pageSettings, siteSettings, out sbDescription);
            SuperFlexiHelpers.ReplaceStaticTokens(sbLink, config, false, displaySettings, moduleID, pageSettings, siteSettings, out sbLink);
            SuperFlexiHelpers.ReplaceStaticTokens(sbLinkQueryAddendum, config, false, displaySettings, moduleID, pageSettings, siteSettings, out sbLinkQueryAddendum);

            foreach (ItemFieldValue fieldValue in ItemFieldValue.GetItemValues(item.ItemGuid))
            {
                Field field = new Field(fieldValue.FieldGuid);
                if (field == null || !field.Searchable)
                {
                    continue;
                }

                if (hasSearchDef)
                {
                    sbTitle.Replace(field.Token, fieldValue.FieldValue);
                    sbKeywords.Replace(field.Token, fieldValue.FieldValue);
                    sbDescription.Replace(field.Token, fieldValue.FieldValue);
                    sbLink.Replace(field.Token, fieldValue.FieldValue);
                    sbLinkQueryAddendum.Replace(field.Token, fieldValue.FieldValue);
                }
                else
                {
                    sbKeywords.Append(fieldValue.FieldValue);
                }

                if (debugLog)
                {
                    log.DebugFormat("RebuildIndex indexing item [{0} = {1}]", field.Name, fieldValue.FieldValue);
                }
            }

            if (hasSearchDef)
            {
                sbTitle.Replace("$_ItemID_$", item.ItemID.ToString());
                sbKeywords.Replace("$_ItemID_$", item.ItemID.ToString());
                sbDescription.Replace("$_ItemID_$", item.ItemID.ToString());
                sbLink.Replace("$_ItemID_$", item.ItemID.ToString());
                sbLinkQueryAddendum.Replace("$_ItemID_$", item.ItemID.ToString());

                indexItem.Content = sbDescription.ToString();
                indexItem.Title   = sbTitle.ToString();

                if (sbLink.Length > 0)
                {
                    indexItem.ViewPage = sbLink.ToString();
                }

                if (sbLinkQueryAddendum.Length > 0)
                {
                    indexItem.QueryStringAddendum  = sbLinkQueryAddendum.ToString();
                    indexItem.UseQueryStringParams = false;
                }
            }
            else
            {
                indexItem.ModuleTitle = pageSettings.PageName;
                indexItem.Title       = String.IsNullOrWhiteSpace(config.ModuleFriendlyName) ? module.ModuleTitle : config.ModuleFriendlyName;
            }

            indexItem.PageMetaKeywords = sbKeywords.ToString();
            indexItem.Categories       = sbKeywords.ToString();

            return(indexItem);
        }