Пример #1
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    resultList = new StringBuilder();
         var    core       = ((CPClass)(cp)).core;
         string pauseHint  = " To pause alarm " + ((cp.User.IsAdmin) ? "set site property 'Diagnostics Pause Until Date' or [/status?pauseUntil=" + core.dateTimeNowMockable.AddHours(1) + "]." : "login as administrator.");
         cp.Response.SetType("text/plain");
         if (cp.Site.GetDate("Diagnostics pause until date") > core.dateTimeNowMockable)
         {
             return("ok, diagnostics paused until " + cp.Site.GetDate("Diagnostics pause until date") + "." + Environment.NewLine + resultList.ToString());
         }
         foreach (var addon in DbBaseModel.createList <AddonModel>(core.cpParent, "(diagnostic>0)"))
         {
             string testResult = core.addon.execute(addon, new BaseClasses.CPUtilsBaseClass.addonExecuteContext());
             if (string.IsNullOrWhiteSpace(testResult))
             {
                 return("ERROR, diagnostic [" + addon.name + "] failed, it returned an empty result." + pauseHint);
             }
             if (testResult.Length < 2)
             {
                 return("ERROR, diagnostic [" + addon.name + "] failed, it returned an invalid result." + pauseHint);
             }
             if (testResult.left(2).ToLower(CultureInfo.InvariantCulture) != "ok")
             {
                 return("ERROR, diagnostic [" + addon.name + "] failed, it returned [" + testResult + "]" + pauseHint);
             }
             resultList.AppendLine(testResult);
         }
         return("ok, all tests passes." + Environment.NewLine + resultList.ToString());
     } catch (Exception ex) {
         cp.Site.ErrorReport(ex);
         return("ERROR, unexpected exception during diagnostics");
     }
 }
        //
        // ====================================================================================================

        public static string get(CPBaseClass cp, PageTemplateModel template)
        {
            try {
                string addonList = "";
                foreach (var rule in DbBaseModel.createList <AddonTemplateRuleModel>(cp, "(templateId=" + template.id + ")"))
                {
                    AddonModel addon = DbBaseModel.create <AddonModel>(cp, rule.addonId);
                    if (addon != null)
                    {
                        addonList += System.Environment.NewLine + "\t\t" + "<IncludeAddon name=\"" + addon.name + "\" guid=\"" + addon.ccguid + "\" />";
                    }
                }
                return(""
                       + System.Environment.NewLine + "\t" + "<Template"
                       + " name=\"" + System.Net.WebUtility.HtmlEncode(template.name) + "\""
                       + " guid=\"" + template.ccguid + "\""
                       + " issecure=\"" + GenericController.getYesNo(template.isSecure) + "\""
                       + " >"
                       + addonList
                       + System.Environment.NewLine + "\t\t" + "<BodyHtml>" + ExportController.tabIndent(cp, ExportController.EncodeCData(template.bodyHTML)) + "</BodyHtml>"
                       + System.Environment.NewLine + "\t" + "</Template>");
            } catch (Exception ex) {
                cp.Site.ErrorReport(ex, "GetAddonNode");
                return(string.Empty);
            }
        }
Пример #3
0
 //
 //====================================================================================================
 /// <summary>
 /// Add a user to a group with an expiration date
 /// </summary>
 /// <param name="core"></param>
 /// <param name="group"></param>
 /// <param name="user"></param>
 /// <param name="dateExpires"></param>
 public static void addUser(CoreController core, GroupModel group, PersonModel user, DateTime dateExpires)
 {
     try {
         var ruleList = DbBaseModel.createList <MemberRuleModel>(core.cpParent, "(MemberID=" + user.id.ToString() + ")and(GroupID=" + group.id.ToString() + ")");
         if (ruleList.Count == 0)
         {
             // -- add new rule
             var rule = DbBaseModel.addDefault <MemberRuleModel>(core.cpParent, Models.Domain.ContentMetadataModel.getDefaultValueDict(core, "groups"));
             rule.groupId     = group.id;
             rule.memberId    = user.id;
             rule.dateExpires = dateExpires;
             rule.save(core.cpParent);
             return;
         }
         // at least one rule found, set expire date, delete the rest
         var ruleFirst = ruleList.First();
         if (ruleFirst.dateExpires != dateExpires)
         {
             ruleFirst.dateExpires = dateExpires;
             ruleFirst.save(core.cpParent);
         }
         if (ruleList.Count > 1)
         {
             foreach (var rule in ruleList)
             {
                 if (!rule.Equals(ruleFirst))
                 {
                     DbBaseModel.delete <MemberRuleModel>(core.cpParent, rule.id);
                 }
             }
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
 }
Пример #4
0
 //
 /// <summary>
 /// addon execute method
 /// </summary>
 /// <param name="cp"></param>
 /// <returns></returns>
 public override object Execute(CPBaseClass cp)
 {
     try {
         //
         // -- optional application object helper for aside cache, etc.
         using (Controllers.ApplicationController ae = new Controllers.ApplicationController(cp)) {
             //
             // -- get an object from the UI (javascript object stringified)
             // -- first inject the fake data to simpulate UI input, then read it
             SampleRequestObject objectValueFromUI = DeserializeObject <SampleRequestObject>(cp.Doc.GetText("objectValueFromUI"));
             //
             // -- create sample data
             List <PersonModel> personList = DbBaseModel.createList <PersonModel>(cp);
             //
             // -- add sample data to a node
             ae.responseNodeList.Add(new Controllers.ResponseNodeClass()
             {
                 dataFor = "nameOfThisDataForUIToRecognize",
                 data    = personList
             });
             return(ae.getResponse());
         }
     } catch (UnauthorizedAccessException) {
         return(Controllers.ApplicationController.getResponseUnauthorized(cp));
     } catch (Exception ex) {
         cp.Site.ErrorReport(ex);
         return(Controllers.ApplicationController.getResponseServerError(cp));
     }
 }
Пример #5
0
 //
 //=================================================================================
 /// <summary>
 /// Get a record lock status. If session.user is the lock holder, returns unlocked
 /// </summary>
 /// <param name="ContentName"></param>
 /// <param name="recordId"></param>
 /// <param name="ReturnMemberID"></param>
 /// <param name="ReturnDateExpires"></param>
 /// <returns></returns>
 public static editLockClass getEditLock(CoreController core, int tableId, int recordId)
 {
     try {
         var table = DbBaseModel.create <TableModel>(core.cpParent, tableId);
         if (table != null)
         {
             //
             // -- get the edit control for this record (not by this person) with the oldest expiration date
             string criteria             = "(createdby<>" + core.session.user.id + ")and" + getAuthoringControlCriteria(getTableRecordKey(table.id, recordId), AuthoringControls.Editing, core.dateTimeNowMockable);
             var    authoringControlList = DbBaseModel.createList <AuthoringControlModel>(core.cpParent, criteria, "dateexpires desc");
             if (authoringControlList.Count > 0)
             {
                 var person = DbBaseModel.create <PersonModel>(core.cpParent, GenericController.encodeInteger(authoringControlList.First().createdBy));
                 return(new editLockClass {
                     isEditLocked = true,
                     editLockExpiresDate = authoringControlList.First().dateExpires,
                     editLockByMemberId = (person == null) ? 0 : person.id,
                     editLockByMemberName = (person == null) ? "" : person.name
                 });
             }
         }
         ;
     } catch (Exception ex) {
         LogController.logError(core, ex);
     }
     return(new editLockClass {
         isEditLocked = false
     });
 }
Пример #6
0
        //
        //====================================================================================================
        /// <summary>
        /// return a visit object for the visitor's last visit before the provided id
        /// </summary>
        /// <param name="core"></param>
        /// <param name="visitId"></param>
        /// <param name="visitorId"></param>
        /// <returns></returns>
        public static VisitModel getLastVisitByVisitor(CPBaseClass cp, int visitId, int visitorId)
        {
            var visitList = DbBaseModel.createList <VisitModel>(cp, "(id<>" + visitId + ")and(VisitorID=" + visitorId + ")", "id desc");

            if (visitList.Count > 0)
            {
                return(visitList.First());
            }
            return(null);
        }
Пример #7
0
        //
        //=================================================================================
        /// <summary>
        /// Set a record locked
        /// </summary>
        /// <param name="ContentName"></param>
        /// <param name="RecordID"></param>
        /// <param name="userId"></param>
        public static void setEditLock(CoreController core, int tableId, int recordId, int userId)
        {
            string contentRecordKey = getTableRecordKey(tableId, recordId);
            var    editLockList     = DbBaseModel.createList <AuthoringControlModel>(core.cpParent, "(contentRecordKey=" + contentRecordKey + ")");
            var    editLock         = (editLockList.Count > 0) ? editLockList.First() : DbBaseModel.addEmpty <AuthoringControlModel>(core.cpParent, userId);

            editLock.contentRecordKey = contentRecordKey;
            editLock.controlType      = (int)AuthoringControls.Editing;
            editLock.createdBy        = userId;
            editLock.dateAdded        = core.dateTimeNowMockable;
            editLock.save(core.cpParent, userId);
        }
Пример #8
0
        //
        //====================================================================================================
        public static Dictionary <string, DomainModel> createDictionary(CPBaseClass cp, string sqlCriteria)
        {
            var result = new Dictionary <string, DomainModel> {
            };

            foreach (var domain in DbBaseModel.createList <DomainModel>(cp, sqlCriteria))
            {
                if (!result.ContainsKey(domain.name.ToLowerInvariant()))
                {
                    result.Add(domain.name.ToLowerInvariant(), domain);
                }
            }
            return(result);
        }
Пример #9
0
 //
 //====================================================================================================
 /// <summary>
 /// drop editRecordId, editarchive, and editblank and all the indexes that reference them
 /// </summary>
 /// <param name="core"></param>
 /// <param name="DataBuildVersion"></param>
 public static void dropLegacyWorkflowField(CoreController core, string fieldName)
 {
     try {
         //
         // verify Db field schema for fields handled internally (fix datatime2(0) problem -- need at least 3 digits for precision)
         var tableList = DbBaseModel.createList <TableModel>(core.cpParent, "(1=1)", "dataSourceId");
         foreach (TableModel table in tableList)
         {
             core.db.deleteTableField(table.name, fieldName, true);
         }
     } catch (Exception ex) {
         LogController.logError(core, ex);
         throw;
     }
 }
Пример #10
0
 //
 //====================================================================================================
 /// <summary>
 /// construct an instance of the class, populating all lists from the DbModels during the load
 /// </summary>
 /// <param name="core"></param>
 public AddonCacheModel(CoreController core)
 {
     foreach (AddonModel addon in DbBaseModel.createList <AddonModel>(core.cpParent, ""))
     {
         add(core, addon);
     }
     foreach (var includeRule in AddonIncludeRuleModel.createList <AddonIncludeRuleModel>(core.cpParent, "", "addonId,includedAddonID"))
     {
         if (!dependencyDictionary.ContainsKey(includeRule.addonId))
         {
             dependencyDictionary.Add(includeRule.addonId, new List <int>());
         }
         dependencyDictionary[includeRule.addonId].Add(includeRule.includedAddonId);
     }
 }
Пример #11
0
 //
 //====================================================================================================
 /// <summary>
 /// install all base51 collection addons
 /// </summary>
 /// <param name="cp"></param>
 /// <returns></returns>
 public override object Execute(Contensive.BaseClasses.CPBaseClass cp)
 {
     try {
         //
         // -- remove any legacy status methods
         var core = ((CPClass)(cp)).core;
         foreach (var addon in DbBaseModel.createList <AddonModel>(core.cpParent, "(name='status')and(ccguid<>'{6444B5C9-36DD-43FF-978C-26650EB2333F}')"))
         {
             addon.name = addon.name + "-blocked";
             addon.save(core.cpParent);
         }
         return("ok");
     } catch (Exception ex) {
         cp.Site.ErrorReport(ex);
         return("ERROR, unexpected exception during OnInstallDiagnostics");
     }
 }
Пример #12
0
 //
 //====================================================================================================
 /// <summary>
 /// getFieldEditorPreference remote method
 /// </summary>
 /// <param name="cp"></param>
 /// <returns></returns>
 public override object Execute(Contensive.BaseClasses.CPBaseClass cp)
 {
     try {
         CoreController core = ((CPClass)cp).core;
         //
         // -- click spam block detected
         {
             string recipientEmailToBlock = core.docProperties.getText(rnEmailBlockRecipientEmail);
             if (!string.IsNullOrEmpty(recipientEmailToBlock))
             {
                 List <PersonModel> recipientList = DbBaseModel.createList <PersonModel>(core.cpParent, "(email=" + DbController.encodeSQLText(recipientEmailToBlock) + ")");
                 foreach (var recipient in recipientList)
                 {
                     recipient.allowBulkEmail = false;
                     recipient.save(cp, 0);
                     //
                     // -- Email spam footer was clicked, clear the AllowBulkEmail field
                     EmailController.addToBlockList(core, recipientEmailToBlock);
                     //
                     // -- log entry to track the result of this email drop
                     int emailDropId = core.docProperties.getInteger(rnEmailBlockRequestDropId);
                     if (emailDropId != 0)
                     {
                         EmailDropModel emailDrop = DbBaseModel.create <EmailDropModel>(cp, emailDropId);
                         if (emailDrop != null)
                         {
                             EmailLogModel log = DbBaseModel.addDefault <EmailLogModel>(core.cpParent);
                             log.name        = "User " + recipient.name + " clicked linked spam block from email drop " + emailDrop.name + " at " + core.doc.profileStartTime.ToString();
                             log.emailDropId = emailDrop.id;
                             log.emailId     = emailDrop.emailId;
                             log.memberId    = recipient.id;
                             log.logType     = EmailLogTypeBlockRequest;
                             log.visitId     = cp.Visit.Id;
                             log.save(cp);
                         }
                     }
                 }
             }
             return(cp.Content.GetCopy("Default Email Blocked Response Page", Resources.defaultEmailBlockedResponsePage));
         }
     } catch (Exception ex) {
         cp.Site.ErrorReport(ex);
     }
     return("");
 }
 //
 //====================================================================================================
 /// <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");
     }
 }
