Пример #1
0
 //
 //====================================================================================================
 //
 public override void OpenCopy(string copyRecordNameOrGuid)
 {
     try {
         accum = "";
         CopyContentModel copy;
         if (copyRecordNameOrGuid.isNumeric())
         {
             //
             // -- recordId
             copy = CopyContentModel.create <CopyContentModel>(cp, GenericController.encodeInteger(copyRecordNameOrGuid));
         }
         else if (GenericController.isGuid(copyRecordNameOrGuid))
         {
             //
             // -- record guid
             copy = CopyContentModel.create <CopyContentModel>(cp, copyRecordNameOrGuid);
         }
         else
         {
             //
             // -- record name
             copy = DbBaseModel.createByUniqueName <CopyContentModel>(cp, copyRecordNameOrGuid);
         }
         if (copy != null)
         {
             accum = copy.copy;
         }
     } catch (Exception ex) {
         LogController.logError(cp.core, ex);
         throw;
     }
 }
Пример #2
0
        //
        //====================================================================================================
        //
        public override int GetTableID(string tableName)
        {
            var table = DbBaseModel.createByUniqueName <TableModel>(cp, tableName);

            if (table == null)
            {
                return(0);
            }
            return(table.id);
        }
Пример #3
0
        //
        //====================================================================================================
        //
        public override int GetID(string ContentName)
        {
            var content = DbBaseModel.createByUniqueName <ContentModel>(cp, ContentName);

            if (content != null)
            {
                return(content.id);
            }
            return(0);
        }
Пример #4
0
        //
        //====================================================================================================
        /// <summary>
        /// Get a group Id
        /// </summary>
        /// <param name="core"></param>
        /// <param name="GroupName"></param>
        /// <returns></returns>
        public static int getGroupId(CoreController core, string GroupName)
        {
            var group = DbBaseModel.createByUniqueName <GroupModel>(core.cpParent, GroupName);

            if (group != null)
            {
                return(group.id);
            }
            return(0);
        }
Пример #5
0
        //
        //====================================================================================================
        /// <summary>
        /// Remove a user from a group.
        /// </summary>
        /// <param name="core"></param>
        /// <param name="groupName"></param>
        /// <param name="userId"></param>
        public static void removeUser(CoreController core, string groupName, int userId)
        {
            var group = DbBaseModel.createByUniqueName <GroupModel>(core.cpParent, groupName);

            if (group != null)
            {
                var user = DbBaseModel.create <PersonModel>(core.cpParent, userId);
                if (user != null)
                {
                    removeUser(core, group, user);
                }
            }
        }
Пример #6
0
        //
        //=====================================================================================================
        /// <summary>
        /// Get the query to test the authoring control table if a record is locked
        /// </summary>
        /// <param name="cdef"></param>
        /// <param name="recordId"></param>
        /// <returns></returns>
        private static string getAuthoringControlCriteria(CoreController core, Models.Domain.ContentMetadataModel cdef, int recordId)
        {
            if (cdef == null)
            {
                return("(1=0)");
            }
            var table = DbBaseModel.createByUniqueName <TableModel>(core.cpParent, cdef.tableName);

            if (table == null)
            {
                return("(1=0)");
            }
            return(getAuthoringControlCriteria(getTableRecordKey(table.id, recordId), core.dateTimeNowMockable));
        }
Пример #7
0
        public override int LandingPageId(string domainName)
        {
            if (string.IsNullOrWhiteSpace(domainName))
            {
                return(GetInteger("LandingPageID", 0));
            }
            var domain = DbBaseModel.createByUniqueName <DomainModel>(cp, domainName);

            if (domain == null)
            {
                return(GetInteger("LandingPageID", 0));
            }
            return(domain.rootPageId);
        }
Пример #8
0
        //
        //========================================================================
        /// <summary>
        /// get the id of the table record for a content
        /// </summary>
        /// <param name="contentName"></param>
        /// <returns></returns>
        public static int getContentTableID(CoreController core, string contentName)
        {
            var meta = ContentMetadataModel.createByUniqueName(core, contentName);

            if (meta == null)
            {
                return(0);
            }
            var table = DbBaseModel.createByUniqueName <TableModel>(core.cpParent, meta.tableName);

            if (table != null)
            {
                return(table.id);
            }
            return(0);
        }
 /// <summary>
 /// For memberSelect type content. memberSelectGroup, name set by xml file load, name get for xml file save, id and name get and set in code
 /// </summary>
 public int memberSelectGroupId_get(CoreController core)
 {
     if ((_memberSelectGroupId == null) && (_memberSelectGroupName != null))
     {
         if (string.IsNullOrEmpty(_memberSelectGroupName))
         {
             _memberSelectGroupId = 0;
         }
         else
         {
             var group = DbBaseModel.createByUniqueName <GroupModel>(core.cpParent, _memberSelectGroupName);
             _memberSelectGroupId = (group == null) ? 0 : group.id;
         };
     }
     return(GenericController.encodeInteger(_memberSelectGroupId));
 }
Пример #10
0
 //
 public static void process(CPBaseClass cp, HtmlDocument htmlDoc, ref List <string> userMessageList)
 {
     //
     // -- data attribute
     {
         string             xPath    = "//*[@data-layout]";
         HtmlNodeCollection nodeList = htmlDoc.DocumentNode.SelectNodes(xPath);
         if (nodeList != null)
         {
             foreach (HtmlNode node in nodeList)
             {
                 string layoutRecordName = node.Attributes["data-layout"]?.Value;
                 node.Attributes.Remove("data-layout");
                 //
                 // -- body found, set the htmlDoc to the body
                 var layoutDoc = new HtmlDocument();
                 layoutDoc.LoadHtml(node.InnerHtml);
                 //
                 // -- process the layout
                 DataDeleteController.process(layoutDoc);
                 MustacheVariableController.process(layoutDoc);
                 MustacheSectionController.process(layoutDoc);
                 MustacheTruthyController.process(layoutDoc);
                 MustacheInvertedSectionController.process(layoutDoc);
                 MustacheValueController.process(layoutDoc);
                 DataAddonController.process(cp, layoutDoc);
                 //
                 // -- save the alyout
                 LayoutModel layout = null;
                 if ((layout == null) && !string.IsNullOrWhiteSpace(layoutRecordName))
                 {
                     layout = DbBaseModel.createByUniqueName <LayoutModel>(cp, layoutRecordName);
                     if (layout == null)
                     {
                         layout      = DbBaseModel.addDefault <LayoutModel>(cp);
                         layout.name = layoutRecordName;
                     }
                     layout.layout.content = layoutDoc.DocumentNode.OuterHtml;
                     layout.save(cp);
                     userMessageList.Add("Saved Layout '" + layoutRecordName + "' from data-layout attribute.");
                 }
             }
         }
     }
 }
Пример #11
0
        //
        //====================================================================================================
        /// <summary>
        /// Add a user to a group. if group is missing and argument is name or guid, it is created.
        /// </summary>
        /// <param name="core"></param>
        /// <param name="groupNameIdOrGuid"></param>
        /// <param name="userid"></param>
        /// <param name="dateExpires"></param>
        public static void addUser(CoreController core, string groupNameIdOrGuid, int userid, DateTime dateExpires)
        {
            GroupModel group = null;

            if (groupNameIdOrGuid.isNumeric())
            {
                group = DbBaseModel.create <GroupModel>(core.cpParent, GenericController.encodeInteger(groupNameIdOrGuid));
                if (group == null)
                {
                    LogController.logError(core, new GenericException("addUser called with invalid groupId [" + groupNameIdOrGuid + "]"));
                    return;
                }
            }
            else if (GenericController.isGuid(groupNameIdOrGuid))
            {
                group = DbBaseModel.create <GroupModel>(core.cpParent, groupNameIdOrGuid);
                if (group == null)
                {
                    var defaultValues = ContentMetadataModel.getDefaultValueDict(core, "groups");
                    group         = DbBaseModel.addDefault <GroupModel>(core.cpParent, defaultValues);
                    group.ccguid  = groupNameIdOrGuid;
                    group.name    = groupNameIdOrGuid;
                    group.caption = groupNameIdOrGuid;
                    group.save(core.cpParent);
                }
            }
            else
            {
                group = DbBaseModel.createByUniqueName <GroupModel>(core.cpParent, groupNameIdOrGuid);
                if (group == null)
                {
                    group         = DbBaseModel.addDefault <GroupModel>(core.cpParent, Models.Domain.ContentMetadataModel.getDefaultValueDict(core, "groups"));
                    group.ccguid  = groupNameIdOrGuid;
                    group.name    = groupNameIdOrGuid;
                    group.caption = groupNameIdOrGuid;
                    group.save(core.cpParent);
                }
            }
            var user = DbBaseModel.create <PersonModel>(core.cpParent, userid);

            if (user != null)
            {
                addUser(core, group, user, dateExpires);
            }
        }
