Пример #1
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
     });
 }
Пример #2
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");
     }
 }
        //
        //====================================================================================================
        /// <summary>
        /// getFieldEditorPreference remote method
        /// </summary>
        /// <param name="cp"></param>
        /// <returns></returns>
        public override object Execute(Contensive.BaseClasses.CPBaseClass cp)
        {
            string result = "";

            try {
                CoreController core = ((CPClass)cp).core;
                //
                // save custom styles
                if (core.session.isAuthenticatedAdmin())
                {
                    int addonId = core.docProperties.getInteger("AddonID");
                    if (addonId > 0)
                    {
                        AddonModel styleAddon = DbBaseModel.create <AddonModel>(core.cpParent, addonId);
                        if (styleAddon.stylesFilename.content != core.docProperties.getText("CustomStyles"))
                        {
                            styleAddon.stylesFilename.content = core.docProperties.getText("CustomStyles");
                            styleAddon.save(core.cpParent);
                            //
                            // Clear Caches
                            //
                            DbBaseModel.invalidateCacheOfRecord <AddonModel>(core.cpParent, addonId);
                        }
                    }
                }
            } catch (Exception ex) {
                cp.Site.ErrorReport(ex);
            }
            return(result);
        }
Пример #4
0
        //
        //====================================================================================================
        /// <summary>
        /// Add a user to a group. If gorupId doesnt exist, an error is logged.
        /// </summary>
        /// <param name="core"></param>
        /// <param name="groupId"></param>
        /// <param name="userId"></param>
        /// <param name="dateExpires"></param>
        public static void addUser(CoreController core, int groupId, int userId, DateTime dateExpires)
        {
            var group = DbBaseModel.create <GroupModel>(core.cpParent, groupId);

            if (group == null)
            {
                //
                // -- inactive or invalid groupId
                //LogController.logError(core, new GenericException("addUser called with invalid groupId [" + groupId + "]"));
                return;
            }
            if (userId.Equals(0))
            {
                //
                // -- default to keyboard user
                userId = core.session.user.id;
            }
            PersonModel user = DbBaseModel.create <PersonModel>(core.cpParent, userId);

            if (user == null)
            {
                //
                // -- inactive or invalid userId
                //LogController.logError(core, new GenericException("addUser called with invalid userId [" + userId + "]"));
                return;
            }
            addUser(core, group, user, dateExpires);
        }
Пример #5
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;
         //
         // -- Email click detected
         EmailDropModel emailDrop = DbBaseModel.create <EmailDropModel>(core.cpParent, core.docProperties.getInteger(rnEmailClickFlag));
         if (emailDrop != null)
         {
             PersonModel recipient = DbBaseModel.create <PersonModel>(core.cpParent, core.docProperties.getInteger(rnEmailMemberId));
             if (recipient != null)
             {
                 EmailLogModel log = DbBaseModel.addDefault <EmailLogModel>(core.cpParent);
                 log.name        = "User " + recipient.name + " clicked link from email drop " + emailDrop.name + " at " + core.doc.profileStartTime.ToString();
                 log.emailDropId = emailDrop.id;
                 log.emailId     = emailDrop.emailId;
                 log.memberId    = recipient.id;
                 log.logType     = EmailLogTypeClick;
                 log.visitId     = cp.Visit.Id;
                 log.save(cp);
             }
         }
     } catch (Exception ex) {
         cp.Site.ErrorReport(ex);
     }
     return("");
 }
        //
        //====================================================================================================
        /// <summary>
        /// setAdminSiteFieldHelp remote method
        /// </summary>
        /// <param name="cp"></param>
        /// <returns></returns>
        public override object Execute(Contensive.BaseClasses.CPBaseClass cp)
        {
            string result = "";

            try {
                CoreController core = ((CPClass)cp).core;
                if (cp.User.IsAdmin)
                {
                    int fieldId = cp.Doc.GetInteger("fieldId");
                    var help    = ContentFieldHelpModel.createByFieldId(cp, fieldId);
                    if (help == null)
                    {
                        help         = DbBaseModel.addDefault <ContentFieldHelpModel>(core.cpParent, Processor.Models.Domain.ContentMetadataModel.getDefaultValueDict(core, ContentFieldHelpModel.tableMetadata.contentName));
                        help.fieldId = fieldId;
                    }
                    help.helpCustom = cp.Doc.GetText("helpcustom");
                    help.save(cp);
                    ContentFieldModel contentField = DbBaseModel.create <ContentFieldModel>(core.cpParent, fieldId);
                    if (contentField != null)
                    {
                        ContentMetadataModel.invalidateCache(core, contentField.contentId);
                    }
                }
            } catch (Exception ex) {
                cp.Site.ErrorReport(ex);
            }
            return(result);
        }
