예제 #1
0
        //
        //
        //
        //
        public static string main_GetRemoteQueryKey(CoreController core, string SQL, string dataSourceName = "default", int maxRows = 1000)
        {
            string remoteKey = "";

            if (maxRows == 0)
            {
                maxRows = 1000;
            }
            using (var cs = new CsModel(core)) {
                cs.insert("Remote Queries");
                if (cs.ok())
                {
                    remoteKey = getGUIDNaked();
                    cs.set("remotekey", remoteKey);
                    cs.set("datasourceid", MetadataController.getRecordIdByUniqueName(core, "Data Sources", dataSourceName));
                    cs.set("sqlquery", SQL);
                    cs.set("maxRows", maxRows);
                    cs.set("dateexpires", DbController.encodeSQLDate(core.doc.profileStartTime.AddDays(1)));
                    cs.set("QueryTypeID", QueryTypeSQL);
                    cs.set("VisitId", core.session.visit.id);
                }
                cs.close();
            }
            //
            return(remoteKey);
        }
예제 #2
0
        //
        //====================================================================================================
        //
        public static string getActiveEditor(CoreController core, string ContentName, int RecordID, string FieldName, string FormElements = "")
        {
            //
            int    ContentID      = 0;
            string Copy           = null;
            string Stream         = "";
            string ButtonPanel    = null;
            string EditorPanel    = null;
            string PanelCopy      = null;
            string intContentName = null;
            int    intRecordId    = 0;
            string strFieldName   = null;

            //
            intContentName = GenericController.encodeText(ContentName);
            intRecordId    = GenericController.encodeInteger(RecordID);
            strFieldName   = GenericController.encodeText(FieldName);
            //
            EditorPanel = "";
            ContentID   = Models.Domain.ContentMetadataModel.getContentId(core, intContentName);
            if ((ContentID < 1) || (intRecordId < 1) || (string.IsNullOrEmpty(strFieldName)))
            {
                PanelCopy   = SpanClassAdminNormal + "The information you have selected can not be accessed.</span>";
                EditorPanel = EditorPanel + core.html.getPanel(PanelCopy);
            }
            else
            {
                intContentName = MetadataController.getContentNameByID(core, ContentID);
                if (!string.IsNullOrEmpty(intContentName))
                {
                    using (var csData = new CsModel(core)) {
                        csData.open(intContentName, "ID=" + intRecordId);
                        if (!csData.ok())
                        {
                            PanelCopy   = SpanClassAdminNormal + "The information you have selected can not be accessed.</span>";
                            EditorPanel = EditorPanel + core.html.getPanel(PanelCopy);
                        }
                        else
                        {
                            Copy        = csData.getText(strFieldName);
                            EditorPanel = EditorPanel + HtmlController.inputHidden("Type", FormTypeActiveEditor);
                            EditorPanel = EditorPanel + HtmlController.inputHidden("cid", ContentID);
                            EditorPanel = EditorPanel + HtmlController.inputHidden("ID", intRecordId);
                            EditorPanel = EditorPanel + HtmlController.inputHidden("fn", strFieldName);
                            EditorPanel = EditorPanel + GenericController.encodeText(FormElements);
                            EditorPanel = EditorPanel + core.html.getFormInputHTML("ContentCopy", Copy, "3", "45", false, true);
                            ButtonPanel = core.html.getPanelButtons(ButtonCancel + "," + ButtonSave);
                            EditorPanel = EditorPanel + ButtonPanel;
                        }
                        csData.close();
                    }
                }
            }
            Stream = Stream + core.html.getPanelHeader("Contensive Active Content Editor");
            Stream = Stream + core.html.getPanel(EditorPanel);
            Stream = HtmlController.form(core, Stream);
            return(Stream);
        }
예제 #3
0
 //
 //====================================================================================================
 /// <summary>
 /// Open dataset for the record specified
 /// </summary>
 /// <param name="contentName"></param>
 /// <param name="recordId"></param>
 /// <param name="selectFieldList"></param>
 /// <param name="activeOnly"></param>
 /// <returns></returns>
 public override bool OpenRecord(string contentName, int recordId, string selectFieldList, bool activeOnly)
 {
     try {
         if (!cs.openRecord(contentName, recordId, selectFieldList))
         {
             return(false);
         }
         if (!activeOnly || cs.getBoolean("active"))
         {
             return(true);
         }
         cs.close();
         return(false);
     } catch (Exception ex) {
         LogController.logError(cp.core, ex);
         throw;
     }
 }
예제 #4
0
        //
        //====================================================================================================
        /// <summary>
        /// Process the active editor form
        /// </summary>
        /// <param name="core"></param>
        public static void processActiveEditor(CoreController core)
        {
            //
            string Button      = null;
            int    ContentID   = 0;
            string ContentName = null;
            int    RecordID    = 0;
            string FieldName   = null;
            string ContentCopy = null;

            //
            Button = core.docProperties.getText("Button");
            switch (Button)
            {
            case ButtonCancel:
                //
                // ----- Do nothing, the form will reload with the previous contents
                //
                break;

            case ButtonSave:
                //
                // ----- read the form fields
                //
                ContentID   = core.docProperties.getInteger("cid");
                RecordID    = core.docProperties.getInteger("id");
                FieldName   = core.docProperties.getText("fn");
                ContentCopy = core.docProperties.getText("ContentCopy");
                //
                // ----- convert editor active edit icons
                //
                ContentCopy = ActiveContentController.processWysiwygResponseForSave(core, ContentCopy);
                //
                // ----- save the content
                //
                ContentName = MetadataController.getContentNameByID(core, ContentID);
                if (!string.IsNullOrEmpty(ContentName))
                {
                    using (var csData = new CsModel(core)) {
                        csData.open(ContentName, "ID=" + DbController.encodeSQLNumber(RecordID), "", false);
                        if (csData.ok())
                        {
                            csData.set(FieldName, ContentCopy);
                        }
                        csData.close();
                    }
                }
                break;
            }
        }
        //
        public static string getDefaultValue(CoreController core, string contentName, string fieldName)
        {
            string defaultValue = "";
            int    contentId    = ContentMetadataModel.getContentId(core, contentName);
            string SQL          = "select defaultvalue from ccfields where name=" + DbController.encodeSQLText(fieldName) + " and contentid=(" + contentId + ")";

            using (var csData = new CsModel(core)) {
                csData.openSql(SQL);
                if (csData.ok())
                {
                    defaultValue = csData.getText("defaultvalue");
                }
                csData.close();
            }
            return(defaultValue);
        }
예제 #6
0
 //
 //=============================================================================
 /// <summary>
 /// Sets the MetaContent subsystem so the next call to main_GetLastMeta... returns the correct value
 /// </summary>
 /// <param name="contentId"></param>
 /// <param name="recordId"></param>
 public void setMetaContent(int contentId, int recordId)
 {
     if ((contentId != 0) && (recordId != 0))
     {
         //
         // -- open meta content record
         string Criteria      = "(ContentID=" + contentId + ")and(RecordID=" + recordId + ")";
         string FieldList     = "ID,Name,MetaDescription,OtherHeadTags,MetaKeywordList";
         string keywordList   = "";
         int    MetaContentId = 0;
         using (var csData = new CsModel(core)) {
             if (csData.open("Meta Content", Criteria, "", false, 0, FieldList))
             {
                 MetaContentId = csData.getInteger("ID");
                 core.html.addTitle(HtmlController.encodeHtml(csData.getText("Name")), "page content");
                 core.html.addMetaDescription(HtmlController.encodeHtml(csData.getText("MetaDescription")), "page content");
                 core.html.addHeadTag(csData.getText("OtherHeadTags"), "page content");
                 keywordList = csData.getText("MetaKeywordList").Replace(Environment.NewLine, ",");
             }
             csData.close();
         }
         //
         // open Keyword List
         using (var csData = new CsModel(core)) {
             string SQL = "select ccMetaKeywords.Name"
                          + " From ccMetaKeywords"
                          + " LEFT JOIN ccMetaKeywordRules on ccMetaKeywordRules.MetaKeywordID=ccMetaKeywords.ID"
                          + " Where ccMetaKeywordRules.MetaContentID=" + MetaContentId;
             csData.openSql(SQL);
             while (csData.ok())
             {
                 keywordList = keywordList + "," + csData.getText("Name");
                 csData.goNext();
             }
             if (!string.IsNullOrEmpty(keywordList))
             {
                 if (keywordList.left(1) == ",")
                 {
                     keywordList = keywordList.Substring(1);
                 }
                 keywordList = HtmlController.encodeHtml(keywordList);
                 core.html.addMetaKeywordList(keywordList, "page content");
             }
         }
     }
 }
예제 #7
0
        //
        //====================================================================================================
        //
        public override int AddRecord(string contentName)
        {
            int result = 0;

            try {
                CsModel cs = new CsModel(cp.core);
                if (cs.insert(contentName))
                {
                    result = cs.getInteger("id");
                }
                cs.close();
            } catch (Exception ex) {
                LogController.logError(cp.core, ex);
                throw;
            }
            return(result);
        }
