public TextContentController(TextContentManager textContentManager, TextFolderManager textFolderManager, WorkflowManager workflowManager, ITextContentBinder binder) { TextContentManager = textContentManager; TextFolderManager = textFolderManager; WorkflowManager = workflowManager; Binder = binder; }
/// <summary> /// Refresh button click event handler. /// </summary> protected void btnRefresh_Click(object sender, EventArgs e) { if (treeNode != null) { // Check permission to modify document if (CMSContext.CurrentUser.IsAuthorizedPerDocument(treeNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed) { // Get curent step WorkflowManager wm = new WorkflowManager(tree); WorkflowStepInfo currentStep = wm.GetStepInfo(treeNode); string currentStepName = currentStep.StepName.ToLower(); bool wasArchived = currentStepName == "archived"; // Move to edit step DocumentHelper.MoveDocumentToEditStep(treeNode, tree); // Refresh frames and tree string script = "if(window.FramesRefresh){FramesRefresh(" + wasArchived.ToString().ToLower() + ", " + treeNode.NodeID + ");}"; ScriptHelper.RegisterStartupScript(this, typeof(string), "refreshAction", ScriptHelper.GetScript(script)); } } }
public RoadTestScheduledState(WorkflowManager manager) : base(manager, WorkflowStates.RoadTestScheduled) { }
public void GetUserTasks() { RequestContext.Current.Add<UserContext>("UserContext", new UserContext { UserId = 1, LanguageId = 1, UserName = "******", SiteId = 1 }); WorkflowManager workflowManager = new WorkflowManager(); List<UserTask> tasks = workflowManager.GetUserTasks(ContextEnum.None, null, null, null, true); }
/// <summary> /// ContentManager /// </summary> public ContentManager() { _securityManager = new SecurityManager(); _workflowManager = new WorkflowManager(); }
protected void Page_Load(object sender, EventArgs e) { // Switch the view mode CMSContext.ViewMode = ViewModeEnum.Preview; // Get the document int nodeId = 0; if (Request.QueryString["nodeid"] != null) { nodeId = ValidationHelper.GetInteger(Request.QueryString["nodeid"], 0); } string siteName = CMSContext.CurrentSiteName; TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); TreeNode node = null; // Check split mode bool isSplitMode = CMSContext.DisplaySplitMode; bool combineWithDefaultCulture = isSplitMode ? false : SiteInfoProvider.CombineWithDefaultCulture(siteName); // Get the document node = tree.SelectSingleNode(nodeId, CMSContext.PreferredCultureCode, combineWithDefaultCulture); // Redirect to the live URL if (node != null) { // If no workflow defined, hide the menu bar WorkflowManager wm = new WorkflowManager(tree); WorkflowInfo wi = wm.GetNodeWorkflow(node); if (wi == null) { headersize = "0"; } else { // Get current step info WorkflowStepInfo si = wm.GetStepInfo(node); if (si != null) { switch (si.StepName.ToLower()) { case "published": case "archived": headersize = "0"; break; } } } // Check the document availability if (!node.DocumentCulture.Equals(CMSContext.PreferredCultureCode, StringComparison.InvariantCultureIgnoreCase) && (!SiteInfoProvider.CombineWithDefaultCulture(siteName) || !node.DocumentCulture.Equals(CultureHelper.GetDefaultCulture(siteName), StringComparison.InvariantCultureIgnoreCase))) { viewpage = "~/CMSMessages/PageNotAvailable.aspx?reason=missingculture"; } else { // Use permanent URL to get proper preview mode viewpage = URLRewriter.GetEditingUrl(node); } } else { viewpage = isSplitMode ? "~/CMSModules/Content/CMSDesk/New/NewCultureVersion.aspx" + URLHelper.Url.Query : "~/CMSMessages/PageNotAvailable.aspx?reason=missingculture&showlink=false"; } // Register synchronization script for split mode if (isSplitMode) { RegisterSplitModeSync(false, false); } viewpage = ResolveUrl(viewpage); }
/// <summary> /// Publishes document. /// </summary> /// <param name="node">Node to publish</param> /// <param name="wm">Workflow manager</param> /// <param name="currentStep">Current workflow step</param> /// <returns>TRUE if operation fails</returns> private bool Publish(TreeNode node, WorkflowManager wm, WorkflowStepInfo currentStep) { string pathCulture = HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")"); bool alreadyPublished = (currentStep == null) || currentStep.StepIsPublished; if (!alreadyPublished) { // Publish document currentStep = wm.PublishDocument(node, null); } // Document is already published, check if still under workflow if (alreadyPublished && (currentStep != null) && currentStep.StepIsPublished) { WorkflowScopeInfo wsi = wm.GetNodeWorkflowScope(node); if (wsi == null) { DocumentHelper.ClearWorkflowInformation(node); VersionManager vm = VersionManager.GetInstance(node.TreeProvider); vm.RemoveWorkflow(node); } } // Document already published if (alreadyPublished) { AddLog(string.Format(ResHelper.GetString("content.publishedalready"), pathCulture)); } else if (!currentStep.StepIsPublished) { AddError(string.Format(ResHelper.GetString("content.PublishWasApproved"), pathCulture)); return true; } else { // Add log record AddLog(pathCulture); } return false; }
public KnowledgeTestScheduledState(WorkflowManager manager) : base(manager, WorkflowStates.KnowledgeTestScheduled) { }
protected void btnOk_Click(object sender, EventArgs e) { // Check allowed cultures if (!CMSContext.CurrentUser.IsCultureAllowed(CMSContext.PreferredCultureCode, CMSContext.CurrentSiteName)) { lblError.Text = GetString("Content.NotAuthorizedFile"); pnlForm.Visible = false; return; } TreeNode node = null; TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); if ((UseFileUploader && !FileUpload.HasFile) || (!UseFileUploader && !ucDirectUploader.HasData())) { lblError.Text = GetString("NewFile.ErrorEmpty"); } else { // Get file extension string fileExtension = UseFileUploader ? FileUpload.FileName : ucDirectUploader.AttachmentName; fileExtension = Path.GetExtension(fileExtension).TrimStart('.'); // Check file extension if (IsExtensionAllowed(fileExtension)) { bool newDocumentCreated = false; try { if (UseFileUploader) { // Process file using file upload node = ProcessFileUploader(tree); } else { // Process file using direct uploader node = ProcessDirectUploader(tree); // Save temporary attachments DocumentHelper.SaveTemporaryAttachments(node, Guid, CMSContext.CurrentSiteName, tree); } newDocumentCreated = true; // Create default SKU if configured if (ModuleEntry.CheckModuleLicense(ModuleEntry.ECOMMERCE, URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert)) { bool? skuCreated = node.CreateDefaultSKU(); if (skuCreated.HasValue && !skuCreated.Value) { lblError.Text = GetString("com.CreateDefaultSKU.Error"); } } // Set additional values if (!string.IsNullOrEmpty(fileExtension)) { // Update document extensions if no custom are used if (!node.DocumentUseCustomExtensions) { node.DocumentExtensions = "." + fileExtension; } node.SetValue("DocumentType", "." + fileExtension); } // Update the document DocumentHelper.UpdateDocument(node, tree); WorkflowManager workflowManager = new WorkflowManager(tree); // Get workflow info WorkflowInfo workflowInfo = workflowManager.GetNodeWorkflow(node); // Check if auto publish changes is allowed if ((workflowInfo != null) && workflowInfo.WorkflowAutoPublishChanges && !workflowInfo.UseCheckInCheckOut(CMSContext.CurrentSiteName)) { // Automatically publish document workflowManager.AutomaticallyPublish(node, workflowInfo, null); } bool createAnother = ValidationHelper.GetBoolean(Request.Params["hidAnother"], false); // Added from CMSDesk->Content if (!isDialog) { if (createAnother) { ltlScript.Text += ScriptHelper.GetScript("PassiveRefresh(" + node.NodeParentID + ", " + node.NodeParentID + "); CreateAnother();"); } else { ltlScript.Text += ScriptHelper.GetScript( " RefreshTree(" + node.NodeID + ", " + node.NodeID + "); SelectNode(" + node.NodeID + "); \n" ); } } // Added from dialog window else { if (createAnother) { txtFileDescription.Text = ""; ltlScript.Text += ScriptHelper.GetScript("FileCreated(" + node.NodeID + ", " + node.NodeParentID + ", false);"); } else { ltlScript.Text += ScriptHelper.GetScript("FileCreated(" + node.NodeID + ", " + node.NodeParentID + ", true);"); } } } catch (Exception ex) { // Delete the document if something failed if (newDocumentCreated && (node != null) && (node.DocumentID > 0)) { DocumentHelper.DeleteDocument(node, tree, false, true, true); } lblError.Text = GetString("NewFile.Failed") + ": " + ex.Message; } } else { lblError.Text = String.Format(GetString("NewFile.ExtensionNotAllowed"), fileExtension); } } }
protected void Page_Load(object sender, EventArgs e) { #region 接收参数 // TaskID bool bIsValid = PageCommon.ValidateQueryString(this, "TaskID", QueryStringType.ID); if (bIsValid == false) { this.Response.Write("{\"ExecResult\":\"Failed\",\"ErrorMsg\":\"Missing required query string.\"}"); return; } string sTaskID = this.Request.QueryString["TaskID"].ToString(); int iTaskID = Convert.ToInt32(sTaskID); // LoanID bIsValid = PageCommon.ValidateQueryString(this, "LoanID", QueryStringType.ID); if (bIsValid == false) { this.Response.Write("{\"ExecResult\":\"Failed\",\"ErrorMsg\":\"Missing required query string.\"}"); return; } string sLoanID = this.Request.QueryString["LoanID"].ToString(); int iLoanID = Convert.ToInt32(sLoanID); #endregion // json示例 // {"ExecResult":"Success","ErrorMsg":"","EmailTemplateID":"1", "LoanClosed":"Yes"} // {"ExecResult":"Failed","ErrorMsg":"执行数据库脚本时发生错误。"} string sErrorMsg = string.Empty; string sEmailTemplateID = string.Empty; bool bIsSuccess = false; string LoanClosed = "No"; var result = ""; try { #region complete task int iEmailTemplateId = 0; bIsSuccess = LPWeb.DAL.WorkflowManager.CompleteTask(iTaskID, this.CurrUser.iUserID, ref iEmailTemplateId); if (bIsSuccess == false) { sErrorMsg = "Failed to invoke WorkflowManager.CompleteTask."; return; } if (iEmailTemplateId != 0) { sEmailTemplateID = iEmailTemplateId.ToString(); } #endregion #region update point file stage int iLoanStageID = 0; #region get loan task info LoanTasks LoanTaskManager = new LoanTasks(); DataTable LoanTaskInfo = LoanTaskManager.GetLoanTaskInfo(iTaskID); if (LoanTaskInfo.Rows.Count == 0) { bIsSuccess = false; sErrorMsg = "Invalid task id."; return; } string sLoanStageID = LoanTaskInfo.Rows[0]["LoanStageId"].ToString(); if (sLoanStageID == string.Empty) { bIsSuccess = false; sErrorMsg = "Invalid loan stage id."; return; } iLoanStageID = Convert.ToInt32(sLoanStageID); #endregion bIsSuccess = true; if (!WorkflowManager.StageCompleted(iLoanStageID)) { sErrorMsg = "Completed task successfully."; return; } #region invoke PointManager.UpdateStage() //add by gdc 20111212 Bug #1306 LPWeb.BLL.PointFiles pfile = new PointFiles(); var model = pfile.GetModel(iLoanID); if (model != null && !string.IsNullOrEmpty(model.Name.Trim())) { #region check Point File Status first ServiceManager sm = new ServiceManager(); using (LP2ServiceClient service = sm.StartServiceClient()) { CheckPointFileStatusReq checkFileReq = new CheckPointFileStatusReq(); checkFileReq.hdr = new ReqHdr(); checkFileReq.hdr.UserId = CurrUser.iUserID; checkFileReq.hdr.SecurityToken = "SecurityToken"; checkFileReq.FileId = iLoanID; CheckPointFileStatusResp checkFileResp = service.CheckPointFileStatus(checkFileReq); if (checkFileResp == null || checkFileResp.hdr == null || !checkFileResp.hdr.Successful) { sErrorMsg = "Unable to get Point file status from Point Manager."; WorkflowManager.UnCompleteTask(iTaskID, CurrUser.iUserID); bIsSuccess = false; return; } if (checkFileResp.FileLocked) { sErrorMsg = checkFileResp.hdr.StatusInfo; WorkflowManager.UnCompleteTask(iTaskID, CurrUser.iUserID); bIsSuccess = false; return; } } #endregion #region UPdatePointFileStage WCF string sError = LoanTaskCommon.UpdatePointFileStage(iLoanID, this.CurrUser.iUserID, iLoanStageID); // the last one, sleep 1 second System.Threading.Thread.Sleep(1000); if (sError == string.Empty) // success { sErrorMsg = "Completed task successfully."; } else { sErrorMsg = "Completed task successfully but failed to update stage date in Point."; //sErrorMsg = "Failed to update point file stage: " + sError.Replace("\"", "\\\""); } #endregion } if (WorkflowManager.IsLoanClosed(iLoanID)) { LoanClosed = "Yes"; } return; #endregion } catch (System.ServiceModel.EndpointNotFoundException ee) { sErrorMsg = "Completed task successfully but failed to update stage date in Point."; return; } catch (Exception ex) { if (bIsSuccess) { sErrorMsg = "Completed task successfully but encountered an error:" + ex.Message; } else { sErrorMsg = "Failed to complete task, reason:" + ex.Message; } //sErrorMsg = "Exception happened when invoke WorkflowManager.CompleteTask: " + ex.ToString().Replace("\"", "\\\""); bIsSuccess = false; return; } finally { if (bIsSuccess) { result = "{\"ExecResult\":\"Success\",\"ErrorMsg\":\"" + sErrorMsg + "\",\"EmailTemplateID\":\"" + sEmailTemplateID + "\",\"TaskID\":\"" + sTaskID + "\",\"LoanClosed\":\"" + LoanClosed + "\"}"; } //result = "{\"ExecResult\":\"Success\",\"ErrorMsg\":\"\",\"EmailTemplateID\":\"" + sEmailTemplateID + "\",\"LoanClosed\":\"" + LoanClosed + "\"}"; else { result = "{\"ExecResult\":\"Failed\",\"ErrorMsg\":\"" + sErrorMsg + "\"}"; } this.Response.Write(result); } #endregion }
public PracticalScheduledState(WorkflowManager manager) : base(manager, WorkflowStates.PracticalScheduled) { }
/// <summary> /// Provides operations necessary to create and store new attachment. /// </summary> private void HandleAttachmentUpload(bool fieldAttachment) { TreeProvider tree = null; TreeNode node = null; // New attachment AttachmentInfo newAttachment = null; string message = string.Empty; bool fullRefresh = false; try { // Get the existing document if (DocumentID != 0) { // Get document tree = new TreeProvider(CMSContext.CurrentUser); node = DocumentHelper.GetDocument(DocumentID, tree); if (node == null) { throw new Exception("Given document doesn't exist!"); } } #region "Check permissions" if (this.CheckPermissions) { CheckNodePermissions(node); } #endregion // Check the allowed extensions CheckAllowedExtensions(); // Standard attachments if (DocumentID != 0) { // Ensure automatic check-in/check-out bool useWorkflow = false; bool autoCheck = false; WorkflowManager workflowMan = new WorkflowManager(tree); VersionManager vm = null; // Get workflow info WorkflowInfo wi = workflowMan.GetNodeWorkflow(node); // Check if the document uses workflow if (wi != null) { useWorkflow = true; autoCheck = !wi.UseCheckInCheckOut(CMSContext.CurrentSiteName); } // Check out the document if (autoCheck) { // Get original step Id int originalStepId = node.DocumentWorkflowStepID; // Get current step info WorkflowStepInfo si = workflowMan.GetStepInfo(node); if (si != null) { // Decide if full refresh is needed bool automaticPublish = wi.WorkflowAutoPublishChanges; string stepName = si.StepName.ToLower(); // Document is published or archived or uses automatic publish or step is different than original (document was updated) fullRefresh = (stepName == "published") || (stepName == "archived") || (automaticPublish && (stepName != "published")) || (originalStepId != node.DocumentWorkflowStepID); } vm = new VersionManager(tree); vm.CheckOut(node, node.IsPublished, true); } // Handle field attachment if (fieldAttachment) { newAttachment = DocumentHelper.AddAttachment(node, AttachmentGUIDColumnName, Guid.Empty, Guid.Empty, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); // Update attachment field DocumentHelper.UpdateDocument(node, tree); } // Handle grouped and unsorted attachments else { // Grouped attachment if (AttachmentGroupGUID != Guid.Empty) { newAttachment = DocumentHelper.AddGroupedAttachment(node, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } // Unsorted attachment else { newAttachment = DocumentHelper.AddUnsortedAttachment(node, AttachmentGUID, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } } // Check in the document if (autoCheck) { if (vm != null) { vm.CheckIn(node, null, null); } } // Log synchronization task if not under workflow if (!useWorkflow) { DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } // Temporary attachments if (FormGUID != Guid.Empty) { newAttachment = AttachmentManager.AddTemporaryAttachment(FormGUID, AttachmentGUIDColumnName, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, CMSContext.CurrentSiteID, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } // Ensure properties update if ((newAttachment != null) && !InsertMode) { AttachmentGUID = newAttachment.AttachmentGUID; } if (newAttachment == null) { throw new Exception("The attachment hasn't been created since no DocumentID or FormGUID was supplied."); } } catch (Exception ex) { message = ex.Message; lblError.Text = message; } finally { // Call aftersave javascript if exists if ((string.IsNullOrEmpty(message)) && (newAttachment != null)) { string closeString = "window.close();"; // Register wopener script ScriptHelper.RegisterWOpenerScript(Page); if (!String.IsNullOrEmpty(AfterSaveJavascript)) { string url = null; string saveName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, CMSContext.CurrentSiteName); if (node != null) { SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID); if (si != null) { bool usePermanent = SettingsKeyProvider.GetBoolValue(si.SiteName + ".CMSUsePermanentURLs"); if (usePermanent) { url = ResolveUrl(AttachmentManager.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName)); } else { url = ResolveUrl(AttachmentManager.GetAttachmentUrl(saveName, node.NodeAliasPath)); } } } else { url = ResolveUrl(AttachmentManager.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName)); } // Calling javascript function with parameters attachments url, name, width, height string jsParams = "('" + url + "', '" + newAttachment.AttachmentName + "', '" + newAttachment.AttachmentImageWidth + "', '" + newAttachment.AttachmentImageHeight + "');"; string script = "if ((wopener.parent != null) && (wopener.parent." + AfterSaveJavascript + " != null)){wopener.parent." + AfterSaveJavascript + jsParams + "}"; script += "else if (wopener." + AfterSaveJavascript + " != null){wopener." + AfterSaveJavascript + jsParams + "}"; ScriptHelper.RegisterStartupScript(this.Page, typeof(Page), "refreshAfterSave", ScriptHelper.GetScript(script + closeString)); } // Create attachment info string string attachmentInfo = ""; if ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (this.IncludeNewItemInfo)) { attachmentInfo = newAttachment.AttachmentGUID.ToString(); } // Ensure message text message = HTMLHelper.EnsureLineEnding(message, " "); // Call function to refresh parent window ScriptHelper.RegisterStartupScript(this.Page, typeof(Page), "refresh", ScriptHelper.GetScript("if ((wopener.parent != null) && (wopener.parent.InitRefresh_" + ParentElemID + " != null)){wopener.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", " + (fullRefresh ? "true" : "false") + ", false" + ((attachmentInfo != "") ? ", '" + attachmentInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}" + closeString)); } } }
/// <summary> /// Provides operations necessary to create and store new content file. /// </summary> private void HandleContentUpload() { TreeNode node = null; TreeProvider tree = null; string message = string.Empty; bool newDocumentCreated = false; try { if (this.NodeParentNodeID == 0) { throw new Exception(GetString("dialogs.document.parentmissing")); } // Check license limitations if (!LicenseHelper.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Documents, VersionActionEnum.Insert)) { throw new Exception(GetString("cmsdesk.documentslicenselimits")); } // Check if class exists DataClassInfo ci = DataClassInfoProvider.GetDataClass("CMS.File"); if (ci == null) { throw new Exception("Class 'CMS.File' not found."); } #region "Check permissions" // Get the node tree = new TreeProvider(CMSContext.CurrentUser); TreeNode parentNode = tree.SelectSingleNode(this.NodeParentNodeID, TreeProvider.ALL_CULTURES); if (parentNode != null) { if (!DataClassInfoProvider.IsChildClassAllowed(ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0), ci.ClassID)) { throw new Exception(GetString("Content.ChildClassNotAllowed")); } } // Check user permissions if (!RaiseOnCheckPermissions("Create", this)) { if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(NodeParentNodeID, NodeClassName)) { throw new Exception("You aren not allowed to create document of type '" + NodeClassName + "' in required location."); } } #endregion // Check the allowed extensions CheckAllowedExtensions(); // Create new document string fileName = Path.GetFileNameWithoutExtension(ucFileUpload.FileName); node = TreeNode.New("CMS.File", tree); node.DocumentCulture = CMSContext.PreferredCultureCode; node.DocumentName = fileName; // Load default values FormHelper.LoadDefaultValues(node); node.SetValue("FileDescription", ""); node.SetValue("FileName", fileName); node.SetValue("FileAttachment", Guid.Empty); // Set default template ID node.DocumentPageTemplateID = ci.ClassDefaultPageTemplateID; // Insert the document DocumentHelper.InsertDocument(node, parentNode, tree); newDocumentCreated = true; // Add the file DocumentHelper.AddAttachment(node, "FileAttachment", ucFileUpload.PostedFile, tree, this.ResizeToWidth, this.ResizeToHeight, this.ResizeToMaxSideSize); // Create default SKU if configured if (ModuleEntry.CheckModuleLicense(ModuleEntry.ECOMMERCE, URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert)) { node.CreateDefaultSKU(); } // Update the document DocumentHelper.UpdateDocument(node, tree); WorkflowManager workflowManager = new WorkflowManager(tree); // Get workflow info WorkflowInfo workflowInfo = workflowManager.GetNodeWorkflow(node); // Check if auto publish changes is allowed if ((workflowInfo != null) && workflowInfo.WorkflowAutoPublishChanges && !workflowInfo.UseCheckInCheckOut(CMSContext.CurrentSiteName)) { // Automatically publish document workflowManager.AutomaticallyPublish(node, workflowInfo, null); } } catch (Exception ex) { // Delete the document if something failed if (newDocumentCreated && (node != null) && (node.DocumentID > 0)) { DocumentHelper.DeleteDocument(node, tree, false, true, true); } message = ex.Message; lblError.Text = message; } finally { if (string.IsNullOrEmpty(message)) { // Create node info string string nodeInfo = ""; if ((node != null) && (node.NodeID > 0) && (this.IncludeNewItemInfo)) { nodeInfo = node.NodeID.ToString(); } // Ensure message text message = HTMLHelper.EnsureLineEnding(message, " "); // Register wopener script ScriptHelper.RegisterWOpenerScript(Page); // Call function to refresh parent window ScriptHelper.RegisterStartupScript(this.Page, typeof(Page), "refresh", ScriptHelper.GetScript("if ((wopener.parent != null) && (wopener.parent.InitRefresh_" + ParentElemID + " != null)){wopener.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", false, false" + ((nodeInfo != "") ? ", '" + nodeInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}window.close();")); } } }
protected DataSet gridAttachments_OnDataReload(string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords) { string where = null; Guid attachmentFormGUID = Guid.Empty; string whereCondition = GetWhereConditionInternal(); int documentVersionHistoryID = UsesWorkflow ? VersionHistoryID : 0; // Grouped attachments if (GroupGUID != Guid.Empty) { // Combine where conditions where = String.Format("(AttachmentGroupGUID='{0}')", GroupGUID); } // Unsorted attachments else { where = "(AttachmentIsUnsorted = 1)"; } // Temporary attachments if ((attachmentFormGUID != Guid.Empty) && (documentVersionHistoryID == 0)) { where += String.Format(" AND (AttachmentFormGUID='{0}')", FormGUID); } // Else document attachments else { if (documentVersionHistoryID == 0) { // Ensure current site name if (string.IsNullOrEmpty(SiteName)) { SiteName = CMSContext.CurrentSiteName; } if (Node != null) { where += String.Format(" AND (AttachmentDocumentID = {0})", Node.DocumentID); // Get attachments for latest version if not live site if (!IsLiveSite) { WorkflowManager wm = new WorkflowManager(TreeProvider); WorkflowInfo wi = wm.GetNodeWorkflow(Node); if (wi != null) { documentVersionHistoryID = Node.DocumentCheckedOutVersionHistoryID; } } } else { return null; } } } // Ensure additional where condition whereCondition = SqlHelperClass.AddWhereCondition(whereCondition, where); // Ensure [AttachmentID] column List<String> cols = new List<string>(columns.Split(new char[] { ',', ';' })); if (!cols.Contains("AttachmentID") && !cols.Contains("[AttachmentID]")) { columns = SqlHelperClass.MergeColumns("AttachmentID", columns); } DataSet ds = null; // Get attachments for published document if (documentVersionHistoryID == 0) { currentOrder = "AttachmentOrder, AttachmentName, AttachmentID"; ds = AttachmentManager.GetAttachments(whereCondition, currentOrder, true, currentTopN, columns); } else { currentOrder = "AttachmentOrder, AttachmentName, AttachmentHistoryID"; VersionManager vm = new VersionManager(TreeProvider); ds = vm.GetVersionAttachments(documentVersionHistoryID, whereCondition, currentOrder, true, currentTopN, columns.Replace("AttachmentID", "AttachmentHistoryID")); } // Ensure consistent ID column name if (!DataHelper.DataSourceIsEmpty(ds)) { ds.Tables[0].Columns[0].ColumnName = "AttachmentID"; } return ds; }
/// <summary> /// Publishes document(s). /// </summary> private void PublishAll(object parameter) { if (parameter == null) { return; } TreeProvider tree = new TreeProvider(currentUser); tree.AllowAsyncActions = false; try { // Begin log AddLog(ResHelper.GetString("content.publishingdocuments", currentCulture)); string[] parameters = ((string)parameter).Split(';'); string siteName = parameters[1]; // Get identifiers int[] workNodes = nodeIds.ToArray(); // Prepare the where condition string where = SqlHelperClass.GetWhereCondition("NodeID", workNodes); string columns = SqlHelperClass.MergeColumns(TreeProvider.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture"); // Get cultures string cultureCode = chkAllCultures.Checked ? TreeProvider.ALL_CULTURES : parameters[0]; // Get the documents DataSet documents = tree.SelectNodes(siteName, "/%", cultureCode, false, null, where, "NodeAliasPath DESC", TreeProvider.ALL_LEVELS, false, 0, columns); // Create instance of workflow manager class WorkflowManager wm = new WorkflowManager(tree); if (!DataHelper.DataSourceIsEmpty(documents)) { foreach (DataRow nodeRow in documents.Tables[0].Rows) { // Get the current document TreeNode node = GetDocument(tree, siteName, nodeRow); // Publish document if (PerformPublish(wm, tree, siteName, nodeRow)) { return; } // Process underlying documents if (chkUnderlying.Checked && (node.NodeChildNodesCount > 0)) { if (PublishSubDocuments(node, tree, wm, cultureCode, siteName)) { return; } } } } else { AddError(ResHelper.GetString("content.nothingtopublish", currentCulture)); } } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state != CMSThread.ABORT_REASON_STOP) { // Log error LogExceptionToEventLog(ResHelper.GetString("content.publishfailed", currentCulture), ex); } } catch (Exception ex) { // Log error LogExceptionToEventLog(ResHelper.GetString("content.publishfailed", currentCulture), ex); } }
/// <summary> /// Publishes document. /// </summary> /// <param name="node">Node to publish</param> /// <param name="wm">Workflow manager</param> /// <param name="currentStep">Current workflow step</param> /// <returns>Whether node is already published</returns> private static bool Publish(TreeNode node, WorkflowManager wm, WorkflowStepInfo currentStep) { bool toReturn = true; if (currentStep != null) { // For archive step start new version if (currentStep.StepName.ToLower() == "archived") { VersionManager vm = new VersionManager(node.TreeProvider); currentStep = vm.CheckOut(node, node.IsPublished, true); vm.CheckIn(node, null, null); } // Approve until the step is publish while ((currentStep != null) && (currentStep.StepName.ToLower() != "published")) { currentStep = wm.MoveToNextStep(node, string.Empty); toReturn = false; } // Document is already published, check if still under workflow if (toReturn && (currentStep.StepName.ToLower() == "published")) { WorkflowScopeInfo wsi = wm.GetNodeWorkflowScope(node); if (wsi == null) { DocumentHelper.ClearWorkflowInformation(node); VersionManager vm = new VersionManager(node.TreeProvider); vm.RemoveWorkflow(node); } } } return toReturn; }
/// <summary> /// Saves metadata and file name of attachment. /// </summary> /// <param name="newFileName">New attachment file name</param> /// <returns>Returns True if attachment was successfully saved.</returns> private bool SaveAttachment(string newFileName) { bool saved = false; // Save new data try { AttachmentInfo attachmentInfo = InfoObject as AttachmentInfo; if (attachmentInfo != null) { // Set new file name if (!string.IsNullOrEmpty(newFileName)) { string name = newFileName + attachmentInfo.AttachmentExtension; // Use correct identifier if attachment is under workflow int identifier = VersionHistoryID > 0 ? AttachmentHistoryID : attachmentInfo.AttachmentID; if (IsAttachmentNameUnique(identifier, attachmentInfo.AttachmentExtension, name)) { attachmentInfo.AttachmentName = name; } else { // Attachment already exists. ShowError(GetString("img.errors.fileexists")); return(false); } } // Ensure automatic check-in/ check-out bool useWorkflow = false; bool autoCheck = false; WorkflowManager workflowMan = WorkflowManager.GetInstance(TreeProvider); if (!nodeIsParent && (Node != null)) { // Get workflow info WorkflowInfo wi = workflowMan.GetNodeWorkflow(Node); // Check if the document uses workflow if (wi != null) { useWorkflow = true; autoCheck = !wi.UseCheckInCheckOut(SiteName); } // Check out the document if (autoCheck) { VersionManager.CheckOut(Node, Node.IsPublished, true); VersionHistoryID = Node.DocumentCheckedOutVersionHistoryID; } // Workflow has been lost, get published attachment if (useWorkflow && (VersionHistoryID == 0)) { attachmentInfo = AttachmentInfoProvider.GetAttachmentInfo(attachmentInfo.AttachmentGUID, SiteName); } } if (attachmentInfo != null) { // Set filename title and description attachmentInfo.AttachmentTitle = ObjectTitle; attachmentInfo.AttachmentDescription = ObjectDescription; // Document uses workflow and document is already saved (attachment is not temporary) if (!nodeIsParent && (VersionHistoryID > 0)) { attachmentInfo.AllowPartialUpdate = true; VersionManager.SaveAttachmentVersion(attachmentInfo, VersionHistoryID); } else { // Update without binary attachmentInfo.AllowPartialUpdate = true; AttachmentInfoProvider.SetAttachmentInfo(attachmentInfo); // Log the synchronization and search task for the document if (!nodeIsParent && (Node != null)) { // Update search index for given document if (DocumentHelper.IsSearchTaskCreationAllowed(Node)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, Node.GetSearchID(), Node.DocumentID); } DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider); } } if (!nodeIsParent && (Node != null)) { // Check in the document if (autoCheck) { if (VersionManager != null) { if (VersionHistoryID > 0 && (Node != null)) { VersionManager.CheckIn(Node, null, null); } } } } saved = true; string fullRefresh = "false"; if (autoCheck || (Node == null)) { fullRefresh = "true"; } // Refresh parent update panel LtlScript.Text = ScriptHelper.GetScript("RefreshMetaData(" + ScriptHelper.GetString(ExternalControlID) + ", '" + fullRefresh + "', '" + attachmentInfo.AttachmentGUID + "', 'refresh')"); } } } catch (Exception ex) { ShowError(GetString("metadata.errors.processing")); EventLogProvider.LogException("Metadata editor", "SAVEATTACHMENT", ex); } return(saved); }
/// <summary> /// Provides operations necessary to create and store new attachment. /// </summary> /// <param name="args">Upload arguments.</param> /// <param name="context">HttpContext instance.</param> private void HandleAttachmentUpload(UploaderHelper args, HttpContext context) { AttachmentInfo newAttachment = null; bool refreshTree = false; try { args.IsExtensionAllowed(); // Get existing document if (args.AttachmentArgs.DocumentID != 0) { node = DocumentHelper.GetDocument(args.AttachmentArgs.DocumentID, TreeProvider); if (node == null) { throw new Exception("Given document doesn't exist!"); } else { #region "Check permissions" // For new document if (args.AttachmentArgs.FormGuid != Guid.Empty) { if (args.AttachmentArgs.ParentNodeID == 0) { throw new Exception(ResHelper.GetString("attach.document.parentmissing")); } if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(args.AttachmentArgs.ParentNodeID, args.AttachmentArgs.NodeClassName)) { throw new Exception(ResHelper.GetString("attach.actiondenied")); } } // For existing document else if (args.AttachmentArgs.DocumentID > 0) { if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { throw new Exception(ResHelper.GetString("attach.actiondenied")); } } #endregion args.IsExtensionAllowed(); // Check out the document if (AutoCheck && args.IsLastUpload) { // Get current step info WorkflowStepInfo si = WorkflowManager.GetStepInfo(node); if (si != null) { // Decide if full refresh is needed args.FullRefresh = si.StepIsPublished || si.StepIsArchived; } VersionManager.CheckOut(node, node.IsPublished, true); } // Handle field attachment if (args.AttachmentArgs.FieldAttachment) { // Extension of CMS file before saving string oldExtension = node.DocumentType; newAttachment = DocumentHelper.AddAttachment(node, args.AttachmentArgs.AttachmentGuidColumnName, Guid.Empty, Guid.Empty, args.FilePath, TreeProvider, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide); DocumentHelper.UpdateDocument(node, TreeProvider); // Different extension if ((oldExtension != null) && !oldExtension.EqualsCSafe(node.DocumentType, true)) { refreshTree = true; } } else { // Handle grouped and unsorted attachments if (args.AttachmentArgs.AttachmentGroupGuid != Guid.Empty) { // Grouped attachment newAttachment = DocumentHelper.AddGroupedAttachment(node, args.AttachmentArgs.AttachmentGUID, args.AttachmentArgs.AttachmentGroupGuid, args.FilePath, TreeProvider, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide); } else { // Unsorted attachment newAttachment = DocumentHelper.AddUnsortedAttachment(node, args.AttachmentArgs.AttachmentGUID, args.FilePath, TreeProvider, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide); } // Log synchronization task if not under workflow if (wi == null) { DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, TreeProvider); } } // Check in the document if (AutoCheck) { VersionManager.CheckIn(node, null, null); } } } else if (args.AttachmentArgs.FormGuid != Guid.Empty) { newAttachment = AttachmentInfoProvider.AddTemporaryAttachment(args.AttachmentArgs.FormGuid, args.AttachmentArgs.AttachmentGuidColumnName, args.AttachmentArgs.AttachmentGUID, args.AttachmentArgs.AttachmentGroupGuid, args.FilePath, CMSContext.CurrentSiteID, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide); } if (newAttachment == null) { throw new Exception("The attachment hasn't been created since no DocumentID or FormGUID was supplied."); } } catch (Exception ex) { // Log the exception EventLogProvider.LogException("Content", "UploadAttachment", ex); // Store exception message args.Message = ex.Message; } finally { // Call after save javascript if exists if (!string.IsNullOrEmpty(args.AfterSaveJavascript)) { if ((args.Message == string.Empty) && (newAttachment != null)) { string url = null; string saveName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, CMSContext.CurrentSiteName); if (node != null) { SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID); if (si != null) { url = SettingsKeyProvider.GetBoolValue(si.SiteName + ".CMSUsePermanentURLs") ? URLHelper.ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName)) : URLHelper.ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(saveName, node.NodeAliasPath)); } } else { url = URLHelper.ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName)); } Hashtable obj = new Hashtable(); if (ImageHelper.IsImage(newAttachment.AttachmentExtension)) { obj[DialogParameters.IMG_URL] = url; obj[DialogParameters.IMG_TOOLTIP] = newAttachment.AttachmentName; obj[DialogParameters.IMG_WIDTH] = newAttachment.AttachmentImageWidth; obj[DialogParameters.IMG_HEIGHT] = newAttachment.AttachmentImageHeight; } else if (MediaHelper.IsFlash(newAttachment.AttachmentExtension)) { obj[DialogParameters.OBJECT_TYPE] = "flash"; obj[DialogParameters.FLASH_URL] = url; obj[DialogParameters.FLASH_EXT] = newAttachment.AttachmentExtension; obj[DialogParameters.FLASH_TITLE] = newAttachment.AttachmentName; obj[DialogParameters.FLASH_WIDTH] = DEFAULT_OBJECT_WIDTH; obj[DialogParameters.FLASH_HEIGHT] = DEFAULT_OBJECT_HEIGHT; } else if (MediaHelper.IsAudioVideo(newAttachment.AttachmentExtension)) { obj[DialogParameters.OBJECT_TYPE] = "audiovideo"; obj[DialogParameters.AV_URL] = url; obj[DialogParameters.AV_EXT] = newAttachment.AttachmentExtension; obj[DialogParameters.AV_WIDTH] = DEFAULT_OBJECT_WIDTH; obj[DialogParameters.AV_HEIGHT] = DEFAULT_OBJECT_HEIGHT; } else { obj[DialogParameters.LINK_URL] = url; obj[DialogParameters.LINK_TEXT] = newAttachment.AttachmentName; } // Calling javascript function with parameters attachments url, name, width, height args.AfterScript += string.Format(@"{5} if (window.{0}) {{ window.{0}('{1}', '{2}', '{3}', '{4}', obj); }} else if((window.parent != null) && window.parent.{0}) {{ window.parent.{0}('{1}', '{2}', '{3}', '{4}', obj); }}", args.AfterSaveJavascript, url, newAttachment.AttachmentName, newAttachment.AttachmentImageWidth, newAttachment.AttachmentImageHeight, CMSDialogHelper.GetDialogItem(obj)); } else { args.AfterScript += ScriptHelper.GetAlertScript(args.Message, false); } } // Create attachment info string string attachmentInfo = ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (args.IncludeNewItemInfo)) ? String.Format("'{0}', ", newAttachment.AttachmentGUID) : ""; // Create after script and return it to the silverlight application, this script will be evaluated by the SL application in the end args.AfterScript += string.Format(@" if (window.InitRefresh_{0}) {{ window.InitRefresh_{0}('{1}', {2}, {3}, {4}); }} else {{ if ('{1}' != '') {{ alert('{1}'); }} }}", args.ParentElementID, ScriptHelper.GetString(args.Message.Trim(), false), args.FullRefresh.ToString().ToLowerCSafe(), refreshTree.ToString().ToLowerCSafe(), attachmentInfo + (args.IsInsertMode ? "'insert'" : "'update'")); args.AddEventTargetPostbackReference(); context.Response.Write(args.AfterScript); context.Response.Flush(); } }
protected void Page_Load(object sender, EventArgs e) { #region 检查必要参数 string sErrorJs = string.Empty; if (this.Request.QueryString["CloseDialogCodes"] == null) { sErrorJs = "window.parent.RefreshPage();"; } else { sErrorJs = this.Request.QueryString["CloseDialogCodes"] + ";"; } bool bIsValid = PageCommon.ValidateQueryString(this, "LoanID", QueryStringType.ID); if (bIsValid == false) { PageCommon.RegisterJsMsg(this, "Missing required query string.", sErrorJs); return; } this.iLoanID = Convert.ToInt32(this.Request.QueryString["LoanID"]); #endregion #region 校验LoanId DataTable LoanInfo = this.LoanManager.GetLoanInfo(this.iLoanID); if (LoanInfo.Rows.Count == 0) { PageCommon.RegisterJsMsg(this, "Invalid required query string.", sErrorJs); return; } // 存储Loan.EstCloseDate if (LoanInfo.Rows[0]["EstCloseDate"] != DBNull.Value) { this.hdnEstCloseDate.Value = Convert.ToDateTime(LoanInfo.Rows[0]["EstCloseDate"]).ToString("MM/dd/yyyy"); } this.iCurrentLoanStageId = WorkflowManager.GetCurrentLoanStageId(this.iLoanID); bIsValid = PageCommon.ValidateQueryString(this, "Stage", QueryStringType.ID); if (bIsValid == true) { int iout = 0; string sStage = this.Request.QueryString["Stage"]; if (Int32.TryParse(sStage, out iout)) { this.iCurrentLoanStageId = iout; } } #endregion if (this.IsPostBack == false) { #region 加载Owner DataTable OwnerList = this.LoanTaskManager.GetLoanTaskOwers(this.iLoanID); DataRow EmptyOwnerRow = OwnerList.NewRow(); EmptyOwnerRow["UserID"] = 0; EmptyOwnerRow["FullName"] = "-- select --"; OwnerList.Rows.InsertAt(EmptyOwnerRow, 0); this.ddlOwner.DataSource = OwnerList; this.ddlOwner.DataBind(); // 绑定Owner this.ddlOwner.SelectedValue = this.CurrUser.iUserID.ToString(); #endregion #region 加载ddlTaskList for TaskNaem LeadTaskList LeadTaskListMgr = new LeadTaskList(); string sOrderBy = string.Empty; if (this.CurrUser.SortTaskPickList == "S") { sOrderBy = "SequenceNumber"; } else { sOrderBy = "TaskName"; } DataTable LeadTaskList1 = LeadTaskListMgr.GetLeadTaskList(" and Enabled=1", sOrderBy); DataRow EmptyTaskRow = LeadTaskList1.NewRow(); EmptyTaskRow["TaskName"] = "-- select --"; LeadTaskList1.Rows.InsertAt(EmptyTaskRow, 0); this.ddlTaskList.DataSource = LeadTaskList1; this.ddlTaskList.DataBind(); #endregion // set default value this.txtDueDate.Text = DateTime.Now.ToString("MM/dd/yyyy"); //this.txtDueTime.Text = DateTime.Now.AddMinutes(15).ToShortTimeString(); this.ddlDueTime_hour.SelectedValue = DateTime.Now.Hour.ToString("00"); this.ddlDueTime_min.SelectedValue = (DateTime.Now.AddMinutes(15).Minute / 5 * 5).ToString(); #region 加载Prerequisite DataTable PrerequisiteList = this.LoanTaskManager.GetPrerequisiteList(" and FileID=" + this.iLoanID + " and LoanStageId = " + iCurrentLoanStageId + " and PrerequisiteTaskId is null"); DataRow NonePrerequisiteRow = PrerequisiteList.NewRow(); NonePrerequisiteRow["LoanTaskId"] = 0; NonePrerequisiteRow["Name"] = "None"; PrerequisiteList.Rows.InsertAt(NonePrerequisiteRow, 0); this.ddlPrerequisite.DataSource = PrerequisiteList; this.ddlPrerequisite.DataBind(); this.ddlPrerequisite2.DataSource = PrerequisiteList; this.ddlPrerequisite2.DataBind(); #endregion #region 加载email template Template_Email EmailTempManager = new Template_Email(); DataTable EmailTemplates = EmailTempManager.GetEmailTemplate(" and Enabled = 1"); DataRow NoneEmailTemplateRow = EmailTemplates.NewRow(); NoneEmailTemplateRow["TemplEmailId"] = 0; NoneEmailTemplateRow["Name"] = "None"; EmailTemplates.Rows.InsertAt(NoneEmailTemplateRow, 0); this.ddlWarningEmail.DataSource = EmailTemplates; this.ddlWarningEmail.DataBind(); this.ddlOverdueEmail.DataSource = EmailTemplates; this.ddlOverdueEmail.DataBind(); this.ddlEmailTemplate.DataSource = EmailTemplates; this.ddlEmailTemplate.DataBind(); #endregion #region completion email list gridCompletetionEmails.DataSource = null; gridCompletetionEmails.DataBind(); #endregion #region Stage //Template_Stages stage = new Template_Stages(); //var dtStage = stage.GetStageTemplateList(" And [Enabled] = 1 order by SequenceNumber "); LoanStages ls = new LoanStages(); var dtStage = ls.GetLoanStageSetupInfo(iLoanID); ddlStage.DataSource = dtStage; ddlStage.DataBind(); ddlStage.SelectedValue = this.iCurrentLoanStageId.ToString(); #endregion } }
protected void btnSave_Click(object sender, EventArgs e) { Model.ProspectTasks prospectTasks = null; if ("0" == Mode) { prospectTasks = new Model.ProspectTasks(); GetValue(ref prospectTasks); // check duplicate if (ptManager.IsProspectTaskNameExists(-1, prospectTasks.TaskName)) { PageCommon.AlertMsg(this, "Duplicate task name."); return; } try { // save the new added prospect task info int iNewProspectID= ptManager.Add(prospectTasks); ProspectTaskId = iNewProspectID; bool bAlert = WorkflowManager.CreateProspectTaskAlerts(iNewProspectID); Mode = "1"; this.btnDelete.Enabled = true; this.btnClone.Enabled = true; //ClientFun("savesuccess", "alert('Saved successfully!');"); PageCommon.RegisterJsMsg(this, "Saved successfully!", "parent.closeProspectTaskSetupWin();"); } catch (Exception ex) { ClientFun("failedToSave", "alert('Failed to save task info, please check your data and try again.');"); LPLog.LogMessage(LogType.Logerror, "Error occured when save the task: " + ex.Message); return; } } else if ("1" == Mode) { prospectTasks = ptManager.GetModel(ProspectTaskId.Value); GetValue(ref prospectTasks); // check name duplicate if (ptManager.IsProspectTaskNameExists(ProspectTaskId.Value, prospectTasks.TaskName)) { ClientFun("duplicateName", "alert('Duplicate task name.');"); return; } try { // update current prospect task info ptManager.Update(prospectTasks); ptManager.CheckProspectTaskAlert(Convert.ToInt32(ProspectTaskId)); //ClientFun("savesuccess", "alert('Saved successfully!');"); PageCommon.RegisterJsMsg(this, "Saved successfully!", "parent.closeProspectTaskSetupWin();"); } catch (Exception ex) { ClientFun("failedToSave", "alert('Failed to save the task, please check your data and try again.');"); LPLog.LogMessage(LogType.Logerror, "Error occured when save the task: " + ex.Message); return; } } }
/// <summary> /// Reloads the page data. /// </summary> protected void ReloadData() { string where = string.Format("StepType IN ({0}, {1}, {2})", (int)WorkflowStepTypeEnum.DocumentEdit, (int)WorkflowStepTypeEnum.DocumentPublished, (int)WorkflowStepTypeEnum.DocumentArchived); // Hide custom steps if license doesn't allow them or check automatically publish changes if (!WorkflowInfoProvider.IsCustomStepAllowed()) { gridSteps.WhereCondition = SqlHelper.AddWhereCondition(gridSteps.WhereCondition, where); } // Hide custom steps (without actual step) if functionality 'Automatically publish changes' is allowed else if ((WorkflowInfo != null) && WorkflowInfo.WorkflowAutoPublishChanges) { gridSteps.WhereCondition = SqlHelper.AddWhereCondition(gridSteps.WhereCondition, where); // Get current step info WorkflowStepInfo currentStep = WorkflowManager.GetStepInfo(Node); if (currentStep != null) { if (!currentStep.StepIsDefault) { gridSteps.WhereCondition = SqlHelper.AddWhereCondition(gridSteps.WhereCondition, "(StepName = '" + SqlHelper.EscapeQuotes(currentStep.StepName) + "')", "OR"); } } } // Do not display steps without order - advanced workflow steps gridSteps.WhereCondition = SqlHelper.AddWhereCondition(gridSteps.WhereCondition, "StepOrder IS NOT NULL"); // Prepare the query parameters QueryDataParameters parameters = new QueryDataParameters(); parameters.Add("@DocumentID", 0); // Prepare the steps query parameters QueryDataParameters stepsParameters = new QueryDataParameters(); stepsParameters.Add("@StepWorkflowID", 0); if (Node != null) { // Check read permissions if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied) { RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), Node.NodeAliasPath)); } // Prepare parameters parameters.Add("@DocumentID", Node.DocumentID); currentStepId = ValidationHelper.GetInteger(Node.GetValue("DocumentWorkflowStepID"), 0); if (WorkflowInfo != null) { plcBasic.Visible = WorkflowInfo.IsBasic; plcAdvanced.Visible = !plcBasic.Visible; if (plcAdvanced.Visible) { ucDesigner.WorkflowID = WorkflowInfo.WorkflowID; ucDesigner.SelectedStepID = currentStepId; ucDesigner.WorkflowType = WorkflowTypeEnum.Approval; } else { stepsParameters.Add("@StepWorkflowID", WorkflowInfo.WorkflowID); } // Initialize grids gridHistory.OnExternalDataBound += gridHistory_OnExternalDataBound; gridSteps.OnExternalDataBound += gridSteps_OnExternalDataBound; gridHistory.ZeroRowsText = GetString("workflowproperties.nohistoryyet"); } } else { pnlWorkflow.Visible = false; } // Initialize query parameters of grids gridSteps.QueryParameters = stepsParameters; gridHistory.QueryParameters = parameters; SetupForm(); gridHistory.ReloadData(); if (plcBasic.Visible) { gridSteps.ReloadData(); } }
protected void gridHistory_OnAction(string actionName, object actionArgument) { int versionHistoryId = ValidationHelper.GetInteger(actionArgument, 0); switch (actionName.ToLowerInvariant()) { case "rollback": if (versionHistoryId > 0) { if (CheckedOutByUserID > 0) { // Document is checked out ShowError(GetString("VersionProperties.CannotRollbackCheckedOut")); } else { // Check permissions if (!WorkflowManager.CheckStepPermissions(Node, WorkflowActionEnum.Approve) || !CanModify || (CheckedOutByAnotherUser && !CanCheckIn) || (versionHistoryId == Node.DocumentCheckedOutVersionHistoryID)) { ShowError(String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), Node.NodeAliasPath)); } else { try { VersionManager.RollbackVersion(versionHistoryId); if (!IsLiveSite) { // Refresh content tree (for the case that document name has been changed) ScriptHelper.RefreshTree(Page, NodeID, Node.NodeParentID); } // Refresh node instance InvalidateNode(); ShowConfirmation(GetString("VersionProperties.RollbackOK")); } catch (Exception ex) { ShowError(ex.Message); } } } } break; case "destroy": if (versionHistoryId > 0) { if (Node != null) { // Check permissions if (!CanDestroy || (CheckedOutByAnotherUser && !CanCheckIn) || (versionHistoryId == Node.DocumentCheckedOutVersionHistoryID)) { ShowError(GetString("History.ErrorNotAllowedToDestroy")); } else { // Refresh node instance InvalidateNode(); VersionManager.DestroyDocumentVersion(versionHistoryId); ShowConfirmation(GetString("VersionProperties.DestroyOK")); } } } break; } }
public WorkflowController(WorkflowManager manager) { Manager = manager; }
/// <summary> /// Performs necessary checks and publishes document. /// </summary> /// <returns>TRUE if operation fails and whole process should be canceled.</returns> private bool PerformPublish(WorkflowManager wm, TreeProvider tree, string siteName, DataRow nodeRow) { string aliasPath = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty); return PerformPublish(wm, tree, GetDocument(tree, siteName, nodeRow), aliasPath); }
/// <summary> /// Provides operations necessary to create and store new attachment. /// </summary> private void HandleAttachmentUpload(bool fieldAttachment) { TreeProvider tree = null; TreeNode node = null; // New attachment AttachmentInfo newAttachment = null; string message = string.Empty; bool fullRefresh = false; try { // Get the existing document if (DocumentID != 0) { // Get document tree = new TreeProvider(CMSContext.CurrentUser); node = DocumentHelper.GetDocument(DocumentID, tree); if (node == null) { throw new Exception("Given document doesn't exist!"); } } #region "Check permissions" if (CheckPermissions) { CheckNodePermissions(node); } #endregion // Check the allowed extensions CheckAllowedExtensions(); // Standard attachments if (DocumentID != 0) { // Ensure automatic check-in/check-out bool useWorkflow = false; bool autoCheck = false; bool checkin = false; WorkflowManager workflowMan = WorkflowManager.GetInstance(tree); VersionManager vm = null; // Get workflow info WorkflowInfo wi = workflowMan.GetNodeWorkflow(node); // Check if the document uses workflow if (wi != null) { useWorkflow = true; autoCheck = !wi.UseCheckInCheckOut(CMSContext.CurrentSiteName); } // Check out the document if (autoCheck) { // Get original step Id int originalStepId = node.DocumentWorkflowStepID; // Get current step info WorkflowStepInfo si = workflowMan.GetStepInfo(node); if (si != null) { // Decide if full refresh is needed bool automaticPublish = wi.WorkflowAutoPublishChanges; // Document is published or archived or uses automatic publish or step is different than original (document was updated) fullRefresh = si.StepIsPublished || si.StepIsArchived || (automaticPublish && !si.StepIsPublished) || (originalStepId != node.DocumentWorkflowStepID); } vm = VersionManager.GetInstance(tree); var step = vm.CheckOut(node, node.IsPublished, true); checkin = (step != null); } // Handle field attachment if (fieldAttachment) { newAttachment = DocumentHelper.AddAttachment(node, AttachmentGUIDColumnName, Guid.Empty, Guid.Empty, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); // Update attachment field DocumentHelper.UpdateDocument(node, tree); } // Handle grouped and unsorted attachments else { // Grouped attachment if (AttachmentGroupGUID != Guid.Empty) { newAttachment = DocumentHelper.AddGroupedAttachment(node, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } // Unsorted attachment else { newAttachment = DocumentHelper.AddUnsortedAttachment(node, AttachmentGUID, ucFileUpload.PostedFile, tree, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } } // Check in the document if (autoCheck) { if ((vm != null) && checkin) { vm.CheckIn(node, null, null); } } // Log synchronization task if not under workflow if (!useWorkflow) { DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, tree); } } // Temporary attachments if (FormGUID != Guid.Empty) { newAttachment = AttachmentInfoProvider.AddTemporaryAttachment(FormGUID, AttachmentGUIDColumnName, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, CMSContext.CurrentSiteID, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } // Ensure properties update if ((newAttachment != null) && !InsertMode) { AttachmentGUID = newAttachment.AttachmentGUID; } if (newAttachment == null) { throw new Exception("The attachment hasn't been created since no DocumentID or FormGUID was supplied."); } } catch (Exception ex) { message = ex.Message; lblError.Text = message; } finally { // Call aftersave javascript if exists if ((string.IsNullOrEmpty(message)) && (newAttachment != null)) { string closeString = "CloseDialog();"; // Register wopener script ScriptHelper.RegisterWOpenerScript(Page); if (!String.IsNullOrEmpty(AfterSaveJavascript)) { string url = null; string saveName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, CMSContext.CurrentSiteName); if (node != null) { SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID); if (si != null) { bool usePermanent = SettingsKeyProvider.GetBoolValue(si.SiteName + ".CMSUsePermanentURLs"); if (usePermanent) { url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName)); } else { url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(saveName, node.NodeAliasPath)); } } } else { url = ResolveUrl(AttachmentInfoProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName)); } // Calling javascript function with parameters attachments url, name, width, height string jsParams = "('" + url + "', '" + newAttachment.AttachmentName + "', '" + newAttachment.AttachmentImageWidth + "', '" + newAttachment.AttachmentImageHeight + "');"; string script = "if ((wopener.parent != null) && (wopener.parent." + AfterSaveJavascript + " != null)){wopener.parent." + AfterSaveJavascript + jsParams + "}"; script += "else if (wopener." + AfterSaveJavascript + " != null){wopener." + AfterSaveJavascript + jsParams + "}"; ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refreshAfterSave", ScriptHelper.GetScript(script + closeString)); } // Create attachment info string string attachmentInfo = ""; if ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (IncludeNewItemInfo)) { attachmentInfo = newAttachment.AttachmentGUID.ToString(); } // Ensure message text message = HTMLHelper.EnsureLineEnding(message, " "); // Call function to refresh parent window ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refresh", ScriptHelper.GetScript("if ((wopener.parent != null) && (wopener.parent.InitRefresh_" + ParentElemID + " != null)){wopener.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", " + (fullRefresh ? "true" : "false") + ", false" + ((attachmentInfo != "") ? ", '" + attachmentInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}" + closeString)); } } }
/// <summary> /// Handles attachment action. /// </summary> /// <param name="argument">Argument coming from upload control</param> private void HandleAttachmentAction(string argument, bool isUpdate) { // Get attachment URL first Guid attachmentGuid = ValidationHelper.GetGuid(argument, Guid.Empty); if (attachmentGuid != Guid.Empty) { // Get attachment info TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Ensure site information SiteInfo si = CMSContext.CurrentSite; if ((TreeNodeObj != null) && (si.SiteID != TreeNodeObj.NodeSiteID)) { si = SiteInfoProvider.GetSiteInfo(TreeNodeObj.NodeSiteID); } AttachmentInfo ai = DocumentHelper.GetAttachment(attachmentGuid, tree, si.SiteName, false); if (ai != null) { string nodeAliasPath = (TreeNodeObj != null) ? TreeNodeObj.NodeAliasPath : null; if (CMSDialogHelper.IsItemSelectable(SelectableContent, ai.AttachmentExtension)) { // Get attachment URL string url = mediaView.GetAttachmentItemUrl(ai.AttachmentGUID, ai.AttachmentName, nodeAliasPath, 0, 0, 0); // Remember last selected attachment GUID if (SourceType == MediaSourceEnum.DocumentAttachments) { LastAttachmentGuid = ai.AttachmentGUID; } // Get the node workflow int versionHistoryId = 0; if (TreeNodeObj != null) { WorkflowManager wm = new WorkflowManager(TreeNodeObj.TreeProvider); WorkflowInfo wi = wm.GetNodeWorkflow(TreeNodeObj); if (wi != null) { // Ensure the document version VersionManager vm = new VersionManager(TreeNodeObj.TreeProvider); versionHistoryId = vm.EnsureVersion(TreeNodeObj, TreeNodeObj.IsPublished); } } MediaItem item = InitializeMediaItem(ai.AttachmentName, ai.AttachmentExtension, ai.AttachmentImageWidth, ai.AttachmentImageHeight, ai.AttachmentSize, url, null, versionHistoryId, 0, ""); SelectMediaItem(item); ItemToColorize = attachmentGuid; ColorizeRow(ItemToColorize.ToString()); } else { // Unselect old attachment and clear properties ColorizeRow(""); Properties.ClearProperties(true); pnlUpdateProperties.Update(); } mediaView.InfoText = (isUpdate ? GetString("dialogs.attachment.updated") : GetString("dialogs.attachment.created")); pnlUpdateView.Update(); } } ClearActionElems(); }
public WorkflowController() { Manager = ServiceFactory.WorkflowManager; }
/// <summary> /// Publishes document. /// </summary> /// <param name="node">Node to publish</param> /// <param name="wm">Workflow manager</param> /// <returns>Whether node is already published</returns> private static bool Publish(TreeNode node, WorkflowManager wm) { WorkflowStepInfo currentStep = wm.GetStepInfo(node); bool toReturn = true; if (currentStep != null) { // For archive step start new version if (currentStep.StepName.ToLower() == "archived") { VersionManager vm = new VersionManager(node.TreeProvider); currentStep = vm.CheckOut(node, node.IsPublished, true); vm.CheckIn(node, null, null); } // Remove possible checkout if (node.GetIntegerValue("DocumentCheckedOutByUserID") > 0) { TreeProvider.ClearCheckoutInformation(node); node.Update(); } // Approve until the document is published while ((currentStep != null) && (currentStep.StepName.ToLower() != "published")) { currentStep = wm.MoveToNextStep(node, string.Empty); toReturn = false; } } return toReturn; }
public NewCustomerState(WorkflowManager manager) : base(manager, WorkflowStates.NewCustomer) { }
/// <summary> /// Publishes document. /// </summary> /// <param name="node">Node to publish</param> /// <param name="wm">Workflow manager</param> /// <returns>Whether node is already published</returns> private bool Publish(TreeNode node, WorkflowManager wm) { string pathCulture = HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")"); WorkflowStepInfo currentStep = wm.GetStepInfo(node); bool alreadyPublished = (currentStep == null) || currentStep.StepIsPublished; if (!alreadyPublished) { using (new CMSActionContext { LogEvents = false }) { // Remove possible checkout if (node.DocumentCheckedOutByUserID > 0) { TreeProvider.ClearCheckoutInformation(node); node.Update(); } } // Publish document currentStep = wm.PublishDocument(node); } // Document is already published, check if still under workflow if (alreadyPublished && (currentStep != null) && currentStep.StepIsPublished) { WorkflowScopeInfo wsi = wm.GetNodeWorkflowScope(node); if (wsi == null) { VersionManager vm = VersionManager.GetInstance(node.TreeProvider); vm.RemoveWorkflow(node); } } // Document already published if (alreadyPublished) { AddLog(string.Format(ResHelper.GetString("content.publishedalready"), pathCulture)); } else if ((currentStep == null) || !currentStep.StepIsPublished) { AddError(string.Format(ResHelper.GetString("content.PublishWasApproved"), pathCulture)); return true; } else { // Add log record AddLog(pathCulture); } return false; }
/// <summary> /// Provides operations necessary to create and store new attachment. /// </summary> private void HandleAttachmentUpload(bool fieldAttachment) { // New attachment DocumentAttachment newAttachment = null; string message = string.Empty; bool fullRefresh = false; bool refreshTree = false; try { // Get the existing document if (DocumentID != 0) { // Get document node = DocumentHelper.GetDocument(DocumentID, TreeProvider); if (node == null) { throw new Exception("Given page doesn't exist!"); } } #region "Check permissions" if (CheckPermissions) { CheckNodePermissions(node); } #endregion // Check the allowed extensions CheckAllowedExtensions(); // Standard attachments if (DocumentID != 0) { // Check out the document if (AutoCheck) { // Get original step Id int originalStepId = node.DocumentWorkflowStepID; // Get current step info WorkflowStepInfo si = WorkflowManager.GetStepInfo(node); if (si != null) { // Decide if full refresh is needed bool automaticPublish = wi.WorkflowAutoPublishChanges; // Document is published or archived or uses automatic publish or step is different than original (document was updated) fullRefresh = si.StepIsPublished || si.StepIsArchived || (automaticPublish && !si.StepIsPublished) || (originalStepId != node.DocumentWorkflowStepID); } using (CMSActionContext ctx = new CMSActionContext() { LogEvents = false }) { VersionManager.CheckOut(node, node.IsPublished); } } // Handle field attachment if (fieldAttachment) { newAttachment = DocumentHelper.AddAttachment(node, AttachmentGUIDColumnName, Guid.Empty, Guid.Empty, new AttachmentSource(ucFileUpload.PostedFile.ToUploadedFile()), ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); // Update attachment field DocumentHelper.UpdateDocument(node, TreeProvider); } // Handle grouped and unsorted attachments else { // Grouped attachment if (AttachmentGroupGUID != Guid.Empty) { newAttachment = DocumentHelper.AddGroupedAttachment(node, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile.ToUploadedFile(), ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } // Unsorted attachment else { newAttachment = DocumentHelper.AddUnsortedAttachment(node, AttachmentGUID, ucFileUpload.PostedFile.ToUploadedFile(), ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } // Log synchronization task if not under workflow if (wi == null) { DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, TreeProvider); } } // Check in the document if (AutoCheck) { using (CMSActionContext ctx = new CMSActionContext() { LogEvents = false }) { VersionManager.CheckIn(node, null, null); } } } // Temporary attachments if (FormGUID != Guid.Empty) { newAttachment = (DocumentAttachment)AttachmentInfoProvider.AddTemporaryAttachment(FormGUID, AttachmentGUIDColumnName, AttachmentGUID, AttachmentGroupGUID, new AttachmentSource(ucFileUpload.PostedFile.ToUploadedFile()), SiteContext.CurrentSiteID, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } // Ensure properties update if ((newAttachment != null) && !InsertMode) { AttachmentGUID = newAttachment.AttachmentGUID; } if (newAttachment == null) { throw new Exception("The attachment hasn't been created since no DocumentID or FormGUID was supplied."); } } catch (Exception ex) { // Log the exception Service.Resolve <IEventLogService>().LogException("Content", "UploadAttachment", ex); message = ex.Message; } finally { string afterSaveScript = string.Empty; // Call aftersave javascript if exists if (!String.IsNullOrEmpty(AfterSaveJavascript)) { if ((message == string.Empty) && (newAttachment != null)) { var url = ResolveUrl(AttachmentURLProvider.GetAttachmentUrl(newAttachment.AttachmentGUID, newAttachment.AttachmentName)); // Calling javascript function with parameters attachments url, name, width, height if (!string.IsNullOrEmpty(AfterSaveJavascript)) { Hashtable obj = new Hashtable(); if (ImageHelper.IsImage(newAttachment.AttachmentExtension)) { obj[DialogParameters.IMG_URL] = url; obj[DialogParameters.IMG_TOOLTIP] = newAttachment.AttachmentName; obj[DialogParameters.IMG_WIDTH] = newAttachment.AttachmentImageWidth; obj[DialogParameters.IMG_HEIGHT] = newAttachment.AttachmentImageHeight; } else if (MediaHelper.IsAudioVideo(newAttachment.AttachmentExtension)) { obj[DialogParameters.OBJECT_TYPE] = "audiovideo"; obj[DialogParameters.AV_URL] = url; obj[DialogParameters.AV_EXT] = newAttachment.AttachmentExtension; obj[DialogParameters.AV_WIDTH] = DEFAULT_OBJECT_WIDTH; obj[DialogParameters.AV_HEIGHT] = DEFAULT_OBJECT_HEIGHT; } else { obj[DialogParameters.LINK_URL] = url; obj[DialogParameters.LINK_TEXT] = newAttachment.AttachmentName; } // Calling javascript function with parameters attachments url, name, width, height afterSaveScript += ScriptHelper.GetScript(string.Format(@"{5} if (window.{0}) {{ window.{0}('{1}', '{2}', '{3}', '{4}', obj); }} else if((window.parent != null) && window.parent.{0}) {{ window.parent.{0}('{1}', '{2}', '{3}', '{4}', obj); }}", AfterSaveJavascript, url, newAttachment.AttachmentName, newAttachment.AttachmentImageWidth, newAttachment.AttachmentImageHeight, CMSDialogHelper.GetDialogItem(obj))); } } else { afterSaveScript += ScriptHelper.GetAlertScript(message); } } // Create attachment info string string attachmentInfo = ((newAttachment != null) && (newAttachment.AttachmentGUID != Guid.Empty) && (IncludeNewItemInfo)) ? String.Format("'{0}', ", newAttachment.AttachmentGUID) : ""; // Ensure message text message = TextHelper.EnsureLineEndings(message, " "); // Call function to refresh parent window afterSaveScript += ScriptHelper.GetScript(String.Format(@" if ((window.parent != null) && (/parentelemid={0}/i.test(window.location.href)) && (window.parent.InitRefresh_{0} != null)){{ window.parent.InitRefresh_{0}({1}, {2}, {3}, {4}); }}", ParentElemID, ScriptHelper.GetString(message.Trim()), (fullRefresh ? "true" : "false"), (refreshTree ? "true" : "false"), attachmentInfo + (InsertMode ? "'insert'" : "'update'"))); ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript); } }
protected DataSet gridAttachments_OnDataReload(string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords) { string where = null; Guid attachmentFormGUID = Guid.Empty; string whereCondition = GetWhereConditionInternal(); int documentVersionHistoryID = UsesWorkflow ? VersionHistoryID : 0; // Grouped attachments if (GroupGUID != Guid.Empty) { // Combine where conditions where = String.Format("(AttachmentGroupGUID='{0}')", GroupGUID); } // Unsorted attachments else { where = "(AttachmentIsUnsorted = 1)"; } // Temporary attachments if ((attachmentFormGUID != Guid.Empty) && (documentVersionHistoryID == 0)) { where += String.Format(" AND (AttachmentFormGUID='{0}')", FormGUID); } // Else document attachments else { if (documentVersionHistoryID == 0) { // Ensure current site name if (string.IsNullOrEmpty(SiteName)) { SiteName = CMSContext.CurrentSiteName; } if (Node != null) { where += String.Format(" AND (AttachmentDocumentID = {0})", Node.DocumentID); // Get attachments for latest version if not live site if (!IsLiveSite) { WorkflowManager wm = new WorkflowManager(TreeProvider); WorkflowInfo wi = wm.GetNodeWorkflow(Node); if (wi != null) { documentVersionHistoryID = Node.DocumentCheckedOutVersionHistoryID; } } } else { return(null); } } } // Ensure additional where condition whereCondition = SqlHelperClass.AddWhereCondition(whereCondition, where); // Ensure [AttachmentID] column List <String> cols = new List <string>(columns.Split(new char[] { ',', ';' })); if (!cols.Contains("AttachmentID") && !cols.Contains("[AttachmentID]")) { columns = SqlHelperClass.MergeColumns("AttachmentID", columns); } DataSet ds = null; // Get attachments for published document if (documentVersionHistoryID == 0) { currentOrder = "AttachmentOrder, AttachmentName, AttachmentID"; ds = AttachmentManager.GetAttachments(whereCondition, currentOrder, true, currentTopN, columns); } else { currentOrder = "AttachmentOrder, AttachmentName, AttachmentHistoryID"; VersionManager vm = new VersionManager(TreeProvider); ds = vm.GetVersionAttachments(documentVersionHistoryID, whereCondition, currentOrder, true, currentTopN, columns.Replace("AttachmentID", "AttachmentHistoryID")); } // Ensure consistent ID column name if (!DataHelper.DataSourceIsEmpty(ds)) { ds.Tables[0].Columns[0].ColumnName = "AttachmentID"; } return(ds); }
protected void gridHistory_OnAction(string actionName, object actionArgument) { int versionHistoryId = ValidationHelper.GetInteger(actionArgument, 0); switch (actionName.ToLowerCSafe()) { case "rollback": if (versionHistoryId > 0) { if (CheckedOutByUserID > 0) { // Document is checked out ShowError(GetString("VersionProperties.CannotRollbackCheckedOut")); } else { // Check permissions if (!WorkflowManager.CheckStepPermissions(Node, WorkflowActionEnum.Approve) || !CanModify) { ShowError(String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), Node.NodeAliasPath)); } else { try { VersionManager.RollbackVersion(versionHistoryId); if (!IsLiveSite) { // Refresh content tree (for the case that document name has been changed) string refreshTreeScript = ScriptHelper.GetScript("if(window.RefreshTree!=null){RefreshTree(" + Node.NodeParentID + ", " + Node.NodeID + ");}"); ScriptHelper.RegisterStartupScript(this, typeof(string), "refreshTree" + ClientID, refreshTreeScript); } ShowConfirmation(GetString("VersionProperties.RollbackOK")); } catch (Exception ex) { ShowError(ex.Message); } } } } break; case "destroy": if (versionHistoryId > 0) { if (Node != null) { // Check permissions if (!CanDestroy || (CheckedOutByAnotherUser && !CanCheckIn)) { ShowError(GetString("History.ErrorNotAllowedToDestroy")); } else { VersionManager.DestroyDocumentVersion(versionHistoryId); ShowConfirmation(GetString("VersionProperties.DestroyOK")); } } } break; } }
/// <summary> /// Reloads the page data. /// </summary> private void ReloadData() { // If no workflow set for node, hide the data if (WorkflowInfo == null) { headCheckOut.ResourceString = "properties.scopenotset"; DisableForm(); pnlVersions.Visible = false; } else { if (!WorkflowStepInfo.StepIsDefault && !WorkflowManager.CheckStepPermissions(Node, WorkflowActionEnum.Approve)) { ShowInfo(GetString("EditContent.NotAuthorizedToApprove"), true); } } bool useCheckInCheckOut = false; if (WorkflowInfo != null) { useCheckInCheckOut = WorkflowInfo.UseCheckInCheckOut(SiteContext.CurrentSiteName); } // Check modify permissions if (!versionsElem.CanModify) { DisableForm(); plcForm.Visible = false; ShowInfo(String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), Node.NodeAliasPath), true); } else if (useCheckInCheckOut || (versionsElem.CheckedOutByUserID != 0)) { btnCheckout.Visible = false; btnCheckout.Enabled = true; btnCheckin.Visible = false; btnCheckin.Enabled = true; btnUndoCheckout.Visible = false; btnUndoCheckout.Enabled = true; txtComment.Enabled = true; txtVersion.Enabled = true; lblComment.Enabled = true; lblVersion.Enabled = true; // Check whether to check out or in if (WorkflowInfo == null) { btnCheckout.Visible = true; headCheckOut.ResourceString = "VersionsProperties.CheckOut"; DisableForm(); } else if (!Node.IsCheckedOut) { headCheckOut.ResourceString = "VersionsProperties.CheckOut"; DisableForm(); btnCheckout.Visible = true; // Do not allow checkout for published or archived step in advanced workflow btnCheckout.Enabled = (WorkflowInfo.IsBasic || (!WorkflowStepInfo.StepIsPublished && !WorkflowStepInfo.StepIsArchived)); } else { // If checked out by current user, allow to check-in if (versionsElem.CheckedOutByUserID == MembershipContext.AuthenticatedUser.UserID) { btnCheckin.Visible = true; btnUndoCheckout.Visible = true; } else { // Else checked out by somebody else btnCheckin.Visible = true; btnCheckout.Visible = false; btnUndoCheckout.Visible = versionsElem.CanCheckIn; btnUndoCheckout.Enabled = versionsElem.CanCheckIn; btnCheckin.Enabled = versionsElem.CanCheckIn; txtComment.Enabled = versionsElem.CanCheckIn; txtVersion.Enabled = versionsElem.CanCheckIn; } headCheckOut.ResourceString = "VersionsProperties.CheckIn"; } if (!WorkflowManager.CheckStepPermissions(Node, WorkflowActionEnum.Approve)) { DisableForm(); } } else { plcForm.Visible = false; } }
private void ImportPost(Guid blogId, GenericBlogPost post) { Guid masterBlogPostId = Guid.NewGuid(); BlogPost blogPost = SFBlogsManager.CreateBlogPost(masterBlogPostId); Blog blog = SFBlogsManager.GetBlogs().Where(b => b.Id == blogId).SingleOrDefault(); blogPost.Parent = blog; masterBlogPostId = blogPost.Id; blogPost.Title = post.Title; blogPost.DateCreated = post.DateCreated; blogPost.PublicationDate = post.PublicationDate; blogPost.LastModified = post.PublicationDate; string content = ParseContent(post.Content); content = ImportAndLinkContentImages(content, post.Title, blog.Title); blogPost.Content = content; blogPost.Summary = post.Summary; blogPost.AllowComments = post.AllowComments; blogPost.UrlName = post.PostName ?? Regex.Replace(post.Title.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-"); blogPost.Owner = Guid.Empty; PostAuthor author = _authors.Where(a => a.Username == post.Creator).FirstOrDefault(); if (author != null) { User user = SFUserManager.GetUserByEmail(author.Email); if (user != null) { blogPost.Owner = user.Id; } } if (ddlCategoriesImportMode.SelectedIndex > 0) { if (post.Categories != null && post.Categories.Count > 0) { foreach (string category in post.Categories) { HierarchicalTaxon taxon; taxon = SFTaxonomyManager.GetTaxa <HierarchicalTaxon>().Where(t => t.Name == category).FirstOrDefault(); if (taxon == null && ddlCategoriesImportMode.SelectedIndex > 1) { taxon = CreateCategory(category); } if (taxon != null) { blogPost.Organizer.AddTaxa("Category", taxon.Id); } } } } if (ddlTagsImportMode.SelectedIndex > 0) { if (post.Tags != null && post.Tags.Count > 0) { foreach (string tag in post.Tags) { FlatTaxon taxon; taxon = SFTaxonomyManager.GetTaxa <FlatTaxon>().Where(t => t.Name == tag).FirstOrDefault(); if (taxon == null && ddlTagsImportMode.SelectedIndex > 1) { taxon = CreateTag(tag); } if (taxon != null) { blogPost.Organizer.AddTaxa("Tags", taxon.Id); } } } } if (post.AttachmentUrl != String.Empty) { string imageSrc = post.AttachmentUrl; string imgFile = Path.GetFileName(imageSrc); var sfImages = App.WorkWith().Images().Where(i => i.Status == ContentLifecycleStatus.Master).Get().ToList(); var sfImg = sfImages.Where(i => Path.GetFileName(i.FilePath) == imgFile.ToLower()).FirstOrDefault(); if (sfImg != null) { blogPost.CreateRelation(sfImg, "Thumbnail"); } else { if (ImportImage(imageSrc, post.Title, blog.Title)) { sfImg = App.WorkWith().Images().Where(i => i.Status == ContentLifecycleStatus.Master).Get().ToList().Where(i => Path.GetFileName(i.FilePath) == imgFile.ToLower()).FirstOrDefault(); blogPost.CreateRelation(sfImg, "Thumbnail"); } } } if (post.Meta != null) { if (post.Meta.ContainsKey("_yoast_wpseo_title")) { blogPost.SetValue("SEOTitle", post.Meta["_yoast_wpseo_title"]); } if (post.Meta.ContainsKey("_yoast_wpseo_metadesc")) { blogPost.SetValue("SEOMetaDescription", post.Meta["_yoast_wpseo_metadesc"]); } if (post.Meta.ContainsKey("_yoast_wpseo_focuskw")) { blogPost.SetValue("SEOMetaKeywords", post.Meta["_yoast_wpseo_focuskw"]); } } SFBlogsManager.RecompileItemUrls(blogPost); SFBlogsManager.Lifecycle.PublishWithSpecificDate(blogPost, post.PublicationDate); SFBlogsManager.SaveChanges(); var bag = new Dictionary <string, string>(); bag.Add("ContentType", typeof(BlogPost).FullName); WorkflowManager.MessageWorkflow(masterBlogPostId, typeof(BlogPost), null, "Publish", false, bag); if (chkImportComments.Checked) { if (post.Comments != null && post.Comments.Count() > 0) { foreach (var comment in post.Comments) { CreateBlogPostComment(masterBlogPostId, comment); } } } var dbg = _importLog; }
private string CompleteTask(int iLoanTaskId) { #region complete task string sErrorMsg = string.Empty; int iEmailTemplateId = 0; bool bIsSuccess = LPWeb.DAL.WorkflowManager.CompleteTask(iLoanTaskId, this.CurrUser.iUserID, ref iEmailTemplateId); if (bIsSuccess == false) { sErrorMsg = "Failed to invoke WorkflowManager.CompleteTask."; return(sErrorMsg); } #endregion #region update point file stage int iLoanStageID = 0; #region get loan task info LoanTasks LoanTaskManager = new LoanTasks(); DataTable LoanTaskInfo = LoanTaskManager.GetLoanTaskInfo(iLoanTaskId); if (LoanTaskInfo.Rows.Count == 0) { sErrorMsg = "Invalid task id."; return(sErrorMsg); } string sLoanStageID = LoanTaskInfo.Rows[0]["LoanStageId"].ToString(); if (sLoanStageID == string.Empty) { sErrorMsg = "Invalid loan stage id."; return(sErrorMsg); } iLoanStageID = Convert.ToInt32(sLoanStageID); #endregion if (WorkflowManager.StageCompleted(iLoanStageID) == true) { #region invoke PointManager.UpdateStage() //add by gdc 20111212 Bug #1306 LPWeb.BLL.PointFiles pfile = new PointFiles(); var model = pfile.GetModel(iLoanID); if (model != null && !string.IsNullOrEmpty(model.Name.Trim())) { #region UPdatePointFileStage WCF string sError = LoanTaskCommon.UpdatePointFileStage(iLoanID, this.CurrUser.iUserID, iLoanStageID); #endregion } #endregion } #endregion return(sErrorMsg); }
/// <summary> /// Saves metadata and file name of attachment. /// </summary> /// <param name="newFileName">New attachment file name</param> /// <returns>Returns True if attachment was succesfully saved.</returns> private bool SaveAttachment(string newFileName) { bool saved = false; // Save new data try { AttachmentInfo attachmentInfo = InfoObject as AttachmentInfo; if (attachmentInfo != null) { // Set new file name if (!string.IsNullOrEmpty(newFileName)) { string name = newFileName + attachmentInfo.AttachmentExtension; if (IsAttachmentNameUnique(attachmentInfo, name)) { attachmentInfo.AttachmentName = name; } else { // Attachment already exists. LabelError = GetString("img.errors.fileexists"); return false; } } // Ensure automatic check-in/ check-out bool useWorkflow = false; bool autoCheck = false; WorkflowManager workflowMan = new WorkflowManager(TreeProvider); if (Node != null) { // Get workflow info WorkflowInfo wi = workflowMan.GetNodeWorkflow(Node); // Check if the document uses workflow if (wi != null) { useWorkflow = true; autoCheck = !wi.UseCheckInCheckOut(SiteName); } // Check out the document if (autoCheck) { VersionManager.CheckOut(Node, Node.IsPublished, true); VersionHistoryID = Node.DocumentCheckedOutVersionHistoryID; } // Workflow has been lost, get published attachment if (useWorkflow && (VersionHistoryID == 0)) { attachmentInfo = AttachmentManager.GetAttachmentInfo(attachmentInfo.AttachmentGUID, SiteName); } } if (attachmentInfo != null) { // Set filename title and description attachmentInfo.AttachmentTitle = ObjectTitle; attachmentInfo.AttachmentDescription = ObjectDescription; // Document uses workflow and document is already saved (attachment is not temporary) if ((VersionHistoryID > 0) && !nodeIsParent) { attachmentInfo.AllowPartialUpdate = true; VersionManager.SaveAttachmentVersion(attachmentInfo, VersionHistoryID); } else { // Update without binary attachmentInfo.AllowPartialUpdate = true; AttachmentManager.SetAttachmentInfo(attachmentInfo); // Log the sycnhronization and search task for the document if (Node != null) { // Update search index for given document if ((Node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, Node.GetSearchID()); } DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider); } } // Check in the document if (autoCheck) { if (VersionManager != null) { if (VersionHistoryID > 0 && (Node != null)) { VersionManager.CheckIn(Node, null, null); } } } saved = true; string fullRefresh = "false"; if (autoCheck || (Node == null)) { fullRefresh = "true"; } // Refresh parent update panel LtlScript.Text = ScriptHelper.GetScript("RefreshMetaData(" + ScriptHelper.GetString(ExternalControlID) + ", '" + fullRefresh + "', '" + attachmentInfo.AttachmentGUID + "', 'refresh')"); } } } catch (Exception ex) { lblError.Text = GetString("metadata.errors.processing"); EventLogProvider.LogException("Metadata editor", "SAVEATTACHMENT", ex); } return saved; }
public void Dispose() { WorkflowManager.Execute(View.GetEventCommands("UnLoad")); WorkflowManager.Instance.Message -= Instance_Message; }
public void NavigationWidget_ValidatePagesCacheDependenciesOnChildPagePublishUnpublish() { const string ParentPageTitle = "ParentPage"; const string ChildPageTitle = "ChildPage"; string url = UrlPath.ResolveAbsoluteUrl("~/" + UrlNamePrefix + Index); var mvcProxy = new MvcControllerProxy() { ControllerName = typeof(NavigationController).FullName, Settings = new ControllerSettings(new NavigationController() { LevelsToInclude = 2 }) }; var paretnPageId = this.pageOperations.CreatePageWithControl(mvcProxy, PageNamePrefix, PageTitlePrefix, UrlNamePrefix, Index); this.createdPageIDs.Add(paretnPageId); var pageGenerator = new Telerik.Sitefinity.TestIntegration.Data.Content.PageContentGenerator(); var pageManager = PageManager.GetManager(); var parentPageId = pageGenerator.CreatePage(ParentPageTitle, ParentPageTitle, ParentPageTitle); this.createdPageIDs.Add(parentPageId); var childPageId = pageGenerator.CreatePage(ChildPageTitle, ChildPageTitle, ChildPageTitle); this.createdPageIDs.Add(childPageId); var parent = pageManager.GetPageNode(parentPageId); var child = pageManager.GetPageNode(childPageId); child.Parent = parent; pageManager.SaveChanges(); var cookies = new CookieContainer(); using (new AuthenticateUserRegion(null)) { var responseContent = this.GetResponse(url, cookies); Assert.IsTrue(responseContent.Contains(ParentPageTitle + "<"), "The parent page was not found"); Assert.IsTrue(responseContent.Contains(ChildPageTitle + "<"), "The child page was not found"); } pageManager.UnpublishPage(child.GetPageData()); pageManager.SaveChanges(); using (new AuthenticateUserRegion(null)) { var responseContent = this.GetResponse(url, cookies); Assert.IsTrue(responseContent.Contains(ParentPageTitle + "<"), "The parent page was not found"); Assert.IsFalse(responseContent.Contains(ChildPageTitle + "<"), "The child page was found"); } var bag = new Dictionary <string, string>(); bag.Add("ContentType", child.GetType().FullName); WorkflowManager.MessageWorkflow(childPageId, child.GetType(), null, "Publish", false, bag); using (new AuthenticateUserRegion(null)) { var responseContent = this.GetResponse(url, cookies); Assert.IsTrue(responseContent.Contains(ParentPageTitle + "<"), "The parent page was not found"); Assert.IsTrue(responseContent.Contains(ChildPageTitle + "<"), "The child page was not found"); } }
public PendingWorkflowController(WorkflowManager manager) { Manager = manager; }
/// <summary> /// Saves modified image data. /// </summary> /// <param name="name">Image name</param> /// <param name="extension">Image extension</param> /// <param name="mimetype">Image mimetype</param> /// <param name="title">Image title</param> /// <param name="description">Image description</param> /// <param name="binary">Image binary data</param> /// <param name="width">Image width</param> /// <param name="height">Image height</param> private void SaveImage(string name, string extension, string mimetype, string title, string description, byte[] binary, int width, int height) { LoadInfos(); // Save image data depending to image type switch (baseImageEditor.ImageType) { // Process attachment case ImageHelper.ImageTypeEnum.Attachment: if ((ai != null) && (AttachmentManager != null)) { // Save new data try { // Get the node TreeNode node = DocumentHelper.GetDocument(ai.AttachmentDocumentID, baseImageEditor.Tree); // Check Create permission when saving temporary attachment, check Modify permission else NodePermissionsEnum permissionToCheck = (ai.AttachmentFormGUID == Guid.Empty) ? NodePermissionsEnum.Modify : NodePermissionsEnum.Create; // Check permission if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, permissionToCheck) != AuthorizationResultEnum.Allowed) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "attach.actiondenied"; this.SavingFailed = true; return; } if (!IsNameUnique(name, extension)) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.namenotunique"; this.SavingFailed = true; return; } // Ensure automatic check-in/ check-out bool useWorkflow = false; bool autoCheck = false; WorkflowManager workflowMan = new WorkflowManager(baseImageEditor.Tree); if (node != null) { // Get workflow info WorkflowInfo wi = workflowMan.GetNodeWorkflow(node); // Check if the document uses workflow if (wi != null) { useWorkflow = true; autoCheck = !wi.UseCheckInCheckOut(CurrentSiteName); } // Check out the document if (autoCheck) { VersionManager.CheckOut(node, node.IsPublished, true); VersionHistoryID = node.DocumentCheckedOutVersionHistoryID; } // Workflow has been lost, get published attachment if (useWorkflow && (VersionHistoryID == 0)) { ai = AttachmentManager.GetAttachmentInfo(ai.AttachmentGUID, CurrentSiteName); } // If extension changed update CMS.File extension if ((node.NodeClassName.ToLower() == "cms.file") && (node.DocumentExtensions != extension)) { // Update document extensions if no custom are used if (!node.DocumentUseCustomExtensions) { node.DocumentExtensions = extension; } node.SetValue("DocumentType", extension); DocumentHelper.UpdateDocument(node, baseImageEditor.Tree); } } if (ai != null) { // Test all parameters to empty values and update new value if available if (name != "") { if (!name.EndsWith(extension)) { ai.AttachmentName = name + extension; } else { ai.AttachmentName = name; } } if (extension != "") { ai.AttachmentExtension = extension; } if (mimetype != "") { ai.AttachmentMimeType = mimetype; } ai.AttachmentTitle = title; ai.AttachmentDescription = description; if (binary != null) { ai.AttachmentBinary = binary; ai.AttachmentSize = binary.Length; } if (width > 0) { ai.AttachmentImageWidth = width; } if (height > 0) { ai.AttachmentImageHeight = height; } // Ensure object ai.MakeComplete(true); if (VersionHistoryID > 0) { VersionManager.SaveAttachmentVersion(ai, VersionHistoryID); } else { AttachmentManager.SetAttachmentInfo(ai); // Log the sycnhronization and search task for the document if (node != null) { // Update search index for given document if ((node.PublishedVersionExists) && (SearchIndexInfoProvider.SearchEnabled)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, PredefinedObjectType.DOCUMENT, SearchHelper.ID_FIELD, node.GetSearchID()); } DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, baseImageEditor.Tree); } } // Check in the document if (autoCheck) { if (VersionManager != null) { if (VersionHistoryID > 0 && node != null) { VersionManager.CheckIn(node, null, null); } } } } } catch (Exception ex) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.processing"; ScriptHelper.AppendTooltip(baseImageEditor.LblLoadFailed, ex.Message, "help"); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); this.SavingFailed = true; } } break; case ImageHelper.ImageTypeEnum.PhysicalFile: if (!String.IsNullOrEmpty(filePath)) { CurrentUserInfo currentUser = CMSContext.CurrentUser; if ((currentUser != null) && currentUser.IsGlobalAdministrator) { try { string physicalPath = Server.MapPath(filePath); string newPath = physicalPath; // Write binary data to the disk File.WriteAllBytes(physicalPath, binary); // Handle rename of the file if (!String.IsNullOrEmpty(name)) { newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(physicalPath), name); } if (!String.IsNullOrEmpty(extension)) { string oldExt = Path.GetExtension(physicalPath); newPath = newPath.Substring(0, newPath.Length - oldExt.Length) + extension; } // Move the file if (newPath != physicalPath) { File.Move(physicalPath, newPath); } } catch (Exception ex) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.processing"; ScriptHelper.AppendTooltip(baseImageEditor.LblLoadFailed, ex.Message, "help"); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); this.SavingFailed = true; } } else { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.rights"; this.SavingFailed = true; } } break; // Process metafile case ImageHelper.ImageTypeEnum.Metafile: if (mf != null) { if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, this.CurrentSiteName, CMSContext.CurrentUser)) { try { // Test all parameters to empty values and update new value if available if (name.CompareTo("") != 0) { if (!name.EndsWith(extension)) { mf.MetaFileName = name + extension; } else { mf.MetaFileName = name; } } if (extension.CompareTo("") != 0) { mf.MetaFileExtension = extension; } if (mimetype.CompareTo("") != 0) { mf.MetaFileMimeType = mimetype; } mf.MetaFileTitle = title; mf.MetaFileDescription = description; if (binary != null) { mf.MetaFileBinary = binary; mf.MetaFileSize = binary.Length; } if (width > 0) { mf.MetaFileImageWidth = width; } if (height > 0) { mf.MetaFileImageHeight = height; } // Save new data MetaFileInfoProvider.SetMetaFileInfo(mf); if (RefreshAfterAction) { if (String.IsNullOrEmpty(externalControlID)) { baseImageEditor.LtlScript.Text = ScriptHelper.GetScript("Refresh();"); } else { baseImageEditor.LtlScript.Text = ScriptHelper.GetScript(String.Format("InitRefresh({0}, false, false, '{1}', 'refresh')", ScriptHelper.GetString(externalControlID), mf.MetaFileGUID)); } } } catch (Exception ex) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.processing"; ScriptHelper.AppendTooltip(baseImageEditor.LblLoadFailed, ex.Message, "help"); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); this.SavingFailed = true; } } else { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.rights"; this.SavingFailed = true; } } break; } }
/// <summary> /// Archives sub documents of given node. /// </summary> /// <param name="parentNode">Parent node</param> /// <param name="tree">Tree provider</param> /// <param name="wm">Workflow manager</param> /// <param name="cultureCode">Culture code</param> /// <param name="siteName">Site name</param> /// <returns>TRUE if operation fails and whole process should be canceled.</returns> private bool ArchiveSubDocuments(TreeNode parentNode, TreeProvider tree, WorkflowManager wm, string cultureCode, string siteName) { DataSet subDocuments = GetSubDocuments(parentNode, tree, cultureCode, siteName); if (!DataHelper.DataSourceIsEmpty(subDocuments)) { foreach (DataRow nodeRow in subDocuments.Tables[0].Rows) { // Get the current document string aliasPath = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty); if (PerformArchive(wm, tree, GetDocument(tree, siteName, nodeRow), aliasPath)) { return true; } } } return false; }
/// <summary> /// WorkflowService /// </summary> public WorkflowService() { _workflowManager = new WorkflowManager(); }
/// <summary> /// Page load. /// </summary> protected void Page_Load(object sender, EventArgs e) { // Initialize control directUpload.Form = Form; directUpload.OnUploadFile += Form.RaiseOnUploadFile; directUpload.OnDeleteFile += Form.RaiseOnDeleteFile; directUpload.CheckPermissions = false; if (this.FieldInfo != null) { directUpload.GUIDColumnName = this.FieldInfo.Name; directUpload.AllowDelete = this.FieldInfo.AllowEmpty; } // Set allowed extensions string extensions = ValidationHelper.GetString(GetValue("extensions"), null); string allowedExtensions = ValidationHelper.GetString(GetValue("allowed_extensions"), null); if (extensions == "custom") { directUpload.AllowedExtensions = !String.IsNullOrEmpty(allowedExtensions) ? allowedExtensions : ""; } // Set image auto resize configuration if (this.FieldInfo != null) { int width = 0; int height = 0; int maxSideSize = 0; ImageHelper.GetAutoResizeDimensions(FieldInfo.Settings, CMSContext.CurrentSiteName, out width, out height, out maxSideSize); directUpload.ResizeToWidth = width; directUpload.ResizeToHeight = height; directUpload.ResizeToMaxSideSize = maxSideSize; } // Set control properties from parent Form if (Form != null) { // Get node TreeNode node = (TreeNode)Form.EditedObject; // Insert mode if ((Form.Mode == FormModeEnum.Insert) || (Form.Mode == FormModeEnum.InsertNewCultureVersion)) { directUpload.FormGUID = Form.FormGUID; if ((Form.ParentObject != null) && (Form.ParentObject is TreeNode)) { directUpload.NodeParentNodeID = ((TreeNode)Form.ParentObject).NodeID; } else if (node != null) { directUpload.NodeParentNodeID = node.NodeParentID; } if (node != null) { directUpload.NodeClassName = node.NodeClassName; directUpload.SiteName = node.NodeSiteName; // Set document version history if (Form.Mode == FormModeEnum.InsertNewCultureVersion) { // Set document version history ID directUpload.VersionHistoryID = node.DocumentCheckedOutVersionHistoryID; directUpload.SiteName = node.NodeSiteName; } } } // Editing existing node else if (node != null) { // Set appropriate control settings directUpload.DocumentID = node.DocumentID; directUpload.NodeParentNodeID = node.NodeParentID; directUpload.NodeClassName = node.NodeClassName; directUpload.SiteName = node.NodeSiteName; // Get the node workflow WorkflowManager wm = new WorkflowManager(node.TreeProvider); WorkflowInfo wi = wm.GetNodeWorkflow(node); if (wi != null) { // Set document version history ID directUpload.VersionHistoryID = node.DocumentCheckedOutVersionHistoryID; } } } // Set style properties of control if (!String.IsNullOrEmpty(ControlStyle)) { directUpload.Attributes.Add("style", ControlStyle); this.ControlStyle = null; } if (!String.IsNullOrEmpty(CssClass)) { directUpload.CssClass = CssClass; this.CssClass = null; } CheckFieldEmptiness = false; }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (this.StopProcessing) { // Do nothing } else { pi = CMSContext.CurrentPageInfo; if (pi != null) { CMSPagePlaceholder parentPlaceHolder = PortalHelper.FindParentPlaceholder(this); // Nothing to render, nothing to do if ((!this.DisplayAddButton && !this.DisplayResetButton) || ((parentPlaceHolder != null) && (parentPlaceHolder.UsingDefaultPageTemplate))) { this.Visible = false; return; } CurrentUserInfo currentUser = CMSContext.CurrentUser; zoneType = WidgetZoneTypeCode.ToEnum(this.WidgetZoneType); // Check security if (((zoneType == WidgetZoneTypeEnum.Group) && !currentUser.IsGroupAdministrator(pi.NodeGroupId)) || ((zoneType == WidgetZoneTypeEnum.User || zoneType == WidgetZoneTypeEnum.Dashboard) && !currentUser.IsAuthenticated())) { this.Visible = false; resetAllowed = false; return; } // Displaying - Editor zone only in edit mode, User/Group zone only in Live site/Preview mode if (((zoneType == WidgetZoneTypeEnum.Editor) && (CMSContext.ViewMode != ViewModeEnum.Edit)) || (((zoneType == WidgetZoneTypeEnum.User) || (zoneType == WidgetZoneTypeEnum.Group)) && ((CMSContext.ViewMode != ViewModeEnum.LiveSite) && (CMSContext.ViewMode != ViewModeEnum.Preview))) || ((zoneType == WidgetZoneTypeEnum.Dashboard) && ((CMSContext.ViewMode != ViewModeEnum.DashboardWidgets) || (String.IsNullOrEmpty(PortalContext.DashboardName))))) { this.Visible = false; resetAllowed = false; return; } // Get current document TreeNode currentNode = DocumentHelper.GetDocument(pi.DocumentId, this.TreeProvider); if (((zoneType == WidgetZoneTypeEnum.Editor) && (!currentUser.IsEditor || (currentUser.IsAuthorizedPerDocument(currentNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied)))) { this.Visible = false; resetAllowed = false; return; } // If use checkin checkout enabled, check if document is checkout by current user if (zoneType == WidgetZoneTypeEnum.Editor) { if (currentNode != null) { WorkflowManager wm = new WorkflowManager(this.TreeProvider); // Get workflow info WorkflowInfo wi = wm.GetNodeWorkflow(currentNode); // Check if node is under workflow and if use checkin checkout enabled if ((wi != null) && (wi.UseCheckInCheckOut(CMSContext.CurrentSiteName))) { int checkedOutBy = currentNode.DocumentCheckedOutByUserID; // Check if document is checkout by current user if (checkedOutBy != CMSContext.CurrentUser.UserID) { this.Visible = false; resetAllowed = false; return; } } } } // Find widget zone PageTemplateInfo pti = pi.PageTemplateInfo; // ZodeID specified directly if (!String.IsNullOrEmpty(this.WidgetZoneID)) { zoneInstance = pti.GetZone(this.WidgetZoneID); } // Zone not find or specified zone is not of correct type if ((zoneInstance != null) && (zoneInstance.WidgetZoneType != zoneType)) { zoneInstance = null; } // For delete all variants all zones are necessairy if (parentPlaceHolder != null) { ArrayList zones = parentPlaceHolder.WebPartZones; if (zones != null) { foreach (CMSWebPartZone zone in zones) { if ((zone.ZoneInstance != null) && (zone.ZoneInstance.WidgetZoneType == zoneType)) { zoneInstances.Add(zone.ZoneInstance); if (zoneInstance == null) { zoneInstance = zone.ZoneInstance; } } } } } // No suitable zones on the page, nothing to do if (zoneInstance == null) { this.Visible = false; resetAllowed = false; return; } // Adding is enabled if (this.DisplayAddButton) { pnlAdd.Visible = true; lnkAddWidget.Visible = true; lnkAddWidget.Text = DataHelper.GetNotEmpty(this.AddButtonText, GetString("widgets.addwidget")); int templateId = 0; if (pi.PageTemplateInfo != null) { templateId = pi.PageTemplateInfo.PageTemplateId; } string script = "NewWidget('" + HttpUtility.UrlEncode(zoneInstance.ZoneID) + "', '" + HttpUtility.UrlEncode(pi.NodeAliasPath) + "', '" + templateId + "'); return false;"; lnkAddWidget.Attributes.Add("onclick", script); } // Reset is enabled if (this.DisplayResetButton) { pnlReset.Visible = true; btnReset.Text = DataHelper.GetNotEmpty(this.ResetButtonText, GetString("widgets.resettodefault")); btnReset.Click += new EventHandler(btnReset_Click); // Add confirmation if required if (this.ResetConfirmationRequired) { btnReset.Attributes.Add("onclick", "if (!confirm('" + GetString("widgets.resetzoneconfirmtext") + "')) return false;"); } } // Set the panel css clas with dependence on actions zone type switch (zoneType) { // Editor case WidgetZoneTypeEnum.Editor: pnlWidgetActions.CssClass = "EditorWidgetActions"; break; // User case WidgetZoneTypeEnum.User: pnlWidgetActions.CssClass = "UserWidgetActions"; break; // Group case WidgetZoneTypeEnum.Group: pnlWidgetActions.CssClass = "GroupWidgetActions"; break; // Dashboard case WidgetZoneTypeEnum.Dashboard: pnlContextHelp.Visible = true; break; } } } }
/// <summary> /// Page load. /// </summary> protected void Page_Load(object sender, EventArgs e) { // Initialize control documentAttachments.Form = this.Form; documentAttachments.CheckPermissions = false; documentAttachments.OnUploadFile += new EventHandler(this.Form.RaiseOnUploadFile); documentAttachments.OnDeleteFile += new EventHandler(this.Form.RaiseOnDeleteFile); documentAttachments.AllowChangeOrder = ValidationHelper.GetBoolean(GetValue("changeorder"), true); documentAttachments.AllowPaging = ValidationHelper.GetBoolean(GetValue("paging"), true); documentAttachments.PageSize = ValidationHelper.GetString(GetValue("pagingsize"), "5,10,25,50,100,##ALL##"); documentAttachments.DefaultPageSize = ValidationHelper.GetInteger(GetValue("defaultpagesize"), 5); if (this.FieldInfo != null) { documentAttachments.GroupGUID = this.FieldInfo.Guid; } // Set allowed extensions string extensions = ValidationHelper.GetString(GetValue("extensions"), null); string allowedExtensions = ValidationHelper.GetString(GetValue("allowed_extensions"), null); if ((extensions == "custom") && (!String.IsNullOrEmpty(allowedExtensions))) { documentAttachments.AllowedExtensions = allowedExtensions; } // Set image auto resize dimensions if (this.FieldInfo != null) { int attachmentsWidth = 0; int attachmentsHeight = 0; int attachmentsMaxSideSize = 0; ImageHelper.GetAutoResizeDimensions(FieldInfo.Settings, CMSContext.CurrentSiteName, out attachmentsWidth, out attachmentsHeight, out attachmentsMaxSideSize); documentAttachments.ResizeToWidth = attachmentsWidth; documentAttachments.ResizeToHeight = attachmentsHeight; documentAttachments.ResizeToMaxSideSize = attachmentsMaxSideSize; } // Get node CMS.TreeEngine.TreeNode node = (CMS.TreeEngine.TreeNode)this.Form.EditedObject; if ((Form.Mode == FormModeEnum.Insert) || (Form.Mode == FormModeEnum.InsertNewCultureVersion)) { documentAttachments.FormGUID = Form.FormGUID; if ((Form.ParentObject != null) && (Form.ParentObject is CMS.TreeEngine.TreeNode)) { documentAttachments.NodeParentNodeID = ((CMS.TreeEngine.TreeNode)Form.ParentObject).NodeID; } else if (node != null) { documentAttachments.NodeParentNodeID = node.NodeParentID; } if (node != null) { documentAttachments.NodeClassName = node.NodeClassName; } } else if (node != null) { // Set appropriate control settings documentAttachments.DocumentID = node.DocumentID; documentAttachments.NodeParentNodeID = node.NodeParentID; documentAttachments.NodeClassName = node.NodeClassName; documentAttachments.ActualNode = node; // Get the node workflow WorkflowManager wm = new WorkflowManager(node.TreeProvider); WorkflowInfo wi = wm.GetNodeWorkflow(node); if (wi != null) { // Ensure the document version documentAttachments.VersionHistoryID = node.DocumentCheckedOutVersionHistoryID; } } if ((node != null) && !string.IsNullOrEmpty(node.NodeSiteName)) { documentAttachments.SiteName = node.NodeSiteName; } // Set control styles if (!String.IsNullOrEmpty(ControlStyle)) { documentAttachments.Attributes.Add("style", ControlStyle); this.ControlStyle = null; } if (!String.IsNullOrEmpty(CssClass)) { documentAttachments.CssClass = CssClass; this.CssClass = null; } }
/// <summary> /// Performs necessary checks and archives document. /// </summary> /// <returns>TRUE if operation fails and whole process should be canceled.</returns> private bool PerformArchive(WorkflowManager wm, TreeProvider tree, TreeNode node, string aliasPath) { if (node != null) { if (!UndoPossibleCheckOut(tree, node)) { return true; } try { if (currentUser.UserHasAllowedCultures && !currentUser.IsCultureAllowed(node.DocumentCulture, node.NodeSiteName)) { AddLog(string.Format(GetString("content.notallowedtomodifycultureversion"), node.DocumentCulture, node.NodeAliasPath)); } else { // Add log record AddLog(HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")")); // Archive document wm.ArchiveDocument(node, string.Empty); } } catch (ThreadAbortException te) { AddLog(te.Message); } catch { AddLog(string.Format(ResHelper.GetString("content.archivenowf"), HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")"))); } return false; } else { AddLog(string.Format(ResHelper.GetString("ContentRequest.DocumentNoLongerExists", currentCulture), HTMLHelper.HTMLEncode(aliasPath))); return false; } }
public PracticalSchedulePendingState(WorkflowManager manager) : base(manager, WorkflowStates.PracticalSchedulePending) { }
/// <summary> /// Performs necessary checks and publishes document. /// </summary> /// <returns>TRUE if operation fails and whole process should be canceled.</returns> private bool PerformPublish(WorkflowManager wm, TreeProvider tree, TreeNode node, string aliasPath) { if (node != null) { if (currentUser.UserHasAllowedCultures && !currentUser.IsCultureAllowed(node.DocumentCulture, node.NodeSiteName)) { AddLog(string.Format(GetString("content.notallowedtomodifycultureversion"), node.DocumentCulture, HTMLHelper.HTMLEncode(node.NodeAliasPath))); } else { if (!UndoPossibleCheckOut(tree, node)) { return true; } WorkflowStepInfo currentStep = null; try { // Try to get workflow scope currentStep = wm.EnsureStepInfo(node); } catch (ThreadAbortException te) { AddLog(te.Message); } catch { AddLog(string.Format(ResHelper.GetString("content.publishnowf"), HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.DocumentCulture + ")"))); return false; } if (currentStep != null) { // Publish document return Publish(node, wm, currentStep); } } return false; } else { AddLog(string.Format(ResHelper.GetString("ContentRequest.DocumentNoLongerExists", currentCulture), HTMLHelper.HTMLEncode(aliasPath))); return false; } }
private void GenerateWorkflowItemList() { string connectionString = ConfigurationManager.ConnectionStrings["CertusDB"].ToString(); string query; SqlConnection conn = new SqlConnection(connectionString); SqlCommand command = conn.CreateCommand(); // get query using (Stream strm = Assembly.GetExecutingAssembly().GetManifestResourceStream("CertusCompanion.ImportQueries.WIR4.0_DS.sql")) { using (StreamReader sr = new StreamReader(strm)) { query = sr.ReadToEnd(); } } // manipulate query if (workflowItemSelection == "Non-completed") { query = query.Replace("TOP", "--TOP"); query = query.Replace("0--<cl>", $"{clientID}--<cl>"); query = query.Replace("AND DocumentWorkflowStatus.DocumentWorkflowStatusID > 3--<c2>", "--AND DocumentWorkflowStatus.DocumentWorkflowStatusID > 3--<c2>"); } else if (workflowItemSelection == "Most Recent...") { query = query.Replace("TOP 0", $"TOP {itemCount}"); query = query.Replace("0--<cl>", $"{clientID}--<cl>"); query = query.Replace("AND DocumentWorkflowStatus.DocumentWorkflowStatusID <= 3--<c1>", "--AND DocumentWorkflowStatus.DocumentWorkflowStatusID <= 3--<c1>"); query = query.Replace("AND DocumentWorkflowStatus.DocumentWorkflowStatusID > 3--<c2>", "--AND DocumentWorkflowStatus.DocumentWorkflowStatusID > 3--<c2>"); } else if (workflowItemSelection == "Most Recent (Non-completed)...") { query = query.Replace("TOP 0", $"TOP {itemCount}"); query = query.Replace("0--<cl>", $"{clientID}--<cl>"); query = query.Replace("AND DocumentWorkflowStatus.DocumentWorkflowStatusID > 3--<c2>", "--AND DocumentWorkflowStatus.DocumentWorkflowStatusID > 3--<c2>"); } else if (workflowItemSelection == "Most Recent (Completed)...") { query = query.Replace("TOP 0", $"TOP {itemCount}"); query = query.Replace("0--<cl>", $"{clientID}--<cl>"); query = query.Replace("AND DocumentWorkflowStatus.DocumentWorkflowStatusID <= 3--<c1>", "--AND DocumentWorkflowStatus.DocumentWorkflowStatusID <= 3--<c1>"); } // execute query command.CommandText = query; command.CommandType = CommandType.Text; command.CommandTimeout = 450; SqlDataAdapter wiAdapter = new SqlDataAdapter(command); DataTable wiTable = new DataTable(); wiAdapter.Fill(wiTable); // if there is a LoadingForm, report progress if (WorkflowManager.CheckIfFormIsOpened("LoadingForm")) { if (Application.OpenForms[0].InvokeRequired) { Application.OpenForms[0].Invoke(new Action(() => { (Application.OpenForms["LoadingForm"] as LoadingForm).ChangeLabel($"Generating items..."); (Application.OpenForms["LoadingForm"] as LoadingForm).MoveBar(25); (Application.OpenForms["LoadingForm"] as LoadingForm).Refresh(); })); } else { (Application.OpenForms["LoadingForm"] as LoadingForm).ChangeLabel($"Generating items..."); (Application.OpenForms["LoadingForm"] as LoadingForm).MoveBar(25); (Application.OpenForms["LoadingForm"] as LoadingForm).Refresh(); } } // add to WI foreach (DataRow row in wiTable.Rows) { string documentWorkflowItemID = row[0].ToString(); string CertificateID = row[1].ToString(); string vendorName = row[2].ToString(); string vendorID = row[3].ToString(); string clID = row[4].ToString(); string workflowAnalyst = row[5].ToString(); string workflowAnalystID = row[6].ToString(); string companyAnalyst = row[7].ToString(); string companyAnalystID = row[8].ToString(); DateTime parsedDateTimeValue; DateTime?emailDate = null; DateTime.TryParse(row[9].ToString(), out parsedDateTimeValue); emailDate = parsedDateTimeValue; string emailFromAddress = row[10].ToString(); string subjectLine = row[11].ToString(); string status = row[12].ToString(); string certusFileID = row[13].ToString(); string fileName = row[14].ToString(); string fileSize = row[15].ToString(); string fileMIME = row[16].ToString(); string fileURL = row[17].ToString(); WorkflowItem wi = new WorkflowItem ( documentWorkflowItemID, CertificateID, vendorName, vendorID, clID, null, null, null, null, workflowAnalyst, workflowAnalystID, companyAnalyst, companyAnalystID, emailDate, emailFromAddress, subjectLine, null, status, certusFileID, fileName, fileURL, fileSize, fileMIME, null ); this.currentImportItems.Add(wi); } // if there is a LoadingForm, report progress if (WorkflowManager.CheckIfFormIsOpened("LoadingForm")) { if (Application.OpenForms[0].InvokeRequired) { Application.OpenForms[0].Invoke(new Action(() => { (Application.OpenForms["LoadingForm"] as LoadingForm).ChangeLabel($"Saving item data..."); (Application.OpenForms["LoadingForm"] as LoadingForm).MoveBar(25); (Application.OpenForms["LoadingForm"] as LoadingForm).Refresh(); })); } else { (Application.OpenForms["LoadingForm"] as LoadingForm).ChangeLabel($"Saving item data..."); (Application.OpenForms["LoadingForm"] as LoadingForm).MoveBar(25); (Application.OpenForms["LoadingForm"] as LoadingForm).Refresh(); } } WorkflowImportRouter(3); }
/// <summary> /// Publishes sub documents of given node. /// </summary> /// <param name="parentNode">Parent node</param> /// <param name="tree">Tree provider</param> /// <param name="wm">Workflow manager</param> /// <param name="cultureCode">Culture code</param> /// <param name="siteName">Site name</param> /// <returns>TRUE if operation fails and whole process should be canceled.</returns> private bool PublishSubDocuments(TreeNode parentNode, TreeProvider tree, WorkflowManager wm, string cultureCode, string siteName) { // Get sub documents DataSet subDocuments = GetSubDocuments(parentNode, tree, cultureCode, siteName); if (!DataHelper.DataSourceIsEmpty(subDocuments)) { foreach (DataRow nodeRow in subDocuments.Tables[0].Rows) { if (PerformPublish(wm, tree, siteName, nodeRow)) { return true; } } } return false; }
protected void libraryMenuElem_OnReloadData(object sender, EventArgs e) { string[] parameters = ValidationHelper.GetString(libraryMenuElem.Parameter, string.Empty).Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); if (parameters.Length == 2) { // Parse identifier and document culture from library parameter int nodeId = ValidationHelper.GetInteger(parameters[0], 0); string cultureCode = ValidationHelper.GetString(parameters[1], string.Empty); // Get document using based on node identifier and culture TreeNode node = DocumentHelper.GetDocument(nodeId, cultureCode, TreeProvider); bool contextMenuVisible = false; bool localizeVisible = false; bool editVisible = false; bool uploadVisible = false; bool copyVisible = false; bool deleteVisible = false; bool openVisible = false; bool propertiesVisible = false; bool permissionsVisible = false; bool versionHistoryVisible = false; bool checkOutVisible = false; bool checkInVisible = false; bool undoCheckoutVisible = false; bool submitToApprovalVisible = false; bool rejectVisible = false; bool archiveVisible = false; if ((node != null) && (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Allowed)) { // Get original node (in case of linked documents) TreeNode originalNode = TreeProvider.GetOriginalNode(node); string documentType = ValidationHelper.GetString(node.GetValue("DocumentType"), string.Empty); string siteName = CMSContext.CurrentSiteName; string currentDocumentCulture = CMSContext.CurrentDocumentCulture.CultureCode; if (CMSContext.CurrentSiteID != originalNode.NodeSiteID) { SiteInfo si = SiteInfoProvider.GetSiteInfo(originalNode.NodeSiteID); siteName = si.SiteName; } // Get permissions const bool authorizedToRead = true; bool authorizedToDelete = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Delete) == AuthorizationResultEnum.Allowed); bool authorizedToModify = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed); bool authorizedCultureToModify = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify, false) == AuthorizationResultEnum.Allowed) && TreeSecurityProvider.HasUserCultureAllowed(NodePermissionsEnum.Modify, currentDocumentCulture, CMSContext.CurrentUser, siteName); bool authorizedToModifyPermissions = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ModifyPermissions) == AuthorizationResultEnum.Allowed); bool authorizedToCreate = CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(node.NodeParentID, node.NodeClassName); bool allowEditByCurrentUser = false; // Hide menu when user has no 'Read' permissions on document libraryMenuElem.Visible = authorizedToRead; // First evaluation of control's visibility bool differentCulture = (string.Compare(node.DocumentCulture, currentDocumentCulture, StringComparison.InvariantCultureIgnoreCase) != 0); localizeVisible = differentCulture && authorizedToCreate && authorizedCultureToModify; uploadVisible = authorizedToModify; copyVisible = authorizedToCreate && authorizedToModify; deleteVisible = authorizedToDelete; openVisible = authorizedToRead; propertiesVisible = authorizedToModify; permissionsVisible = authorizedToModifyPermissions; versionHistoryVisible = authorizedToModify; editVisible = authorizedToModify && CMSContext.IsWebDAVEnabled(CMSContext.CurrentSiteName) && RequestHelper.IsWindowsAuthentication() && WebDAVSettings.IsExtensionAllowedForEditMode(documentType, CMSContext.CurrentSiteName); // Get workflow object WorkflowInfo wi = WorkflowManager.GetNodeWorkflow(node); if ((wi != null) && authorizedToModify) { bool autoPublishChanges = wi.WorkflowAutoPublishChanges; // Get current step info, do not update document WorkflowStepInfo si = WorkflowManager.GetStepInfo(node, false) ?? WorkflowManager.GetFirstWorkflowStep(node, wi); bool canApprove = true; // If license does not allow custom steps, 'can approve' check is meaningless if (WorkflowInfoProvider.IsCustomStepAllowed()) { canApprove = WorkflowManager.CanUserApprove(node, CMSContext.CurrentUser); } // Get name of current workflow step string stepName = si.StepName.ToLower(); bool useCheckinCheckout = wi.UseCheckInCheckOut(CMSContext.CurrentSiteName); int nodeCheckedOutByUser = node.DocumentCheckedOutByUserID; bool nodeIsCheckedOut = (nodeCheckedOutByUser != 0); bool allowEdit = canApprove || (stepName == "edit") || (stepName == "published") || (stepName == "archived"); // If document is checked in if (nodeIsCheckedOut) { // If checked out by current user, add the check-in button and undo checkout button if (nodeCheckedOutByUser == CMSContext.CurrentUser.UserID) { undoCheckoutVisible = true; checkInVisible = true; allowEditByCurrentUser = allowEdit; } } else { // Hide check-out menu item if user can't apporve or document is in specific step if (allowEdit) { // If site uses check-out / check-in if (useCheckinCheckout) { checkOutVisible = true; } else { allowEditByCurrentUser = true; } } } rejectVisible = canApprove && !nodeIsCheckedOut && (stepName != "edit") && (stepName != "published") && (stepName != "archived") && !autoPublishChanges; submitToApprovalVisible = (canApprove || ((stepName == "edit") && authorizedToRead)) && !nodeIsCheckedOut && (stepName != "published") && (stepName != "archived") && !autoPublishChanges; archiveVisible = canApprove && !nodeIsCheckedOut && (stepName == "published"); } else { allowEditByCurrentUser = true; } // Check whether the document is not checked out by another user editVisible &= allowEditByCurrentUser; uploadVisible &= allowEditByCurrentUser; string parameterScript = "GetContextMenuParameter('" + libraryMenuElem.MenuID + "')"; // Initialize edit menu item Guid attachmentGuid = ValidationHelper.GetGuid(node.GetValue("FileAttachment"), Guid.Empty); // If attachment field doesn't allow empty value and the value is empty if ((FieldInfo != null) && !FieldInfo.AllowEmpty && (attachmentGuid == Guid.Empty)) { submitToApprovalVisible = false; archiveVisible = false; checkInVisible = false; } // Get attachment AttachmentInfo ai = DocumentHelper.GetAttachment(attachmentGuid, TreeProvider, siteName, false); Panel previousPanel = null; Panel currentPanel = pnlEdit; if (editVisible) { if (ai != null) { // Load WebDAV edit control and initialize it WebDAVEditControl editAttachment = Page.LoadControl("~/CMSModules/WebDAV/Controls/AttachmentWebDAVEditControl.ascx") as WebDAVEditControl; if (editAttachment != null) { editAttachment.ID = "editAttachment"; editAttachment.NodeAliasPath = node.NodeAliasPath; editAttachment.NodeCultureCode = node.DocumentCulture; editAttachment.AttachmentFieldName = "FileAttachment"; editAttachment.FileName = ai.AttachmentName; editAttachment.IsLiveSite = IsLiveSite; editAttachment.UseImageButton = true; editAttachment.LabelText = GetString("general.edit"); editAttachment.CssClass = "Icon"; editAttachment.LabelCssClass = "Name"; editAttachment.RefreshScript = JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'WebDAVRefresh');"; // Set Group ID for live site editAttachment.GroupID = IsLiveSite ? node.GetIntegerValue("NodeGroupID") : 0; editAttachment.ReloadData(true); pnlEditPadding.Controls.Add(editAttachment); pnlEditPadding.CssClass = editAttachment.EnabledResult ? "ItemPadding" : "ItemPaddingDisabled"; } } else { editVisible = false; openVisible = false; } } previousPanel = currentPanel; currentPanel = pnlUpload; // Initialize upload menu item if (authorizedToModify) { string uploaderImg = "<img class=\"UploaderImage\" src=\"" + GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Upload.png", IsLiveSite) + "\" alt=\"" + GetString("general.update") + "\" />"; string uploaderText = "<span class=\"UploaderText\">" + GetString("general.update") + "</span>"; StringBuilder uploaderInnerHtml = new StringBuilder(); bool isRTL = (IsLiveSite && CultureHelper.IsPreferredCultureRTL()) || (!IsLiveSite && CultureHelper.IsUICultureRTL()); if (isRTL) { uploaderInnerHtml.Append(uploaderText); uploaderInnerHtml.Append(uploaderImg); } else { uploaderInnerHtml.Append(uploaderImg); uploaderInnerHtml.Append(uploaderText); } // Initialize direct file uploader updateAttachment.InnerDivHtml = uploaderInnerHtml.ToString(); updateAttachment.InnerDivClass = "LibraryContextUploader"; updateAttachment.DocumentID = node.DocumentID; updateAttachment.ParentElemID = ClientID; updateAttachment.SourceType = MediaSourceEnum.Attachment; updateAttachment.AttachmentGUIDColumnName = "FileAttachment"; updateAttachment.DisplayInline = true; updateAttachment.IsLiveSite = IsLiveSite; // Set allowed extensions if ((FieldInfo != null) && ValidationHelper.GetString(FieldInfo.Settings["extensions"], "") == "custom") { // Load allowed extensions updateAttachment.AllowedExtensions = ValidationHelper.GetString(FieldInfo.Settings["allowed_extensions"], ""); } else { // Use site settings updateAttachment.AllowedExtensions = SettingsKeyProvider.GetStringValue(siteName + ".CMSUploadExtensions"); } updateAttachment.ReloadData(); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlLocalize; // Initialize localize menu item if (localizeVisible) { lblLocalize.RefreshText(); imgLocalize.AlternateText = lblLocalize.Text; imgLocalize.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Localize.png", IsLiveSite); pnlLocalize.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Localize');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = null; currentPanel = pnlCopy; // Initialize copy menu item if (copyVisible) { lblCopy.RefreshText(); imgCopy.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Copy.png", IsLiveSite); pnlCopy.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ",'Copy');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlDelete; // Initialize delete menu item if (deleteVisible) { lblDelete.RefreshText(); imgDelete.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Delete.png", IsLiveSite); pnlDelete.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Delete');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlOpen; // Initialize open menu item if (openVisible) { lblOpen.RefreshText(); imgOpen.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Open.png", IsLiveSite); if (ai != null) { // Get document URL string attachmentUrl = CMSContext.ResolveUIUrl(AttachmentURLProvider.GetPermanentAttachmentUrl(node.NodeGUID, node.NodeAlias)); if (authorizedToModify) { attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "latestfordocid", ValidationHelper.GetString(node.DocumentID, string.Empty)); attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "hash", ValidationHelper.GetHashString("d" + node.DocumentID)); } attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString()); if (!string.IsNullOrEmpty(attachmentUrl)) { pnlOpen.Attributes.Add("onclick", "location.href = " + ScriptHelper.GetString(attachmentUrl) + ";"); } } SetupPanelClasses(currentPanel, previousPanel); } previousPanel = null; currentPanel = pnlProperties; // Initialize properties menu item lblProperties.RefreshText(); imgProperties.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Properties.png", IsLiveSite); pnlProperties.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Properties');"); SetupPanelClasses(currentPanel, previousPanel); previousPanel = currentPanel; currentPanel = pnlPermissions; // Initialize permissions menu item lblPermissions.RefreshText(); imgPermissions.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Permissions.png", IsLiveSite); pnlPermissions.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Permissions');"); SetupPanelClasses(currentPanel, previousPanel); previousPanel = currentPanel; currentPanel = pnlVersionHistory; // Initialize version history menu item lblVersionHistory.RefreshText(); imgVersionHistory.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/VersionHistory.png", IsLiveSite); pnlVersionHistory.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'VersionHistory');"); SetupPanelClasses(currentPanel, previousPanel); previousPanel = null; currentPanel = pnlCheckOut; // Initialize checkout menu item if (checkOutVisible) { lblCheckOut.RefreshText(); imgCheckOut.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/CheckOut.png", IsLiveSite); pnlCheckOut.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckOut');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlCheckIn; // Initialize checkin menu item if (checkInVisible) { lblCheckIn.RefreshText(); imgCheckIn.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/CheckIn.png", IsLiveSite); pnlCheckIn.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckIn');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlUndoCheckout; // Initialize undo checkout menu item if (undoCheckoutVisible) { lblUndoCheckout.RefreshText(); imgUndoCheckout.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/UndoCheckout.png", IsLiveSite); pnlUndoCheckout.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'UndoCheckout');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlSubmitToApproval; // Initialize submit to approval / publish menu item if (submitToApprovalVisible) { if (wi != null) { // Get next step info WorkflowStepInfo nsi = WorkflowManager.GetNextStepInfo(node); if (nsi.StepName.ToLower() == "published") { // Set 'Publish' label lblSubmitToApproval.ResourceString = "general.publish"; } } lblSubmitToApproval.RefreshText(); imgSubmitToApproval.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/SubmitToApproval.png", IsLiveSite); pnlSubmitToApproval.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'SubmitToApproval');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlReject; // Initialize reject menu item if (rejectVisible) { lblReject.RefreshText(); imgReject.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Reject.png", IsLiveSite); pnlReject.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Reject');"); SetupPanelClasses(currentPanel, previousPanel); } previousPanel = currentPanel; currentPanel = pnlArchive; // Initialize archive menu item if (archiveVisible) { lblArchive.RefreshText(); imgArchive.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Archive.png", IsLiveSite); pnlArchive.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Archive');"); SetupPanelClasses(currentPanel, previousPanel); } // Set up visibility of menu items pnlLocalize.Visible = localizeVisible; pnlUpload.Visible = uploadVisible; pnlDelete.Visible = deleteVisible; pnlCopy.Visible = copyVisible; pnlOpen.Visible = openVisible; pnlProperties.Visible = propertiesVisible; pnlPermissions.Visible = permissionsVisible; pnlVersionHistory.Visible = versionHistoryVisible; pnlEdit.Visible = editVisible; pnlCheckOut.Visible = checkOutVisible; pnlCheckIn.Visible = checkInVisible; pnlUndoCheckout.Visible = undoCheckoutVisible; pnlSubmitToApproval.Visible = submitToApprovalVisible; pnlReject.Visible = rejectVisible; pnlArchive.Visible = archiveVisible; // Set up visibility of whole menu contextMenuVisible = true; } // Set up visibility of separators bool firstGroupVisible = editVisible || uploadVisible || localizeVisible; bool secondGroupVisible = copyVisible || deleteVisible || openVisible; bool thirdGroupVisible = propertiesVisible || permissionsVisible || versionHistoryVisible; bool fourthGroupVisible = checkOutVisible || checkInVisible || undoCheckoutVisible || submitToApprovalVisible || rejectVisible || archiveVisible; pnlSep1.Visible = firstGroupVisible && secondGroupVisible; pnlSep2.Visible = secondGroupVisible && thirdGroupVisible; pnlSep3.Visible = thirdGroupVisible && fourthGroupVisible; // Setup 'No action available' menu item pnlNoAction.Visible = !contextMenuVisible; lblNoAction.RefreshText(); } }
/// <summary> /// Performs actions necessary to select particular item from a list. /// </summary> private void SelectMediaItem(string argument) { if (!string.IsNullOrEmpty(argument)) { Hashtable argTable = CMSModules_Content_Controls_Dialogs_LinkMediaSelector_MediaView.GetArgumentsTable(argument); if (argTable.Count >= 2) { // Get information from argument string name = argTable["name"].ToString(); string ext = argTable["attachmentextension"].ToString(); int imageWidth = ValidationHelper.GetInteger(argTable["attachmentimagewidth"], 0); int imageHeight = ValidationHelper.GetInteger(argTable["attachmentimageheight"], 0); int nodeID = ValidationHelper.GetInteger(argTable["nodeid"], NodeID); long size = ValidationHelper.GetLong(argTable["attachmentsize"], 0); string url = argTable["url"].ToString(); string aliasPath = null; // Do not update properties when selecting recently edited image item bool avoidPropUpdate = false; // Remember last selected attachment GUID if (SourceType == MediaSourceEnum.DocumentAttachments) { Guid attGuid = ValidationHelper.GetGuid(argTable["attachmentguid"], Guid.Empty); avoidPropUpdate = (LastAttachmentGuid == attGuid); LastAttachmentGuid = attGuid; ItemToColorize = LastAttachmentGuid; } else { aliasPath = argTable["nodealiaspath"].ToString(); Guid nodeAttGuid = ValidationHelper.GetGuid(argTable["attachmentguid"], Guid.Empty); Properties.SiteDomainName = mediaView.SiteObj.DomainName; avoidPropUpdate = (ItemToColorize == nodeAttGuid); ItemToColorize = nodeAttGuid; if (ItemToColorize == Guid.Empty) { ItemToColorize = ValidationHelper.GetGuid(argTable["nodeguid"], Guid.Empty); } } avoidPropUpdate = (avoidPropUpdate && IsEditImage); if (!avoidPropUpdate) { if (SourceType == MediaSourceEnum.DocumentAttachments) { int versionHistoryId = 0; if (TreeNodeObj != null) { // Get the node workflow WorkflowManager wm = new WorkflowManager(TreeNodeObj.TreeProvider); WorkflowInfo wi = wm.GetNodeWorkflow(TreeNodeObj); if (wi != null) { // Get the document version versionHistoryId = TreeNodeObj.DocumentCheckedOutVersionHistoryID; } } MediaItem item = InitializeMediaItem(name, ext, imageWidth, imageHeight, size, url, null, versionHistoryId, nodeID, aliasPath); SelectMediaItem(item); } else { // Select item SelectMediaItem(name, ext, imageWidth, imageHeight, size, url, null, nodeID, aliasPath); } } } } }
public AdditionalClassesCompletedState(WorkflowManager manager) : base(manager, WorkflowStates.AdditionalClassesCompleted) { }
/// <summary> /// Creates new page(CMS.MenuItem) and assignes selected template. /// </summary> protected void Save(bool createAnother) { // Check security CheckSecurity(true); string newPageName = txtPageName.Text.Trim(); string errorMessage = null; if (!String.IsNullOrEmpty(newPageName)) { // Limit length to 100 characters newPageName = TextHelper.LimitLength(newPageName, TreePathUtils.MaxNameLength, String.Empty); } else { errorMessage = GetString("newpage.nameempty"); } if (parentNodeId == 0) { errorMessage = GetString("newpage.invalidparentnode"); } // If error, show error message and return if (String.IsNullOrEmpty(errorMessage)) { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); TreeNode node = TreeNode.New("CMS.MenuItem", tree); // Load default data FormHelper.LoadDefaultValues(node); node.DocumentName = newPageName; node.SetValue("MenuItemName", newPageName); lblError.Style.Remove("display"); node.DocumentPageTemplateID = selTemplate.EnsureTemplate(node.DocumentName, ref errorMessage); // Switch to design mode (the template is empty at this moment) if (selTemplate.NewTemplateIsEmpty && !createAnother) { CMSContext.ViewMode = ViewModeEnum.Design; } // Insert node if no error if (String.IsNullOrEmpty(errorMessage)) { node.DocumentCulture = CMSContext.PreferredCultureCode; // Insert the document DocumentHelper.InsertDocument(node, parentNodeId, tree); //node.Insert(parentNodeId); // Create default SKU if configured if (ModuleEntry.CheckModuleLicense(ModuleEntry.ECOMMERCE, URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce, VersionActionEnum.Insert)) { bool? skuCreated = node.CreateDefaultSKU(); if (skuCreated.HasValue && !skuCreated.Value) { lblError.Text = GetString("com.CreateDefaultSKU.Error"); } } if (node.NodeSKUID > 0) { DocumentHelper.UpdateDocument(node, tree); } // Automatically publish // Check if allowed 'Automatically publish changes' WorkflowManager wm = new WorkflowManager(tree); WorkflowInfo wi = wm.GetNodeWorkflow(node); if ((wi != null) && wi.WorkflowAutoPublishChanges && !wi.UseCheckInCheckOut(CMSContext.CurrentSiteName)) { wm.AutomaticallyPublish(node, wi, null); } // Process create another flag string script = null; if (createAnother) { script = ScriptHelper.GetScript("parent.PassiveRefresh(" + node.NodeParentID + ", " + node.NodeParentID + "); parent.CreateAnother();"); } else { script = ScriptHelper.GetScript("parent.RefreshTree(" + node.NodeID + ", " + node.NodeID + ");"); script += ScriptHelper.GetScript("parent.SelectNode(" + node.NodeID + ");"); } ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "Refresh", script); } } // Insert node if no error if (!String.IsNullOrEmpty(errorMessage)) { lblError.Text = errorMessage; lblError.Visible = true; return; } }
public ParkingTestScheduledState(WorkflowManager manager) : base(manager, WorkflowStates.ParkingTestScheduled) { }
private void PublishAndFinish(object parameter) { TreeNode node = null; Tree.AllowAsyncActions = false; CanceledString = ResHelper.GetString("content.publishcanceled", currentCulture); try { // Begin log AddLog(ResHelper.GetString("content.preparingdocuments", currentCulture)); // Get the documents DataSet documents = GetDocumentsToProcess(); if (!DataHelper.DataSourceIsEmpty(documents)) { // Create instance of workflow manager class WorkflowManager wm = new WorkflowManager(Tree); // Begin publishing AddLog(ResHelper.GetString("content.publishingdocuments", currentCulture)); foreach (DataTable classTable in documents.Tables) { foreach (DataRow nodeRow in classTable.Rows) { // Get the current document string className = ValidationHelper.GetString(nodeRow["ClassName"], string.Empty); string aliasPath = ValidationHelper.GetString(nodeRow["NodeAliasPath"], string.Empty); string docCulture = ValidationHelper.GetString(nodeRow["DocumentCulture"], string.Empty); string siteName = ValidationHelper.GetString(nodeRow["SiteName"], string.Empty); node = DocumentHelper.GetDocument(siteName, aliasPath, docCulture, false, className, null, null, -1, false, null, Tree); // Publish document if (!Publish(node, wm)) { // Add log record AddLog(HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.GetValue("DocumentCulture") + ")")); } else { AddLog(string.Format(ResHelper.GetString("content.publishedalready"), HTMLHelper.HTMLEncode(node.NodeAliasPath + " (" + node.GetValue("DocumentCulture") + ")"))); } } } CurrentInfo = GetString("workflowdocuments.publishcomplete"); } else { AddError(ResHelper.GetString("content.nothingtopublish", currentCulture)); } } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state == CMSThread.ABORT_REASON_STOP) { // When canceled CurrentInfo = CanceledString; } else { int siteId = (node != null) ? node.NodeSiteID : CMSContext.CurrentSiteID; // Log error LogExceptionToEventLog("PUBLISHDOC", "content.publishfailed", ex, siteId); } } catch (Exception ex) { int siteId = (node != null) ? node.NodeSiteID : CMSContext.CurrentSiteID; // Log error LogExceptionToEventLog("PUBLISHDOC", "content.publishfailed", ex, siteId); } }
protected void Page_Load(object sender, EventArgs e) { #region 接收参数 if (this.Request.QueryString["TaskIDs"] == null) { this.Response.Write("{\"ExecResult\":\"Failed\",\"ErrorMsg\":\"Missing required query string.\"}"); return; } string sTaskIDs = this.Request.QueryString["TaskIDs"].ToString(); if (Regex.IsMatch(sTaskIDs, @"^([1-9]\d*)(,[1-9]\d*)*$") == false) { this.Response.Write("{\"ExecResult\":\"Failed\",\"ErrorMsg\":\"Invalid query string[" + sTaskIDs + "].\"}"); return; } // LoanID bool bIsValid = PageCommon.ValidateQueryString(this, "LoanID", QueryStringType.ID); if (bIsValid == false) { this.Response.Write("{\"ExecResult\":\"Failed\",\"ErrorMsg\":\"Missing required query string.\"}"); return; } string sLoanID = this.Request.QueryString["LoanID"].ToString(); int iLoanID = Convert.ToInt32(sLoanID); #endregion // json示例 // {"ExecResult":"Success","ErrorMsg":""} // {"ExecResult":"Failed","ErrorMsg":"执行数据库脚本时发生错误。"} string sExecResult = string.Empty; string sErrorMsg = string.Empty; string sLoanClosed = "No"; string result = ""; bool bIsSuccess = false; try { // workflow api string[] TaskIDArray = sTaskIDs.Split(','); foreach (string sTaskID in TaskIDArray) { int iTaskID = Convert.ToInt32(sTaskID); #region get loan task info LoanTasks LoanTaskManager = new LoanTasks(); DataTable LoanTaskInfo = LoanTaskManager.GetLoanTaskInfo(iTaskID); if (LoanTaskInfo.Rows.Count == 0) { sErrorMsg = "Failed to delete the tasks(s) invalid task id."; return; } string sLoanStageID = LoanTaskInfo.Rows[0]["LoanStageId"].ToString(); if (sLoanStageID == string.Empty) { sErrorMsg = "Failed to delete the task(s) invalid Stage Id"; return; } int iLoanStageID = Convert.ToInt32(sLoanStageID); #endregion #region delete task bIsSuccess = LPWeb.DAL.WorkflowManager.DeleteTask(iTaskID, this.CurrUser.iUserID); if (bIsSuccess == false) { sErrorMsg = "Failed to delete the task(s) due to a Workflow Manager problem."; return; } bool StageCompletedAfter = LPWeb.BLL.WorkflowManager.StageCompleted(iLoanStageID); #endregion if (StageCompletedAfter) { #region update point file stage #region invoke PointManager.UpdateStage() string sError = LoanTaskCommon.UpdatePointFileStage(iLoanID, this.CurrUser.iUserID, iLoanStageID); // the last one, sleep 1 second System.Threading.Thread.Sleep(1000); if (sError == string.Empty) // success { bIsSuccess = true; sErrorMsg = "Deleted the task(s) successfully."; } else { sErrorMsg = "Deleted the task(s) but failed to update stage date in Point."; return; } if (WorkflowManager.IsLoanClosed(iLoanID)) { sLoanClosed = "Yes"; } #endregion #endregion } } return; } catch (Exception ex) { sErrorMsg = "Failed to delete selected task(s): " + ex.ToString().Replace("\"", "\\\""); return; } finally { string sEmailTemplateID = ""; if (bIsSuccess) { result = "{\"ExecResult\":\"Success\",\"ErrorMsg\":\"" + sErrorMsg + "\",\"EmailTemplateID\":\"" + sEmailTemplateID + "\",\"LoanClosed\":\"" + sLoanClosed + "\"}"; } else { result = "{\"ExecResult\":\"Failed\",\"ErrorMsg\":\"" + sErrorMsg + "\"}"; } Response.Write(result); } }