//
 //======================================================================================================
 //
 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;
     }
 }
        //
        //====================================================================================================
        //   Get an LocalElements attribute value
        //
        public string elementAttributeValue(int ElementPointer, int AttributePointer)
        {
            string tempElementAttributeValue = null;

            try {
                //
                tempElementAttributeValue = "";
                LoadElement(ElementPointer);
                if (ElementPointer < elementCount)
                {
                    if (AttributePointer < LocalElements[ElementPointer].AttributeCount)
                    {
                        tempElementAttributeValue = LocalElements[ElementPointer].Attributes[AttributePointer].Value;
                    }
                }
                //
                return(tempElementAttributeValue);
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(tempElementAttributeValue);
        }
 //
 //====================================================================================================
 // <summary>
 // invalidates a tag
 // </summary>
 // <param name="tag"></param>
 // <remarks></remarks>
 public void invalidate(string key, int recursionLimit = 5)
 {
     try {
         Controllers.LogController.logTrace(core, "invalidate, key [" + key + "], recursionLimit [" + recursionLimit + "]");
         if ((recursionLimit > 0) && (!string.IsNullOrWhiteSpace(key.Trim())))
         {
             key = Regex.Replace(key, "0x[a-fA-F\\d]{2}", "_").ToLowerInvariant().Replace(" ", "_");
             // if key is a ptr, we need to invalidate the real key
             CacheDocumentClass cacheDocument = getCacheDocument(key);
             if (cacheDocument == null)
             {
                 // no cache for this key, if this is a dependency for another key, save invalidated
                 storeCacheDocument(key, new CacheDocumentClass(core.dateTimeNowMockable)
                 {
                     saveDate = core.dateTimeNowMockable
                 });
             }
             else
             {
                 if (!string.IsNullOrWhiteSpace(cacheDocument.keyPtr))
                 {
                     // this key is an alias, invalidate it's parent key
                     invalidate(cacheDocument.keyPtr, --recursionLimit);
                 }
                 else
                 {
                     // key is a valid cache, invalidate it
                     storeCacheDocument(key, new CacheDocumentClass(core.dateTimeNowMockable)
                     {
                         saveDate = core.dateTimeNowMockable
                     });
                 }
             }
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
         throw;
     }
 }
 //
 /// <summary>
 /// coreClass constructor common tasks.
 /// </summary>
 /// <param name="cp"></param>
 /// <remarks></remarks>
 private void constructorInitialize(bool allowVisit)
 {
     try {
         //
         doc.docGuid                     = GenericController.getGUID();
         doc.allowDebugLog               = true;
         doc.profileStartTime            = dateTimeNowMockable;
         doc.visitPropertyAllowDebugging = true;
         //
         // -- attempt auth load
         if (appConfig == null)
         {
             //
             // -- server mode, there is no application
             session = SessionController.create(this, false);
         }
         else if (appConfig.appStatus != AppConfigModel.AppStatusEnum.ok)
         {
             //
             // -- application is not ready, might be error, or in maintainence mode
             session = SessionController.create(this, false);
         }
         else
         {
             session = SessionController.create(this, allowVisit && siteProperties.allowVisitTracking);
             //
             // -- debug defaults on, so if not on, set it off and clear what was collected
             doc.visitPropertyAllowDebugging = visitProperty.getBoolean("AllowDebugging");
             if (!doc.visitPropertyAllowDebugging)
             {
                 doc.testPointMessage = "";
             }
         }
     } catch (Exception ex) {
         LogController.logLocalOnly("CoreController constructorInitialize, exception [" + ex.ToString() + "]", BaseClasses.CPLogBaseClass.LogLevel.Fatal);
         throw;
     }
 }
Beispiel #5
0
        //
        //========================================================================
        /// <summary>
        /// A complete html page with the login form in the middle. If it processes successfully it returns and empty response. (legacy, sorry)
        /// </summary>
        /// <param name="forceDefaultLogin"></param>
        /// <returns></returns>
        public static string getLoginPage(CoreController core, bool forceDefaultLogin)
        {
            string result = "";

            try {
                if (forceDefaultLogin)
                {
                    result = getLoginForm_Default(core);
                }
                else
                {
                    result = getLoginForm(core);
                }
                if (string.IsNullOrWhiteSpace(result))
                {
                    return(result);
                }
                return("<div class=\"ccCon bg-light pt-2 pb-4\" style=\"width:400px;margin:100px auto 0 auto;border:1px solid #bbb;border-radius:5px;\">" + result + "</div>");
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
        }
Beispiel #6
0
        //
        //====================================================================================================
        /// <summary>
        /// return the correctly formated connection string for this datasource. Called only from within this class
        /// </summary>
        /// <returns>
        /// </returns>
        public string getConnectionStringADONET()
        {
            //
            // (OLEDB) OLE DB Provider for SQL Server > "Provider=sqloledb;Data Source=MyServerName;Initial Catalog=MyDatabaseName;User Id=MyUsername;Password=MyPassword;"
            //     https://www.codeproject.com/Articles/2304/ADO-Connection-Strings#OLE%20DB%20SqlServer
            //
            // (OLEDB) Microsoft OLE DB Provider for SQL Server connection strings > "Provider=sqloledb;Data Source=myServerAddress;Initial Catalog=myDataBase;User Id = myUsername;Password=myPassword;"
            //     https://www.connectionstrings.com/microsoft-ole-db-provider-for-sql-server-sqloledb/
            //
            // (ADONET) .NET Framework Data Provider for SQL Server > Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password = myPassword;
            //     https://www.connectionstrings.com/sql-server/
            //
            string returnConnString = "";

            try {
                string serverUrl = core.serverConfig.defaultDataSourceAddress;
                if (serverUrl.IndexOf(":") > 0)
                {
                    serverUrl = serverUrl.left(serverUrl.IndexOf(":"));
                }
                returnConnString += ""
                                    + "server=" + serverUrl + ";"
                                    + "User Id=" + core.serverConfig.defaultDataSourceUsername + ";"
                                    + "Password="******";"
                                    + "";
                //
                // -- add certificate requirement, if true, set yes, if false, no not add it
                if (core.serverConfig.defaultDataSourceSecure)
                {
                    returnConnString += "Encrypt=yes;";
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(returnConnString);
        }
Beispiel #7
0
 //
 //=============================================================================
 //
 public void verifyRegistrationFormPage(CoreController core)
 {
     try {
         MetadataController.deleteContentRecords(core, "Form Pages", "name=" + DbController.encodeSQLText("Registration Form"));
         using (var csData = new CsModel(core)) {
             if (!csData.open("Form Pages", "name=" + DbController.encodeSQLText("Registration Form")))
             {
                 //
                 // create Version 1 template - just to main_Get it started
                 //
                 if (csData.insert("Form Pages"))
                 {
                     csData.set("name", "Registration Form");
                     string Copy = ""
                                   + Environment.NewLine + "<table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" width=\"100%\">"
                                   + Environment.NewLine + "{{REPEATSTART}}<tr><td align=right style=\"height:22px;\">{{CAPTION}}&nbsp;</td><td align=left>{{FIELD}}</td></tr>{{REPEATEND}}"
                                   + Environment.NewLine + "<tr><td align=right><img alt=\"space\" src=\"" + cdnPrefix + "images/spacer.gif\" width=135 height=1></td><td width=\"100%\">&nbsp;</td></tr>"
                                   + Environment.NewLine + "<tr><td colspan=2>&nbsp;<br>" + core.html.getPanelButtons(ButtonRegister) + "</td></tr>"
                                   + Environment.NewLine + "</table>";
                     csData.set("Body", Copy);
                     Copy = ""
                            + "1"
                            + Environment.NewLine + "Registered\r\ntrue"
                            + Environment.NewLine + "1,First Name,true,FirstName"
                            + Environment.NewLine + "1,Last Name,true,LastName"
                            + Environment.NewLine + "1,Email Address,true,Email"
                            + Environment.NewLine + "1,Phone,true,Phone"
                            + Environment.NewLine + "2,Please keep me informed of news and events,false,Subscribers"
                            + "";
                     csData.set("Instructions", Copy);
                 }
             }
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
 //
 //=============================================================
 /// <summary>
 /// get the lowest recordId based on its name. If no record is found, 0 is returned
 /// </summary>
 /// <param name="contentName"></param>
 /// <param name="recordName"></param>
 /// <returns></returns>
 public static int getRecordIdByUniqueName(CoreController core, string contentName, string recordName)
 {
     try {
         if (String.IsNullOrWhiteSpace(recordName))
         {
             return(0);
         }
         var meta = ContentMetadataModel.createByUniqueName(core, contentName);
         if ((meta == null) || (String.IsNullOrWhiteSpace(meta.tableName)))
         {
             return(0);
         }
         using (DataTable dt = core.db.executeQuery("select top 1 id from " + meta.tableName + " where name=" + DbController.encodeSQLText(recordName) + " order by id")) {
             foreach (DataRow dr in dt.Rows)
             {
                 return(DbController.getDataRowFieldInteger(dr, "id"));
             }
         }
         return(0);
     } catch (Exception ex) {
         LogController.logError(core, ex);
         throw;
     }
 }
Beispiel #9
0
 //
 //========================================================================
 /// <summary>
 /// get site property without a cache check, return as text. If not found, set and return default value
 /// </summary>
 /// <param name="PropertyName"></param>
 /// <param name="DefaultValue"></param>
 /// <param name="memberId"></param>
 /// <returns></returns>
 /// <remarks></remarks>
 public string getTextFromDb(string PropertyName, string DefaultValue, ref bool return_propertyFound)
 {
     try {
         string returnString = SitePropertyModel.getValue(core.cpParent, PropertyName, ref return_propertyFound);
         if (return_propertyFound)
         {
             return(returnString);
         }
         //
         // -- proprety not found
         if (string.IsNullOrEmpty(DefaultValue))
         {
             return(string.Empty);
         }
         //
         // do not set - set may have to save, and save needs contentId, which now loads ondemand, which checks cache, which does a getSiteProperty.
         setProperty(PropertyName, DefaultValue);
         return_propertyFound = true;
         return(DefaultValue);
     } catch (Exception ex) {
         LogController.logError(core, ex);
         throw;
     }
 }
 //
 //====================================================================================================
 /// <summary>
 /// coreClass constructor for app, non-Internet use. coreClass is the primary object internally, created by cp.
 /// </summary>
 /// <param name="cp"></param>
 /// <remarks></remarks>
 public CoreController(CPClass cp, string applicationName, ServerConfigModel serverConfig, System.Web.HttpContext httpContext)
 {
     try {
         this.cpParent       = cp;
         this.cpParent.core  = this;
         _mockNow            = null;
         deleteSessionOnExit = false;
         LogController.log(this, "CoreController constructor-3, enter", BaseClasses.CPLogBaseClass.LogLevel.Trace);
         //
         // -- create default auth objects for non-user methods, or until auth is available
         session = new SessionController(this);
         //
         this.serverConfig = serverConfig;
         this.serverConfig.defaultDataSourceType = ServerConfigBaseModel.DataSourceTypeEnum.sqlServer;
         appConfig = AppConfigModel.getObject(this, serverConfig, applicationName);
         this.appConfig.appStatus = AppConfigModel.AppStatusEnum.ok;
         webServer.initWebContext(httpContext);
         constructorInitialize(true);
         LogController.log(this, "CoreController constructor-3, exit", BaseClasses.CPLogBaseClass.LogLevel.Trace);
     } catch (Exception ex) {
         LogController.logLocalOnly("CoreController constructor-3, exception [" + ex.ToString() + "]", BaseClasses.CPLogBaseClass.LogLevel.Fatal);
         throw;
     }
 }
 //
 //====================================================================================================
 /// <summary>
 /// coreClass constructor for app, non-Internet use. coreClass is the primary object internally, created by cp.
 /// In this mode, user, visit and visitor or empty objects.
 /// To create a session.user, call session.verifyUser()
 /// </summary>
 /// <param name="cp"></param>
 /// <remarks></remarks>
 public CoreController(CPClass cp, string applicationName)
 {
     this.cpParent       = cp;
     this.cpParent.core  = this;
     _mockNow            = null;
     deleteSessionOnExit = true;
     LogController.log(this, "CoreController constructor-1, enter", BaseClasses.CPLogBaseClass.LogLevel.Trace);
     //
     metaDataDictionary    = new Dictionary <string, Models.Domain.ContentMetadataModel>();
     tableSchemaDictionary = null;
     //
     // -- create default auth objects for non-user methods, or until auth is available
     session = new SessionController(this);
     //
     serverConfig = ServerConfigModel.getObject(this);
     serverConfig.defaultDataSourceType = ServerConfigBaseModel.DataSourceTypeEnum.sqlServer;
     appConfig = AppConfigModel.getObject(this, serverConfig, applicationName);
     if (appConfig != null)
     {
         webServer.iisContext = null;
         constructorInitialize(false);
     }
     LogController.log(this, "CoreController constructor-1, exit", BaseClasses.CPLogBaseClass.LogLevel.Trace);
 }
Beispiel #12
0
        //
        //====================================================================================================
        /// <summary>
        /// Process manual changes needed for special cases
        /// </summary>
        /// <param name="isDelete"></param>
        /// <param name="contentName"></param>
        /// <param name="recordId"></param>
        /// <param name="recordName"></param>
        /// <param name="recordParentID"></param>
        /// <param name="useContentWatchLink"></param>
        public static void processAfterSave(CoreController core, bool isDelete, string contentName, int recordId, string recordName, int recordParentID, bool useContentWatchLink)
        {
            try {
                PageContentModel.markReviewed(core.cpParent, recordId);
                string tableName = MetadataController.getContentTablename(core, contentName);
                //
                // -- invalidate the specific cache for this record
                core.cache.invalidateDbRecord(recordId, tableName);
                //
                string tableNameLower = tableName.ToLower(CultureInfo.InvariantCulture);
                if (tableNameLower == AddonCollectionModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- addon collection
                    processAfterSave_AddonCollection(core, isDelete, contentName, recordId, recordName, recordParentID, useContentWatchLink);
                }
                else if (tableNameLower == LinkForwardModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- link forward
                    core.routeMapCacheClear();
                }
                else if (tableNameLower == LinkAliasModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- link alias
                    core.routeMapCacheClear();
                }
                else if (tableNameLower == AddonModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- addon
                    core.routeMapCacheClear();
                }
                else if (tableNameLower == PersonModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- PersonModel
                    var person = PersonModel.create <PersonModel>(core.cpParent, recordId);
                    if (person != null)
                    {
                        if (isDelete)
                        {
                            LogController.addSiteActivity(core, "deleting user #" + recordId + " (" + recordName + ")", recordId, person.organizationId);
                        }
                        else
                        {
                            LogController.addSiteActivity(core, "saving changes to user #" + recordId + " (" + recordName + ")", recordId, person.organizationId);
                        }
                    }
                }
                else if (tableNameLower == OrganizationModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- Log Activity for changes to people and organizattions
                    if (isDelete)
                    {
                        LogController.addSiteActivity(core, "deleting organization #" + recordId + " (" + recordName + ")", 0, recordId);
                    }
                    else
                    {
                        LogController.addSiteActivity(core, "saving changes to organization #" + recordId + " (" + recordName + ")", 0, recordId);
                    }
                }
                else if (tableNameLower == SitePropertyModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- Site Properties
                    switch (GenericController.toLCase(recordName))
                    {
                    case "allowlinkalias":
                        PageContentModel.invalidateCacheOfTable <PageContentModel>(core.cpParent);
                        break;

                    case "sectionlandinglink":
                        PageContentModel.invalidateCacheOfTable <PageContentModel>(core.cpParent);
                        break;

                    case Constants._siteproperty_serverPageDefault_name:
                        PageContentModel.invalidateCacheOfTable <PageContentModel>(core.cpParent);
                        break;
                    }
                }
                else if (tableNameLower == PageContentModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- set ChildPagesFound true for parent page
                    if (recordParentID > 0)
                    {
                        if (!isDelete)
                        {
                            core.db.executeNonQuery("update ccpagecontent set ChildPagesfound=1 where ID=" + recordParentID);
                        }
                    }
                    if (isDelete)
                    {
                        //
                        // Clear the Landing page and page not found site properties
                        if (recordId == GenericController.encodeInteger(core.siteProperties.getText("PageNotFoundPageID", "0")))
                        {
                            core.siteProperties.setProperty("PageNotFoundPageID", "0");
                        }
                        if (recordId == core.siteProperties.landingPageID)
                        {
                            core.siteProperties.setProperty("landingPageId", "0");
                        }
                        //
                        // Delete Link Alias entries with this PageID
                        core.db.executeNonQuery("delete from cclinkAliases where PageID=" + recordId);
                    }
                    DbBaseModel.invalidateCacheOfRecord <PageContentModel>(core.cpParent, recordId);
                }
                else if (tableNameLower == LibraryFilesModel.tableMetadata.tableNameLower)
                {
                    //
                    // --
                    processAfterSave_LibraryFiles(core, isDelete, contentName, recordId, recordName, recordParentID, useContentWatchLink);
                }
                //
                // Process Addons marked to trigger a process call on content change
                //
                Dictionary <string, string> instanceArguments;
                bool onChangeAddonsAsync = core.siteProperties.getBoolean("execute oncontentchange addons async", false);
                using (var csData = new CsModel(core)) {
                    int contentId = ContentMetadataModel.getContentId(core, contentName);
                    csData.open("Add-on Content Trigger Rules", "ContentID=" + contentId, "", false, 0, "addonid");
                    string Option_String = null;
                    if (isDelete)
                    {
                        instanceArguments = new Dictionary <string, string> {
                            { "action", "contentdelete" },
                            { "contentid", contentId.ToString() },
                            { "recordid", recordId.ToString() }
                        };
                        Option_String = ""
                                        + Environment.NewLine + "action=contentdelete"
                                        + Environment.NewLine + "contentid=" + contentId
                                        + Environment.NewLine + "recordid=" + recordId + "";
                    }
                    else
                    {
                        instanceArguments = new Dictionary <string, string> {
                            { "action", "contentchange" },
                            { "contentid", contentId.ToString() },
                            { "recordid", recordId.ToString() }
                        };
                        Option_String = ""
                                        + Environment.NewLine + "action=contentchange"
                                        + Environment.NewLine + "contentid=" + contentId
                                        + Environment.NewLine + "recordid=" + recordId + "";
                    }
                    while (csData.ok())
                    {
                        var addon = DbBaseModel.create <AddonModel>(core.cpParent, csData.getInteger("Addonid"));
                        if (addon != null)
                        {
                            if (onChangeAddonsAsync)
                            {
                                //
                                // -- execute addon async
                                core.addon.executeAsync(addon, instanceArguments);
                            }
                            else
                            {
                                //
                                // -- execute addon
                                core.addon.execute(addon, new CPUtilsBaseClass.addonExecuteContext {
                                    addonType             = CPUtilsBaseClass.addonContext.ContextOnContentChange,
                                    backgroundProcess     = false,
                                    errorContextMessage   = "",
                                    argumentKeyValuePairs = instanceArguments
                                });
                            }
                        }
                        csData.goNext();
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
        }
Beispiel #13
0
        //
        //====================================================================================================
        /// <summary>
        /// Checks if the member is a content manager for the specific content, Which includes transversing up the tree to find the next rule that applies. Member must be checked for authenticated and main_IsAdmin already
        /// </summary>
        /// <param name="core"></param>
        /// <param name="contentId"></param>
        /// <param name="returnAllowEdit"></param>
        /// <param name="returnAllowAdd"></param>
        /// <param name="returnAllowDelete"></param>
        /// <param name="usedContentIdList"></param>
        //========================================================================
        //
        private static UserContentPermissions getUserAuthoringPermissions_ContentManager(CoreController core, ContentMetadataModel cdef, List <int> usedContentIdList)
        {
            var result = new UserContentPermissions {
                allowAdd    = false,
                allowDelete = false,
                allowEdit   = false,
                allowSave   = false
            };

            try {
                if (usedContentIdList.Contains(cdef.id))
                {
                    //
                    // failed usedContentIdList test, this content id was in the child path
                    //
                    throw new ArgumentException("ContentID [" + cdef.id + "] was found to be in it's own parentid path.");
                }
                else if (cdef.id < 1)
                {
                    //
                    // ----- not a valid contentname
                    //
                }
                else if (core.doc.contentAccessRights_NotList.Contains(cdef.id))
                {
                    //
                    // ----- was previously found to not be a Content Manager
                    //
                }
                else if (core.doc.contentAccessRights_List.Contains(cdef.id))
                {
                    //
                    // ----- was previously found to be a Content Manager
                    //
                    result.allowEdit   = true;
                    result.allowSave   = true;
                    result.allowAdd    = core.doc.contentAccessRights_AllowAddList.Contains(cdef.id);
                    result.allowDelete = core.doc.contentAccessRights_AllowDeleteList.Contains(cdef.id);
                }
                else
                {
                    //
                    // ----- Must test it
                    //
                    string SQL = "SELECT ccGroupRules.ContentID,allowAdd,allowDelete"
                                 + " FROM ccGroupRules RIGHT JOIN ccMemberRules ON ccGroupRules.GroupId = ccMemberRules.GroupID"
                                 + " WHERE ("
                                 + " (ccMemberRules.memberId=" + DbController.encodeSQLNumber(core.session.user.id) + ")"
                                 + " AND(ccMemberRules.active<>0)"
                                 + " AND(ccGroupRules.active<>0)"
                                 + " AND(ccGroupRules.ContentID=" + cdef.id + ")"
                                 + " AND((ccMemberRules.DateExpires is null)OR(ccMemberRules.DateExpires>" + DbController.encodeSQLDate(core.doc.profileStartTime) + "))"
                                 + ");";
                    using (var csData = new CsModel(core)) {
                        csData.openSql(SQL);
                        if (csData.ok())
                        {
                            result.allowEdit   = true;
                            result.allowSave   = true;
                            result.allowAdd    = csData.getBoolean("allowAdd");
                            result.allowDelete = csData.getBoolean("allowDelete");
                        }
                    }
                    //
                    if (!result.allowEdit)
                    {
                        //
                        // ----- Not a content manager for this one, check the parent
                        if (cdef.parentId > 0)
                        {
                            var parentCdef = ContentMetadataModel.create(core, cdef.parentId);
                            usedContentIdList.Add(cdef.id);
                            getUserAuthoringPermissions_ContentManager(core, cdef, usedContentIdList);
                        }
                    }
                    if (result.allowEdit)
                    {
                        //
                        // ----- Was found to be true
                        //
                        core.doc.contentAccessRights_List.Add(cdef.id);
                        if (result.allowEdit)
                        {
                            core.doc.contentAccessRights_AllowAddList.Add(cdef.id);
                        }
                        if (result.allowDelete)
                        {
                            core.doc.contentAccessRights_AllowDeleteList.Add(cdef.id);
                        }
                    }
                    else
                    {
                        //
                        // ----- Was found to be false
                        //
                        core.doc.contentAccessRights_NotList.Add(cdef.id);
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(result);
        }
Beispiel #14
0
        //
        //=============================================================================
        /// <summary>
        /// editor for page content inline editing
        /// </summary>
        /// <param name="core"></param>
        /// <param name="rootPageId"></param>
        /// <param name="OrderByClause"></param>
        /// <param name="AllowPageList"></param>
        /// <param name="AllowReturnLink"></param>
        /// <param name="ArchivePages"></param>
        /// <param name="contactMemberID"></param>
        /// <param name="childListSortMethodId"></param>
        /// <param name="main_AllowChildListComposite"></param>
        /// <param name="ArchivePage"></param>
        /// <returns></returns>
        internal static string getQuickEditing(CoreController core)
        {
            string result = "";

            try {
                int childListSortMethodId = core.doc.pageController.page.childListSortMethodId;
                int contactMemberId       = core.doc.pageController.page.contactMemberId;
                int rootPageId            = core.doc.pageController.pageToRootList.Last().id;
                core.html.addStyleLink("" + cdnPrefix + "quickEditor/styles.css", "Quick Editor");
                //
                // -- First Active Record - Output Quick Editor form
                Models.Domain.ContentMetadataModel cdef = Models.Domain.ContentMetadataModel.createByUniqueName(core, PageContentModel.tableMetadata.contentName);
                var pageContentTable = DbBaseModel.create <TableModel>(core.cpParent, cdef.id);
                var editLock         = WorkflowController.getEditLock(core, pageContentTable.id, core.doc.pageController.page.id);
                WorkflowController.recordWorkflowStatusClass authoringStatus        = WorkflowController.getWorkflowStatus(core, PageContentModel.tableMetadata.contentName, core.doc.pageController.page.id);
                PermissionController.UserContentPermissions  userContentPermissions = PermissionController.getUserContentPermissions(core, cdef);
                bool   AllowMarkReviewed           = DbBaseModel.containsField <PageContentModel>("DateReviewed");
                string OptionsPanelAuthoringStatus = core.session.getAuthoringStatusMessage(false, editLock.isEditLocked, editLock.editLockByMemberName, encodeDate(editLock.editLockExpiresDate), authoringStatus.isWorkflowApproved, authoringStatus.workflowApprovedMemberName, authoringStatus.isWorkflowSubmitted, authoringStatus.workflowSubmittedMemberName, authoringStatus.isWorkflowDeleted, authoringStatus.isWorkflowInserted, authoringStatus.isWorkflowModified, authoringStatus.workflowModifiedByMemberName);
                //
                // Set Editing Authoring Control
                //
                WorkflowController.setEditLock(core, pageContentTable.id, core.doc.pageController.page.id);
                //
                // SubPanel: Authoring Status
                //
                string leftButtonCommaList = "";
                leftButtonCommaList = leftButtonCommaList + "," + ButtonCancel;
                if (userContentPermissions.allowSave)
                {
                    leftButtonCommaList = leftButtonCommaList + "," + ButtonSave + "," + ButtonOK;
                }
                if (userContentPermissions.allowDelete && (core.doc.pageController.pageToRootList.Count == 1))
                {
                    //
                    // -- allow delete and not root page
                    leftButtonCommaList = leftButtonCommaList + "," + ButtonDelete;
                }
                if (userContentPermissions.allowAdd)
                {
                    leftButtonCommaList = leftButtonCommaList + "," + ButtonAddChildPage;
                }
                int page_ParentId = 0;
                if ((page_ParentId != 0) && userContentPermissions.allowAdd)
                {
                    leftButtonCommaList = leftButtonCommaList + "," + ButtonAddSiblingPage;
                }
                if (AllowMarkReviewed)
                {
                    leftButtonCommaList = leftButtonCommaList + "," + ButtonMarkReviewed;
                }
                if (!string.IsNullOrEmpty(leftButtonCommaList))
                {
                    leftButtonCommaList = leftButtonCommaList.Substring(1);
                    leftButtonCommaList = core.html.getPanelButtons(leftButtonCommaList);
                }
                if (!core.doc.userErrorList.Count.Equals(0))
                {
                    result += ""
                              + "\r<tr>"
                              + cr2 + "<td colspan=2 class=\"qeRow\"><div class=\"qeHeadCon\">" + ErrorController.getUserError(core) + "</div></td>"
                              + "\r</tr>";
                }
                if (!userContentPermissions.allowSave)
                {
                    result += ""
                              + "\r<tr>"
                              + cr2 + "<td colspan=\"2\" class=\"qeRow\">" + getQuickEditingBody(core, PageContentModel.tableMetadata.contentName, "", true, true, rootPageId, !userContentPermissions.allowSave, true, PageContentModel.tableMetadata.contentName, false, contactMemberId) + "</td>"
                              + "\r</tr>";
                }
                else
                {
                    result += ""
                              + "\r<tr>"
                              + cr2 + "<td colspan=\"2\" class=\"qeRow\">" + getQuickEditingBody(core, PageContentModel.tableMetadata.contentName, "", true, true, rootPageId, !userContentPermissions.allowSave, true, PageContentModel.tableMetadata.contentName, false, contactMemberId) + "</td>"
                              + "\r</tr>";
                }
                result += "\r<tr>"
                          + cr2 + "<td class=\"qeRow qeLeft\" style=\"padding-top:10px;\">Name</td>"
                          + cr2 + "<td class=\"qeRow qeRight\">" + HtmlController.inputText_Legacy(core, "name", core.doc.pageController.page.name, 1, 0, "", false, !userContentPermissions.allowSave) + "</td>"
                          + "\r</tr>"
                          + "";
                string pageList = "&nbsp;(there are no parent pages)";
                //
                // ----- Parent pages
                //
                if (core.doc.pageController.pageToRootList.Count > 1)
                {
                    pageList = "<ul class=\"qeListUL\"><li class=\"qeListLI\">Current Page</li></ul>";
                    foreach (PageContentModel testPage in Enumerable.Reverse(core.doc.pageController.pageToRootList))
                    {
                        string pageCaption = testPage.name;
                        if (string.IsNullOrEmpty(pageCaption))
                        {
                            pageCaption = "no name #" + GenericController.encodeText(testPage.id);
                        }
                        pageCaption = "<a href=\"" + PageContentController.getPageLink(core, testPage.id, "") + "\">" + pageCaption + "</a>";
                        pageList    = "<ul class=\"qeListUL\"><li class=\"qeListLI\">" + pageCaption + pageList + "</li></ul>";
                    }
                }
                result += ""
                          + "\r<tr>"
                          + cr2 + "<td class=\"qeRow qeLeft\" style=\"padding-top:26px;\">Parent Pages</td>"
                          + cr2 + "<td class=\"qeRow qeRight\"><div class=\"qeListCon\">" + pageList + "</div></td>"
                          + "\r</tr>";
                //
                // ----- Child pages
                //
                AddonModel addon = DbBaseModel.create <AddonModel>(core.cpParent, addonGuidChildList);
                CPUtilsBaseClass.addonExecuteContext executeContext = new CPUtilsBaseClass.addonExecuteContext {
                    addonType  = CPUtilsBaseClass.addonContext.ContextPage,
                    hostRecord = new CPUtilsBaseClass.addonExecuteHostRecordContext {
                        contentName = PageContentModel.tableMetadata.contentName,
                        fieldName   = "",
                        recordId    = core.doc.pageController.page.id
                    },
                    argumentKeyValuePairs = GenericController.convertQSNVAArgumentstoDocPropertiesList(core, core.doc.pageController.page.childListInstanceOptions),
                    instanceGuid          = PageChildListInstanceId,
                    errorContextMessage   = "calling child page addon in quick editing editor"
                };
                pageList = core.addon.execute(addon, executeContext);
                if (GenericController.strInstr(1, pageList, "<ul", 1) == 0)
                {
                    pageList = "(there are no child pages)";
                }
                result += "\r<tr>"
                          + cr2 + "<td class=\"qeRow qeLeft\" style=\"padding-top:36px;\">Child Pages</td>"
                          + cr2 + "<td class=\"qeRow qeRight\"><div class=\"qeListCon\">" + pageList + "</div></td>"
                          + "\r</tr>";
                result = ""
                         + "\r<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">"
                         + GenericController.nop(result) + "\r</table>";
                result = ""
                         + leftButtonCommaList + result + leftButtonCommaList;
                result = core.html.getPanel(result);
                //
                // Form Wrapper
                //
                result += ""
                          + HtmlController.inputHidden("Type", FormTypePageAuthoring)
                          + HtmlController.inputHidden("ID", core.doc.pageController.page.id)
                          + HtmlController.inputHidden("ContentName", PageContentModel.tableMetadata.contentName);
                result = HtmlController.formMultipart(core, result, core.webServer.requestQueryString, "", "ccForm");
                result = "<div class=\"ccCon\">" + result + "</div>";
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(result);
        }
 //
 //====================================================================================================
 /// <summary>
 /// run as single task from the cctasks table of an app, makred with a runnerGuid
 /// called from runTasks or from the cli in a different process
 /// when the task starts,
 /// saves the addons output to the task.filename
 /// </summary>
 public static void executeRunnerTasks(string appName, string runnerGuid)
 {
     try {
         using (var cp = new Contensive.Processor.CPClass(appName)) {
             try {
                 foreach (var task in DbBaseModel.createList <TaskModel>(cp, "(cmdRunner=" + DbController.encodeSQLText(runnerGuid) + ")and(datestarted is null)", "id"))
                 {
                     //
                     // -- trace log without core
                     LogController.log(cp.core, "taskRunner.runTask, runTask, task [" + task.name + "], cmdDetail [" + task.cmdDetail + "]", BaseClasses.CPLogBaseClass.LogLevel.Info);
                     //
                     DateTime dateStarted = cp.core.dateTimeNowMockable;
                     var      cmdDetail   = DeserializeObject <TaskModel.CmdDetailClass>(task.cmdDetail);
                     if (cmdDetail != null)
                     {
                         var addon = DbBaseModel.create <AddonModel>(cp, cmdDetail.addonId);
                         if (addon != null)
                         {
                             var context = new BaseClasses.CPUtilsBaseClass.addonExecuteContext {
                                 backgroundProcess     = true,
                                 addonType             = BaseClasses.CPUtilsBaseClass.addonContext.ContextSimple,
                                 argumentKeyValuePairs = cmdDetail.args,
                                 errorContextMessage   = "running task, addon [" + cmdDetail.addonId + "]"
                             };
                             string result = cp.core.addon.execute(addon, context);
                             if (!string.IsNullOrEmpty(result))
                             {
                                 //
                                 LogController.logTrace(cp.core, "executeRunnerTasks, result not empty, downloadId [" + task.resultDownloadId + "], result first 100 [" + (result.Length > 100 ? result.Substring(0, 100) : result) + "]");
                                 //
                                 // -- save output
                                 if (task.resultDownloadId > 0)
                                 {
                                     var download = DbBaseModel.create <DownloadModel>(cp, task.resultDownloadId);
                                     if (download != null)
                                     {
                                         //
                                         LogController.logTrace(cp.core, "executeRunnerTasks, download found, [id" + download.id + ", name:" + download.name + ", filename:" + download.filename + "]");
                                         //
                                         if (string.IsNullOrEmpty(download.name))
                                         {
                                             download.name = "Download";
                                         }
                                         download.resultMessage    = "Completed";
                                         download.filename.content = result;
                                         download.dateRequested    = dateStarted;
                                         download.dateCompleted    = cp.core.dateTimeNowMockable;
                                         download.save(cp);
                                     }
                                 }
                             }
                         }
                     }
                     task.dateCompleted = cp.core.dateTimeNowMockable;
                     DbBaseModel.delete <TaskModel>(cp, task.id);
                     //
                     // -- info log the task running - so info state will log for memory leaks
                     LogController.log(cp.core, "TaskRunner exit, task [" + task.name + "], cmdDetail [" + task.cmdDetail + "]", BaseClasses.CPLogBaseClass.LogLevel.Info);
                 }
             } catch (Exception exInner) {
                 LogController.log(cp.core, "TaskRunner exception, ex [" + exInner.ToString() + "]", BaseClasses.CPLogBaseClass.LogLevel.Error);
                 throw;
             }
         }
     } catch (Exception ex) {
         Console.WriteLine("Error: [" + ex + "]");
     }
 }
 //
 //====================================================================================================
 /// <summary>
 /// Iterate through all apps and execute tasks in processes
 /// </summary>
 private void runTasks(CoreController serverCore)
 {
     try {
         Stopwatch swProcess = new Stopwatch();
         swProcess.Start();
         //
         foreach (var appKVP in serverCore.serverConfig.apps)
         {
             if (appKVP.Value.enabled && appKVP.Value.appStatus.Equals(AppConfigModel.AppStatusEnum.ok))
             {
                 //
                 // query tasks that need to be run
                 //
                 using (CPClass cpApp = new CPClass(appKVP.Value.name)) {
                     //
                     LogController.logTrace(cpApp.core, "runTasks, appname=[" + appKVP.Value.name + "]");
                     //
                     try {
                         int recordsAffected     = 0;
                         int sequentialTaskCount = 0;
                         do
                         {
                             //
                             // for now run an sql to get processes, eventually cache in variant cache
                             string sqlCmdRunner = DbController.encodeSQLText(runnerGuid);
                             string sql          = ""
                                                   + Environment.NewLine + " BEGIN TRANSACTION"
                                                   + Environment.NewLine + " update cctasks set cmdRunner=" + sqlCmdRunner + " where id in (select top 1 id from cctasks where (cmdRunner is null)and(datestarted is null) order by id)"
                                                   + Environment.NewLine + " COMMIT TRANSACTION";
                             cpApp.core.db.executeNonQuery(sql, ref recordsAffected);
                             if (recordsAffected == 0)
                             {
                                 //
                                 // -- no tasks found
                                 LogController.logTrace(cpApp.core, "runTasks, appname=[" + appKVP.Value.name + "], no tasks");
                             }
                             else
                             {
                                 //
                                 // -- select task to get timeout
                                 List <TaskModel> taskList = DbBaseModel.createList <TaskModel>(cpApp, "(cmdRunner=" + sqlCmdRunner + ")");
                                 if (taskList.Count > 0)
                                 {
                                     TaskModel task   = taskList.First();
                                     Stopwatch swTask = new Stopwatch();
                                     swTask.Start();
                                     //
                                     // -- track multiple executions
                                     if (sequentialTaskCount > 0)
                                     {
                                         LogController.logTrace(cpApp.core, "runTasks, appname=[" + appKVP.Value.name + "], multiple tasks run in a single cycle, sequentialTaskCount [" + sequentialTaskCount + "]");
                                     }
                                     //
                                     // -- two execution methods, 1) run task here, 2) start process and wait (so bad addon code does not memory link)
                                     bool   runInServiceProcess = cpApp.Site.GetBoolean("Run tasks in service process");
                                     string cliPathFilename     = cpApp.core.programFiles.localAbsRootPath + "cc.exe";
                                     if (!runInServiceProcess && !System.IO.File.Exists(cliPathFilename))
                                     {
                                         runInServiceProcess = true;
                                         LogController.logError(cpApp.core, "TaskRunner cannot run out of process because command line program cc.exe not found in program files folder [" + cpApp.core.programFiles.localAbsRootPath + "]");
                                     }
                                     if (runInServiceProcess)
                                     {
                                         //
                                         // -- execute here
                                         executeRunnerTasks(cpApp.Site.Name, runnerGuid);
                                     }
                                     else
                                     {
                                         //
                                         // -- execute in new  process
                                         string filename         = "cc.exe";
                                         string workingDirectory = cpApp.core.programFiles.localAbsRootPath;
                                         string arguments        = "-a \"" + appKVP.Value.name + "\" --runTask \"" + runnerGuid + "\"";
                                         LogController.logInfo(cpApp.core, "TaskRunner starting process to execute task for filename [" + filename + "], workingDirectory [" + workingDirectory + "], arguments [" + arguments + "]");
                                         //
                                         // todo manage multiple executing processes
                                         using (Process process = new Process()) {
                                             process.StartInfo.CreateNoWindow   = true;
                                             process.StartInfo.FileName         = filename;
                                             process.StartInfo.WorkingDirectory = workingDirectory;
                                             process.StartInfo.Arguments        = arguments;
                                             process.StartInfo.WindowStyle      = ProcessWindowStyle.Hidden;
                                             process.Start();
                                             //
                                             // -- determine how long to wait
                                             int timeoutMsec = 0;
                                             if ((int.MaxValue / 1000) >= task.timeout)
                                             {
                                                 // minus 1 because maxvalue causes wait for ever
                                                 timeoutMsec = int.MaxValue - 1;
                                             }
                                             else
                                             {
                                                 timeoutMsec = task.timeout * 1000;
                                             }
                                             if (timeoutMsec == 0)
                                             {
                                                 //
                                                 // --no timeout, just run the task
                                                 process.WaitForExit();
                                             }
                                             else
                                             {
                                                 process.WaitForExit(timeoutMsec);
                                             }
                                             if (!process.HasExited)
                                             {
                                                 LogController.logError(cpApp.core, "TaskRunner Killing process, process timed out, app [" + appKVP.Value.name + "].");
                                                 process.Kill();
                                                 process.WaitForExit();
                                             }
                                             process.Close();
                                         }
                                     }
                                     LogController.logTrace(cpApp.core, "runTasks, app [" + appKVP.Value.name + "], task complete (" + swTask.ElapsedMilliseconds + "ms)");
                                 }
                             }
                             sequentialTaskCount++;
                         } while (recordsAffected > 0);
                     } catch (Exception ex) {
                         LogController.logError(cpApp.core, ex);
                     }
                 }
             }
         }
         //
         // -- trace log without core
     } catch (Exception ex) {
         LogController.logError(serverCore, ex);
     }
 }
Beispiel #17
0
        //
        //====================================================================================================
        /// <summary>
        /// execute vb script
        /// </summary>
        /// <param name="addon"></param>
        /// <param name="Code"></param>
        /// <param name="EntryPoint"></param>
        /// <param name="ScriptingTimeout"></param>
        /// <param name="ScriptName"></param>
        /// <returns></returns>
        public static string execute_Script_VBScript(CoreController core, ref AddonModel addon)
        {
            string returnText = "";

            try {
                // todo - move locals
                using (var engine = new Microsoft.ClearScript.Windows.VBScriptEngine()) {
                    //var engine = new Microsoft.ClearScript.Windows.VBScriptEngine(Microsoft.ClearScript.Windows.WindowsScriptEngineFlags.EnableDebugging);
                    string entryPoint = addon.scriptingEntryPoint;
                    if (string.IsNullOrEmpty(entryPoint))
                    {
                        //
                        // -- compatibility mode, if no entry point given, if the code starts with "function myFuncton()" and add "call myFunction()"
                        int pos = addon.scriptingCode.IndexOf("function", StringComparison.CurrentCultureIgnoreCase);
                        if (pos >= 0)
                        {
                            entryPoint = addon.scriptingCode.Substring(pos + 9);
                            pos        = entryPoint.IndexOf("\r");
                            if (pos > 0)
                            {
                                entryPoint = entryPoint.Substring(0, pos);
                            }
                            pos = entryPoint.IndexOf("\n");
                            if (pos > 0)
                            {
                                entryPoint = entryPoint.Substring(0, pos);
                            }
                            pos = entryPoint.IndexOf("(");
                            if (pos > 0)
                            {
                                entryPoint = entryPoint.Substring(0, pos);
                            }
                        }
                    }
                    else
                    {
                        //
                        // -- etnry point provided, remove "()" if included and add to code
                        int pos = entryPoint.IndexOf("(");
                        if (pos > 0)
                        {
                            entryPoint = entryPoint.Substring(0, pos);
                        }
                    }
                    //
                    // -- adding cclib
                    try {
                        MainCsvScriptCompatibilityClass mainCsv = new MainCsvScriptCompatibilityClass(core);
                        engine.AddHostObject("ccLib", mainCsv);
                    } catch (Microsoft.ClearScript.ScriptEngineException ex) {
                        string errorMessage = getScriptEngineExceptionMessage(ex, "Adding cclib compatibility object ");
                        LogController.logError(core, ex, errorMessage);
                        throw new GenericException(errorMessage, ex);
                    } catch (Exception ex) {
                        LogController.logError(core, ex);
                        throw;
                    }
                    //
                    // -- adding cp
                    try {
                        engine.AddHostObject("cp", core.cpParent);
                    } catch (Microsoft.ClearScript.ScriptEngineException ex) {
                        string errorMessage = getScriptEngineExceptionMessage(ex, "Adding cp object ");
                        LogController.logError(core, ex, errorMessage);
                        throw new GenericException(errorMessage, ex);
                    } catch (Exception ex) {
                        LogController.logError(core, ex);
                        throw;
                    }
                    //
                    // -- execute code
                    try {
                        engine.Execute(addon.scriptingCode);
                        object returnObj = engine.Evaluate(entryPoint);
                        if (returnObj != null)
                        {
                            if (returnObj.GetType() == typeof(String))
                            {
                                returnText = (String)returnObj;
                            }
                        }
                    } catch (Microsoft.ClearScript.ScriptEngineException ex) {
                        string errorMessage = getScriptEngineExceptionMessage(ex, "executing script ");
                        LogController.logError(core, ex, errorMessage);
                        throw new GenericException(errorMessage, ex);
                    } catch (Exception ex) {
                        string addonDescription = AddonController.getAddonDescription(core, addon);
                        string errorMessage     = "Error executing addon script, " + addonDescription;
                        throw new GenericException(errorMessage, ex);
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(returnText);
        }
 //
 //====================================================================================================
 /// <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;
     }
 }
        //
        //======================================================================================================
        //
        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;
            }
        }
        //
        //=================================================================================================
        //   return the position following the tag which closes the tag that starts the string
        //       starting postion<div><div><p>this and that</p><!-- </div> --></div></div>And a whole lot more
        //       returns the position of the "A" following the last /div
        //       string 123<img>456 returns pointing to "4"
        //       string 123456 returns pointing to "6"
        //       returns 0 if the end was not found
        //=================================================================================================
        //
        public static int getTagEndPos(CoreController core, string Source, int startPos)
        {
            int returnValue = 0;

            try {
                int    Pos        = 0;
                string TagName    = null;
                string endTag     = null;
                string startTag   = null;
                int    posNest    = 0;
                int    posEnd     = 0;
                int    posComment = 0;
                string c          = null;
                //
                Pos         = GenericController.strInstr(startPos, Source, "<");
                TagName     = "";
                returnValue = 0;
                if (Pos != 0)
                {
                    Pos = Pos + 1;
                    while (Pos < Source.Length)
                    {
                        c = GenericController.toLCase(Source.Substring(Pos - 1, 1));
                        if ((string.CompareOrdinal(c, "a") >= 0) && (string.CompareOrdinal(c, "z") <= 0))
                        {
                            TagName = TagName + c;
                        }
                        else
                        {
                            break;
                        }
                        Pos = Pos + 1;
                    }
                    if (!string.IsNullOrEmpty(TagName))
                    {
                        endTag   = "</" + TagName;
                        startTag = "<" + TagName;
                        while (Pos != 0)
                        {
                            posEnd = GenericController.strInstr(Pos + 1, Source, endTag, 1);
                            if (posEnd == 0)
                            {
                                //
                                // no end was found, return the tag or rest of the string
                                //
                                returnValue = GenericController.strInstr(Pos + 1, Source, ">") + 1;
                                if (posEnd == 1)
                                {
                                    returnValue = Source.Length;
                                }
                                break;
                            }
                            else
                            {
                                posNest = GenericController.strInstr(Pos + 1, Source, startTag, 1);
                                if (posNest == 0)
                                {
                                    //
                                    // no nest found, set to end
                                    //
                                    posNest = Source.Length;
                                }
                                posComment = GenericController.strInstr(Pos + 1, Source, "<!--");
                                if (posComment == 0)
                                {
                                    //
                                    // no comment found, set to end
                                    //
                                    posComment = Source.Length;
                                }
                                if ((posNest < posEnd) && (posNest < posComment))
                                {
                                    //
                                    // ----- the tag is nested, find the end of the nest
                                    //
                                    Pos = getTagEndPos(core, Source, posNest);
                                    // 8/28/2012, if there is a nested tag right before the correct end tag, it skips the end:
                                    // <div class=a>a<div class=b>b</div></div>
                                    // the second /div is missed because returnValue returns one past the >, then the
                                    // next search starts +1 that position
                                    if (Pos > 0)
                                    {
                                        Pos = Pos - 1;
                                    }
                                }
                                else if (posComment < posEnd)
                                {
                                    //
                                    // ----- there is a comment between the tag and the first tagend, skip it
                                    //
                                    Pos = GenericController.strInstr(posComment, Source, "-->");
                                    if (Pos == 0)
                                    {
                                        //
                                        // start comment with no end, exit now
                                        //
                                        returnValue = Source.Length;
                                        break;
                                    }
                                }
                                else
                                {
                                    //
                                    // ----- end position is here, go to the end of it and exit
                                    //
                                    Pos = GenericController.strInstr(posEnd, Source, ">");
                                    if (Pos == 0)
                                    {
                                        //
                                        // no end was found, just exit
                                        //
                                        returnValue = Source.Length;
                                        break;
                                    }
                                    else
                                    {
                                        //
                                        // ----- end was found
                                        //
                                        returnValue = Pos + 1;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(returnValue);
        }
        //
        //====================================================================================================
        public static int getTagStartPos(CoreController core, string layout, int layoutStartPos, string Key)
        {
            int returnValue = 0;

            try {
                int      returnPos    = 0;
                int      SegmentStart = 0;
                int      Pos          = 0;
                int      LoopPtr      = 0;
                string   searchKey    = null;
                int      lenSearchKey = 0;
                int      Ptr          = 0;
                string   workingKey   = null;
                string[] workingKeys  = null;
                string   searchClass  = null;
                string   searchId     = null;
                string   searchTag    = null;
                int      posStartTag  = 0;
                //
                returnPos  = 0;
                workingKey = Key;
                if (GenericController.strInstr(1, workingKey, ">") != 0)
                {
                    //
                    // does not support > yet.
                    //
                    workingKey = GenericController.strReplace(workingKey, ">", " ");
                }
                //
                // eliminate whitespace
                //
                while (GenericController.strInstr(1, workingKey, "\t") != 0)
                {
                    workingKey = GenericController.strReplace(workingKey, "\t", " ");
                }
                //
                while (GenericController.strInstr(1, workingKey, "\r") != 0)
                {
                    workingKey = GenericController.strReplace(workingKey, "\r", " ");
                }
                //
                while (GenericController.strInstr(1, workingKey, "\n") != 0)
                {
                    workingKey = GenericController.strReplace(workingKey, "\n", " ");
                }
                //
                while (GenericController.strInstr(1, workingKey, "  ") != 0)
                {
                    workingKey = GenericController.strReplace(workingKey, "  ", " ");
                }
                //
                workingKey = workingKey.Trim(' ');
                //
                if (GenericController.strInstr(1, workingKey, " ") != 0)
                {
                    //
                    // if there are spaces, do them sequentially
                    //
                    workingKeys  = workingKey.Split(' ');
                    SegmentStart = 1;
                    while ((!string.IsNullOrEmpty(layout)) && (SegmentStart != 0) && (Ptr <= workingKeys.GetUpperBound(0)))
                    {
                        SegmentStart = getTagStartPos(null, layout, SegmentStart, workingKeys[Ptr]);
                        Ptr          = Ptr + 1;
                    }
                    returnPos = SegmentStart;
                }
                else
                {
                    //
                    // find this single key and get the outerHTML
                    //   at this point, the key can be
                    //       a class = .xxxx
                    //       an id = #xxxx
                    //       a tag = xxxx
                    //       a compound in either form, xxxx.xxxx or xxxx#xxxx
                    //
                    //   searchKey = the search pattern to start
                    //
                    if (workingKey.left(1) == ".")
                    {
                        //
                        // search for a class
                        //
                        searchClass = workingKey.Substring(1);
                        searchTag   = "";
                        searchId    = "";
                        Pos         = GenericController.strInstr(1, searchClass, "#");
                        if (Pos != 0)
                        {
                            searchId    = searchClass.Substring(Pos - 1);
                            searchClass = searchClass.left(Pos - 1);
                        }
                        //
                        searchKey = "<";
                    }
                    else if (workingKey.left(1) == "#")
                    {
                        //
                        // search for an ID
                        //
                        searchClass = "";
                        searchTag   = "";
                        searchId    = workingKey.Substring(1);
                        Pos         = GenericController.strInstr(1, searchId, ".");
                        if (Pos != 0)
                        {
                            searchClass = searchId.Substring(Pos - 1);
                            searchId    = searchId.left(Pos - 1);
                        }
                        //
                        searchKey = "<";
                    }
                    else
                    {
                        //
                        // search for a tagname
                        //
                        searchClass = "";
                        searchTag   = workingKey;
                        searchId    = "";
                        //
                        Pos = GenericController.strInstr(1, searchTag, "#");
                        if (Pos != 0)
                        {
                            searchId  = searchTag.Substring(Pos);
                            searchTag = searchTag.left(Pos - 1);
                            Pos       = GenericController.strInstr(1, searchId, ".");
                            if (Pos != 0)
                            {
                                searchClass = searchId.Substring(Pos - 1);
                                searchId    = searchId.left(Pos - 1);
                            }
                        }
                        Pos = GenericController.strInstr(1, searchTag, ".");
                        if (Pos != 0)
                        {
                            searchClass = searchTag.Substring(Pos);
                            searchTag   = searchTag.left(Pos - 1);
                            Pos         = GenericController.strInstr(1, searchClass, "#");
                            if (Pos != 0)
                            {
                                searchId    = searchClass.Substring(Pos - 1);
                                searchClass = searchClass.left(Pos - 1);
                            }
                        }
                        //
                        searchKey = "<" + searchTag;
                    }
                    lenSearchKey = searchKey.Length;
                    Pos          = layoutStartPos;
                    do
                    {
                        Pos = GenericController.strInstr(Pos, layout, searchKey);
                        if (Pos == 0)
                        {
                            //
                            // not found, return empty
                            //
                            break;
                        }
                        else
                        {
                            //
                            // string found - go to the start of the tag
                            //
                            posStartTag = layout.LastIndexOf("<", Pos) + 1;
                            if (posStartTag <= 0)
                            {
                                //
                                // bad html, no start tag found
                                //
                                Pos       = 0;
                                returnPos = 0;
                            }
                            else if (layout.Substring(posStartTag - 1, 2) == "</")
                            {
                                //
                                // this is an end tag, skip it
                                //
                                Pos = Pos + 1;
                            }
                            else if (tagMatch(core, layout, posStartTag, searchId, searchClass))
                            {
                                //
                                // match, return with this position
                                //
                                returnPos = Pos;
                                break;
                            }
                            else
                            {
                                //
                                // no match, skip this and go to the next
                                //
                                Pos = Pos + 1;
                            }
                        }
                        LoopPtr = LoopPtr + 1;
                    } while (LoopPtr < 1000);
                    //
                    //
                    //
                    if (LoopPtr >= 10000)
                    {
                        LogController.logError(core, new GenericException("Tag limit of 10000 tags per block reached."));
                    }
                }
                //
                returnValue = returnPos;
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(returnValue);
        }
        //
        //====================================================================================================
        private static bool tagMatch(CoreController core, string layout, int posStartTag, string searchId, string searchClass)
        {
            bool returnValue = false;

            try {
                const string attrAllowedChars = "abcdefghijklmnopqrstuvwzyz-_";
                string       Tag           = null;
                string       tagLower      = null;
                int          Pos           = 0;
                string       Delimiter     = null;
                string       testChar      = null;
                int          tagLength     = 0;
                int          posValueStart = 0;
                string       testValue     = null;
                string[]     testValues    = null;
                int          testCnt       = 0;
                int          Ptr           = 0;
                //
                returnValue = false;
                Pos         = GenericController.strInstr(posStartTag, layout, ">");
                if (Pos > 0)
                {
                    returnValue = true;
                    Tag         = layout.Substring(posStartTag - 1, Pos - posStartTag + 1);
                    tagLower    = GenericController.toLCase(Tag);
                    tagLength   = Tag.Length;
                    //
                    // check searchId
                    //
                    if (returnValue && (!string.IsNullOrEmpty(searchId)))
                    {
                        Pos = GenericController.strInstr(1, tagLower, " id=", 1);
                        if (Pos <= 0)
                        {
                            //
                            // id required but this tag has no id attr
                            //
                            returnValue = false;
                        }
                        else
                        {
                            //
                            // test if the id attr value matches the searchClass
                            //
                            Pos       = Pos + 4;
                            Delimiter = tagLower.Substring(Pos - 1, 1);
                            testValue = "";
                            if ((Delimiter == "\"") || (Delimiter == "'"))
                            {
                                //
                                // search for end of delimited attribute value
                                //
                                posValueStart = Pos + 1;
                                do
                                {
                                    Pos      = Pos + 1;
                                    testChar = tagLower.Substring(Pos - 1, 1);
                                } while ((Pos < tagLength) && (testChar != Delimiter));
                                if (Pos >= tagLength)
                                {
                                    //
                                    // delimiter not found, html error
                                    //
                                    returnValue = false;
                                }
                                else
                                {
                                    testValue = Tag.Substring(posValueStart - 1, Pos - posValueStart);
                                }
                            }
                            else
                            {
                                //
                                // search for end of non-delimited attribute value
                                //
                                posValueStart = Pos;
                                while ((Pos < tagLength) && (isInStr(1, attrAllowedChars, tagLower.Substring(Pos - 1, 1))))
                                {
                                    Pos = Pos + 1;
                                }
                                if (Pos >= tagLength)
                                {
                                    //
                                    // delimiter not found, html error
                                    //
                                    returnValue = false;
                                }
                                else
                                {
                                    testValue = Tag.Substring(posValueStart - 1, Pos - posValueStart);
                                }
                            }
                            if (returnValue && (!string.IsNullOrEmpty(testValue)))
                            {
                                //
                                //
                                //
                                if (searchId != testValue)
                                {
                                    //
                                    // there can only be one id, and this does not match
                                    //
                                    returnValue = false;
                                }
                            }
                        }
                    }
                    //
                    // check searchClass
                    //
                    if (returnValue && (!string.IsNullOrEmpty(searchClass)))
                    {
                        Pos = GenericController.strInstr(1, tagLower, " class=", 1);
                        if (Pos <= 0)
                        {
                            //
                            // class required but this tag has no class attr
                            //
                            returnValue = false;
                        }
                        else
                        {
                            //
                            // test if the class attr value matches the searchClass
                            //
                            Pos       = Pos + 7;
                            Delimiter = tagLower.Substring(Pos - 1, 1);
                            testValue = "";
                            if ((Delimiter == "\"") || (Delimiter == "'"))
                            {
                                //
                                // search for end of delimited attribute value
                                //
                                posValueStart = Pos + 1;
                                do
                                {
                                    Pos      = Pos + 1;
                                    testChar = tagLower.Substring(Pos - 1, 1);
                                } while ((Pos < tagLength) && (testChar != Delimiter));
                                if (Pos >= tagLength)
                                {
                                    //
                                    // delimiter not found, html error
                                    //
                                    returnValue = false;
                                }
                                else
                                {
                                    testValue = Tag.Substring(posValueStart - 1, Pos - posValueStart);
                                }
                            }
                            else
                            {
                                //
                                // search for end of non-delimited attribute value
                                //
                                posValueStart = Pos;
                                while ((Pos < tagLength) && (isInStr(1, attrAllowedChars, tagLower.Substring(Pos - 1, 1))))
                                {
                                    Pos = Pos + 1;
                                }
                                if (Pos >= tagLength)
                                {
                                    //
                                    // delimiter not found, html error
                                    //
                                    returnValue = false;
                                }
                                else
                                {
                                    testValue = Tag.Substring(posValueStart - 1, Pos - posValueStart);
                                }
                            }
                            if (returnValue && (!string.IsNullOrEmpty(testValue)))
                            {
                                //
                                //
                                //
                                testValues = testValue.Split(' ');
                                testCnt    = testValues.GetUpperBound(0) + 1;
                                for (Ptr = 0; Ptr < testCnt; Ptr++)
                                {
                                    if (searchClass == testValues[Ptr])
                                    {
                                        break;
                                    }
                                }
                                if (Ptr >= testCnt)
                                {
                                    returnValue = false;
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(returnValue);
        }
Beispiel #23
0
        //
        //====================================================================================================
        /// <summary>
        /// Send email by SMTP. return 'ok' if success, else return a user compatible error message
        /// </summary>
        public static bool send(CoreController core, AmazonSimpleEmailServiceClient client, EmailSendDomainModel email, ref string reasonForFail)
        {
            string logShortDetail = ", subject [" + email.subject + "], toMemberId [" + email.toMemberId + "], toAddress [" + email.toAddress + "], fromAddress [" + email.fromAddress + "]";
            string logLongDetail  = logShortDetail + ", BounceAddress [" + email.bounceAddress + "], replyToAddress [" + email.replyToAddress + "]";

            reasonForFail = "";
            try {
                if (core.mockEmail)
                {
                    //
                    // -- for unit tests, mock interface by adding email to core.mockSmptList
                    core.mockEmailList.Add(new MockEmailClass {
                        email = email
                    });
                    return(true);
                }
                //
                // -- test for email bounce block list
                using (var cs = core.cpParent.CSNew()) {
                    string sql = "select count(*) as cnt from EmailBounceList where name like" + DbController.encodeSqlTextLike(email.toAddress) + " and transient=0";
                    if (cs.OpenSQL(sql))
                    {
                        if (!cs.GetInteger("cnt").Equals(0))
                        {
                            reasonForFail = "Recipient email address is on the email block list";
                            return(false);
                        }
                    }
                }
                //
                // -- send email
                Body messageBody = new Body {
                };
                if (!string.IsNullOrEmpty(email.htmlBody))
                {
                    messageBody.Html = new Content {
                        Charset = "UTF-8", Data = email.htmlBody
                    };
                }
                if (!string.IsNullOrEmpty(email.textBody))
                {
                    messageBody.Text = new Content {
                        Charset = "UTF-8", Data = email.textBody
                    };
                }
                var sendRequest = new SendEmailRequest {
                    Source      = email.fromAddress,
                    Destination = new Destination {
                        ToAddresses = new List <string> {
                            email.toAddress
                        }
                    },
                    Message = new Message {
                        Subject = new Content(email.subject),
                        Body    = messageBody
                    }
                };
                try {
                    LogController.logInfo(core, "Sending SES email" + logShortDetail);
                    var response = client.SendEmail(sendRequest);
                    return(true);
                } catch (Exception ex) {
                    reasonForFail = "Error sending email [" + ex.Message + "]" + logShortDetail;
                    LogController.logError(core, "Unexpected exception during SES send" + logLongDetail + ", exception [" + ex + "]");
                    return(false);
                }
            } catch (Exception ex) {
                reasonForFail = "Error sending email [" + ex.Message + "]" + logShortDetail;
                LogController.logError(core, "Unexpected exception during SES configure" + logLongDetail + ", exception [" + ex + "]");
                return(false);
            }
        }
Beispiel #24
0
        //====================================================================================================
        /// <summary>
        /// main_GetPageDynamicLinkWithArgs
        /// </summary>
        /// <param name="contentControlID"></param>
        /// <param name="PageID"></param>
        /// <param name="DefaultLink"></param>
        /// <param name="IsRootPage"></param>
        /// <param name="templateId"></param>
        /// <param name="SectionID"></param>
        /// <param name="MenuLinkOverRide"></param>
        /// <param name="UseContentWatchLink"></param>
        /// <returns></returns>
        internal string main_GetPageDynamicLinkWithArgs(int contentControlID, int PageID, string DefaultLink, bool IsRootPage, int templateId, int SectionID, string MenuLinkOverRide, bool UseContentWatchLink)
        {
            string resultLink = "";

            try {
                if (!string.IsNullOrEmpty(MenuLinkOverRide))
                {
                    //
                    // -- redirect to this page record
                    resultLink = "?rc=" + contentControlID + "&ri=" + PageID;
                }
                else
                {
                    if (UseContentWatchLink)
                    {
                        //
                        // -- Legacy method - lookup link from a table set during the last page hit
                        resultLink = getContentWatchLinkByID(contentControlID, PageID, DefaultLink, false);
                    }
                    else
                    {
                        //
                        // -- Current method - all pages are in the Template, Section, Page structure
                        if (templateId != 0)
                        {
                            PageTemplateModel template = DbBaseModel.create <PageTemplateModel>(core.cpParent, templateId);
                            if (template != null)
                            {
                                resultLink = ""; // template.Link
                            }
                        }
                        if (string.IsNullOrEmpty(resultLink))
                        {
                            //
                            // -- not found, use default
                            if (!string.IsNullOrEmpty(DefaultLink))
                            {
                                //
                                // if default given, use that
                                resultLink = DefaultLink;
                            }
                            else
                            {
                                //
                                // -- fallback, use content watch
                                resultLink = getContentWatchLinkByID(contentControlID, PageID, "", false);
                            }
                        }
                        if ((PageID == 0) || (IsRootPage))
                        {
                            //
                            // -- Link to Root Page, no bid, and include sectionid if not 0
                            if (IsRootPage && (SectionID != 0))
                            {
                                resultLink = GenericController.modifyLinkQuery(resultLink, "sid", SectionID.ToString(), true);
                            }
                            resultLink = GenericController.modifyLinkQuery(resultLink, rnPageId, "", false);
                        }
                        else
                        {
                            resultLink = GenericController.modifyLinkQuery(resultLink, rnPageId, GenericController.encodeText(PageID), true);
                            if (PageID != 0)
                            {
                                resultLink = GenericController.modifyLinkQuery(resultLink, "sid", "", false);
                            }
                        }
                    }
                }
                resultLink = GenericController.encodeVirtualPath(resultLink, core.appConfig.cdnFileUrl, appRootPath, core.webServer.requestDomain);
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(resultLink);
        }
        //
        //====================================================================================================
        /// <summary>
        /// add a link alias to a page as the primary
        /// </summary>
        public static void addLinkAlias(CoreController core, string linkAlias, int pageId, string queryStringSuffix, bool overRideDuplicate, bool dupCausesWarning, ref string return_WarningMessage)
        {
            string hint = "";

            try {
                //
                LogController.logTrace(core, "addLinkAlias, enter, linkAlias [" + linkAlias + "], pageID [" + pageId + "], queryStringSuffix [" + queryStringSuffix + "], overRideDuplicate [" + overRideDuplicate + "], dupCausesWarning [" + dupCausesWarning + "]");
                //
                const string SafeStringLc   = "0123456789abcdefghijklmnopqrstuvwxyz-_/.";
                bool         AllowLinkAlias = core.siteProperties.getBoolean("allowLinkAlias", true);
                //
                string normalizedLinkAlias = linkAlias;
                if (!string.IsNullOrEmpty(normalizedLinkAlias))
                {
                    //
                    // remove nonsafe URL characters
                    string Src = normalizedLinkAlias.Replace('\t', ' ');
                    normalizedLinkAlias = "";
                    for (int srcPtr = 0; srcPtr < Src.Length; srcPtr++)
                    {
                        string TestChr = Src.Substring(srcPtr, 1).ToLowerInvariant();
                        if (!SafeStringLc.Contains(TestChr))
                        {
                            TestChr = "\t";
                        }
                        normalizedLinkAlias += TestChr;
                    }
                    int Ptr = 0;
                    while (normalizedLinkAlias.Contains("\t\t") && (Ptr < 100))
                    {
                        normalizedLinkAlias = GenericController.strReplace(normalizedLinkAlias, "\t\t", "\t");
                        Ptr = Ptr + 1;
                    }
                    if (normalizedLinkAlias.Substring(normalizedLinkAlias.Length - 1) == "\t")
                    {
                        normalizedLinkAlias = normalizedLinkAlias.left(normalizedLinkAlias.Length - 1);
                    }
                    if (normalizedLinkAlias.left(1) == "\t")
                    {
                        normalizedLinkAlias = normalizedLinkAlias.Substring(1);
                    }
                    normalizedLinkAlias = GenericController.strReplace(normalizedLinkAlias, "\t", "-");
                    if (!string.IsNullOrEmpty(normalizedLinkAlias))
                    {
                        if (normalizedLinkAlias.left(1) != "/")
                        {
                            normalizedLinkAlias = "/" + normalizedLinkAlias;
                        }
                        //
                        LogController.logTrace(core, "addLinkAlias, normalized normalizedLinkAlias [" + normalizedLinkAlias + "]");
                        //
                        // Make sure there is not a folder or page in the wwwroot that matches this Alias
                        //
                        if (GenericController.toLCase(normalizedLinkAlias) == GenericController.toLCase("/" + core.appConfig.name))
                        {
                            //
                            // This alias points to the cclib folder
                            //
                            if (AllowLinkAlias)
                            {
                                return_WarningMessage = ""
                                                        + "The Link Alias being created (" + normalizedLinkAlias + ") can not be used because there is a virtual directory in your website directory that already uses this name."
                                                        + " Please change it to ensure the Link Alias is unique. To set or change the Link Alias, use the Link Alias tab and select a name not used by another page.";
                            }
                        }
                        else if (GenericController.toLCase(normalizedLinkAlias) == "/cclib")
                        {
                            //
                            // This alias points to the cclib folder
                            //
                            if (AllowLinkAlias)
                            {
                                return_WarningMessage = ""
                                                        + "The Link Alias being created (" + normalizedLinkAlias + ") can not be used because there is a virtual directory in your website directory that already uses this name."
                                                        + " Please change it to ensure the Link Alias is unique. To set or change the Link Alias, use the Link Alias tab and select a name not used by another page.";
                            }
                        }
                        else if (core.wwwFiles.pathExists(core.appConfig.localWwwPath + "\\" + normalizedLinkAlias.Substring(1)))
                        {
                            //
                            // This alias points to a different link, call it an error
                            //
                            if (AllowLinkAlias)
                            {
                                return_WarningMessage = ""
                                                        + "The Link Alias being created (" + normalizedLinkAlias + ") can not be used because there is a folder in your website directory that already uses this name."
                                                        + " Please change it to ensure the Link Alias is unique. To set or change the Link Alias, use the Link Alias tab and select a name not used by another page.";
                            }
                        }
                        else
                        {
                            //
                            // Make sure there is one here for this
                            //
                            bool flushLinkAliasCache = false;
                            int  linkAliasId         = 0;
                            using (var csData = new CsModel(core)) {
                                csData.open("Link Aliases", "name=" + DbController.encodeSQLText(normalizedLinkAlias), "", false, 0, "Name,PageID,QueryStringSuffix");
                                if (!csData.ok())
                                {
                                    //
                                    LogController.logTrace(core, "addLinkAlias, not found in Db, add");
                                    //
                                    // Alias not found, create a Link Aliases
                                    //
                                    csData.close();
                                    csData.insert("Link Aliases");
                                    if (csData.ok())
                                    {
                                        csData.set("Name", normalizedLinkAlias);
                                        csData.set("Pageid", pageId);
                                        csData.set("QueryStringSuffix", queryStringSuffix);
                                        flushLinkAliasCache = true;
                                    }
                                }
                                else
                                {
                                    int    recordPageId = csData.getInteger("pageID");
                                    string recordQss    = csData.getText("QueryStringSuffix").ToLowerInvariant();
                                    //
                                    LogController.logTrace(core, "addLinkAlias, linkalias record found by its name, record recordPageId [" + recordPageId + "], record QueryStringSuffix [" + recordQss + "]");
                                    //
                                    // Alias found, verify the pageid & QueryStringSuffix
                                    //
                                    int  CurrentLinkAliasId = 0;
                                    bool resaveLinkAlias    = false;
                                    if ((recordQss == queryStringSuffix.ToLowerInvariant()) && (pageId == recordPageId))
                                    {
                                        CurrentLinkAliasId = csData.getInteger("id");
                                        //
                                        LogController.logTrace(core, "addLinkAlias, linkalias matches name, pageid, and querystring of linkalias [" + CurrentLinkAliasId + "]");
                                        //
                                        // it maches a current entry for this link alias, if the current entry is not the highest number id,
                                        //   remove it and add this one
                                        //
                                        string sql = "select top 1 id from ccLinkAliases where (pageid=" + recordPageId + ")and(QueryStringSuffix=" + DbController.encodeSQLText(queryStringSuffix) + ") order by id desc";
                                        using (var CS3 = new CsModel(core)) {
                                            CS3.openSql(sql);
                                            if (CS3.ok())
                                            {
                                                resaveLinkAlias = (CurrentLinkAliasId != CS3.getInteger("id"));
                                            }
                                        }
                                        if (resaveLinkAlias)
                                        {
                                            //
                                            LogController.logTrace(core, "addLinkAlias, another link alias matches this pageId and QS. Move this to the top position");
                                            //
                                            core.db.executeNonQuery("delete from ccLinkAliases where id=" + CurrentLinkAliasId);
                                            using (var CS3 = new CsModel(core)) {
                                                CS3.insert("Link Aliases");
                                                if (CS3.ok())
                                                {
                                                    CS3.set("Name", normalizedLinkAlias);
                                                    CS3.set("Pageid", pageId);
                                                    CS3.set("QueryStringSuffix", queryStringSuffix);
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //
                                        LogController.logTrace(core, "addLinkAlias, linkalias matches name, but pageid and querystring are different. Add this a newest linkalias");
                                        //
                                        // link alias matches, but id/qs does not -- this is either a change, or a duplicate that needs to be blocked
                                        //
                                        if (overRideDuplicate)
                                        {
                                            //
                                            LogController.logTrace(core, "addLinkAlias, overRideDuplicate true, change the Link Alias to the new link");
                                            //
                                            // change the Link Alias to the new link
                                            csData.set("Pageid", pageId);
                                            csData.set("QueryStringSuffix", queryStringSuffix);
                                            flushLinkAliasCache = true;
                                        }
                                        else if (dupCausesWarning)
                                        {
                                            //
                                            LogController.logTrace(core, "addLinkAlias, overRideDuplicate false, dupCausesWarning true, just return user warning if this is from admin");
                                            //
                                            if (recordPageId == 0)
                                            {
                                                int PageContentCId = Models.Domain.ContentMetadataModel.getContentId(core, "Page Content");
                                                return_WarningMessage = ""
                                                                        + "This page has been saved, but the Link Alias could not be created (" + normalizedLinkAlias + ") because it is already in use for another page."
                                                                        + " To use Link Aliasing (friendly page names) for this page, the Link Alias value must be unique on this site. To set or change the Link Alias, clicke the Link Alias tab and select a name not used by another page or a folder in your website.";
                                            }
                                            else
                                            {
                                                int PageContentCid = Models.Domain.ContentMetadataModel.getContentId(core, "Page Content");
                                                return_WarningMessage = ""
                                                                        + "This page has been saved, but the Link Alias could not be created (" + normalizedLinkAlias + ") because it is already in use for another page (<a href=\"?af=4&cid=" + PageContentCid + "&id=" + recordPageId + "\">edit</a>)."
                                                                        + " To use Link Aliasing (friendly page names) for this page, the Link Alias value must be unique. To set or change the Link Alias, click the Link Alias tab and select a name not used by another page or a folder in your website.";
                                            }
                                        }
                                    }
                                }
                                linkAliasId = csData.getInteger("id");
                                csData.close();
                            }
                            if (flushLinkAliasCache)
                            {
                                //
                                // -- invalidate all linkAlias
                                core.cache.invalidateDbRecord(linkAliasId, LinkAliasModel.tableMetadata.tableNameLower);
                                //
                                // -- invalidate routemap
                                Models.Domain.RouteMapModel.invalidateCache(core);
                                core.routeMapCacheClear();
                            }
                        }
                    }
                }
                //
                LogController.logTrace(core, "addLinkAlias, exit");
                //
            } catch (Exception ex) {
                LogController.logError(core, ex, "addLinkAlias exception, hint [" + hint + "]");
                throw;
            }
        }
Beispiel #26
0
 /// <summary>
 /// Appends a log file in the /alarms folder in program files. The diagnostic monitor should signal a fail.
 /// </summary>
 /// <param name="core"></param>
 /// <param name="cause"></param>
 public static void logAlarm(CoreController core, string cause)
 {
     LogController.logFatal(core, "logAlarm: " + cause);
     core.programDataFiles.appendFile("Alarms/", "LogAlarm called, cause [" + cause + "]");
 }
Beispiel #27
0
        //
        //=============================================================================
        /// <summary>
        /// Executes the current route. To determine the route:
        /// route can be from URL, or from routeOverride
        /// how to process route
        /// -- urlParameters - /urlParameter(0)/urlParameter(1)/etc.
        /// -- first try full url, then remove them from the left and test until last, try just urlParameter(0)
        /// ---- so url /a/b/c, with addon /a and addon /a/b -> would run addon /a/b
        ///
        /// </summary>
        /// <returns>The doc created by the default addon. (html, json, etc)</returns>
        public static string executeRoute(CoreController core, string routeOverride = "")
        {
            string result = "";
            var    sw     = new Stopwatch();

            sw.Start();
            LogController.log(core, "CoreController executeRoute, enter", BaseClasses.CPLogBaseClass.LogLevel.Trace);
            try {
                if (core.appConfig != null)
                {
                    //
                    // -- test fix for 404 response during routing - could it be a response left over from processing before we are called
                    core.webServer.setResponseStatus(WebServerController.httpResponseStatus200_Success);
                    //
                    // -- execute intercept methods first, like login, that run before the route that returns the page
                    // -- intercept routes should be addons alos
                    //
                    // -- determine the route: try routeOverride
                    string normalizedRoute = GenericController.normalizeRoute(routeOverride);
                    if (string.IsNullOrEmpty(normalizedRoute))
                    {
                        //
                        // -- no override, try argument route (remoteMethodAddon=)
                        normalizedRoute = GenericController.normalizeRoute(core.docProperties.getText(RequestNameRemoteMethodAddon));
                        if (string.IsNullOrEmpty(normalizedRoute))
                        {
                            //
                            // -- no override or argument, use the url as the route
                            normalizedRoute = GenericController.normalizeRoute(core.webServer.requestPathPage.ToLowerInvariant());
                        }
                    }
                    //
                    // -- legacy ajaxfn methods
                    string AjaxFunction = core.docProperties.getText(RequestNameAjaxFunction);
                    if (!string.IsNullOrEmpty(AjaxFunction))
                    {
                        //
                        // -- Need to be converted to Url parameter addons
                        switch ((AjaxFunction))
                        {
                        case ajaxGetFieldEditorPreferenceForm: {
                            //
                            // moved to Addons.AdminSite
                            return((new Contensive.Processor.Addons.AdminSite.GetFieldEditorPreference()).Execute(core.cpParent).ToString());
                        }

                        case AjaxGetDefaultAddonOptionString: {
                            //
                            // moved to Addons.AdminSite
                            return((new Contensive.Processor.Addons.AdminSite.GetAjaxDefaultAddonOptionStringClass()).Execute(core.cpParent).ToString());
                        }

                        case AjaxSetVisitProperty: {
                            //
                            // moved to Addons.AdminSite
                            return((new Contensive.Processor.Addons.AdminSite.SetAjaxVisitPropertyClass()).Execute(core.cpParent).ToString());
                        }

                        case AjaxGetVisitProperty: {
                            //
                            // moved to Addons.AdminSite
                            return((new Contensive.Processor.Addons.AdminSite.GetAjaxVisitPropertyClass()).Execute(core.cpParent).ToString());
                        }

                        case AjaxData: {
                            //
                            // moved to Addons.AdminSite
                            return((new Contensive.Processor.Addons.AdminSite.ProcessAjaxDataClass()).Execute(core.cpParent).ToString());
                        }

                        case AjaxPing: {
                            //
                            // moved to Addons.AdminSite
                            return((new Contensive.Processor.Addons.AdminSite.GetOKClass()).Execute(core.cpParent).ToString());
                        }

                        case AjaxOpenIndexFilter: {
                            //
                            // moved to Addons.AdminSite
                            return((new Contensive.Processor.Addons.AdminSite.OpenAjaxIndexFilterClass()).Execute(core.cpParent).ToString());
                        }

                        case AjaxOpenIndexFilterGetContent: {
                            //
                            // moved to Addons.AdminSite
                            return((new Contensive.Processor.Addons.AdminSite.OpenAjaxIndexFilterGetContentClass()).Execute(core.cpParent).ToString());
                        }

                        case AjaxCloseIndexFilter: {
                            //
                            // moved to Addons.AdminSite
                            return((new Contensive.Processor.Addons.AdminSite.CloseAjaxIndexFilterClass()).Execute(core.cpParent).ToString());
                        }

                        default: {
                            //
                            // -- unknown method, log warning
                            return(string.Empty);
                        }
                        }
                    }
                    //
                    // -- legacy email intercept methods
                    if (core.docProperties.getInteger(rnEmailOpenFlag) > 0)
                    {
                        //
                        // -- Process Email Open
                        return((new Contensive.Processor.Addons.Primitives.OpenEmailClass()).Execute(core.cpParent).ToString());
                    }
                    if (core.docProperties.getInteger(rnEmailClickFlag) > 0)
                    {
                        //
                        // -- Process Email click, execute and continue
                        (new Contensive.Processor.Addons.Primitives.ClickEmailClass()).Execute(core.cpParent).ToString();
                    }
                    if (!string.IsNullOrWhiteSpace(core.docProperties.getText(rnEmailBlockRecipientEmail)))
                    {
                        //
                        // -- Process Email block
                        return((new Contensive.Processor.Addons.Primitives.BlockEmailClass()).Execute(core.cpParent).ToString());
                    }
                    //
                    // -- legacy form process methods
                    string formType = core.docProperties.getText(core.docProperties.getText("ccformsn") + "type");
                    if (!string.IsNullOrEmpty(formType))
                    {
                        //
                        // set the meta content flag to show it is not needed for the head tag
                        switch (formType)
                        {
                        case FormTypeAddonStyleEditor: {
                            //
                            result = (new Contensive.Processor.Addons.Primitives.ProcessAddonStyleEditorClass()).Execute(core.cpParent).ToString();
                            break;
                        }

                        case FormTypeAddonSettingsEditor: {
                            //
                            result = (new Contensive.Processor.Addons.Primitives.ProcessAddonSettingsEditorClass()).Execute(core.cpParent).ToString();
                            break;
                        }

                        case FormTypeSendPassword: {
                            //
                            result = (new Contensive.Processor.Addons.Primitives.processSendPasswordFormClass()).Execute(core.cpParent).ToString();
                            break;
                        }

                        case FormTypeLogin:
                        case "l09H58a195": {
                            //
                            result = (new Contensive.Processor.Addons.Primitives.ProcessLoginDefaultClass()).Execute(core.cpParent).ToString();
                            break;
                        }

                        case FormTypeToolsPanel: {
                            //
                            result = (new Contensive.Processor.Addons.Primitives.processFormToolsPanelClass()).Execute(core.cpParent).ToString();
                            break;
                        }

                        case FormTypePageAuthoring: {
                            //
                            result = (new Contensive.Processor.Addons.Primitives.processFormQuickEditingClass()).Execute(core.cpParent).ToString();
                            break;
                        }

                        case FormTypeActiveEditor: {
                            //
                            result = (new Contensive.Processor.Addons.Primitives.ProcessActiveEditorClass()).Execute(core.cpParent).ToString();
                            break;
                        }

                        case FormTypeSiteStyleEditor: {
                            //
                            result = (new Contensive.Processor.Addons.Primitives.ProcessSiteStyleEditorClass()).Execute(core.cpParent).ToString();
                            break;
                        }

                        case FormTypeHelpBubbleEditor: {
                            //
                            result = (new Contensive.Processor.Addons.Primitives.processHelpBubbleEditorClass()).Execute(core.cpParent).ToString();
                            break;
                        }

                        case FormTypeJoin: {
                            //
                            result = (new Contensive.Processor.Addons.Primitives.processJoinFormClass()).Execute(core.cpParent).ToString();
                            break;
                        }

                        default: {
                            break;
                        }
                        }
                    }
                    //
                    // -- legacy methods=
                    string HardCodedPage = core.docProperties.getText(RequestNameHardCodedPage);
                    if (!string.IsNullOrEmpty(HardCodedPage))
                    {
                        switch (GenericController.toLCase(HardCodedPage))
                        {
                        case HardCodedPageLogout: {
                            //
                            // -- logout intercept
                            (new Contensive.Processor.Addons.Primitives.ProcessLogoutMethodClass()).Execute(core.cpParent);
                            //
                            // -- redirect to the route without the method
                            string routeWithoutQuery = modifyLinkQuery(core.webServer.requestUrlSource, "method", "", false);
                            core.webServer.redirect(routeWithoutQuery, "Redirect to route without 'method' because login was successful.");
                            return(string.Empty);
                        }

                        case HardCodedPageSendPassword: {
                            //
                            return((new Contensive.Processor.Addons.Primitives.ProcessSendPasswordMethodClass()).Execute(core.cpParent).ToString());
                        }

                        case HardCodedPageResourceLibrary: {
                            //
                            return((new Contensive.Processor.Addons.Primitives.ProcessResourceLibraryMethodClass()).Execute(core.cpParent).ToString());
                        }

                        case HardCodedPageLoginDefault: {
                            //
                            if (core.session.isAuthenticated)
                            {
                                //
                                // -- if authenticated, redirect to the route without the method
                                string routeWithoutQuery = modifyLinkQuery(core.webServer.requestUrlSource, "method", "", false);
                                core.webServer.redirect(routeWithoutQuery, "Redirect to route without 'method' because login was successful.");
                                return(string.Empty);
                            }
                            //
                            // -- process the login method, or return the login form
                            return((new Contensive.Processor.Addons.Primitives.ProcessLoginDefaultMethodClass()).Execute(core.cpParent).ToString());
                        }

                        case HardCodedPageLogin: {
                            //
                            if (core.session.isAuthenticated)
                            {
                                //
                                // -- if authenticated, redirect to the route without the method
                                string routeWithoutQuery = modifyLinkQuery(core.webServer.requestUrlSource, "method", "", false);
                                core.webServer.redirect(routeWithoutQuery, "Redirect to route without 'method' because login was successful.");
                                return(string.Empty);
                            }
                            //
                            // -- process the login method, or return the login form
                            return((new Contensive.Processor.Addons.Primitives.ProcessLoginMethodClass()).Execute(core.cpParent).ToString());
                        }

                        case HardCodedPageLogoutLogin: {
                            //
                            return((new Contensive.Processor.Addons.Primitives.ProcessLogoutLoginMethodClass()).Execute(core.cpParent).ToString());
                        }

                        case HardCodedPageSiteExplorer: {
                            //
                            return((new Contensive.Processor.Addons.Primitives.ProcessSiteExplorerMethodClass()).Execute(core.cpParent).ToString());
                        }

                        case HardCodedPageStatus: {
                            //
                            return((new Contensive.Processor.Addons.Diagnostics.StatusClass()).Execute(core.cpParent).ToString());
                        }

                        case HardCodedPageRedirect: {
                            //
                            return((new Contensive.Processor.Addons.Primitives.ProcessRedirectMethodClass()).Execute(core.cpParent).ToString());
                        }

                        case HardCodedPageExportAscii: {
                            //
                            return((new Contensive.Processor.Addons.Primitives.ProcessExportAsciiMethodClass()).Execute(core.cpParent).ToString());
                        }

                        default: {
                            break;
                        }
                        }
                    }
                    //
                    // -- try route Dictionary (addons, admin, link forwards, link alias), from full route to first segment one at a time
                    // -- so route /this/and/that would first test /this/and/that, then test /this/and, then test /this
                    string routeTest  = normalizedRoute;
                    bool   routeFound = false;
                    int    routeCnt   = 100;
                    do
                    {
                        routeFound = core.routeMap.routeDictionary.ContainsKey(routeTest);
                        if (routeFound)
                        {
                            break;
                        }
                        if (routeTest.IndexOf("/") < 0)
                        {
                            break;
                        }
                        routeTest = routeTest.left(routeTest.LastIndexOf("/"));
                        routeCnt -= 1;
                    } while ((routeCnt > 0) && (!routeFound));
                    //
                    // -- execute route
                    if (routeFound)
                    {
                        RouteMapModel.RouteClass route = core.routeMap.routeDictionary[routeTest];
                        switch (route.routeType)
                        {
                        case RouteMapModel.RouteTypeEnum.admin: {
                            //
                            // -- admin site
                            AddonModel addon = DbBaseModel.create <AddonModel>(core.cpParent, addonGuidAdminSite);
                            if (addon == null)
                            {
                                LogController.logError(core, new GenericException("The admin site addon could not be found by guid [" + addonGuidAdminSite + "]."));
                                return("The default admin site addon could not be found. Please run an upgrade on this application to restore default services (command line> cc -a appName -r )");
                            }
                            else
                            {
                                return(core.addon.execute(addon, new CPUtilsBaseClass.addonExecuteContext {
                                        addonType = CPUtilsBaseClass.addonContext.ContextAdmin,
                                        errorContextMessage = "calling admin route [" + addonGuidAdminSite + "] during execute route method"
                                    }));
                            }
                        }

                        case RouteMapModel.RouteTypeEnum.remoteMethod: {
                            //
                            // -- remote method
                            AddonModel addon = core.addonCache.getAddonById(route.remoteMethodAddonId);
                            if (addon == null)
                            {
                                LogController.logError(core, new GenericException("The addon for remoteMethodAddonId [" + route.remoteMethodAddonId + "] could not be opened."));
                                return("");
                            }
                            else
                            {
                                CPUtilsBaseClass.addonExecuteContext executeContext = new CPUtilsBaseClass.addonExecuteContext {
                                    addonType         = CPUtilsBaseClass.addonContext.ContextRemoteMethodJson,
                                    cssContainerClass = "",
                                    cssContainerId    = "",
                                    hostRecord        = new CPUtilsBaseClass.addonExecuteHostRecordContext {
                                        contentName = core.docProperties.getText("hostcontentname"),
                                        fieldName   = "",
                                        recordId    = core.docProperties.getInteger("HostRecordID")
                                    },
                                    errorContextMessage = "calling remote method addon [" + route.remoteMethodAddonId + "] during execute route method"
                                };
                                return(core.addon.execute(addon, executeContext));
                            }
                        }

                        case RouteMapModel.RouteTypeEnum.linkAlias: {
                            //
                            // - link alias
                            // -- all the query string values have already been added to doc properties, so do not over write them.
                            // -- consensus is that since the link alias (permalink, long-tail url, etc) comes first on the left, that the querystring should override
                            // -- so http://www.mySite.com/My-Blog-Post?bid=9 means use the bid not the bid from the link-alias
                            LinkAliasModel linkAlias = DbBaseModel.create <LinkAliasModel>(core.cpParent, route.linkAliasId);
                            if (linkAlias != null)
                            {
                                // -- set the link alias page number, unless it has been overridden
                                if (!core.docProperties.containsKey("bid"))
                                {
                                    core.docProperties.setProperty("bid", linkAlias.pageId);
                                }
                                if (!string.IsNullOrWhiteSpace(linkAlias.queryStringSuffix))
                                {
                                    string[] keyValuePairs = linkAlias.queryStringSuffix.Split('&');
                                    // -- iterate through all the key=value pairs
                                    foreach (var keyEqualsValue in keyValuePairs)
                                    {
                                        string[] keyValue = keyEqualsValue.Split('=');
                                        if (!string.IsNullOrEmpty(keyValue[0]))
                                        {
                                            if (!core.docProperties.containsKey(keyValue[0]))
                                            {
                                                if (keyValue.Length > 1)
                                                {
                                                    core.docProperties.setProperty(keyValue[0], keyValue[1]);
                                                }
                                                else
                                                {
                                                    core.docProperties.setProperty(keyValue[0], string.Empty);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        }

                        case RouteMapModel.RouteTypeEnum.linkForward: {
                            //
                            // -- link forward
                            LinkForwardModel linkForward = DbBaseModel.create <LinkForwardModel>(core.cpParent, route.linkForwardId);
                            return(core.webServer.redirect(linkForward.destinationLink, "Link Forward #" + linkForward.id + ", " + linkForward.name));
                        }

                        default: {
                            break;
                        }
                        }
                    }
                    //
                    // -- default route
                    int defaultAddonId = 0;
                    if (core.doc.domain != null)
                    {
                        defaultAddonId = core.doc.domain.defaultRouteId;
                    }
                    if (defaultAddonId == 0)
                    {
                        defaultAddonId = core.siteProperties.defaultRouteId;
                    }
                    if (defaultAddonId > 0)
                    {
                        //
                        // -- default route is run if no other route is found, which includes the route=defaultPage (default.aspx)
                        CPUtilsBaseClass.addonExecuteContext executeContext = new CPUtilsBaseClass.addonExecuteContext {
                            addonType         = CPUtilsBaseClass.addonContext.ContextPage,
                            cssContainerClass = "",
                            cssContainerId    = "",
                            hostRecord        = new CPUtilsBaseClass.addonExecuteHostRecordContext {
                                contentName = "",
                                fieldName   = "",
                                recordId    = 0
                            },
                            errorContextMessage = "calling default route addon [" + defaultAddonId + "] during execute route method"
                        };
                        return(core.addon.execute(DbBaseModel.create <AddonModel>(core.cpParent, defaultAddonId), executeContext));
                    }
                    //
                    // -- no route
                    LogController.logWarn(core, "executeRoute called with an unknown route [" + normalizedRoute + "], and no default route is set to handle it. Go to the admin site, open preferences and set a detault route. Typically this is Page Manager for websites or an authorization error for remote applications.");
                    result = "<p>This site is not configured for website traffic. Please set the default route.</p>";
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
            } finally {
                // if (core.doc.routeDictionaryChanges) { DefaultSite.configurationClass.loadRouteMap(cp))}
                LogController.log(core, "CoreController executeRoute, exit", BaseClasses.CPLogBaseClass.LogLevel.Trace);
            }
            return(result);
        }
        //
        //==================================================================================================
        /// <summary>
        /// Remove this record from all watch lists
        /// </summary>
        /// <param name="ContentID"></param>
        /// <param name="RecordID"></param>
        //
        public static void deleteContentRules(CoreController core, ContentMetadataModel meta, int RecordID)
        {
            try {
                if (meta == null)
                {
                    return;
                }
                if (RecordID <= 0)
                {
                    throw new GenericException("RecordID [" + RecordID + "] where blank");
                }
                string ContentRecordKey = meta.id.ToString() + "." + RecordID.ToString();
                //
                // ----- Table Specific rules
                switch (meta.tableName.ToUpperInvariant())
                {
                case "CCCONTENT":
                    //
                    deleteContentRecords(core, "Group Rules", "ContentID=" + RecordID);
                    break;

                case "CCCONTENTWATCH":
                    //
                    deleteContentRecords(core, "Content Watch List Rules", "Contentwatchid=" + RecordID);
                    break;

                case "CCCONTENTWATCHLISTS":
                    //
                    deleteContentRecords(core, "Content Watch List Rules", "Contentwatchlistid=" + RecordID);
                    break;

                case "CCGROUPS":
                    //
                    deleteContentRecords(core, "Group Rules", "GroupID=" + RecordID);
                    deleteContentRecords(core, "Library Folder Rules", "GroupID=" + RecordID);
                    deleteContentRecords(core, "Member Rules", "GroupID=" + RecordID);
                    deleteContentRecords(core, "Page Content Block Rules", "GroupID=" + RecordID);
                    break;

                case "CCLIBRARYFOLDERS":
                    //
                    deleteContentRecords(core, "Library Folder Rules", "FolderID=" + RecordID);
                    break;

                case "CCMEMBERS":
                    //
                    deleteContentRecords(core, "Member Rules", "MemberID=" + RecordID);
                    deleteContentRecords(core, "Topic Habits", "MemberID=" + RecordID);
                    deleteContentRecords(core, "Member Topic Rules", "MemberID=" + RecordID);
                    break;

                case "CCPAGECONTENT":
                    //
                    deleteContentRecords(core, "Page Content Block Rules", "RecordID=" + RecordID);
                    deleteContentRecords(core, "Page Content Topic Rules", "PageID=" + RecordID);
                    break;

                case "CCSURVEYQUESTIONS":
                    //
                    deleteContentRecords(core, "Survey Results", "QuestionID=" + RecordID);
                    break;

                case "CCSURVEYS":
                    //
                    deleteContentRecords(core, "Survey Questions", "SurveyID=" + RecordID);
                    break;

                case "CCTOPICS":
                    //
                    deleteContentRecords(core, "Topic Habits", "TopicID=" + RecordID);
                    deleteContentRecords(core, "Page Content Topic Rules", "TopicID=" + RecordID);
                    deleteContentRecords(core, "Member Topic Rules", "TopicID=" + RecordID);
                    break;
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
        }
Beispiel #29
0
        //
        //====================================================================================================
        /// <summary>
        /// download a collectionZip from the collection library to a privateFilesPath
        /// </summary>
        /// <param name="core"></param>
        /// <param name="tempFilesDownloadPath"></param>
        /// <param name="collectionGuid"></param>
        /// <param name="return_CollectionLastModifiedDate"></param>
        /// <param name="return_ErrorMessage"></param>
        /// <returns></returns>
        internal static bool downloadCollectionFromLibrary(CoreController core, string tempFilesDownloadPath, string collectionGuid, ref DateTime return_CollectionLastModifiedDate, ref string return_ErrorMessage)
        {
            bool result = false;

            try {
                //
                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", downloading collection [" + collectionGuid + "]");
                //
                // Request the Download file for this collection
                XmlDocument Doc              = new XmlDocument();
                string      URL              = "http://support.contensive.com/GetCollection?iv=" + CoreController.codeVersion() + "&guid=" + collectionGuid;
                string      errorPrefix      = "DownloadCollectionFiles, Error reading the collection library status file from the server for Collection [" + collectionGuid + "], download URL [" + URL + "]. ";
                int         downloadRetry    = 0;
                int         downloadDelay    = 2000;
                const int   downloadRetryMax = 3;
                do
                {
                    try {
                        result = true;
                        return_ErrorMessage = "";
                        //
                        // -- pause for a second between fetches to pace the server (<10 hits in 10 seconds)
                        Thread.Sleep(downloadDelay);
                        //
                        // -- download file
                        System.Net.WebRequest rq = System.Net.WebRequest.Create(URL);
                        rq.Timeout = 60000;
                        System.Net.WebResponse response = rq.GetResponse();
                        Stream        responseStream    = response.GetResponseStream();
                        XmlTextReader reader            = new XmlTextReader(responseStream);
                        Doc.Load(reader);
                        break;
                    } catch (Exception ex) {
                        //
                        // this error could be data related, and may not be critical. log issue and continue
                        downloadDelay      += 2000;
                        return_ErrorMessage = "There was an error while requesting the download details for collection [" + collectionGuid + "]";
                        result = false;
                        LogController.logInfo(core, errorPrefix + "There was a parse error reading the response [" + ex + "]");
                    }
                    downloadRetry += 1;
                } while (downloadRetry < downloadRetryMax);
                if (string.IsNullOrEmpty(return_ErrorMessage))
                {
                    //
                    // continue if no errors
                    if (Doc.DocumentElement.Name.ToLowerInvariant() != GenericController.toLCase(DownloadFileRootNode))
                    {
                        return_ErrorMessage = "The collection file from the server was not valid for collection [" + collectionGuid + "]";
                        result = false;
                        LogController.logInfo(core, errorPrefix + "The response has a basename [" + Doc.DocumentElement.Name + "] but [" + DownloadFileRootNode + "] was expected.");
                    }
                    else
                    {
                        //
                        // Parse the Download File and download each file into the working folder
                        if (Doc.DocumentElement.ChildNodes.Count == 0)
                        {
                            return_ErrorMessage = "The collection library status file from the server has a valid basename, but no childnodes.";
                            LogController.logInfo(core, errorPrefix + "The collection library status file from the server has a valid basename, but no childnodes. The collection was probably Not found");
                            result = false;
                        }
                        else
                        {
                            //
                            int CollectionFileCnt = 0;
                            foreach (XmlNode metaDataSection in Doc.DocumentElement.ChildNodes)
                            {
                                string ResourceFilename   = null;
                                string ResourceLink       = null;
                                string CollectionVersion  = null;
                                string CollectionFileLink = null;
                                string Collectionname     = null;
                                switch (GenericController.toLCase(metaDataSection.Name))
                                {
                                case "collection":
                                    //
                                    // Read in the interfaces and save to Add-ons
                                    ResourceFilename   = "";
                                    ResourceLink       = "";
                                    Collectionname     = "";
                                    collectionGuid     = "";
                                    CollectionVersion  = "";
                                    CollectionFileLink = "";
                                    foreach (XmlNode metaDataInterfaces in metaDataSection.ChildNodes)
                                    {
                                        int    Pos       = 0;
                                        string UserError = null;
                                        switch (GenericController.toLCase(metaDataInterfaces.Name))
                                        {
                                        case "name":
                                            Collectionname = metaDataInterfaces.InnerText;
                                            break;

                                        case "help":
                                            if (!string.IsNullOrWhiteSpace(metaDataInterfaces.InnerText))
                                            {
                                                core.tempFiles.saveFile(tempFilesDownloadPath + "Collection.hlp", metaDataInterfaces.InnerText);
                                            }
                                            break;

                                        case "guid":
                                            collectionGuid = metaDataInterfaces.InnerText;
                                            break;

                                        case "lastmodifieddate":
                                            return_CollectionLastModifiedDate = GenericController.encodeDate(metaDataInterfaces.InnerText);
                                            break;

                                        case "version":
                                            CollectionVersion = metaDataInterfaces.InnerText;
                                            break;

                                        case "collectionfilelink":
                                            CollectionFileLink = metaDataInterfaces.InnerText;
                                            CollectionFileCnt  = CollectionFileCnt + 1;
                                            if (!string.IsNullOrEmpty(CollectionFileLink))
                                            {
                                                Pos = CollectionFileLink.LastIndexOf("/") + 1;
                                                if ((Pos <= 0) && (Pos < CollectionFileLink.Length))
                                                {
                                                    //
                                                    // Skip this file because the collecion file link has no slash (no file)
                                                    LogController.logInfo(core, errorPrefix + "Collection [" + Collectionname + "] was not installed because the Collection File Link does not point to a valid file [" + CollectionFileLink + "]");
                                                }
                                                else
                                                {
                                                    string CollectionFilePath = tempFilesDownloadPath + CollectionFileLink.Substring(Pos);
                                                    core.tempFiles.saveHttpRequestToFile(CollectionFileLink, CollectionFilePath);
                                                }
                                            }
                                            break;

                                        case "activexdll":
                                        case "resourcelink":
                                            //
                                            // save the filenames and download them only if OKtoinstall
                                            ResourceFilename = "";
                                            ResourceLink     = "";
                                            foreach (XmlNode ActiveXNode in metaDataInterfaces.ChildNodes)
                                            {
                                                switch (GenericController.toLCase(ActiveXNode.Name))
                                                {
                                                case "filename":
                                                    ResourceFilename = ActiveXNode.InnerText;
                                                    break;

                                                case "link":
                                                    ResourceLink = ActiveXNode.InnerText;
                                                    break;
                                                }
                                            }
                                            if (string.IsNullOrEmpty(ResourceLink))
                                            {
                                                UserError = "There was an error processing a collection in the download file [" + Collectionname + "]. An ActiveXDll node with filename [" + ResourceFilename + "] contained no 'Link' attribute.";
                                                LogController.logInfo(core, errorPrefix + UserError);
                                            }
                                            else
                                            {
                                                if (string.IsNullOrEmpty(ResourceFilename))
                                                {
                                                    //
                                                    // Take Filename from Link
                                                    Pos = ResourceLink.LastIndexOf("/") + 1;
                                                    if (Pos != 0)
                                                    {
                                                        ResourceFilename = ResourceLink.Substring(Pos);
                                                    }
                                                }
                                                if (string.IsNullOrEmpty(ResourceFilename))
                                                {
                                                    UserError = "There was an error processing a collection in the download file [" + Collectionname + "]. The ActiveX filename attribute was empty, and the filename could not be read from the link [" + ResourceLink + "].";
                                                    LogController.logInfo(core, errorPrefix + UserError);
                                                }
                                                else
                                                {
                                                    core.tempFiles.saveHttpRequestToFile(ResourceLink, tempFilesDownloadPath + ResourceFilename);
                                                }
                                            }
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                            if (CollectionFileCnt == 0)
                            {
                                LogController.logInfo(core, errorPrefix + "The collection was requested and downloaded, but was not installed because the download file did not have a collection root node.");
                            }
                        }
                    }
                    //
                    // -- invalidate cache
                    core.cache.invalidateAll();
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(result);
        }
Beispiel #30
0
        //
        //====================================================================================================
        //
        public static string exportAscii_GetAsciiExport(CoreController core, string ContentName, int PageSize, int PageNumber)
        {
            string result = "";

            try {
                string Delimiter             = null;
                string Copy                  = "";
                string TableName             = null;
                string FieldNameVariant      = null;
                string FieldName             = null;
                string UcaseFieldName        = null;
                string iContentName          = null;
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                string TestFilename;
                //
                TestFilename = "AsciiExport" + GenericController.getRandomInteger(core) + ".txt";
                //
                iContentName = GenericController.encodeText(ContentName);
                if (PageSize == 0)
                {
                    PageSize = 1000;
                }
                if (PageNumber == 0)
                {
                    PageNumber = 1;
                }
                //
                // ----- Check for special case iContentNames
                //
                core.webServer.setResponseContentType("text/plain");
                core.html.enableOutputBuffer(false);
                TableName = DbController.getDbObjectTableName(MetadataController.getContentTablename(core, iContentName));
                switch (GenericController.toUCase(TableName))
                {
                case "CCMEMBERS":
                    //
                    // ----- People and member content export
                    //
                    if (!core.session.isAuthenticatedAdmin())
                    {
                        sb.Append("Warning: You must be a site administrator to export this information.");
                    }
                    else
                    {
                        using (var csData = new CsModel(core)) {
                            csData.open(iContentName, "", "ID", false, 0, "", PageSize, PageNumber);
                            //
                            // ----- print out the field names
                            //
                            if (csData.ok())
                            {
                                sb.Append("\"EID\"");
                                Delimiter        = ",";
                                FieldNameVariant = csData.getFirstFieldName();
                                while (!string.IsNullOrEmpty(FieldNameVariant))
                                {
                                    FieldName      = GenericController.encodeText(FieldNameVariant);
                                    UcaseFieldName = GenericController.toUCase(FieldName);
                                    if ((UcaseFieldName != "USERNAME") && (UcaseFieldName != "PASSWORD"))
                                    {
                                        sb.Append(Delimiter + "\"" + FieldName + "\"");
                                    }
                                    FieldNameVariant = csData.getNextFieldName();
                                }
                                sb.Append(Environment.NewLine);
                            }
                            //
                            // ----- print out the values
                            //
                            while (csData.ok())
                            {
                                if (!(csData.getBoolean("Developer")))
                                {
                                    Copy = SecurityController.encodeToken(core, csData.getInteger("ID"), core.doc.profileStartTime.AddDays(30));
                                    sb.Append("\"" + Copy + "\"");
                                    Delimiter        = ",";
                                    FieldNameVariant = csData.getFirstFieldName();
                                    while (!string.IsNullOrEmpty(FieldNameVariant))
                                    {
                                        FieldName      = GenericController.encodeText(FieldNameVariant);
                                        UcaseFieldName = GenericController.toUCase(FieldName);
                                        if ((UcaseFieldName != "USERNAME") && (UcaseFieldName != "PASSWORD"))
                                        {
                                            Copy = csData.getText(FieldName);
                                            if (!string.IsNullOrEmpty(Copy))
                                            {
                                                Copy = GenericController.strReplace(Copy, "\"", "'");
                                                Copy = GenericController.strReplace(Copy, Environment.NewLine, " ");
                                                Copy = GenericController.strReplace(Copy, "\r", " ");
                                                Copy = GenericController.strReplace(Copy, "\n", " ");
                                            }
                                            sb.Append(Delimiter + "\"" + Copy + "\"");
                                        }
                                        FieldNameVariant = csData.getNextFieldName();
                                    }
                                    sb.Append(Environment.NewLine);
                                }
                                csData.goNext();
                            }
                        }
                    }
                    // End Case
                    break;

                default:
                    //
                    // ----- All other content
                    //
                    if (!core.session.isAuthenticatedContentManager(iContentName))
                    {
                        sb.Append("Error: You must be a content manager to export this data.");
                    }
                    else
                    {
                        using (var csData = new CsModel(core)) {
                            csData.open(iContentName, "", "ID", false, 0, "", PageSize, PageNumber);
                            //
                            // ----- print out the field names
                            if (csData.ok())
                            {
                                Delimiter        = "";
                                FieldNameVariant = csData.getFirstFieldName();
                                while (!string.IsNullOrEmpty(FieldNameVariant))
                                {
                                    core.wwwFiles.appendFile(TestFilename, Delimiter + "\"" + FieldNameVariant + "\"");
                                    Delimiter        = ",";
                                    FieldNameVariant = csData.getNextFieldName();
                                }
                                core.wwwFiles.appendFile(TestFilename, Environment.NewLine);
                            }
                            //
                            // ----- print out the values
                            while (csData.ok())
                            {
                                Delimiter        = "";
                                FieldNameVariant = csData.getFirstFieldName();
                                while (!string.IsNullOrEmpty(FieldNameVariant))
                                {
                                    switch (csData.getFieldTypeId(GenericController.encodeText(FieldNameVariant)))
                                    {
                                    case CPContentBaseClass.FieldTypeIdEnum.FileText:
                                    case CPContentBaseClass.FieldTypeIdEnum.FileCSS:
                                    case CPContentBaseClass.FieldTypeIdEnum.FileXML:
                                    case CPContentBaseClass.FieldTypeIdEnum.FileJavascript:
                                    case CPContentBaseClass.FieldTypeIdEnum.FileHTML:
                                    case CPContentBaseClass.FieldTypeIdEnum.FileHTMLCode:
                                        Copy = csData.getTextEncoded(GenericController.encodeText(FieldNameVariant));
                                        break;

                                    case CPContentBaseClass.FieldTypeIdEnum.Lookup:
                                        Copy = csData.getText(GenericController.encodeText(FieldNameVariant));
                                        break;

                                    case CPContentBaseClass.FieldTypeIdEnum.Redirect:
                                    case CPContentBaseClass.FieldTypeIdEnum.ManyToMany:
                                        break;

                                    default:
                                        Copy = csData.getText(GenericController.encodeText(FieldNameVariant));
                                        break;
                                    }
                                    if (!string.IsNullOrEmpty(Copy))
                                    {
                                        Copy = GenericController.strReplace(Copy, "\"", "'");
                                        Copy = GenericController.strReplace(Copy, Environment.NewLine, " ");
                                        Copy = GenericController.strReplace(Copy, "\r", " ");
                                        Copy = GenericController.strReplace(Copy, "\n", " ");
                                    }
                                    core.wwwFiles.appendFile(TestFilename, Delimiter + "\"" + Copy + "\"");
                                    Delimiter        = ",";
                                    FieldNameVariant = csData.getNextFieldName();
                                }
                                core.wwwFiles.appendFile(TestFilename, Environment.NewLine);
                                csData.goNext();
                            }
                        }
                    }
                    break;
                }
                result = core.wwwFiles.readFileText(TestFilename);
                core.wwwFiles.deleteFile(TestFilename);
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(result);
        }