예제 #8
0
 //====================================================================================================
 //
 public static void housekeep(CoreController core, HouseKeepEnvironmentModel env)
 {
     try {
         //
         LogController.logInfo(core, "HousekeepDaily, page content");
         {
             //
             // Move Archived pages from their current parent to their archive parent
             //
             bool   NeedToClearCache = false;
             string SQL = "select * from ccpagecontent where (( DateArchive is not null )and(DateArchive<" + core.sqlDateTimeMockable + "))and(active<>0)";
             using (var csData = new CsModel(core)) {
                 csData.openSql(SQL);
                 while (csData.ok())
                 {
                     int RecordId        = csData.getInteger("ID");
                     int ArchiveParentId = csData.getInteger("ArchiveParentID");
                     if (ArchiveParentId == 0)
                     {
                         SQL = "update ccpagecontent set DateArchive=null where (id=" + RecordId + ")";
                         core.db.executeNonQuery(SQL);
                     }
                     else
                     {
                         SQL = "update ccpagecontent set ArchiveParentID=null,DateArchive=null,parentid=" + ArchiveParentId + " where (id=" + RecordId + ")";
                         core.db.executeNonQuery(SQL);
                         NeedToClearCache = true;
                     }
                     csData.goNext();
                 }
                 csData.close();
             }
             //
             // Clear caches
             //
             if (NeedToClearCache)
             {
                 object emptyData = null;
                 core.cache.invalidate("Page Content");
                 core.cache.storeObject("PCC", emptyData);
             }
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
        //
        //=============================================================================
        // Create a child content
        //=============================================================================
        //
        private static string GetContentChildTool_Options(CPClass cp, int ParentId, int DefaultValue)
        {
            string returnOptions = "";

            try {
                //
                string SQL        = null;
                int    RecordId   = 0;
                string RecordName = null;
                //
                if (ParentId == 0)
                {
                    SQL = "select Name, ID from ccContent where ((ParentID<1)or(Parentid is null)) and (AllowContentChildTool<>0);";
                }
                else
                {
                    SQL = "select Name, ID from ccContent where ParentID=" + ParentId + " and (AllowContentChildTool<>0) and not (allowcontentchildtool is null);";
                }
                using (var csData = new CsModel(cp.core)) {
                    csData.openSql(SQL);
                    while (csData.ok())
                    {
                        RecordName = csData.getText("Name");
                        RecordId   = csData.getInteger("ID");
                        if (RecordId == DefaultValue)
                        {
                            returnOptions = returnOptions + "<option value=\"" + RecordId + "\" selected>" + csData.getText("name") + "</option>";
                        }
                        else
                        {
                            returnOptions = returnOptions + "<option value=\"" + RecordId + "\" >" + csData.getText("name") + "</option>";
                        }
                        returnOptions = returnOptions + GetContentChildTool_Options(cp, RecordId, DefaultValue);
                        csData.goNext();
                    }
                    csData.close();
                }
            } catch (Exception ex) {
                LogController.logError(cp.core, ex);
                throw;
            }
            return(returnOptions);
        }
예제 #10
0
        //
        //====================================================================================================
        /// <summary>
        /// Get the Configure Edit
        /// </summary>
        /// <param name="cp"></param>
        /// <returns></returns>
        public static string get(CPClass cp)
        {
            CoreController core = cp.core;

            try {
                KeyPtrController Index = new KeyPtrController();
                int    ContentId       = cp.Doc.GetInteger(RequestNameToolContentId);
                var    contentMetadata = ContentMetadataModel.create(core, ContentId, true, true);
                int    RecordCount     = 0;
                int    formFieldId     = 0;
                string StatusMessage   = "";
                string ErrorMessage    = "";
                bool   ReloadCDef      = cp.Doc.GetBoolean("ReloadCDef");
                if (contentMetadata != null)
                {
                    string ToolButton = cp.Doc.GetText("Button");
                    //
                    if (!string.IsNullOrEmpty(ToolButton))
                    {
                        bool AllowContentAutoLoad = false;
                        if (ToolButton != ButtonCancel)
                        {
                            //
                            // Save the form changes
                            //
                            AllowContentAutoLoad = cp.Site.GetBoolean("AllowContentAutoLoad", true);
                            cp.Site.SetProperty("AllowContentAutoLoad", "false");
                            //
                            // ----- Save the input
                            //
                            RecordCount = GenericController.encodeInteger(cp.Doc.GetInteger("dtfaRecordCount"));
                            if (RecordCount > 0)
                            {
                                int RecordPointer = 0;
                                for (RecordPointer = 0; RecordPointer < RecordCount; RecordPointer++)
                                {
                                    //
                                    string formFieldName = cp.Doc.GetText("dtfaName." + RecordPointer);
                                    CPContentBaseClass.FieldTypeIdEnum formFieldTypeId = (CPContentBaseClass.FieldTypeIdEnum)cp.Doc.GetInteger("dtfaType." + RecordPointer);
                                    formFieldId = GenericController.encodeInteger(cp.Doc.GetInteger("dtfaID." + RecordPointer));
                                    bool formFieldInherited = cp.Doc.GetBoolean("dtfaInherited." + RecordPointer);
                                    //
                                    // problem - looking for the name in the Db using the form's name, but it could have changed.
                                    // have to look field up by id
                                    //
                                    foreach (KeyValuePair <string, Processor.Models.Domain.ContentFieldMetadataModel> cdefFieldKvp in contentMetadata.fields)
                                    {
                                        if (cdefFieldKvp.Value.id == formFieldId)
                                        {
                                            //
                                            // Field was found in CDef
                                            //
                                            if (cdefFieldKvp.Value.inherited && (!formFieldInherited))
                                            {
                                                //
                                                // Was inherited, but make a copy of the field
                                                //
                                                using (var CSTarget = new CsModel(core)) {
                                                    if (CSTarget.insert("Content Fields"))
                                                    {
                                                        using (var CSSource = new CsModel(core)) {
                                                            if (CSSource.openRecord("Content Fields", formFieldId))
                                                            {
                                                                CSSource.copyRecord(CSTarget);
                                                            }
                                                        }
                                                        formFieldId = CSTarget.getInteger("ID");
                                                        CSTarget.set("ContentID", ContentId);
                                                    }
                                                    CSTarget.close();
                                                }
                                                ReloadCDef = true;
                                            }
                                            else if ((!cdefFieldKvp.Value.inherited) && (formFieldInherited))
                                            {
                                                //
                                                // Was a field, make it inherit from it's parent
                                                MetadataController.deleteContentRecord(core, "Content Fields", formFieldId);
                                                ReloadCDef = true;
                                            }
                                            else if ((!cdefFieldKvp.Value.inherited) && (!formFieldInherited))
                                            {
                                                //
                                                // not inherited, save the field values and mark for a reload
                                                //
                                                {
                                                    if (formFieldName.IndexOf(" ") != -1)
                                                    {
                                                        //
                                                        // remoave spaces from new name
                                                        //
                                                        StatusMessage = StatusMessage + "<LI>Field [" + formFieldName + "] was renamed [" + GenericController.strReplace(formFieldName, " ", "") + "] because the field name can not include spaces.</LI>";
                                                        formFieldName = GenericController.strReplace(formFieldName, " ", "");
                                                    }
                                                    //
                                                    string SQL = null;
                                                    //
                                                    if ((!string.IsNullOrEmpty(formFieldName)) && ((int)formFieldTypeId != 0) && ((cdefFieldKvp.Value.nameLc == "") || (cdefFieldKvp.Value.fieldTypeId == 0)))
                                                    {
                                                        //
                                                        // Create Db field, Field is good but was not before
                                                        //
                                                        core.db.createSQLTableField(contentMetadata.tableName, formFieldName, formFieldTypeId);
                                                        StatusMessage = StatusMessage + "<LI>Field [" + formFieldName + "] was saved to this content definition and a database field was created in [" + contentMetadata.tableName + "].</LI>";
                                                    }
                                                    else if ((string.IsNullOrEmpty(formFieldName)) || ((int)formFieldTypeId == 0))
                                                    {
                                                        //
                                                        // name blank or type=0 - do nothing but tell them
                                                        //
                                                        if (string.IsNullOrEmpty(formFieldName) && ((int)formFieldTypeId == 0))
                                                        {
                                                            ErrorMessage += "<LI>Field number " + (RecordPointer + 1) + " was saved to this content definition but no database field was created because a name and field type are required.</LI>";
                                                        }
                                                        else if (formFieldName == "unnamedfield" + formFieldId.ToString())
                                                        {
                                                            ErrorMessage += "<LI>Field number " + (RecordPointer + 1) + " was saved to this content definition but no database field was created because a field name is required.</LI>";
                                                        }
                                                        else
                                                        {
                                                            ErrorMessage += "<LI>Field [" + formFieldName + "] was saved to this content definition but no database field was created because a field type are required.</LI>";
                                                        }
                                                    }
                                                    else if ((formFieldName == cdefFieldKvp.Value.nameLc) && (formFieldTypeId != cdefFieldKvp.Value.fieldTypeId))
                                                    {
                                                        //
                                                        // Field Type changed, must be done manually
                                                        //
                                                        ErrorMessage += "<LI>Field [" + formFieldName + "] changed type from [" + DbBaseModel.getRecordName <ContentFieldTypeModel>(core.cpParent, (int)cdefFieldKvp.Value.fieldTypeId) + "] to [" + DbBaseModel.getRecordName <ContentFieldTypeModel>(core.cpParent, (int)formFieldTypeId) + "]. This may have caused a problem converting content.</LI>";
                                                        int DataSourceTypeId = core.db.getDataSourceType();
                                                        switch (DataSourceTypeId)
                                                        {
                                                        case DataSourceTypeODBCMySQL:
                                                            SQL = "alter table " + contentMetadata.tableName + " change " + cdefFieldKvp.Value.nameLc + " " + cdefFieldKvp.Value.nameLc + " " + core.db.getSQLAlterColumnType(formFieldTypeId) + ";";
                                                            break;

                                                        default:
                                                            SQL = "alter table " + contentMetadata.tableName + " alter column " + cdefFieldKvp.Value.nameLc + " " + core.db.getSQLAlterColumnType(formFieldTypeId) + ";";
                                                            break;
                                                        }
                                                        core.db.executeNonQuery(SQL);
                                                    }
                                                    SQL = "Update ccFields"
                                                          + " Set name=" + DbController.encodeSQLText(formFieldName)
                                                          + ",type=" + (int)formFieldTypeId
                                                          + ",caption=" + DbController.encodeSQLText(cp.Doc.GetText("dtfaCaption." + RecordPointer))
                                                          + ",DefaultValue=" + DbController.encodeSQLText(cp.Doc.GetText("dtfaDefaultValue." + RecordPointer))
                                                          + ",EditSortPriority=" + DbController.encodeSQLText(GenericController.encodeText(cp.Doc.GetInteger("dtfaEditSortPriority." + RecordPointer)))
                                                          + ",Active=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaActive." + RecordPointer))
                                                          + ",ReadOnly=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaReadOnly." + RecordPointer))
                                                          + ",Authorable=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaAuthorable." + RecordPointer))
                                                          + ",Required=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaRequired." + RecordPointer))
                                                          + ",UniqueName=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaUniqueName." + RecordPointer))
                                                          + ",TextBuffered=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaTextBuffered." + RecordPointer))
                                                          + ",Password="******"dtfaPassword." + RecordPointer))
                                                          + ",HTMLContent=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaHTMLContent." + RecordPointer))
                                                          + ",EditTab=" + DbController.encodeSQLText(cp.Doc.GetText("dtfaEditTab." + RecordPointer))
                                                          + ",Scramble=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaScramble." + RecordPointer)) + "";
                                                    if (core.session.isAuthenticatedAdmin())
                                                    {
                                                        SQL += ",adminonly=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaAdminOnly." + RecordPointer));
                                                    }
                                                    if (core.session.isAuthenticatedDeveloper())
                                                    {
                                                        SQL += ",DeveloperOnly=" + DbController.encodeSQLBoolean(cp.Doc.GetBoolean("dtfaDeveloperOnly." + RecordPointer));
                                                    }
                                                    SQL += " where ID=" + formFieldId;
                                                    core.db.executeNonQuery(SQL);
                                                    ReloadCDef = true;
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                            core.cache.invalidateAll();
                            core.clearMetaData();
                        }
                        if (ToolButton == ButtonAdd)
                        {
                            //
                            // ----- Insert a blank Field
                            var defaultValues = ContentMetadataModel.getDefaultValueDict(core, ContentFieldModel.tableMetadata.contentName);
                            var field         = ContentFieldModel.addDefault <ContentFieldModel>(core.cpParent, defaultValues);
                            field.name             = "unnamedField" + field.id.ToString();
                            field.contentId        = ContentId;
                            field.editSortPriority = 0;
                            field.save(core.cpParent);
                            ReloadCDef = true;
                        }
                        //
                        // ----- Button Reload CDef
                        if (ToolButton == ButtonSaveandInvalidateCache)
                        {
                            core.cache.invalidateAll();
                            core.clearMetaData();
                        }
                        //
                        // ----- Restore Content Autoload site property
                        //
                        if (AllowContentAutoLoad)
                        {
                            cp.Site.SetProperty("AllowContentAutoLoad", AllowContentAutoLoad.ToString());
                        }
                        //
                        // ----- Cancel or Save, reload CDef and go
                        //
                        if ((ToolButton == ButtonCancel) || (ToolButton == ButtonOK))
                        {
                            //
                            // ----- Exit back to menu
                            //
                            return(core.webServer.redirect(core.appConfig.adminRoute, "Tool-ConfigureContentEdit, ok or cancel button, go to root."));
                        }
                    }
                }
                //
                //   Print Output
                string description = ""
                                     + HtmlController.p("Use this tool to add or modify content definition fields and the underlying sql table fields.")
                                     + ((ContentId.Equals(0)) ? "" : ""
                                        + HtmlController.ul(""
                                                            + HtmlController.li(HtmlController.a("Edit Content", "?aa=0&cid=3&id=" + ContentId + "&tx=&ad=0&asf=1&af=4", "nav-link btn btn-primary"), "nav-item mr-1")
                                                            + HtmlController.li(HtmlController.a("Edit Records", "?cid=" + ContentId, "nav-link btn btn-primary"), "nav-item mr-1")
                                                            + HtmlController.li(HtmlController.a("Select Different Fields", "?af=105", "nav-link btn btn-primary"), "nav-item mr-1")
                                                            , "nav")
                                        );
                StringBuilderLegacyController Stream = new StringBuilderLegacyController();
                Stream.add(AdminUIController.getHeaderTitleDescription("Manage Admin Edit Fields", description));
                //
                // -- status of last operation
                if (!string.IsNullOrEmpty(StatusMessage))
                {
                    Stream.add(AdminUIController.getToolFormRow(core, "<UL>" + StatusMessage + "</UL>"));
                }
                //
                // -- errors with last operations
                if (!string.IsNullOrEmpty(ErrorMessage))
                {
                    Stream.add(HtmlController.div("There was a problem saving these changes" + "<UL>" + ErrorMessage + "</UL>", "ccError"));
                }
                if (ReloadCDef)
                {
                    contentMetadata = Processor.Models.Domain.ContentMetadataModel.create(core, ContentId, true, true);
                }
                string ButtonList = ButtonCancel + "," + ButtonSelect;
                if (ContentId == 0)
                {
                    //
                    // content tables that have edit forms to Configure
                    bool isEmptyList = false;
                    Stream.add(AdminUIController.getToolFormInputRow(core, "Select a Content Definition to Configure", AdminUIEditorController.getLookupContentEditor(core, RequestNameToolContentId, ContentId, ContentMetadataModel.getContentId(core, "Content"), ref isEmptyList, false, "", "", false, "")));
                }
                else
                {
                    //
                    // Configure edit form
                    Stream.add(HtmlController.inputHidden(RequestNameToolContentId, ContentId));
                    Stream.add(core.html.getPanelTop());
                    ButtonList = ButtonCancel + "," + ButtonSave + "," + ButtonOK + "," + ButtonAdd;
                    //
                    // Get a new copy of the content definition
                    //
                    Stream.add(SpanClassAdminNormal + "<P><B>" + contentMetadata.name + "</b></P>");
                    Stream.add("<table border=\"0\" cellpadding=\"1\" cellspacing=\"1\" width=\"100%\">");
                    //
                    int  ParentContentId  = contentMetadata.parentId;
                    bool AllowCDefInherit = false;
                    Processor.Models.Domain.ContentMetadataModel ParentCDef = null;
                    if (ParentContentId == -1)
                    {
                        AllowCDefInherit = false;
                    }
                    else
                    {
                        AllowCDefInherit = true;
                        string ParentContentName = MetadataController.getContentNameByID(core, ParentContentId);
                        ParentCDef = Processor.Models.Domain.ContentMetadataModel.create(core, ParentContentId, true, true);
                    }
                    bool NeedFootNote1 = false;
                    bool NeedFootNote2 = false;
                    if (contentMetadata.fields.Count > 0)
                    {
                        //
                        // -- header row
                        Stream.add("<tr>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\"></td>");
                        if (!AllowCDefInherit)
                        {
                            Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Inherited*</b></span></td>");
                            NeedFootNote1 = true;
                        }
                        else
                        {
                            Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Inherited</b></span></td>");
                        }
                        Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Field</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Caption</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Edit Tab</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"100\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Default</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>Type</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b>Edit<br>Order</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Active</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b>Read<br>Only</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Auth</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Req</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Unique</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b>Text<br>Buffer</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b><br>Pass</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "<b>Text<br>Scrm</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b><br>HTML</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b>Admin<br>Only</b></span></td>");
                        Stream.add("<td valign=\"bottom\" width=\"50\" class=\"ccPanelInput\" align=\"left\">" + SpanClassAdminSmall + "<b>Dev<br>Only</b></span></td>");
                        Stream.add("</tr>");
                        RecordCount = 0;
                        //
                        // Build a select template for Type
                        //
                        string TypeSelectTemplate = core.html.selectFromContent("menuname", -1, "Content Field Types", "", "unknown");
                        //
                        // Index the sort order
                        //
                        List <FieldSortClass> fieldList = new List <FieldSortClass>();
                        int FieldCount = contentMetadata.fields.Count;
                        foreach (var keyValuePair in contentMetadata.fields)
                        {
                            FieldSortClass fieldSort = new FieldSortClass();
                            string         sortOrder = "";
                            fieldSort.field = keyValuePair.Value;
                            sortOrder       = "";
                            if (fieldSort.field.active)
                            {
                                sortOrder += "0";
                            }
                            else
                            {
                                sortOrder += "1";
                            }
                            if (fieldSort.field.authorable)
                            {
                                sortOrder += "0";
                            }
                            else
                            {
                                sortOrder += "1";
                            }
                            sortOrder     += fieldSort.field.editTabName + getIntegerString(fieldSort.field.editSortPriority, 10) + getIntegerString(fieldSort.field.id, 10);
                            fieldSort.sort = sortOrder;
                            fieldList.Add(fieldSort);
                        }
                        fieldList.Sort((p1, p2) => p1.sort.CompareTo(p2.sort));
                        StringBuilderLegacyController StreamValidRows = new StringBuilderLegacyController();
                        var contentFieldsCdef = Processor.Models.Domain.ContentMetadataModel.createByUniqueName(core, "content fields");
                        foreach (FieldSortClass fieldsort in fieldList)
                        {
                            StringBuilderLegacyController streamRow = new StringBuilderLegacyController();
                            bool rowValid = true;
                            //
                            // If Field has name and type, it is locked and can not be changed
                            //
                            bool FieldLocked = (fieldsort.field.nameLc != "") && (fieldsort.field.fieldTypeId != 0);
                            //
                            // put the menu into the current menu format
                            //
                            formFieldId = fieldsort.field.id;
                            streamRow.add(HtmlController.inputHidden("dtfaID." + RecordCount, formFieldId));
                            streamRow.add("<tr>");
                            //
                            // edit button
                            //
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\">" + AdminUIController.getRecordEditAnchorTag(core, contentFieldsCdef, formFieldId) + "</td>");
                            //
                            // Inherited
                            //
                            if (!AllowCDefInherit)
                            {
                                //
                                // no parent
                                //
                                streamRow.add("<td class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "False</span></td>");
                            }
                            else if (fieldsort.field.inherited)
                            {
                                //
                                // inherited property
                                //
                                streamRow.add("<td class=\"ccPanelInput\" align=\"center\">" + HtmlController.checkbox("dtfaInherited." + RecordCount, fieldsort.field.inherited) + "</td>");
                            }
                            else
                            {
                                Processor.Models.Domain.ContentFieldMetadataModel parentField = null;
                                //
                                // CDef has a parent, but the field is non-inherited, test for a matching Parent Field
                                //
                                if (ParentCDef == null)
                                {
                                    foreach (KeyValuePair <string, Processor.Models.Domain.ContentFieldMetadataModel> kvp in ParentCDef.fields)
                                    {
                                        if (kvp.Value.nameLc == fieldsort.field.nameLc)
                                        {
                                            parentField = kvp.Value;
                                            break;
                                        }
                                    }
                                }
                                if (parentField == null)
                                {
                                    streamRow.add("<td class=\"ccPanelInput\" align=\"center\">" + SpanClassAdminSmall + "False**</span></td>");
                                    NeedFootNote2 = true;
                                }
                                else
                                {
                                    streamRow.add("<td class=\"ccPanelInput\" align=\"center\">" + HtmlController.checkbox("dtfaInherited." + RecordCount, fieldsort.field.inherited) + "</td>");
                                }
                            }
                            //
                            // name
                            //
                            bool tmpValue = string.IsNullOrEmpty(fieldsort.field.nameLc);
                            rowValid = rowValid && !tmpValue;
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>");
                            if (fieldsort.field.inherited)
                            {
                                streamRow.add(SpanClassAdminSmall + fieldsort.field.nameLc + "&nbsp;</SPAN>");
                            }
                            else if (FieldLocked)
                            {
                                streamRow.add(SpanClassAdminSmall + fieldsort.field.nameLc + "&nbsp;</SPAN><input type=hidden name=dtfaName." + RecordCount + " value=\"" + fieldsort.field.nameLc + "\">");
                            }
                            else
                            {
                                streamRow.add(HtmlController.inputText_Legacy(core, "dtfaName." + RecordCount, fieldsort.field.nameLc, 1, 10));
                            }
                            streamRow.add("</nobr></td>");
                            //
                            // caption
                            //
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>");
                            if (fieldsort.field.inherited)
                            {
                                streamRow.add(SpanClassAdminSmall + fieldsort.field.caption + "</SPAN>");
                            }
                            else
                            {
                                streamRow.add(HtmlController.inputText_Legacy(core, "dtfaCaption." + RecordCount, fieldsort.field.caption, 1, 10));
                            }
                            streamRow.add("</nobr></td>");
                            //
                            // Edit Tab
                            //
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>");
                            if (fieldsort.field.inherited)
                            {
                                streamRow.add(SpanClassAdminSmall + fieldsort.field.editTabName + "</SPAN>");
                            }
                            else
                            {
                                streamRow.add(HtmlController.inputText_Legacy(core, "dtfaEditTab." + RecordCount, fieldsort.field.editTabName, 1, 10));
                            }
                            streamRow.add("</nobr></td>");
                            //
                            // default
                            //
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>");
                            if (fieldsort.field.inherited)
                            {
                                streamRow.add(SpanClassAdminSmall + GenericController.encodeText(fieldsort.field.defaultValue) + "</SPAN>");
                            }
                            else
                            {
                                streamRow.add(HtmlController.inputText_Legacy(core, "dtfaDefaultValue." + RecordCount, GenericController.encodeText(fieldsort.field.defaultValue), 1, 10));
                            }
                            streamRow.add("</nobr></td>");
                            //
                            // type
                            //
                            rowValid = rowValid && (fieldsort.field.fieldTypeId > 0);
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>");
                            if (fieldsort.field.inherited)
                            {
                                using (var csData = new CsModel(core)) {
                                    csData.openRecord("Content Field Types", (int)fieldsort.field.fieldTypeId);
                                    if (!csData.ok())
                                    {
                                        streamRow.add(SpanClassAdminSmall + "Unknown[" + fieldsort.field.fieldTypeId + "]</SPAN>");
                                    }
                                    else
                                    {
                                        streamRow.add(SpanClassAdminSmall + csData.getText("Name") + "</SPAN>");
                                    }
                                }
                            }
                            else if (FieldLocked)
                            {
                                streamRow.add(DbBaseModel.getRecordName <ContentFieldTypeModel>(core.cpParent, (int)fieldsort.field.fieldTypeId) + HtmlController.inputHidden("dtfaType." + RecordCount, (int)fieldsort.field.fieldTypeId));
                            }
                            else
                            {
                                string TypeSelect = TypeSelectTemplate;
                                TypeSelect = GenericController.strReplace(TypeSelect, "menuname", "dtfaType." + RecordCount, 1, 99, 1);
                                TypeSelect = GenericController.strReplace(TypeSelect, "=\"" + fieldsort.field.fieldTypeId + "\"", "=\"" + fieldsort.field.fieldTypeId + "\" selected", 1, 99, 1);
                                streamRow.add(TypeSelect);
                            }
                            streamRow.add("</nobr></td>");
                            //
                            // sort priority
                            //
                            streamRow.add("<td class=\"ccPanelInput\" align=\"left\"><nobr>");
                            if (fieldsort.field.inherited)
                            {
                                streamRow.add(SpanClassAdminSmall + fieldsort.field.editSortPriority + "</SPAN>");
                            }
                            else
                            {
                                streamRow.add(HtmlController.inputText_Legacy(core, "dtfaEditSortPriority." + RecordCount, fieldsort.field.editSortPriority.ToString(), 1, 10));
                            }
                            streamRow.add("</nobr></td>");
                            //
                            // active
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaActive." + RecordCount, fieldsort.field.active, fieldsort.field.inherited));
                            //
                            // read only
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaReadOnly." + RecordCount, fieldsort.field.readOnly, fieldsort.field.inherited));
                            //
                            // authorable
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaAuthorable." + RecordCount, fieldsort.field.authorable, fieldsort.field.inherited));
                            //
                            // required
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaRequired." + RecordCount, fieldsort.field.required, fieldsort.field.inherited));
                            //
                            // UniqueName
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaUniqueName." + RecordCount, fieldsort.field.uniqueName, fieldsort.field.inherited));
                            //
                            // text buffered
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaTextBuffered." + RecordCount, fieldsort.field.textBuffered, fieldsort.field.inherited));
                            //
                            // password
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaPassword." + RecordCount, fieldsort.field.password, fieldsort.field.inherited));
                            //
                            // scramble
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaScramble." + RecordCount, fieldsort.field.scramble, fieldsort.field.inherited));
                            //
                            // HTML Content
                            //
                            streamRow.add(configureEdit_CheckBox("dtfaHTMLContent." + RecordCount, fieldsort.field.htmlContent, fieldsort.field.inherited));
                            //
                            // Admin Only
                            //
                            if (core.session.isAuthenticatedAdmin())
                            {
                                streamRow.add(configureEdit_CheckBox("dtfaAdminOnly." + RecordCount, fieldsort.field.adminOnly, fieldsort.field.inherited));
                            }
                            //
                            // Developer Only
                            //
                            if (core.session.isAuthenticatedDeveloper())
                            {
                                streamRow.add(configureEdit_CheckBox("dtfaDeveloperOnly." + RecordCount, fieldsort.field.developerOnly, fieldsort.field.inherited));
                            }
                            //
                            streamRow.add("</tr>");
                            RecordCount = RecordCount + 1;
                            //
                            // rows are built - put the blank rows at the top
                            //
                            if (!rowValid)
                            {
                                Stream.add(streamRow.text);
                            }
                            else
                            {
                                StreamValidRows.add(streamRow.text);
                            }
                        }
                        Stream.add(StreamValidRows.text);
                        Stream.add(HtmlController.inputHidden("dtfaRecordCount", RecordCount));
                    }
                    Stream.add("</table>");
                    //
                    Stream.add(core.html.getPanelBottom());
                    if (NeedFootNote1)
                    {
                        Stream.add("<br>*Field Inheritance is not allowed because this Content Definition has no parent.");
                    }
                    if (NeedFootNote2)
                    {
                        Stream.add("<br>**This field can not be inherited because the Parent Content Definition does not have a field with the same name.");
                    }
                }
                Stream.add(HtmlController.inputHidden("ReloadCDef", ReloadCDef));
                //
                // -- assemble form
                return(AdminUIController.getToolForm(core, Stream.text, ButtonList));
            } catch (Exception ex) {
                LogController.logError(core, ex);
                return(toolExceptionMessage);
            }
        }
