Ejemplo n.º 1
0
        //
        //====================================================================================================
        // 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;
            }
        }
Ejemplo n.º 2
0
 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);
     }
 }
Ejemplo n.º 3
0
        //====================================================================================================
        //
        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);
            }
        }
Ejemplo n.º 4
0
        //
        //=============================================================================
        /// <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;
            }
        }
Ejemplo n.º 5
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);
     }
 }
Ejemplo n.º 6
0
 //
 //=============================================================================
 //
 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);
     }
 }
Ejemplo n.º 7
0
 //
 //====================================================================================================
 //
 public override int GetInteger(string FieldName)
 {
     try {
         return(cs.getInteger(FieldName));
     } catch (Exception ex) {
         LogController.logError(cp.core, ex);
         throw;
     }
 }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
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");
             }
         }
     }
 }
Ejemplo n.º 10
0
        //
        //---------------------------------------------------------------------------
        //   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);
        }
Ejemplo n.º 11
0
        //
        //=============================================================================
        // 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);
        }
Ejemplo n.º 12
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 + "]");
            }
        }
Ejemplo n.º 13
0
 public static void housekeep(CoreController core, HouseKeepEnvironmentModel env)
 {
     try {
         //
         LogController.logInfo(core, "Housekeep, metadata");
         //
         //
         // block duplicate redirect fields (match contentid+fieldtype+caption)
         //
         LogController.logInfo(core, "Inactivate duplicate redirect fields");
         int    FieldContentId = 0;
         string FieldLast      = null;
         string FieldNew       = null;
         int    FieldRecordId  = 0;
         using (var csData = new CsModel(core)) {
             csData.openSql("Select ID, ContentID, Type, Caption from ccFields where (active<>0)and(Type=" + (int)CPContentBaseClass.FieldTypeIdEnum.Redirect + ") Order By ContentID, Caption, ID");
             FieldLast = "";
             while (csData.ok())
             {
                 FieldContentId = csData.getInteger("Contentid");
                 string FieldCaption = csData.getText("Caption");
                 FieldNew = FieldContentId + FieldCaption;
                 if (FieldNew == FieldLast)
                 {
                     FieldRecordId = csData.getInteger("ID");
                     core.db.executeNonQuery("Update ccFields set active=0 where ID=" + FieldRecordId + ";");
                 }
                 FieldLast = FieldNew;
                 csData.goNext();
             }
         }
         //
         // convert FieldTypeLongText + htmlContent to FieldTypeHTML
         LogController.logInfo(core, "convert FieldTypeLongText + htmlContent to FieldTypeHTML.");
         string sql = "update ccfields set type=" + (int)CPContentBaseClass.FieldTypeIdEnum.HTML + " where type=" + (int)CPContentBaseClass.FieldTypeIdEnum.LongText + " and ( htmlcontent<>0 )";
         core.db.executeNonQuery(sql);
         //
         // Content TextFile types with no controlling record
         //
         if (GenericController.encodeBoolean(core.siteProperties.getText("ArchiveAllowFileClean", "false")))
         {
             //
             int DSType = core.db.getDataSourceType();
             LogController.logInfo(core, "Content TextFile types with no controlling record.");
             using (var csData = new CsModel(core)) {
                 sql = "SELECT DISTINCT ccTables.Name as TableName, ccFields.Name as FieldName"
                       + " FROM (ccFields LEFT JOIN ccContent ON ccFields.ContentId = ccContent.ID) LEFT JOIN ccTables ON ccContent.ContentTableId = ccTables.ID"
                       + " Where (((ccFields.Type) = 10))"
                       + " ORDER BY ccTables.Name";
                 csData.openSql(sql);
                 while (csData.ok())
                 {
                     //
                     // Get all the files in this path, and check that the record exists with this in its field
                     //
                     string FieldName = csData.getText("FieldName");
                     string TableName = csData.getText("TableName");
                     string PathName  = TableName + "\\" + FieldName;
                     List <CPFileSystemBaseClass.FileDetail> FileList = core.cdnFiles.getFileList(PathName);
                     if (FileList.Count > 0)
                     {
                         core.db.executeNonQuery("CREATE INDEX temp" + FieldName + " ON " + TableName + " (" + FieldName + ")");
                         foreach (CPFileSystemBaseClass.FileDetail file in FileList)
                         {
                             string Filename        = file.Name;
                             string VirtualFileName = PathName + "\\" + Filename;
                             string VirtualLink     = GenericController.strReplace(VirtualFileName, "\\", "/");
                             long   FileSize        = file.Size;
                             if (FileSize == 0)
                             {
                                 sql = "update " + TableName + " set " + FieldName + "=null where (" + FieldName + "=" + DbController.encodeSQLText(VirtualFileName) + ")or(" + FieldName + "=" + DbController.encodeSQLText(VirtualLink) + ")";
                                 core.db.executeNonQuery(sql);
                                 core.cdnFiles.deleteFile(VirtualFileName);
                             }
                             else
                             {
                                 using (var csTest = new CsModel(core)) {
                                     sql = "SELECT ID FROM " + TableName + " WHERE (" + FieldName + "=" + DbController.encodeSQLText(VirtualFileName) + ")or(" + FieldName + "=" + DbController.encodeSQLText(VirtualLink) + ")";
                                     if (!csTest.openSql(sql))
                                     {
                                         core.cdnFiles.deleteFile(VirtualFileName);
                                     }
                                 }
                             }
                         }
                         if (DSType == 1)
                         {
                             // access
                             sql = "Drop INDEX temp" + FieldName + " ON " + TableName;
                         }
                         else if (DSType == 2)
                         {
                             // sql server
                             sql = "DROP INDEX " + TableName + ".temp" + FieldName;
                         }
                         else
                         {
                             // mysql
                             sql = "ALTER TABLE " + TableName + " DROP INDEX temp" + FieldName;
                         }
                         core.db.executeNonQuery(sql);
                     }
                     csData.goNext();
                 }
             }
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
Ejemplo n.º 14
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);
            }
        }
        //
        //=============================================================================
        // Find and Replace launch tool
        //=============================================================================
        //
        public static string get(CoreController core)
        {
            string result = "";

            try {
                StringBuilderLegacyController Stream = new StringBuilderLegacyController();
                //
                Stream.add(AdminUIController.getHeaderTitleDescription("Find and Replace", "This tool runs a find and replace operation on content throughout the site."));
                //
                // Process the form
                //
                string Button      = core.docProperties.getText("button");
                bool   IsDeveloper = core.session.isAuthenticatedDeveloper();
                int    RowPtr      = 0;
                string CDefList    = "";
                string FindText    = "";
                string ReplaceText = "";
                string lcName      = null;
                if (Button == ButtonFindAndReplace)
                {
                    int RowCnt = core.docProperties.getInteger("CDefRowCnt");
                    if (RowCnt > 0)
                    {
                        for (RowPtr = 0; RowPtr < RowCnt; RowPtr++)
                        {
                            if (core.docProperties.getBoolean("Cdef" + RowPtr))
                            {
                                lcName = GenericController.toLCase(core.docProperties.getText("CDefName" + RowPtr));
                                if (IsDeveloper || (lcName == "page content") || (lcName == "copy content") || (lcName == "page templates"))
                                {
                                    CDefList = CDefList + "," + lcName;
                                }
                            }
                        }
                        if (!string.IsNullOrEmpty(CDefList))
                        {
                            CDefList = CDefList.Substring(1);
                        }
                        FindText    = core.docProperties.getText("FindText");
                        ReplaceText = core.docProperties.getText("ReplaceText");
                        //string QS = "app=" + encodeNvaArgument(core.appConfig.name) + "&FindText=" + encodeNvaArgument(FindText) + "&ReplaceText=" + encodeNvaArgument(ReplaceText) + "&CDefNameList=" + encodeNvaArgument(CDefList);
                        var cmdDetail = new TaskModel.CmdDetailClass {
                            addonId   = 0,
                            addonName = "GetForm_FindAndReplace",
                            args      = new System.Collections.Generic.Dictionary <string, string> {
                                { "app", core.appConfig.name },
                                { "FindText", FindText },
                                { "ReplaceText", ReplaceText },
                                { "CDefNameList", CDefList }
                            }
                        };
                        TaskSchedulerController.addTaskToQueue(core, cmdDetail, false);
                        Stream.add("Find and Replace has been requested for content definitions [" + CDefList + "], finding [" + FindText + "] and replacing with [" + ReplaceText + "]");
                    }
                }
                else
                {
                    CDefList    = "Page Content,Copy Content,Page Templates";
                    FindText    = "";
                    ReplaceText = "";
                }
                //
                // Display form
                //
                int FindRows = core.docProperties.getInteger("SQLRows");
                if (FindRows == 0)
                {
                    FindRows = core.userProperty.getInteger("FindAndReplaceFindRows", 1);
                }
                else
                {
                    core.userProperty.setProperty("FindAndReplaceFindRows", FindRows.ToString());
                }
                int ReplaceRows = core.docProperties.getInteger("ReplaceRows");
                if (ReplaceRows == 0)
                {
                    ReplaceRows = core.userProperty.getInteger("FindAndReplaceReplaceRows", 1);
                }
                else
                {
                    core.userProperty.setProperty("FindAndReplaceReplaceRows", ReplaceRows.ToString());
                }
                //
                Stream.add("<div>Find</div>");
                Stream.add("<TEXTAREA NAME=\"FindText\" ROWS=\"" + FindRows + "\" ID=\"FindText\" STYLE=\"width: 800px;\">" + FindText + "</TEXTAREA>");
                Stream.add("&nbsp;<INPUT TYPE=\"Text\" TabIndex=-1 NAME=\"FindTextRows\" SIZE=\"3\" VALUE=\"" + FindRows + "\" ID=\"\"  onchange=\"FindText.rows=FindTextRows.value; return true\"> Rows");
                Stream.add("<br><br>");
                //
                Stream.add("<div>Replace it with</div>");
                Stream.add("<TEXTAREA NAME=\"ReplaceText\" ROWS=\"" + ReplaceRows + "\" ID=\"ReplaceText\" STYLE=\"width: 800px;\">" + ReplaceText + "</TEXTAREA>");
                Stream.add("&nbsp;<INPUT TYPE=\"Text\" TabIndex=-1 NAME=\"ReplaceTextRows\" SIZE=\"3\" VALUE=\"" + ReplaceRows + "\" ID=\"\"  onchange=\"ReplaceText.rows=ReplaceTextRows.value; return true\"> Rows");
                Stream.add("<br><br>");
                string TopHalf    = "";
                string BottomHalf = "";
                //
                using (var csData = new CsModel(core)) {
                    csData.open("Content");
                    while (csData.ok())
                    {
                        string RecordName = csData.getText("Name");
                        lcName = GenericController.toLCase(RecordName);
                        if (IsDeveloper || (lcName == "page content") || (lcName == "copy content") || (lcName == "page templates"))
                        {
                            int RecordId = csData.getInteger("ID");
                            if (GenericController.strInstr(1, "," + CDefList + ",", "," + RecordName + ",") != 0)
                            {
                                TopHalf = TopHalf + "<div>" + HtmlController.checkbox("Cdef" + RowPtr, true) + HtmlController.inputHidden("CDefName" + RowPtr, RecordName) + "&nbsp;" + csData.getText("Name") + "</div>";
                            }
                            else
                            {
                                BottomHalf = BottomHalf + "<div>" + HtmlController.checkbox("Cdef" + RowPtr, false) + HtmlController.inputHidden("CDefName" + RowPtr, RecordName) + "&nbsp;" + csData.getText("Name") + "</div>";
                            }
                        }
                        csData.goNext();
                        RowPtr += 1;
                    }
                }
                Stream.add(TopHalf + BottomHalf + HtmlController.inputHidden("CDefRowCnt", RowPtr));
                //
                result = AdminUIController.getToolForm(core, Stream.text, ButtonCancel + "," + ButtonFindAndReplace);
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(result);
        }
Ejemplo n.º 16
0
 //
 //=============================================================================
 // 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>
 /// 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;
     }
 }