Пример #7
0
 //
 //====================================================================================================
 //
 public override void OpenCopy(string copyRecordNameOrGuid)
 {
     try {
         accum = "";
         CopyContentModel copy;
         if (copyRecordNameOrGuid.isNumeric())
         {
             //
             // -- recordId
             copy = CopyContentModel.create <CopyContentModel>(cp, GenericController.encodeInteger(copyRecordNameOrGuid));
         }
         else if (GenericController.isGuid(copyRecordNameOrGuid))
         {
             //
             // -- record guid
             copy = CopyContentModel.create <CopyContentModel>(cp, copyRecordNameOrGuid);
         }
         else
         {
             //
             // -- record name
             copy = DbBaseModel.createByUniqueName <CopyContentModel>(cp, copyRecordNameOrGuid);
         }
         if (copy != null)
         {
             accum = copy.copy;
         }
     } catch (Exception ex) {
         LogController.logError(cp.core, ex);
         throw;
     }
 }
Пример #8
0
 //
 //====================================================================================================
 //
 public override void OpenLayout(string layoutRecordNameOrGuid)
 {
     try {
         accum = "";
         LayoutModel layout;
         if (layoutRecordNameOrGuid.isNumeric())
         {
             //
             // -- recordId
             layout = DbBaseModel.create <LayoutModel>(cp, GenericController.encodeInteger(layoutRecordNameOrGuid));
         }
         else if (GenericController.isGuid(layoutRecordNameOrGuid))
         {
             //
             // -- record guid
             layout = LayoutModel.create <LayoutModel>(cp, layoutRecordNameOrGuid);
         }
         else
         {
             //
             // -- record name
             layout = LayoutModel.createByUniqueName <LayoutModel>(cp, layoutRecordNameOrGuid);
         }
         if (layout != null)
         {
             accum = layout.layout.content;
         }
     } catch (Exception ex) {
         LogController.logError(cp.core, ex);
         throw;
     }
 }
        //
        // ====================================================================================================

        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);
            }
        }
Пример #10
0
 //
 //====================================================================================================
 //
 public override void ExportCsv(string sql, string exportName, string filename)
 {
     try {
         var ExportCSVAddon = DbBaseModel.create <AddonModel>(cp, addonGuidExportCSV);
         if (ExportCSVAddon == null)
         {
             LogController.logError(cp.core, new GenericException("ExportCSV addon not found. Task could not be added to task queue."));
         }
         else
         {
             var cmdDetail = new TaskModel.CmdDetailClass {
                 addonId   = ExportCSVAddon.id,
                 addonName = ExportCSVAddon.name,
                 args      = new Dictionary <string, string> {
                     { "sql", sql },
                     { "ExportName", exportName },
                     { "filename", filename }
                 }
             };
             TaskSchedulerController.addTaskToQueue(cp.core, cmdDetail, false, exportName, filename);
         }
     } catch (Exception) {
         throw;
     }
 }
Пример #11
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;
         int            emailDropId = core.docProperties.getInteger(rnEmailOpenFlag);
         if (emailDropId != 0)
         {
             //
             // -- Email open detected. Log it and redirect to a 1x1 spacer
             EmailDropModel emailDrop = DbBaseModel.create <EmailDropModel>(core.cpParent, emailDropId);
             if (emailDrop != null)
             {
                 PersonModel recipient = DbBaseModel.create <PersonModel>(core.cpParent, core.docProperties.getInteger(rnEmailMemberId));
                 if (recipient != null)
                 {
                     EmailLogModel log = DbBaseModel.addDefault <EmailLogModel>(core.cpParent);
                     log.name        = "User " + recipient.name + " opened email drop " + emailDrop.name + " at " + core.doc.profileStartTime.ToString();
                     log.emailDropId = emailDrop.id;
                     log.emailId     = emailDrop.emailId;
                     log.memberId    = recipient.id;
                     log.logType     = EmailLogTypeOpen;
                     log.visitId     = cp.Visit.Id;
                     log.save(cp);
                 }
             }
         }
         core.webServer.redirect(NonEncodedLink: "" + cdnPrefix + "images/spacer.gif", RedirectReason: "Group Email Open hit, redirecting to a dummy image", IsPageNotFound: false, allowDebugMessage: false);
     } catch (Exception ex) {
         cp.Site.ErrorReport(ex);
     }
     return("");
 }