Пример #14
0
        //
        //========================================================================
        //
        //========================================================================
        //
        public static string get(CoreController core)
        {
            string tempGetForm_Downloads = null;

            try {
                //
                string Button = core.docProperties.getText(RequestNameButton);
                if (Button == ButtonCancel)
                {
                    return(core.webServer.redirect("/" + core.appConfig.adminRoute, "Downloads, Cancel Button Pressed"));
                }
                string ButtonListLeft  = "";
                string ButtonListRight = "";
                string Content         = "";
                //
                if (!core.session.isAuthenticatedAdmin())
                {
                    //
                    // Must be a developer
                    //
                    ButtonListLeft  = ButtonCancel;
                    ButtonListRight = "";
                    Content         = Content + AdminUIController.getFormBodyAdminOnly();
                }
                else
                {
                    int    ContentId = core.docProperties.getInteger("ContentID");
                    string Format    = core.docProperties.getText("Format");
                    //
                    // Process Requests
                    //
                    if (!string.IsNullOrEmpty(Button))
                    {
                        int RowCnt = 0;
                        switch (Button)
                        {
                        case ButtonDelete:
                            RowCnt = core.docProperties.getInteger("RowCnt");
                            if (RowCnt > 0)
                            {
                                int RowPtr = 0;
                                for (RowPtr = 0; RowPtr < RowCnt; RowPtr++)
                                {
                                    if (core.docProperties.getBoolean("Row" + RowPtr))
                                    {
                                        DownloadModel.delete <DownloadModel>(core.cpParent, core.docProperties.getInteger("RowID" + RowPtr));
                                    }
                                }
                            }
                            break;
                        }
                    }
                    //
                    // Build Tab0
                    //
                    string RQS      = core.doc.refreshQueryString;
                    int    PageSize = core.docProperties.getInteger(RequestNamePageSize);
                    if (PageSize == 0)
                    {
                        PageSize = 50;
                    }
                    int PageNumber = core.docProperties.getInteger(RequestNamePageNumber);
                    if (PageNumber == 0)
                    {
                        PageNumber = 1;
                    }
                    string AdminURL = "/" + core.appConfig.adminRoute;
                    int    TopCount = PageNumber * PageSize;
                    //
                    const int ColumnCnt = 5;
                    //
                    // Setup Headings
                    //
                    string[] ColCaption = new string[ColumnCnt + 1];
                    string[] ColAlign   = new string[ColumnCnt + 1];
                    string[] ColWidth   = new string[ColumnCnt + 1];
                    string[,] Cells = new string[PageSize + 1, ColumnCnt + 1];
                    int ColumnPtr = 0;
                    //
                    ColCaption[ColumnPtr] = "&nbsp;";
                    ColAlign[ColumnPtr]   = "center";
                    ColWidth[ColumnPtr]   = "10px";
                    ColumnPtr             = ColumnPtr + 1;
                    //
                    ColCaption[ColumnPtr] = "Name";
                    ColAlign[ColumnPtr]   = "left";
                    ColWidth[ColumnPtr]   = "";
                    ColumnPtr             = ColumnPtr + 1;
                    //
                    ColCaption[ColumnPtr] = "For";
                    ColAlign[ColumnPtr]   = "left";
                    ColWidth[ColumnPtr]   = "200px";
                    ColumnPtr             = ColumnPtr + 1;
                    //
                    ColCaption[ColumnPtr] = "Requested";
                    ColAlign[ColumnPtr]   = "left";
                    ColWidth[ColumnPtr]   = "200px";
                    ColumnPtr             = ColumnPtr + 1;
                    //
                    ColCaption[ColumnPtr] = "File";
                    ColAlign[ColumnPtr]   = "Left";
                    ColWidth[ColumnPtr]   = "100px";
                    ColumnPtr             = ColumnPtr + 1;
                    //
                    //   Get Downloads available
                    //
                    int DataRowCount = 0;
                    var downloadList = DbBaseModel.createList <DownloadModel>(core.cpParent, "", "id desc", PageSize, PageNumber);
                    int RowPointer   = 0;
                    if (downloadList.Count == 0)
                    {
                        Cells[0, 1] = "There are no download requests";
                        RowPointer  = 1;
                    }
                    else
                    {
                        RowPointer   = 0;
                        DataRowCount = DbBaseModel.getCount <DownloadModel>(core.cpParent);
                        string LinkPrefix = "<a href=\"" + core.appConfig.cdnFileUrl;
                        string LinkSuffix = "\" target=_blank>Download</a>";
                        foreach (var download in downloadList)
                        {
                            if (RowPointer >= PageSize)
                            {
                                break;
                            }
                            var requestedBy = DbBaseModel.create <PersonModel>(core.cpParent, download.requestedBy);
                            Cells[RowPointer, 0] = HtmlController.checkbox("Row" + RowPointer) + HtmlController.inputHidden("RowID" + RowPointer, download.id);
                            Cells[RowPointer, 1] = download.name;
                            Cells[RowPointer, 2] = (requestedBy == null) ? "unknown" : requestedBy.name;
                            Cells[RowPointer, 3] = download.dateRequested.ToString();
                            if (string.IsNullOrEmpty(download.resultMessage))
                            {
                                Cells[RowPointer, 4] = "\r\n<div id=\"pending" + RowPointer + "\">Pending <img src=\"/ccLib/images/ajax-loader-small.gif\" width=16 height=16></div>";
                            }
                            else if (!string.IsNullOrEmpty(download.filename.filename))
                            {
                                Cells[RowPointer, 4] = "<div id=\"pending" + RowPointer + "\">" + LinkPrefix + download.filename.filename + LinkSuffix + "</div>";
                            }
                            else
                            {
                                Cells[RowPointer, 4] = "<div id=\"pending" + RowPointer + "\">error</div>";
                            }
                            RowPointer = RowPointer + 1;
                        }
                    }
                    StringBuilderLegacyController Tab0 = new StringBuilderLegacyController();
                    Tab0.add(HtmlController.inputHidden("RowCnt", RowPointer));
                    string PreTableCopy  = "";
                    string PostTableCopy = "";
                    string Cell          = AdminUIController.getReport(core, RowPointer, ColCaption, ColAlign, ColWidth, Cells, PageSize, PageNumber, PreTableCopy, PostTableCopy, DataRowCount, "ccPanel");
                    Tab0.add(Cell);
                    Content         = Tab0.text;
                    ButtonListLeft  = ButtonCancel + "," + ButtonRefresh + "," + ButtonDelete;
                    ButtonListRight = "";
                    Content         = Content + HtmlController.inputHidden(rnAdminSourceForm, AdminFormDownloads);
                }
                //
                string Caption     = "Download Manager";
                string Description = ""
                                     + "<p>The Download Manager holds all downloads requested from anywhere on the website. It also provides tools to request downloads from any Content.</p>"
                                     + "<p>To add a new download of any content in Contensive, click Export on the filter tab of the content listing page. To add a new download from a SQL statement, use Custom Reports under Reports on the Navigator.</p>";
                int    ContentPadding = 0;
                string ContentSummary = "";
                tempGetForm_Downloads = AdminUIController.getToolBody(core, Caption, ButtonListLeft, ButtonListRight, true, true, Description, ContentSummary, ContentPadding, Content);
                //
                core.html.addTitle(Caption);
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(tempGetForm_Downloads);
        }
 //
 //====================================================================================================
 /// <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;
     }
 }