Пример #12
0
        //
        //====================================================================================================
        //
        public override int GetId(string GroupNameOrGuid)
        {
            GroupModel group;

            if (GenericController.isGuid(GroupNameOrGuid))
            {
                group = DbBaseModel.create <GroupModel>(cp, GroupNameOrGuid);
            }
            else
            {
                group = DbBaseModel.createByUniqueName <GroupModel>(cp, GroupNameOrGuid);
            }
            if (group != null)
            {
                return(group.id);
            }
            return(0);
        }
Пример #13
0
 //
 //====================================================================================================
 /// <summary>
 /// Create model for Addons. This method allows for the alias field if the name does not match
 /// </summary>
 /// <param name="cp"></param>
 /// <param name="recordName"></param>
 /// <returns></returns>
 public static AddonModel createByUniqueName(CPBaseClass cp, string recordName)
 {
     try {
         AddonModel addon = DbBaseModel.createByUniqueName <AddonModel>(cp, recordName);
         if (addon != null)
         {
             return(addon);
         }
         List <AddonModel> addonList = createList <AddonModel>(cp, "(','+aliasList+',' like " + cp.Db.EncodeSQLTextLike("," + recordName + ",") + ")");
         if (addonList.Count > 0)
         {
             return(addonList.First());
         }
         return(null);
     } catch (Exception ex) {
         cp.Site.ErrorReport(ex);
         throw;
     }
 }
 //
 //======================================================================================================
 //
 public static void installNode(CoreController core, XmlNode rootNode, int collectionId, ref bool return_UpgradeOK, ref string return_ErrorMessage, ref bool collectionIncludesDiagnosticAddons)
 {
     return_ErrorMessage = "";
     return_UpgradeOK    = true;
     try {
         string Basename = GenericController.toLCase(rootNode.Name);
         if (Basename == "layout")
         {
             bool   IsFound    = false;
             string layoutName = XmlController.getXMLAttribute(core, ref IsFound, rootNode, "name", "No Name");
             if (string.IsNullOrEmpty(layoutName))
             {
                 layoutName = "No Name";
             }
             string layoutGuid = XmlController.getXMLAttribute(core, ref IsFound, rootNode, "guid", layoutName);
             if (string.IsNullOrEmpty(layoutGuid))
             {
                 layoutGuid = layoutName;
             }
             var layout = DbBaseModel.create <LayoutModel>(core.cpParent, layoutGuid);
             if (layout == null)
             {
                 layout = DbBaseModel.createByUniqueName <LayoutModel>(core.cpParent, layoutName);
             }
             if (layout == null)
             {
                 layout = DbBaseModel.addDefault <LayoutModel>(core.cpParent);
             }
             layout.ccguid                  = layoutGuid;
             layout.name                    = layoutName;
             layout.layout.content          = rootNode.InnerText;
             layout.installedByCollectionId = collectionId;
             layout.save(core.cpParent);
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
         throw;
     }
 }
Пример #15
0
            //
            //====================================================================================================
            /// <summary>
            /// Import a file and process the html. Save the result.
            /// </summary>
            /// <param name="cp"></param>
            /// <param name="htmlSourceTempPathFilename"></param>
            /// <param name="importTypeId"></param>
            /// <param name="layoutId">If not 0, the imported html will be saved to the record in this table.</param>
            /// <param name="pageTemplateId">If not 0, the imported html will be saved to the record in this table.</param>
            /// <param name="emailTemplateId">If not 0, the imported html will be saved to the record in this table.</param>
            /// <param name="emailId">If not 0, the imported html will be saved to the record in this table.</param>
            /// <param name="userMessageList">If there were any processing errors caused by the data, return them here. These can be presented to the user.</param>
            /// <returns></returns>
            public static bool processImportFile(CPBaseClass cp, string htmlSourceTempPathFilename, ImporttypeEnum importTypeId, int layoutId, int pageTemplateId, int emailTemplateId, int emailId, ref List <string> userMessageList)
            {
                try {
                    if (System.IO.Path.GetExtension(htmlSourceTempPathFilename).Equals(".zip"))
                    {
                        //
                        // -- upload file is a zip and unzip to temp and copy assets to wwwroot
                        cp.TempFiles.UnzipFile(htmlSourceTempPathFilename);
                        cp.TempFiles.DeleteFile(htmlSourceTempPathFilename);
                        //
                        // -- copy non-html files to wwwroot
                        copyNonHtmlFilesToWWW(cp, cp.TempFiles.GetPath(htmlSourceTempPathFilename), "");
                    }
                    //
                    // -- import all html files in the root folder
                    string tempPath      = cp.TempFiles.GetPath(htmlSourceTempPathFilename);
                    bool   htmlFileFound = false;
                    foreach (var file in cp.TempFiles.FileList(tempPath))
                    {
                        if (file.Extension.ToLowerInvariant().Equals(".html"))
                        {
                            //
                            // -- process each html file one at a time
                            userMessageList.Add("Processing file " + cp.CdnFiles.GetFilename(file.Name));
                            string newRecordName = Path.GetFileNameWithoutExtension(file.Name);
                            htmlFileFound = true;
                            HtmlDocument htmlDoc = new HtmlDocument();
                            htmlDoc.Load(cp.TempFiles.PhysicalFilePath + tempPath + file.Name, Encoding.UTF8);
                            if (htmlDoc == null)
                            {
                                //
                                // -- body tag not found, import the whole document
                                userMessageList.Add("The file is empty.");
                                return(false);
                            }
                            //
                            // -- get record names for each import type
                            string layoutRecordName        = string.Empty;
                            string pageTemplateRecordName  = string.Empty;
                            string emailTemplateRecordName = string.Empty;
                            string emailRecordName         = string.Empty;
                            //
                            // -- search for meta name=template|layout content=recordaname
                            var metadataList = htmlDoc.DocumentNode.SelectNodes("//meta");
                            if (metadataList != null)
                            {
                                foreach (var metadataNode in metadataList)
                                {
                                    switch (metadataNode.GetAttributeValue("name", String.Empty).ToLowerInvariant())
                                    {
                                    case "layout": {
                                        layoutRecordName = metadataNode.GetAttributeValue("content", String.Empty);
                                        break;
                                    }

                                    case "template":
                                    case "pagetemplate": {
                                        pageTemplateRecordName = metadataNode.GetAttributeValue("content", String.Empty);
                                        break;
                                    }

                                    case "emailtemplate": {
                                        emailTemplateRecordName = metadataNode.GetAttributeValue("content", String.Empty);
                                        break;
                                    }

                                    case "email": {
                                        emailRecordName = metadataNode.GetAttributeValue("content", String.Empty);
                                        break;
                                    }

                                    default: {
                                        break;
                                    }
                                    }
                                }
                            }
                            //
                            // -- process the document html
                            if (!processHtmlDoc(cp, htmlDoc, importTypeId, ref userMessageList))
                            {
                                return(false);
                            }
                            //
                            // -- save manual layout
                            LayoutModel layout = null;
                            {
                                if (importTypeId.Equals(ImporttypeEnum.LayoutForAddon) && layoutId.Equals(0) & string.IsNullOrWhiteSpace(layoutRecordName))
                                {
                                    //
                                    // -- layout type but no layout selected, and no layout imported, use filename
                                    layoutRecordName = newRecordName;
                                }
                                if (importTypeId.Equals(ImporttypeEnum.LayoutForAddon) && !layoutId.Equals(0))
                                {
                                    layout = DbBaseModel.create <LayoutModel>(cp, layoutId);
                                    if (layout == null)
                                    {
                                        userMessageList.Add("The layout selected could not be found.");
                                        return(false);
                                    }
                                    layout.layout.content = htmlDoc.DocumentNode.OuterHtml;
                                    layout.save(cp);
                                }
                                //
                                // -- save meta layout
                                if ((layout == null) && !string.IsNullOrWhiteSpace(layoutRecordName))
                                {
                                    layout = DbBaseModel.createByUniqueName <LayoutModel>(cp, layoutRecordName);
                                    if (layout == null)
                                    {
                                        layout      = DbBaseModel.addDefault <LayoutModel>(cp);
                                        layout.name = layoutRecordName;
                                    }
                                    layout.layout.content = htmlDoc.DocumentNode.OuterHtml;
                                    layout.save(cp);
                                    userMessageList.Add("Saved Layout '" + layoutRecordName + "'.");
                                }
                            }
                            //
                            // -- save page template
                            PageTemplateModel pageTemplate = null;
                            {
                                if (importTypeId.Equals(ImporttypeEnum.PageTemplate) && pageTemplateId.Equals(0) & string.IsNullOrWhiteSpace(pageTemplateRecordName))
                                {
                                    //
                                    // -- layout type but no layout selected, and no layout imported, use filename
                                    pageTemplateRecordName = newRecordName;
                                }
                                if (importTypeId.Equals(ImporttypeEnum.PageTemplate) && !pageTemplateId.Equals(0))
                                {
                                    pageTemplate = DbBaseModel.create <PageTemplateModel>(cp, pageTemplateId);
                                    if (pageTemplate == null)
                                    {
                                        userMessageList.Add("The template selected could not be found.");
                                        return(false);
                                    }
                                    pageTemplate.bodyHTML = htmlDoc.DocumentNode.OuterHtml;
                                    pageTemplate.save(cp);
                                    userMessageList.Add("Saved Page Template '" + pageTemplateRecordName + "'.");
                                }
                                //
                                // -- save meta template
                                if ((pageTemplate == null) && !string.IsNullOrWhiteSpace(pageTemplateRecordName))
                                {
                                    pageTemplate = DbBaseModel.createByUniqueName <PageTemplateModel>(cp, pageTemplateRecordName);
                                    if (pageTemplate == null)
                                    {
                                        pageTemplate      = DbBaseModel.addDefault <PageTemplateModel>(cp);
                                        pageTemplate.name = pageTemplateRecordName;
                                    }
                                    //
                                    // -- try to resolve the various relative urls possible into the primary url, then to a reoot relative url
                                    string urlProtocolDomainSlash = "https://" + cp.Site.DomainPrimary + "/";
                                    string bodyhtml = htmlDoc.DocumentNode.OuterHtml;
                                    bodyhtml = genericController.convertLinksToAbsolute(bodyhtml, urlProtocolDomainSlash);
                                    bodyhtml = bodyhtml.Replace(urlProtocolDomainSlash, "/");
                                    //
                                    pageTemplate.bodyHTML = bodyhtml;
                                    pageTemplate.save(cp);
                                    userMessageList.Add("Saved Page Template '" + pageTemplateRecordName + "'.");
                                }
                            }
                            //
                            // -- save email template
                            EmailTemplateModel emailTemplate = null;
                            {
                                if (importTypeId.Equals(ImporttypeEnum.EmailTemplate) && emailTemplateId.Equals(0) & string.IsNullOrWhiteSpace(emailTemplateRecordName))
                                {
                                    //
                                    // --  type but no layout selected, and no layout imported, use filename
                                    emailTemplateRecordName = newRecordName;
                                }
                                if (importTypeId.Equals(ImporttypeEnum.EmailTemplate) && !emailTemplateId.Equals(0))
                                {
                                    emailTemplate = DbBaseModel.create <EmailTemplateModel>(cp, emailTemplateId);
                                    if (emailTemplate == null)
                                    {
                                        userMessageList.Add("The template selected could not be found.");
                                        return(false);
                                    }
                                    emailTemplate.bodyHTML = htmlDoc.DocumentNode.OuterHtml;
                                    emailTemplate.save(cp);
                                }
                                //
                                // -- save meta template
                                if ((emailTemplate == null) && !string.IsNullOrWhiteSpace(emailTemplateRecordName))
                                {
                                    emailTemplate = DbBaseModel.createByUniqueName <EmailTemplateModel>(cp, emailTemplateRecordName);
                                    if (emailTemplate == null)
                                    {
                                        emailTemplate      = DbBaseModel.addDefault <EmailTemplateModel>(cp);
                                        emailTemplate.name = emailTemplateRecordName;
                                    }
                                    emailTemplate.bodyHTML = htmlDoc.DocumentNode.OuterHtml;
                                    emailTemplate.save(cp);
                                    userMessageList.Add("Saved Email Template '" + emailTemplateRecordName + "'.");
                                }
                            }
                            //
                            // -- save email
                            EmailModel email = null;
                            {
                                if (importTypeId.Equals(5) && emailId.Equals(0) & string.IsNullOrWhiteSpace(emailRecordName))
                                {
                                    //
                                    // -- layout type but no layout selected, and no layout imported, use filename
                                    emailRecordName = newRecordName;
                                }
                                if (!emailId.Equals(0))
                                {
                                    email = DbBaseModel.create <EmailModel>(cp, emailId);
                                    if (email == null)
                                    {
                                        userMessageList.Add("The email selected could not be found.");
                                        return(false);
                                    }
                                    email.copyFilename.content = htmlDoc.DocumentNode.OuterHtml;
                                    email.save(cp);
                                    userMessageList.Add("Saved Email '" + emailRecordName + "'.");
                                }
                                //
                                // -- save meta template
                                if ((email == null) && !string.IsNullOrWhiteSpace(emailRecordName))
                                {
                                    email = DbBaseModel.createByUniqueName <EmailModel>(cp, emailRecordName);
                                    if (email == null)
                                    {
                                        email      = DbBaseModel.addDefault <EmailModel>(cp);
                                        email.name = emailRecordName;
                                    }
                                    email.copyFilename.content = htmlDoc.DocumentNode.OuterHtml;
                                    email.save(cp);
                                    userMessageList.Add("Saved Email '" + emailRecordName + "'.");
                                }
                            }
                        }
                    }
                    if (!htmlFileFound)
                    {
                        userMessageList.Add("No files were found with .HTML extension. Only files with .HTML extensions are imported.");
                        return(false);
                    }
                    return(true);
                } catch (Exception ex) {
                    cp.Site.ErrorReport(ex);
                    throw;
                }
            }
Пример #16
0
        //
        //======================================================================================================
        //
        public static void installNode(CoreController core, XmlNode AddonNode, string AddonGuidFieldName, int CollectionID, ref bool return_UpgradeOK, ref string return_ErrorMessage, ref bool collectionIncludesDiagnosticAddons)
        {
            // todo - return bool
            return_ErrorMessage = "";
            return_UpgradeOK    = true;
            try {
                string Basename = GenericController.toLCase(AddonNode.Name);
                if ((Basename == "page") || (Basename == "process") || (Basename == "addon") || (Basename == "add-on"))
                {
                    bool   IsFound   = false;
                    string addonName = XmlController.getXMLAttribute(core, ref IsFound, AddonNode, "name", "No Name");
                    if (string.IsNullOrEmpty(addonName))
                    {
                        addonName = "No Name";
                    }
                    string addonGuid = XmlController.getXMLAttribute(core, ref IsFound, AddonNode, "guid", addonName);
                    if (string.IsNullOrEmpty(addonGuid))
                    {
                        addonGuid = addonName;
                    }
                    string navTypeName = XmlController.getXMLAttribute(core, ref IsFound, AddonNode, "type", "");
                    int    navTypeId   = getListIndex(navTypeName, navTypeIDList);
                    if (navTypeId == 0)
                    {
                        navTypeId = NavTypeIDAddon;
                    }
                    using (var cs = new CsModel(core)) {
                        string Criteria = "(" + AddonGuidFieldName + "=" + DbController.encodeSQLText(addonGuid) + ")";
                        cs.open(AddonModel.tableMetadata.contentName, Criteria, "", false);
                        if (cs.ok())
                        {
                            //
                            // Update the Addon
                            //
                            LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, GUID match with existing Add-on, Updating Add-on [" + addonName + "], Guid [" + addonGuid + "]");
                        }
                        else
                        {
                            //
                            // not found by GUID - search name against name to update legacy Add-ons
                            //
                            cs.close();
                            Criteria = "(name=" + DbController.encodeSQLText(addonName) + ")and(" + AddonGuidFieldName + " is null)";
                            cs.open(AddonModel.tableMetadata.contentName, Criteria, "", false);
                            if (cs.ok())
                            {
                                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, Add-on name matched an existing Add-on that has no GUID, Updating legacy Aggregate Function to Add-on [" + addonName + "], Guid [" + addonGuid + "]");
                            }
                        }
                        if (!cs.ok())
                        {
                            //
                            // not found by GUID or by name, Insert a new addon
                            //
                            cs.close();
                            cs.insert(AddonModel.tableMetadata.contentName);
                            if (cs.ok())
                            {
                                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, Creating new Add-on [" + addonName + "], Guid [" + addonGuid + "]");
                            }
                        }
                        if (!cs.ok())
                        {
                            //
                            // Could not create new Add-on
                            //
                            LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, Add-on could not be created, skipping Add-on [" + addonName + "], Guid [" + addonGuid + "]");
                        }
                        else
                        {
                            int addonId = cs.getInteger("ID");
                            MetadataController.deleteContentRecords(core, "Add-on Include Rules", "addonid=" + addonId);
                            MetadataController.deleteContentRecords(core, "Add-on Content Trigger Rules", "addonid=" + addonId);
                            //
                            cs.set("collectionid", CollectionID);
                            cs.set(AddonGuidFieldName, addonGuid);
                            cs.set("name", addonName);
                            cs.set("navTypeId", navTypeId);
                            var ArgumentList = new StringBuilder();
                            var StyleSheet   = new StringBuilder();
                            if (AddonNode.ChildNodes.Count > 0)
                            {
                                foreach (XmlNode Addonfield in AddonNode.ChildNodes)
                                {
                                    if (!(Addonfield is XmlComment))
                                    {
                                        XmlNode PageInterface = Addonfield;
                                        string  fieldName     = null;
                                        string  FieldValue    = "";
                                        switch (GenericController.toLCase(Addonfield.Name))
                                        {
                                        case "activexdll": {
                                            //
                                            // This is handled in BuildLocalCollectionFolder
                                            //
                                            break;
                                        }

                                        case "editors": {
                                            //
                                            // list of editors
                                            //
                                            foreach (XmlNode TriggerNode in Addonfield.ChildNodes)
                                            {
                                                //
                                                int    fieldTypeId = 0;
                                                string fieldType   = null;
                                                switch (GenericController.toLCase(TriggerNode.Name))
                                                {
                                                case "type": {
                                                    fieldType   = TriggerNode.InnerText;
                                                    fieldTypeId = MetadataController.getRecordIdByUniqueName(core, "Content Field Types", fieldType);
                                                    if (fieldTypeId > 0)
                                                    {
                                                        using (var CS2 = new CsModel(core)) {
                                                            Criteria = "(addonid=" + addonId + ")and(contentfieldTypeID=" + fieldTypeId + ")";
                                                            CS2.open("Add-on Content Field Type Rules", Criteria);
                                                            if (!CS2.ok())
                                                            {
                                                                CS2.insert("Add-on Content Field Type Rules");
                                                            }
                                                            if (CS2.ok())
                                                            {
                                                                CS2.set("addonid", addonId);
                                                                CS2.set("contentfieldTypeID", fieldTypeId);
                                                            }
                                                        }
                                                    }
                                                    break;
                                                }

                                                default: {
                                                    // do nothing
                                                    break;
                                                }
                                                }
                                            }
                                            break;
                                        }

                                        case "processtriggers": {
                                            //
                                            // list of events that trigger a process run for this addon
                                            //
                                            foreach (XmlNode TriggerNode in Addonfield.ChildNodes)
                                            {
                                                switch (GenericController.toLCase(TriggerNode.Name))
                                                {
                                                case "contentchange": {
                                                    int    TriggerContentId  = 0;
                                                    string ContentNameorGuid = TriggerNode.InnerText;
                                                    if (string.IsNullOrEmpty(ContentNameorGuid))
                                                    {
                                                        ContentNameorGuid = XmlController.getXMLAttribute(core, ref IsFound, TriggerNode, "guid", "");
                                                        if (string.IsNullOrEmpty(ContentNameorGuid))
                                                        {
                                                            ContentNameorGuid = XmlController.getXMLAttribute(core, ref IsFound, TriggerNode, "name", "");
                                                        }
                                                    }
                                                    using (var CS2 = new CsModel(core)) {
                                                        Criteria = "(ccguid=" + DbController.encodeSQLText(ContentNameorGuid) + ")";
                                                        CS2.open("Content", Criteria);
                                                        if (!CS2.ok())
                                                        {
                                                            Criteria = "(ccguid is null)and(name=" + DbController.encodeSQLText(ContentNameorGuid) + ")";
                                                            CS2.open("content", Criteria);
                                                        }
                                                        if (CS2.ok())
                                                        {
                                                            TriggerContentId = CS2.getInteger("ID");
                                                        }
                                                    }
                                                    if (TriggerContentId != 0)
                                                    {
                                                        using (var CS2 = new CsModel(core)) {
                                                            Criteria = "(addonid=" + addonId + ")and(contentid=" + TriggerContentId + ")";
                                                            CS2.open("Add-on Content Trigger Rules", Criteria);
                                                            if (!CS2.ok())
                                                            {
                                                                CS2.insert("Add-on Content Trigger Rules");
                                                                if (CS2.ok())
                                                                {
                                                                    CS2.set("addonid", addonId);
                                                                    CS2.set("contentid", TriggerContentId);
                                                                }
                                                            }
                                                            CS2.close();
                                                        }
                                                    }
                                                    break;
                                                }

                                                default: {
                                                    // do nothing
                                                    break;
                                                }
                                                }
                                            }
                                            break;
                                        }

                                        case "scripting": {
                                            //
                                            // include add-ons - NOTE - import collections must be run before interfaces
                                            // when importing a collectin that will be used for an include
                                            int    scriptinglanguageid = (int)AddonController.ScriptLanguages.VBScript;
                                            string ScriptingLanguage   = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "language", "").ToLowerInvariant();
                                            if (ScriptingLanguage.Equals("javascript") || ScriptingLanguage.Equals("jscript"))
                                            {
                                                scriptinglanguageid = (int)AddonController.ScriptLanguages.Javascript;
                                            }
                                            cs.set("scriptinglanguageid", scriptinglanguageid);
                                            string ScriptingEntryPoint = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "entrypoint", "");
                                            cs.set("ScriptingEntryPoint", ScriptingEntryPoint);
                                            int ScriptingTimeout = GenericController.encodeInteger(XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "timeout", "5000"));
                                            cs.set("ScriptingTimeout", ScriptingTimeout);
                                            string ScriptingCode = "";
                                            foreach (XmlNode ScriptingNode in Addonfield.ChildNodes)
                                            {
                                                switch (GenericController.toLCase(ScriptingNode.Name))
                                                {
                                                case "code": {
                                                    ScriptingCode += ScriptingNode.InnerText;
                                                    break;
                                                }

                                                default: {
                                                    // do nothing
                                                    break;
                                                }
                                                }
                                            }
                                            cs.set("ScriptingCode", ScriptingCode);
                                            break;
                                        }

                                        case "activexprogramid": {
                                            //
                                            // save program id
                                            //
                                            FieldValue = Addonfield.InnerText;
                                            cs.set("ObjectProgramID", FieldValue);
                                            break;
                                        }

                                        case "navigator": {
                                            //
                                            // create a navigator entry with a parent set to this
                                            //
                                            cs.save();
                                            string menuNameSpace = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "NameSpace", "");
                                            if (!string.IsNullOrEmpty(menuNameSpace))
                                            {
                                                string NavIconTypeString = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "type", "");
                                                if (string.IsNullOrEmpty(NavIconTypeString))
                                                {
                                                    NavIconTypeString = "Addon";
                                                }
                                                BuildController.verifyNavigatorEntry(core, new MetadataMiniCollectionModel.MiniCollectionMenuModel {
                                                        menuNameSpace = menuNameSpace,
                                                        name          = addonName,
                                                        adminOnly     = false,
                                                        developerOnly = false,
                                                        newWindow     = false,
                                                        active        = true,
                                                        addonName     = addonName,
                                                        navIconType   = NavIconTypeString,
                                                        navIconTitle  = addonName
                                                    }, CollectionID);
                                            }
                                            break;
                                        }

                                        case "argument":
                                        case "argumentlist": {
                                            //
                                            // multiple argumentlist elements are concatinated with crlf
                                            ArgumentList.Append(Addonfield.InnerText.Trim(' ') + Environment.NewLine);
                                            break;
                                        }

                                        case "style": {
                                            //
                                            // import exclusive style
                                            //
                                            string NodeName = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "name", "");
                                            string NewValue = encodeText(Addonfield.InnerText).Trim(' ');
                                            if (NewValue.left(1) != "{")
                                            {
                                                NewValue = "{" + NewValue;
                                            }
                                            if (NewValue.Substring(NewValue.Length - 1) != "}")
                                            {
                                                NewValue += "}";
                                            }
                                            StyleSheet.Append(NodeName + " " + NewValue + Environment.NewLine);
                                            break;
                                        }

                                        case "stylesheet":
                                        case "styles": {
                                            //
                                            // import exclusive stylesheet if more then whitespace
                                            //
                                            string test = Addonfield.InnerText;
                                            test = strReplace(test, " ", "");
                                            test = strReplace(test, "\r", "");
                                            test = strReplace(test, "\n", "");
                                            test = strReplace(test, "\t", "");
                                            if (!string.IsNullOrEmpty(test))
                                            {
                                                StyleSheet.Append(Addonfield.InnerText + Environment.NewLine);
                                            }
                                            break;
                                        }

                                        case "template":
                                        case "content":
                                        case "admin": {
                                            //
                                            // these add-ons will be "non-developer only" in navigation
                                            //
                                            fieldName  = Addonfield.Name;
                                            FieldValue = Addonfield.InnerText;
                                            if (!cs.isFieldSupported(fieldName))
                                            {
                                                //
                                                // Bad field name - need to report it somehow
                                                //
                                            }
                                            else
                                            {
                                                cs.set(fieldName, FieldValue);
                                                if (GenericController.encodeBoolean(Addonfield.InnerText))
                                                {
                                                    //
                                                    // if template, admin or content - let non-developers have navigator entry
                                                    //
                                                }
                                            }
                                            break;
                                        }

                                        case "icon": {
                                            //
                                            // icon
                                            //
                                            FieldValue = XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "link", "");
                                            if (!string.IsNullOrEmpty(FieldValue))
                                            {
                                                //
                                                // Icons can be either in the root of the website or in content files
                                                //
                                                FieldValue = GenericController.strReplace(FieldValue, "\\", "/");         // make it a link, not a file
                                                if (GenericController.strInstr(1, FieldValue, "://") != 0)
                                                {
                                                    //
                                                    // the link is an absolute URL, leave it link this
                                                    //
                                                }
                                                else
                                                {
                                                    if (FieldValue.left(1) != "/")
                                                    {
                                                        //
                                                        // make sure it starts with a slash to be consistance
                                                        //
                                                        FieldValue = "/" + FieldValue;
                                                    }
                                                    if (FieldValue.left(17) == "/contensivefiles/")
                                                    {
                                                        //
                                                        // in content files, start link without the slash
                                                        //
                                                        FieldValue = FieldValue.Substring(17);
                                                    }
                                                }
                                                cs.set("IconFilename", FieldValue);
                                                {
                                                    cs.set("IconWidth", GenericController.encodeInteger(XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "width", "0")));
                                                    cs.set("IconHeight", GenericController.encodeInteger(XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "height", "0")));
                                                    cs.set("IconSprites", GenericController.encodeInteger(XmlController.getXMLAttribute(core, ref IsFound, Addonfield, "sprites", "0")));
                                                }
                                            }
                                            break;
                                        }

                                        case "includeaddon":
                                        case "includeadd-on":
                                        case "include addon":
                                        case "include add-on": {
                                            //
                                            // processed in phase2 of this routine, after all the add-ons are installed
                                            //
                                            break;
                                        }

                                        case "form": {
                                            //
                                            // The value of this node is the xml instructions to create a form. Take then
                                            //   entire node, children and all, and save them in the formxml field.
                                            //   this replaces the settings add-on type, and soo to be report add-on types as well.
                                            //   this removes the ccsettingpages and settingcollectionrules, etc.
                                            //
                                            {
                                                cs.set("formxml", Addonfield.InnerXml);
                                            }
                                            break;
                                        }

                                        case "javascript":
                                        case "javascriptinhead": {
                                            //
                                            // these all translate to JSFilename
                                            //
                                            fieldName = "jsfilename";
                                            cs.set(fieldName, Addonfield.InnerText);

                                            break;
                                        }

                                        case "iniframe": {
                                            //
                                            // typo - field is inframe
                                            //
                                            fieldName = "inframe";
                                            cs.set(fieldName, Addonfield.InnerText);
                                            break;
                                        }

                                        case "diagnostic": {
                                            bool fieldValue = encodeBoolean(Addonfield.InnerText);
                                            cs.set("diagnostic", fieldValue);
                                            collectionIncludesDiagnosticAddons = collectionIncludesDiagnosticAddons || fieldValue;
                                            break;
                                        }

                                        case "category": {
                                            if (!string.IsNullOrWhiteSpace(Addonfield.InnerText))
                                            {
                                                AddonCategoryModel category = DbBaseModel.createByUniqueName <AddonCategoryModel>(core.cpParent, Addonfield.InnerText);
                                                if (category == null)
                                                {
                                                    category      = DbBaseModel.addDefault <AddonCategoryModel>(core.cpParent);
                                                    category.name = Addonfield.InnerText;
                                                    category.save(core.cpParent);
                                                }
                                                cs.set("addonCategoryId", category.id);
                                            }
                                            break;
                                        }

                                        case "instancesettingprimarycontentid": {
                                            int lookupContentId = 0;
                                            if (!string.IsNullOrWhiteSpace(Addonfield.InnerText))
                                            {
                                                ContentModel lookupContent = DbBaseModel.createByUniqueName <ContentModel>(core.cpParent, Addonfield.InnerText);
                                                if (lookupContent != null)
                                                {
                                                    lookupContentId = lookupContent.id;
                                                }
                                            }
                                            cs.set("instancesettingprimarycontentid", lookupContentId);
                                            break;
                                        }

                                        default: {
                                            //
                                            // All the other fields should match the Db fields
                                            //
                                            fieldName  = Addonfield.Name;
                                            FieldValue = Addonfield.InnerText;
                                            if (!cs.isFieldSupported(fieldName))
                                            {
                                                //
                                                // Bad field name - need to report it somehow
                                                //
                                                LogController.logError(core, new ApplicationException("bad field found [" + fieldName + "], in addon node [" + addonName + "], of collection [" + MetadataController.getRecordName(core, "add-on collections", CollectionID) + "]"));
                                            }
                                            else
                                            {
                                                cs.set(fieldName, FieldValue);
                                            }
                                            break;
                                        }
                                        }
                                    }
                                }
                            }
                            cs.set("ArgumentList", ArgumentList.ToString());
                            cs.set("StylesFilename", StyleSheet.ToString());
                        }
                        cs.close();
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
        }
        //
        //======================================================================================================
        //
        public static void installNode(CoreController core, XmlNode templateNode, int collectionId, ref bool return_UpgradeOK, ref string return_ErrorMessage, ref bool collectionIncludesDiagnosticAddons)
        {
            return_ErrorMessage = "";
            return_UpgradeOK    = true;
            try {
                string Basename = toLCase(templateNode.Name);
                if (Basename == "template")
                {
                    bool   IsFound      = false;
                    string templateName = XmlController.getXMLAttribute(core, ref IsFound, templateNode, "name", "No Name");
                    if (string.IsNullOrEmpty(templateName))
                    {
                        templateName = "No Name";
                    }
                    string recordGuid = XmlController.getXMLAttribute(core, ref IsFound, templateNode, "guid", templateName);
                    if (string.IsNullOrEmpty(recordGuid))
                    {
                        recordGuid = templateName;
                    }
                    var template = DbBaseModel.create <PageTemplateModel>(core.cpParent, recordGuid);
                    if (template == null)
                    {
                        template = DbBaseModel.createByUniqueName <PageTemplateModel>(core.cpParent, templateName);
                    }
                    if (template == null)
                    {
                        template = DbBaseModel.addDefault <PageTemplateModel>(core.cpParent);
                    }
                    foreach (XmlNode childNode in templateNode.ChildNodes)
                    {
                        switch (childNode.Name.ToLowerInvariant())
                        {
                        case "includeaddon": {
                            string addonGuid = XmlController.getXMLAttribute(core, ref IsFound, childNode, "guid", "");
                            string addonName = XmlController.getXMLAttribute(core, ref IsFound, childNode, "name", "No Name");
                            if (!string.IsNullOrEmpty(addonGuid))
                            {
                                var addon = DbBaseModel.create <AddonModel>(core.cpParent, addonGuid);
                                if (addon == null)
                                {
                                    return_ErrorMessage += "Addon dependency [" + addonName + "] for template [" + templateName + "] could not be found by its guid [" + addonGuid + "]";
                                }
                                var ruleList = DbBaseModel.createList <AddonTemplateRuleModel>(core.cpParent, "(addonId=" + addon.id + ")and(addonId=" + template.id + ")");
                                if (ruleList.Count.Equals(0))
                                {
                                    var rule = DbBaseModel.addDefault <AddonTemplateRuleModel>(core.cpParent);
                                    rule.addonId    = addon.id;
                                    rule.templateId = template.id;
                                    rule.save(core.cpParent);
                                }
                            }
                            break;
                        }

                        case "bodyhtml": {
                            template.bodyHTML = childNode.InnerText;
                            break;
                        }
                        }
                    }
                    template.ccguid = recordGuid;
                    template.name   = templateName;
                    //record.bodyHTML = templateNode.InnerText;
                    template.collectionId = collectionId;
                    template.isSecure     = XmlController.getXMLAttributeBoolean(core, ref IsFound, templateNode, "issecure", false);
                    template.save(core.cpParent);
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
        }
 //
 //====================================================================================================
 /// <summary>
 /// when breaking changes are required for data, update them here
 /// </summary>
 /// <param name="core"></param>
 /// <param name="DataBuildVersion"></param>
 public static void migrateData(CoreController core, string DataBuildVersion, string logPrefix)
 {
     try {
         CPClass cp = core.cpParent;
         //
         // -- Roll the style sheet cache if it is setup
         core.siteProperties.setProperty("StylesheetSerialNumber", (-1).ToString());
         //
         // -- verify ID is primary key on all tables with an id
         foreach (TableModel table in DbBaseModel.createList <TableModel>(cp))
         {
             if (!string.IsNullOrWhiteSpace(table.name))
             {
                 bool tableHasId = false;
                 {
                     //
                     // -- verify table as an id field
                     string    sql = "SELECT name FROM sys.columns WHERE Name = N'ID' AND Object_ID = Object_ID(N'ccmembers')";
                     DataTable dt  = cp.Db.ExecuteQuery(sql);
                     if (dt != null)
                     {
                         tableHasId = !dt.Rows.Equals(0);
                     }
                 }
                 if (tableHasId)
                 {
                     //
                     // -- table has id field, make sure it is primary key
                     string sql = ""
                                  + " select Col.Column_Name"
                                  + " from INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col"
                                  + " where (Col.Constraint_Name = Tab.Constraint_Name) AND (Col.Table_Name = Tab.Table_Name) AND (Constraint_Type = 'PRIMARY KEY') AND (Col.Table_Name = '" + table.name + "')";
                     bool idPrimaryKeyFound = false;
                     foreach (DataRow dr in core.db.executeQuery(sql).Rows)
                     {
                         if (GenericController.encodeText(dr["Column_Name"]).ToLower().Equals("id"))
                         {
                             idPrimaryKeyFound = true;
                             break;
                         }
                     }
                     if (!idPrimaryKeyFound)
                     {
                         try {
                             core.db.executeNonQuery("alter table " + table.name + " add primary key (ID)");
                         } catch (Exception ex) {
                             LogController.logError(core, ex, "Content Table [" + table.name + "] does not include column ID. Exception happened while adding column and setting it primarykey.");
                         }
                     }
                 }
             }
         }
         //
         // -- continue only if a previous build exists
         if (!string.IsNullOrEmpty(DataBuildVersion))
         {
             //
             // -- 4.1 to 5 conversions
             if (GenericController.versionIsOlder(DataBuildVersion, "4.1"))
             {
                 //
                 // -- create Data Migration Assets collection
                 var migrationCollection = DbBaseModel.createByUniqueName <AddonCollectionModel>(cp, "Data Migration Assets");
                 if (migrationCollection == null)
                 {
                     migrationCollection      = DbBaseModel.addDefault <AddonCollectionModel>(cp);
                     migrationCollection.name = "Data Migration Assets";
                 }
                 //
                 // -- remove all addon content fieldtype rules
                 Contensive.Models.Db.DbBaseModel.deleteRows <Contensive.Models.Db.AddonContentFieldTypeRulesModel>(cp, "(1=1)");
                 //
                 // -- delete /admin www subfolder
                 core.wwwFiles.deleteFolder("admin");
                 //
                 // -- delete .asp and .php files
                 foreach (BaseClasses.CPFileSystemBaseClass.FileDetail file in core.wwwFiles.getFileList(""))
                 {
                     if (file == null)
                     {
                         continue;
                     }
                     if (string.IsNullOrWhiteSpace(file.Name))
                     {
                         continue;
                     }
                     if (file.Name.Length < 4)
                     {
                         continue;
                     }
                     string extension = System.IO.Path.GetExtension(file.Name).ToLower(CultureInfo.InvariantCulture);
                     if ((extension == ".php") || (extension == ".asp"))
                     {
                         core.wwwFiles.deleteFile(file.Name);
                     }
                 }
                 //
                 // -- create www /cclib folder and copy in legacy resources
                 core.programFiles.copyFile("cclib.zip", "cclib.zip", core.wwwFiles);
                 core.wwwFiles.unzipFile("cclib.zip");
                 //
                 // -- remove all the old menu entries and leave the navigation entries
                 var navContent = DbBaseModel.createByUniqueName <ContentModel>(cp, Contensive.Models.Db.NavigatorEntryModel.tableMetadata.contentName);
                 if (navContent != null)
                 {
                     core.db.executeNonQuery("delete from ccMenuEntries where ((contentcontrolid<>0)and(contentcontrolid<>" + navContent.id + ")and(contentcontrolid is not null))");
                 }
                 //
                 // -- reinstall newest font-awesome collection
                 string returnErrorMessage       = "";
                 var    context                  = new Stack <string>();
                 var    nonCritialErrorList      = new List <string>();
                 var    collectionsInstalledList = new List <string>();
                 CollectionLibraryController.installCollectionFromLibrary(core, false, context, Constants.fontAwesomeCollectionGuid, ref returnErrorMessage, false, true, ref nonCritialErrorList, logPrefix, ref collectionsInstalledList);
                 //
                 // -- reinstall newest redactor collection
                 returnErrorMessage       = "";
                 context                  = new Stack <string>();
                 nonCritialErrorList      = new List <string>();
                 collectionsInstalledList = new List <string>();
                 CollectionLibraryController.installCollectionFromLibrary(core, false, context, Constants.redactorCollectionGuid, ref returnErrorMessage, false, true, ref nonCritialErrorList, logPrefix, ref collectionsInstalledList);
                 //
                 // -- addons with active-x -- remove programid and add script code that logs error
                 string newCode = ""
                                  + "function m"
                                  + " ' + CHAR(13)+CHAR(10) + ' \ncp.Site.ErrorReport(\"deprecated active-X add-on executed [#\" & cp.addon.id & \", \" & cp.addon.name & \"]\")"
                                  + " ' + CHAR(13)+CHAR(10) + ' \nend function"
                                  + "";
                 string sql = "update ccaggregatefunctions set help='Legacy activeX: ' + objectprogramId, objectprogramId=null, ScriptingCode='" + newCode + "' where (ObjectProgramID is not null)";
                 LogController.logInfo(core, "MigrateData, removing activex addons, adding exception logging, sql [" + sql + "]");
                 core.db.executeNonQuery(sql);
                 //
                 // -- create page menus from section menus
                 using (var cs = new CsModel(core)) {
                     sql = "select m.name as menuName, m.id as menuId, p.name as pageName, p.id as pageId, s.name as sectionName, m.*"
                           + " from ccDynamicMenus m"
                           + " left join ccDynamicMenuSectionRules r on r.DynamicMenuId = m.id"
                           + " left join ccSections s on s.id = r.SectionID"
                           + " left join ccPageContent p on p.id = s.RootPageID"
                           + " where (p.id is not null)and(s.active>0)"
                           + " order by m.id, s.sortorder,s.id";
                     if (cs.openSql(sql))
                     {
                         int sortOrder = 0;
                         do
                         {
                             string menuName = cs.getText("menuName");
                             if (!string.IsNullOrWhiteSpace(menuName))
                             {
                                 var menu = DbBaseModel.createByUniqueName <MenuModel>(cp, menuName);
                                 if (menu == null)
                                 {
                                     menu      = DbBaseModel.addEmpty <MenuModel>(cp);
                                     menu.name = menuName;
                                     try {
                                         menu.classItemActive = cs.getText("classItemActive");
                                         menu.classItemFirst  = cs.getText("classItemFirst");
                                         menu.classItemHover  = cs.getText("classItemHover");
                                         menu.classItemLast   = cs.getText("classItemLast");
                                         menu.classTierAnchor = cs.getText("classTierItem");
                                         menu.classTierItem   = cs.getText("classTierItem");
                                         menu.classTierList   = cs.getText("classTierList");
                                         menu.classTopAnchor  = cs.getText("classTopItem");
                                         menu.classTopItem    = cs.getText("classTopItem");
                                         menu.classTopList    = cs.getText("classTopList");
                                         menu.classTopWrapper = cs.getText("classTopWrapper");
                                     } catch (Exception ex) {
                                         LogController.logError(core, ex, "migrateData error populating menu from dynamic menu.");
                                     }
                                     menu.save(cp);
                                 }
                                 //
                                 // -- set the root page's menuHeadline to the section name
                                 var page = DbBaseModel.create <PageContentModel>(cp, cs.getInteger("pageId"));
                                 if (page != null)
                                 {
                                     page.menuHeadline = cs.getText("sectionName");
                                     page.save(cp);
                                     //
                                     // -- create a menu-page rule to attach this page to the menu in the current order
                                     var menuPageRule = DbBaseModel.addEmpty <MenuPageRuleModel>(cp);
                                     if (menuPageRule != null)
                                     {
                                         menuPageRule.name      = "Created from v4.1 menu sections " + core.dateTimeNowMockable.ToString();
                                         menuPageRule.pageId    = page.id;
                                         menuPageRule.menuId    = menu.id;
                                         menuPageRule.active    = true;
                                         menuPageRule.sortOrder = sortOrder.ToString().PadLeft(4, '0');
                                         menuPageRule.save(cp);
                                         sortOrder += 10;
                                     }
                                 }
                             }
                             cs.goNext();
                         } while (cs.ok());
                     }
                 }
                 //
                 // -- create a theme addon for each template for styles and meta content
                 using (var csTemplate = cp.CSNew()) {
                     if (csTemplate.Open("page templates"))
                     {
                         do
                         {
                             int    templateId           = csTemplate.GetInteger("id");
                             string templateStylePrepend = "";
                             string templateStyles       = csTemplate.GetText("StylesFilename");
                             //
                             // -- add shared styles to the template stylesheet
                             using (var csStyleRule = cp.CSNew()) {
                                 if (csStyleRule.Open("shared styles template rules", "(TemplateID=" + templateId + ")"))
                                 {
                                     do
                                     {
                                         int sharedStyleId = csStyleRule.GetInteger("styleid");
                                         using (var csStyle = cp.CSNew()) {
                                             if (csStyleRule.Open("shared styles", "(id=" + sharedStyleId + ")"))
                                             {
                                                 //
                                                 // -- prepend lines beginning with @ t
                                                 string styles = csStyleRule.GetText("StyleFilename");
                                                 if (!string.IsNullOrWhiteSpace(styles))
                                                 {
                                                     //
                                                     // -- trim off leading spaces, newlines, comments
                                                     styles = styles.Trim();
                                                     while (!string.IsNullOrWhiteSpace(styles) && styles.Substring(0, 1).Equals("@"))
                                                     {
                                                         if (styles.IndexOf(Environment.NewLine) >= 0)
                                                         {
                                                             templateStylePrepend += styles.Substring(0, styles.IndexOf(Environment.NewLine));
                                                             styles = styles.Substring(styles.IndexOf(Environment.NewLine) + 1).Trim();
                                                         }
                                                         else
                                                         {
                                                             templateStylePrepend += styles;
                                                             styles = string.Empty;
                                                         }
                                                     }
                                                     ;
                                                     templateStyles += Environment.NewLine + styles;
                                                 }
                                             }
                                         }
                                         csStyleRule.GoNext();
                                     } while (csStyleRule.OK());
                                 }
                             }
                             //
                             // -- create an addon
                             var themeAddon = DbBaseModel.addDefault <AddonModel>(cp);
                             themeAddon.name                   = "Theme assets for template " + csTemplate.GetText("name");
                             themeAddon.otherHeadTags          = csTemplate.GetText("otherheadtags");
                             themeAddon.javaScriptBodyEnd      = csTemplate.GetText("jsendbody");
                             themeAddon.stylesFilename.content = templateStylePrepend + Environment.NewLine + templateStyles;
                             themeAddon.collectionId           = migrationCollection.id;
                             themeAddon.save(cp);
                             //
                             // -- create an addon template rule to set dependency
                             var rule = DbBaseModel.addEmpty <AddonTemplateRuleModel>(cp);
                             rule.addonId    = themeAddon.id;
                             rule.templateId = templateId;
                             rule.save(cp);
                             //
                             csTemplate.GoNext();
                         } while (csTemplate.OK());
                     }
                 }
                 //
                 // -- reset the html minify so it is easier to resolve other issues
                 core.siteProperties.setProperty("ALLOW HTML MINIFY", false);
                 //
                 // -- remove contentcategoryid from all edit page
                 cp.Db.ExecuteNonQuery("update ccfields set Authorable=0 where name='contentcategoryid'");
                 cp.Db.ExecuteNonQuery("update ccfields set Authorable=0 where name='editsourceid'");
                 cp.Db.ExecuteNonQuery("update ccfields set Authorable=0 where name='editarchive'");
                 cp.Db.ExecuteNonQuery("update ccfields set Authorable=0 where name='editblank'");
                 //
                 // -- remove legacy workflow fields
                 UpgradeController.dropLegacyWorkflowField(core, "editsourceid");
                 cp.Db.ExecuteNonQuery("delete from ccfields where name='editsourceid'");
                 //
                 UpgradeController.dropLegacyWorkflowField(core, "editblank");
                 cp.Db.ExecuteNonQuery("delete from ccfields where name='editblank'");
                 //
                 UpgradeController.dropLegacyWorkflowField(core, "editarchive");
                 cp.Db.ExecuteNonQuery("delete from ccfields where name='editarchive'");
                 //
                 UpgradeController.dropLegacyWorkflowField(core, "contentcategoryid");
                 cp.Db.ExecuteNonQuery("delete from ccfields where name='contentcategoryid'");
                 //
                 //
                 // -- end of 4.1 to 5 conversion
             }
             //
             // -- 5.19.1223 conversion -- render AddonList no copyFilename
             if (GenericController.versionIsOlder(DataBuildVersion, "5.19.1223"))
             {
                 //
                 // -- verify design block installation
                 string returnUserError = "";
                 if (!cp.Db.IsTable("dbtext"))
                 {
                     if (!cp.Addon.InstallCollectionFromLibrary(Constants.designBlockCollectionGuid, ref returnUserError))
                     {
                         throw new Exception("Error installing Design Blocks, required for data upgrade. " + returnUserError);
                     }
                 }
                 //
                 // -- add a text block and childPageList to every page without an addonlist
                 foreach (var page in DbBaseModel.createList <PageContentModel>(cp, "(addonList is null)"))
                 {
                     convertPageContentToAddonList(core, page);
                 }
                 core.siteProperties.setProperty("PageController Render Legacy Copy", false);
             }
             //
             // -- 5.2005.9.4 conversion -- collections incorrectly marked not-updateable - mark all except themes (templates)
             if (GenericController.versionIsOlder(DataBuildVersion, "5.2005.9.4"))
             {
                 //
                 // --
                 cp.Db.ExecuteNonQuery("update ccaddoncollections set updatable=1 where name not like '%theme%'");
             }
             //
             // -- 5.2005.19.1 conversion -- rename site property EmailUrlRootRelativePrefix to LocalFileModeProtocolDomain
             if (GenericController.versionIsOlder(DataBuildVersion, "5.2005.19.1"))
             {
                 //
                 // --
                 if (string.IsNullOrWhiteSpace(cp.Site.GetText("webAddressProtocolDomain")))
                 {
                     cp.Site.SetProperty("webAddressProtocolDomain", cp.Site.GetText("EmailUrlRootRelativePrefix"));
                 }
             }
             //
             // -- delete legacy corehelp collection. Created with fields that have only field name, legacy install layed collections over the application collection
             //    new install loads fields directly from collection, which coreHelp then marks all fields inactive.
             core.db.delete("{6e905db1-d3f0-40af-aac4-4bd78e680fae}", "ccaddoncollections");
         }
         // -- Reload
         core.cache.invalidateAll();
         core.clearMetaData();
     } catch (Exception ex) {
         LogController.logError(core, ex);
         throw;
     }
 }
        //
        //====================================================================================================
        /// <summary>
        /// pageManager addon interface. decode: "sortlist=childPageList_{parentId}_{listName},page{idOfChild},page{idOfChild},etc"
        /// </summary>
        /// <param name="cp"></param>
        /// <returns></returns>
        public override object Execute(Contensive.BaseClasses.CPBaseClass cp)
        {
            string returnHtml = "";

            try {
                CoreController core          = ((CPClass)cp).core;
                string         pageCommaList = cp.Doc.GetText("sortlist");
                List <string>  pageList      = new List <string>(pageCommaList.Split(','));
                if (pageList.Count > 1)
                {
                    string[] ParentPageValues = pageList[0].Split('_');
                    if (ParentPageValues.Count() < 3)
                    {
                        //
                        // -- parent page is not valid
                        cp.Site.ErrorReport(new ArgumentException("pageResort requires first value to identify the parent page"));
                    }
                    else
                    {
                        int parentPageId = encodeInteger(ParentPageValues[1]);
                        if (parentPageId == 0)
                        {
                            //
                            // -- parent page is not valid
                            cp.Site.ErrorReport(new ArgumentException("pageResort requires a parent page id"));
                        }
                        else
                        {
                            //
                            // -- create childPageIdList
                            List <int> childPageIdList = new List <int>();
                            foreach (string PageIDText in pageList)
                            {
                                int pageId = encodeInteger(PageIDText.Replace("page", ""));
                                if (pageId > 0)
                                {
                                    childPageIdList.Add(pageId);
                                }
                            }
                            //
                            PageContentModel parentPage = DbBaseModel.create <PageContentModel>(core.cpParent, parentPageId);
                            if (parentPage == null)
                            {
                                //
                                // -- parent page is not valid
                                cp.Site.ErrorReport(new ArgumentException("pageResort requires a parent page id"));
                            }
                            else
                            {
                                //
                                // -- verify page set to required sort method Id
                                SortMethodModel sortMethod = DbBaseModel.createByUniqueName <SortMethodModel>(core.cpParent, "By Alpha Sort Order Field");
                                if (sortMethod == null)
                                {
                                    sortMethod = DbBaseModel.createByUniqueName <SortMethodModel>(core.cpParent, "Alpha Sort Order Field");
                                }
                                if (sortMethod == null)
                                {
                                    //
                                    // -- create the required sortMethod
                                    sortMethod               = DbBaseModel.addDefault <SortMethodModel>(core.cpParent, Processor.Models.Domain.ContentMetadataModel.getDefaultValueDict(core, SortMethodModel.tableMetadata.contentName));
                                    sortMethod.name          = "By Alpha Sort Order Field";
                                    sortMethod.orderByClause = "sortOrder";
                                    sortMethod.save(core.cpParent);
                                }
                                if (parentPage.childListSortMethodId != sortMethod.id)
                                {
                                    //
                                    // -- update page if not set correctly
                                    parentPage.childListSortMethodId = sortMethod.id;
                                    parentPage.save(core.cpParent);
                                }
                                int pagePtr = 0;
                                foreach (var childPageId in childPageIdList)
                                {
                                    if (childPageId == 0)
                                    {
                                        //
                                        // -- invalid child page
                                        cp.Site.ErrorReport(new GenericException("child page id is invalid from remote request [" + pageCommaList + "]"));
                                    }
                                    else
                                    {
                                        string           SortOrder = (100000 + (pagePtr * 10)).ToString();
                                        PageContentModel childPage = DbBaseModel.create <PageContentModel>(core.cpParent, childPageId);
                                        if (childPage.sortOrder != SortOrder)
                                        {
                                            childPage.sortOrder = SortOrder;
                                            childPage.save(core.cpParent);
                                        }
                                    }
                                    pagePtr += 1;
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                cp.Site.ErrorReport(ex);
            }
            return(returnHtml);
        }