Пример #12
0
        //
        //========================================================================
        //
        public static void requestDownload(CoreController core, int customReportId)
        {
            //
            // Request the download
            //
            var customReport = DbBaseModel.create <CustomReportModel>(core.cpParent, customReportId);

            if (customReport != null)
            {
                var ExportCSVAddon = DbBaseModel.create <AddonModel>(core.cpParent, addonGuidExportCSV);
                if (ExportCSVAddon == null)
                {
                    LogController.logError(core, new GenericException("ExportCSV addon not found. Task could not be added to task queue."));
                }
                else
                {
                    var docProperties = new Dictionary <string, string> {
                        { "sql", customReport.sqlQuery },
                        { "datasource", "default" }
                    };
                    var cmdDetail = new TaskModel.CmdDetailClass {
                        addonId   = ExportCSVAddon.id,
                        addonName = ExportCSVAddon.name,
                        args      = docProperties
                    };
                    string ExportFilename = "CustomReport_" + customReport.id.ToString("00000000") + ".csv";
                    string reportName     = customReport.name ?? "#" + customReport.id;
                    TaskSchedulerController.addTaskToQueue(core, cmdDetail, false, "Custom Report, " + reportName, ExportFilename);
                }
            }
        }
Пример #13
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);
     }
 }
Пример #14
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));
     }
 }
Пример #15
0
        //
        public static AuthenticateResponse authenticateUsernamePassword(CoreController core, string username, string password, string errorPrefix)
        {
            int userId = core.session.getUserIdForUsernameCredentials(username, password);

            if (userId == 0)
            {
                //
                // -- user was not found
                core.webServer.setResponseStatus(WebServerController.httpResponseStatus401_Unauthorized);
                return(new AuthenticateResponse {
                    errors = new List <string> {
                        errorPrefix + " failed."
                    },
                    data = new AuthenticateResponseData()
                });
            }
            else
            {
                if (!core.session.authenticateById(userId, core.session))
                {
                    //
                    // -- username/password login failed
                    core.webServer.setResponseStatus(WebServerController.httpResponseStatus401_Unauthorized);
                    return(new AuthenticateResponse {
                        errors = new List <string> {
                            errorPrefix + " failed."
                        },
                        data = new AuthenticateResponseData()
                    });
                }
                else
                {
                    var user = DbBaseModel.create <PersonModel>(core.cpParent, core.session.user.id);
                    if (user == null)
                    {
                        core.webServer.setResponseStatus(WebServerController.httpResponseStatus401_Unauthorized);
                        return(new AuthenticateResponse {
                            errors = new List <string> {
                                errorPrefix + " user is not valid."
                            },
                            data = new AuthenticateResponseData()
                        });
                    }
                    else
                    {
                        LogController.addSiteActivity(core, errorPrefix + " successful", core.session.user.id, core.session.user.organizationId);
                        return(new AuthenticateResponse {
                            errors = new List <string>(),
                            data = new AuthenticateResponseData {
                                firstName = user.firstName,
                                lastName = user.lastName,
                                email = user.email,
                                avatar = (!string.IsNullOrWhiteSpace(user.thumbnailFilename)) ? core.appConfig.cdnFileUrl + user.thumbnailFilename : (!string.IsNullOrWhiteSpace(user.imageFilename)) ? core.appConfig.cdnFileUrl + user.imageFilename : ""
                            }
                        });
                    }
                }
            }
        }
Пример #16
0
        //
        //====================================================================================================
        //
        public override int GetTableID(string tableName)
        {
            var table = DbBaseModel.createByUniqueName <TableModel>(cp, tableName);

            if (table == null)
            {
                return(0);
            }
            return(table.id);
        }
Пример #17
0
        //
        //====================================================================================================
        //
        public override string GetName(int contentId)
        {
            var content = DbBaseModel.create <ContentModel>(cp, contentId);

            if (content != null)
            {
                return(content.name);
            }
            return(string.Empty);
        }
Пример #18
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);
        }
Пример #19
0
        //
        //====================================================================================================
        //
        public override int GetID(string ContentName)
        {
            var content = DbBaseModel.createByUniqueName <ContentModel>(cp, ContentName);

            if (content != null)
            {
                return(content.id);
            }
            return(0);
        }
