// //===================================================================================================== /// <summary> /// add activity about a user to the site's activity log for content managers to review /// </summary> /// <param name="core"></param> /// <param name="Message"></param> /// <param name="ByMemberID"></param> /// <param name="SubjectMemberID"></param> /// <param name="SubjectOrganizationID"></param> /// <param name="Link"></param> /// <param name="VisitorID"></param> /// <param name="VisitID"></param> public static void addSiteActivity(CoreController core, string Message, int ByMemberID, int SubjectMemberID, int SubjectOrganizationID, string Link = "", int VisitorId = 0, int VisitId = 0) { try { // if (Message.Length > 255) { Message = Message.Substring(0, 255); } if (Link.Length > 255) { Message = Link.Substring(0, 255); } using (var csData = new CsModel(core)) { if (csData.insert("Activity Log")) { csData.set("MemberID", SubjectMemberID); csData.set("OrganizationID", SubjectOrganizationID); csData.set("Message", Message); csData.set("Link", Link); csData.set("VisitorID", VisitorId); csData.set("VisitID", VisitId); } } // return; // } catch (Exception ex) { LogController.logError(core, ex); } }
// //============================================================================= /// <summary> /// Get the link for a Content Record by its ContentRecordKey /// </summary> /// <param name="ContentRecordKey"></param> /// <param name="DefaultLink"></param> /// <param name="IncrementClicks"></param> /// <returns></returns> public string getContentWatchLinkByKey(string ContentRecordKey, string DefaultLink, bool IncrementClicks) { string result = ""; try { using (var csData = new CsModel(core)) { if (csData.open("Content Watch", "ContentRecordKey=" + DbController.encodeSQLText(ContentRecordKey), "", false, 0, "Link,Clicks")) { result = csData.getText("Link"); if (GenericController.encodeBoolean(IncrementClicks)) { csData.set("Clicks", csData.getInteger("clicks") + 1); } } else { result = GenericController.encodeText(DefaultLink); } } return(GenericController.encodeVirtualPath(result, core.appConfig.cdnFileUrl, appRootPath, core.webServer.requestDomain)); } catch (Exception ex) { LogController.logError(core, ex); throw; } }
//==================================================================================================== // public static void housekeep(CoreController core, HouseKeepEnvironmentModel env) { try { // LogController.logInfo(core, "Housekeep, viewingsummary"); // // // -- there is a bug and I need to move on. return; // // Page View Summary // { DateTime datePtr = default; using (var csData = new CsModel(core)) { if (!csData.openSql(core.db.getSQLSelect("ccviewingsummary", "DateNumber", "TimeDuration=24 and DateNumber>=" + env.oldestVisitSummaryWeCareAbout.Date.ToOADate(), "DateNumber Desc", "", 1))) { datePtr = env.oldestVisitSummaryWeCareAbout; } else { datePtr = DateTime.MinValue.AddDays(csData.getInteger("DateNumber")); } } if (datePtr < env.oldestVisitSummaryWeCareAbout) { datePtr = env.oldestVisitSummaryWeCareAbout; } pageViewSummary(core, datePtr, env.yesterday, 24, core.siteProperties.dataBuildVersion, env.oldestVisitSummaryWeCareAbout); } } catch (Exception ex) { LogController.logError(core, ex); } }
public static void housekeep(CoreController core, HouseKeepEnvironmentModel env) { try { // LogController.logInfo(core, "Housekeep, grouprules"); // // // GroupRules with bad ContentID // Handled record by record removed to prevent CDEF reload // LogController.logInfo(core, "Deleting Group Rules with bad ContentID."); string sql = "Select ccGroupRules.ID" + " From ccGroupRules LEFT JOIN ccContent on ccContent.ID=ccGroupRules.ContentID" + " WHERE (ccContent.ID is null)"; using (var csData = new CsModel(core)) { csData.openSql(sql); while (csData.ok()) { MetadataController.deleteContentRecord(core, "Group Rules", csData.getInteger("ID")); csData.goNext(); } } // // GroupRules with bad GroupID // LogController.logInfo(core, "Deleting Group Rules with bad GroupID."); sql = "delete ccGroupRules" + " From ccGroupRules" + " LEFT JOIN ccgroups on ccgroups.ID=ccGroupRules.GroupID" + " WHERE (ccgroups.ID is null)"; core.db.executeNonQuery(sql); } catch (Exception ex) { LogController.logError(core, ex); } }
// //==================================================================================================== /// <summary> /// set property /// </summary> /// <param name="propertyName"></param> /// <param name="propertyValue"></param> /// <param name="keyId">keyId is like vistiId, vistorId, userId</param> public void setProperty(string propertyName, string propertyValue, int keyId) { try { if (!propertyCacheLoaded) { loadFromDb(keyId); } int Ptr = -1; if (propertyCacheCnt > 0) { Ptr = propertyCache_nameIndex.getPtr(propertyName); } if (Ptr < 0) { Ptr = propertyCacheCnt; propertyCacheCnt += 1; string[,] tempVar = new string[3, Ptr + 1]; if (propertyCache != null) { for (int Dimension0 = 0; Dimension0 < propertyCache.GetLength(0); Dimension0++) { int CopyLength = Math.Min(propertyCache.GetLength(1), tempVar.GetLength(1)); for (int Dimension1 = 0; Dimension1 < CopyLength; Dimension1++) { tempVar[Dimension0, Dimension1] = propertyCache[Dimension0, Dimension1]; } } } propertyCache = tempVar; propertyCache[0, Ptr] = propertyName; propertyCache[1, Ptr] = propertyValue; propertyCache_nameIndex.setPtr(propertyName, Ptr); // // insert a new property record, get the ID back and save it in cache // using (var csData = new CsModel(core)) { if (csData.insert("Properties")) { propertyCache[2, Ptr] = csData.getText("ID"); csData.set("name", propertyName); csData.set("FieldValue", propertyValue); csData.set("TypeID", (int)propertyType); csData.set("KeyID", keyId.ToString()); } } } else if (propertyCache[1, Ptr] != propertyValue) { propertyCache[1, Ptr] = propertyValue; int RecordId = GenericController.encodeInteger(propertyCache[2, Ptr]); string SQLNow = DbController.encodeSQLDate(core.dateTimeNowMockable); // // save the value in the property that was found // core.db.executeNonQuery("update ccProperties set FieldValue=" + DbController.encodeSQLText(propertyValue) + ",ModifiedDate=" + SQLNow + " where id=" + RecordId); } } catch (Exception ex) { LogController.logError(core, ex); } }
// // // // 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); }
// //==================================================================================================== // Replace with main_GetPageArgs() // // Used Interally by main_GetPageLink to main_Get the TemplateID of the parents //==================================================================================================== // internal int getPageDynamicLink_GetTemplateID(int PageID, string UsedIDList) { int result = 0; try { int ParentID = 0; int templateId = 0; using (var csData = new CsModel(core)) { if (csData.openRecord("Page Content", PageID, "TemplateID,ParentID")) { templateId = csData.getInteger("TemplateID"); ParentID = csData.getInteger("ParentID"); } } // // Chase page tree to main_Get templateid if (templateId == 0 && ParentID != 0) { if (!GenericController.isInDelimitedString(UsedIDList, ParentID.ToString(), ",")) { result = getPageDynamicLink_GetTemplateID(ParentID, UsedIDList + "," + ParentID); } } return(result); } catch (Exception ex) { LogController.logError(core, ex); throw; } }
// //==================================================================================================== // 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); }
// //============================================================================= // public static string getWhatsRelated(CoreController core) { try { CPClass cp = core.cpParent; if (core.doc.pageController.page.id == 0) { return(string.Empty); } StringBuilder items = new StringBuilder(); using (var cs = new CsModel(core)) { string sql = "select rp.id,rp.name,rp.menuheadline,rp.briefFilename" + " from ccpagecontenttopicrules sr" + " left join ccpagecontenttopicrules rr on rr.topicid=sr.topicid" + " left join ccpagecontent rp on rp.id=rr.pageid" + " group by rp.id,rp.name,rp.menuheadline,rp.briefFilename" + " order by count(rp.id)"; if (cs.openSql(sql)) { do { int pageId = cs.getInteger("id"); if (!pageId.Equals(core.doc.pageController.page.id)) { string link = cp.Content.GetPageLink(pageId); if (!string.IsNullOrWhiteSpace(link)) { if (!link.Contains("://")) { link = core.webServer.requestProtocol + link; } string menuHeadline = cs.getText("menuheadline"); string content = HtmlController.a(string.IsNullOrWhiteSpace(menuHeadline) ? cs.getText("name") : menuHeadline, link); string briefFilename = cs.getText("briefFilename"); if (!string.IsNullOrWhiteSpace(briefFilename)) { content += HtmlController.div(cp.CdnFiles.Read(briefFilename), "ccListCopy"); } items.Append(HtmlController.li(content, "wrItem")); } } cs.goNext(); } while (cs.ok()); } } if (items.Length > 0) { return(HtmlController.div(HtmlController.h4("Whats Related") + HtmlController.ul(items.ToString(), "ccList"), "ccWhatsRelated")); } if (cp.User.IsEditing("")) { return(HtmlController.div(HtmlController.h4("Whats Related") + HtmlController.ul("<li>[empty list]</li>", "ccList"), "ccWhatsRelated")); } return(string.Empty); } catch (Exception ex) { LogController.logError(core, ex); return(string.Empty); } }
//============================================================================= /// <summary> /// Go through all Content Definitions and create appropriate tables and fields. /// </summary> /// <returns></returns> public static string get(CoreController core) { string returnValue = ""; try { Processor.Models.Domain.ContentMetadataModel metadata = null; StringBuilderLegacyController Stream = new StringBuilderLegacyController(); string[,] ContentNameArray = null; int ContentNameCount = 0; string TableName = null; string ButtonList; // ButtonList = ButtonCancel + "," + ButtonRun; // Stream.add(AdminUIController.getHeaderTitleDescription("Synchronize Tables to Content Definitions", "This tools goes through all Content Definitions and creates any necessary Tables and Table Fields to support the Definition.")); // if (core.docProperties.getText("Button") != "") { // // Run Tools // Stream.add("Synchronizing Tables to Content Definitions<br>"); using (var csData = new CsModel(core)) { csData.open("Content", "", "", false, 0, "id"); if (csData.ok()) { do { metadata = Processor.Models.Domain.ContentMetadataModel.create(core, csData.getInteger("id")); TableName = metadata.tableName; Stream.add("Synchronizing Content " + metadata.name + " to table " + TableName + "<br>"); using (var db = new DbController(core, metadata.dataSourceName)) { db.createSQLTable(TableName); if (metadata.fields.Count > 0) { foreach (var keyValuePair in metadata.fields) { ContentFieldMetadataModel field = keyValuePair.Value; Stream.add("...Field " + field.nameLc + "<br>"); db.createSQLTableField(TableName, field.nameLc, field.fieldTypeId); } } } csData.goNext(); } while (csData.ok()); ContentNameArray = csData.getRows(); ContentNameCount = ContentNameArray.GetUpperBound(1) + 1; } } } returnValue = AdminUIController.getToolForm(core, Stream.text, ButtonList); } catch (Exception ex) { LogController.logError(core, ex); throw; } return(returnValue); }
// //============================================================================= // Print the See Also listing // ContentName is the name of the parent table // RecordID is the parent RecordID //============================================================================= // public static string getSeeAlso(CoreController core) { try { if (core.doc.pageController.page.id == 0) { return(string.Empty); } int SeeAlsoCount = 0; string result = ""; using (var cs = new CsModel(core)) { if (cs.open("See Also", "(RecordID=" + core.doc.pageController.page.id + ")")) { do { string link = cs.getText("Link"); if ((!string.IsNullOrWhiteSpace(link)) && (!link.Contains("://"))) { link = core.webServer.requestProtocol + link; } string editAnchorTag = (!core.session.isEditing() ? "" : AdminUIController.getRecordEditAnchorTag(core, "See Also", cs.getInteger("ID"))); string pageAnchorTag = HtmlController.a(cs.getText("name"), HtmlController.encodeHtml(link)); string brief = cs.getText("Brief"); if (!string.IsNullOrEmpty(brief)) { brief = HtmlController.p(brief, "ccListCopy"); } result += HtmlController.li(editAnchorTag + pageAnchorTag + brief, "ccListItem"); SeeAlsoCount += 1; cs.goNext(); } while (cs.ok()); } } if (core.session.isEditing()) { SeeAlsoCount += 1; foreach (var AddLink in AdminUIController.getRecordAddAnchorTag(core, "See Also", "RecordID=" + core.doc.pageController.page.id)) { if (!string.IsNullOrEmpty(AddLink)) { result += HtmlController.li(AddLink, "ccEditWrapper ccListItem"); } } } if (SeeAlsoCount == 0) { return(string.Empty); } return(HtmlController.div(HtmlController.h4("See Also") + HtmlController.ul(result, "ccList"), "ccSeeAlso")); } catch (Exception ex) { LogController.logError(core, ex); return(string.Empty); } }
// //==================================================================================================== /// <summary> /// Add a command task to the taskQueue to be run by the taskRunner. Returns false if the task was already there (dups fround by command name and cmdDetailJson) /// </summary> /// <param name="core"></param> /// <param name="command"></param> /// <param name="cmdDetail"></param> /// <param name="downloadName"></param> /// <returns></returns> static public bool addTaskToQueue(CoreController core, TaskModel.CmdDetailClass cmdDetail, bool blockDuplicates, string downloadName, string downloadFilename) { try { // int downloadId = 0; if (!string.IsNullOrEmpty(downloadName)) { Dictionary <string, string> defaultValues = ContentMetadataModel.getDefaultValueDict(core, DownloadModel.tableMetadata.contentName); var download = DbBaseModel.addDefault <DownloadModel>(core.cpParent, defaultValues); download.name = downloadName; download.dateRequested = core.dateTimeNowMockable; download.requestedBy = core.session.user.id; if (!string.IsNullOrEmpty(downloadFilename)) { // // -- if the donwloadfilename is specified, save it in the download record and force the file to save with a space in content download.filename.filename = FileController.getVirtualRecordUnixPathFilename(DownloadModel.tableMetadata.tableNameLower, "filename", download.id, downloadFilename); download.filename.content = " "; } downloadId = download.id; download.save(core.cpParent); } string cmdDetailJson = SerializeObject(cmdDetail); bool allowAdd = true; if (blockDuplicates) { // // -- Search for a duplicate string sql = "select top 1 id from cctasks where ((cmdDetail=" + DbController.encodeSQLText(cmdDetailJson) + ")and(datestarted is null)and(datecompleted is null))"; using (var csData = new CsModel(core)) { allowAdd = !csData.openSql(sql); } } // // -- add it to the queue and shell out to the command if (allowAdd) { var task = TaskModel.addEmpty <TaskModel>(core.cpParent); task.name = "addon [#" + cmdDetail.addonId + "," + cmdDetail.addonName + "]"; task.cmdDetail = cmdDetailJson; task.resultDownloadId = downloadId; task.save(core.cpParent); LogController.logTrace(core, "addTaskToQueue, task added, cmdDetailJson [" + cmdDetailJson + "]"); return(true); } LogController.logTrace(core, "addTaskToQueue, task blocked because duplicate found, cmdDetailJson [" + cmdDetailJson + "]"); return(false); } catch (Exception ex) { LogController.logError(core, ex); return(false); } }
// //==================================================================================================== /// <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 override string GetLayout(int layoutid) { try { using (var cs = new CsModel(cp.core)) { string sql = "select layout from ccLayouts where id=" + layoutid; cs.openSql(sql); if (cs.ok()) { return(cs.getText("layout")); } } } catch (Exception ex) { LogController.logError(cp.core, ex); } return(string.Empty); }
// 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); }
// //============================================================================= /// <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"); } } } }
//==================================================================================================== // 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); } }
// //==================================================================================================== // 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); }
// //================================================================================================ /// <summary> /// Add a site Warning: for content managers to make content changes with the site /// Report Warning /// A warning is logged in the site warnings log /// name - a generic description of the warning /// "bad link found on page" /// issueCategory - a generic string that describes the warning. the warning report /// will display one line for each generalKey (name matches guid) /// like "bad link" /// location - the URL, service or process that caused the problem /// "http://goodpageThankHasBadLink.com" /// pageid - the record id of the bad page. /// "http://goodpageThankHasBadLink.com" /// description - a specific description /// "link to http://www.this.com/pagename was found on http://www.this.com/About-us" /// count - the number of times the name and issueCategory matched. "This error was reported 100 times" /// </summary> /// <param name="core"></param> /// <param name="Name">A generic description of the warning that describes the problem, but if the issue occurs again the name will match, like Page Not Found on /Home</param> /// <param name="ignore">To be deprecated - same as name</param> /// <param name="location">Where the issue occurred, like on a page, or in a background process.</param> /// <param name="PageID"></param> /// <param name="Description">Any detail the use will need to debug the problem.</param> /// <param name="issueCategory">A general description of the issue that can be grouped in a report, like Page Not Found</param> /// <param name="ignore2">to be deprecated, same a name.</param> // public static void addSiteWarning(CoreController core, string Name, string ignore, string location, int PageID, string Description, string issueCategory, string ignore2) { int warningId = 0; // warningId = 0; string SQL = "select top 1 ID from ccSiteWarnings" + " where (name=" + DbController.encodeSQLText(Name) + ")" + " and(generalKey=" + DbController.encodeSQLText(issueCategory) + ")" + ""; DataTable dt = core.db.executeQuery(SQL); if (dt.Rows.Count > 0) { warningId = GenericController.encodeInteger(dt.Rows[0]["id"]); } // if (warningId != 0) { // // increment count for matching warning // SQL = "update ccsitewarnings set count=count+1,DateLastReported=" + DbController.encodeSQLDate(core.dateTimeNowMockable) + " where id=" + warningId; core.db.executeNonQuery(SQL); } else { // // insert new record // using (var csData = new CsModel(core)) { if (csData.insert("Site Warnings")) { csData.set("name", Name); csData.set("description", Description); csData.set("generalKey", issueCategory); csData.set("count", 1); csData.set("DateLastReported", core.dateTimeNowMockable); csData.set("location", location); csData.set("pageId", PageID); } } } // }
// //--------------------------------------------------------------------------- // Create the default landing page if it is missing //--------------------------------------------------------------------------- // public int createPageGetID(string PageName, string ContentName, int CreatedBy, string pageGuid) { int Id = 0; using (var csData = new CsModel(core)) { if (csData.insert(ContentName)) { Id = csData.getInteger("ID"); csData.set("name", PageName); csData.set("active", "1"); { csData.set("ccGuid", pageGuid); } csData.save(); } } return(Id); }
public static void housekeep(CoreController core, HouseKeepEnvironmentModel env) { try { // LogController.logInfo(core, "HousekeepDaily, contentwatch"); // using (var csData = new CsModel(core)) { string sql = "select cccontentwatch.id from cccontentwatch left join cccontent on cccontent.id=cccontentwatch.contentid where (cccontent.id is null)or(cccontent.active=0)or(cccontent.active is null)"; csData.openSql(sql); while (csData.ok()) { MetadataController.deleteContentRecord(core, "Content Watch", csData.getInteger("ID")); csData.goNext(); } } } 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); }
// //==================================================================================================== // public override string getLayout(string layoutName) { try { if (string.IsNullOrWhiteSpace(layoutName)) { return(string.Empty); } using (var cs = new CsModel(cp.core)) { cs.open("layouts", "name=" + DbController.encodeSQLText(layoutName), "id", false, cp.core.session.user.id, "layout"); if (cs.ok()) { return(cs.getText("layout")); } } } catch (Exception ex) { LogController.logError(cp.core, ex); } return(string.Empty); }
// // dispose // protected virtual void Dispose(bool disposing_cs) { if (!this.disposed_cs) { if (disposing_cs) { // // ----- call .dispose for managed objects if (cs != null) { cs.Dispose(); cs = null; } } // // ----- release unmanaged resources // } this.disposed_cs = true; }
// //==================================================================================================== /// <summary> /// GetAjaxDefaultAddonOptionStringClass remote method /// </summary> /// <param name="cp"></param> /// <returns></returns> public override object Execute(Contensive.BaseClasses.CPBaseClass cp) { string returnHtml = ""; try { using (CoreController core = ((CPClass)cp).core) { using (var csData = new CsModel(core)) { string AddonGuid = core.docProperties.getText("guid"); csData.open(AddonModel.tableMetadata.contentName, "ccguid=" + DbController.encodeSQLText(AddonGuid)); if (csData.ok()) { string addonArgumentList = csData.getText("argumentlist"); bool addonIsInline = csData.getBoolean("IsInline"); string jsonCommand = ""; returnHtml = AddonController.getDefaultAddonOptions(core, addonArgumentList, AddonGuid, addonIsInline, csData.getText("name"), ref jsonCommand); } } } } catch (Exception ex) { cp.Site.ErrorReport(ex); } return(returnHtml); }
// //============================================================================= // public void verifyRegistrationFormPage(CoreController core) { try { MetadataController.deleteContentRecords(core, "Form Pages", "name=" + DbController.encodeSQLText("Registration Form")); using (var csData = new CsModel(core)) { if (!csData.open("Form Pages", "name=" + DbController.encodeSQLText("Registration Form"))) { // // create Version 1 template - just to main_Get it started // if (csData.insert("Form Pages")) { csData.set("name", "Registration Form"); string Copy = "" + Environment.NewLine + "<table border=\"0\" cellpadding=\"2\" cellspacing=\"0\" width=\"100%\">" + Environment.NewLine + "{{REPEATSTART}}<tr><td align=right style=\"height:22px;\">{{CAPTION}} </td><td align=left>{{FIELD}}</td></tr>{{REPEATEND}}" + Environment.NewLine + "<tr><td align=right><img alt=\"space\" src=\"" + cdnPrefix + "images/spacer.gif\" width=135 height=1></td><td width=\"100%\"> </td></tr>" + Environment.NewLine + "<tr><td colspan=2> <br>" + core.html.getPanelButtons(ButtonRegister) + "</td></tr>" + Environment.NewLine + "</table>"; csData.set("Body", Copy); Copy = "" + "1" + Environment.NewLine + "Registered\r\ntrue" + Environment.NewLine + "1,First Name,true,FirstName" + Environment.NewLine + "1,Last Name,true,LastName" + Environment.NewLine + "1,Email Address,true,Email" + Environment.NewLine + "1,Phone,true,Phone" + Environment.NewLine + "2,Please keep me informed of news and events,false,Subscribers" + ""; csData.set("Instructions", Copy); } } } } catch (Exception ex) { LogController.logError(core, ex); } }
// //==================================================================================================== /// <summary> /// Returns OK on success /// + available drive space /// + log size /// </summary> /// <param name="cp"></param> /// <returns></returns> public override object Execute(Contensive.BaseClasses.CPBaseClass cp) { try { var result = new StringBuilder(); var core = ((CPClass)cp).core; // // -- tmp, check for 10% free on C-drive and D-drive if (Directory.Exists(@"c:\")) { DriveInfo driveTest = new DriveInfo("c"); double freeSpace = Math.Round(100.0 * (Convert.ToDouble(driveTest.AvailableFreeSpace) / Convert.ToDouble(driveTest.TotalSize)), 2); if (freeSpace < 10) { return("ERROR, Drive-C does not have 10% free"); } result.AppendLine("ok, drive-c free space [" + freeSpace + "%], [" + (driveTest.AvailableFreeSpace / (1024 * 1024)).ToString("F2", CultureInfo.InvariantCulture) + " MB]"); } if (Directory.Exists(@"d:\")) { DriveInfo driveTest = new DriveInfo("d"); double freeSpace = Math.Round(100.0 * (Convert.ToDouble(driveTest.AvailableFreeSpace) / Convert.ToDouble(driveTest.TotalSize)), 2); if (freeSpace < 10) { return("ERROR, Drive-D does not have 10% free"); } result.AppendLine("ok, drive-D free space [" + freeSpace + "%], [" + (driveTest.AvailableFreeSpace / (1024 * 1024)).ToString("F2", CultureInfo.InvariantCulture) + " MB]"); } // // -- log files under 1MB if (!core.programDataFiles.pathExists("Logs/")) { core.programDataFiles.createPath("Logs/"); } foreach (var fileDetail in core.programDataFiles.getFileList("Logs/")) { if (fileDetail.Size > 1000000) { return("ERROR, log file size error [" + fileDetail.Name + "], size [" + fileDetail.Size + "]"); } } result.AppendLine("ok, all log files under 1 MB"); // // test default data connection try { using (var csData = new CsModel(core)) { int recordId = 0; if (csData.insert("Properties")) { recordId = csData.getInteger("ID"); } if (recordId == 0) { return("ERROR, Failed to insert record in default data source."); } else { MetadataController.deleteContentRecord(core, "Properties", recordId); } } } catch (Exception exDb) { return("ERROR, exception occured during default data source record insert, [" + exDb + "]."); } result.AppendLine("ok, database connection passed."); // // -- test for taskscheduler not running if (DbBaseModel.createList <AddonModel>(core.cpParent, "(ProcessNextRun<" + DbController.encodeSQLDate(core.dateTimeNowMockable.AddHours(-1)) + ")").Count > 0) { return("ERROR, there are process addons unexecuted for over 1 hour. TaskScheduler may not be enabled, or no server is running the Contensive Task Service."); } if (DbBaseModel.createList <TaskModel>(core.cpParent, "(dateCompleted is null)and(dateStarted<" + DbController.encodeSQLDate(core.dateTimeNowMockable.AddHours(-1)) + ")").Count > 0) { return("ERROR, there are tasks that have been executing for over 1 hour. The Task Runner Server may have stopped."); } result.AppendLine("ok, taskscheduler running."); // // -- test for taskrunner not running if (DbBaseModel.createList <TaskModel>(core.cpParent, "(dateCompleted is null)and(dateStarted is null)").Count > 100) { return("ERROR, there are over 100 task waiting to be execute. The Task Runner Server may have stopped."); } result.AppendLine("ok, taskrunner running."); // // -- verify the email process is running. if (cp.Site.GetDate("EmailServiceLastCheck") < core.dateTimeNowMockable.AddHours(-1)) { return("ERROR, Email process has not executed for over 1 hour."); } result.AppendLine("ok, email process running."); // // -- last -- if alarm folder is not empty, fail diagnostic. Last so others can add an alarm entry if (!core.programDataFiles.pathExists("Alarms/")) { core.programDataFiles.createPath("Alarms/"); } foreach (var alarmFile in core.programDataFiles.getFileList("Alarms/")) { return("ERROR, Alarm folder is not empty, [" + core.programDataFiles.readFileText("Alarms/" + alarmFile.Name) + "]."); } // -- verify the default username=root, password=contensive is not present var rootUserList = PersonModel.createList <PersonModel>(cp, "((username='******')and(password='******')and(active>0))"); if (rootUserList.Count > 0) { return("ERROR, delete or inactive default user root/contensive."); } // // -- meta data test- lookup field without lookup set string sql = "select c.id as contentid, c.name as contentName, f.* from ccfields f left join ccContent c on c.id = f.LookupContentID where f.Type = 7 and c.id is null and f.LookupContentID > 0 and f.Active > 0 and f.Authorable > 0"; using (DataTable dt = core.db.executeQuery(sql)) { if (!dt.Rows.Count.Equals(0)) { string badFieldList = ""; foreach (DataRow row in dt.Rows) { badFieldList += "," + row["contentName"] + "." + row["name"].ToString(); } return("ERROR, the following field(s) are configured as lookup, but the field's lookup-content is not set [" + badFieldList.Substring(1) + "]."); } } // // -- metadata test - many to many setup sql = "select f.id,f.name as fieldName,f.ManyToManyContentID, f.ManyToManyRuleContentID, f.ManyToManyRulePrimaryField, f.ManyToManyRuleSecondaryField" + " ,pc.name as primaryContentName" + " , sc.name as secondaryContentName" + " , r.name as ruleContentName" + " , rp.name as PrimaryContentField" + " , rs.name as SecondaryContentField" + " from ccfields f" + " left join cccontent sc on sc.id = f.ManyToManyContentID" + " left join cccontent pc on pc.id = f.contentid" + " left join cccontent r on r.id = f.ManyToManyRuleContentID" + " left join ccfields rp on (rp.name = f.ManyToManyRulePrimaryField)and(rp.ContentID = r.id)" + " left join ccfields rs on(rs.name = f.ManyToManyRuleSecondaryField)and(rs.ContentID = r.id)" + " where" + " (f.type = 14)and(f.Authorable > 0)and(f.active > 0)" + " and((1 = 0)or(sc.id is null)or(pc.id is null)or(r.id is null)or(rp.id is null)or(rs.id is null))"; using (DataTable dt = core.db.executeQuery(sql)) { if (!dt.Rows.Count.Equals(0)) { string badFieldList = ""; foreach (DataRow row in dt.Rows) { badFieldList += "," + row["primaryContentName"] + "." + row["fieldName"].ToString(); } return("ERROR, the following field(s) are configured as many-to-many, but the field's many-to-many metadata is not set [" + badFieldList.Substring(1) + "]."); } } return("ok, all server diagnostics passed" + Environment.NewLine + result.ToString()); } catch (Exception ex) { cp.Site.ErrorReport(ex); return("ERROR, unexpected exception during diagnostics"); } }
// //==================================================================================================== /// <summary> /// when breaking changes are required for data, update them here /// </summary> /// <param name="core"></param> /// <param name="DataBuildVersion"></param> public static void migrateData(CoreController core, string DataBuildVersion, string logPrefix) { try { CPClass cp = core.cpParent; // // -- Roll the style sheet cache if it is setup core.siteProperties.setProperty("StylesheetSerialNumber", (-1).ToString()); // // -- verify ID is primary key on all tables with an id foreach (TableModel table in DbBaseModel.createList <TableModel>(cp)) { if (!string.IsNullOrWhiteSpace(table.name)) { bool tableHasId = false; { // // -- verify table as an id field string sql = "SELECT name FROM sys.columns WHERE Name = N'ID' AND Object_ID = Object_ID(N'ccmembers')"; DataTable dt = cp.Db.ExecuteQuery(sql); if (dt != null) { tableHasId = !dt.Rows.Equals(0); } } if (tableHasId) { // // -- table has id field, make sure it is primary key string sql = "" + " select Col.Column_Name" + " from INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col" + " where (Col.Constraint_Name = Tab.Constraint_Name) AND (Col.Table_Name = Tab.Table_Name) AND (Constraint_Type = 'PRIMARY KEY') AND (Col.Table_Name = '" + table.name + "')"; bool idPrimaryKeyFound = false; foreach (DataRow dr in core.db.executeQuery(sql).Rows) { if (GenericController.encodeText(dr["Column_Name"]).ToLower().Equals("id")) { idPrimaryKeyFound = true; break; } } if (!idPrimaryKeyFound) { try { core.db.executeNonQuery("alter table " + table.name + " add primary key (ID)"); } catch (Exception ex) { LogController.logError(core, ex, "Content Table [" + table.name + "] does not include column ID. Exception happened while adding column and setting it primarykey."); } } } } } // // -- continue only if a previous build exists if (!string.IsNullOrEmpty(DataBuildVersion)) { // // -- 4.1 to 5 conversions if (GenericController.versionIsOlder(DataBuildVersion, "4.1")) { // // -- create Data Migration Assets collection var migrationCollection = DbBaseModel.createByUniqueName <AddonCollectionModel>(cp, "Data Migration Assets"); if (migrationCollection == null) { migrationCollection = DbBaseModel.addDefault <AddonCollectionModel>(cp); migrationCollection.name = "Data Migration Assets"; } // // -- remove all addon content fieldtype rules Contensive.Models.Db.DbBaseModel.deleteRows <Contensive.Models.Db.AddonContentFieldTypeRulesModel>(cp, "(1=1)"); // // -- delete /admin www subfolder core.wwwFiles.deleteFolder("admin"); // // -- delete .asp and .php files foreach (BaseClasses.CPFileSystemBaseClass.FileDetail file in core.wwwFiles.getFileList("")) { if (file == null) { continue; } if (string.IsNullOrWhiteSpace(file.Name)) { continue; } if (file.Name.Length < 4) { continue; } string extension = System.IO.Path.GetExtension(file.Name).ToLower(CultureInfo.InvariantCulture); if ((extension == ".php") || (extension == ".asp")) { core.wwwFiles.deleteFile(file.Name); } } // // -- create www /cclib folder and copy in legacy resources core.programFiles.copyFile("cclib.zip", "cclib.zip", core.wwwFiles); core.wwwFiles.unzipFile("cclib.zip"); // // -- remove all the old menu entries and leave the navigation entries var navContent = DbBaseModel.createByUniqueName <ContentModel>(cp, Contensive.Models.Db.NavigatorEntryModel.tableMetadata.contentName); if (navContent != null) { core.db.executeNonQuery("delete from ccMenuEntries where ((contentcontrolid<>0)and(contentcontrolid<>" + navContent.id + ")and(contentcontrolid is not null))"); } // // -- reinstall newest font-awesome collection string returnErrorMessage = ""; var context = new Stack <string>(); var nonCritialErrorList = new List <string>(); var collectionsInstalledList = new List <string>(); CollectionLibraryController.installCollectionFromLibrary(core, false, context, Constants.fontAwesomeCollectionGuid, ref returnErrorMessage, false, true, ref nonCritialErrorList, logPrefix, ref collectionsInstalledList); // // -- reinstall newest redactor collection returnErrorMessage = ""; context = new Stack <string>(); nonCritialErrorList = new List <string>(); collectionsInstalledList = new List <string>(); CollectionLibraryController.installCollectionFromLibrary(core, false, context, Constants.redactorCollectionGuid, ref returnErrorMessage, false, true, ref nonCritialErrorList, logPrefix, ref collectionsInstalledList); // // -- addons with active-x -- remove programid and add script code that logs error string newCode = "" + "function m" + " ' + CHAR(13)+CHAR(10) + ' \ncp.Site.ErrorReport(\"deprecated active-X add-on executed [#\" & cp.addon.id & \", \" & cp.addon.name & \"]\")" + " ' + CHAR(13)+CHAR(10) + ' \nend function" + ""; string sql = "update ccaggregatefunctions set help='Legacy activeX: ' + objectprogramId, objectprogramId=null, ScriptingCode='" + newCode + "' where (ObjectProgramID is not null)"; LogController.logInfo(core, "MigrateData, removing activex addons, adding exception logging, sql [" + sql + "]"); core.db.executeNonQuery(sql); // // -- create page menus from section menus using (var cs = new CsModel(core)) { sql = "select m.name as menuName, m.id as menuId, p.name as pageName, p.id as pageId, s.name as sectionName, m.*" + " from ccDynamicMenus m" + " left join ccDynamicMenuSectionRules r on r.DynamicMenuId = m.id" + " left join ccSections s on s.id = r.SectionID" + " left join ccPageContent p on p.id = s.RootPageID" + " where (p.id is not null)and(s.active>0)" + " order by m.id, s.sortorder,s.id"; if (cs.openSql(sql)) { int sortOrder = 0; do { string menuName = cs.getText("menuName"); if (!string.IsNullOrWhiteSpace(menuName)) { var menu = DbBaseModel.createByUniqueName <MenuModel>(cp, menuName); if (menu == null) { menu = DbBaseModel.addEmpty <MenuModel>(cp); menu.name = menuName; try { menu.classItemActive = cs.getText("classItemActive"); menu.classItemFirst = cs.getText("classItemFirst"); menu.classItemHover = cs.getText("classItemHover"); menu.classItemLast = cs.getText("classItemLast"); menu.classTierAnchor = cs.getText("classTierItem"); menu.classTierItem = cs.getText("classTierItem"); menu.classTierList = cs.getText("classTierList"); menu.classTopAnchor = cs.getText("classTopItem"); menu.classTopItem = cs.getText("classTopItem"); menu.classTopList = cs.getText("classTopList"); menu.classTopWrapper = cs.getText("classTopWrapper"); } catch (Exception ex) { LogController.logError(core, ex, "migrateData error populating menu from dynamic menu."); } menu.save(cp); } // // -- set the root page's menuHeadline to the section name var page = DbBaseModel.create <PageContentModel>(cp, cs.getInteger("pageId")); if (page != null) { page.menuHeadline = cs.getText("sectionName"); page.save(cp); // // -- create a menu-page rule to attach this page to the menu in the current order var menuPageRule = DbBaseModel.addEmpty <MenuPageRuleModel>(cp); if (menuPageRule != null) { menuPageRule.name = "Created from v4.1 menu sections " + core.dateTimeNowMockable.ToString(); menuPageRule.pageId = page.id; menuPageRule.menuId = menu.id; menuPageRule.active = true; menuPageRule.sortOrder = sortOrder.ToString().PadLeft(4, '0'); menuPageRule.save(cp); sortOrder += 10; } } } cs.goNext(); } while (cs.ok()); } } // // -- create a theme addon for each template for styles and meta content using (var csTemplate = cp.CSNew()) { if (csTemplate.Open("page templates")) { do { int templateId = csTemplate.GetInteger("id"); string templateStylePrepend = ""; string templateStyles = csTemplate.GetText("StylesFilename"); // // -- add shared styles to the template stylesheet using (var csStyleRule = cp.CSNew()) { if (csStyleRule.Open("shared styles template rules", "(TemplateID=" + templateId + ")")) { do { int sharedStyleId = csStyleRule.GetInteger("styleid"); using (var csStyle = cp.CSNew()) { if (csStyleRule.Open("shared styles", "(id=" + sharedStyleId + ")")) { // // -- prepend lines beginning with @ t string styles = csStyleRule.GetText("StyleFilename"); if (!string.IsNullOrWhiteSpace(styles)) { // // -- trim off leading spaces, newlines, comments styles = styles.Trim(); while (!string.IsNullOrWhiteSpace(styles) && styles.Substring(0, 1).Equals("@")) { if (styles.IndexOf(Environment.NewLine) >= 0) { templateStylePrepend += styles.Substring(0, styles.IndexOf(Environment.NewLine)); styles = styles.Substring(styles.IndexOf(Environment.NewLine) + 1).Trim(); } else { templateStylePrepend += styles; styles = string.Empty; } } ; templateStyles += Environment.NewLine + styles; } } } csStyleRule.GoNext(); } while (csStyleRule.OK()); } } // // -- create an addon var themeAddon = DbBaseModel.addDefault <AddonModel>(cp); themeAddon.name = "Theme assets for template " + csTemplate.GetText("name"); themeAddon.otherHeadTags = csTemplate.GetText("otherheadtags"); themeAddon.javaScriptBodyEnd = csTemplate.GetText("jsendbody"); themeAddon.stylesFilename.content = templateStylePrepend + Environment.NewLine + templateStyles; themeAddon.collectionId = migrationCollection.id; themeAddon.save(cp); // // -- create an addon template rule to set dependency var rule = DbBaseModel.addEmpty <AddonTemplateRuleModel>(cp); rule.addonId = themeAddon.id; rule.templateId = templateId; rule.save(cp); // csTemplate.GoNext(); } while (csTemplate.OK()); } } // // -- reset the html minify so it is easier to resolve other issues core.siteProperties.setProperty("ALLOW HTML MINIFY", false); // // -- remove contentcategoryid from all edit page cp.Db.ExecuteNonQuery("update ccfields set Authorable=0 where name='contentcategoryid'"); cp.Db.ExecuteNonQuery("update ccfields set Authorable=0 where name='editsourceid'"); cp.Db.ExecuteNonQuery("update ccfields set Authorable=0 where name='editarchive'"); cp.Db.ExecuteNonQuery("update ccfields set Authorable=0 where name='editblank'"); // // -- remove legacy workflow fields UpgradeController.dropLegacyWorkflowField(core, "editsourceid"); cp.Db.ExecuteNonQuery("delete from ccfields where name='editsourceid'"); // UpgradeController.dropLegacyWorkflowField(core, "editblank"); cp.Db.ExecuteNonQuery("delete from ccfields where name='editblank'"); // UpgradeController.dropLegacyWorkflowField(core, "editarchive"); cp.Db.ExecuteNonQuery("delete from ccfields where name='editarchive'"); // UpgradeController.dropLegacyWorkflowField(core, "contentcategoryid"); cp.Db.ExecuteNonQuery("delete from ccfields where name='contentcategoryid'"); // // // -- end of 4.1 to 5 conversion } // // -- 5.19.1223 conversion -- render AddonList no copyFilename if (GenericController.versionIsOlder(DataBuildVersion, "5.19.1223")) { // // -- verify design block installation string returnUserError = ""; if (!cp.Db.IsTable("dbtext")) { if (!cp.Addon.InstallCollectionFromLibrary(Constants.designBlockCollectionGuid, ref returnUserError)) { throw new Exception("Error installing Design Blocks, required for data upgrade. " + returnUserError); } } // // -- add a text block and childPageList to every page without an addonlist foreach (var page in DbBaseModel.createList <PageContentModel>(cp, "(addonList is null)")) { convertPageContentToAddonList(core, page); } core.siteProperties.setProperty("PageController Render Legacy Copy", false); } // // -- 5.2005.9.4 conversion -- collections incorrectly marked not-updateable - mark all except themes (templates) if (GenericController.versionIsOlder(DataBuildVersion, "5.2005.9.4")) { // // -- cp.Db.ExecuteNonQuery("update ccaddoncollections set updatable=1 where name not like '%theme%'"); } // // -- 5.2005.19.1 conversion -- rename site property EmailUrlRootRelativePrefix to LocalFileModeProtocolDomain if (GenericController.versionIsOlder(DataBuildVersion, "5.2005.19.1")) { // // -- if (string.IsNullOrWhiteSpace(cp.Site.GetText("webAddressProtocolDomain"))) { cp.Site.SetProperty("webAddressProtocolDomain", cp.Site.GetText("EmailUrlRootRelativePrefix")); } } // // -- delete legacy corehelp collection. Created with fields that have only field name, legacy install layed collections over the application collection // new install loads fields directly from collection, which coreHelp then marks all fields inactive. core.db.delete("{6e905db1-d3f0-40af-aac4-4bd78e680fae}", "ccaddoncollections"); } // -- Reload core.cache.invalidateAll(); core.clearMetaData(); } catch (Exception ex) { LogController.logError(core, ex); throw; } }
// //==================================================================================================== /// <summary> /// 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 + " </SPAN>"); } else if (FieldLocked) { streamRow.add(SpanClassAdminSmall + fieldsort.field.nameLc + " </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); } }
//==================================================================================================== /// <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 + "]"); } }