public void SetUp() { engine = new Fakes.FakeEngine(new Type[] { typeof(ContentHandlerTestsPage), typeof(ContentHandlerTestsPart), typeof(Fakes.FakeNodeAdapter) }); //engine.Resolve<Fakes.FakeNodeAdapter>().Engine = engine; handler = new ContentHandler(engine); context = new Fakes.FakeWebContextWrapper(); context.HttpContext.User = SecurityUtilities.CreatePrincipal("Admin"); startPage = new ContentHandlerTestsPage { Title = "Start page" }; engine.Persister.Save(startPage); page = new ContentHandlerTestsPage { Title = "Page in question" }; page.AddTo(startPage); engine.Persister.Save(page); engine.AddComponentInstance<IWebContext>(context); engine.AddComponentInstance<IUrlParser>(new Fakes.FakeUrlParser(startPage: startPage)); var persister = engine.Persister; var activator = engine.Resolve<ContentActivator>(); var versionRepository = TestSupport.CreateVersionRepository(ref persister, ref activator, new Type[] { typeof(ContentHandlerTestsPage), typeof(ContentHandlerTestsPart) }); engine.AddComponentInstance<ContentVersionRepository>(versionRepository); engine.AddComponentInstance<VersionManager>(versionManager = TestSupport.SetupVersionManager(engine.Persister, versionRepository)); (engine.Resolve<IContentAdapterProvider>() as N2.Plugin.IAutoStart).Start(); engine.Resolve<IContentAdapterProvider>().ResolveAdapter<N2.Edit.NodeAdapter>(typeof(ContentItem)).Engine = engine; engine.AddComponentInstance(new HtmlSanitizer(new N2.Configuration.HostSection())); engine.AddComponentInstance<IEditUrlManager>(new FakeEditUrlManager()); engine.AddComponentInstance(new ConfigurationManagerWrapper()); engine.AddComponentInstance<ILanguageGateway>(new FakeLanguageGateway()); engine.AddComponentInstance(new DraftRepository(versionRepository, new FakeCacheWrapper())); }
public override void TestFixtureSetUp() { base.TestFixtureSetUp(); persister = (ContentPersister) engine.Resolve<IPersister>(); versioner = (VersionManager) engine.Resolve<IVersionManager>(); engine.SecurityManager.ScopeEnabled = false; }
public override void SetUp() { base.SetUp(); var types = new[] { typeof(Items.PageItem), typeof(Items.DataItem) }; versionRepository = TestSupport.CreateVersionRepository(ref persister, ref activator, types); versions = TestSupport.SetupVersionManager(persister, versionRepository); copyer = new ItemCopyer( // persister, new Navigator(persister, TestSupport.SetupHost(), new VirtualNodeFactory(), TestSupport.SetupContentSource()), new FakeIntegrityManager(), versions, versionRepository); request = new NameValueCollection(); root = CreateOneItem<Items.PageItem>(0, "root", null); }
public void SetUp() { engine = new Fakes.FakeEngine(new Type[] { typeof(ContentHandlerTestsPage) }); handler = new ContentHandler(engine); context = new Fakes.FakeWebContextWrapper(); context.HttpContext.User = SecurityUtilities.CreatePrincipal("Admin"); startPage = new ContentHandlerTestsPage { Title = "Start page" }; engine.Persister.Save(startPage); page = new ContentHandlerTestsPage { Title = "Page in question" }; page.AddTo(startPage); engine.Persister.Save(page); engine.AddComponentInstance<IWebContext>(context); engine.AddComponentInstance<IUrlParser>(new Fakes.FakeUrlParser(startPage: startPage)); var versionRepository = TestSupport.CreateVersionRepository(new Type[] { typeof(ContentHandlerTestsPage) }); engine.AddComponentInstance<ContentVersionRepository>(versionRepository); engine.AddComponentInstance<VersionManager>(versionManager = TestSupport.SetupVersionManager(engine.Persister, versionRepository)); }
public override WidgetResult Show(IssueDto issue = null) { var filter = IsSessionFilter() || CurrentCard.CardType != ProjectTemplatePageType.Custom && "app/changelog/view".Equals(CurrentCard.Url, StringComparison.InvariantCultureIgnoreCase) ? HttpSessionManager.GetFilter(CurrentCard.Id, IssuesFilter.CreateProjectFilter(CurrentUser.Entity.Id, CurrentProject.Entity.Id)) : CurrentCard.Filter; HttpSessionManager.SetFilter(CurrentCard.Id, filter); var workspaceProjects = new List <int>(); int?currentProjectId = 0; int versionId = 0; HttpSessionManager.Set <List <UserIssuesView> >(null, Constants.ChangelogSessionView); // Safety check required because of http://gemini.countersoft.com/project/DEV/21/item/5088 PageSettings pageSettings = null; try { if (CurrentCard.Options.ContainsKey(AppGuid)) { pageSettings = CurrentCard.Options[AppGuid].FromJson <PageSettings>(); if (pageSettings.PageData != null) { currentProjectId = pageSettings.PageData.projectId; versionId = pageSettings.PageData.versionId; } } } catch (Exception ex) {} var activeProjects = ProjectManager.GetActive(); var viewableProjects = new List <ProjectDto>(); if (activeProjects == null || activeProjects.Count == 0) { activeProjects = new List <ProjectDto>(); } else { viewableProjects = ProjectManager.GetAppViewableProjects(this); } if (!viewableProjects.Any(s => s.Entity.Id == currentProjectId.Value)) { currentProjectId = viewableProjects.Count > 0 ? viewableProjects.First().Entity.Id : 0; } UserContext.Project = ProjectManager.Get(currentProjectId); IEnumerable <Countersoft.Gemini.Commons.Entity.Version> versions = null; // get all versions that are released or not according to settings passed (BUT - NEVER show archived projects) versions = Cache.Versions.GetAll().Where(v => v.ProjectId == currentProjectId && v.Released == true && v.Archived == false).OrderBy(o => o.Sequence); if (versionId == 0) { VersionDto version = VersionManager.GetFirstChangeLogVersion(UserContext.Project.Entity.Id); if (version != null) { versionId = version.Entity.Id; } else { versionId = versions.Count() > 0 ? versions.First().Id : 0; } } Changelog.Models.ChangelogpAppModel model = BuildModelData(versionId, versions); model.ProjectList = new SelectList(viewableProjects, "Entity.Id", "Entity.Name", currentProjectId.GetValueOrDefault()); if (pageSettings == null) { pageSettings = new PageSettings(); } pageSettings.PageData.versionId = versionId; pageSettings.PageData.projectId = currentProjectId.GetValueOrDefault(); CurrentCard.Options[AppGuid] = pageSettings.ToJson(); return(new WidgetResult() { Success = true, Markup = new WidgetMarkup("views/Changelog.cshtml", model) }); }
public override void Execute(CommandContext context) { Assert.ArgumentNotNull(context, "context"); VersionManager.Refresh(); SheerResponse.SetLocation(string.Empty); }
private Changelog.Models.ChangelogpAppModel BuildModelData(int versionId, IEnumerable <Countersoft.Gemini.Commons.Entity.Version> iVersions, IssuesFilter OriginalFilter = null) { StringBuilder builder = new StringBuilder(); Changelog.Models.ChangelogpAppModel model = new Changelog.Models.ChangelogpAppModel(); List <VersionDto> versions = VersionManager.ConvertDesc(new List <Countersoft.Gemini.Commons.Entity.Version>(iVersions)); if (versions.Count != iVersions.Count()) { // Need to get the version again as parents is missing, probably released foreach (var ver in iVersions) { if (versions.Find(v => v.Entity.Id == ver.Id) == null) { int index = versions.FindIndex(v => v.Entity.Sequence > ver.Sequence); if (index == -1) { versions.Add(VersionManager.Convert(ver)); } else { versions.Insert(index, VersionManager.Convert(ver)); } } } } IssuesFilter filter = new IssuesFilter(); // Build up the progress data on all the cards as we go foreach (var version in versions) { Changelog.Models.ChangelogpAppModel tmp = new Changelog.Models.ChangelogpAppModel(); builder.Append(BuildAllProjectVersions(version.Entity, version.Entity.Id == versionId, version.HierarchyLevel)); if (version.Entity.Id == versionId) { List <IssueDto> issues = IssueManager.GetRoadmap(UserContext.Project.Entity.Id, null, version.Entity.Id); var visibility = GetChangelogFields(UserContext.Project.Entity.Id); var properties = GridManager.GetDisplayProperties(MetaManager.TypeGetAll(new List <ProjectDto>() { CurrentProject }), visibility, new List <int>() { version.Project.Entity.Id }); List <ColumnInfoModel> gridColumns = GridManager.DescribeGridColumns(properties); GridOptionsModel gridOptions = GridManager.DescribeGridOptions(); // get the version specific data tmp.Issues = issues; tmp.Columns = gridColumns; tmp.Options = gridOptions; tmp.Closed = tmp.Issues.Count(i => i.IsClosed); tmp.Open = tmp.Issues.Count(i => !i.IsClosed); tmp.Statuses = (from i in tmp.Issues group i by new { Id = i.Entity.StatusId, Name = i.Status } into g select new Triple <string, int, string>(g.Key.Name, g.Count(), string.Format("{0}{1}?versions={2}&statuses={3}", UserContext.Url, NavigationHelper.GetProjectPageUrl(UserContext.Project, ProjectTemplatePageType.Items), versionId, g.Key.Id))).OrderByDescending(g => g.Second).Take(3); tmp.Types = (from i in tmp.Issues group i by new { Id = i.Entity.TypeId, Name = i.Type } into g select new Triple <string, int, string>(g.Key.Name, g.Count(), string.Format("{0}{1}?versions={2}&types={3}&includeclosed=yes", UserContext.Url, NavigationHelper.GetProjectPageUrl(UserContext.Project, ProjectTemplatePageType.Items), versionId, g.Key.Id))).OrderByDescending(g => g.Second).Take(3); // store the version Id model.VersionId = version.Entity.Id; model.VersionLabel = version.Entity.Name; model.Closed = tmp.Closed; model.Columns = tmp.Columns; model.Issues = tmp.Issues; model.DisplayData = GridManager.GetDisplayData(tmp.Issues, tmp.Columns); model.Open = tmp.Open; model.Options = tmp.Options; model.Statuses = tmp.Statuses; model.Types = tmp.Types; model.Estimated = issues.Sum(i => i.Entity.EstimatedHours * 60 + i.EstimatedMinutes); model.Logged = issues.Sum(i => i.Entity.LoggedHours * 60 + i.Entity.LoggedMinutes); model.Remain = model.Estimated > model.Logged ? model.Estimated - model.Logged : 0; model.TimeLoggedOver = model.Logged > model.Estimated ? model.Logged - model.Estimated : 0; model.ReleaseStartDate = version.Entity.StartDate; model.ReleaseEndDate = version.Entity.ReleaseDate; // Now get with the extra data that we need var projectId = UserContext.Project.Entity.Id; IssuesGridFilter defaultFilter = new IssuesGridFilter(IssuesFilter.CreateProjectFilter(CurrentUser.Entity.Id, CurrentProject.Entity.Id)); filter = IssuesFilter.CreateVersionFilter(CurrentUser.Entity.Id, CurrentProject.Entity.Id, version.Entity.Id); if (OriginalFilter != null) { filter.SortField = OriginalFilter.SortField; filter.SortOrder = OriginalFilter.SortOrder; } ItemFilterManager.SetSortedColumns(gridColumns, filter); model.Filter = IssueFilterHelper.PopulateModel(model.Filter, filter, filter, PermissionsManager, ItemFilterManager, IssueFilterHelper.GetViewableFields(filter, ProjectManager, MetaManager), false); } } // attach version cards model.VersionCards = builder.ToString(); // Visibility model[ItemAttributeVisibility.Status] = CanSeeProjectItemAttribute(ItemAttributeVisibility.Status); model[ItemAttributeVisibility.EstimatedEffort] = CanSeeProjectItemAttribute(ItemAttributeVisibility.EstimatedEffort); model[ItemAttributeVisibility.CalculatedTimeLogged] = CanSeeProjectItemAttribute(ItemAttributeVisibility.CalculatedTimeLogged); model[ItemAttributeVisibility.CalculatedTimeRemaining] = model[ItemAttributeVisibility.EstimatedEffort] && model[ItemAttributeVisibility.CalculatedTimeLogged]; StringBuilder sort = new StringBuilder(); List <string> sorting = new IssuesFilter().GetSortFields(); List <int> orders = new IssuesFilter().GetSortOrders(); for (int i = 0; i < sorting.Count; i++) { sort.AppendFormat("{0}|{1}", sorting[i], orders[i] == 1 ? 0 : 1); } model.Sort = sort.ToString(); model.CurrentPageCard = CurrentCard; return(model); }
/// <summary> /// Restores set of given version histories. /// </summary> /// <param name="currentUserInfo">Current user info</param> /// <param name="recycleBin">DataSet with nodes to restore</param> private void RestoreDataSet(CurrentUserInfo currentUserInfo, DataSet recycleBin) { // Result flags bool resultOK = true; bool permissionsOK = true; if (!DataHelper.DataSourceIsEmpty(recycleBin)) { TreeProvider tree = new TreeProvider(currentUserInfo); tree.AllowAsyncActions = false; VersionManager verMan = new VersionManager(tree); // Restore all documents foreach (DataRow dataRow in recycleBin.Tables[0].Rows) { int versionId = ValidationHelper.GetInteger(dataRow["VersionHistoryID"], 0); // Log actual event string taskTitle = HTMLHelper.HTMLEncode(ValidationHelper.GetString(dataRow["DocumentNamePath"], string.Empty)); // Restore document if (versionId > 0) { // Check permissions TreeNode tn = null; if (!IsAuthorizedPerDocument(versionId, "Create", currentUser, out tn, verMan)) { CurrentError = String.Format(ResHelper.GetString("Recyclebin.RestorationFailedPermissions", currentCulture), taskTitle); AddLog(CurrentError); permissionsOK = false; } else { tn = verMan.RestoreDocument(versionId, tn); if (tn != null) { AddLog(ResHelper.GetString("general.document", currentCulture) + "'" + taskTitle + "'"); } else { // Set result flag if (resultOK) { resultOK = false; } } } } } } if (resultOK && permissionsOK) { CurrentInfo = ResHelper.GetString("Recyclebin.RestorationOK", currentCulture); AddLog(CurrentInfo); } else { CurrentError = ResHelper.GetString("Recyclebin.RestorationFailed", currentCulture); if (!permissionsOK) { CurrentError += "<br />" + ResHelper.GetString("recyclebin.errorsomenotrestored", currentCulture); } AddLog(CurrentError); } }
/// <summary> /// Restores the document from the recycle bin. Called when the "Restore document" button is pressed. /// Expects the "CreateDocumentStructure" and "MoveDocumentToRecycleBin" methods to be run first. /// </summary> private bool RestoreFromRecycleBin() { // Prepare the where condition string where = "VersionNodeAliasPath LIKE N'/API-Example/Document-1'"; // Get the recycled document DataSet recycleBin = VersionHistoryInfoProvider.GetRecycleBin(CMSContext.CurrentSiteID, where, null, 0, "VersionHistoryID"); if (!DataHelper.DataSourceIsEmpty(recycleBin)) { // Create a new version history info object from the data row VersionHistoryInfo version = new VersionHistoryInfo(recycleBin.Tables[0].Rows[0]); // Create a new version manager instance and restore the document VersionManager manager = new VersionManager(new TreeProvider(CMSContext.CurrentUser)); manager.RestoreDocument(version.VersionHistoryID); return true; } return false; }
public void Unpresisted_ChildParts_AreMainteinedWhenRestoringVersions() { var master = CreateOneItem<Items.NormalPage>(0, "master", null); persister.Save(master); var part = CreateOneItem<Items.NormalItem>(0, "part", master); part.ZoneName = "TheZone"; var part2 = CreateOneItem<Items.NormalItem>(0, "part2", part); part2.ZoneName = "TheZone"; var manager = new VersionManager(repository, persister.Repository, new StateChanger(), new N2.Configuration.EditSection()); var version = manager.AddVersion(master, asPreviousVersion: false); persister.Dispose(); master = (Items.NormalPage)persister.Get(master.ID); version = manager.GetVersion(master, version.VersionIndex); version.Children.Single().Name.ShouldBe("part"); version.Children.Single().Children.Single().Name.ShouldBe("part2"); }
/// <summary> /// Gets a dataset of documents in the example section and updates them. Called when the "Get and update documents" button is pressed. /// Expects the "CreateExampleObjects" and "CreateDocument" methods to be run first. /// </summary> private bool GetAndUpdateDocuments() { // Create an instance of the Tree provider first TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Prepare parameters string siteName = CMSContext.CurrentSiteName; string aliasPath = "/API-Example/%"; string culture = "en-us"; bool combineWithDefaultCulture = false; string classNames = "CMS.MenuItem"; string where = null; string orderBy = null; int maxRelativeLevel = -1; bool selectOnlyPublished = false; // Fill dataset with documents DataSet documents = DocumentHelper.GetDocuments(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, tree); if (!DataHelper.DataSourceIsEmpty(documents)) { // Create a new Version manager instance VersionManager manager = new VersionManager(tree); // Loop through all documents foreach (DataRow documentRow in documents.Tables[0].Rows) { // Create a new Tree node from the data row TreeNode editDocument = TreeNode.New(documentRow, "CMS.MenuItem", tree); // Check out the document manager.CheckOut(editDocument); string newName = editDocument.DocumentName.ToLower(); // Change document data editDocument.DocumentName = newName; // Change coupled data editDocument.SetValue("MenuItemName", newName); // Save the changes DocumentHelper.UpdateDocument(editDocument, tree); // Check in the document manager.CheckIn(editDocument, null, null); } return true; } return false; }
private void RemoveWorkflow(object parameter) { VersionManager verMan = VersionManager.GetInstance(Tree); TreeNode node = null; // Custom logging Tree.LogEvents = false; Tree.AllowAsyncActions = false; CanceledString = ResHelper.GetString("workflowdocuments.removingcanceled", currentCulture); try { // Begin log AddLog(ResHelper.GetString("content.preparingdocuments", currentCulture)); string where = parameter as string; // Get the documents DataSet documents = GetDocumentsToProcess(where); if (!DataHelper.DataSourceIsEmpty(documents)) { // Begin log AddLog(ResHelper.GetString("workflowdocuments.removingwf", 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); // Get published version node = Tree.SelectSingleNode(siteName, aliasPath, docCulture, false, className, false); string encodedAliasPath = HTMLHelper.HTMLEncode(ValidationHelper.GetString(aliasPath, string.Empty) + " (" + node.GetValue("DocumentCulture") + ")"); // Destroy document history verMan.DestroyDocumentHistory(node.DocumentID); using (new CMSActionContext { LogEvents = false }) { // Clear workflow DocumentHelper.ClearWorkflowInformation(node); node.Update(); } // Add log record AddLog(encodedAliasPath); // Add record to eventlog LogContext.LogEvent(EventType.INFORMATION, "Content", "REMOVEDOCWORKFLOW", string.Format(GetString("workflowdocuments.removeworkflowsuccess"), encodedAliasPath), RequestContext.RawURL, currentUser.UserID, currentUser.UserName, node.NodeID, node.GetDocumentName(), RequestContext.UserHostAddress, node.NodeSiteID, SystemContext.MachineName, RequestContext.URLReferrer, RequestContext.UserAgent, DateTime.Now); } } CurrentInfo = GetString("workflowdocuments.removecomplete"); } else { AddError(ResHelper.GetString("workflowdocuments.nodocumentstoclear", 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 : SiteContext.CurrentSiteID; // Log error LogExceptionToEventLog("REMOVEDOCWORKFLOW", "workflowdocuments.removefailed", ex, siteId); } } catch (Exception ex) { int siteId = (node != null) ? node.NodeSiteID : SiteContext.CurrentSiteID; // Log error LogExceptionToEventLog("REMOVEDOCWORKFLOW", "workflowdocuments.removefailed", ex, siteId); } }
public void OpenProjectDiagrams() { #if DEBUG if (Environment.MachineName.Contains("TRUPIK")) { string currentFile = CurrentProject.FilePath; List <string> recentFiles; if (File.Exists(lastFilePath)) { recentFiles = File.ReadAllLines(lastFilePath).ToList(); } else { recentFiles = new List <string>(); } if (!String.IsNullOrEmpty(currentFile)) { if (recentFiles.Contains(currentFile)) { recentFiles.Remove(currentFile); } recentFiles.Insert(0, currentFile); } bOpenProject.ContextMenu = new ContextMenu(); foreach (string recentFile in recentFiles) { if (!string.IsNullOrEmpty(recentFile)) { string name = Path.GetFileNameWithoutExtension(recentFile); ContextMenuItem cmi = new ContextMenuItem(name); cmi.DataContext = recentFile; cmi.Click += delegate { OpenProject((string)cmi.DataContext); }; bOpenProject.ContextMenu.Items.Add(cmi); } } File.WriteAllLines(lastFilePath, recentFiles.Take(15).ToArray()); if (System.Windows.Forms.Screen.AllScreens.Length > 1) { this.WindowState = WindowState.Normal; this.Left = System.Windows.Forms.Screen.AllScreens[0].Bounds.X; this.Top = System.Windows.Forms.Screen.AllScreens[0].Bounds.Y; this.Width = System.Windows.Forms.Screen.AllScreens[0].Bounds.Width; this.Height = System.Windows.Forms.Screen.AllScreens[0].Bounds.Height; } } #endif if (CurrentProject != null) { VersionManager versionManager = CurrentProject.VersionManager; // HACK - TRUPIK: added for simplier debugging, only on my machine.. if (Environment.MachineName.Contains("TRUPIK") && versionManager != null && versionManager.Versions.Count == 2) { Version v1 = versionManager.Versions[0]; Version v2 = versionManager.Versions[1]; ObservableCollection <PSMDiagram> diagramsV1 = versionManager.VersionedProjects[v1].PSMDiagrams; ObservableCollection <PSMDiagram> diagramsV2 = versionManager.VersionedProjects[v2].PSMDiagrams; if (diagramsV1.Count > 0) { DiagramTabManager.AddTab(diagramsV1.Last()); propertiesWindow.BindDiagram(ref dockManager); } if (diagramsV2.Count > 0) { DiagramTabManager.AddTab(diagramsV2.Last()); propertiesWindow.BindDiagram(ref dockManager); } if (diagramsV1.Count == 0 && diagramsV2.Count == 0) { ObservableCollection <PIMDiagram> pimDiagramsV1 = versionManager.VersionedProjects[v1].PIMDiagrams; ObservableCollection <PIMDiagram> pimDiagramsV2 = versionManager.VersionedProjects[v2].PIMDiagrams; if (pimDiagramsV1.Count > 0) { DiagramTabManager.AddTab(pimDiagramsV1.Last()); propertiesWindow.BindDiagram(ref dockManager); } if (pimDiagramsV2.Count > 0) { DiagramTabManager.AddTab(pimDiagramsV2.Last()); propertiesWindow.BindDiagram(ref dockManager); } } //DocumentPane.NewVerticalTabGroupCommand.Execute(null, DiagramTabManager.ActivePane); DiagramTabManager.ActivePane.CreateNewVerticalTabGroup(); if (diagramsV2.Count > 0) { DiagramTabManager.ActivateDiagram(diagramsV2.Last()); } } else { for (int i = 0; i < Math.Min(CurrentProject.Diagrams.Count, 8); i++) { DiagramTabManager.AddTab(CurrentProject.Diagrams[i]); propertiesWindow.BindDiagram(ref dockManager); } } } }
public override WidgetResult Show(IssueDto issue = null) { var filter = IsSessionFilter() || CurrentCard.CardType != ProjectTemplatePageType.Custom && "app/roadmap/view".Equals(CurrentCard.Url, StringComparison.InvariantCultureIgnoreCase) ? HttpSessionManager.GetFilter(CurrentCard.Id, IssuesFilter.CreateProjectFilter(CurrentUser.Entity.Id, CurrentProject.Entity.Id)) : CurrentCard.Filter; HttpSessionManager.SetFilter(CurrentCard.Id, filter); int? currentProjectId = 0; bool includeSubversions = false; int versionId = 0; HttpSessionManager.Set <List <UserIssuesView> >(null, Constants.RoadmapSessionView); // Safety check required because of http://gemini.countersoft.com/project/DEV/21/item/5088 PageSettings pageSettings = null; try { if (CurrentCard.Options.ContainsKey(AppGuid)) { pageSettings = CurrentCard.Options[AppGuid].FromJson <PageSettings>(); if (pageSettings.PageData != null) { currentProjectId = pageSettings.PageData.projectId; versionId = pageSettings.PageData.versionId; includeSubversions = pageSettings.PageData.includeSubversions; } } } catch { } //If no project is selected, select the first workspace project. if ((!currentProjectId.HasValue || currentProjectId.Value == 0) && filter.Projects.HasValue()) { try { var workspaceProjects = filter.Projects.Split('|'); if (workspaceProjects.Count() > 0) { currentProjectId = Convert.ToInt32(workspaceProjects[0]); } } catch { } } var viewableProjects = ProjectManager.GetAppViewableProjects(this).ToList(); if (!viewableProjects.Any(s => s.Entity.Id == currentProjectId.Value)) { currentProjectId = viewableProjects.Count > 0 ? viewableProjects.First().Entity.Id : 0; } UserContext.Project = ProjectManager.Get(currentProjectId); IEnumerable <Countersoft.Gemini.Commons.Entity.Version> versions = null; // get all versions that are released or not according to settings passed (BUT - NEVER show archived projects) versions = Cache.Versions.GetAll().Where(v => v.ProjectId == currentProjectId && v.Released == false && v.Archived == false).OrderBy(o => o.Sequence); if (versionId == 0) { VersionDto version = VersionManager.GetFirstRoadmapVersion(UserContext.Project.Entity.Id); if (version != null) { versionId = version.Entity.Id; } else { versionId = versions.Count() > 0 ? versions.First().Id : 0; } } List <IssueDto> issues; issues = IssueManager.GetRoadmap(UserContext.Project.Entity.Id, filter, versionId); if (includeSubversions) { var child = versions.Where(v => v.ParentId == versionId).ToList(); AddChildVersions(versions.ToList(), UserContext.Project.Entity.Id, filter, child, ref issues); } RoadmapAppModel model = BuildModelData(versionId, versions, issues); model.ProjectList = new SelectList(viewableProjects, "Entity.Id", "Entity.Name", currentProjectId.GetValueOrDefault()); model.IncludeSubVersions = includeSubversions; if (pageSettings == null) { pageSettings = new PageSettings(); } pageSettings.PageData.versionId = versionId; pageSettings.PageData.projectId = currentProjectId.GetValueOrDefault(); CurrentCard.Options[AppGuid] = pageSettings.ToJson(); //var view = RenderPartialViewToString(this, "~/views/Roadmap.cshtml", model); return(new WidgetResult() { Success = true, Markup = new WidgetMarkup("views/Roadmap.cshtml", model) }); }
/// <summary> /// This method will /// 1. Make sure if a Feature Layer is selected. /// 2. The Workspace is not null /// 3. Make sure that the workspace is an Enterprise SQL Server Geodatabase Workspace /// /// and then create a new version (In a Queued Task) /// and Connect to the newly created version and delete all the features for the selected subtype (In a separate QueuedTask) /// </summary> /// <param name="item">The newly selected combo box item</param> protected override async void OnSelectionChange(ComboBoxItem item) { if (item == null) { return; } if (string.IsNullOrEmpty(item.Text)) { return; } Layer layer = MapView.Active.GetSelectedLayers()[0]; FeatureLayer featureLayer = null; if (layer is FeatureLayer) { featureLayer = layer as FeatureLayer; Geodatabase geodatabase = null; await QueuedTask.Run(() => geodatabase = (featureLayer.GetTable().GetDatastore() as Geodatabase)); using (geodatabase) { if (geodatabase == null) { return; } } } else { return; } EnterpriseDatabaseType enterpriseDatabaseType = EnterpriseDatabaseType.Unknown; await QueuedTask.Run(() => { using (Table table = (MapView.Active.GetSelectedLayers()[0] as FeatureLayer).GetTable()) { try { var geodatabase = table.GetDatastore() as Geodatabase; enterpriseDatabaseType = (geodatabase.GetConnector() as DatabaseConnectionProperties).DBMS; } catch (InvalidOperationException) { } } }); if (enterpriseDatabaseType != EnterpriseDatabaseType.SQLServer) { Enabled = false; return; } string versionName = String.Empty; await QueuedTask.Run(async() => { using (Table table = featureLayer.GetTable()) { versionName = await CreateVersion(table); } }); if (versionName == null) { return; } await QueuedTask.Run(() => { using (Table table = featureLayer.GetTable()) { if (table.GetRegistrationType().Equals(RegistrationType.Nonversioned)) { return; } } }); await QueuedTask.Run(async() => { using (Table table = featureLayer.GetTable()) { string subtypeField = table.GetDefinition().GetSubtypeField(); int code = table.GetDefinition().GetSubtypes().First(subtype => subtype.GetName().Equals(item.Text)).GetCode(); QueryFilter queryFilter = new QueryFilter { WhereClause = string.Format("{0} = {1}", subtypeField, code) }; try { VersionManager versionManager = (table.GetDatastore() as Geodatabase).GetVersionManager(); Version newVersion = versionManager.GetVersions().First(version => version.GetName().Contains(versionName)); Geodatabase newVersionGeodatabase = newVersion.Connect(); using (Table newVersionTable = newVersionGeodatabase.OpenDataset <Table>(table.GetName())) { using (var rowCursor = newVersionTable.Search(queryFilter, false)) { EditOperation editOperation = new EditOperation { EditOperationType = EditOperationType.Long, Name = "Delete Based On Subtype" }; editOperation.Callback(context => { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { context.Invalidate(row); row.Delete(); } } }, newVersionTable); bool result = await editOperation.ExecuteAsync(); if (!result) { MessageBox.Show(String.Format("Could not delete features for subtype {0} : {1}", item.Text, editOperation.ErrorMessage)); } await Project.Current.SaveEditsAsync(); } } } catch (Exception e) { Console.WriteLine(e); } } }); }
public void Initialize() { vm = new VersionManager(); }
/// <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; }
private static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; var commandName = string.Empty; var commandArgs = new List <string>(); if (args.Length >= 1) { for (var i = 0; i < args.Length; i++) { if (i == 0) { commandName = args[i]; } else { commandArgs.Add(args[i]); } } } Console.WriteLine("Welcome to SiteServer Cli Tool"); Console.WriteLine(); try { if (StringUtils.EqualsIgnoreCase(commandName, BackupManager.CommandName)) { BackupManager.Execute(commandArgs.ToArray()); } else if (StringUtils.EqualsIgnoreCase(commandName, RestoreManager.CommandName)) { RestoreManager.Execute(commandArgs.ToArray()); } else if (StringUtils.EqualsIgnoreCase(commandName, UpdateManager.CommandName)) { UpdateManager.Execute(commandArgs.ToArray()); } else if (StringUtils.EqualsIgnoreCase(commandName, VersionManager.CommandName)) { VersionManager.Execute(commandArgs.ToArray()); } else if (StringUtils.EqualsIgnoreCase(commandName, TestManager.CommandName)) { TestManager.Execute(commandArgs.ToArray()); } else { CliUtils.PrintLine(); CliUtils.PrintRow("Usage"); CliUtils.PrintLine(); BackupManager.PrintUsage(); RestoreManager.PrintUsage(); UpdateManager.PrintUsage(); VersionManager.PrintUsage(); CliUtils.PrintLine(); CliUtils.PrintRow("http://www.siteserver.cn/docs/cli"); CliUtils.PrintLine(); Console.ReadLine(); } } catch (Exception ex) { CliUtils.PrintError(ex.Message); var errorLogFilePath = CliUtils.CreateErrorLogFile("siteserver"); CliUtils.AppendErrorLogs(errorLogFilePath, new List <TextLogInfo> { new TextLogInfo { DateTime = DateTime.Now, Detail = "Console Error", Exception = ex } }); } }
public void SavedAsPrevious_IsNotFoundAsDraft() { var master = CreateOneItem<Items.NormalPage>(0, "pageX", null); persister.Save(master); var manager = new VersionManager(repository, persister.Repository, new StateChanger(), new N2.Configuration.EditSection()); manager.AddVersion(master, asPreviousVersion: true); drafts.FindDrafts().Any().ShouldBe(false); }
public static TrafficLightStatus GetTrafficLight(string userName, string itemId, bool requiresAck) { TrafficLightStatus tlStatus = new TrafficLightStatus(); string groupId = VersionManager.GetVersionByItemId(itemId).GroupId; IList <VersionItem> publishedVersions = VersionManager.GetPublishedVersions(groupId); int currentVersPubMajPart = Int32.Parse(publishedVersions[0].VersionNumber.Split('.')[0]); //for a minor -> minor change if (publishedVersions[0].EditSeverity.Equals("minor")) { foreach (VersionItem version in publishedVersions) { int temp = Int32.Parse(version.VersionNumber.Split('.')[0]); if (temp == currentVersPubMajPart) { //reset traffic light if ack required else check audit table(reset if no record exists) //the scenario for traffic lights when its a major publish and acknowledgement is not required(traffic light stays green) is not covered here since we are not capturing that in Audit table. if (!requiresAck) { if (AuditManager.GetAuditItems(userName, version.ItemId, AuditRecord.AuditAction.Viewed).Count > 0) { tlStatus.Viewed = true; break; } if (AuditManager.GetAuditItems(userName, version.ItemId, AuditRecord.AuditAction.Acknowledged).Count > 0) { tlStatus.Viewed = true; break; } } else { if (AuditManager.GetAuditItems(userName, version.ItemId, AuditRecord.AuditAction.Acknowledged).Count > 0) { tlStatus.Acknowledged = true; break; } } } } } else { if (!requiresAck) { if (AuditManager.GetAuditItems(userName, itemId, AuditRecord.AuditAction.Viewed).Count > 0) { tlStatus.Viewed = true; } } else { if (AuditManager.GetAuditItems(userName, itemId, AuditRecord.AuditAction.Acknowledged).Count > 0) { tlStatus.Acknowledged = true; } } } tlStatus.RequiresAck = requiresAck; return(tlStatus); }
public void AutoImplementedProperties_AreMaintained() { var master = CreateOneItem<Items.NormalPage>(0, "master", null); master.WidthType = Items.WidthType.Pixels; master.Width = 123; persister.Save(master); var manager = new VersionManager(repository, persister.Repository, new StateChanger(), new N2.Configuration.EditSection()); var version = (Items.NormalPage)manager.AddVersion(master, asPreviousVersion: false); persister.Dispose(); master = (Items.NormalPage)persister.Get(master.ID); version = (Items.NormalPage)manager.GetVersion(master, version.VersionIndex); version.WidthType.ShouldBe(Items.WidthType.Pixels); version.Width.ShouldBe(123); }
/// <summary> /// Handles attachment edit action. /// </summary> /// <param name="argument">Attachment GUID coming from view control</param> private void HandleAttachmentEdit(string argument) { IsEditImage = true; if (!string.IsNullOrEmpty(argument)) { string[] argArr = argument.Split('|'); Guid attachmentGuid = ValidationHelper.GetGuid(argArr[1], Guid.Empty); AttachmentInfo ai = null; int versionHistoryId = 0; if (TreeNodeObj != null) { versionHistoryId = TreeNodeObj.DocumentCheckedOutVersionHistoryID; } if (versionHistoryId == 0) { ai = AttachmentManager.GetAttachmentInfo(attachmentGuid, CMSContext.CurrentSiteName); } else { VersionManager vm = new VersionManager(TreeNodeObj.TreeProvider); if (vm != null) { // Get the attachment version data AttachmentHistoryInfo attachmentVersion = vm.GetAttachmentVersion(versionHistoryId, attachmentGuid, false); if (attachmentVersion == null) { ai = null; } else { // Create the attachment info from given data ai = new AttachmentInfo(attachmentVersion.Generalized.DataClass); ai.AttachmentID = attachmentVersion.AttachmentHistoryID; } if (ai != null) { ai.AttachmentLastHistoryID = versionHistoryId; } } } if (ai != null) { string nodeAliasPath = ""; if (TreeNodeObj != null) { nodeAliasPath = TreeNodeObj.NodeAliasPath; } string url = mediaView.GetAttachmentItemUrl(ai.AttachmentGUID, ai.AttachmentName, nodeAliasPath, ai.AttachmentImageHeight, ai.AttachmentImageWidth, 0); if (LastAttachmentGuid == attachmentGuid) { SelectMediaItem(ai.AttachmentName, ai.AttachmentExtension, ai.AttachmentImageWidth, ai.AttachmentImageHeight, ai.AttachmentSize, url); } // Update select action to reflect changes made during editing LoadDataSource(); mediaView.Reload(); pnlUpdateView.Update(); } } ClearActionElems(); }
public void AncestralTrail_IsUpdated_WhenUsing_VersioningManager() { PersistableItem root = CreateOneItem<PersistableItem>(0, "root", null); PersistableItem one = CreateOneItem<PersistableItem>(0, "one", root); persister.Repository.SaveOrUpdate(root, one); VersionManager vm = new VersionManager(TestSupport.CreateVersionRepository(typeof(PersistableItem)), persister.Repository, new N2.Edit.Workflow.StateChanger(), new N2.Configuration.EditSection()); var version = vm.AddVersion(one); one.Name += "2"; persister.Save(one); Assert.That(version.AncestralTrail, Is.EqualTo("/")); Assert.That(one.AncestralTrail, Is.EqualTo("/" + root.ID + "/")); }
/// <summary> /// Reverts back the changes made in the latest version if check-in/check-out is used. Called when the "Undo check-out" button is pressed. /// Expects the "CreateExampleObjects" and "CheckOut" methods to be run first. /// </summary> private bool UndoCheckout() { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Prepare parameters string siteName = CMSContext.CurrentSiteName; string aliasPath = "/API-Example"; string culture = "en-us"; bool combineWithDefaultCulture = false; string classNames = TreeProvider.ALL_CLASSNAMES; string where = null; string orderBy = null; int maxRelativeLevel = -1; bool selectOnlyPublished = false; string columns = null; // Get the document TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, columns, tree); if (node != null) { WorkflowManager workflowmanager = new WorkflowManager(tree); // Make sure the document uses workflow WorkflowInfo workflow = workflowmanager.GetNodeWorkflow(node); if (workflow != null) { if (node.IsCheckedOut) { VersionManager versionmanager = new VersionManager(tree); // Undo the checkout versionmanager.UndoCheckOut(node); return true; } else { apiUndoCheckout.ErrorMessage = "The document hasn't been checked out."; } } else { apiUndoCheckout.ErrorMessage = "The document doesn't use workflow."; } } return false; }
/// <summary> /// Handles the UniGrid's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that throws event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void ugRecycleBin_OnAction(string actionName, object actionArgument) { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); VersionManager verMan = new VersionManager(tree); int versionHistoryId = ValidationHelper.GetInteger(actionArgument, 0); TreeNode doc = null; if (actionName == "restore") { try { if (IsAuthorizedPerDocument(versionHistoryId, "Create", currentUser, out doc, verMan)) { verMan.RestoreDocument(versionHistoryId, doc); lblInfo.Visible = true; lblInfo.Text = GetString("Recyclebin.RestorationOK"); } else { lblError.Visible = true; lblError.Text = String.Format(ResHelper.GetString("Recyclebin.RestorationFailedPermissions", currentCulture), doc.DocumentNamePath); } } catch (Exception ex) { lblError.Visible = true; lblError.Text = GetString("recyclebin.errorrestoringdocument") + " " + ex.Message; } } else if (actionName == "destroy") { if (IsAuthorizedPerDocument(versionHistoryId, "Destroy", currentUser, out doc, verMan)) { verMan.DestroyDocumentHistory(doc.DocumentID); lblInfo.Visible = true; lblInfo.Text = GetString("recyclebin.destroyok"); } else { lblError.Visible = true; lblError.Text = String.Format(ResHelper.GetString("recyclebin.destructionfailedpermissions", currentCulture), doc.DocumentNamePath); } } ugRecycleBin.ResetSelection(); }
/// <summary> /// Provides operations necessary to create and store new attachment. /// </summary> private void HandleAttachmentUpload(bool fieldAttachment) { // New attachment AttachmentInfo 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 document 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, true); } } // Handle field attachment if (fieldAttachment) { // Extension of CMS file before saving string oldExtension = node.DocumentType; newAttachment = DocumentHelper.AddAttachment(node, AttachmentGUIDColumnName, Guid.Empty, Guid.Empty, ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); // Update attachment field DocumentHelper.UpdateDocument(node, TreeProvider); // Different extension if ((oldExtension != null) && !oldExtension.EqualsCSafe(node.DocumentType, true)) { refreshTree = true; } } // Handle grouped and unsorted attachments else { // Grouped attachment if (AttachmentGroupGUID != Guid.Empty) { newAttachment = DocumentHelper.AddGroupedAttachment(node, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, TreeProvider, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize); } // Unsorted attachment else { newAttachment = DocumentHelper.AddUnsortedAttachment(node, AttachmentGUID, ucFileUpload.PostedFile, TreeProvider, 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 = AttachmentInfoProvider.AddTemporaryAttachment(FormGUID, AttachmentGUIDColumnName, AttachmentGUID, AttachmentGroupGUID, ucFileUpload.PostedFile, 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 EventLogProvider.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)) { string url = null; string saveName = URLHelper.GetSafeFileName(newAttachment.AttachmentName, SiteContext.CurrentSiteName); if (node != null) { SiteInfo si = SiteInfoProvider.GetSiteInfo(node.NodeSiteID); if (si != null) { bool usePermanent = SettingsKeyInfoProvider.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 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.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 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 = HTMLHelper.EnsureLineEnding(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); } }
// Load a saved game, does nothing if file does not exist public static void Load(int num = 0) { Game game = Game.Get(); try { if (File.Exists(SaveFile(num))) { if (!Directory.Exists(ContentData.TempValyriePath)) { Directory.CreateDirectory(ContentData.TempValyriePath); } string valkyrieLoadPath = Path.Combine(ContentData.TempValyriePath, "Load"); if (!Directory.Exists(valkyrieLoadPath)) { Directory.CreateDirectory(valkyrieLoadPath); } Directory.Delete(valkyrieLoadPath, true); ZipManager.Extract(valkyrieLoadPath, SaveFile(num), ZipManager.Extract_mode.ZIPMANAGER_EXTRACT_FULL); string savefile_content = File.ReadAllText(Path.Combine(valkyrieLoadPath, "save.ini")); IniData saveData = IniRead.ReadFromString(savefile_content); // when loading a quest, path should always be $TMP/load/quest/$subquest/quest.ini // Make sure it is when loading a quest saved for the first time, as in that case it is the original load path string questLoadPath = Path.GetDirectoryName(saveData.Get("Quest", "path")); string questOriginalPath = saveData.Get("Quest", "originalpath"); // loading a quest saved for the first time if (questLoadPath.Contains(questOriginalPath)) { questLoadPath = questLoadPath.Replace(questOriginalPath, ContentData.ValkyrieLoadQuestPath); } // Check that quest in save is valid QuestData.Quest q = new QuestData.Quest(questLoadPath); if (!q.valid) { ValkyrieDebug.Log("Error: save contains unsupported quest version." + System.Environment.NewLine); Destroyer.MainMenu(); return; } saveData.data["Quest"]["path"] = Path.Combine(questLoadPath, "quest.ini"); if (VersionManager.VersionNewer(game.version, saveData.Get("Quest", "valkyrie"))) { ValkyrieDebug.Log("Error: save is from a future version." + System.Environment.NewLine); Destroyer.MainMenu(); return; } if (!VersionManager.VersionNewerOrEqual(minValkyieVersion, saveData.Get("Quest", "valkyrie"))) { ValkyrieDebug.Log("Error: save is from an old unsupported version." + System.Environment.NewLine); Destroyer.MainMenu(); return; } Destroyer.Dialog(); // Restart contend data so we can select from save game.cd = new ContentData(game.gameType.DataDirectory()); // Check if we found anything if (game.cd.GetPacks().Count == 0) { ValkyrieDebug.Log("Error: Failed to find any content packs, please check that you have them present in: " + game.gameType.DataDirectory() + System.Environment.NewLine); Application.Quit(); } game.cd.LoadContentID(""); // Load the base content // Load content that the save game uses Dictionary <string, string> packs = saveData.Get("Packs"); foreach (KeyValuePair <string, string> kv in packs) { game.cd.LoadContentID(""); // Support for save games from 1.2 and older if (kv.Key.Equals("FA")) { game.cd.LoadContentID("FAI"); game.cd.LoadContentID("FAM"); game.cd.LoadContentID("FAT"); } if (kv.Key.Equals("CotW")) { game.cd.LoadContentID("CotWI"); game.cd.LoadContentID("CotWM"); game.cd.LoadContentID("CotWT"); } if (kv.Key.Equals("MoM1E")) { game.cd.LoadContentID("MoM1EI"); game.cd.LoadContentID("MoM1EM"); game.cd.LoadContentID("MoM1ET"); } else { game.cd.LoadContentID(kv.Key); } } // This loads the game new Quest(saveData); // Draw things on the screen game.heroCanvas.SetupUI(); game.heroCanvas.UpdateImages(); game.heroCanvas.UpdateStatus(); if (game.gameType.DisplayMorale()) { game.moraleDisplay = new MoraleDisplay(); } if (!game.gameType.DisplayHeroes()) { game.heroCanvas.Clean(); } // Create the menu button new MenuButton(); new LogButton(); new SkillButton(); new InventoryButton(); game.stageUI = new NextStageButton(); } } catch (IOException e) { ValkyrieDebug.Log("Error: Unable to open save file: " + SaveFile(num) + " " + e.Message); Application.Quit(); } }
static VersionManager() { Instance = new VersionManager(); }
/// <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 SaveData(int num = 0) { Game game = Game.Get(); if (!File.Exists(SaveFile(num))) { return; } try { if (!Directory.Exists(ContentData.TempValyriePath)) { Directory.CreateDirectory(ContentData.TempValyriePath); } string valkyrieLoadPath = Path.Combine(ContentData.TempValyriePath, "Preload"); if (!Directory.Exists(valkyrieLoadPath)) { Directory.CreateDirectory(valkyrieLoadPath); } ZipManager.Extract(valkyrieLoadPath, SaveFile(num), ZipManager.Extract_mode.ZIPMANAGER_EXTRACT_SAVE_INI_PIC); image = ContentData.FileToTexture(Path.Combine(valkyrieLoadPath, "image.png")); string data = File.ReadAllText(Path.Combine(valkyrieLoadPath, "save.ini")); IniData saveData = IniRead.ReadFromString(data); // when loading a quest, path should always be $TMP/load/quest/$subquest/quest.ini // Make sure it is when loading a quest saved for the first time, as in that case it is the original load path string questLoadPath = Path.GetDirectoryName(saveData.Get("Quest", "path")); string questOriginalPath = saveData.Get("Quest", "originalpath"); // loading a quest saved for the first time if (questLoadPath.Contains(questOriginalPath)) { questLoadPath = questLoadPath.Replace(questOriginalPath, ContentData.ValkyrieLoadQuestPath); } // use preload path rather than load questLoadPath = questLoadPath.Replace(ContentData.ValkyrieLoadPath, ContentData.ValkyriePreloadPath); QuestData.Quest q = new QuestData.Quest(questLoadPath); if (!q.valid) { ValkyrieDebug.Log("Warning: Save " + num + " contains unsupported quest version." + System.Environment.NewLine); return; } quest_name = saveData.Get("Quest", "questname"); if (VersionManager.VersionNewer(game.version, saveData.Get("Quest", "valkyrie"))) { ValkyrieDebug.Log("Warning: Save " + num + " is from a future version." + System.Environment.NewLine); return; } if (!VersionManager.VersionNewerOrEqual(minValkyieVersion, saveData.Get("Quest", "valkyrie"))) { ValkyrieDebug.Log("Warning: Save " + num + " is from an old unsupported version." + System.Environment.NewLine); return; } saveTime = System.DateTime.Parse(saveData.Get("Quest", "time")); valid = true; } catch (System.Exception e) { ValkyrieDebug.Log("Warning: Unable to open save file: " + SaveFile(num) + "\nException: " + e.ToString()); } }
/// <summary> /// Empties recycle bin. /// </summary> private void EmptyBin(object parameter) { // Begin log AddLog(ResHelper.GetString("Recyclebin.EmptyingBin", mCurrentCulture)); BinSettingsContainer settings = (BinSettingsContainer)parameter; CurrentUserInfo currentUserInfo = settings.User; string where = null; DateTime modifiedFrom = DateTimeHelper.ZERO_TIME; DateTime modifiedTo = DateTimeHelper.ZERO_TIME; switch (settings.CurrentWhat) { case What.AllDocuments: SetDocumentAge(ref modifiedFrom, ref modifiedTo); where = GetWhereCondition(filter.WhereCondition); break; case What.SelectedDocuments: // Restore selected documents var toRestore = settings.SelectedItems; if ((toRestore != null) && (toRestore.Count > 0)) { where = new WhereCondition().WhereIn("VersionHistoryID", toRestore).ToString(true); } break; } DataSet recycleBin = VersionHistoryInfoProvider.GetRecycleBin((mSelectedSite != null) ? mSelectedSite.SiteID : 0, 0, @where, "DocumentNamePath ASC", -1, null, modifiedFrom, modifiedTo); try { if (!DataHelper.DataSourceIsEmpty(recycleBin)) { TreeProvider tree = new TreeProvider(currentUserInfo); tree.AllowAsyncActions = false; VersionManager versionManager = VersionManager.GetInstance(tree); foreach (DataRow dr in recycleBin.Tables[0].Rows) { int versionHistoryId = Convert.ToInt32(dr["VersionHistoryID"]); var versionHistoryInfo = GetVersionHistoryInfo(versionHistoryId); string documentNamePath = ValidationHelper.GetString(dr["DocumentNamePath"], string.Empty); // Check permissions if (!IsAuthorizedPerDocument(versionHistoryInfo, "Destroy", mCurrentUser)) { CurrentError = String.Format(ResHelper.GetString("Recyclebin.DestructionFailedPermissions", mCurrentCulture), documentNamePath); AddLog(CurrentError); } else { AddLog(ResHelper.GetString("general.document", mCurrentCulture) + "'" + HTMLHelper.HTMLEncode(ValidationHelper.GetString(dr["DocumentNamePath"], string.Empty)) + "'"); // Destroy the version versionManager.DestroyDocumentHistory(ValidationHelper.GetInteger(dr["DocumentID"], 0)); LogContext.LogEventToCurrent(EventType.INFORMATION, "Content", "DESTROYDOC", string.Format(ResHelper.GetString("Recyclebin.documentdestroyed"), documentNamePath), RequestContext.RawURL, mCurrentUser.UserID, mCurrentUser.UserName, 0, null, RequestContext.UserHostAddress, SiteContext.CurrentSiteID, SystemContext.MachineName, RequestContext.URLReferrer, RequestContext.UserAgent, DateTime.Now); } } if (!String.IsNullOrEmpty(CurrentError)) { CurrentError = ResHelper.GetString("recyclebin.errorsomenotdestroyed", mCurrentCulture); AddLog(CurrentError); } else { CurrentInfo = ResHelper.GetString("recyclebin.destroyok", mCurrentCulture); AddLog(CurrentInfo); } } } catch (ThreadAbortException ex) { if (!CMSThread.Stopped(ex)) { // Log error LogException("DESTROYDOC", ex); } } catch (Exception ex) { // Log error LogException("DESTROYDOC", ex); } }
/// <summary> /// OnInitializedAsync 方法 /// </summary> /// <returns></returns> protected override async Task OnInitializedAsync() { Version = await VersionManager.GetVersionAsync("Bootstrap.Blazor.Templates"); }
/// <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)); } } }
public override void Init() { base.Init(); Instance = this; }
/// <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) { // Get current step info WorkflowStepInfo si = WorkflowManager.GetStepInfo(node); if (si != null) { // Decide if full refresh is needed string stepName = si.StepName.ToLower(); args.FullRefresh = (stepName == "published") || (stepName == "archived"); } 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.Equals(node.DocumentType, StringComparison.InvariantCultureIgnoreCase)) { 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 = AttachmentManager.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 aftersave 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(AttachmentManager.GetAttachmentUrl(newAttachment.AttachmentGUID, saveName)) : URLHelper.ResolveUrl(AttachmentManager.GetAttachmentUrl(saveName, node.NodeAliasPath)); } } else { url = URLHelper.ResolveUrl(AttachmentManager.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().ToLower(), refreshTree.ToString().ToLower(), attachmentInfo + (args.IsInsertMode ? "'insert'" : "'update'")); args.AddEventTargetPostbackReference(); context.Response.Write(args.AfterScript); context.Response.Flush(); } }
/// <summary> /// Method to get an <see cref="ObservableCollection{T}"/> of <see cref="VersionEntity"/>. /// </summary> /// <param name="op">Version list options to perform query.</param> /// <returns>An <see cref="ObservableCollection{T}"/> of <see cref="VersionEntity"/>.</returns> public ObservableCollection <VersionEntity> List(VersionOptionsList op = null) { using (Db.Context) { return(new ObservableCollection <VersionEntity>(VersionManager.List(op))); } }
public ActionResult GetChangelog(int versionId, int projectId) { UserContext.Project = ProjectManager.Get(projectId); IssuesFilter filter = null; if (Request.Form.Keys.Count > 0) { filter = new IssuesFilter(); string[] sort = Request.Form[0].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); StringBuilder sortField = new StringBuilder(); StringBuilder sortDirection = new StringBuilder(); for (int i = 0; i < sort.Length; i += 2) { sortField.Append(sort[i]); sortField.Append('|'); sortDirection.Append(sort[i + 1] == "0" ? (int)SortDirection.Ascending : (int)SortDirection.Descending); sortDirection.Append('|'); } filter.SortField = sortField.ToString(); filter.SortOrder = sortDirection.ToString(); filter.ShowSequenced = false; } if (filter == null) { filter = HttpSessionManager.GetFilter(CurrentCard.Id, new IssuesFilter()); filter.ShowSequenced = false; } IEnumerable <Countersoft.Gemini.Commons.Entity.Version> versions = Cache.Versions.GetAll().Where(v => v.ProjectId == projectId && v.Released == true && v.Archived == false).OrderBy(o => o.Sequence); // get all versions that are released or not according to settings passed (BUT - NEVER show archived projects) if (!versions.Any(s => s.Id == versionId)) { VersionDto newVersion = VersionManager.GetFirstChangeLogVersion(UserContext.Project.Entity.Id); if (newVersion != null) { versionId = newVersion.Entity.Id; } else { versionId = versions.Count() > 0 ? versions.First().Id : 0; } } var version = VersionManager.Get(versionId); List <IssueDto> issues = new List <IssueDto>(); if (version != null && version.Entity.Released) { issues = IssueManager.GetRoadmap(UserContext.Project.Entity.Id, filter, versionId); } Changelog.Models.ChangelogpAppModel model = BuildModelData(versionId, versions, filter); model.Issues = issues; return(JsonSuccess(new { success = true, grid = RenderPartialViewToString(this, "~/Views/Shared/DisplayTemplates/IssueDto.cshtml", model), statusBar = RenderPartialViewToString(this, AppManager.Instance.GetAppUrl("20A79C86-9FB4-4160-A4FD-29E37E185673", "views/StatusBar.cshtml"), model), versions = RenderPartialViewToString(this, AppManager.Instance.GetAppUrl("20A79C86-9FB4-4160-A4FD-29E37E185673", "views/VersionProgress.cshtml"), model) })); }
/// <summary> /// OnInitializedAsync 方法 /// </summary> /// <returns></returns> protected override async Task OnInitializedAsync() { Version = await VersionManager.GetVersionAsync("bootstrapblazor.summernote"); }
protected void btnCheckIn_Click(object sender, EventArgs e) { try { // Check in the document if (node != null) { // Check modify permissions if (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { formElem.Enabled = false; lblWorkflowInfo.Text = String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), node.NodeAliasPath); return; } // Validate the form first if (formElem.BasicForm.ValidateData()) { // Save the document first if (SaveChanges) { SaveDocument(true); } else { formElem.BasicForm.LoadControlValues(); PassiveRefresh(nodeId, node.NodeParentID, node.DocumentName); } VersionManager verMan = new VersionManager(TreeProvider); // Check in the document verMan.CheckIn(node, null, null); formElem.lblInfo.Text += " " + GetString("ContentEdit.WasCheckedIn"); } } } catch (WorkflowException) { formElem.lblError.Text += GetString("EditContent.DocumentCannotCheckIn"); } catch (Exception ex) { formElem.lblError.Text += ex.Message; } ReloadForm(); }
Widget _buildContent() { return(new Flexible( child: new Container( color: CColors.Background, child: new ListView( physics: new AlwaysScrollableScrollPhysics(), children: new List <Widget> { this.widget.viewModel.hasReviewUrl || this.widget.viewModel.anonymous ? _buildGapView() : new Container(), this.widget.viewModel.hasReviewUrl ? _buildCellView("评分", () => { AnalyticsManager.ClickSetGrade(); this.widget.actionModel.openUrl(obj: this.widget.viewModel.reviewUrl); }) : new Container(), this.widget.viewModel.anonymous ? _buildCellView("绑定 Unity ID", () => this.widget.actionModel.mainRouterPushTo(MainNavigatorRoutes.BindUnity)) : new Container(), _buildGapView(), _buildCellView("检查更新", () => { AnalyticsManager.ClickCheckUpdate(); VersionManager.checkForUpdates(CheckVersionType.setting); }), _buildGapView(), _buildCellView("清理缓存", () => { AnalyticsManager.ClickClearCache(); CustomDialogUtils.showCustomDialog( child: new CustomLoadingDialog( message: "正在清理缓存" ) ); this.widget.actionModel.clearCache(); Window.instance.run(TimeSpan.FromSeconds(1), () => { CustomDialogUtils.hiddenCustomDialog(); CustomDialogUtils.showToast("缓存已清除", Icons.check_circle_outline); } ); }), CCommonUtils.isIPhone ? _buildGapView() : new Container(), CCommonUtils.isIPhone ? _switchRow( "帧率监测", value: this.fpsLabelIsOpen, value => { LocalDataManager.setFPSLabelStatus(isOpen: value); this.fpsLabelIsOpen = value; this.setState(() => {}); FPSLabelPlugin.SwitchFPSLabelShowStatus(isOpen: value); } ) : new Container(), this.widget.viewModel.isLoggedIn ? _buildGapView() : new Container(), this.widget.viewModel.isLoggedIn ? this._buildLogoutBtn() : new Container() } ) ) )); }
public void DraftsCanBeFound_ForSingleItem() { var master = CreateOneItem<Items.NormalPage>(0, "pageX", null); persister.Save(master); var manager = new VersionManager(repository, persister.Repository, new StateChanger(), new N2.Configuration.EditSection()); manager.AddVersion(master, asPreviousVersion: false); drafts.FindDrafts().Single().Master.ID.ShouldBe(master.ID); }
public override void Add(Site site, Layout o) { base.Add(site, o); VersionManager.LogVersion(o); }
public void AutoImplementedProperties_AreMaintained_OnPeristedParts() { var master = CreateOneItem<Items.NormalPage>(0, "master", null); persister.Save(master); var part = CreateOneItem<Items.NormalItem>(0, "part", master); part.WidthType = Items.WidthType.Pixels; part.Width = 123; part.ZoneName = "TheZone"; persister.Save(part); persister.Dispose(); master = (Items.NormalPage)persister.Get(master.ID); var manager = new VersionManager(repository, persister.Repository, new StateChanger(), new N2.Configuration.EditSection()); var version = (Items.NormalPage)manager.AddVersion(master, asPreviousVersion: false); persister.Dispose(); master = (Items.NormalPage)persister.Get(master.ID); version = (Items.NormalPage)manager.GetVersion(master, version.VersionIndex); version.Children.OfType<Items.NormalItem>().Single().WidthType.ShouldBe(Items.WidthType.Pixels); version.Children.OfType<Items.NormalItem>().Single().Width.ShouldBe(123); }
public override void Update(Site site, Layout @new, Layout old) { base.Update(site, @new, old); VersionManager.LogVersion(@new); }
public void Version_GetsParent_FromMasterVersion() { var parent = CreateOneItem<Items.NormalPage>(0, "parent", null); persister.Save(parent); var master = CreateOneItem<Items.NormalPage>(0, "master", parent); persister.Save(master); var manager = new VersionManager(repository, persister.Repository, new StateChanger(), new N2.Configuration.EditSection()); var versionIndex = manager.AddVersion(master, asPreviousVersion: false).VersionIndex; persister.Dispose(); var version = repository.DeserializeVersion(repository.GetVersion(master, versionIndex)); version.Parent.ShouldBe(parent); }
/// <summary> /// OnInitializedAsync 方法 /// </summary> /// <returns></returns> protected override async Task OnInitializedAsync() { Version = await VersionManager.GetVersionAsync(); }
public HelloSynMessageHandler(PeerList peerList, MessageManager messageManager, VersionManager _versionManager) { _peerList = peerList; _messageManager = messageManager; this._versionManager = _versionManager; }
void Awake() { mInst = this; }
/// <summary> /// Check user permissions for document version. /// </summary> /// <param name="versionId">Document version</param> /// <param name="permission">Permission</param> /// <param name="user">User</param> /// <param name="checkedNode">Checked node</param> /// <param name="versionManager">Version manager</param> /// <returns>True if authorized, false otherwise</returns> public bool IsAuthorizedPerDocument(int versionId, string permission, CurrentUserInfo user, out TreeNode checkedNode, VersionManager versionManager) { if (versionManager == null) { TreeProvider tree = new TreeProvider(user); tree.AllowAsyncActions = false; versionManager = new VersionManager(tree); } // Get the values form deleted node checkedNode = versionManager.GetVersion(versionId); return IsAuthorizedPerDocument(checkedNode, permission, user); }
private void DeleteAttachmentAction(Guid attGuid) { if (!createTempAttachment) { if (attGuid != Guid.Empty) { // Delete attachment if (FormGUID == Guid.Empty) { // Ensure automatic check-in/ check-out VersionManager vm = null; // Check out the document if (AutoCheck) { vm = VersionManager.GetInstance(TreeProvider); vm.CheckOut(Node, Node.IsPublished, true); } // If the GUID column is set, use it to process additional actions for field attachments if (!String.IsNullOrEmpty(GUIDColumnName)) { DocumentHelper.DeleteAttachment(Node, GUIDColumnName); } else { DocumentHelper.DeleteAttachment(Node, attGuid); } DocumentHelper.UpdateDocument(Node, TreeProvider); // Ensure full page refresh if (AutoCheck) { ScriptHelper.RegisterStartupScript(Page, typeof(Page), "deleteRefresh", ScriptHelper.GetScript("InitRefresh_" + ClientID + "('', true, true, '" + attGuid + "', 'delete');")); } else { string script = "if (window.RefreshTree) { RefreshTree(" + Node.NodeParentID + ", " + Node.NodeID + "); }"; ScriptHelper.RegisterStartupScript(Page, typeof(Page), "refreshTree", ScriptHelper.GetScript(script)); } // Check in the document if (AutoCheck) { if (vm != null) { vm.CheckIn(Node, null); } } // Log synchronization task if not under workflow if (!UsesWorkflow) { DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider); } } else { AttachmentInfoProvider.DeleteTemporaryAttachment(attGuid, SiteContext.CurrentSiteName); } } } LastAction = "delete"; Value = null; }
/// <summary> /// Empties recycle bin. /// </summary> private void EmptyBin(object parameter) { // Begin log AddLog(ResHelper.GetString("Recyclebin.EmptyingBin", currentCulture)); BinSettingsContainer settings = (BinSettingsContainer)parameter; CurrentUserInfo currentUserInfo = settings.User; DataSet recycleBin = null; string where = null; DateTime modifiedFrom = DateTimeHelper.ZERO_TIME; DateTime modifiedTo = DateTimeHelper.ZERO_TIME; switch (settings.CurrentWhat) { case What.AllDocuments: SetDocumentAge(ref modifiedFrom, ref modifiedTo); where = GetWhereCondition(string.Empty); break; case What.SelectedDocuments: ArrayList toRestore = ugRecycleBin.SelectedItems; // Restore selected documents if (toRestore.Count > 0) { where = SqlHelperClass.GetWhereCondition("VersionHistoryID", (string[])toRestore.ToArray(typeof(string))); } break; } recycleBin = VersionHistoryInfoProvider.GetRecycleBin((mSelectedSite != null) ? mSelectedSite.SiteID : 0, 0, where, "DocumentNamePath ASC", -1, null, modifiedFrom, modifiedTo); try { if (!DataHelper.DataSourceIsEmpty(recycleBin)) { TreeProvider tree = new TreeProvider(currentUserInfo); tree.AllowAsyncActions = false; VersionManager verMan = new VersionManager(tree); foreach (DataRow dr in recycleBin.Tables[0].Rows) { int versionHistoryId = Convert.ToInt32(dr["VersionHistoryID"]); string documentNamePath = ValidationHelper.GetString(dr["DocumentNamePath"], string.Empty); // Check permissions TreeNode tn = null; if (!IsAuthorizedPerDocument(versionHistoryId, "Destroy", currentUser, out tn, verMan)) { CurrentError = String.Format(ResHelper.GetString("Recyclebin.DestructionFailedPermissions", currentCulture), documentNamePath); AddLog(CurrentError); } else { AddLog(ResHelper.GetString("general.document", currentCulture) + "'" + HTMLHelper.HTMLEncode(ValidationHelper.GetString(dr["DocumentNamePath"], string.Empty)) + "'"); // Destroy the version verMan.DestroyDocumentHistory(ValidationHelper.GetInteger(dr["DocumentID"], 0)); LogContext.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "Content", "DESTROYDOC", currentUser.UserID, currentUser.UserName, 0, null, HTTPHelper.UserHostAddress, string.Format(ResHelper.GetString("Recyclebin.documentdestroyed"), documentNamePath), currentSite.SiteID, HTTPHelper.GetAbsoluteUri(), HTTPHelper.MachineName, HTTPHelper.GetUrlReferrer(), HTTPHelper.GetUserAgent()); } } if (!String.IsNullOrEmpty(CurrentError)) { CurrentError = ResHelper.GetString("recyclebin.errorsomenotdestroyed", currentCulture); AddLog(CurrentError); } else { CurrentInfo = ResHelper.GetString("recyclebin.destroyok", currentCulture); AddLog(CurrentInfo); } } } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state != CMSThread.ABORT_REASON_STOP) { // Log error CurrentError = "Error occurred: " + ex.Message; AddLog(CurrentError); } } catch (Exception ex) { // Log error CurrentError = "Error occurred: " + ex.Message; AddLog(CurrentError); } }
/// <summary> /// Initializes common properties used for processing image. /// </summary> private void baseImageEditor_InitializeProperties() { CurrentUserInfo currentUser = CMSContext.CurrentUser; // Process attachment switch (baseImageEditor.ImageType) { default: case ImageHelper.ImageTypeEnum.Attachment: { baseImageEditor.Tree = new TreeProvider(currentUser); // If using workflow then get versioned attachment if (VersionHistoryID != 0) { // Get the versioned attachment AttachmentHistoryInfo attachmentVersion = VersionManager.GetAttachmentVersion(VersionHistoryID, attachmentGuid); if (attachmentVersion == null) { ai = null; } else { // Create new attachment object ai = new AttachmentInfo(attachmentVersion.Generalized.DataClass); ai.AttachmentID = attachmentVersion.AttachmentHistoryID; } } // else get file without binary data else { ai = AttachmentInfoProvider.GetAttachmentInfoWithoutBinary(attachmentGuid, CurrentSiteName); } // If file is not null and current user is set if (ai != null) { TreeNode node = null; if (ai.AttachmentDocumentID > 0) { node = baseImageEditor.Tree.SelectSingleDocument(ai.AttachmentDocumentID); } else { // Get parent node ID in case attachment is edited for document not created yet int parentNodeId = QueryHelper.GetInteger("parentId", 0); node = baseImageEditor.Tree.SelectSingleNode(parentNodeId); } // If current user has appropriate permissions then set image - check hash fro live site otherwise check node permissions if ((currentUser != null) && (node != null) && ((IsLiveSite && QueryHelper.ValidateHash("hash")) || (!IsLiveSite && (currentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed)))) { // Ensure attachment binary data if (VersionHistoryID == 0) { ai.AttachmentBinary = AttachmentInfoProvider.GetFile(ai, CurrentSiteName); } if (ai.AttachmentBinary != null) { baseImageEditor.ImgHelper = new ImageHelper(ai.AttachmentBinary); } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading"; } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.filemodify"; } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading"; } } break; // Process physical file case ImageHelper.ImageTypeEnum.PhysicalFile: { if (!String.IsNullOrEmpty(filePath)) { if ((currentUser != null) && currentUser.IsGlobalAdministrator) { try { // Load the file from disk string physicalPath = Server.MapPath(filePath); byte[] data = File.ReadAllBytes(physicalPath); baseImageEditor.ImgHelper = new ImageHelper(data); } catch { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading"; } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.rights"; } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading"; } } break; // Process metafile case ImageHelper.ImageTypeEnum.Metafile: { // Get metafile mf = MetaFileInfoProvider.GetMetaFileInfoWithoutBinary(metafileGuid, CurrentSiteName, true); // If file is not null and current user is global administrator then set image if (mf != null) { if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, CurrentSiteName, CMSContext.CurrentUser)) { // Ensure metafile binary data mf.MetaFileBinary = MetaFileInfoProvider.GetFile(mf, CurrentSiteName); if (mf.MetaFileBinary != null) { baseImageEditor.ImgHelper = new ImageHelper(mf.MetaFileBinary); } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading"; } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.rights"; } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.loading"; } } break; } // Check that image is in supported formats if ((!baseImageEditor.LoadingFailed) && (baseImageEditor.ImgHelper.ImageFormatToString() == null)) { baseImageEditor.LoadingFailed = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.format"; } }
/// <summary> /// Gets the file from version history. /// </summary> /// <param name="attachmentGuid">Atachment GUID</param> /// <param name="versionHistoryId">Version history ID</param> protected AttachmentInfo GetFile(Guid attachmentGuid, int versionHistoryId) { VersionManager vm = new VersionManager(TreeProvider); // Get the attachment version AttachmentHistoryInfo attachmentVersion = vm.GetAttachmentVersion(versionHistoryId, attachmentGuid); if (attachmentVersion == null) { return null; } else { // Create the attachment object from the version AttachmentInfo ai = new AttachmentInfo(attachmentVersion.Generalized.DataClass); ai.AttachmentVersionHistoryID = versionHistoryId; return ai; } }
/// <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) { // 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"; SavingFailed = true; return; } if (!IsNameUnique(name, extension)) { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.namenotunique"; SavingFailed = true; return; } // Ensure automatic check-in/ check-out bool useWorkflow = false; bool autoCheck = false; WorkflowManager workflowMan = WorkflowManager.GetInstance(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 = AttachmentInfoProvider.GetAttachmentInfo(ai.AttachmentGUID, CurrentSiteName); } // If extension changed update CMS.File extension if ((node.NodeClassName.ToLowerCSafe() == "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.EndsWithCSafe(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 { AttachmentInfoProvider.SetAttachmentInfo(ai); // Log the synchronization 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); 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); SavingFailed = true; } } else { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.rights"; SavingFailed = true; } } break; // Process metafile case ImageHelper.ImageTypeEnum.Metafile: if (mf != null) { if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, CurrentSiteName, CMSContext.CurrentUser)) { try { // Test all parameters to empty values and update new value if available if (name.CompareToCSafe("") != 0) { if (!name.EndsWithCSafe(extension)) { mf.MetaFileName = name + extension; } else { mf.MetaFileName = name; } } if (extension.CompareToCSafe("") != 0) { mf.MetaFileExtension = extension; } if (mimetype.CompareToCSafe("") != 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); SavingFailed = true; } } else { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.rights"; SavingFailed = true; } } break; } }
/// <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(); }
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> /// UniGrid action buttons event handler. /// </summary> protected void gridAttachments_OnAction(string actionName, object actionArgument) { if (Enabled && !HideActions) { // Check the permissions #region "Check permissions" if (CheckPermissions) { if (FormGUID != Guid.Empty) { if (!RaiseOnCheckPermissions("Create", this)) { if (!CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(NodeParentNodeID, NodeClassName)) { lblError.Text = GetString("attach.actiondenied"); return; } } } else { if (!RaiseOnCheckPermissions("Modify", this)) { if (CMSContext.CurrentUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { lblError.Text = GetString("attach.actiondenied"); return; } } } } #endregion Guid attachmentGuid = Guid.Empty; // Get action argument (Guid or int) if (ValidationHelper.IsGuid(actionArgument)) { attachmentGuid = ValidationHelper.GetGuid(actionArgument, Guid.Empty); } // Process proper action switch (actionName.ToLower()) { case "moveup": if (attachmentGuid != Guid.Empty) { // Move attachment up if (FormGUID == Guid.Empty) { // Ensure automatic check-in/ check-out VersionManager vm = null; // Check out the document if (AutoCheck) { vm = new VersionManager(TreeProvider); vm.CheckOut(Node, Node.IsPublished, true); } DocumentHelper.MoveAttachmentUp(attachmentGuid, Node); // Check in the document if (AutoCheck) { if (vm != null) { vm.CheckIn(Node, null, null); VersionHistoryID = Node.DocumentCheckedOutVersionHistoryID; } // Ensure full page refresh ScriptHelper.RegisterStartupScript(Page, typeof(Page), "moveUpRefresh", ScriptHelper.GetScript(String.Format("InitRefresh_{0}('', true, false, 'moveup');", ClientID))); } // Log synchronization task if not under workflow if (!UsesWorkflow) { DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider); } } else { AttachmentManager.MoveAttachmentUp(attachmentGuid, 0); } } break; case "movedown": if (attachmentGuid != Guid.Empty) { // Move attachment down if (FormGUID == Guid.Empty) { // Ensure automatic check-in/ check-out VersionManager vm = null; // Check out the document if (AutoCheck) { vm = new VersionManager(TreeProvider); vm.CheckOut(Node, Node.IsPublished, true); } DocumentHelper.MoveAttachmentDown(attachmentGuid, Node); // Check in the document if (AutoCheck) { if (vm != null) { vm.CheckIn(Node, null, null); VersionHistoryID = Node.DocumentCheckedOutVersionHistoryID; } // Ensure full page refresh ScriptHelper.RegisterStartupScript(Page, typeof(Page), "moveDownRefresh", ScriptHelper.GetScript(String.Format("InitRefresh_{0}('', true, false, 'movedown');", ClientID))); } // Log synchronization task if not under workflow if (!UsesWorkflow) { DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider); } } else { AttachmentManager.MoveAttachmentDown(attachmentGuid, 0); } } break; case "delete": if (attachmentGuid != Guid.Empty) { // Delete attachment if (FormGUID == Guid.Empty) { // Ensure automatic check-in/ check-out VersionManager vm = null; // Check out the document if (AutoCheck) { vm = new VersionManager(TreeProvider); vm.CheckOut(Node, Node.IsPublished, true); } DocumentHelper.DeleteAttachment(Node, attachmentGuid, TreeProvider); // Check in the document if (AutoCheck) { if (vm != null) { vm.CheckIn(Node, null, null); VersionHistoryID = Node.DocumentCheckedOutVersionHistoryID; } // Ensure full page refresh ScriptHelper.RegisterStartupScript(Page, typeof(Page), "deleteRefresh", ScriptHelper.GetScript(String.Format("InitRefresh_{0}('', true, false, 'delete');", ClientID))); } // Log synchronization task if not under workflow if (!UsesWorkflow) { DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, TreeProvider); } } else { AttachmentManager.DeleteTemporaryAttachment(attachmentGuid, CMSContext.CurrentSiteName); } lblInfo.Text = GetString("attach.deleted"); } break; } } }
/// <summary> /// Restores set of given version histories. /// </summary> /// <param name="currentUserInfo">Current user info</param> /// <param name="recycleBin">DataSet with nodes to restore</param> private void RestoreDataSet(CurrentUserInfo currentUserInfo, DataSet recycleBin) { // Result flags bool resultOK = true; bool permissionsOK = true; if (!DataHelper.DataSourceIsEmpty(recycleBin)) { TreeProvider tree = new TreeProvider(currentUserInfo); tree.AllowAsyncActions = false; VersionManager versionManager = VersionManager.GetInstance(tree); // Restore all documents foreach (DataRow dataRow in recycleBin.Tables[0].Rows) { // Log actual event string taskTitle = HTMLHelper.HTMLEncode(ValidationHelper.GetString(dataRow["DocumentNamePath"], string.Empty)); // Restore document int versionHistoryId = ValidationHelper.GetInteger(dataRow["VersionHistoryID"], 0); if (versionHistoryId > 0) { var versionHistoryInfo = GetVersionHistoryInfo(versionHistoryId); // Check permissions if (!IsAuthorizedPerDocument(versionHistoryInfo, "Create", mCurrentUser)) { CurrentError = String.Format(ResHelper.GetString("Recyclebin.RestorationFailedPermissions", mCurrentCulture), taskTitle); AddLog(CurrentError); permissionsOK = false; } else { var treeNode = versionManager.RestoreDocument(versionHistoryId); if (treeNode != null) { AddLog(ResHelper.GetString("general.document", mCurrentCulture) + "'" + taskTitle + "'"); } else { // Set result flag if (resultOK) { resultOK = false; } } } } } } if (resultOK && permissionsOK) { CurrentInfo = ResHelper.GetString("Recyclebin.RestorationOK", mCurrentCulture); AddLog(CurrentInfo); } else { CurrentError = ResHelper.GetString("Recyclebin.RestorationFailed", mCurrentCulture); if (!permissionsOK) { CurrentError += "<br />" + ResHelper.GetString("recyclebin.errorsomenotrestored", mCurrentCulture); } AddLog(CurrentError); } }
private void RemoveWorkflow(object parameter) { VersionManager verMan = new VersionManager(Tree); TreeNode node = null; // Custom logging Tree.LogEvents = false; Tree.AllowAsyncActions = false; CanceledString = ResHelper.GetString("workflowdocuments.removingcanceled", currentCulture); try { // Begin log AddLog(ResHelper.GetString("content.preparingdocuments", currentCulture)); // Get the documents DataSet documents = GetDocumentsToProcess(); if (!DataHelper.DataSourceIsEmpty(documents)) { // Begin log AddLog(ResHelper.GetString("workflowdocuments.removingwf", 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); // Get published version node = Tree.SelectSingleNode(siteName, aliasPath, docCulture, false, className, false); string encodedAliasPath = HTMLHelper.HTMLEncode(ValidationHelper.GetString(aliasPath, string.Empty) + " (" + node.GetValue("DocumentCulture") + ")"); // Destroy document history verMan.DestroyDocumentHistory(node.DocumentID); // Clear workflow DocumentHelper.ClearWorkflowInformation(node); node.Update(); // Add log record AddLog(encodedAliasPath); // Add record to eventlog LogContext.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "Content", "REMOVEDOCWORKFLOW", currentUser.UserID, currentUser.UserName, node.NodeID, node.DocumentName, HTTPHelper.GetUserHostAddress(), string.Format(GetString("workflowdocuments.removeworkflowsuccess"), encodedAliasPath), node.NodeSiteID, HTTPHelper.GetAbsoluteUri(), HTTPHelper.MachineName, HTTPHelper.GetUrlReferrer(), HTTPHelper.GetUserAgent()); } } CurrentInfo = GetString("workflowdocuments.removecomplete"); } else { AddError(ResHelper.GetString("workflowdocuments.nodocumentstoclear", 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("REMOVEDOCWORKFLOW", "workflowdocuments.removefailed", ex, siteId); } } catch (Exception ex) { int siteId = (node != null) ? node.NodeSiteID : CMSContext.CurrentSiteID; // Log error LogExceptionToEventLog("REMOVEDOCWORKFLOW", "workflowdocuments.removefailed", ex, siteId); } }
/// <summary> /// Rolls the document back to a specified document version. Called when the "Rollback version" button is pressed. /// Expects the "CreateExampleObjects" and at least the "EditDocument" method to be run first. /// </summary> private bool RollbackVersion() { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Prepare parameters string siteName = CMSContext.CurrentSiteName; string aliasPath = "/API-Example"; string culture = "en-us"; bool combineWithDefaultCulture = false; string classNames = TreeProvider.ALL_CLASSNAMES; string where = null; string orderBy = null; int maxRelativeLevel = -1; bool selectOnlyPublished = false; string columns = null; // Get the document TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, culture, combineWithDefaultCulture, classNames, where, orderBy, maxRelativeLevel, selectOnlyPublished, columns, tree); if (node != null) { // Prepare the WHERE condition for the oldest document version where = "DocumentID = " + node.DocumentID; orderBy = "ModifiedWhen ASC"; int topN = 1; // Get the version ID DataSet versionHistory = VersionHistoryInfoProvider.GetVersionHistories(where, orderBy, topN, columns); if (!DataHelper.DataSourceIsEmpty(versionHistory)) { // Create the Version history info object VersionHistoryInfo version = new VersionHistoryInfo(versionHistory.Tables[0].Rows[0]); VersionManager versionManager = new VersionManager(tree); // Roll back version versionManager.RollbackVersion(version.VersionHistoryID); return true; } else { apiRollbackVersion.ErrorMessage = "The document's version history is empty."; } } return false; }