Ejemplo n.º 18
0
 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);
     }
 }
Ejemplo n.º 19
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);
            }
        }
Ejemplo n.º 20
0
        //
        //=============================================================================
        // 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);
        }
        //
        //========================================================================
        /// <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);
        }
Ejemplo n.º 22
0
        //
        //===========================================================================
        //
        public static string get(CoreController core, AdminDataModel adminData, IndexConfigClass indexConfig, PermissionController.UserContentPermissions userContentPermissions, string sql, DataSourceModel dataSource, Dictionary <string, bool> FieldUsedInColumns, Dictionary <string, bool> IsLookupFieldValid)
        {
            try {
                bool allowDelete      = (adminData.adminContent.allowDelete) && (userContentPermissions.allowDelete) && (indexConfig.allowDelete);
                var  DataTable_HdrRow = new StringBuilder("<tr>");
                //
                // Row Number Column
                DataTable_HdrRow.Append("<td width=20 align=center valign=bottom class=\"small ccAdminListCaption\">Row</td>");
                //
                // Edit Column
                DataTable_HdrRow.Append("<td width=20 align=center valign=bottom class=\"small ccAdminListCaption\">Edit</td>");
                //
                // Delete Select Box Columns
                if (!allowDelete)
                {
                    DataTable_HdrRow.Append("<td width=20 align=center valign=bottom class=\"small ccAdminListCaption\"><input TYPE=CheckBox disabled=\"disabled\"></td>");
                }
                else
                {
                    DataTable_HdrRow.Append("<td width=20 align=center valign=bottom class=\"small ccAdminListCaption\"><input TYPE=CheckBox OnClick=\"CheckInputs('DelCheck',this.checked);\"></td>");
                }
                //
                // -- create header
                int ColumnWidthTotal = 0;
                foreach (var column in indexConfig.columns)
                {
                    if (column.Width < 1)
                    {
                        column.Width = 1;
                    }
                    ColumnWidthTotal += column.Width;
                }
                foreach (var column in indexConfig.columns)
                {
                    //
                    // ----- print column headers - anchored so they sort columns
                    //
                    int ColumnWidth = encodeInteger((100 * column.Width) / (double)ColumnWidthTotal);
                    //
                    // if this is a current sort ,add the reverse flag
                    //
                    StringBuilder buttonHref = new StringBuilder();
                    buttonHref.Append("/" + core.appConfig.adminRoute + "?" + rnAdminForm + "=" + AdminFormIndex + "&SetSortField=" + column.Name + "&RT=0&" + RequestNameTitleExtension + "=" + GenericController.encodeRequestVariable(adminData.titleExtension) + "&cid=" + adminData.adminContent.id + "&ad=" + adminData.ignore_legacyMenuDepth);
                    if (!indexConfig.sorts.ContainsKey(column.Name))
                    {
                        buttonHref.Append("&SetSortDirection=1");
                    }
                    else
                    {
                        switch (indexConfig.sorts[column.Name].direction)
                        {
                        case 1: {
                            buttonHref.Append("&SetSortDirection=2");
                            break;
                        }

                        case 2: {
                            buttonHref.Append("&SetSortDirection=0");
                            break;
                        }

                        default: {
                            // nothing
                            break;
                        }
                        }
                    }
                    //
                    // -- column header includes WherePairCount
                    if (!adminData.wherePair.Count.Equals(0))
                    {
                        int ptr = 0;
                        foreach (var kvp in adminData.wherePair)
                        {
                            if (!string.IsNullOrWhiteSpace(kvp.Key))
                            {
                                buttonHref.Append("&wl" + ptr + "=" + GenericController.encodeRequestVariable(kvp.Value));
                                buttonHref.Append("&wr" + ptr + "=" + GenericController.encodeRequestVariable(kvp.Value));
                                ptr++;
                            }
                        }
                    }
                    string buttonFace = adminData.adminContent.fields[column.Name.ToLowerInvariant()].caption;
                    buttonFace = GenericController.strReplace(buttonFace, " ", "&nbsp;");
                    string SortTitle = "Sort A-Z";
                    //
                    if (indexConfig.sorts.ContainsKey(column.Name))
                    {
                        string sortSuffix = ((indexConfig.sorts.Count < 2) ? "" : indexConfig.sorts[column.Name].order.ToString());
                        switch (indexConfig.sorts[column.Name].direction)
                        {
                        case 1: {
                            buttonFace = iconArrowDown + sortSuffix + "&nbsp;" + buttonFace;
                            SortTitle  = "Sort Z-A";
                            break;
                        }

                        case 2: {
                            buttonFace = iconArrowUp + sortSuffix + "&nbsp;" + buttonFace;
                            SortTitle  = "Remove Sort";
                            break;
                        }

                        default: {
                            // nothing
                            break;
                        }
                        }
                    }
                    if (indexConfig.allowColumnSort)
                    {
                        buttonFace = HtmlController.a(buttonFace, new CPBase.BaseModels.HtmlAttributesA()
                        {
                            title  = SortTitle,
                            href   = buttonHref.ToString(),
                            @class = "ccAdminListCaption"
                        });
                    }
                    adminData.buttonObjectCount += 1;
                    DataTable_HdrRow.Append("<td width=\"" + ColumnWidth + "%\" valign=bottom align=left class=\"small ccAdminListCaption\">");
                    DataTable_HdrRow.Append(buttonFace);
                    DataTable_HdrRow.Append("</td>");
                }
                DataTable_HdrRow.Append("</tr>");
                //
                // -- generic admin url for edit and add links
                string adminEditPresetArgQsList = "";
                string adminUrlBase             = "\\" + core.appConfig.adminRoute + "?" + rnAdminAction + "=" + Constants.AdminActionNop + "&cid=" + adminData.adminContent.id + "&" + RequestNameTitleExtension + "=" + GenericController.encodeRequestVariable(adminData.titleExtension) + "&ad=" + adminData.ignore_legacyMenuDepth + "&" + rnAdminSourceForm + "=" + adminData.adminForm + "&" + rnAdminForm + "=" + AdminFormEdit;
                if (!adminData.wherePair.Count.Equals(0))
                {
                    int WhereCount = 0;
                    foreach (var kvp in adminData.wherePair)
                    {
                        adminEditPresetArgQsList += "&" + encodeRequestVariable(kvp.Key) + "=" + GenericController.encodeRequestVariable(kvp.Value);
                        WhereCount++;
                    }
                    adminUrlBase += adminEditPresetArgQsList;
                }
                //
                // -- output data rows
                var    dataTableRows = new StringBuilder();
                string rowColor      = "";
                int    rowNumber     = 0;
                int    rowNumberLast = 0;
                using (var csData = new CsModel(core)) {
                    if (csData.openSql(sql, dataSource.name, indexConfig.recordsPerPage, indexConfig.pageNumber))
                    {
                        rowNumber     = indexConfig.recordTop;
                        rowNumberLast = indexConfig.recordTop + indexConfig.recordsPerPage;
                        //
                        // --- Print out the records
                        while ((csData.ok()) && (rowNumber < rowNumberLast))
                        {
                            int recordId = csData.getInteger("ID");
                            if (rowColor == "class=\"ccAdminListRowOdd\"")
                            {
                                rowColor = "class=\"ccAdminListRowEven\"";
                            }
                            else
                            {
                                rowColor = "class=\"ccAdminListRowOdd\"";
                            }
                            //
                            // -- new row
                            dataTableRows.Append(Environment.NewLine + "<tr>");
                            //
                            // --- row number column
                            dataTableRows.Append("<td align=right " + rowColor + ">" + (rowNumber + 1).ToString() + "</td>");
                            //
                            // --- edit column
                            dataTableRows.Append("<td align=center " + rowColor + ">" + getRecordEditAnchorTag(adminUrlBase + "&id=" + recordId) + "</td>");
                            //
                            // --- Delete Checkbox Columns
                            if (allowDelete)
                            {
                                dataTableRows.Append("<td align=center " + rowColor + "><input TYPE=CheckBox NAME=row" + rowNumber + " VALUE=1 ID=\"DelCheck\"><input type=hidden name=rowid" + rowNumber + " VALUE=" + recordId + "></span></td>");
                            }
                            else
                            {
                                dataTableRows.Append("<td align=center " + rowColor + "><input TYPE=CheckBox disabled=\"disabled\" NAME=row" + rowNumber + " VALUE=1><input type=hidden name=rowid" + rowNumber + " VALUE=" + recordId + "></span></td>");
                            }
                            //
                            // --- field columns
                            foreach (var column in indexConfig.columns)
                            {
                                string columnNameLc = column.Name.ToLowerInvariant();
                                if (FieldUsedInColumns.ContainsKey(columnNameLc))
                                {
                                    if (FieldUsedInColumns[columnNameLc])
                                    {
                                        dataTableRows.Append((Environment.NewLine + "<td valign=\"middle\" " + rowColor + " align=\"left\">" + SpanClassAdminNormal));
                                        dataTableRows.Append(getGridCell(core, adminData, column.Name, csData, IsLookupFieldValid[columnNameLc], GenericController.toLCase(adminData.adminContent.tableName) == "ccemail"));
                                        dataTableRows.Append(("&nbsp;</span></td>"));
                                    }
                                }
                            }
                            dataTableRows.Append(("\n    </tr>"));
                            csData.goNext();
                            rowNumber = rowNumber + 1;
                        }
                        dataTableRows.Append("<input type=hidden name=rowcnt value=" + rowNumber + ">");
                        //
                        // --- print out the stuff at the bottom
                        //
                        int RecordTop_NextPage = indexConfig.recordTop;
                        if (csData.ok())
                        {
                            RecordTop_NextPage = rowNumber;
                        }
                        int RecordTop_PreviousPage = indexConfig.recordTop - indexConfig.recordsPerPage;
                        if (RecordTop_PreviousPage < 0)
                        {
                            RecordTop_PreviousPage = 0;
                        }
                    }
                }
                //
                // Header at bottom
                //
                if (rowColor == "class=\"ccAdminListRowOdd\"")
                {
                    rowColor = "class=\"ccAdminListRowEven\"";
                }
                else
                {
                    rowColor = "class=\"ccAdminListRowOdd\"";
                }
                string blankRow = "<tr><td colspan=" + (indexConfig.columns.Count + 3) + " " + rowColor + " style=\"text-align:left ! important;\">{msg}</td></tr>";
                if (rowNumber == 0)
                {
                    //
                    // -- No records found
                    dataTableRows.Append(blankRow.Replace("{msg}", "----- no records were found -----"));
                }
                else
                {
                    if (rowNumber < rowNumberLast)
                    {
                        //
                        // --End of list
                        dataTableRows.Append(blankRow.Replace("{msg}", "----- end of list -----"));
                    }
                }
                if (indexConfig.allowAddRow)
                {
                    //
                    // optional AddRow
                    foreach (var addTag in getRecordAddAnchorTag(core, adminData.adminContent.name, adminEditPresetArgQsList, false, userContentPermissions.allowAdd))
                    {
                        dataTableRows.Append(blankRow.Replace("{msg}", addTag));
                    }
                }
                //
                // Add another header to the data rows
                //
                dataTableRows.Append(DataTable_HdrRow.ToString());
                //
                var DataTable_FindRow = new StringBuilder();
                if (indexConfig.allowFind)
                {
                    //
                    // ----- DataTable_FindRow
                    //
                    DataTable_FindRow.Append("<tr><td colspan=" + (3 + indexConfig.columns.Count) + " style=\"background-color:black;height:1;\"></td></tr>");
                    DataTable_FindRow.Append("<tr>");
                    DataTable_FindRow.Append("<td valign=\"middle\" colspan=3 width=\"60\" class=\"ccPanel\" align=center style=\"vertical-align:middle;padding:8px;text-align:center ! important;\">");
                    DataTable_FindRow.Append(AdminUIController.getButtonPrimary(ButtonFind, "", false, "FindButton") + "</td>");
                    int ColumnPointer = 0;
                    var listOfMatches = new List <FindWordMatchEnum> {
                        FindWordMatchEnum.matchincludes, FindWordMatchEnum.MatchEquals, FindWordMatchEnum.MatchTrue, FindWordMatchEnum.MatchFalse
                    };
                    foreach (var column in indexConfig.columns)
                    {
                        string FieldName     = GenericController.toLCase(column.Name);
                        string FindWordValue = "";
                        if (indexConfig.findWords.ContainsKey(FieldName))
                        {
                            var findWord = indexConfig.findWords[FieldName];
                            if (listOfMatches.Any(s => findWord.MatchOption.Equals(s)))
                            {
                                FindWordValue = findWord.Value;
                            }
                        }
                        DataTable_FindRow.Append(Environment.NewLine + "<td valign=\"middle\" align=\"center\" class=\"ccPanel3DReverse\" style=\"padding:8px;\">"
                                                 + "<input type=hidden name=\"FindName" + ColumnPointer + "\" value=\"" + FieldName + "\">"
                                                 + "<input class=\"form-control findInput\"  onkeypress=\"KeyCheck(event);\"  type=text id=\"F" + ColumnPointer + "\" name=\"FindValue" + ColumnPointer + "\" value=\"" + FindWordValue + "\" style=\"padding-right:.2rem;padding-left:.2rem;\">"
                                                 + "</td>");
                        ColumnPointer += 1;
                    }
                    DataTable_FindRow.Append("</tr>");
                }
                //
                // Assemble DataTable
                //
                string grid = ""
                              + "<table ID=\"DataTable\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"Background-Color:white;\">"
                              + DataTable_HdrRow + dataTableRows + DataTable_FindRow + "</table>";
                return(grid);
            } catch (Exception ex) {
                LogController.logError(core, ex);
                return(HtmlController.div("There was an error creating the record list."));
            }
        }