예제 #11
0
        //
        //====================================================================================================
        /// <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;
            }
        }
        //
        //========================================================================
        /// <summary>
        /// Control edit tab
        /// </summary>
        /// <param name="core"></param>
        /// <param name="adminData"></param>
        /// <returns></returns>
        public static string get(CoreController core, AdminDataModel adminData, EditorEnvironmentModel editorEnv)
        {
            string result = null;

            try {
                bool disabled = false;
                //
                var tabPanel = new StringBuilderLegacyController();
                if (string.IsNullOrEmpty(adminData.adminContent.name))
                {
                    //
                    // Content not found or not loaded
                    if (adminData.adminContent.id == 0)
                    {
                        //
                        LogController.logError(core, new GenericException("No content definition was specified for this page"));
                        return(HtmlController.p("No content was specified."));
                    }
                    else
                    {
                        //
                        // Content Definition was not specified
                        LogController.logError(core, new GenericException("The content definition specified for this page [" + adminData.adminContent.id + "] was not found"));
                        return(HtmlController.p("No content was specified."));
                    }
                }
                //
                // ----- Authoring status
                bool FieldRequired = false;


                List <string> TabsFound = new List <string>();
                foreach (KeyValuePair <string, ContentFieldMetadataModel> keyValuePair in adminData.adminContent.fields)
                {
                    ContentFieldMetadataModel field = keyValuePair.Value;
                    if ((field.editTabName.ToLowerInvariant().Equals("control info")) && (field.authorable) && (field.active))
                    {
                        tabPanel.add(EditorRowClass.getEditorRow(core, field, adminData, editorEnv));
                    }
                }
                //
                // ----- RecordID
                {
                    string fieldValue  = (adminData.editRecord.id == 0) ? "(available after save)" : adminData.editRecord.id.ToString();
                    string fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore", fieldValue, true, "");
                    string fieldHelp   = "This is the unique number that identifies this record within this content.";
                    tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Record Number", fieldHelp, true, false, ""));
                }
                //
                // -- Active
                {
                    string htmlId      = "fieldActive";
                    string fieldEditor = HtmlController.checkbox("active", adminData.editRecord.active, htmlId, disabled, "", adminData.editRecord.userReadOnly);
                    string fieldHelp   = "When unchecked, add-ons can ignore this record as if it was temporarily deleted.";
                    tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Active", fieldHelp, false, false, htmlId));
                }
                //
                // -- GUID
                {
                    string guidSetHtmlId   = "guidSet" + GenericController.getRandomInteger(core).ToString();
                    string guidInputHtmlId = "guidInput" + GenericController.getRandomInteger(core).ToString();
                    string fieldValue      = GenericController.encodeText(adminData.editRecord.fieldsLc["ccguid"].value);
                    string fieldEditor     = "";
                    if (adminData.editRecord.userReadOnly)
                    {
                        //
                        // -- readonly
                        fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore", fieldValue, true, "");
                    }
                    else if (string.IsNullOrEmpty(fieldValue))
                    {
                        //
                        // add a set button
                        string setButton        = "<input id=\"" + guidSetHtmlId + "\" type=\"submit\" value=\"Set\" class=\"btn btn-primary btn-sm\">";
                        string setButtonWrapped = "<div class=\"input-group-append\">" + setButton + "</div>";
                        string inputCell        = AdminUIEditorController.getTextEditor(core, "ccguid", "", false, guidInputHtmlId);
                        fieldEditor = HtmlController.div(inputCell + setButtonWrapped, "input-group");
                        string newGuid   = GenericController.getGUID(true);
                        string onClickFn = "function(e){e.preventDefault();e.stopPropagation();$('#" + guidInputHtmlId + "').val('" + newGuid + "');}";
                        string script    = "$('body').on('click','#" + guidSetHtmlId + "'," + onClickFn + ")";
                        core.html.addScriptCode(script, "Admin edit control-info-tab guid set button");
                    }
                    else
                    {
                        //
                        // field is read-only except for developers
                        fieldEditor = AdminUIEditorController.getTextEditor(core, "ccguid", fieldValue, !core.session.isAuthenticatedDeveloper(), guidInputHtmlId);
                    }
                    string FieldHelp = "This is a unique number that identifies this record globally. A GUID is not required, but when set it should never be changed. GUIDs are used to synchronize records. When empty, you can create a new guid. Only Developers can modify the guid.";
                    tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "GUID", FieldHelp, false, false, guidInputHtmlId));
                }
                //
                // ----- EID (Encoded ID)
                {
                    if (GenericController.toUCase(adminData.adminContent.tableName) == GenericController.toUCase("ccMembers"))
                    {
                        string htmlId      = "fieldGuid";
                        bool   AllowEId    = (core.siteProperties.getBoolean("AllowLinkLogin", true)) || (core.siteProperties.getBoolean("AllowLinkRecognize", true));
                        string fieldHelp   = "This string is an authentication token that can be used in the URL for the next 15 minutes to log in as this user.";
                        string fieldEditor = "";
                        if (!AllowEId)
                        {
                            fieldEditor = "(link login and link recognize are disabled in security preferences)";
                        }
                        else if (adminData.editRecord.id == 0)
                        {
                            fieldEditor = "(available after save)";
                        }
                        else
                        {
                            string eidQueryString = "eid=" + WebUtility.UrlEncode(SecurityController.encodeToken(core, adminData.editRecord.id, core.doc.profileStartTime.AddMinutes(15)));
                            string sampleUrl      = core.webServer.requestProtocol + core.webServer.requestDomain + "/" + core.siteProperties.serverPageDefault + "?" + eidQueryString;
                            if (core.siteProperties.getBoolean("AllowLinkLogin", true))
                            {
                                fieldHelp = " If " + eidQueryString + " is added to a url querystring for this site, the user be logged in as this person.";
                            }
                            else
                            {
                                fieldHelp = " If " + eidQueryString + " is added to a url querystring for this site, the user be recognized in as this person, but not logged in.";
                            }
                            fieldHelp  += " To enable, disable or modify this feature, use the security tab on the Preferences page.";
                            fieldHelp  += "<br>For example: " + sampleUrl;
                            fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore_eid", eidQueryString, true, htmlId);
                        }
                        tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Member Link Login Querystring", fieldHelp, true, false, htmlId));
                    }
                }
                //
                // ----- Controlling Content
                {
                    string HTMLFieldString          = "";
                    string FieldHelp                = "The content in which this record is stored. This is similar to a database table.";
                    ContentFieldMetadataModel field = null;
                    if (adminData.adminContent.fields.ContainsKey("contentcontrolid"))
                    {
                        field = adminData.adminContent.fields["contentcontrolid"];
                        //
                        // if this record has a parent id, only include CDefs compatible with the parent record - otherwise get all for the table
                        FieldHelp     = GenericController.encodeText(field.helpMessage);
                        FieldRequired = GenericController.encodeBoolean(field.required);
                        int FieldValueInteger = (adminData.editRecord.contentControlId.Equals(0)) ? adminData.adminContent.id : adminData.editRecord.contentControlId;
                        if (!core.session.isAuthenticatedAdmin())
                        {
                            HTMLFieldString = HTMLFieldString + HtmlController.inputHidden("contentControlId", FieldValueInteger);
                        }
                        else
                        {
                            string RecordContentName = adminData.editRecord.contentControlId_Name;
                            string TableName2        = MetadataController.getContentTablename(core, RecordContentName);
                            int    TableId           = MetadataController.getRecordIdByUniqueName(core, "Tables", TableName2);
                            //
                            // Test for parentid
                            int  ParentId = 0;
                            bool ContentSupportsParentId = false;
                            if (adminData.editRecord.id > 0)
                            {
                                using (var csData = new CsModel(core)) {
                                    if (csData.openRecord(RecordContentName, adminData.editRecord.id))
                                    {
                                        ContentSupportsParentId = csData.isFieldSupported("ParentID");
                                        if (ContentSupportsParentId)
                                        {
                                            ParentId = csData.getInteger("ParentID");
                                        }
                                    }
                                }
                            }
                            bool IsEmptyList = false;
                            if (core.session.isAuthenticatedAdmin())
                            {
                                //
                                // administrator, and either ( no parentid or does not support it), let them select any content compatible with the table
                                string sqlFilter  = "(ContentTableID=" + TableId + ")";
                                int    contentCId = MetadataController.getRecordIdByUniqueName(core, ContentModel.tableMetadata.contentName, ContentModel.tableMetadata.contentName);
                                HTMLFieldString += AdminUIEditorController.getLookupContentEditor(core, "contentcontrolid", FieldValueInteger, contentCId, ref IsEmptyList, adminData.editRecord.userReadOnly, "", "", true, sqlFilter);
                                FieldHelp        = FieldHelp + " (Only administrators have access to this control. Changing the Controlling Content allows you to change who can author the record, as well as how it is edited.)";
                            }
                        }
                    }
                    if (string.IsNullOrEmpty(HTMLFieldString))
                    {
                        HTMLFieldString = adminData.editRecord.contentControlId_Name;
                    }
                    tabPanel.add(AdminUIController.getEditRow(core, HTMLFieldString, "Controlling Content", FieldHelp, FieldRequired, false, ""));
                }
                //
                // ----- Created By
                {
                    string FieldHelp  = "The people account of the user who created this record.";
                    string fieldValue = "";
                    if (adminData.editRecord == null)
                    {
                        fieldValue = "(not set)";
                    }
                    else if (adminData.editRecord.id == 0)
                    {
                        fieldValue = "(available after save)";
                    }
                    else if (adminData.editRecord.createdBy == null)
                    {
                        fieldValue = "(not set)";
                    }
                    else
                    {
                        int FieldValueInteger = adminData.editRecord.createdBy.id;
                        if (FieldValueInteger == 0)
                        {
                            fieldValue = "(not set)";
                        }
                        else
                        {
                            using (var csData = new CsModel(core)) {
                                csData.open("people", "(id=" + FieldValueInteger + ")", "name,active", false);
                                if (!csData.ok())
                                {
                                    fieldValue = "#" + FieldValueInteger + ", (deleted)";
                                }
                                else
                                {
                                    fieldValue = "#" + FieldValueInteger + ", " + csData.getText("name");
                                    if (!csData.getBoolean("active"))
                                    {
                                        fieldValue += " (inactive)";
                                    }
                                }
                                csData.close();
                            }
                        }
                    }
                    string fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore_createdBy", fieldValue, true, "");
                    tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Created By", FieldHelp, FieldRequired, false, ""));
                }
                //
                // ----- Created Date
                {
                    string FieldHelp  = "The date and time when this record was originally created.";
                    string fieldValue = "";
                    if (adminData.editRecord == null)
                    {
                        fieldValue = "(not set)";
                    }
                    else if (adminData.editRecord.id == 0)
                    {
                        fieldValue = "(available after save)";
                    }
                    else
                    {
                        if (GenericController.encodeDateMinValue(adminData.editRecord.dateAdded) == DateTime.MinValue)
                        {
                            fieldValue = "(not set)";
                        }
                        else
                        {
                            fieldValue = adminData.editRecord.dateAdded.ToString();
                        }
                    }
                    string fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore_createdDate", fieldValue, true, "");
                    tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Created Date", FieldHelp, FieldRequired, false, ""));
                }
                //
                // ----- Modified By
                {
                    string FieldHelp  = "The people account of the last user who modified this record.";
                    string fieldValue = "";
                    if (adminData.editRecord == null)
                    {
                        fieldValue = "(not set)";
                    }
                    else if (adminData.editRecord.id == 0)
                    {
                        fieldValue = "(available after save)";
                    }
                    else if (adminData.editRecord.modifiedBy == null)
                    {
                        fieldValue = "(not set)";
                    }
                    else
                    {
                        int FieldValueInteger = adminData.editRecord.modifiedBy.id;
                        if (FieldValueInteger == 0)
                        {
                            fieldValue = "(not set)";
                        }
                        else
                        {
                            using (var csData = new CsModel(core)) {
                                csData.open("people", "(id=" + FieldValueInteger + ")", "name,active", false);
                                if (!csData.ok())
                                {
                                    fieldValue = "#" + FieldValueInteger + ", (deleted)";
                                }
                                else
                                {
                                    fieldValue = "#" + FieldValueInteger + ", " + csData.getText("name");
                                    if (!csData.getBoolean("active"))
                                    {
                                        fieldValue += " (inactive)";
                                    }
                                }
                                csData.close();
                            }
                        }
                    }
                    string fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore_modifiedBy", fieldValue, true, "");
                    tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Modified By", FieldHelp, FieldRequired, false, ""));
                }
                //
                // ----- Modified Date
                {
                    string FieldHelp  = "The date and time when this record was last modified.";
                    string fieldValue = "";
                    if (adminData.editRecord == null)
                    {
                        fieldValue = "(not set)";
                    }
                    else if (adminData.editRecord.id == 0)
                    {
                        fieldValue = "(available after save)";
                    }
                    else
                    {
                        if (GenericController.encodeDateMinValue(adminData.editRecord.modifiedDate) == DateTime.MinValue)
                        {
                            fieldValue = "(not set)";
                        }
                        else
                        {
                            fieldValue = adminData.editRecord.modifiedDate.ToString();
                        }
                    }
                    string fieldEditor = AdminUIEditorController.getTextEditor(core, "ignore_modifiedBy", fieldValue, true, "");
                    tabPanel.add(AdminUIController.getEditRow(core, fieldEditor, "Modified Date", FieldHelp, false, false, ""));
                }
                string s = AdminUIController.editTable(tabPanel.text);
                result = AdminUIController.getEditPanel(core, true, "Control Information", "", s);
                adminData.editSectionPanelCount += 1;
                tabPanel = null;
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(result);
        }
        //
        //=============================================================================
        // Create a child content
        //=============================================================================
        //
        public static string get(CPClass cp)
        {
            string result = "";

            try {
                //
                bool   IsEmptyList       = false;
                int    ParentContentId   = 0;
                string ChildContentName  = "";
                int    ChildContentId    = 0;
                bool   AddAdminMenuEntry = false;
                StringBuilderLegacyController Content = new StringBuilderLegacyController();
                string FieldValue   = null;
                bool   NewGroup     = false;
                int    GroupId      = 0;
                string NewGroupName = "";
                string Button       = null;
                string Caption      = null;
                string Description  = "";
                string ButtonList   = "";
                bool   BlockForm    = false;
                //
                Button = cp.core.docProperties.getText(RequestNameButton);
                if (Button == ButtonCancel)
                {
                    //
                    //
                    //
                    return(cp.core.webServer.redirect("/" + cp.core.appConfig.adminRoute, "GetContentChildTool, Cancel Button Pressed"));
                }
                else if (!cp.core.session.isAuthenticatedAdmin())
                {
                    //
                    //
                    //
                    ButtonList = ButtonCancel;
                    Content.add(AdminUIController.getFormBodyAdminOnly());
                }
                else
                {
                    //
                    if (Button != ButtonOK)
                    {
                        //
                        // Load defaults
                        //
                        ParentContentId = cp.core.docProperties.getInteger("ParentContentID");
                        if (ParentContentId == 0)
                        {
                            ParentContentId = ContentMetadataModel.getContentId(cp.core, "Page Content");
                        }
                        AddAdminMenuEntry = true;
                        GroupId           = 0;
                    }
                    else
                    {
                        //
                        // Process input
                        //
                        ParentContentId = cp.core.docProperties.getInteger("ParentContentID");
                        var parentContentMetadata = ContentMetadataModel.create(cp.core, ParentContentId);
                        ChildContentName  = cp.core.docProperties.getText("ChildContentName");
                        AddAdminMenuEntry = cp.core.docProperties.getBoolean("AddAdminMenuEntry");
                        GroupId           = cp.core.docProperties.getInteger("GroupID");
                        NewGroup          = cp.core.docProperties.getBoolean("NewGroup");
                        NewGroupName      = cp.core.docProperties.getText("NewGroupName");
                        //
                        if ((parentContentMetadata == null) || (string.IsNullOrEmpty(ChildContentName)))
                        {
                            Processor.Controllers.ErrorController.addUserError(cp.core, "You must select a parent and provide a child name.");
                        }
                        else
                        {
                            //
                            // Create Definition
                            //
                            Description = Description + "<div>&nbsp;</div>"
                                          + "<div>Creating content [" + ChildContentName + "] from [" + parentContentMetadata.name + "]</div>";
                            var childContentMetadata = parentContentMetadata.createContentChild(cp.core, ChildContentName, cp.core.session.user.id);

                            ChildContentId = ContentMetadataModel.getContentId(cp.core, ChildContentName);
                            //
                            // Create Group and Rule
                            //
                            if (NewGroup && (!string.IsNullOrEmpty(NewGroupName)))
                            {
                                using (var csData = new CsModel(cp.core)) {
                                    csData.open("Groups", "name=" + DbController.encodeSQLText(NewGroupName));
                                    if (csData.ok())
                                    {
                                        Description = Description + "<div>Group [" + NewGroupName + "] already exists, using existing group.</div>";
                                        GroupId     = csData.getInteger("ID");
                                    }
                                    else
                                    {
                                        Description = Description + "<div>Creating new group [" + NewGroupName + "]</div>";
                                        csData.close();
                                        csData.insert("Groups");
                                        if (csData.ok())
                                        {
                                            GroupId = csData.getInteger("ID");
                                            csData.set("Name", NewGroupName);
                                            csData.set("Caption", NewGroupName);
                                        }
                                    }
                                }
                            }
                            if (GroupId != 0)
                            {
                                using (var csData = new CsModel(cp.core)) {
                                    csData.insert("Group Rules");
                                    if (csData.ok())
                                    {
                                        Description = Description + "<div>Assigning group [" + MetadataController.getRecordName(cp.core, "Groups", GroupId) + "] to edit content [" + ChildContentName + "].</div>";
                                        csData.set("GroupID", GroupId);
                                        csData.set("ContentID", ChildContentId);
                                    }
                                }
                            }
                            //
                            // Add Admin Menu Entry
                            //
                            if (AddAdminMenuEntry)
                            {
                                //
                                // Add Navigator entries
                            }
                            //
                            Description = Description + "<div>&nbsp;</div>"
                                          + "<div>Your new content is ready. <a href=\"?" + rnAdminForm + "=22\">Click here</a> to create another Content Definition, or hit [Cancel] to return to the main menu.</div>";
                            ButtonList = ButtonCancel;
                            BlockForm  = true;
                        }
                        cp.core.clearMetaData();
                        cp.core.cache.invalidateAll();
                    }
                    //
                    // Get the form
                    //
                    if (!BlockForm)
                    {
                        string tableBody = "";
                        //
                        FieldValue = "<select size=\"1\" name=\"ParentContentID\" ID=\"\"><option value=\"\">Select One</option>";
                        FieldValue = FieldValue + GetContentChildTool_Options(cp, 0, ParentContentId);
                        FieldValue = FieldValue + "</select>";
                        tableBody += AdminUIController.getEditRowLegacy(cp.core, FieldValue, "Parent Content Name", "", false, false, "");
                        //
                        FieldValue = HtmlController.inputText_Legacy(cp.core, "ChildContentName", ChildContentName, 1, 40);
                        tableBody += AdminUIController.getEditRowLegacy(cp.core, FieldValue, "New Child Content Name", "", false, false, "");
                        //
                        FieldValue = ""
                                     + HtmlController.inputRadio("NewGroup", false.ToString(), NewGroup.ToString()) + cp.core.html.selectFromContent("GroupID", GroupId, "Groups", "", "", "", ref IsEmptyList) + "(Select a current group)"
                                     + "<br>" + HtmlController.inputRadio("NewGroup", true.ToString(), NewGroup.ToString()) + HtmlController.inputText_Legacy(cp.core, "NewGroupName", NewGroupName) + "(Create a new group)";
                        tableBody += AdminUIController.getEditRowLegacy(cp.core, FieldValue, "Content Manager Group", "", false, false, "");
                        //
                        Content.add(AdminUIController.editTable(tableBody));
                        Content.add("</td></tr>" + kmaEndTable);
                        //
                        ButtonList = ButtonOK + "," + ButtonCancel;
                    }
                    Content.add(HtmlController.inputHidden(rnAdminSourceForm, AdminFormContentChildTool));
                }
                //
                Caption     = "Create Content Definition";
                Description = "<div>This tool is used to create content definitions that help segregate your content into authorable segments.</div>" + Description;
                result      = AdminUIController.getToolBody(cp.core, Caption, ButtonList, "", false, false, Description, "", 0, Content.text);
            } catch (Exception ex) {
                LogController.logError(cp.core, ex);
            }
            return(result);
        }