Пример #16
0
        //
        //=====================================================================================================
        /// <summary>
        /// the Approved Authoring Control
        /// </summary>
        /// <param name="ContentName"></param>
        /// <param name="RecordID"></param>
        /// <returns></returns>
        public static recordWorkflowStatusClass getWorkflowStatus(CoreController core, string ContentName, int RecordID)
        {
            recordWorkflowStatusClass result = new recordWorkflowStatusClass {
                isEditLocked                 = false,
                editLockByMemberName         = "",
                editLockExpiresDate          = DateTime.MinValue,
                workflowSubmittedMemberName  = "",
                isWorkflowModified           = false,
                workflowModifiedByMemberName = "",
                workflowModifiedDate         = DateTime.MinValue,
                isWorkflowSubmitted          = false,
                workflowSubmittedDate        = DateTime.MinValue,
                isWorkflowApproved           = false,
                workflowApprovedMemberName   = "",
                workflowApprovedDate         = DateTime.MinValue,
                isWorkflowDeleted            = false,
                isWorkflowInserted           = false
            };

            try {
                if (RecordID > 0)
                {
                    //
                    // Get Workflow Locks
                    Models.Domain.ContentMetadataModel CDef = Models.Domain.ContentMetadataModel.createByUniqueName(core, ContentName);
                    if (CDef.id > 0)
                    {
                        var nameDict = new Dictionary <int, string>();
                        foreach (var recordLock in DbBaseModel.createList <AuthoringControlModel>(core.cpParent, getAuthoringControlCriteria(core, ContentName, RecordID)))
                        {
                            int createdBy = GenericController.encodeInteger(recordLock.createdBy);
                            switch ((AuthoringControls)recordLock.controlType)
                            {
                            case AuthoringControls.Editing:
                                if (!result.isEditLocked)
                                {
                                    result.isEditLocked        = true;
                                    result.editLockExpiresDate = recordLock.dateAdded;
                                    if (nameDict.ContainsKey(createdBy))
                                    {
                                        result.editLockByMemberName = nameDict[createdBy];
                                    }
                                    else
                                    {
                                        result.editLockByMemberName = DbBaseModel.getRecordName <PersonModel>(core.cpParent, createdBy);
                                        nameDict.Add(createdBy, result.workflowModifiedByMemberName);
                                    }
                                }
                                break;

                            case AuthoringControls.Modified:
                                if (!result.isWorkflowModified)
                                {
                                    result.isWorkflowModified    = true;
                                    result.workflowSubmittedDate = recordLock.dateAdded;
                                    if (nameDict.ContainsKey(createdBy))
                                    {
                                        result.workflowModifiedByMemberName = nameDict[createdBy];
                                    }
                                    else
                                    {
                                        result.workflowModifiedByMemberName = DbBaseModel.getRecordName <PersonModel>(core.cpParent, createdBy);
                                        nameDict.Add(createdBy, result.workflowModifiedByMemberName);
                                    }
                                }
                                break;

                            case AuthoringControls.Submitted:
                                if (!result.isWorkflowSubmitted)
                                {
                                    result.isWorkflowSubmitted  = true;
                                    result.workflowModifiedDate = recordLock.dateAdded;
                                    if (nameDict.ContainsKey(createdBy))
                                    {
                                        result.workflowSubmittedMemberName = nameDict[createdBy];
                                    }
                                    else
                                    {
                                        result.workflowSubmittedMemberName = DbBaseModel.getRecordName <PersonModel>(core.cpParent, createdBy);
                                        nameDict.Add(createdBy, result.workflowSubmittedMemberName);
                                    }
                                }
                                break;

                            case AuthoringControls.Approved:
                                if (!result.isWorkflowApproved)
                                {
                                    result.isWorkflowApproved   = true;
                                    result.workflowApprovedDate = encodeDate(recordLock.dateAdded);
                                    if (nameDict.ContainsKey(createdBy))
                                    {
                                        result.workflowApprovedMemberName = nameDict[createdBy];
                                    }
                                    else
                                    {
                                        result.workflowApprovedMemberName = DbBaseModel.getRecordName <PersonModel>(core.cpParent, createdBy);
                                        nameDict.Add(createdBy, result.workflowSubmittedMemberName);
                                    }
                                }
                                break;

                            default:
                                break;
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
            return(result);
        }
Пример #17
0
 //
 //====================================================================================================
 /// <summary>
 /// Iterate through all apps, find addosn that need to run and add them to the task queue
 /// </summary>
 private void scheduleTasks(CoreController core)
 {
     try {
         //
         // -- run tasks for each app
         foreach (var appKvp in core.serverConfig.apps)
         {
             if (appKvp.Value.enabled && appKvp.Value.appStatus.Equals(AppConfigModel.AppStatusEnum.ok))
             {
                 LogController.logTrace(core, "scheduleTasks, app=[" + appKvp.Value.name + "]");
                 using (CPClass cpApp = new CPClass(appKvp.Value.name)) {
                     //
                     // Execute Processes
                     try {
                         string sqlAddonsCriteria = ""
                                                    + "(active<>0)"
                                                    + " and(name<>'')"
                                                    + " and("
                                                    + "  ((ProcessRunOnce is not null)and(ProcessRunOnce<>0))"
                                                    + "  or((ProcessInterval is not null)and(ProcessInterval<>0)and(ProcessNextRun is null))"
                                                    + "  or(ProcessNextRun<" + DbController.encodeSQLDate(core.dateTimeNowMockable) + ")"
                                                    + " )";
                         var addonList = DbBaseModel.createList <AddonModel>(cpApp, sqlAddonsCriteria);
                         foreach (var addon in addonList)
                         {
                             //
                             int addonProcessInterval = encodeInteger(addon.processInterval);
                             if (addon.processRunOnce)
                             {
                                 //
                                 // -- run once checked
                                 addon.processNextRun = core.dateTimeNowMockable;
                                 addon.processRunOnce = false;
                             }
                             else if ((addon.processNextRun == null) && (addonProcessInterval > 0))
                             {
                                 //
                                 // -- processInterval set but everything else blank )
                                 addon.processNextRun = core.dateTimeNowMockable.AddMinutes(addonProcessInterval);
                             }
                             if (addon.processNextRun <= core.dateTimeNowMockable)
                             {
                                 //
                                 LogController.logInfo(cpApp.core, "scheduleTasks, addon [" + addon.name + "], add task, addonProcessRunOnce [" + addon.processRunOnce + "], addonProcessNextRun [" + addon.processNextRun + "]");
                                 //
                                 // -- add task to queue for runner
                                 addTaskToQueue(cpApp.core, new TaskModel.CmdDetailClass {
                                     addonId   = addon.id,
                                     addonName = addon.name,
                                     args      = GenericController.convertAddonArgumentstoDocPropertiesList(cpApp.core, addon.argumentList)
                                 }, true);
                                 if (addonProcessInterval > 0)
                                 {
                                     //
                                     // -- interval set, update the next run
                                     addon.processNextRun = core.dateTimeNowMockable.AddMinutes(addonProcessInterval);
                                 }
                                 else
                                 {
                                     //
                                     // -- no interval, no next run
                                     addon.processNextRun = null;
                                 }
                             }
                             addon.save(cpApp);
                         }
                     } catch (Exception ex) {
                         LogController.logTrace(cpApp.core, "scheduleTasks, exception [" + ex + "]");
                         LogController.logError(cpApp.core, ex);
                     }
                 }
             }
         }
     } catch (Exception ex) {
         LogController.logTrace(core, "scheduleTasks, exeception [" + ex + "]");
         LogController.logError(core, ex);
     }
 }
Пример #18
0
        //
        //===================================================================================================
        /// <summary>
        /// Create a list of routes
        /// </summary>
        /// <param name="core"></param>
        /// <returns></returns>
        public static RouteMapModel create(CoreController core)
        {
            RouteMapModel result = new RouteMapModel();

            try {
                result = getCache(core);
                if (result == null)
                {
                    result = new RouteMapModel {
                        dateCreated     = core.dateTimeNowMockable,
                        routeDictionary = new Dictionary <string, RouteClass>()
                    };
                    string physicalFile = "~/" + core.siteProperties.serverPageDefault;
                    //
                    // -- admin route
                    string adminRoute = GenericController.normalizeRoute(core.appConfig.adminRoute);
                    if (!string.IsNullOrWhiteSpace(adminRoute))
                    {
                        result.routeDictionary.Add(adminRoute, new RouteClass {
                            physicalRoute = physicalFile,
                            virtualRoute  = adminRoute,
                            routeType     = RouteTypeEnum.admin
                        });
                    }
                    //
                    // -- remote methods
                    foreach (var remoteMethod in core.addonCache.getRemoteMethodAddonList())
                    {
                        string route = GenericController.normalizeRoute(remoteMethod.name);
                        if (!string.IsNullOrWhiteSpace(route))
                        {
                            if (result.routeDictionary.ContainsKey(route))
                            {
                                LogController.logWarn(core, new GenericException("Route [" + route + "] cannot be added because it is a matches the Admin Route or another Remote Method."));
                            }
                            else
                            {
                                result.routeDictionary.Add(route, new RouteClass {
                                    physicalRoute       = physicalFile,
                                    virtualRoute        = route,
                                    routeType           = RouteTypeEnum.remoteMethod,
                                    remoteMethodAddonId = remoteMethod.id
                                });
                            }
                        }
                    }
                    //
                    // -- link forwards
                    foreach (var linkForward in DbBaseModel.createList <LinkForwardModel>(core.cpParent, "name Is Not null"))
                    {
                        string route = GenericController.normalizeRoute(linkForward.sourceLink);
                        if (!string.IsNullOrEmpty(route))
                        {
                            if (result.routeDictionary.ContainsKey(route))
                            {
                                LogController.logError(core, new GenericException("Link Forward Route [" + route + "] cannot be added because it is a matches the Admin Route, a Remote Method or another Link Forward."));
                            }
                            else
                            {
                                result.routeDictionary.Add(route, new RouteClass {
                                    physicalRoute = physicalFile,
                                    virtualRoute  = route,
                                    routeType     = RouteTypeEnum.linkForward,
                                    linkForwardId = linkForward.id
                                });
                            }
                        }
                    }
                    //
                    // -- link aliases
                    foreach (var linkAlias in DbBaseModel.createList <LinkAliasModel>(core.cpParent, "name Is Not null"))
                    {
                        string route = GenericController.normalizeRoute(linkAlias.name);
                        if (!string.IsNullOrEmpty(route))
                        {
                            if (result.routeDictionary.ContainsKey(route))
                            {
                                LogController.logError(core, new GenericException("Link Alias route [" + route + "] cannot be added because it is a matches the Admin Route, a Remote Method, a Link Forward o another Link Alias."));
                            }
                            else
                            {
                                result.routeDictionary.Add(route, new RouteClass {
                                    physicalRoute = physicalFile,
                                    virtualRoute  = route,
                                    routeType     = RouteTypeEnum.linkAlias,
                                    linkAliasId   = linkAlias.id
                                });
                            }
                        }
                    }
                    setCache(core, result);
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
            }
            return(result);
        }
Пример #19
0
 //
 //====================================================================================================
 /// <summary>
 /// Iterate through all apps and execute tasks in processes
 /// </summary>
 private void runTasks(CoreController serverCore)
 {
     try {
         Stopwatch swProcess = new Stopwatch();
         swProcess.Start();
         //
         foreach (var appKVP in serverCore.serverConfig.apps)
         {
             if (appKVP.Value.enabled && appKVP.Value.appStatus.Equals(AppConfigModel.AppStatusEnum.ok))
             {
                 //
                 // query tasks that need to be run
                 //
                 using (CPClass cpApp = new CPClass(appKVP.Value.name)) {
                     //
                     LogController.logTrace(cpApp.core, "runTasks, appname=[" + appKVP.Value.name + "]");
                     //
                     try {
                         int recordsAffected     = 0;
                         int sequentialTaskCount = 0;
                         do
                         {
                             //
                             // for now run an sql to get processes, eventually cache in variant cache
                             string sqlCmdRunner = DbController.encodeSQLText(runnerGuid);
                             string sql          = ""
                                                   + Environment.NewLine + " BEGIN TRANSACTION"
                                                   + Environment.NewLine + " update cctasks set cmdRunner=" + sqlCmdRunner + " where id in (select top 1 id from cctasks where (cmdRunner is null)and(datestarted is null) order by id)"
                                                   + Environment.NewLine + " COMMIT TRANSACTION";
                             cpApp.core.db.executeNonQuery(sql, ref recordsAffected);
                             if (recordsAffected == 0)
                             {
                                 //
                                 // -- no tasks found
                                 LogController.logTrace(cpApp.core, "runTasks, appname=[" + appKVP.Value.name + "], no tasks");
                             }
                             else
                             {
                                 //
                                 // -- select task to get timeout
                                 List <TaskModel> taskList = DbBaseModel.createList <TaskModel>(cpApp, "(cmdRunner=" + sqlCmdRunner + ")");
                                 if (taskList.Count > 0)
                                 {
                                     TaskModel task   = taskList.First();
                                     Stopwatch swTask = new Stopwatch();
                                     swTask.Start();
                                     //
                                     // -- track multiple executions
                                     if (sequentialTaskCount > 0)
                                     {
                                         LogController.logTrace(cpApp.core, "runTasks, appname=[" + appKVP.Value.name + "], multiple tasks run in a single cycle, sequentialTaskCount [" + sequentialTaskCount + "]");
                                     }
                                     //
                                     // -- two execution methods, 1) run task here, 2) start process and wait (so bad addon code does not memory link)
                                     bool   runInServiceProcess = cpApp.Site.GetBoolean("Run tasks in service process");
                                     string cliPathFilename     = cpApp.core.programFiles.localAbsRootPath + "cc.exe";
                                     if (!runInServiceProcess && !System.IO.File.Exists(cliPathFilename))
                                     {
                                         runInServiceProcess = true;
                                         LogController.logError(cpApp.core, "TaskRunner cannot run out of process because command line program cc.exe not found in program files folder [" + cpApp.core.programFiles.localAbsRootPath + "]");
                                     }
                                     if (runInServiceProcess)
                                     {
                                         //
                                         // -- execute here
                                         executeRunnerTasks(cpApp.Site.Name, runnerGuid);
                                     }
                                     else
                                     {
                                         //
                                         // -- execute in new  process
                                         string filename         = "cc.exe";
                                         string workingDirectory = cpApp.core.programFiles.localAbsRootPath;
                                         string arguments        = "-a \"" + appKVP.Value.name + "\" --runTask \"" + runnerGuid + "\"";
                                         LogController.logInfo(cpApp.core, "TaskRunner starting process to execute task for filename [" + filename + "], workingDirectory [" + workingDirectory + "], arguments [" + arguments + "]");
                                         //
                                         // todo manage multiple executing processes
                                         using (Process process = new Process()) {
                                             process.StartInfo.CreateNoWindow   = true;
                                             process.StartInfo.FileName         = filename;
                                             process.StartInfo.WorkingDirectory = workingDirectory;
                                             process.StartInfo.Arguments        = arguments;
                                             process.StartInfo.WindowStyle      = ProcessWindowStyle.Hidden;
                                             process.Start();
                                             //
                                             // -- determine how long to wait
                                             int timeoutMsec = 0;
                                             if ((int.MaxValue / 1000) >= task.timeout)
                                             {
                                                 // minus 1 because maxvalue causes wait for ever
                                                 timeoutMsec = int.MaxValue - 1;
                                             }
                                             else
                                             {
                                                 timeoutMsec = task.timeout * 1000;
                                             }
                                             if (timeoutMsec == 0)
                                             {
                                                 //
                                                 // --no timeout, just run the task
                                                 process.WaitForExit();
                                             }
                                             else
                                             {
                                                 process.WaitForExit(timeoutMsec);
                                             }
                                             if (!process.HasExited)
                                             {
                                                 LogController.logError(cpApp.core, "TaskRunner Killing process, process timed out, app [" + appKVP.Value.name + "].");
                                                 process.Kill();
                                                 process.WaitForExit();
                                             }
                                             process.Close();
                                         }
                                     }
                                     LogController.logTrace(cpApp.core, "runTasks, app [" + appKVP.Value.name + "], task complete (" + swTask.ElapsedMilliseconds + "ms)");
                                 }
                             }
                             sequentialTaskCount++;
                         } while (recordsAffected > 0);
                     } catch (Exception ex) {
                         LogController.logError(cpApp.core, ex);
                     }
                 }
             }
         }
         //
         // -- trace log without core
     } catch (Exception ex) {
         LogController.logError(serverCore, ex);
     }
 }
Пример #20
0
 //
 //====================================================================================================
 /// <summary>
 /// run as single task from the cctasks table of an app, makred with a runnerGuid
 /// called from runTasks or from the cli in a different process
 /// when the task starts,
 /// saves the addons output to the task.filename
 /// </summary>
 public static void executeRunnerTasks(string appName, string runnerGuid)
 {
     try {
         using (var cp = new Contensive.Processor.CPClass(appName)) {
             try {
                 foreach (var task in DbBaseModel.createList <TaskModel>(cp, "(cmdRunner=" + DbController.encodeSQLText(runnerGuid) + ")and(datestarted is null)", "id"))
                 {
                     //
                     // -- trace log without core
                     LogController.log(cp.core, "taskRunner.runTask, runTask, task [" + task.name + "], cmdDetail [" + task.cmdDetail + "]", BaseClasses.CPLogBaseClass.LogLevel.Info);
                     //
                     DateTime dateStarted = cp.core.dateTimeNowMockable;
                     var      cmdDetail   = DeserializeObject <TaskModel.CmdDetailClass>(task.cmdDetail);
                     if (cmdDetail != null)
                     {
                         var addon = DbBaseModel.create <AddonModel>(cp, cmdDetail.addonId);
                         if (addon != null)
                         {
                             var context = new BaseClasses.CPUtilsBaseClass.addonExecuteContext {
                                 backgroundProcess     = true,
                                 addonType             = BaseClasses.CPUtilsBaseClass.addonContext.ContextSimple,
                                 argumentKeyValuePairs = cmdDetail.args,
                                 errorContextMessage   = "running task, addon [" + cmdDetail.addonId + "]"
                             };
                             string result = cp.core.addon.execute(addon, context);
                             if (!string.IsNullOrEmpty(result))
                             {
                                 //
                                 LogController.logTrace(cp.core, "executeRunnerTasks, result not empty, downloadId [" + task.resultDownloadId + "], result first 100 [" + (result.Length > 100 ? result.Substring(0, 100) : result) + "]");
                                 //
                                 // -- save output
                                 if (task.resultDownloadId > 0)
                                 {
                                     var download = DbBaseModel.create <DownloadModel>(cp, task.resultDownloadId);
                                     if (download != null)
                                     {
                                         //
                                         LogController.logTrace(cp.core, "executeRunnerTasks, download found, [id" + download.id + ", name:" + download.name + ", filename:" + download.filename + "]");
                                         //
                                         if (string.IsNullOrEmpty(download.name))
                                         {
                                             download.name = "Download";
                                         }
                                         download.resultMessage    = "Completed";
                                         download.filename.content = result;
                                         download.dateRequested    = dateStarted;
                                         download.dateCompleted    = cp.core.dateTimeNowMockable;
                                         download.save(cp);
                                     }
                                 }
                             }
                         }
                     }
                     task.dateCompleted = cp.core.dateTimeNowMockable;
                     DbBaseModel.delete <TaskModel>(cp, task.id);
                     //
                     // -- info log the task running - so info state will log for memory leaks
                     LogController.log(cp.core, "TaskRunner exit, task [" + task.name + "], cmdDetail [" + task.cmdDetail + "]", BaseClasses.CPLogBaseClass.LogLevel.Info);
                 }
             } catch (Exception exInner) {
                 LogController.log(cp.core, "TaskRunner exception, ex [" + exInner.ToString() + "]", BaseClasses.CPLogBaseClass.LogLevel.Error);
                 throw;
             }
         }
     } catch (Exception ex) {
         Console.WriteLine("Error: [" + ex + "]");
     }
 }
Пример #21
0
 //
 //====================================================================================================
 //
 //   Creates the child page list used by PageContent
 //
 //   RequestedListName is the name of the ChildList (ActiveContent Child Page List)
 //       ----- New
 //       {CHILDPAGELIST} = the listname for the orphan list at the bottom of all page content, same as "", "ORPHAN", "NONE"
 //       RequestedListName = "", same as "ORPHAN", same as "NONE"
 //           prints orphan list (child pages that have not printed so far (orphan list))
 //       AllowChildListDisplay - if false, no Child Page List is displayed, but authoring tags are still there
 //       Changed to friend, not public
 //       ----- Old
 //       "NONE" returns child pages with no RequestedListName
 //       "" same as "NONE"
 //       "ORPHAN" returns all child pages that have not been printed on this page
 //           - uses ChildPageListTracking to track what has been seen
 //=============================================================================
 //
 public static string getChildPageList(CoreController core, string requestedListName, string contentName, int parentPageID, bool allowChildListDisplay, bool ArchivePages = false)
 {
     try {
         if (string.IsNullOrEmpty(contentName))
         {
             contentName = PageContentModel.tableMetadata.contentName;
         }
         string UcaseRequestedListName = toUCase(requestedListName);
         if ((UcaseRequestedListName == "NONE") || (UcaseRequestedListName == "ORPHAN") || (UcaseRequestedListName == "{CHILDPAGELIST}"))
         {
             UcaseRequestedListName = "";
         }
         string archiveLink = core.webServer.requestPathPage;
         archiveLink = convertLinkToShortLink(archiveLink, core.webServer.requestDomain, core.appConfig.cdnFileUrl);
         archiveLink = encodeVirtualPath(archiveLink, core.appConfig.cdnFileUrl, appRootPath, core.webServer.requestDomain);
         string sqlCriteria = "(parentId=" + parentPageID + ")" + ((string.IsNullOrWhiteSpace(UcaseRequestedListName)) ? "" : "and(parentListName=" + DbController.encodeSQLText(UcaseRequestedListName) + ")");
         List <PageContentModel> childPageList = DbBaseModel.createList <PageContentModel>(core.cpParent, sqlCriteria, "sortOrder");
         var  inactiveList   = new StringBuilder();
         var  activeList     = new StringBuilder();
         bool isAuthoring    = core.session.isEditing(contentName);
         int  ChildListCount = 0;
         if (childPageList.Count > 0)
         {
             string currentPageChildPageIdList = core.cpParent.Doc.GetText("Current Page Child PageId List", "0");
             string testPageIdList             = "," + currentPageChildPageIdList + ",";
             foreach (PageContentModel childPage in childPageList)
             {
                 if (!testPageIdList.Contains("," + childPage.id + ","))
                 {
                     currentPageChildPageIdList += "," + childPage.id;
                 }
                 string PageLink         = PageContentController.getPageLink(core, childPage.id, "", true, false);
                 string pageMenuHeadline = childPage.menuHeadline;
                 if (string.IsNullOrEmpty(pageMenuHeadline))
                 {
                     pageMenuHeadline = childPage.name.Trim(' ');
                     if (string.IsNullOrEmpty(pageMenuHeadline))
                     {
                         pageMenuHeadline = "Related Page";
                     }
                 }
                 string pageEditLink = "";
                 if (core.session.isEditing(contentName))
                 {
                     pageEditLink = AdminUIController.getRecordEditAndCutAnchorTag(core, contentName, childPage.id, true, childPage.name);
                 }
                 //
                 string link = PageLink;
                 if (ArchivePages)
                 {
                     link = GenericController.modifyLinkQuery(archiveLink, rnPageId, encodeText(childPage.id), true);
                 }
                 bool blockContentComposite = false;
                 if (childPage.blockContent || childPage.blockPage)
                 {
                     blockContentComposite = !PageContentController.allowThroughPageBlock(core, childPage.id);
                 }
                 string LinkedText = GenericController.getLinkedText("<a href=\"" + HtmlController.encodeHtml(link) + "\">", pageMenuHeadline);
                 if ((string.IsNullOrEmpty(UcaseRequestedListName)) && (childPage.parentListName != "") && (!isAuthoring))
                 {
                     //
                     // ----- Requested orphan list, and this record is in a named list, and not editing, do not display
                     //
                 }
                 else if ((string.IsNullOrEmpty(UcaseRequestedListName)) && (childPage.parentListName != ""))
                 {
                     //
                     // -- child page has a parentListName but this request does not
                     if (!core.doc.pageController.childPageIdsListed.Contains(childPage.id))
                     {
                         //
                         // -- child page has not yet displays, if editing show it as an orphan page
                         if (isAuthoring)
                         {
                             inactiveList.Append("\r<li name=\"page" + childPage.id + "\" name=\"page" + childPage.id + "\"  id=\"page" + childPage.id + "\" class=\"ccEditWrapper ccListItemNoBullet\">");
                             inactiveList.Append(pageEditLink);
                             inactiveList.Append("[from missing child page list '" + childPage.parentListName + "': " + LinkedText + "]");
                             inactiveList.Append("</li>");
                         }
                     }
                 }
                 else if ((string.IsNullOrEmpty(UcaseRequestedListName)) && (!allowChildListDisplay) && (!isAuthoring))
                 {
                     //
                     // ----- Requested orphan List, Not AllowChildListDisplay, not Authoring, do not display
                     //
                 }
                 else if ((!string.IsNullOrEmpty(UcaseRequestedListName)) && (UcaseRequestedListName != GenericController.toUCase(childPage.parentListName)))
                 {
                     //
                     // ----- requested named list and wrong RequestedListName, do not display
                     //
                 }
                 else if (!childPage.allowInChildLists)
                 {
                     //
                     // ----- Allow in Child Page Lists is false, display hint to authors
                     //
                     if (isAuthoring)
                     {
                         inactiveList.Append("\r<li name=\"page" + childPage.id + "\"  id=\"page" + childPage.id + "\" class=\"ccEditWrapper ccListItemNoBullet\">");
                         inactiveList.Append(pageEditLink);
                         inactiveList.Append("[Hidden (Allow in Child Lists is not checked): " + LinkedText + "]");
                         inactiveList.Append("</li>");
                     }
                 }
                 else if (!childPage.active)
                 {
                     //
                     // ----- Not active record, display hint if authoring
                     //
                     if (isAuthoring)
                     {
                         inactiveList.Append("\r<li name=\"page" + childPage.id + "\"  id=\"page" + childPage.id + "\" class=\"ccEditWrapper ccListItemNoBullet\">");
                         inactiveList.Append(pageEditLink);
                         inactiveList.Append("[Hidden (Inactive): " + LinkedText + "]");
                         inactiveList.Append("</li>");
                     }
                 }
                 else if ((childPage.pubDate != DateTime.MinValue) && (childPage.pubDate > core.doc.profileStartTime))
                 {
                     //
                     // ----- Child page has not been published
                     //
                     if (isAuthoring)
                     {
                         inactiveList.Append("\r<li name=\"page" + childPage.id + "\"  id=\"page" + childPage.id + "\" class=\"ccEditWrapper ccListItemNoBullet\">");
                         inactiveList.Append(pageEditLink);
                         inactiveList.Append("[Hidden (To be published " + childPage.pubDate + "): " + LinkedText + "]");
                         inactiveList.Append("</li>");
                     }
                 }
                 else if ((childPage.dateExpires != DateTime.MinValue) && (childPage.dateExpires < core.doc.profileStartTime))
                 {
                     //
                     // ----- Child page has expired
                     //
                     if (isAuthoring)
                     {
                         inactiveList.Append("\r<li name=\"page" + childPage.id + "\"  id=\"page" + childPage.id + "\" class=\"ccEditWrapper ccListItemNoBullet\">");
                         inactiveList.Append(pageEditLink);
                         inactiveList.Append("[Hidden (Expired " + childPage.dateExpires + "): " + LinkedText + "]");
                         inactiveList.Append("</li>");
                     }
                 }
                 else
                 {
                     //
                     // ----- display list (and authoring links)
                     //
                     if (isAuthoring)
                     {
                         activeList.Append("\r<li name=\"page" + childPage.id + "\"  id=\"page" + childPage.id + "\" class=\"ccEditWrapper ccListItem allowSort\">");
                         if (!string.IsNullOrEmpty(pageEditLink))
                         {
                             activeList.Append(HtmlController.div(iconGrip, "ccListItemDragHandle") + pageEditLink + "&nbsp;");
                         }
                         activeList.Append(LinkedText);
                         //
                         // include authoring mark for content block
                         //
                         if (childPage.blockContent)
                         {
                             activeList.Append("&nbsp;[Content Blocked]");
                         }
                         if (childPage.blockPage)
                         {
                             activeList.Append("&nbsp;[Page Blocked]");
                         }
                     }
                     else
                     {
                         activeList.Append("\r<li name=\"page" + childPage.id + "\"  id=\"page" + childPage.id + "\" class=\"ccListItem allowSort\">");
                         activeList.Append(LinkedText);
                     }
                     //
                     // include overview
                     // if AllowBrief is false, BriefFilename is not loaded
                     //
                     if ((childPage.briefFilename != "") && (childPage.allowBrief))
                     {
                         string Brief = encodeText(core.cdnFiles.readFileText(childPage.briefFilename)).Trim(' ');
                         if (!string.IsNullOrEmpty(Brief))
                         {
                             activeList.Append("<div class=\"ccListCopy\">" + Brief + "</div>");
                         }
                     }
                     activeList.Append("</li>");
                     //
                     // -- add child page to childPagesListed list
                     if (!core.doc.pageController.childPageIdsListed.Contains(childPage.id))
                     {
                         core.doc.pageController.childPageIdsListed.Add(childPage.id);
                     }
                     ChildListCount = ChildListCount + 1;
                 }
             }
             if (!string.IsNullOrWhiteSpace(currentPageChildPageIdList))
             {
                 core.cpParent.Doc.SetProperty("Current Page Child PageId List", currentPageChildPageIdList);
             }
         }
         //
         // ----- Add Link
         //
         if (!ArchivePages && isAuthoring)
         {
             foreach (var AddLink in AdminUIController.getRecordAddAnchorTag(core, contentName, "parentid=" + parentPageID + ",ParentListName=" + UcaseRequestedListName, true))
             {
                 if (!string.IsNullOrEmpty(AddLink))
                 {
                     inactiveList.Append("\r<li class=\"ccEditWrapper ccListItemNoBullet\">" + AddLink + "</LI>");
                 }
             }
         }
         //
         // ----- If there is a list, add the list start and list end
         //
         string result = activeList.ToString() + inactiveList.ToString();
         if (!string.IsNullOrEmpty(result))
         {
             result = "\r<ul id=\"childPageList_" + parentPageID + "_" + requestedListName + "\" class=\"ccChildList\">" + result + "\r</ul>";
         }
         if ((!string.IsNullOrEmpty(UcaseRequestedListName)) && (ChildListCount == 0) && isAuthoring)
         {
             result = "[Child Page List with no pages]</p><p>" + result;
         }
         return(result);
     } catch (Exception ex) {
         LogController.logError(core, ex);
         return(string.Empty);
     }
 }
Пример #22
0
        //
        // ====================================================================================================
        /// <summary>
        /// create the colleciton zip file and return the pathFilename in the Cdn
        /// </summary>
        /// <param name="cp"></param>
        /// <param name="collectionId"></param>
        /// <returns></returns>
        public static string createCollectionZip_returnCdnPathFilename(CPBaseClass cp, AddonCollectionModel collection)
        {
            string cdnExportZip_Filename = "";

            try {
                if ((collection == null))
                {
                    //
                    // -- exit with error
                    cp.UserError.Add("The collection you selected could not be found");
                    return(string.Empty);
                }
                using (CPCSBaseClass CS = cp.CSNew()) {
                    CS.OpenRecord("Add-on Collections", collection.id);
                    if (!CS.OK())
                    {
                        //
                        // -- exit with error
                        cp.UserError.Add("The collection you selected could not be found");
                        return(string.Empty);
                    }
                    string collectionXml  = "<?xml version=\"1.0\" encoding=\"windows-1252\"?>";
                    string CollectionGuid = CS.GetText("ccGuid");
                    if (CollectionGuid == "")
                    {
                        CollectionGuid = cp.Utils.CreateGuid();
                        CS.SetField("ccGuid", CollectionGuid);
                    }
                    string onInstallAddonGuid = "";
                    if ((CS.FieldOK("onInstallAddonId")))
                    {
                        int onInstallAddonId = CS.GetInteger("onInstallAddonId");
                        if ((onInstallAddonId > 0))
                        {
                            AddonModel addon = AddonModel.create <AddonModel>(cp, onInstallAddonId);
                            if ((addon != null))
                            {
                                onInstallAddonGuid = addon.ccguid;
                            }
                        }
                    }
                    string CollectionName = CS.GetText("name");
                    collectionXml        += System.Environment.NewLine + "<Collection";
                    collectionXml        += " name=\"" + CollectionName + "\"";
                    collectionXml        += " guid=\"" + CollectionGuid + "\"";
                    collectionXml        += " system=\"" + GenericController.getYesNo(CS.GetBoolean("system")) + "\"";
                    collectionXml        += " updatable=\"" + GenericController.getYesNo(CS.GetBoolean("updatable")) + "\"";
                    collectionXml        += " blockNavigatorNode=\"" + GenericController.getYesNo(CS.GetBoolean("blockNavigatorNode")) + "\"";
                    collectionXml        += " onInstallAddonGuid=\"" + onInstallAddonGuid + "\"";
                    collectionXml        += ">";
                    cdnExportZip_Filename = encodeFilename(cp, CollectionName + ".zip");
                    List <string> tempPathFileList = new List <string>();
                    string        tempExportPath   = "CollectionExport" + Guid.NewGuid().ToString() + @"\";
                    //
                    // --resource executable files
                    string        wwwFileList          = CS.GetText("wwwFileList");
                    string        ContentFileList      = CS.GetText("ContentFileList");
                    List <string> execFileList         = ExportResourceListController.getResourceFileList(cp, CS.GetText("execFileList"), CollectionGuid);
                    string        execResourceNodeList = ExportResourceListController.getResourceNodeList(cp, execFileList, CollectionGuid, tempPathFileList, tempExportPath);
                    //
                    // helpLink
                    //
                    if (CS.FieldOK("HelpLink"))
                    {
                        collectionXml += System.Environment.NewLine + "\t" + "<HelpLink>" + System.Net.WebUtility.HtmlEncode(CS.GetText("HelpLink")) + "</HelpLink>";
                    }
                    //
                    // Help
                    //
                    collectionXml += System.Environment.NewLine + "\t" + "<Help>" + System.Net.WebUtility.HtmlEncode(CS.GetText("Help")) + "</Help>";
                    //
                    // Addons
                    //
                    string IncludeSharedStyleGuidList = "";
                    string IncludeModuleGuidList      = "";
                    foreach (var addon in DbBaseModel.createList <AddonModel>(cp, "collectionid=" + collection.id))
                    {
                        //
                        // -- style sheet is in the wwwroot
                        if (!string.IsNullOrEmpty(addon.stylesLinkHref))
                        {
                            string filename = addon.stylesLinkHref.Replace("/", "\\");
                            if (filename.Substring(0, 1).Equals(@"\"))
                            {
                                filename = filename.Substring(1);
                            }
                            if (!cp.WwwFiles.FileExists(filename))
                            {
                                cp.WwwFiles.Save(filename, @"/* css file created as exported for addon [" + addon.name + "], collection [" + collection.name + "] in site [" + cp.Site.Name + "] */");
                            }
                            wwwFileList += System.Environment.NewLine + addon.stylesLinkHref;
                        }
                        //
                        // -- js is in the wwwroot
                        if (!string.IsNullOrEmpty(addon.jsHeadScriptSrc))
                        {
                            string filename = addon.jsHeadScriptSrc.Replace("/", "\\");
                            if (filename.Substring(0, 1).Equals(@"\"))
                            {
                                filename = filename.Substring(1);
                            }
                            if (!cp.WwwFiles.FileExists(filename))
                            {
                                cp.WwwFiles.Save(filename, @"// javascript file created as exported for addon [" + addon.name + "], collection [" + collection.name + "] in site [" + cp.Site.Name + "]");
                            }
                            wwwFileList += System.Environment.NewLine + addon.jsHeadScriptSrc;
                        }
                        collectionXml += ExportAddonController.getAddonNode(cp, addon.id, ref IncludeModuleGuidList, ref IncludeSharedStyleGuidList);
                    }
                    //
                    // Layouts
                    foreach (var layout in DbBaseModel.createList <LayoutModel>(cp, "(installedByCollectionId=" + collection.id + ")"))
                    {
                        collectionXml += ExportLayoutController.get(cp, layout);
                    }
                    //
                    // Templates
                    foreach (var template in DbBaseModel.createList <PageTemplateModel>(cp, "(collectionId=" + collection.id + ")"))
                    {
                        collectionXml += ExportTemplateController.get(cp, template);
                    }
                    //
                    // Data Records
                    string DataRecordList = CS.GetText("DataRecordList");
                    collectionXml += ExportDataRecordController.getNodeList(cp, DataRecordList, tempPathFileList, tempExportPath);
                    //
                    // CDef
                    foreach (Contensive.Models.Db.ContentModel content in createListFromCollection(cp, collection.id))
                    {
                        if ((string.IsNullOrEmpty(content.ccguid)))
                        {
                            content.ccguid = cp.Utils.CreateGuid();
                            content.save(cp);
                        }
                        XmlController xmlTool = new XmlController(cp);
                        string        Node    = xmlTool.GetXMLContentDefinition3(content.name);
                        //
                        // remove the <collection> top node
                        //
                        int Pos = Strings.InStr(1, Node, "<cdef", CompareMethod.Text);
                        if (Pos > 0)
                        {
                            Node = Strings.Mid(Node, Pos);
                            Pos  = Strings.InStr(1, Node, "</cdef>", CompareMethod.Text);
                            if (Pos > 0)
                            {
                                Node           = Strings.Mid(Node, 1, Pos + 6);
                                collectionXml += System.Environment.NewLine + "\t" + Node;
                            }
                        }
                    }
                    //
                    // Scripting Modules
                    if (IncludeModuleGuidList != "")
                    {
                        string[] Modules = Strings.Split(IncludeModuleGuidList, System.Environment.NewLine);
                        for (var Ptr = 0; Ptr <= Information.UBound(Modules); Ptr++)
                        {
                            string ModuleGuid = Modules[Ptr];
                            if (ModuleGuid != "")
                            {
                                using (CPCSBaseClass CS2 = cp.CSNew()) {
                                    CS2.Open("Scripting Modules", "ccguid=" + cp.Db.EncodeSQLText(ModuleGuid));
                                    if (CS2.OK())
                                    {
                                        string Code = CS2.GetText("code").Trim();
                                        Code           = EncodeCData(Code);
                                        collectionXml += System.Environment.NewLine + "\t" + "<ScriptingModule Name=\"" + System.Net.WebUtility.HtmlEncode(CS2.GetText("name")) + "\" guid=\"" + ModuleGuid + "\">" + Code + "</ScriptingModule>";
                                    }
                                    CS2.Close();
                                }
                            }
                        }
                    }
                    //
                    // shared styles
                    string[] recordGuids;
                    string   recordGuid;
                    if ((IncludeSharedStyleGuidList != ""))
                    {
                        recordGuids = Strings.Split(IncludeSharedStyleGuidList, System.Environment.NewLine);
                        for (var Ptr = 0; Ptr <= Information.UBound(recordGuids); Ptr++)
                        {
                            recordGuid = recordGuids[Ptr];
                            if (recordGuid != "")
                            {
                                using (CPCSBaseClass CS2 = cp.CSNew()) {
                                    CS2.Open("Shared Styles", "ccguid=" + cp.Db.EncodeSQLText(recordGuid));
                                    if (CS2.OK())
                                    {
                                        collectionXml += System.Environment.NewLine + "\t" + "<SharedStyle"
                                                         + " Name=\"" + System.Net.WebUtility.HtmlEncode(CS2.GetText("name")) + "\""
                                                         + " guid=\"" + recordGuid + "\""
                                                         + " alwaysInclude=\"" + CS2.GetBoolean("alwaysInclude") + "\""
                                                         + " prefix=\"" + System.Net.WebUtility.HtmlEncode(CS2.GetText("prefix")) + "\""
                                                         + " suffix=\"" + System.Net.WebUtility.HtmlEncode(CS2.GetText("suffix")) + "\""
                                                         + " sortOrder=\"" + System.Net.WebUtility.HtmlEncode(CS2.GetText("sortOrder")) + "\""
                                                         + ">"
                                                         + EncodeCData(CS2.GetText("styleFilename").Trim())
                                                         + "</SharedStyle>";
                                    }
                                    CS2.Close();
                                }
                            }
                        }
                    }
                    //
                    // Import Collections
                    {
                        string Node = "";
                        using (CPCSBaseClass CS3 = cp.CSNew()) {
                            if (CS3.Open("Add-on Collection Parent Rules", "parentid=" + collection.id))
                            {
                                do
                                {
                                    using (CPCSBaseClass CS2 = cp.CSNew()) {
                                        if (CS2.OpenRecord("Add-on Collections", CS3.GetInteger("childid")))
                                        {
                                            string Guid = CS2.GetText("ccGuid");
                                            if (Guid == "")
                                            {
                                                Guid = cp.Utils.CreateGuid();
                                                CS2.SetField("ccGuid", Guid);
                                            }

                                            Node = Node + System.Environment.NewLine + "\t" + "<ImportCollection name=\"" + System.Net.WebUtility.HtmlEncode(CS2.GetText("name")) + "\">" + Guid + "</ImportCollection>";
                                        }

                                        CS2.Close();
                                    }

                                    CS3.GoNext();
                                }while (CS3.OK());
                            }
                            CS3.Close();
                        }
                        collectionXml += Node;
                    }
                    //
                    // wwwFileList
                    if (wwwFileList != "")
                    {
                        string[] Files = Strings.Split(wwwFileList, System.Environment.NewLine);
                        for (int Ptr = 0; Ptr <= Information.UBound(Files); Ptr++)
                        {
                            string pathFilename = Files[Ptr];
                            if (pathFilename != "")
                            {
                                pathFilename = Strings.Replace(pathFilename, @"\", "/");
                                string path     = "";
                                string filename = pathFilename;
                                int    Pos      = Strings.InStrRev(pathFilename, "/");
                                if (Pos > 0)
                                {
                                    filename = Strings.Mid(pathFilename, Pos + 1);
                                    path     = Strings.Mid(pathFilename, 1, Pos - 1);
                                }
                                string fileExtension = System.IO.Path.GetExtension(filename);
                                pathFilename = Strings.Replace(pathFilename, "/", @"\");
                                if (tempPathFileList.Contains(tempExportPath + filename))
                                {
                                    //
                                    // -- the path already has a file with this name
                                    cp.UserError.Add("There was an error exporting this collection because there were multiple files with the same filename [" + filename + "]");
                                }
                                else if (fileExtension.ToUpperInvariant().Equals(".ZIP"))
                                {
                                    //
                                    // -- zip files come from the collection folder
                                    CoreController core           = ((CPClass)cp).core;
                                    string         addonPath      = AddonController.getPrivateFilesAddonPath();
                                    string         collectionPath = CollectionFolderController.getCollectionConfigFolderPath(core, collection.ccguid);
                                    if (!cp.PrivateFiles.FileExists(addonPath + collectionPath + filename))
                                    {
                                        //
                                        // - not there
                                        cp.UserError.Add("There was an error exporting this collection because the zip file [" + pathFilename + "] was not found in the collection path [" + collectionPath + "].");
                                    }
                                    else
                                    {
                                        //
                                        // -- copy file from here
                                        cp.PrivateFiles.Copy(addonPath + collectionPath + filename, tempExportPath + filename, cp.TempFiles);
                                        tempPathFileList.Add(tempExportPath + filename);
                                        collectionXml += System.Environment.NewLine + "\t" + "<Resource name=\"" + System.Net.WebUtility.HtmlEncode(filename) + "\" type=\"www\" path=\"" + System.Net.WebUtility.HtmlEncode(path) + "\" />";
                                    }
                                }
                                else if ((!cp.WwwFiles.FileExists(pathFilename)))
                                {
                                    cp.UserError.Add("There was an error exporting this collection because the www file [" + pathFilename + "] was not found.");
                                }
                                else
                                {
                                    cp.WwwFiles.Copy(pathFilename, tempExportPath + filename, cp.TempFiles);
                                    tempPathFileList.Add(tempExportPath + filename);
                                    collectionXml += System.Environment.NewLine + "\t" + "<Resource name=\"" + System.Net.WebUtility.HtmlEncode(filename) + "\" type=\"www\" path=\"" + System.Net.WebUtility.HtmlEncode(path) + "\" />";
                                }
                            }
                        }
                    }
                    //
                    // ContentFileList
                    //
                    if (true)
                    {
                        if (ContentFileList != "")
                        {
                            string[] Files = Strings.Split(ContentFileList, System.Environment.NewLine);
                            for (var Ptr = 0; Ptr <= Information.UBound(Files); Ptr++)
                            {
                                string PathFilename = Files[Ptr];
                                if (PathFilename != "")
                                {
                                    PathFilename = Strings.Replace(PathFilename, @"\", "/");
                                    string Path     = "";
                                    string Filename = PathFilename;
                                    int    Pos      = Strings.InStrRev(PathFilename, "/");
                                    if (Pos > 0)
                                    {
                                        Filename = Strings.Mid(PathFilename, Pos + 1);
                                        Path     = Strings.Mid(PathFilename, 1, Pos - 1);
                                    }
                                    if (tempPathFileList.Contains(tempExportPath + Filename))
                                    {
                                        cp.UserError.Add("There was an error exporting this collection because there were multiple files with the same filename [" + Filename + "]");
                                    }
                                    else if ((!cp.CdnFiles.FileExists(PathFilename)))
                                    {
                                        cp.UserError.Add("There was an error exporting this collection because the cdn file [" + PathFilename + "] was not found.");
                                    }
                                    else
                                    {
                                        cp.CdnFiles.Copy(PathFilename, tempExportPath + Filename, cp.TempFiles);
                                        tempPathFileList.Add(tempExportPath + Filename);
                                        collectionXml += System.Environment.NewLine + "\t" + "<Resource name=\"" + System.Net.WebUtility.HtmlEncode(Filename) + "\" type=\"content\" path=\"" + System.Net.WebUtility.HtmlEncode(Path) + "\" />";
                                    }
                                }
                            }
                        }
                    }
                    //
                    // ExecFileListNode
                    //
                    collectionXml += execResourceNodeList;
                    //
                    // Other XML
                    //
                    string OtherXML;
                    OtherXML = CS.GetText("otherxml");
                    if (Strings.Trim(OtherXML) != "")
                    {
                        collectionXml += System.Environment.NewLine + OtherXML;
                    }
                    collectionXml += System.Environment.NewLine + "</Collection>";
                    CS.Close();
                    string tempExportXml_Filename = encodeFilename(cp, CollectionName + ".xml");
                    //
                    // Save the installation file and add it to the archive
                    //
                    cp.TempFiles.Save(tempExportPath + tempExportXml_Filename, collectionXml);
                    if (!tempPathFileList.Contains(tempExportPath + tempExportXml_Filename))
                    {
                        tempPathFileList.Add(tempExportPath + tempExportXml_Filename);
                    }
                    string tempExportZip_Filename = encodeFilename(cp, CollectionName + ".zip");
                    //
                    // -- zip up the folder to make the collection zip file in temp filesystem
                    zipTempCdnFile(cp, tempExportPath + tempExportZip_Filename, tempPathFileList);
                    //
                    // -- copy the collection zip file to the cdn filesystem as the download link
                    cp.TempFiles.Copy(tempExportPath + tempExportZip_Filename, cdnExportZip_Filename, cp.CdnFiles);
                    //
                    // -- delete the temp folder
                    cp.TempFiles.DeleteFolder(tempExportPath);
                }
            } catch (Exception ex) {
                cp.Site.ErrorReport(ex);
            }
            return(cdnExportZip_Filename);
        }
Пример #23
0
            //
            // ====================================================================================================
            public void processButtonSubmit(CPBaseClass cp, ForumModel settings)
            {
                try {
                    string button = cp.Doc.GetText("button");
                    if (!string.IsNullOrWhiteSpace(button))
                    {
                        var buttonParts = button.Split('-');
                        switch (buttonParts[0].ToLowerInvariant())
                        {
                        case "addcomment": {
                            //
                            // -- comment required
                            string commentBody = cp.Doc.GetText("CommentInput");
                            if (!string.IsNullOrWhiteSpace(commentBody))
                            {
                                //
                                // -- if not authenticated, add user with name and email
                                if (!cp.User.IsAuthenticated)
                                {
                                    string commentEmail = cp.Doc.GetText("CommentUserName");
                                    var    testUserList = DbBaseModel.createList <PersonModel>(cp, "(email=" + cp.Db.EncodeSQLText(commentEmail) + ")");
                                    if (testUserList.Count.Equals(0))
                                    {
                                        //
                                        // -- the mail is not in use, add the guest as a new user
                                        cp.User.Logout();
                                        user       = DbBaseModel.addDefault <PersonModel>(cp);
                                        user.name  = cp.Doc.GetText("CommentUserName");
                                        user.email = commentEmail;
                                        user.save(cp);
                                        cp.User.LoginByID(user.id);
                                    }
                                }
                                //
                                // -- save comment
                                var comment = DbBaseModel.addDefault <ForumCommentModel>(cp);
                                comment.comment      = cp.Doc.GetText("CommentInput");
                                comment.commentid    = 0;
                                comment.forumid      = settings.id;
                                comment.name         = "user " + user.id + ", " + user.name + " comment";
                                comment.createdBy    = cp.User.Id;
                                comment.dateAdded    = DateTime.Now;
                                comment.modifiedBy   = cp.User.Id;
                                comment.modifiedDate = DateTime.Now;
                                comment.save(cp);
                            }
                            break;
                        }

                        case "addreply": {
                            //
                            // -- comment required
                            int    commentId = cp.Utils.EncodeInteger(buttonParts[1]);
                            string replyBody = cp.Doc.GetText("replyBody" + commentId.ToString());
                            if (!string.IsNullOrWhiteSpace(replyBody))
                            {
                                //
                                // -- if not authenticated, add user with name and email
                                if (!cp.User.IsAuthenticated)
                                {
                                    string commentEmail = cp.Doc.GetText("replyUserEmail" + commentId.ToString());
                                    var    testUserList = DbBaseModel.createList <PersonModel>(cp, "(email=" + cp.Db.EncodeSQLText(commentEmail) + ")");
                                    if (testUserList.Count.Equals(0))
                                    {
                                        //
                                        // -- the mail is not in use, add the guest as a new user
                                        cp.User.Logout();
                                        user       = DbBaseModel.addDefault <PersonModel>(cp);
                                        user.name  = cp.Doc.GetText("replyUserEmail" + commentId.ToString());
                                        user.email = commentEmail;
                                        user.save(cp);
                                        cp.User.LoginByID(user.id);
                                    }
                                }
                                //
                                // -- save comment
                                var reply = DbBaseModel.addDefault <ForumCommentModel>(cp);
                                reply.comment      = replyBody;
                                reply.commentid    = commentId;
                                reply.forumid      = settings.id;
                                reply.name         = "user " + user.id + ", " + user.name + " comment";
                                reply.createdBy    = cp.User.Id;
                                reply.dateAdded    = DateTime.Now;
                                reply.modifiedBy   = cp.User.Id;
                                reply.modifiedDate = DateTime.Now;
                                reply.save(cp);
                            }
                            break;
                        }

                        default: {
                            break;
                        }
                        }
                    }
                } catch (Exception ex) {
                    cp.Site.ErrorReport(ex);
                    throw;
                }
            }
Пример #24
0
 //
 public static List <ContentModel> createListFromCollection(CPBaseClass cp, int collectionId)
 {
     return(DbBaseModel.createList <ContentModel>(cp, "id in (select distinct contentId from ccAddonCollectionCDefRules where collectionid=" + collectionId + ")", "name"));
 }
        //
        //======================================================================================================
        //
        public static void installNode(CoreController core, XmlNode templateNode, int collectionId, ref bool return_UpgradeOK, ref string return_ErrorMessage, ref bool collectionIncludesDiagnosticAddons)
        {
            return_ErrorMessage = "";
            return_UpgradeOK    = true;
            try {
                string Basename = toLCase(templateNode.Name);
                if (Basename == "template")
                {
                    bool   IsFound      = false;
                    string templateName = XmlController.getXMLAttribute(core, ref IsFound, templateNode, "name", "No Name");
                    if (string.IsNullOrEmpty(templateName))
                    {
                        templateName = "No Name";
                    }
                    string recordGuid = XmlController.getXMLAttribute(core, ref IsFound, templateNode, "guid", templateName);
                    if (string.IsNullOrEmpty(recordGuid))
                    {
                        recordGuid = templateName;
                    }
                    var template = DbBaseModel.create <PageTemplateModel>(core.cpParent, recordGuid);
                    if (template == null)
                    {
                        template = DbBaseModel.createByUniqueName <PageTemplateModel>(core.cpParent, templateName);
                    }
                    if (template == null)
                    {
                        template = DbBaseModel.addDefault <PageTemplateModel>(core.cpParent);
                    }
                    foreach (XmlNode childNode in templateNode.ChildNodes)
                    {
                        switch (childNode.Name.ToLowerInvariant())
                        {
                        case "includeaddon": {
                            string addonGuid = XmlController.getXMLAttribute(core, ref IsFound, childNode, "guid", "");
                            string addonName = XmlController.getXMLAttribute(core, ref IsFound, childNode, "name", "No Name");
                            if (!string.IsNullOrEmpty(addonGuid))
                            {
                                var addon = DbBaseModel.create <AddonModel>(core.cpParent, addonGuid);
                                if (addon == null)
                                {
                                    return_ErrorMessage += "Addon dependency [" + addonName + "] for template [" + templateName + "] could not be found by its guid [" + addonGuid + "]";
                                }
                                var ruleList = DbBaseModel.createList <AddonTemplateRuleModel>(core.cpParent, "(addonId=" + addon.id + ")and(addonId=" + template.id + ")");
                                if (ruleList.Count.Equals(0))
                                {
                                    var rule = DbBaseModel.addDefault <AddonTemplateRuleModel>(core.cpParent);
                                    rule.addonId    = addon.id;
                                    rule.templateId = template.id;
                                    rule.save(core.cpParent);
                                }
                            }
                            break;
                        }

                        case "bodyhtml": {
                            template.bodyHTML = childNode.InnerText;
                            break;
                        }
                        }
                    }
                    template.ccguid = recordGuid;
                    template.name   = templateName;
                    //record.bodyHTML = templateNode.InnerText;
                    template.collectionId = collectionId;
                    template.isSecure     = XmlController.getXMLAttributeBoolean(core, ref IsFound, templateNode, "issecure", false);
                    template.save(core.cpParent);
                }
            } catch (Exception ex) {
                LogController.logError(core, ex);
                throw;
            }
        }