Ejemplo n.º 23
0
        //
        //========================================================================
        /// <summary>
        /// Display a field in the admin index form
        /// </summary>
        /// <param name="core"></param>
        /// <param name="adminData"></param>
        /// <param name="fieldName"></param>
        /// <param name="CS"></param>
        /// <param name="IsLookupFieldValid"></param>
        /// <param name="IsEmailContent"></param>
        /// <returns></returns>
        public static string getGridCell(CoreController core, AdminDataModel adminData, string fieldName, CsModel csData, bool IsLookupFieldValid, bool IsEmailContent)
        {
            try {
                var Stream = new StringBuilderLegacyController();
                var field  = adminData.adminContent.fields[fieldName.ToLowerInvariant()];
                if (field.password)
                {
                    //
                    // -- do not list password fields
                    Stream.add("****");
                }
                else
                {
                    int Pos = 0;
                    switch (field.fieldTypeId)
                    {
                    case CPContentBaseClass.FieldTypeIdEnum.File:
                    case CPContentBaseClass.FieldTypeIdEnum.FileImage: {
                        string filename = csData.getText(field.nameLc);
                        filename = GenericController.strReplace(filename, "\\", "/");
                        Pos      = filename.LastIndexOf("/") + 1;
                        if (Pos != 0)
                        {
                            filename = filename.Substring(Pos);
                        }
                        Stream.add(filename);
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Lookup: {
                        if (IsLookupFieldValid)
                        {
                            Stream.add(csData.getText("LookupTable" + field.id + "Name"));
                        }
                        else if (field.lookupList != "")
                        {
                            string[] lookups   = field.lookupList.Split(',');
                            int      LookupPtr = csData.getInteger(field.nameLc) - 1;
                            if (LookupPtr <= lookups.GetUpperBound(0))
                            {
                                if (LookupPtr >= 0)
                                {
                                    Stream.add(lookups[LookupPtr]);
                                }
                            }
                        }
                        else
                        {
                            Stream.add(" ");
                        }
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.MemberSelect: {
                        if (IsLookupFieldValid)
                        {
                            Stream.add(csData.getText("LookupTable" + field.id + "Name"));
                        }
                        else
                        {
                            Stream.add(csData.getText(field.nameLc));
                        }
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Boolean: {
                        if (csData.getBoolean(field.nameLc))
                        {
                            Stream.add("yes");
                        }
                        else
                        {
                            Stream.add("no");
                        }
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Currency: {
                        string fieldValueText = csData.getText(field.nameLc);
                        if (string.IsNullOrWhiteSpace(fieldValueText))
                        {
                            Stream.add(fieldValueText);
                            break;
                        }
                        Stream.add(string.Format("{0:C}", csData.getNumber(field.nameLc)));
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.LongText:
                    case CPContentBaseClass.FieldTypeIdEnum.HTML:
                    case CPContentBaseClass.FieldTypeIdEnum.HTMLCode: {
                        string fieldValueText = csData.getText(field.nameLc);
                        if (fieldValueText.Length > 50)
                        {
                            fieldValueText = fieldValueText.left(50) + "[more]";
                        }
                        Stream.add(fieldValueText);
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.FileText:
                    case CPContentBaseClass.FieldTypeIdEnum.FileCSS:
                    case CPContentBaseClass.FieldTypeIdEnum.FileXML:
                    case CPContentBaseClass.FieldTypeIdEnum.FileJavascript:
                    case CPContentBaseClass.FieldTypeIdEnum.FileHTML:
                    case CPContentBaseClass.FieldTypeIdEnum.FileHTMLCode: {
                        string filename = csData.getText(field.nameLc);
                        if (!string.IsNullOrEmpty(filename))
                        {
                            string Copy = core.cdnFiles.readFileText(filename);
                            Stream.add(Copy);
                        }
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Redirect:
                    case CPContentBaseClass.FieldTypeIdEnum.ManyToMany: {
                        Stream.add("n/a");
                        break;
                    }

                    case CPContentBaseClass.FieldTypeIdEnum.Date: {
                        //
                        // -- if minvalue, use blank, if no time-part, do short-date
                        DateTime cellValueDate = csData.getDate(field.nameLc);
                        if (cellValueDate.Equals(DateTime.MinValue))
                        {
                            Stream.add("");
                        }
                        else if (cellValueDate.Equals(cellValueDate.Date))
                        {
                            Stream.add(cellValueDate.ToShortDateString());
                        }
                        else
                        {
                            Stream.add(cellValueDate.ToString());
                        }
                        break;
                    }

                    default: {
                        string valueString = csData.getText(field.nameLc);
                        if (string.IsNullOrWhiteSpace(valueString))
                        {
                            Stream.add(valueString);
                            break;
                        }
                        Stream.add(csData.getText(field.nameLc));
                        break;
                    }
                    }
                }
                return(HtmlController.encodeHtml(Stream.text));
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
        }
Ejemplo n.º 24
0
        //=============================================================================
        /// <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);
        }
Ejemplo n.º 25
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);
     }
 }
Ejemplo n.º 26
0
        //
        //====================================================================================================
        /// <summary>
        /// Process manual changes needed for special cases
        /// </summary>
        /// <param name="isDelete"></param>
        /// <param name="contentName"></param>
        /// <param name="recordId"></param>
        /// <param name="recordName"></param>
        /// <param name="recordParentID"></param>
        /// <param name="useContentWatchLink"></param>
        public static void processAfterSave(CoreController core, bool isDelete, string contentName, int recordId, string recordName, int recordParentID, bool useContentWatchLink)
        {
            try {
                PageContentModel.markReviewed(core.cpParent, recordId);
                string tableName = MetadataController.getContentTablename(core, contentName);
                //
                // -- invalidate the specific cache for this record
                core.cache.invalidateDbRecord(recordId, tableName);
                //
                string tableNameLower = tableName.ToLower(CultureInfo.InvariantCulture);
                if (tableNameLower == AddonCollectionModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- addon collection
                    processAfterSave_AddonCollection(core, isDelete, contentName, recordId, recordName, recordParentID, useContentWatchLink);
                }
                else if (tableNameLower == LinkForwardModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- link forward
                    core.routeMapCacheClear();
                }
                else if (tableNameLower == LinkAliasModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- link alias
                    core.routeMapCacheClear();
                }
                else if (tableNameLower == AddonModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- addon
                    core.routeMapCacheClear();
                }
                else if (tableNameLower == PersonModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- PersonModel
                    var person = PersonModel.create <PersonModel>(core.cpParent, recordId);
                    if (person != null)
                    {
                        if (isDelete)
                        {
                            LogController.addSiteActivity(core, "deleting user #" + recordId + " (" + recordName + ")", recordId, person.organizationId);
                        }
                        else
                        {
                            LogController.addSiteActivity(core, "saving changes to user #" + recordId + " (" + recordName + ")", recordId, person.organizationId);
                        }
                    }
                }
                else if (tableNameLower == OrganizationModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- Log Activity for changes to people and organizattions
                    if (isDelete)
                    {
                        LogController.addSiteActivity(core, "deleting organization #" + recordId + " (" + recordName + ")", 0, recordId);
                    }
                    else
                    {
                        LogController.addSiteActivity(core, "saving changes to organization #" + recordId + " (" + recordName + ")", 0, recordId);
                    }
                }
                else if (tableNameLower == SitePropertyModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- Site Properties
                    switch (GenericController.toLCase(recordName))
                    {
                    case "allowlinkalias":
                        PageContentModel.invalidateCacheOfTable <PageContentModel>(core.cpParent);
                        break;

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

                    case Constants._siteproperty_serverPageDefault_name:
                        PageContentModel.invalidateCacheOfTable <PageContentModel>(core.cpParent);
                        break;
                    }
                }
                else if (tableNameLower == PageContentModel.tableMetadata.tableNameLower)
                {
                    //
                    // -- set ChildPagesFound true for parent page
                    if (recordParentID > 0)
                    {
                        if (!isDelete)
                        {
                            core.db.executeNonQuery("update ccpagecontent set ChildPagesfound=1 where ID=" + recordParentID);
                        }
                    }
                    if (isDelete)
                    {
                        //
                        // Clear the Landing page and page not found site properties
                        if (recordId == GenericController.encodeInteger(core.siteProperties.getText("PageNotFoundPageID", "0")))
                        {
                            core.siteProperties.setProperty("PageNotFoundPageID", "0");
                        }
                        if (recordId == core.siteProperties.landingPageID)
                        {
                            core.siteProperties.setProperty("landingPageId", "0");
                        }
                        //
                        // Delete Link Alias entries with this PageID
                        core.db.executeNonQuery("delete from cclinkAliases where PageID=" + recordId);
                    }
                    DbBaseModel.invalidateCacheOfRecord <PageContentModel>(core.cpParent, recordId);
                }
                else if (tableNameLower == LibraryFilesModel.tableMetadata.tableNameLower)
                {
                    //
                    // --
                    processAfterSave_LibraryFiles(core, isDelete, contentName, recordId, recordName, recordParentID, useContentWatchLink);
                }
                //
                // Process Addons marked to trigger a process call on content change
                //
                Dictionary <string, string> instanceArguments;
                bool onChangeAddonsAsync = core.siteProperties.getBoolean("execute oncontentchange addons async", false);
                using (var csData = new CsModel(core)) {
                    int contentId = ContentMetadataModel.getContentId(core, contentName);
                    csData.open("Add-on Content Trigger Rules", "ContentID=" + contentId, "", false, 0, "addonid");
                    string Option_String = null;
                    if (isDelete)
                    {
                        instanceArguments = new Dictionary <string, string> {
                            { "action", "contentdelete" },
                            { "contentid", contentId.ToString() },
                            { "recordid", recordId.ToString() }
                        };
                        Option_String = ""
                                        + Environment.NewLine + "action=contentdelete"
                                        + Environment.NewLine + "contentid=" + contentId
                                        + Environment.NewLine + "recordid=" + recordId + "";
                    }
                    else
                    {
                        instanceArguments = new Dictionary <string, string> {
                            { "action", "contentchange" },
                            { "contentid", contentId.ToString() },
                            { "recordid", recordId.ToString() }
                        };
                        Option_String = ""
                                        + Environment.NewLine + "action=contentchange"
                                        + Environment.NewLine + "contentid=" + contentId
                                        + Environment.NewLine + "recordid=" + recordId + "";
                    }
                    while (csData.ok())
                    {
                        var addon = DbBaseModel.create <AddonModel>(core.cpParent, csData.getInteger("Addonid"));
                        if (addon != null)
                        {
                            if (onChangeAddonsAsync)
                            {
                                //
                                // -- execute addon async
                                core.addon.executeAsync(addon, instanceArguments);
                            }
                            else
                            {
                                //
                                // -- execute addon
                                core.addon.execute(addon, new CPUtilsBaseClass.addonExecuteContext {
                                    addonType             = CPUtilsBaseClass.addonContext.ContextOnContentChange,
                                    backgroundProcess     = false,
                                    errorContextMessage   = "",
                                    argumentKeyValuePairs = instanceArguments
                                });
                            }
                        }
                        csData.goNext();
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
        }
Ejemplo n.º 27
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);
     }
 }
Ejemplo n.º 28
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;
            }
        }
Ejemplo n.º 29
0
 //
 //====================================================================================================
 /// <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");
     }
 }
Ejemplo n.º 30
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);
        }