예제 #14
0
        //
        //====================================================================================================
        /// <summary>
        /// Send the Member his username and password
        /// </summary>
        /// <param name="Email"></param>
        /// <returns></returns>
        public static bool sendPassword(CoreController core, string Email, ref string returnUserMessage)
        {
            bool result = false;

            returnUserMessage = "";
            try {
                const string passwordChrs       = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678999999";
                const int    passwordChrsLength = 62;
                //
                string workingEmail = GenericController.encodeText(Email);
                //
                string Message     = "";
                string FromAddress = "";
                string subject     = "";
                if (string.IsNullOrEmpty(workingEmail))
                {
                    ErrorController.addUserError(core, "Please enter your email address before requesting your username and password.");
                }
                else
                {
                    int atPtr = GenericController.strInstr(1, workingEmail, "@");
                    if (atPtr < 2)
                    {
                        //
                        // email not valid
                        //
                        ErrorController.addUserError(core, "Please enter a valid email address before requesting your username and password.");
                    }
                    else
                    {
                        string EMailName = strMid(workingEmail, 1, atPtr - 1);
                        //
                        LogController.addSiteActivity(core, "password request for email " + workingEmail, core.session.user.id, core.session.user.organizationId);
                        //
                        bool allowEmailLogin = core.siteProperties.getBoolean("allowEmailLogin", false);
                        int  recordCnt       = 0;
                        using (var csData = new CsModel(core)) {
                            string sqlCriteria = "(email=" + DbController.encodeSQLText(workingEmail) + ")";
                            sqlCriteria = sqlCriteria + "and((dateExpires is null)or(dateExpires>" + DbController.encodeSQLDate(core.dateTimeNowMockable) + "))";
                            csData.open("People", sqlCriteria, "ID", true, core.session.user.id, "username,password", 1);
                            if (!csData.ok())
                            {
                                //
                                // valid login account for this email not found
                                //
                                if (encodeText(strMid(workingEmail, atPtr + 1)).ToLowerInvariant() == "contensive.com")
                                {
                                    //
                                    // look for expired account to renew
                                    //
                                    csData.close();
                                    csData.open("People", "((email=" + DbController.encodeSQLText(workingEmail) + "))", "ID");
                                    if (csData.ok())
                                    {
                                        //
                                        // renew this old record
                                        //
                                        csData.set("developer", "1");
                                        csData.set("admin", "1");
                                        if (csData.getDate("dateExpires") > DateTime.MinValue)
                                        {
                                            csData.set("dateExpires", core.dateTimeNowMockable.AddDays(7).Date.ToString());
                                        }
                                    }
                                    else
                                    {
                                        //
                                        // inject support record
                                        //
                                        csData.close();
                                        csData.insert("people");
                                        csData.set("name", "Contensive Support");
                                        csData.set("email", workingEmail);
                                        csData.set("developer", "1");
                                        csData.set("admin", "1");
                                        csData.set("dateExpires", core.dateTimeNowMockable.AddDays(7).Date.ToString());
                                    }
                                }
                                else
                                {
                                    ErrorController.addUserError(core, "No current user was found matching this email address. Please try again. ");
                                }
                            }
                            if (csData.ok())
                            {
                                FromAddress = core.siteProperties.getText("EmailFromAddress", "info@" + core.webServer.requestDomain);
                                subject     = "Password Request at " + core.webServer.requestDomain;
                                Message     = "";
                                while (csData.ok())
                                {
                                    bool updateUser = false;
                                    if (string.IsNullOrEmpty(Message))
                                    {
                                        Message  = "This email was sent in reply to a request at " + core.webServer.requestDomain + " for the username and password associated with this email address. ";
                                        Message += "If this request was made by you, please return to the login screen and use the following:\r\n";
                                        Message += Environment.NewLine;
                                    }
                                    else
                                    {
                                        Message += Environment.NewLine;
                                        Message += "Additional user accounts with the same email address: \r\n";
                                    }
                                    //
                                    // username
                                    //
                                    string Username   = csData.getText("Username");
                                    bool   usernameOK = true;
                                    int    Ptr        = 0;
                                    if (!allowEmailLogin)
                                    {
                                        if (Username != Username.Trim())
                                        {
                                            Username   = Username.Trim();
                                            updateUser = true;
                                        }
                                        if (string.IsNullOrEmpty(Username))
                                        {
                                            usernameOK = false;
                                            Ptr        = 0;
                                            while (!usernameOK && (Ptr < 100))
                                            {
                                                Username   = EMailName + encodeInteger(Math.Floor(encodeNumber(Microsoft.VisualBasic.VBMath.Rnd() * 9999)));
                                                usernameOK = !core.session.isLoginOK(Username, "test");
                                                Ptr        = Ptr + 1;
                                            }
                                            if (usernameOK)
                                            {
                                                updateUser = true;
                                            }
                                        }
                                        Message += " username: "******"Password");
                                        if (Password.Trim() != Password)
                                        {
                                            Password   = Password.Trim();
                                            updateUser = true;
                                        }
                                        if (string.IsNullOrEmpty(Password))
                                        {
                                            for (Ptr = 0; Ptr <= 8; Ptr++)
                                            {
                                                int Index = encodeInteger(Microsoft.VisualBasic.VBMath.Rnd() * passwordChrsLength);
                                                Password = Password + strMid(passwordChrs, Index, 1);
                                            }
                                            updateUser = true;
                                        }
                                        Message += " password: "******"username", Username);
                                            csData.set("password", Password);
                                        }
                                        recordCnt = recordCnt + 1;
                                    }
                                    csData.goNext();
                                }
                            }
                        }
                    }
                }
                if (result)
                {
                    string sendStatus = "";
                    EmailController.queueAdHocEmail(core, "Password Email", core.session.user.id, workingEmail, FromAddress, subject, Message, "", "", "", true, false, 0, ref sendStatus);
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(result);
        }
        //
        //====================================================================================================
        //
        public static string get(CoreController core)
        {
            string result = "";

            try {
                //
                int    ContentId   = 0;
                string TableName   = "";
                string ContentName = "";
                StringBuilderLegacyController Stream = new StringBuilderLegacyController();
                string          ButtonList           = null;
                string          Description          = null;
                string          Caption     = null;
                int             NavId       = 0;
                int             ParentNavId = 0;
                DataSourceModel datasource  = DataSourceModel.create(core.cpParent, core.docProperties.getInteger("DataSourceID"));
                //
                ButtonList  = ButtonCancel + "," + ButtonRun;
                Caption     = "Create Content Definition";
                Description = "This tool creates a Content Definition. If the SQL table exists, it is used. If it does not exist, it is created. If records exist in the table with a blank ContentControlID, the ContentControlID will be populated from this new definition. A Navigator Menu entry will be added under Manage Site Content - Advanced.";
                //
                //   print out the submit form
                //
                if (core.docProperties.getText("Button") != "")
                {
                    //
                    // Process input
                    //
                    ContentName = core.docProperties.getText("ContentName");
                    TableName   = core.docProperties.getText("TableName");
                    //
                    Stream.add(SpanClassAdminSmall);
                    Stream.add("<P>Creating content [" + ContentName + "] on table [" + TableName + "] on Datasource [" + datasource.name + "].</P>");
                    if ((!string.IsNullOrEmpty(ContentName)) && (!string.IsNullOrEmpty(TableName)) && (!string.IsNullOrEmpty(datasource.name)))
                    {
                        using (var db = new DbController(core, datasource.name)) {
                            db.createSQLTable(TableName);
                        }
                        ContentMetadataModel.createFromSQLTable(core, datasource, TableName, ContentName);
                        core.cache.invalidateAll();
                        core.clearMetaData();
                        ContentId   = Processor.Models.Domain.ContentMetadataModel.getContentId(core, ContentName);
                        ParentNavId = MetadataController.getRecordIdByUniqueName(core, NavigatorEntryModel.tableMetadata.contentName, "Manage Site Content");
                        if (ParentNavId != 0)
                        {
                            ParentNavId = 0;
                            using (var csSrc = new CsModel(core)) {
                                if (csSrc.open(NavigatorEntryModel.tableMetadata.contentName, "(name=" + DbController.encodeSQLText("Advanced") + ")and(parentid=" + ParentNavId + ")"))
                                {
                                    ParentNavId = csSrc.getInteger("ID");
                                }
                            }
                            if (ParentNavId != 0)
                            {
                                using (var csDest = new CsModel(core)) {
                                    csDest.open(NavigatorEntryModel.tableMetadata.contentName, "(name=" + DbController.encodeSQLText(ContentName) + ")and(parentid=" + NavId + ")");
                                    if (!csDest.ok())
                                    {
                                        csDest.close();
                                        csDest.insert(NavigatorEntryModel.tableMetadata.contentName);
                                    }
                                    if (csDest.ok())
                                    {
                                        csDest.set("name", ContentName);
                                        csDest.set("parentid", ParentNavId);
                                        csDest.set("contentid", ContentId);
                                    }
                                }
                            }
                        }
                        ContentId = ContentMetadataModel.getContentId(core, ContentName);
                        Stream.add("<P>Content Definition was created. An admin menu entry for this definition has been added under 'Site Content', and will be visible on the next page view. Use the [<a href=\"?af=105&ContentID=" + ContentId + "\">Edit Content Definition Fields</a>] tool to review and edit this definition's fields.</P>");
                    }
                    else
                    {
                        Stream.add("<P>Error, a required field is missing. Content not created.</P>");
                    }
                    Stream.add("</SPAN>");
                }
                Stream.add(SpanClassAdminNormal);
                Stream.add("Data Source<br>");
                Stream.add(core.html.selectFromContent("DataSourceID", datasource.id, "Data Sources", "", "Default"));
                Stream.add("<br><br>");
                Stream.add("Content Name<br>");
                Stream.add(HtmlController.inputText_Legacy(core, "ContentName", ContentName, 1, 40));
                Stream.add("<br><br>");
                Stream.add("Table Name<br>");
                Stream.add(HtmlController.inputText_Legacy(core, "TableName", TableName, 1, 40));
                Stream.add("<br><br>");
                Stream.add("</SPAN>");
                result = AdminUIController.getToolBody(core, Caption, ButtonList, "", false, false, Description, "", 10, Stream.text);
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(result);
        }
예제 #16
0
 //
 //========================================================================
 //
 public static void processJoinForm(CoreController core)
 {
     try {
         string ErrorMessage = "";
         string FirstName    = null;
         string LastName     = null;
         string FullName     = null;
         string Email        = null;
         int    errorCode    = 0;
         //
         string loginForm_Username = "";
         string loginForm_Password = "";
         loginForm_Username = core.docProperties.getText("username");
         loginForm_Password = core.docProperties.getText("password");
         //
         if (!GenericController.encodeBoolean(core.siteProperties.getBoolean("AllowMemberJoin", false)))
         {
             ErrorController.addUserError(core, "This site does not accept public main_MemberShip.");
         }
         else
         {
             if (!core.session.isNewCredentialOK(loginForm_Username, loginForm_Password, ref ErrorMessage, ref errorCode))
             {
                 ErrorController.addUserError(core, ErrorMessage);
             }
             else
             {
                 if (!(!core.doc.userErrorList.Count.Equals(0)))
                 {
                     using (var csData = new CsModel(core)) {
                         csData.open("people", "ID=" + DbController.encodeSQLNumber(core.session.user.id));
                         if (!csData.ok())
                         {
                             LogController.logError(core, new Exception("Could not open the current members account to set the username and password."));
                         }
                         else
                         {
                             if ((csData.getText("username") != "") || (csData.getText("password") != "") || (csData.getBoolean("admin")) || (csData.getBoolean("developer")))
                             {
                                 //
                                 // if the current account can be logged into, you can not join 'into' it
                                 //
                                 core.session.logout();
                             }
                             FirstName = core.docProperties.getText("firstname");
                             LastName  = core.docProperties.getText("lastname");
                             FullName  = FirstName + " " + LastName;
                             Email     = core.docProperties.getText("email");
                             csData.set("FirstName", FirstName);
                             csData.set("LastName", LastName);
                             csData.set("Name", FullName);
                             csData.set("username", loginForm_Username);
                             csData.set("password", loginForm_Password);
                             core.session.authenticateById(core.session.user.id, core.session);
                         }
                         csData.close();
                     }
                 }
             }
         }
         PersonModel.invalidateCacheOfRecord <PersonModel>(core.cpParent, core.session.user.id);
     } catch (Exception ex) {
         LogController.logError(core, ex);
         throw;
     }
 }
예제 #17
0
        //
        //====================================================================================================
        //
        public static string get(CoreController core)
        {
            string tempGetForm_QuickStats = null;

            try {
                string sql        = null;
                string RowColor   = null;
                string Panel      = null;
                int    VisitID    = 0;
                int    VisitCount = 0;
                double PageCount  = 0;
                StringBuilderLegacyController Stream = new StringBuilderLegacyController();
                //
                // --- Start a form to make a refresh button
                Stream.add(core.html.getPanelButtons(ButtonCancel + "," + ButtonRefresh));
                Stream.add("<input TYPE=\"hidden\" NAME=\"asf\" VALUE=\"" + AdminFormQuickStats + "\">");
                Stream.add(core.html.getPanel(" "));
                //

                // --- Indented part (Title Area plus page)
                //
                Stream.add("<table border=\"0\" cellpadding=\"20\" cellspacing=\"0\" width=\"100%\"><tr><td>" + SpanClassAdminNormal);
                Stream.add("<h1>Real-Time Activity Report</h1>");
                //
                // --- set column width
                //
                Stream.add("<h2>Visits Today</h2>");
                Stream.add("<table border=\"0\" cellpadding=\"3\" cellspacing=\"0\" width=\"100%\" style=\"background-color:white;border-top:1px solid #888;\">");
                //
                // ----- All Visits Today
                //
                using (var csData = new CsModel(core)) {
                    sql = "SELECT Count(ccVisits.ID) AS VisitCount, Avg(ccVisits.PageVisits) AS PageCount FROM ccVisits WHERE ((ccVisits.StartTime)>" + DbController.encodeSQLDate(core.doc.profileStartTime.Date) + ");";
                    csData.openSql(sql);
                    if (csData.ok())
                    {
                        VisitCount = csData.getInteger("VisitCount");
                        PageCount  = csData.getNumber("pageCount");
                        Stream.add("<tr>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "All Visits</span></td>");
                        Stream.add("<td style=\"width:150px;border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "<a target=\"_blank\" href=\"/" + HtmlController.encodeHtml(core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormReports + "&rid=3&DateFrom=" + core.doc.profileStartTime + "&DateTo=" + core.doc.profileStartTime.ToShortDateString()) + "\">" + VisitCount + "</A>, " + string.Format("{0:N2}", PageCount) + " pages/visit.</span></td>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "This includes all visitors to the website, including guests, bots and administrators. Pages/visit includes page hits and not ajax or remote method hits.</span></td>");
                        Stream.add("</tr>");
                    }
                }
                //
                // ----- Non-Bot Visits Today
                //
                using (var csData = new CsModel(core)) {
                    sql = "SELECT Count(ccVisits.ID) AS VisitCount, Avg(ccVisits.PageVisits) AS PageCount FROM ccVisits WHERE (ccVisits.CookieSupport=1)and((ccVisits.StartTime)>" + DbController.encodeSQLDate(core.doc.profileStartTime.Date) + ");";
                    csData.openSql(sql);
                    if (csData.ok())
                    {
                        VisitCount = csData.getInteger("VisitCount");
                        PageCount  = csData.getNumber("pageCount");
                        Stream.add("<tr>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "Non-bot Visits</span></td>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "<a target=\"_blank\" href=\"/" + HtmlController.encodeHtml(core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormReports + "&rid=3&DateFrom=" + core.doc.profileStartTime.ToShortDateString() + "&DateTo=" + core.doc.profileStartTime.ToShortDateString()) + "\">" + VisitCount + "</A>, " + string.Format("{0:N2}", PageCount) + " pages/visit.</span></td>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "This excludes hits from visitors identified as bots. Pages/visit includes page hits and not ajax or remote method hits.</span></td>");
                        Stream.add("</tr>");
                    }
                }
                //
                // ----- Visits Today by new visitors
                //
                using (var csData = new CsModel(core)) {
                    sql = "SELECT Count(ccVisits.ID) AS VisitCount, Avg(ccVisits.PageVisits) AS PageCount FROM ccVisits WHERE (ccVisits.CookieSupport=1)and(ccVisits.StartTime>" + DbController.encodeSQLDate(core.doc.profileStartTime.Date) + ")AND(ccVisits.VisitorNew<>0);";
                    csData.openSql(sql);
                    if (csData.ok())
                    {
                        VisitCount = csData.getInteger("VisitCount");
                        PageCount  = csData.getNumber("pageCount");
                        Stream.add("<tr>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "Visits by New Visitors</span></td>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "<a target=\"_blank\" href=\"/" + HtmlController.encodeHtml(core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormReports + "&rid=3&ExcludeOldVisitors=1&DateFrom=" + core.doc.profileStartTime.ToShortDateString() + "&DateTo=" + core.doc.profileStartTime.ToShortDateString()) + "\">" + VisitCount + "</A>, " + string.Format("{0:N2}", PageCount) + " pages/visit.</span></td>");
                        Stream.add("<td style=\"border-bottom:1px solid #888;\" valign=top>" + SpanClassAdminNormal + "This includes only new visitors not identified as bots. Pages/visit includes page hits and not ajax or remote method hits.</span></td>");
                        Stream.add("</tr>");
                    }
                    csData.close();
                }
                //
                Stream.add("</table>");
                //
                // ----- Visits currently online
                //
                {
                    Panel = "";
                    Stream.add("<h2>Current Visits</h2>");
                    using (var csData = new CsModel(core)) {
                        sql = "SELECT ccVisits.HTTP_REFERER as referer,ccVisits.remote_addr as Remote_Addr, ccVisits.LastVisitTime as LastVisitTime, ccVisits.PageVisits as PageVisits, ccMembers.Name as MemberName, ccVisits.ID as VisitID, ccMembers.ID as MemberID"
                              + " FROM ccVisits LEFT JOIN ccMembers ON ccVisits.memberId = ccMembers.ID"
                              + " WHERE (((ccVisits.LastVisitTime)>" + DbController.encodeSQLDate(core.doc.profileStartTime.AddHours(-1)) + "))"
                              + " ORDER BY ccVisits.LastVisitTime DESC;";
                        csData.openSql(sql);
                        if (csData.ok())
                        {
                            Panel    = Panel + "<table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"2\">";
                            Panel    = Panel + "<tr bgcolor=\"#B0B0B0\">";
                            Panel    = Panel + "<td width=\"20%\" align=\"left\">" + SpanClassAdminNormal + "User</td>";
                            Panel    = Panel + "<td width=\"20%\" align=\"left\">" + SpanClassAdminNormal + "IP&nbsp;Address</td>";
                            Panel    = Panel + "<td width=\"20%\" align=\"left\">" + SpanClassAdminNormal + "Last&nbsp;Page&nbsp;Hit</td>";
                            Panel    = Panel + "<td width=\"10%\" align=\"right\">" + SpanClassAdminNormal + "Page&nbsp;Hits</td>";
                            Panel    = Panel + "<td width=\"10%\" align=\"right\">" + SpanClassAdminNormal + "Visit</td>";
                            Panel    = Panel + "<td width=\"30%\" align=\"left\">" + SpanClassAdminNormal + "Referer</td>";
                            Panel    = Panel + "</tr>";
                            RowColor = "ccPanelRowEven";
                            while (csData.ok())
                            {
                                VisitID = csData.getInteger("VisitID");
                                Panel   = Panel + "<tr class=\"" + RowColor + "\">";
                                Panel   = Panel + "<td align=\"left\">" + SpanClassAdminNormal + "<a target=\"_blank\" href=\"/" + HtmlController.encodeHtml(core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormReports + "&rid=16&MemberID=" + csData.getInteger("MemberID")) + "\">" + csData.getText("MemberName") + "</A></span></td>";
                                Panel   = Panel + "<td align=\"left\">" + SpanClassAdminNormal + csData.getText("Remote_Addr") + "</span></td>";
                                Panel   = Panel + "<td align=\"left\">" + SpanClassAdminNormal + csData.getDate("LastVisitTime").ToString("") + "</span></td>";
                                Panel   = Panel + "<td align=\"right\">" + SpanClassAdminNormal + "<a target=\"_blank\" href=\"/" + core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormReports + "&rid=10&VisitID=" + VisitID + "\">" + csData.getText("PageVisits") + "</A></span></td>";
                                Panel   = Panel + "<td align=\"right\">" + SpanClassAdminNormal + "<a target=\"_blank\" href=\"/" + core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormReports + "&rid=17&VisitID=" + VisitID + "\">" + VisitID + "</A></span></td>";
                                Panel   = Panel + "<td align=\"left\">" + SpanClassAdminNormal + "&nbsp;" + csData.getText("referer") + "</span></td>";
                                Panel   = Panel + "</tr>";
                                if (RowColor == "ccPanelRowEven")
                                {
                                    RowColor = "ccPanelRowOdd";
                                }
                                else
                                {
                                    RowColor = "ccPanelRowEven";
                                }
                                csData.goNext();
                            }
                            Panel = Panel + "</table>";
                        }
                        csData.close();
                    }
                    Stream.add(core.html.getPanel(Panel, "ccPanel", "ccPanelShadow", "ccPanelHilite", "100%", 0));
                }
                Stream.add("</td></tr></table>");
                //Stream.Add(htmlController.form_end());
                //
                tempGetForm_QuickStats = HtmlController.form(core, Stream.text);
                core.html.addTitle("Quick Stats");
                return(tempGetForm_QuickStats);
                //
                // ----- Error Trap
                //
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(tempGetForm_QuickStats);
        }
예제 #18
0
 //
 //=========================================================================================
 /// <summary>
 /// summarized visits hourly
 /// </summary>
 /// <param name="core"></param>
 /// <param name="env"></param>
 public static void housekeep(CoreController core, HouseKeepEnvironmentModel env)
 {
     try {
         //
         LogController.logInfo(core, "Housekeep, visitsummary");
         //
         bool newHour = (core.dateTimeNowMockable.Hour != env.lastCheckDateTime.Hour);
         if (env.forceHousekeep || newHour)
         {
             //
             // Set NextSummaryStartDate based on the last time we ran hourly summarization
             //
             DateTime LastTimeSummaryWasRun = env.visitArchiveDate;
             core.db.sqlCommandTimeout = 180;
             using (var csData = new CsModel(core)) {
                 if (csData.openSql(core.db.getSQLSelect("ccVisitSummary", "DateAdded", "(timeduration=1)and(Dateadded>" + DbController.encodeSQLDate(env.visitArchiveDate) + ")", "id Desc", "", 1)))
                 {
                     LastTimeSummaryWasRun = csData.getDate("DateAdded");
                     LogController.logInfo(core, "Update hourly visit summary, last time summary was run was [" + LastTimeSummaryWasRun + "]");
                 }
                 else
                 {
                     LogController.logInfo(core, "Update hourly visit summary, no hourly summaries were found, set start to [" + LastTimeSummaryWasRun + "]");
                 }
             }
             DateTime NextSummaryStartDate = LastTimeSummaryWasRun;
             //
             // Each hourly entry includes visits that started during that hour, but we do not know when they finished (maybe during last hour)
             //   Find the oldest starttime of all the visits with endtimes after the LastTimeSummaryWasRun. Resummarize all periods
             //   from then to now
             //
             //   For the past 24 hours, find the oldest visit with the last viewing during the last hour
             //
             DateTime StartOfHour     = (new DateTime(LastTimeSummaryWasRun.Year, LastTimeSummaryWasRun.Month, LastTimeSummaryWasRun.Day, LastTimeSummaryWasRun.Hour, 1, 1)).AddHours(-1); // (Int(24 * LastTimeSummaryWasRun) / 24) - PeriodStep
             DateTime OldestDateAdded = StartOfHour;
             core.db.sqlCommandTimeout = 180;
             using (var csData = new CsModel(core)) {
                 if (csData.openSql(core.db.getSQLSelect("ccVisits", "DateAdded", "LastVisitTime>" + DbController.encodeSQLDate(StartOfHour), "dateadded", "", 1)))
                 {
                     OldestDateAdded = csData.getDate("DateAdded");
                     if (OldestDateAdded < NextSummaryStartDate)
                     {
                         NextSummaryStartDate = OldestDateAdded;
                         LogController.logInfo(core, "Update hourly visit summary, found a visit with the last viewing during the past hour. It started [" + OldestDateAdded + "], before the last summary was run.");
                     }
                 }
             }
             DateTime PeriodStartDate = core.dateTimeNowMockable.Date.AddDays(-90);
             double   PeriodStep      = 1;
             int      HoursPerDay     = 0;
             core.db.sqlCommandTimeout = 180;
             for (double PeriodDatePtr = PeriodStartDate.ToOADate(); PeriodDatePtr <= OldestDateAdded.ToOADate(); PeriodDatePtr += PeriodStep)
             {
                 //
                 // Verify there are 24 hour records for every day back the past 90 days
                 //
                 DateTime DateofMissingSummary = DateTime.MinValue;
                 using (var csData = new CsModel(core)) {
                     if (csData.openSql("select count(id) as HoursPerDay from ccVisitSummary where TimeDuration=1 and DateNumber=" + encodeInteger(PeriodDatePtr) + " group by DateNumber"))
                     {
                         HoursPerDay = csData.getInteger("HoursPerDay");
                     }
                     csData.close();
                     if (HoursPerDay < 24)
                     {
                         DateofMissingSummary = DateTime.FromOADate(PeriodDatePtr);
                         break;
                     }
                 }
                 if ((DateofMissingSummary != DateTime.MinValue) && (DateofMissingSummary < NextSummaryStartDate))
                 {
                     LogController.logInfo(core, "Found a missing hourly period in the visit summary table [" + DateofMissingSummary + "], it only has [" + HoursPerDay + "] hourly summaries.");
                     NextSummaryStartDate = DateofMissingSummary;
                 }
                 //
                 // Now summarize all visits during all hourly periods between OldestDateAdded and the previous Hour
                 //
                 LogController.logInfo(core, "Summaryize visits hourly, starting [" + NextSummaryStartDate + "]");
                 PeriodStep = (double)1 / (double)24;
                 VisitSummaryClass.summarizePeriod(core, env, NextSummaryStartDate, core.dateTimeNowMockable, 1, core.siteProperties.dataBuildVersion, env.oldestVisitSummaryWeCareAbout);
             }
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
예제 #19
0
 //
 //=========================================================================================
 // Summarize the visits
 //   excludes non-cookie visits
 //   excludes administrator and developer visits
 //   excludes authenticated users with ExcludeFromReporting
 //
 // Average time on site
 //
 //   Example data
 //   Pages       TimeToLastHit
 //   1           0           - hit 1 page, start time = last time
 //   10          3510        - hit 10 pages, first hit time - last hit time = 3510
 //   2           30          - hit 2 pages, first hit time - last hit time = 30
 //
 // AveReadTime is the average time spent reading pages
 //   this is calculated from the multi-page visits only
 //   = MultiPageTimeToLastHitSum / ( MultiPageHitCnt - MultiPageVisitCnt )
 //   = ( 3510 + 30 ) / ((10+2) - 2 )
 //   = 354
 //
 // TotalTimeOnSite is the total time people spent reading pages
 //   There are two parts:
 //     1) the TimeToLastHit, which covers all but the last hit of each visit
 //     2) assume the last hit of each visit is the AveReadTime
 //   = MultiPageTimeToLastHitSum + ( AveReadTime * VisitCnt )
 //   = ( 3510 + 30 ) + ( 354 * 3 )
 //   = 4602
 //
 // AveTimeOnSite
 //   = TotalTimeOnSite / TotalHits
 //   = 4602 / 3
 //   = 1534
 //
 //=========================================================================================
 //
 private static void summarizePeriod(CoreController core, HouseKeepEnvironmentModel env, DateTime StartTimeDate, DateTime EndTimeDate, int HourDuration, string BuildVersion, DateTime OldestVisitSummaryWeCareAbout)
 {
     try {
         //
         if (string.CompareOrdinal(BuildVersion, CoreController.codeVersion()) >= 0)
         {
             DateTime PeriodStart = default(DateTime);
             PeriodStart = StartTimeDate;
             if (PeriodStart < OldestVisitSummaryWeCareAbout)
             {
                 PeriodStart = OldestVisitSummaryWeCareAbout;
             }
             double StartTimeHoursSinceMidnight = PeriodStart.TimeOfDay.TotalHours;
             PeriodStart = PeriodStart.Date.AddHours(StartTimeHoursSinceMidnight);
             DateTime PeriodDatePtr = default(DateTime);
             PeriodDatePtr = PeriodStart;
             while (PeriodDatePtr < EndTimeDate)
             {
                 //
                 int      DateNumber = encodeInteger(PeriodDatePtr.AddHours(HourDuration / 2.0).ToOADate());
                 int      TimeNumber = encodeInteger(PeriodDatePtr.TimeOfDay.TotalHours);
                 DateTime DateStart  = default(DateTime);
                 DateStart = PeriodDatePtr.Date;
                 DateTime DateEnd = default(DateTime);
                 DateEnd = PeriodDatePtr.AddHours(HourDuration).Date;
                 //
                 // No Cookie Visits
                 //
                 string SQL = "select count(v.id) as NoCookieVisits"
                              + " from ccvisits v"
                              + " where (v.CookieSupport<>1)"
                              + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                              + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                              + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                              + "";
                 int NoCookieVisits = 0;
                 using (var csData = new CsModel(core)) {
                     core.db.sqlCommandTimeout = 180;
                     csData.openSql(SQL);
                     if (csData.ok())
                     {
                         NoCookieVisits = csData.getInteger("NoCookieVisits");
                     }
                 }
                 //
                 // Total Visits
                 //
                 SQL = "select count(v.id) as VisitCnt ,Sum(v.PageVisits) as HitCnt ,sum(v.TimetoLastHit) as TimeOnSite"
                       + " from ccvisits v"
                       + " where (v.CookieSupport<>0)"
                       + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                       + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                       + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                       + "";
                 //
                 int VisitCnt = 0;
                 int HitCnt   = 0;
                 using (var csData = new CsModel(core)) {
                     core.db.sqlCommandTimeout = 180;
                     csData.openSql(SQL);
                     if (csData.ok())
                     {
                         VisitCnt = csData.getInteger("VisitCnt");
                         HitCnt   = csData.getInteger("HitCnt");
                         double TimeOnSite = csData.getNumber("TimeOnSite");
                     }
                 }
                 //
                 // -- Visits by new visitors
                 int    NewVisitorVisits    = 0;
                 int    SinglePageVisits    = 0;
                 int    AuthenticatedVisits = 0;
                 int    MobileVisits        = 0;
                 int    BotVisits           = 0;
                 double AveTimeOnSite       = 0;
                 if (VisitCnt > 0)
                 {
                     SQL = "select count(v.id) as NewVisitorVisits"
                           + " from ccvisits v"
                           + " where (v.CookieSupport<>0)"
                           + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                           + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                           + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                           + " and(v.VisitorNew<>0)"
                           + "";
                     using (var csData = new CsModel(core)) {
                         core.db.sqlCommandTimeout = 180;
                         csData.openSql(SQL);
                         if (csData.ok())
                         {
                             NewVisitorVisits = csData.getInteger("NewVisitorVisits");
                         }
                     }
                     //
                     // Single Page Visits
                     //
                     SQL = "select count(v.id) as SinglePageVisits"
                           + " from ccvisits v"
                           + " where (v.CookieSupport<>0)"
                           + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                           + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                           + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                           + " and(v.PageVisits=1)"
                           + "";
                     using (var csData = new CsModel(core)) {
                         core.db.sqlCommandTimeout = 180;
                         csData.openSql(SQL);
                         if (csData.ok())
                         {
                             SinglePageVisits = csData.getInteger("SinglePageVisits");
                         }
                     }
                     //
                     // Multipage Visits
                     //
                     SQL = "select count(v.id) as VisitCnt ,sum(v.PageVisits) as HitCnt ,sum(v.TimetoLastHit) as TimetoLastHitSum "
                           + " from ccvisits v"
                           + " where (v.CookieSupport<>0)"
                           + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                           + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                           + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                           + " and(PageVisits>1)"
                           + "";
                     int    MultiPageHitCnt           = 0;
                     int    MultiPageVisitCnt         = 0;
                     double MultiPageTimetoLastHitSum = 0;
                     using (var csData = new CsModel(core)) {
                         core.db.sqlCommandTimeout = 180;
                         csData.openSql(SQL);
                         if (csData.ok())
                         {
                             MultiPageVisitCnt         = csData.getInteger("VisitCnt");
                             MultiPageHitCnt           = csData.getInteger("HitCnt");
                             MultiPageTimetoLastHitSum = csData.getNumber("TimetoLastHitSum");
                         }
                     }
                     //
                     // Authenticated Visits
                     //
                     SQL = "select count(v.id) as AuthenticatedVisits "
                           + " from ccvisits v"
                           + " where (v.CookieSupport<>0)"
                           + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                           + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                           + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                           + " and(VisitAuthenticated<>0)"
                           + "";
                     using (var csData = new CsModel(core)) {
                         core.db.sqlCommandTimeout = 180;
                         csData.openSql(SQL);
                         if (csData.ok())
                         {
                             AuthenticatedVisits = csData.getInteger("AuthenticatedVisits");
                         }
                     }
                     //
                     //
                     // Mobile Visits
                     //
                     SQL = "select count(v.id) as cnt "
                           + " from ccvisits v"
                           + " where (v.CookieSupport<>0)"
                           + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                           + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                           + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                           + " and(Mobile<>0)"
                           + "";
                     using (var csData = new CsModel(core)) {
                         core.db.sqlCommandTimeout = 180;
                         csData.openSql(SQL);
                         if (csData.ok())
                         {
                             MobileVisits = csData.getInteger("cnt");
                         }
                     }
                     //
                     // Bot Visits
                     //
                     SQL = "select count(v.id) as cnt "
                           + " from ccvisits v"
                           + " where (v.CookieSupport<>0)"
                           + " and(v.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                           + " and (v.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                           + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                           + " and(Bot<>0)"
                           + "";
                     using (var csData = new CsModel(core)) {
                         core.db.sqlCommandTimeout = 180;
                         csData.openSql(SQL);
                         if (csData.ok())
                         {
                             BotVisits = csData.getInteger("cnt");
                         }
                     }
                     //
                     if ((MultiPageHitCnt > MultiPageVisitCnt) && (HitCnt > 0))
                     {
                         int    AveReadTime     = encodeInteger(MultiPageTimetoLastHitSum / (MultiPageHitCnt - MultiPageVisitCnt));
                         double TotalTimeOnSite = MultiPageTimetoLastHitSum + (AveReadTime * VisitCnt);
                         AveTimeOnSite = TotalTimeOnSite / VisitCnt;
                     }
                 }
                 //
                 // Add or update the Visit Summary Record
                 //
                 using (var csData = new CsModel(core)) {
                     core.db.sqlCommandTimeout = 180;
                     csData.open("Visit Summary", "(timeduration=" + HourDuration + ")and(DateNumber=" + DateNumber + ")and(TimeNumber=" + TimeNumber + ")");
                     if (!csData.ok())
                     {
                         csData.close();
                         csData.insert("Visit Summary");
                     }
                     //
                     if (csData.ok())
                     {
                         csData.set("name", HourDuration + " hr summary for " + DateTime.FromOADate(DateNumber).ToShortDateString() + " " + TimeNumber + ":00");
                         csData.set("DateNumber", DateNumber);
                         csData.set("TimeNumber", TimeNumber);
                         csData.set("Visits", VisitCnt);
                         csData.set("PagesViewed", HitCnt);
                         csData.set("TimeDuration", HourDuration);
                         csData.set("NewVisitorVisits", NewVisitorVisits);
                         csData.set("SinglePageVisits", SinglePageVisits);
                         csData.set("AuthenticatedVisits", AuthenticatedVisits);
                         csData.set("NoCookieVisits", NoCookieVisits);
                         csData.set("AveTimeOnSite", AveTimeOnSite);
                         {
                             csData.set("MobileVisits", MobileVisits);
                             csData.set("BotVisits", BotVisits);
                         }
                     }
                 }
                 PeriodDatePtr = PeriodDatePtr.AddHours(HourDuration);
             }
             {
                 //
                 // Delete any daily visit summary duplicates during this period(keep the first)
                 //
                 string SQL = "delete from ccvisitsummary"
                              + " where id in ("
                              + " select d.id from ccvisitsummary d,ccvisitsummary f"
                              + " where f.datenumber=d.datenumber"
                              + " and f.datenumber>" + env.oldestVisitSummaryWeCareAbout.ToOADate() + " and f.datenumber<" + env.yesterday.ToOADate() + " and f.TimeDuration=24"
                              + " and d.TimeDuration=24"
                              + " and f.id<d.id"
                              + ")";
                 core.db.sqlCommandTimeout = 180;
                 core.db.executeNonQuery(SQL);
                 //
                 // Find missing daily summaries, summarize that date
                 //
                 SQL = core.db.getSQLSelect("ccVisitSummary", "DateNumber", "TimeDuration=24 and DateNumber>=" + env.oldestVisitSummaryWeCareAbout.Date.ToOADate(), "DateNumber,TimeNumber");
                 using (var csData = new CsModel(core)) {
                     csData.openSql(SQL);
                     DateTime datePtr = env.oldestVisitSummaryWeCareAbout;
                     while (datePtr <= env.yesterday)
                     {
                         if (!csData.ok())
                         {
                             //
                             // Out of data, start with this DatePtr
                             //
                             VisitSummaryClass.summarizePeriod(core, env, datePtr, datePtr, 24, core.siteProperties.dataBuildVersion, env.oldestVisitSummaryWeCareAbout);
                         }
                         else
                         {
                             DateTime workingDate = DateTime.MinValue.AddDays(csData.getInteger("DateNumber"));
                             if (datePtr < workingDate)
                             {
                                 //
                                 // There are missing dates, update them
                                 //
                                 VisitSummaryClass.summarizePeriod(core, env, datePtr, workingDate.AddDays(-1), 24, core.siteProperties.dataBuildVersion, env.oldestVisitSummaryWeCareAbout);
                             }
                         }
                         if (csData.ok())
                         {
                             //
                             // if there is more data, go to the next record
                             //
                             csData.goNext();
                         }
                         datePtr = datePtr.AddDays(1).Date;
                     }
                     csData.close();
                 }
             }
         }
         //
         return;
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
예제 #20
0
        //
        //========================================================================
        //
        public static string get(CoreController core)
        {
            try {
                //
                string   Button        = null;
                string   SQL           = null;
                string   RQS           = null;
                int      PageSize      = 0;
                int      PageNumber    = 0;
                int      TopCount      = 0;
                int      RowPointer    = 0;
                int      DataRowCount  = 0;
                string   PreTableCopy  = "";
                string   PostTableCopy = "";
                int      ColumnPtr     = 0;
                string[] ColCaption    = null;
                string[] ColAlign      = null;
                string[] ColWidth      = null;
                string[,] Cells = null;
                string AdminURL                    = null;
                int    RowCnt                      = 0;
                int    RowPtr                      = 0;
                int    ContentId                   = 0;
                string Format                      = null;
                string Name                        = null;
                string title                       = null;
                string Description                 = null;
                string ButtonCommaListLeft         = null;
                string ButtonCommaListRight        = null;
                int    ContentPadding              = 0;
                string ContentSummary              = "";
                StringBuilderLegacyController Tab0 = new StringBuilderLegacyController();
                StringBuilderLegacyController Tab1 = new StringBuilderLegacyController();
                string Content                     = "";
                string SQLFieldName                = null;
                var    adminMenu                   = new EditTabModel();
                //
                const int ColumnCnt = 4;
                //
                Button    = core.docProperties.getText(RequestNameButton);
                ContentId = core.docProperties.getInteger("ContentID");
                Format    = core.docProperties.getText("Format");
                //
                title                = "Custom Report Manager";
                Description          = "Custom Reports are a way for you to create a snapshot of data to view or download. To request a report, select the Custom Reports tab, check the report(s) you want, and click the [Request Download] Button. When your report is ready, it will be available in the <a href=\"?" + rnAdminForm + "=30\">Download Manager</a>. To create a new custom report, select the Request New Report tab, enter a name and SQL statement, and click the Apply button.";
                ContentPadding       = 0;
                ButtonCommaListLeft  = ButtonCancel + "," + ButtonDelete + "," + ButtonRequestDownload;
                ButtonCommaListRight = "";
                SQLFieldName         = "SQLQuery";
                //
                if (!core.session.isAuthenticatedAdmin())
                {
                    //
                    // Must be a developer
                    //
                    Description = Description + "You can not access the Custom Report Manager because your account is not configured as an administrator.";
                }
                else
                {
                    //
                    // Process Requests
                    //
                    if (!string.IsNullOrEmpty(Button))
                    {
                        switch (Button)
                        {
                        case ButtonCancel:
                            return(core.webServer.redirect("/" + core.appConfig.adminRoute, "CustomReports, Cancel Button Pressed"));

                        case ButtonDelete:
                            RowCnt = core.docProperties.getInteger("RowCnt");
                            if (RowCnt > 0)
                            {
                                for (RowPtr = 0; RowPtr < RowCnt; RowPtr++)
                                {
                                    if (core.docProperties.getBoolean("Row" + RowPtr))
                                    {
                                        MetadataController.deleteContentRecord(core, "Custom Reports", core.docProperties.getInteger("RowID" + RowPtr));
                                    }
                                }
                            }
                            break;

                        case ButtonRequestDownload:
                        case ButtonApply:
                            //
                            Name = core.docProperties.getText("name");
                            SQL  = core.docProperties.getText(SQLFieldName);
                            if (!string.IsNullOrEmpty(Name) || !string.IsNullOrEmpty(SQL))
                            {
                                if ((string.IsNullOrEmpty(Name)) || (string.IsNullOrEmpty(SQL)))
                                {
                                    Processor.Controllers.ErrorController.addUserError(core, "A name and SQL Query are required to save a new custom report.");
                                }
                                else
                                {
                                    int customReportId = 0;
                                    using (var csData = new CsModel(core)) {
                                        csData.insert("Custom Reports");
                                        if (csData.ok())
                                        {
                                            customReportId = csData.getInteger("id");
                                            csData.set("Name", Name);
                                            csData.set(SQLFieldName, SQL);
                                        }
                                        csData.close();
                                    }
                                    requestDownload(core, customReportId);
                                }
                            }
                            //
                            RowCnt = core.docProperties.getInteger("RowCnt");
                            if (RowCnt > 0)
                            {
                                for (RowPtr = 0; RowPtr < RowCnt; RowPtr++)
                                {
                                    if (core.docProperties.getBoolean("Row" + RowPtr))
                                    {
                                        int customReportId = core.docProperties.getInteger("RowID" + RowPtr);
                                        using (var csData = new CsModel(core)) {
                                            csData.openRecord("Custom Reports", customReportId);
                                            if (csData.ok())
                                            {
                                                SQL  = csData.getText(SQLFieldName);
                                                Name = csData.getText("Name");
                                            }
                                        }
                                        requestDownload(core, customReportId);
                                    }
                                }
                            }
                            break;
                        }
                    }
                    //
                    // Build Tab0
                    //
                    Tab0.add("<p>The following is a list of available custom reports.</p>");
                    //
                    RQS      = core.doc.refreshQueryString;
                    PageSize = core.docProperties.getInteger(RequestNamePageSize);
                    if (PageSize == 0)
                    {
                        PageSize = 50;
                    }
                    PageNumber = core.docProperties.getInteger(RequestNamePageNumber);
                    if (PageNumber == 0)
                    {
                        PageNumber = 1;
                    }
                    AdminURL = "/" + core.appConfig.adminRoute;
                    TopCount = PageNumber * PageSize;
                    //
                    // Setup Headings
                    //
                    ColCaption = new string[ColumnCnt + 1];
                    ColAlign   = new string[ColumnCnt + 1];
                    ColWidth   = new string[ColumnCnt + 1];
                    Cells      = new string[PageSize + 1, ColumnCnt + 1];
                    //
                    ColCaption[ColumnPtr] = "Select<br><img alt=\"space\" src=\"" + cdnPrefix + "images/spacer.gif\" width=10 height=1>";
                    ColAlign[ColumnPtr]   = "center";
                    ColWidth[ColumnPtr]   = "10";
                    ColumnPtr             = ColumnPtr + 1;
                    //
                    ColCaption[ColumnPtr] = "Name";
                    ColAlign[ColumnPtr]   = "left";
                    ColWidth[ColumnPtr]   = "100%";
                    ColumnPtr             = ColumnPtr + 1;
                    //
                    ColCaption[ColumnPtr] = "Created By<br><img alt=\"space\" src=\"" + cdnPrefix + "images/spacer.gif\" width=100 height=1>";
                    ColAlign[ColumnPtr]   = "left";
                    ColWidth[ColumnPtr]   = "100";
                    ColumnPtr             = ColumnPtr + 1;
                    //
                    ColCaption[ColumnPtr] = "Date Created<br><img alt=\"space\" src=\"" + cdnPrefix + "images/spacer.gif\" width=150 height=1>";
                    ColAlign[ColumnPtr]   = "left";
                    ColWidth[ColumnPtr]   = "150";
                    ColumnPtr             = ColumnPtr + 1;
                    //
                    //   Get Data
                    //
                    using (var csData = new CsModel(core)) {
                        RowPointer = 0;
                        if (!csData.open("Custom Reports"))
                        {
                            Cells[0, 1] = "There are no custom reports defined";
                            RowPointer  = 1;
                        }
                        else
                        {
                            DataRowCount = csData.getRowCount();
                            while (csData.ok() && (RowPointer < PageSize))
                            {
                                int customReportId = csData.getInteger("ID");
                                Cells[RowPointer, 0] = HtmlController.checkbox("Row" + RowPointer) + HtmlController.inputHidden("RowID" + RowPointer, customReportId);
                                Cells[RowPointer, 1] = csData.getText("name");
                                Cells[RowPointer, 2] = csData.getText("CreatedBy");
                                Cells[RowPointer, 3] = csData.getDate("DateAdded").ToShortDateString();
                                RowPointer           = RowPointer + 1;
                                csData.goNext();
                            }
                        }
                        csData.close();
                    }
                    string Cell = null;
                    Tab0.add(HtmlController.inputHidden("RowCnt", RowPointer));
                    Cell = AdminUIController.getReport(core, RowPointer, ColCaption, ColAlign, ColWidth, Cells, PageSize, PageNumber, PreTableCopy, PostTableCopy, DataRowCount, "ccPanel");
                    Tab0.add("<div>" + Cell + "</div>");
                    //
                    // Build RequestContent Form
                    //
                    Tab1.add("<p>Use this form to create a new custom report. Enter the SQL Query for the report, and a name that will be used as a caption.</p>");
                    //
                    Tab1.add("<table border=\"0\" cellpadding=\"3\" cellspacing=\"0\" width=\"100%\">");
                    //
                    Tab1.add("<tr>");
                    Tab1.add("<td align=right>Name</td>");
                    Tab1.add("<td>" + HtmlController.inputText_Legacy(core, "Name", "", 1, 40) + "</td>");
                    Tab1.add("</tr>");
                    //
                    Tab1.add("<tr>");
                    Tab1.add("<td align=right>SQL Query</td>");
                    Tab1.add("<td>" + HtmlController.inputText_Legacy(core, SQLFieldName, "", 8, 40) + "</td>");
                    Tab1.add("</tr>");
                    //
                    Tab1.add("<tr><td width=\"120\"><img alt=\"space\" src=\"" + cdnPrefix + "images/spacer.gif\" width=\"120\" height=\"1\"></td><td width=\"100%\">&nbsp;</td></tr></table>");
                    //
                    // Build and add tabs
                    //
                    adminMenu.addEntry("Custom&nbsp;Reports", Tab0.text, "ccAdminTab");
                    adminMenu.addEntry("Request&nbsp;New&nbsp;Report", Tab1.text, "ccAdminTab");
                    Content = adminMenu.getTabs(core);
                    //
                }
                //
                core.html.addTitle("Custom Reports");
                //
                return(AdminUIController.getToolBody(core, title, ButtonCommaListLeft, ButtonCommaListRight, true, true, Description, ContentSummary, ContentPadding, Content));
            } catch (Exception ex) {
                LogController.logError(core, ex);
                return(toolExceptionMessage);
            }
        }
예제 #21
0
        //====================================================================================================
        /// <summary>
        /// Summarize the page views, excludes non-cookie visits, excludes administrator and developer visits, excludes authenticated users with ExcludeFromReporting
        /// </summary>
        /// <param name="core"></param>
        /// <param name="StartTimeDate"></param>
        /// <param name="EndTimeDate"></param>
        /// <param name="HourDuration"></param>
        /// <param name="BuildVersion"></param>
        /// <param name="OldestVisitSummaryWeCareAbout"></param>
        //
        public static void pageViewSummary(CoreController core, DateTime StartTimeDate, DateTime EndTimeDate, int HourDuration, string BuildVersion, DateTime OldestVisitSummaryWeCareAbout)
        {
            int    hint    = 0;
            string hinttxt = "";

            try {
                XmlDocument LibraryCollections = new XmlDocument();
                XmlDocument LocalCollections   = new XmlDocument();
                XmlDocument Doc = new XmlDocument();
                {
                    hint = 1;
                    DateTime PeriodStart = default;
                    PeriodStart = StartTimeDate;
                    if (PeriodStart < OldestVisitSummaryWeCareAbout)
                    {
                        PeriodStart = OldestVisitSummaryWeCareAbout;
                    }
                    DateTime PeriodDatePtr = default;
                    PeriodDatePtr = PeriodStart.Date;
                    while (PeriodDatePtr < EndTimeDate)
                    {
                        hint = 2;
                        //
                        hinttxt = ", HourDuration [" + HourDuration + "], PeriodDatePtr [" + PeriodDatePtr + "], PeriodDatePtr.AddHours(HourDuration / 2.0) [" + PeriodDatePtr.AddHours(HourDuration / 2.0) + "]";
                        int DateNumber = encodeInteger((PeriodDatePtr - default(DateTime)).TotalDays);
                        // encodeInteger(PeriodDatePtr.AddHours(HourDuration / 2.0).ToOADate());
                        int      TimeNumber = encodeInteger(PeriodDatePtr.TimeOfDay.TotalHours);
                        DateTime DateStart  = default(DateTime);
                        DateStart = PeriodDatePtr.Date;
                        DateTime DateEnd = default(DateTime);
                        DateEnd = PeriodDatePtr.AddHours(HourDuration).Date;
                        string PageTitle = "";
                        int    PageId    = 0;
                        int    PageViews = 0;
                        int    AuthenticatedPageViews = 0;
                        int    MobilePageViews        = 0;
                        int    BotPageViews           = 0;
                        int    NoCookiePageViews      = 0;
                        //
                        // Loop through all the pages hit during this period
                        //
                        //
                        // for now ignore the problem caused by addons like Blogs creating multiple 'pages' within on pageid
                        // One way to handle this is to expect the addon to set something unquie in he page title
                        // then use the title to distinguish a page. The problem with this is the current system puts the
                        // visit number and page number in the name. if we select on district name, they will all be.
                        //
                        using (var csPages = new CsModel(core)) {
                            string sql = "select distinct recordid,pagetitle from ccviewings h"
                                         + " where (h.recordid<>0)"
                                         + " and(h.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                                         + " and (h.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                                         + " and((h.ExcludeFromAnalytics is null)or(h.ExcludeFromAnalytics=0))"
                                         + "order by recordid";
                            hint = 3;
                            if (!csPages.openSql(sql))
                            {
                                //
                                // no hits found - add or update a single record for this day so we know it has been calculated
                                csPages.open("Page View Summary", "(timeduration=" + HourDuration + ")and(DateNumber=" + DateNumber + ")and(TimeNumber=" + TimeNumber + ")and(pageid=" + PageId + ")and(pagetitle=" + DbController.encodeSQLText(PageTitle) + ")");
                                if (!csPages.ok())
                                {
                                    csPages.close();
                                    csPages.insert("Page View Summary");
                                }
                                //
                                if (csPages.ok())
                                {
                                    csPages.set("name", HourDuration + " hr summary for " + DateTime.MinValue.AddDays(DateNumber) + " " + TimeNumber + ":00, " + PageTitle);
                                    csPages.set("DateNumber", DateNumber);
                                    csPages.set("TimeNumber", TimeNumber);
                                    csPages.set("TimeDuration", HourDuration);
                                    csPages.set("PageViews", PageViews);
                                    csPages.set("PageID", PageId);
                                    csPages.set("PageTitle", PageTitle);
                                    csPages.set("AuthenticatedPageViews", AuthenticatedPageViews);
                                    csPages.set("NoCookiePageViews", NoCookiePageViews);
                                    {
                                        csPages.set("MobilePageViews", MobilePageViews);
                                        csPages.set("BotPageViews", BotPageViews);
                                    }
                                }
                                csPages.close();
                                hint = 4;
                            }
                            else
                            {
                                hint = 5;
                                //
                                // add an entry for each page hit on this day
                                //
                                while (csPages.ok())
                                {
                                    PageId    = csPages.getInteger("recordid");
                                    PageTitle = csPages.getText("pagetitle");
                                    string baseCriteria = ""
                                                          + " (h.recordid=" + PageId + ")"
                                                          + " "
                                                          + " and(h.dateadded>=" + DbController.encodeSQLDate(DateStart) + ")"
                                                          + " and(h.dateadded<" + DbController.encodeSQLDate(DateEnd) + ")"
                                                          + " and((v.ExcludeFromAnalytics is null)or(v.ExcludeFromAnalytics=0))"
                                                          + " and((h.ExcludeFromAnalytics is null)or(h.ExcludeFromAnalytics=0))"
                                                          + "";
                                    if (!string.IsNullOrEmpty(PageTitle))
                                    {
                                        baseCriteria = baseCriteria + "and(h.pagetitle=" + DbController.encodeSQLText(PageTitle) + ")";
                                    }
                                    hint = 6;
                                    //
                                    // Total Page Views
                                    using (var csPageViews = new CsModel(core)) {
                                        sql = "select count(h.id) as cnt"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and (v.CookieSupport<>0)"
                                              + "";
                                        csPageViews.openSql(sql);
                                        if (csPageViews.ok())
                                        {
                                            PageViews = csPageViews.getInteger("cnt");
                                        }
                                    }
                                    //
                                    // Authenticated Visits
                                    //
                                    using (var csAuthPages = new CsModel(core)) {
                                        sql = "select count(h.id) as cnt"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and(v.CookieSupport<>0)"
                                              + " and(v.visitAuthenticated<>0)"
                                              + "";
                                        csAuthPages.openSql(sql);
                                        if (csAuthPages.ok())
                                        {
                                            AuthenticatedPageViews = csAuthPages.getInteger("cnt");
                                        }
                                    }
                                    //
                                    // No Cookie Page Views
                                    //
                                    using (var csNoCookie = new CsModel(core)) {
                                        sql = "select count(h.id) as NoCookiePageViews"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and((v.CookieSupport=0)or(v.CookieSupport is null))"
                                              + "";
                                        csNoCookie.openSql(sql);
                                        if (csNoCookie.ok())
                                        {
                                            NoCookiePageViews = csNoCookie.getInteger("NoCookiePageViews");
                                        }
                                    }
                                    //
                                    //
                                    // Mobile Visits
                                    using (var csMobileVisits = new CsModel(core)) {
                                        sql = "select count(h.id) as cnt"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and(v.CookieSupport<>0)"
                                              + " and(v.mobile<>0)"
                                              + "";
                                        csMobileVisits.openSql(sql);
                                        if (csMobileVisits.ok())
                                        {
                                            MobilePageViews = csMobileVisits.getInteger("cnt");
                                        }
                                    }
                                    //
                                    // Bot Visits
                                    using (var csBotVisits = new CsModel(core)) {
                                        sql = "select count(h.id) as cnt"
                                              + " from ccviewings h left join ccvisits v on h.visitid=v.id"
                                              + " where " + baseCriteria + " and(v.CookieSupport<>0)"
                                              + " and(v.bot<>0)"
                                              + "";
                                        csBotVisits.openSql(sql);
                                        if (csBotVisits.ok())
                                        {
                                            BotPageViews = csBotVisits.getInteger("cnt");
                                        }
                                    }
                                    //
                                    // Add or update the Visit Summary Record
                                    //
                                    using (var csPVS = new CsModel(core)) {
                                        if (!csPVS.open("Page View Summary", "(timeduration=" + HourDuration + ")and(DateNumber=" + DateNumber + ")and(TimeNumber=" + TimeNumber + ")and(pageid=" + PageId + ")and(pagetitle=" + DbController.encodeSQLText(PageTitle) + ")"))
                                        {
                                            csPVS.insert("Page View Summary");
                                        }
                                        //
                                        if (csPVS.ok())
                                        {
                                            hint = 11;
                                            string PageName = "";
                                            if (string.IsNullOrEmpty(PageTitle))
                                            {
                                                PageName = MetadataController.getRecordName(core, "page content", PageId);
                                                csPVS.set("name", HourDuration + " hr summary for " + DateTime.MinValue.AddDays(DateNumber) + " " + TimeNumber + ":00, " + PageName);
                                                csPVS.set("PageTitle", PageName);
                                            }
                                            else
                                            {
                                                csPVS.set("name", HourDuration + " hr summary for " + DateTime.MinValue.AddDays(DateNumber) + " " + TimeNumber + ":00, " + PageTitle);
                                                csPVS.set("PageTitle", PageTitle);
                                            }
                                            csPVS.set("DateNumber", DateNumber);
                                            csPVS.set("TimeNumber", TimeNumber);
                                            csPVS.set("TimeDuration", HourDuration);
                                            csPVS.set("PageViews", PageViews);
                                            csPVS.set("PageID", PageId);
                                            csPVS.set("AuthenticatedPageViews", AuthenticatedPageViews);
                                            csPVS.set("NoCookiePageViews", NoCookiePageViews);
                                            hint = 12;
                                            {
                                                csPVS.set("MobilePageViews", MobilePageViews);
                                                csPVS.set("BotPageViews", BotPageViews);
                                            }
                                        }
                                    }
                                    csPages.goNext();
                                }
                            }
                        }
                        PeriodDatePtr = PeriodDatePtr.AddHours(HourDuration);
                    }
                }
                //
                return;
            } catch (Exception ex) {
                LogController.logError(core, ex, "hint [" + hint + "]");
            }
        }
예제 #22
0
        //
        //========================================================================
        //
        //========================================================================
        //
        public static string get(CPClass cp)
        {
            string tempGetForm_HouseKeepingControl = null;

            try {
                //
                StringBuilderLegacyController Content = new StringBuilderLegacyController();
                string   Copy                  = null;
                string   SQL                   = null;
                string   Button                = null;
                int      PagesTotal            = 0;
                string   Caption               = null;
                DateTime DateValue             = default(DateTime);
                string   AgeInDays             = null;
                int      ArchiveRecordAgeDays  = 0;
                string   ArchiveTimeOfDay      = null;
                bool     ArchiveAllowFileClean = false;
                string   ButtonList            = "";
                string   Description           = null;
                //
                Button = cp.core.docProperties.getText(RequestNameButton);
                if (Button == ButtonCancel)
                {
                    //
                    //
                    //
                    return(cp.core.webServer.redirect("/" + cp.core.appConfig.adminRoute, "HouseKeepingControl, Cancel Button Pressed"));
                }
                else if (!cp.core.session.isAuthenticatedAdmin())
                {
                    //
                    //
                    //
                    ButtonList = ButtonCancel;
                    Content.add(AdminUIController.getFormBodyAdminOnly());
                }
                else
                {
                    //
                    string tableBody = "";
                    //
                    // Set defaults
                    //
                    ArchiveRecordAgeDays  = (cp.core.siteProperties.getInteger("ArchiveRecordAgeDays", 0));
                    ArchiveTimeOfDay      = cp.core.siteProperties.getText("ArchiveTimeOfDay", "12:00:00 AM");
                    ArchiveAllowFileClean = (cp.core.siteProperties.getBoolean("ArchiveAllowFileClean", false));
                    //
                    // Process Requests
                    //
                    switch (Button)
                    {
                    case ButtonOK:
                    case ButtonSave:
                        //
                        ArchiveRecordAgeDays = cp.core.docProperties.getInteger("ArchiveRecordAgeDays");
                        cp.core.siteProperties.setProperty("ArchiveRecordAgeDays", GenericController.encodeText(ArchiveRecordAgeDays));
                        //
                        ArchiveTimeOfDay = cp.core.docProperties.getText("ArchiveTimeOfDay");
                        cp.core.siteProperties.setProperty("ArchiveTimeOfDay", ArchiveTimeOfDay);
                        //
                        ArchiveAllowFileClean = cp.core.docProperties.getBoolean("ArchiveAllowFileClean");
                        cp.core.siteProperties.setProperty("ArchiveAllowFileClean", GenericController.encodeText(ArchiveAllowFileClean));
                        break;
                    }
                    //
                    if (Button == ButtonOK)
                    {
                        return(cp.core.webServer.redirect("/" + cp.core.appConfig.adminRoute, "StaticPublishControl, OK Button Pressed"));
                    }
                    //
                    // ----- Status
                    //
                    tableBody += HtmlController.tableRowStart() + "<td colspan=\"3\" class=\"ccPanel3D ccAdminEditSubHeader\"><b>Status</b>" + tableCellEnd + kmaEndTableRow;
                    //
                    // ----- Visits Found
                    //
                    PagesTotal = 0;
                    SQL        = "SELECT Count(ID) as Result FROM ccVisits;";
                    using (var csData = new CsModel(cp.core)) {
                        csData.openSql(SQL);
                        if (csData.ok())
                        {
                            PagesTotal = csData.getInteger("Result");
                        }
                    }
                    tableBody += AdminUIController.getEditRowLegacy(cp.core, SpanClassAdminNormal + PagesTotal, "Visits Found", "", false, false, "");
                    //
                    // ----- Oldest Visit
                    //
                    Copy      = "unknown";
                    AgeInDays = "unknown";
                    using (var csData = new CsModel(cp.core)) {
                        SQL = cp.core.db.getSQLSelect("ccVisits", "DateAdded", "", "ID", "", 1);
                        csData.openSql(SQL);
                        if (csData.ok())
                        {
                            DateValue = csData.getDate("DateAdded");
                            if (DateValue != DateTime.MinValue)
                            {
                                Copy      = GenericController.encodeText(DateValue);
                                AgeInDays = GenericController.encodeText(encodeInteger(Math.Floor(encodeNumber(cp.core.doc.profileStartTime - DateValue))));
                            }
                        }
                    }
                    tableBody += (AdminUIController.getEditRowLegacy(cp.core, SpanClassAdminNormal + Copy + " (" + AgeInDays + " days)", "Oldest Visit", "", false, false, ""));
                    //
                    // ----- Viewings Found
                    //
                    PagesTotal = 0;
                    SQL        = "SELECT Count(ID) as result  FROM ccViewings;";
                    using (var csData = new CsModel(cp.core)) {
                        csData.openSql(SQL);
                        if (csData.ok())
                        {
                            PagesTotal = csData.getInteger("Result");
                        }
                        csData.close();
                    }
                    tableBody += (AdminUIController.getEditRowLegacy(cp.core, SpanClassAdminNormal + PagesTotal, "Viewings Found", "", false, false, ""));
                    //
                    tableBody += (HtmlController.tableRowStart() + "<td colspan=\"3\" class=\"ccPanel3D ccAdminEditSubHeader\"><b>Options</b>" + tableCellEnd + kmaEndTableRow);
                    //
                    Caption    = "Archive Age";
                    Copy       = HtmlController.inputText_Legacy(cp.core, "ArchiveRecordAgeDays", ArchiveRecordAgeDays.ToString(), -1, 20) + "&nbsp;Number of days to keep visit records. 0 disables housekeeping.";
                    tableBody += (AdminUIController.getEditRowLegacy(cp.core, Copy, Caption));
                    //
                    Caption    = "Housekeeping Time";
                    Copy       = HtmlController.inputText_Legacy(cp.core, "ArchiveTimeOfDay", ArchiveTimeOfDay, -1, 20) + "&nbsp;The time of day when record deleting should start.";
                    tableBody += (AdminUIController.getEditRowLegacy(cp.core, Copy, Caption));
                    //
                    Caption    = "Purge Content Files";
                    Copy       = HtmlController.checkbox("ArchiveAllowFileClean", ArchiveAllowFileClean) + "&nbsp;Delete Contensive content files with no associated database record.";
                    tableBody += (AdminUIController.getEditRowLegacy(cp.core, Copy, Caption));
                    //
                    Content.add(AdminUIController.editTable(tableBody));
                    Content.add(HtmlController.inputHidden(rnAdminSourceForm, AdminformHousekeepingControl));
                    ButtonList = ButtonCancel + ",Refresh," + ButtonSave + "," + ButtonOK;
                }
                //
                Caption     = "Data Housekeeping Control";
                Description = "This tool is used to control the database record housekeeping process. This process deletes visit history records, so care should be taken before making any changes.";
                tempGetForm_HouseKeepingControl = AdminUIController.getToolBody(cp.core, Caption, ButtonList, "", false, false, Description, "", 0, Content.text);
                //
                cp.core.html.addTitle(Caption);
            } catch (Exception ex) {
                LogController.logError(cp.core, ex);
            }
            return(tempGetForm_HouseKeepingControl);
        }
예제 #23
0
        //
        //======================================================================================================
        //
        public static void installNode(CoreController core, XmlNode AddonNode, string AddonGuidFieldName, int CollectionID, ref bool return_UpgradeOK, ref string return_ErrorMessage, ref bool collectionIncludesDiagnosticAddons)
        {
            // todo - return bool
            return_ErrorMessage = "";
            return_UpgradeOK    = true;
            try {
                string Basename = GenericController.toLCase(AddonNode.Name);
                if ((Basename == "page") || (Basename == "process") || (Basename == "addon") || (Basename == "add-on"))
                {
                    bool   IsFound   = false;
                    string addonName = XmlController.getXMLAttribute(core, ref IsFound, AddonNode, "name", "No Name");
                    if (string.IsNullOrEmpty(addonName))
                    {
                        addonName = "No Name";
                    }
                    string addonGuid = XmlController.getXMLAttribute(core, ref IsFound, AddonNode, "guid", addonName);
                    if (string.IsNullOrEmpty(addonGuid))
                    {
                        addonGuid = addonName;
                    }
                    string navTypeName = XmlController.getXMLAttribute(core, ref IsFound, AddonNode, "type", "");
                    int    navTypeId   = getListIndex(navTypeName, navTypeIDList);
                    if (navTypeId == 0)
                    {
                        navTypeId = NavTypeIDAddon;
                    }
                    using (var cs = new CsModel(core)) {
                        string Criteria = "(" + AddonGuidFieldName + "=" + DbController.encodeSQLText(addonGuid) + ")";
                        cs.open(AddonModel.tableMetadata.contentName, Criteria, "", false);
                        if (cs.ok())
                        {
                            //
                            // Update the Addon
                            //
                            LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, GUID match with existing Add-on, Updating Add-on [" + addonName + "], Guid [" + addonGuid + "]");
                        }
                        else
                        {
                            //
                            // not found by GUID - search name against name to update legacy Add-ons
                            //
                            cs.close();
                            Criteria = "(name=" + DbController.encodeSQLText(addonName) + ")and(" + AddonGuidFieldName + " is null)";
                            cs.open(AddonModel.tableMetadata.contentName, Criteria, "", false);
                            if (cs.ok())
                            {
                                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, Add-on name matched an existing Add-on that has no GUID, Updating legacy Aggregate Function to Add-on [" + addonName + "], Guid [" + addonGuid + "]");
                            }
                        }
                        if (!cs.ok())
                        {
                            //
                            // not found by GUID or by name, Insert a new addon
                            //
                            cs.close();
                            cs.insert(AddonModel.tableMetadata.contentName);
                            if (cs.ok())
                            {
                                LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, Creating new Add-on [" + addonName + "], Guid [" + addonGuid + "]");
                            }
                        }
                        if (!cs.ok())
                        {
                            //
                            // Could not create new Add-on
                            //
                            LogController.logInfo(core, MethodInfo.GetCurrentMethod().Name + ", UpgradeAppFromLocalCollection, Add-on could not be created, skipping Add-on [" + addonName + "], Guid [" + addonGuid + "]");
                        }
                        else
                        {
                            int addonId = cs.getInteger("ID");
                            MetadataController.deleteContentRecords(core, "Add-on Include Rules", "addonid=" + addonId);
                            MetadataController.deleteContentRecords(core, "Add-on Content Trigger Rules", "addonid=" + addonId);
                            //
                            cs.set("collectionid", CollectionID);
                            cs.set(AddonGuidFieldName, addonGuid);
                            cs.set("name", addonName);
                            cs.set("navTypeId", navTypeId);
                            var ArgumentList = new StringBuilder();
                            var StyleSheet   = new StringBuilder();
                            if (AddonNode.ChildNodes.Count > 0)
                            {
                                foreach (XmlNode Addonfield in AddonNode.ChildNodes)
                                {
                                    if (!(Addonfield is XmlComment))
                                    {
                                        XmlNode PageInterface = Addonfield;
                                        string  fieldName     = null;
                                        string  FieldValue    = "";
                                        switch (GenericController.toLCase(Addonfield.Name))
                                        {
                                        case "activexdll": {
                                            //
                                            // This is handled in BuildLocalCollectionFolder
                                            //
                                            break;
                                        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                            break;
                                        }

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

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

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

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

                                        default: {
                                            //
                                            // All the other fields should match the Db fields
                                            //
                                            fieldName  = Addonfield.Name;
                                            FieldValue = Addonfield.InnerText;
                                            if (!cs.isFieldSupported(fieldName))
                                            {
                                                //
                                                // Bad field name - need to report it somehow
                                                //
                                                LogController.logError(core, new ApplicationException("bad field found [" + fieldName + "], in addon node [" + addonName + "], of collection [" + MetadataController.getRecordName(core, "add-on collections", CollectionID) + "]"));
                                            }
                                            else
                                            {
                                                cs.set(fieldName, FieldValue);
                                            }
                                            break;
                                        }
                                        }
                                    }
                                }
                            }
                            cs.set("ArgumentList", ArgumentList.ToString());
                            cs.set("StylesFilename", StyleSheet.ToString());
                        }
                        cs.close();
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
        }