Пример #20
0
        //
        //====================================================================================================
        /// <summary>
        /// Get a group Name
        /// </summary>
        /// <param name="core"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public static string getGroupName(CoreController core, int groupId)
        {
            var group = DbBaseModel.create <GroupModel>(core.cpParent, groupId);

            if (group != null)
            {
                return(group.name);
            }
            return(String.Empty);
        }
Пример #21
0
        //
        //====================================================================================================
        /// <summary>
        /// Get a group Id
        /// </summary>
        /// <param name="core"></param>
        /// <param name="GroupName"></param>
        /// <returns></returns>
        public static int getGroupId(CoreController core, string GroupName)
        {
            var group = DbBaseModel.createByUniqueName <GroupModel>(core.cpParent, GroupName);

            if (group != null)
            {
                return(group.id);
            }
            return(0);
        }
Пример #22
0
        //
        //====================================================================================================
        //
        public override void sendUser(int toUserId, string fromAddress, string subject, string body, bool sendImmediately, bool bodyIsHtml, ref string userErrorMessage)
        {
            PersonModel person = DbBaseModel.create <PersonModel>(cp, toUserId);

            if (person == null)
            {
                userErrorMessage = "An email could not be sent because the user could not be located.";
                return;
            }
            EmailController.queuePersonEmail(cp.core, "Ad Hoc Email", person, fromAddress, subject, body, "", "", sendImmediately, bodyIsHtml, 0, "", false, ref userErrorMessage);
        }
Пример #23
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);
        }
Пример #24
0
 //
 //====================================================================================================
 /// <summary>
 /// Add a command task to the taskQueue to be run by the taskRunner. Returns false if the task was already there (dups fround by command name and cmdDetailJson)
 /// </summary>
 /// <param name="core"></param>
 /// <param name="command"></param>
 /// <param name="cmdDetail"></param>
 /// <param name="downloadName"></param>
 /// <returns></returns>
 static public bool addTaskToQueue(CoreController core, TaskModel.CmdDetailClass cmdDetail, bool blockDuplicates, string downloadName, string downloadFilename)
 {
     try {
         //
         int downloadId = 0;
         if (!string.IsNullOrEmpty(downloadName))
         {
             Dictionary <string, string> defaultValues = ContentMetadataModel.getDefaultValueDict(core, DownloadModel.tableMetadata.contentName);
             var download = DbBaseModel.addDefault <DownloadModel>(core.cpParent, defaultValues);
             download.name          = downloadName;
             download.dateRequested = core.dateTimeNowMockable;
             download.requestedBy   = core.session.user.id;
             if (!string.IsNullOrEmpty(downloadFilename))
             {
                 //
                 // -- if the donwloadfilename is specified, save it in the download record and force the file to save with a space in content
                 download.filename.filename = FileController.getVirtualRecordUnixPathFilename(DownloadModel.tableMetadata.tableNameLower, "filename", download.id, downloadFilename);
                 download.filename.content  = " ";
             }
             downloadId = download.id;
             download.save(core.cpParent);
         }
         string cmdDetailJson = SerializeObject(cmdDetail);
         bool   allowAdd      = true;
         if (blockDuplicates)
         {
             //
             // -- Search for a duplicate
             string sql = "select top 1 id from cctasks where ((cmdDetail=" + DbController.encodeSQLText(cmdDetailJson) + ")and(datestarted is null)and(datecompleted is null))";
             using (var csData = new CsModel(core)) {
                 allowAdd = !csData.openSql(sql);
             }
         }
         //
         // -- add it to the queue and shell out to the command
         if (allowAdd)
         {
             var task = TaskModel.addEmpty <TaskModel>(core.cpParent);
             task.name             = "addon [#" + cmdDetail.addonId + "," + cmdDetail.addonName + "]";
             task.cmdDetail        = cmdDetailJson;
             task.resultDownloadId = downloadId;
             task.save(core.cpParent);
             LogController.logTrace(core, "addTaskToQueue, task added, cmdDetailJson [" + cmdDetailJson + "]");
             return(true);
         }
         LogController.logTrace(core, "addTaskToQueue, task blocked because duplicate found, cmdDetailJson [" + cmdDetailJson + "]");
         return(false);
     } catch (Exception ex) {
         LogController.logError(core, ex);
         return(false);
     }
 }
Пример #25
0
            //
            // ====================================================================================================
            public static AddonMockDataModel createOrAddSettings(CPBaseClass cp, string settingsGuid)
            {
                AddonMockDataModel result = create <AddonMockDataModel>(cp, settingsGuid);

                if ((result == null))
                {
                    //
                    // -- create default content
                    result              = addDefault <AddonMockDataModel>(cp);
                    result.name         = tableMetadata.contentName + " " + result.id;
                    result.ccguid       = settingsGuid;
                    result.themeStyleId = 0;
                    result.padTop       = false;
                    result.padBottom    = false;
                    result.padRight     = false;
                    result.padLeft      = false;
                    //
                    // -- create custom content
                    result.jsondata = "{\"headline\":\"Hello World\",\"items\":[{\"name\":\"Rock\",\"price\":\"$1.24\"},{\"name\":\"Nice Rock\",\"price\":\"$2.99\"}]}";
                    //
                    DateTime rightNow      = DateTime.Now;
                    var      layout        = DbBaseModel.create <LayoutModel>(cp, Constants.guidAddonMockLayout);
                    string   defaultLayout = "<h2>{{headline}}</h2><ul>{{#items}}<hr><li><div>name: {{name}}</div><div>price: {{price}}</div></li>{{/items}}</ul><hr>";
                    if (layout == null)
                    {
                        //
                        // -- no layout found for the default guid, create now
                        layout                = DbBaseModel.addDefault <LayoutModel>(cp);
                        layout.name           = "Addon Mock Default Layout, " + rightNow.Year + rightNow.Month.ToString().PadLeft(2, '0') + rightNow.Day.ToString().PadLeft(2, '0');
                        layout.ccguid         = Constants.guidAddonMockLayout;
                        layout.layout.content = defaultLayout;
                        layout.save(cp);
                    }
                    if (layout.layout.content != defaultLayout)
                    {
                        //
                        // -- layout does not match default content, they edited it so just create a new record
                        layout                = DbBaseModel.addDefault <LayoutModel>(cp);
                        layout.name           = "Addon Mock Default Layout, " + rightNow.Year + rightNow.Month.ToString().PadLeft(2, '0') + rightNow.Day.ToString().PadLeft(2, '0');
                        layout.ccguid         = cp.Utils.CreateGuid();
                        layout.layout.content = defaultLayout;
                        layout.save(cp);
                    }
                    result.layoutid = layout.id;
                    //
                    result.save(cp);
                    //
                    // -- track the last modified date
                    cp.Content.LatestContentModifiedDate.Track(result.modifiedDate);
                }
                return(result);
            }
Пример #26
0
        //
        //====================================================================================================
        /// <summary>
        /// Remove a user from a group.
        /// </summary>
        /// <param name="core"></param>
        /// <param name="groupId"></param>
        /// <param name="userId"></param>
        public static void removeUser(CoreController core, int groupId, int userId)
        {
            var group = DbBaseModel.create <GroupModel>(core.cpParent, groupId);

            if (group != null)
            {
                var user = DbBaseModel.create <PersonModel>(core.cpParent, userId);
                if (user != null)
                {
                    removeUser(core, group, user);
                }
            }
        }
Пример #27
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);
        }
Пример #28
0
        public override int LandingPageId(string domainName)
        {
            if (string.IsNullOrWhiteSpace(domainName))
            {
                return(GetInteger("LandingPageID", 0));
            }
            var domain = DbBaseModel.createByUniqueName <DomainModel>(cp, domainName);

            if (domain == null)
            {
                return(GetInteger("LandingPageID", 0));
            }
            return(domain.rootPageId);
        }
        public void ShouldReturnSameDescription(string description)
        {
            var expectedBaseModel = new BaseModel
            {
                Description = description
            };
            var dbBaseModel = new DbBaseModel
            {
                Description = description
            };
            var actualBaseModel = _dbBaseModelToBaseModelTransformer.ToEntity(dbBaseModel);

            Assert.AreEqual(expectedBaseModel.Description, actualBaseModel.Description);
        }
        public void ShouldReturnSameModificationTime(DateTime dateTime)
        {
            var expectedBaseModel = new BaseModel
            {
                ModificationTime = dateTime
            };
            var dbBaseModel = new DbBaseModel
            {
                ModificationTime = dateTime
            };
            var actualBaseModel = _dbBaseModelToBaseModelTransformer.ToEntity(dbBaseModel);

            Assert.AreEqual(expectedBaseModel.ModificationTime, actualBaseModel.ModificationTime);
        }