コード例 #1
0
        public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
        {
            UrlActionToken urlActionToken = (UrlActionToken)actionToken;

            string currentConsoleId = flowControllerServicesContainer.GetService <IManagementConsoleMessageService>().CurrentConsoleId;

            string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken);

            string url = string.Format("{0}?EntityToken={1}", urlActionToken.Url, HttpUtility.UrlEncode(serializedEntityToken));

            ConsoleMessageQueueFacade.Enqueue(new OpenViewMessageQueueItem {
                Url = url, ViewId = Guid.NewGuid().ToString(), ViewType = ViewType.Main, Label = urlActionToken.Label
            }, currentConsoleId);

            return(null);
        }
コード例 #2
0
        /// <exclude />
        public static List <ClientLabeledProperty> GetLabeledProperties(string providerName, string serializedEntityToken, string piggybag)
        {
            var elementEntityToken = EntityTokenSerializer.Deserialize(serializedEntityToken);
            var elementHandle      = new ElementHandle(providerName, elementEntityToken, piggybag);

            bool showForeign = UserSettings.ForeignLocaleCultureInfo != null &&
                               UserSettings.ForeignLocaleCultureInfo.Equals(UserSettings.ActiveLocaleCultureInfo);

            var labeledProperties = showForeign
                ? ElementFacade.GetForeignLabeledProperties(elementHandle)
                : ElementFacade.GetLabeledProperties(elementHandle);

            return
                ((from property in labeledProperties
                  select new ClientLabeledProperty(property)).ToList());
        }
コード例 #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string pageIdString = this.Request.QueryString["pageId"];

            if (pageIdString == null)
            {
                throw new InvalidOperationException();
            }

            Guid pageId = new Guid(pageIdString);

            //var editWorkflowAttribute = teaser.DataSourceId.InterfaceType.GetCustomAttributes(true).OfType<EditWorkflowAttribute>().FirstOrDefault();
            //if (editWorkflowAttribute == null)
            //{
            //    editLink.Link = string.Empty;
            //    return editLink;
            //}


            var pagex        = PageManager.GetPageById(pageId);
            var _entityToken = new PageDataEntityToken(pagex);

            var serializedEntityToken = EntityTokenSerializer.Serialize(_entityToken, true);

            var editActionToken = new WorkflowActionToken(typeof(EditDataWorkflow));

            var token = new WorkflowActionToken(WorkflowFacade.GetWorkflowType(typeof(EditPageWorkflow).FullName));


            var serializedActionToken = ActionTokenSerializer.Serialize(token, true);

            //var m = ActionTokenSerializer.Deserialize(k);
            var x = ActionTokenSerializer.Deserialize(serializedActionToken);

            providerName = pagex.DataSourceId.ProviderName;
            entityToken  = serializedEntityToken;
            actionToken  = serializedActionToken;
            piggybag     = string.Empty;
            piggybagHash = HashSigner.GetSignedHash(string.Empty).Serialize();

            using (new DataScope(DataScopeIdentifier.Administrated, UserSettings.ActiveLocaleCultureInfo))
            {
                IPage page = PageManager.GetPageById(pageId);

                this.MyPlaceHolder.Controls.Add(new LiteralControl("Title: " + page.Title + "<br />"));
            }
        }
コード例 #4
0
        private static XElement BuildReportXmlRec(Measurement measurement, /* int level,*/ long totalTime, long parentTime, bool parallel, string id)
        {
            long persentTotal = (measurement.TotalTime * 100) / totalTime;

            long ownTime = measurement.TotalTime - measurement.Nodes.Select(childNode => childNode.TotalTime).Sum();

            var entityToken = measurement.EntityTokenFactory != null?measurement.EntityTokenFactory() : null;

            string serializedEntityToken = entityToken != null
                ? EntityTokenSerializer.Serialize(entityToken, true)
                : null;

            var result = new XElement("Measurement",
                                      new XAttribute("_id", id),
                                      new XAttribute("title", measurement.Name),
                                      new XAttribute("totalTime", measurement.TotalTime),
                                      new XAttribute("ownTime", ownTime),
                                      new XAttribute("persentFromTotal", persentTotal),
                                      new XAttribute("parallel", parallel.ToString().ToLowerInvariant()));

            if (serializedEntityToken != null)
            {
                result.Add(new XAttribute("entityToken", serializedEntityToken));
            }

            if (measurement.MemoryUsage != 0)
            {
                result.Add(new XAttribute("memoryUsageKb", measurement.MemoryUsage / 1024));
            }

            int index = 0;

            foreach (var childNode in measurement.Nodes)  // .OrderByDescending(c => c.TotalTime)
            {
                result.Add(BuildReportXmlRec(childNode, totalTime, measurement.TotalTime, false, (id + "|" + index)));
                index++;
            }

            foreach (var childNode in measurement.ParallelNodes) // .OrderByDescending(c => c.TotalTime)
            {
                result.Add(BuildReportXmlRec(childNode, totalTime, measurement.TotalTime, true, (id + "|" + index)));
                index++;
            }

            return(result);
        }
コード例 #5
0
        /// <exclude />
        public static List <ClientElement> GetChildren(string providerName, string serializedEntityToken, string piggybag, string serializedSearchToken)
        {
            //LoggingService.LogVerbose("RGB(255, 0, 255)TreeServiceFacade", "----- Start -----------------------------------------------");

            int t1 = Environment.TickCount;

            EntityToken   entityToken   = EntityTokenSerializer.Deserialize(serializedEntityToken);
            ElementHandle elementHandle = new ElementHandle(providerName, entityToken, piggybag);

            //int t2 = Environment.TickCount;

            SearchToken searchToken = null;

            if (!string.IsNullOrEmpty(serializedSearchToken))
            {
                searchToken = SearchToken.Deserialize(serializedSearchToken);
            }

            List <Element> childElements;

            if (UserSettings.ForeignLocaleCultureInfo == null || UserSettings.ForeignLocaleCultureInfo.Equals(UserSettings.ActiveLocaleCultureInfo))
            {
                childElements = ElementFacade.GetChildren(elementHandle, searchToken).ToList();
            }
            else
            {
                childElements = ElementFacade.GetForeignChildren(elementHandle, searchToken).ToList();
            }

            //int t3 = Environment.TickCount;

            List <ClientElement> resultList = childElements.ToClientElementList();

            int t4 = Environment.TickCount;

            //LoggingService.LogVerbose("RGB(255, 0, 255)TreeServiceFacade", string.Format("ElementHandle: {0} ms", t2 - t1));
            //LoggingService.LogVerbose("RGB(255, 0, 255)TreeServiceFacade", string.Format("GetChildren: {0} ms", t3 - t2));
            //LoggingService.LogVerbose("RGB(255, 0, 255)TreeServiceFacade", string.Format("ToClientElementList: {0} ms", t4 - t3));
            //LoggingService.LogVerbose("RGB(255, 0, 255)TreeServiceFacade", string.Format("Total: {0} ms", t4 - t1));
            //LoggingService.LogVerbose("RGB(255, 0, 255)TreeServiceFacade", "----- End -------------------------------------------------");

            //LoggingService.LogVerbose("TreeServiceFacade", string.Format("GetChildren: {0} ms", t4 - t1));

            return(resultList);
        }
コード例 #6
0
        public void Execute(EntityToken entityToken, ActionToken actionToken, TaskManagerEvent taskManagerEvent)
        {
            var flowServicesContainer = new FlowControllerServicesContainer(
                new ManagementConsoleMessageService(this.ConsoleId),
                new ElementDataExchangeService(this.ElementProviderName),
                this
                );

            FlowToken flowToken = ActionExecutorFacade.Execute(entityToken, actionToken, flowServicesContainer, taskManagerEvent);

            IFlowUiDefinition uiDefinition = FlowControllerFacade.GetCurrentUiDefinition(flowToken, flowServicesContainer);

            if (uiDefinition is FlowUiDefinitionBase flowUiDefinition)
            {
                string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken, true);
                ViewTransitionHelper.HandleNew(this.ConsoleId, this.ElementProviderName, serializedEntityToken, flowToken, flowUiDefinition);
            }
        }
コード例 #7
0
        public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
        {
            string url = UrlUtils.ResolveAdminUrl("InstalledPackages/content/views/Composite.Tools.LinkChecker/ListBrokenLinks.aspx");

            var consoleServices = flowControllerServicesContainer.GetService <IManagementConsoleMessageService>();
            var openViewMsg     = new OpenViewMessageQueueItem
            {
                EntityToken = EntityTokenSerializer.Serialize(entityToken, true),
                ViewId      = "LinkChecker",
                Label       = GetResourceString("LinkCheckerActionToken.Label"),
                Url         = url,
                ViewType    = ViewType.Main
            };

            ConsoleMessageQueueFacade.Enqueue(openViewMsg, consoleServices.CurrentConsoleId);

            return(null);
        }
コード例 #8
0
        public override IEnumerable <System.Xml.Linq.XElement> Install()
        {
            // grant Perspective permissions to the current user
            string      perspectiveName = "Composite.Tools.PackageCreator";
            EntityToken entityToken     = new VirtualElementProviderEntityToken("VirtualElementProvider", perspectiveName);

            IUserActivePerspective activePerspective = DataFacade.BuildNew <IUserActivePerspective>();
            string Username = Composite.C1Console.Users.UserSettings.Username;

            activePerspective.Username = Username;
            activePerspective.SerializedEntityToken = EntityTokenSerializer.Serialize(entityToken);
            activePerspective.Id = Guid.NewGuid();

            DataFacade.AddNew <IUserActivePerspective>(activePerspective);
            LoggingService.LogInformation("Composite.Tools.PackageCreator", String.Format("Access to the {0} granted for the {1}.", perspectiveName, Username));

            yield break;
        }
コード例 #9
0
        /// <exclude />
        public static IEnumerable <EntityToken> GetParentEntityTokens(this Dictionary <string, string> piggybag, EntityToken entityTokenToInclude = null)
        {
            if (entityTokenToInclude != null)
            {
                yield return(entityTokenToInclude);
            }

            int generation = 1;

            string seriazliedEntityToken;

            while (piggybag.TryGetValue(string.Format("{0}{1}", ParentEntityTokenPiggybagString, generation), out seriazliedEntityToken))
            {
                yield return(EntityTokenSerializer.Deserialize(seriazliedEntityToken));

                generation++;
            }
        }
コード例 #10
0
        private void saveCodeActivity_Save_ExecuteCode(object sender, EventArgs e)
        {
            IUserGroup    userGroup = this.GetBinding <IUserGroup>("UserGroup");
            List <string> newUserGroupEntityTokens = ActivePerspectiveFormsHelper.GetSelectedSerializedEntityTokens(this.Bindings).ToList();

            // If current user belongs to currently edited group -> checking that user won't lost access "Users" perspective
            if (!ValidateUserPreservesAdminRights(userGroup, newUserGroupEntityTokens))
            {
                return;
            }

            UpdateTreeRefresher updateTreeRefresher = CreateUpdateTreeRefresher(this.EntityToken);

            EntityToken rootEntityToken = ElementFacade.GetRootsWithNoSecurity().Select(f => f.ElementHandle.EntityToken).Single();
            IEnumerable <PermissionType> newPermissionTypes = GlobalPermissionsFormsHelper.GetSelectedPermissionTypes(this.Bindings);

            UserGroupPermissionDefinition userGroupPermissionDefinition =
                new ConstructorBasedUserGroupPermissionDefinition(
                    userGroup.Id,
                    newPermissionTypes,
                    EntityTokenSerializer.Serialize(rootEntityToken)
                    );

            PermissionTypeFacade.SetUserGroupPermissionDefinition(userGroupPermissionDefinition);

            UserGroupPerspectiveFacade.SetSerializedEntityTokens(userGroup.Id, newUserGroupEntityTokens);

            SetSaveStatus(true);

            LoggingService.LogEntry("UserManagement",
                                    $"C1 Console user group '{userGroup.Name}' updated by '{UserValidationFacade.GetUsername()}'.",
                                    LoggingService.Category.Audit,
                                    TraceEventType.Information);

            if (userGroup.Name != this.GetBinding <string>("OldName"))
            {
                DataFacade.Update(userGroup);

                this.UpdateBinding("OldName", userGroup.Name);

                updateTreeRefresher.PostRefreshMesseges(userGroup.GetDataEntityToken());
            }
        }
コード例 #11
0
        /// <exclude />
        public static void ExecuteElementAction(string providerName, string serializedEntityToken, string piggybag, string serializedActionToken, string consoleId)
        {
            using (DebugLoggingScope.MethodInfoScope)
            {
                EntityToken entityToken = EntityTokenSerializer.Deserialize(serializedEntityToken);
                if (!entityToken.IsValid())
                {
                    ShowInvalidEntityMessage(consoleId);
                    return;
                }

                var elementHandle = new ElementHandle(providerName, entityToken, piggybag);

                ActionToken  actionToken  = ActionTokenSerializer.Deserialize(serializedActionToken, true);
                ActionHandle actionHandle = new ActionHandle(actionToken);

                ActionExecutionMediator.ExecuteElementAction(elementHandle, actionHandle, consoleId);
            }
        }
コード例 #12
0
        public static void ExecuteElementAction(ElementHandle elementHandle, ActionHandle actionHandle, string consoleId)
        {
            var flowServicesContainer = new FlowControllerServicesContainer(
                new ManagementConsoleMessageService(consoleId),
                new ElementDataExchangeService(elementHandle.ProviderName),
                new ActionExecutionService(elementHandle.ProviderName, consoleId),
                new ElementInformationService(elementHandle)
                );

            FlowToken flowToken = ActionExecutorFacade.Execute(elementHandle.EntityToken, actionHandle.ActionToken, flowServicesContainer);

            IFlowUiDefinition uiDefinition = FlowControllerFacade.GetCurrentUiDefinition(flowToken, flowServicesContainer);

            if (uiDefinition is FlowUiDefinitionBase flowUiDefinition)
            {
                string serializedEntityToken = EntityTokenSerializer.Serialize(elementHandle.EntityToken, true);
                ViewTransitionHelper.HandleNew(consoleId, elementHandle.ProviderName, serializedEntityToken, flowToken, flowUiDefinition);
            }
        }
コード例 #13
0
        public override IEnumerable <XElement> Install()
        {
            // Sitemap Perspective
            IUserGroupActivePerspective sitemapPerspective = DataFacade.BuildNew <IUserGroupActivePerspective>();
            var userGroup = DataFacade.GetData <IUserGroup>().FirstOrDefault(u => u.Name == "Administrator");

            if (userGroup != null)
            {
                sitemapPerspective.UserGroupId = userGroup.Id;
                EntityToken entityToken = new TreePerspectiveEntityToken("SitemapElement");
                sitemapPerspective.SerializedEntityToken = EntityTokenSerializer.Serialize(entityToken);
                sitemapPerspective.Id = Guid.NewGuid();
                DataFacade.AddNew(sitemapPerspective);
                LoggingService.LogInformation("ComposerExperience", string.Format("Access to the Sitemap Perspective granted for group {0}.", userGroup.Name));
            }

            FixDefaultLanguageUrlMapping();

            yield break;
        }
コード例 #14
0
        public void Execute(EntityToken entityToken, ActionToken actionToken, TaskManagerEvent taskManagerEvent)
        {
            FlowControllerServicesContainer flowServicesContainer = new FlowControllerServicesContainer();

            flowServicesContainer.AddService(new ManagementConsoleMessageService(this.ConsoleId));
            flowServicesContainer.AddService(new ElementDataExchangeService(this.ElementProviderName));
            flowServicesContainer.AddService(this);

            FlowToken flowToken = ActionExecutorFacade.Execute(entityToken, actionToken, flowServicesContainer, taskManagerEvent);

            IFlowUiDefinition uiDefinition = FlowControllerFacade.GetCurrentUiDefinition(flowToken, flowServicesContainer);

            ActionResult result = new ActionResult();

            if (typeof(FlowUiDefinitionBase).IsAssignableFrom(uiDefinition.GetType()))
            {
                string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken, true);
                ViewTransitionHelper.HandleNew(this.ConsoleId, this.ElementProviderName, serializedEntityToken, flowToken, (FlowUiDefinitionBase)uiDefinition);
            }
        }
コード例 #15
0
        private static void UpdateLockingInformation(EntityToken entityToken, object newOwnerId)
        {
            LockingInformation lockingInformation;

            if (!_lockingInformations.TryGetValue(entityToken, out lockingInformation))
            {
                throw new InvalidOperationException("LockingInformation record missing");
            }

            string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken);

            ILockingInformation lockingInformationDataItem =
                DataFacade.GetData <ILockingInformation>().
                Single(f => f.SerializedEntityToken == serializedEntityToken);

            lockingInformationDataItem.SerializedOwnerId = SerializeOwnerId(newOwnerId);
            DataFacade.Update(lockingInformationDataItem);

            lockingInformation.OwnerId = newOwnerId;
        }
コード例 #16
0
        public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
        {
            string currentConsoleId = flowControllerServicesContainer.GetService <Composite.C1Console.Events.IManagementConsoleMessageService>().CurrentConsoleId;

            DisplayLocalOrderingActionToken castedActionToken = (DisplayLocalOrderingActionToken)actionToken;

            string url = string.Format("{0}?ParentPageId={1}", BaseUrl, HttpUtility.UrlEncode(castedActionToken.ParentPageId.ToString()));

            ConsoleMessageQueueFacade.Enqueue(
                new OpenViewMessageQueueItem
            {
                EntityToken = EntityTokenSerializer.Serialize(entityToken, true),
                Url         = url,
                ViewId      = Guid.NewGuid().ToString(),
                ViewType    = ViewType.Main,
                Label       = "Pages local orderings"
            },
                currentConsoleId);

            return(null);
        }
コード例 #17
0
        /// <exclude />
        public static List <ClientLabeledProperty> GetLabeledProperties(string providerName, string serializedEntityToken, string piggybag)
        {
            EntityToken   elementEntityToken = EntityTokenSerializer.Deserialize(serializedEntityToken);
            ElementHandle elementHandle      = new ElementHandle(providerName, elementEntityToken, piggybag);

            IEnumerable <LabeledProperty> labeledProperties;

            if (UserSettings.ForeignLocaleCultureInfo == null || UserSettings.ForeignLocaleCultureInfo.Equals(UserSettings.ActiveLocaleCultureInfo))
            {
                labeledProperties = ElementFacade.GetLabeledProperties(elementHandle);
            }
            else
            {
                labeledProperties = ElementFacade.GetForeignLabeledProperties(elementHandle);
            }


            return
                ((from property in labeledProperties
                  select new ClientLabeledProperty(property)).ToList());
        }
コード例 #18
0
        protected static void UpdateParents(string seralizedEntityToken, string consoleId)
        {
            var entityToken = EntityTokenSerializer.Deserialize(seralizedEntityToken);
            var graph       = new RelationshipGraph(entityToken, RelationshipGraphSearchOption.Both);

            if (graph.Levels.Count() <= 1)
            {
                return;
            }

            var level = graph.Levels.ElementAt(1);

            foreach (var token in level.AllEntities)
            {
                var consoleMessageQueueItem = new RefreshTreeMessageQueueItem
                {
                    EntityToken = token
                };

                ConsoleMessageQueueFacade.Enqueue(consoleMessageQueueItem, consoleId);
            }
        }
コード例 #19
0
        private void saveCodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            string virtualPath = GetFileVirtualPath();
            string filePath    = PathUtil.Resolve(virtualPath);

            WebsiteFile websiteFile = new WebsiteFile(filePath);

            string content     = this.GetBinding <string>("FileContent");
            string fixedSource = PageTemplateHelper.FixHtmlEscapeSequences(content);

            EntityToken newEntityToken;
            bool        isValid = ValidateMarkup(virtualPath, fixedSource, out newEntityToken);

            if (isValid)
            {
                websiteFile.WriteAllText(fixedSource);

                PageTemplateProviderRegistry.FlushTemplates();

                this.CreateParentTreeRefresher().PostRefreshMesseges(this.EntityToken);
            }

            if (isValid && newEntityToken != null)
            {
                SetSaveStatus(true, newEntityToken);

                SerializedEntityToken = EntityTokenSerializer.Serialize(newEntityToken);
            }
            else
            {
                SetSaveStatus(isValid);
            }

            if (isValid && fixedSource != content)
            {
                UpdateBinding("FileContent", fixedSource);
                RerenderView();
            }
        }
コード例 #20
0
    protected void Page_Load(object sender, EventArgs e)
    {
        EntityToken entityToken = EntityTokenSerializer.Deserialize(Request["entityToken"]);
        var         result      = XElement.Load(entityToken.Id);
        var         table       = new XElement("table");

        Response.ContentType = "application/vnd.ms-excel";

        Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", Path.GetFileNameWithoutExtension(entityToken.Id)));

        var attributes = result.Elements().Attributes()
                         .Where(a => !a.IsNamespaceDeclaration)
                         .Select(a => a.Name).Distinct();

        table.Add(
            new XElement("tr",
                         attributes.Select(
                             a => new XElement("th",
                                               a.LocalName
                                               )
                             )
                         )
            );

        table.Add(
            result.Elements().Select(
                row => new XElement("tr",
                                    attributes.Select(
                                        a => new XElement("td",
                                                          (row.Attribute(a) != null) ? row.Attribute(a).Value : string.Empty
                                                          )
                                        )
                                    )
                )
            );

        TableLiteral.Text = table.ToString();
    }
コード例 #21
0
        public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
        {
            UrlActionToken urlActionToken = (UrlActionToken)actionToken;

            string currentConsoleId = flowControllerServicesContainer.GetService <IManagementConsoleMessageService>().CurrentConsoleId;

            string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken);

            string url = urlActionToken.Url;

            string extendedUrl = $"{url}{(url.Contains("?") ? "&" : "?")}EntityToken={HttpUtility.UrlEncode(serializedEntityToken)}";

            ConsoleMessageQueueFacade.Enqueue(
                new OpenViewMessageQueueItem
            {
                Url                = extendedUrl,
                ViewId             = Guid.NewGuid().ToString(),
                ViewType           = ViewType.Main,
                Label              = urlActionToken.Label,
                IconResourceHandle = urlActionToken.Icon
            }, currentConsoleId);

            return(null);
        }
コード例 #22
0
        /// <exclude />
        public FlowToken Execute(string serializedEntityToken, string serializedActionToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
        {
            var dataEntityToken = (DataEntityToken)EntityTokenSerializer.Deserialize(serializedEntityToken);

            var data = dataEntityToken.Data;

            Verify.IsNotNull(data, "Failed to get the data from an entity token");

            using (new DataScope(DataScopeIdentifier.Administrated))
            {
                var treeRefresher = new AddNewTreeRefresher(dataEntityToken, flowControllerServicesContainer);

                var newData = (IData)StaticReflection.GetGenericMethodInfo(() => CloneData((IData)null))
                              .MakeGenericMethod(data.DataSourceId.InterfaceType).Invoke(this, new object[] { data });

                var consoleId = flowControllerServicesContainer.GetService <IManagementConsoleMessageService>().CurrentConsoleId;

                ConsoleCommandHelper.SelectConsoleElementWithoutPerspectiveChange(consoleId, newData.GetDataEntityToken());

                treeRefresher.PostRefreshMessages(dataEntityToken);
            }

            return(null);
        }
コード例 #23
0
        private void saveCodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            IUser user          = this.GetBinding <IUser>(BindingNames.User);
            var   userFormLogin = GetBinding <IUserFormLogin>(BindingNames.UserFormLogin);

            var userFormLoginFromDatabase = user.GetUserFormLogin();

            bool userValidated = true;

            ValidationResults validationResults = ValidationFacade.Validate(user);

            foreach (ValidationResult result in validationResults)
            {
                this.ShowFieldMessage($"{BindingNames.User}.{result.Key}", result.Message);
                userValidated = false;
            }


            List <CultureInfo> newActiveLocales     = ActiveLocalesFormsHelper.GetSelectedLocalesTypes(this.Bindings).ToList();
            List <CultureInfo> currentActiveLocales = null;
            CultureInfo        selectedActiveLocal  = null;

            if (newActiveLocales.Count > 0)
            {
                currentActiveLocales = UserSettings.GetActiveLocaleCultureInfos(user.Username).ToList();


                string selectedActiveLocaleName = (user.Username != UserSettings.Username ?
                                                   this.GetBinding <string>("ActiveLocaleName") :
                                                   UserSettings.ActiveLocaleCultureInfo.ToString());

                if (selectedActiveLocaleName != null)
                {
                    selectedActiveLocal = CultureInfo.CreateSpecificCulture(selectedActiveLocaleName);
                    if (!newActiveLocales.Contains(selectedActiveLocal))
                    {
                        if (user.Username != UserSettings.Username)
                        {
                            this.ShowFieldMessage("ActiveLocaleName", GetText("Website.Forms.Administrative.EditUserStep1.ActiveLocaleNotChecked"));
                        }
                        else
                        {
                            this.ShowFieldMessage("ActiveLocalesFormsHelper_Selected", GetText("Website.Forms.Administrative.EditUserStep1.NoActiveLocaleSelected"));
                        }
                        userValidated = false;
                    }
                }
            }
            else
            {
                this.ShowFieldMessage("ActiveLocalesFormsHelper_Selected", GetText("Website.Forms.Administrative.EditUserStep1.NoActiveLocaleSelected"));
                userValidated = false;
            }


            string systemPerspectiveEntityToken = EntityTokenSerializer.Serialize(AttachingPoint.SystemPerspective.EntityToken);

            List <Guid>   newUserGroupIds            = UserGroupsFormsHelper.GetSelectedUserGroupIds(this.Bindings);
            List <string> newSerializedEnitityTokens = ActivePerspectiveFormsHelper.GetSelectedSerializedEntityTokens(this.Bindings).ToList();


            if (string.Compare(user.Username, UserSettings.Username, StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                // Current user shouldn't be able to lock itself
                if (userFormLogin.IsLocked)
                {
                    this.ShowMessage(DialogType.Message,
                                     Texts.EditUserWorkflow_EditErrorTitle,
                                     Texts.EditUserWorkflow_LockingOwnUserAccount);

                    userValidated = false;
                }

                // Current user shouldn't be able to remove its own access to "System" perspective
                var groupsWithAccessToSystemPerspective = new HashSet <Guid>(GetGroupsThatHasAccessToPerspective(systemPerspectiveEntityToken));

                if (!newSerializedEnitityTokens.Contains(systemPerspectiveEntityToken) &&
                    !newUserGroupIds.Any(groupsWithAccessToSystemPerspective.Contains))
                {
                    this.ShowMessage(DialogType.Message,
                                     Texts.EditUserWorkflow_EditErrorTitle,
                                     Texts.EditUserWorkflow_EditOwnAccessToSystemPerspective);

                    userValidated = false;
                }
            }

            string newPassword = this.GetBinding <string>(BindingNames.NewPassword);

            if (newPassword == NotPassword || UserFormLoginManager.ValidatePassword(userFormLoginFromDatabase, newPassword))
            {
                newPassword = null;
            }
            else
            {
                IList <string> validationMessages;
                if (!PasswordPolicyFacade.ValidatePassword(user, newPassword, out validationMessages))
                {
                    foreach (var message in validationMessages)
                    {
                        this.ShowFieldMessage(BindingNames.NewPassword, message);
                    }

                    userValidated = false;
                }
            }

            if (!userValidated)
            {
                return;
            }

            if (!userFormLogin.IsLocked)
            {
                userFormLogin.LockoutReason = (int)UserLockoutReason.Undefined;
            }
            else
            {
                bool wasLockedBefore = userFormLoginFromDatabase.IsLocked;

                if (!wasLockedBefore)
                {
                    userFormLoginFromDatabase.LockoutReason = (int)UserLockoutReason.LockedByAdministrator;
                }
            }

            UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken);

            bool reloadUsersConsoles = false;

            using (var transactionScope = TransactionsFacade.CreateNewScope())
            {
                DataFacade.Update(user);

                userFormLoginFromDatabase.Folder   = userFormLogin.Folder;
                userFormLoginFromDatabase.IsLocked = userFormLogin.IsLocked;
                DataFacade.Update(userFormLoginFromDatabase);

                if (newPassword != null)
                {
                    UserFormLoginManager.SetPassword(userFormLoginFromDatabase, newPassword);
                }

                string cultureName             = this.GetBinding <string>("CultureName");
                string c1ConsoleUiLanguageName = this.GetBinding <string>("C1ConsoleUiLanguageName");

                UserSettings.SetUserCultureInfo(user.Username, CultureInfo.CreateSpecificCulture(cultureName));
                UserSettings.SetUserC1ConsoleUiLanguage(user.Username, CultureInfo.CreateSpecificCulture(c1ConsoleUiLanguageName));

                List <string> existingSerializedEntityTokens = UserPerspectiveFacade.GetSerializedEntityTokens(user.Username).ToList();

                int intersectCount = existingSerializedEntityTokens.Intersect(newSerializedEnitityTokens).Count();
                if ((intersectCount != newSerializedEnitityTokens.Count) ||
                    (intersectCount != existingSerializedEntityTokens.Count))
                {
                    UserPerspectiveFacade.SetSerializedEntityTokens(user.Username, newSerializedEnitityTokens);

                    if (UserSettings.Username == user.Username)
                    {
                        reloadUsersConsoles = true;
                    }
                }

                if (DataLocalizationFacade.ActiveLocalizationCultures.Any())
                {
                    foreach (CultureInfo cultureInfo in newActiveLocales)
                    {
                        if (!currentActiveLocales.Contains(cultureInfo))
                        {
                            UserSettings.AddActiveLocaleCultureInfo(user.Username, cultureInfo);
                        }
                    }

                    foreach (CultureInfo cultureInfo in currentActiveLocales)
                    {
                        if (!newActiveLocales.Contains(cultureInfo))
                        {
                            UserSettings.RemoveActiveLocaleCultureInfo(user.Username, cultureInfo);
                        }
                    }

                    if (selectedActiveLocal != null)
                    {
                        if (!UserSettings.GetCurrentActiveLocaleCultureInfo(user.Username).Equals(selectedActiveLocal))
                        {
                            reloadUsersConsoles = true;
                        }

                        UserSettings.SetCurrentActiveLocaleCultureInfo(user.Username, selectedActiveLocal);
                    }
                    else if (UserSettings.GetActiveLocaleCultureInfos(user.Username).Any())
                    {
                        UserSettings.SetCurrentActiveLocaleCultureInfo(user.Username, UserSettings.GetActiveLocaleCultureInfos(user.Username).First());
                    }
                }


                List <IUserUserGroupRelation> oldRelations = DataFacade.GetData <IUserUserGroupRelation>(f => f.UserId == user.Id).ToList();

                IEnumerable <IUserUserGroupRelation> deleteRelations =
                    from r in oldRelations
                    where !newUserGroupIds.Contains(r.UserGroupId)
                    select r;

                DataFacade.Delete(deleteRelations);


                foreach (Guid newUserGroupId in newUserGroupIds)
                {
                    Guid groupId = newUserGroupId;
                    if (oldRelations.Any(f => f.UserGroupId == groupId))
                    {
                        continue;
                    }

                    var userUserGroupRelation = DataFacade.BuildNew <IUserUserGroupRelation>();
                    userUserGroupRelation.UserId      = user.Id;
                    userUserGroupRelation.UserGroupId = newUserGroupId;

                    DataFacade.AddNew(userUserGroupRelation);
                }

                LoggingService.LogEntry("UserManagement",
                                        $"C1 Console user '{user.Username}' updated by '{UserValidationFacade.GetUsername()}'.",
                                        LoggingService.Category.Audit,
                                        TraceEventType.Information);

                transactionScope.Complete();
            }

            if (reloadUsersConsoles)
            {
                foreach (string consoleId in GetConsoleIdsOpenedByCurrentUser())
                {
                    ConsoleMessageQueueFacade.Enqueue(new RebootConsoleMessageQueueItem(), consoleId);
                }
            }

            SetSaveStatus(true);
            updateTreeRefresher.PostRefreshMesseges(user.GetDataEntityToken());
        }
        private static void UpgradeStoredData()
        {
            const string _ET  = "EntityToken";
            const string _DSI = "DataSourceId";

            List <string> magicPropertyNames = new List <string> {
                _ET, _DSI
            };
            Func <DataFieldDescriptor, bool> isSerializedFieldFunc = g => magicPropertyNames.Any(s => g.Name.Contains(s));
            var descriptors = DataMetaDataFacade.AllDataTypeDescriptors.Where(f => f.Fields.Any(isSerializedFieldFunc));

            foreach (var descriptor in descriptors)
            {
                Type dataType = descriptor.GetInterfaceType();

                if (dataType == null)
                {
                    continue;
                }

                var propertiesToUpdate = new List <PropertyInfo>();
                foreach (var tokenField in descriptor.Fields.Where(isSerializedFieldFunc))
                {
                    var tokenProperty = dataType.GetProperty(tokenField.Name);
                    propertiesToUpdate.Add(tokenProperty);
                }

                using (var dc = new DataConnection(PublicationScope.Unpublished))
                {
                    var allRows = DataFacade.GetData(dataType).ToDataList();

                    foreach (var rowItem in allRows)
                    {
                        bool rowChange = false;

                        foreach (var tokenProperty in propertiesToUpdate)
                        {
                            string token = tokenProperty.GetValue(rowItem) as string;

                            if (tokenProperty.Name.Contains(_ET))
                            {
                                try
                                {
                                    var entityToken       = EntityTokenSerializer.Deserialize(token);
                                    var tokenReserialized = EntityTokenSerializer.Serialize(entityToken);

                                    if (tokenReserialized != token)
                                    {
                                        tokenProperty.SetValue(rowItem, tokenReserialized);
                                        rowChange = true;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _log.LogError(nameof(LegacySerializedEntityTokenUpgrader), "Failed to upgrade old token {0} from data type {1} as EntityToken.\n{2}", token, dataType.FullName, ex);
                                }
                            }

                            if (tokenProperty.Name.Contains(_DSI))
                            {
                                try
                                {
                                    token = EnsureValidDataSourceId(token);
                                    var dataSourceId             = DataSourceId.Deserialize(token);
                                    var dataSourceIdReserialized = dataSourceId.Serialize();

                                    if (dataSourceIdReserialized != token)
                                    {
                                        tokenProperty.SetValue(rowItem, dataSourceIdReserialized);
                                        rowChange = true;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _log.LogError(nameof(LegacySerializedEntityTokenUpgrader), "Failed to upgrade old token {0} from data type {1} as DataSourceId.\n{2}", token, dataType.FullName, ex);
                                }
                            }

                            if (rowChange)
                            {
                                DataFacade.Update(rowItem);
                            }
                        }
                    }
                }
            }
        }
コード例 #25
0
        /// <exclude />
        public static FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer, TaskManagerEvent taskManagerEvent)
        {
            if (entityToken == null)
            {
                throw new ArgumentNullException("entityToken");
            }
            if (actionToken == null)
            {
                throw new ArgumentNullException("actionToken");
            }


            string username = UserValidationFacade.GetUsername();

#if NO_SECURITY
#else
            HookingFacade.EnsureInitialization();

            IEnumerable <UserPermissionDefinition>      userPermissionDefinitions      = PermissionTypeFacade.GetUserPermissionDefinitions(username);
            IEnumerable <UserGroupPermissionDefinition> userGroupPermissionDefinitions = PermissionTypeFacade.GetUserGroupPermissionDefinitions(username);
            SecurityResult securityResult = SecurityResolver.Resolve(UserValidationFacade.GetUserToken(), actionToken, entityToken, userPermissionDefinitions, userGroupPermissionDefinitions);
            if (securityResult != SecurityResult.Allowed && !(entityToken is SecurityViolationWorkflowEntityToken))
            {
                return(ExecuteSecurityViolation(actionToken, entityToken, flowControllerServicesContainer));
            }
#endif

            bool ignoreLocking = actionToken.IsIgnoreEntityTokenLocking();

            if (!ignoreLocking && ActionLockingFacade.IsLocked(entityToken))
            {
                return(ExecuteEntityTokenLocked(actionToken, entityToken, flowControllerServicesContainer));
            }

            IActionExecutor actionExecutor = ActionExecutorCache.GetActionExecutor(actionToken);

            ActionEventSystemFacade.FireOnBeforeActionExecution(entityToken, actionToken);

            FlowToken flowToken;
            using (TaskContainer taskContainer = TaskManagerFacade.CreateNewTasks(entityToken, actionToken, taskManagerEvent))
            {
                ITaskManagerFlowControllerService taskManagerService = null;
                if (flowControllerServicesContainer.GetService(typeof(ITaskManagerFlowControllerService)) == null)
                {
                    taskManagerService = new TaskManagerFlowControllerService(taskContainer);
                    flowControllerServicesContainer.AddService(taskManagerService);
                }

                try
                {
                    if (actionExecutor is IActionExecutorSerializedParameters)
                    {
                        string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken);
                        string serializedActionToken = ActionTokenSerializer.Serialize(actionToken);

                        flowToken = Execute(actionExecutor as IActionExecutorSerializedParameters,
                                            serializedEntityToken, serializedActionToken, actionToken,
                                            flowControllerServicesContainer);
                    }
                    else
                    {
                        flowToken = Execute(actionExecutor, entityToken, actionToken,
                                            flowControllerServicesContainer);
                    }
                }
                finally
                {
                    if (taskManagerService != null)
                    {
                        flowControllerServicesContainer.RemoveService(taskManagerService);
                    }
                }

                taskContainer.SetOnIdleTaskManagerEvent(new FlowTaskManagerEvent(flowToken));
                taskContainer.UpdateTasksWithFlowToken(flowToken);

                taskContainer.SaveTasks();
            }

            ActionEventSystemFacade.FireOnAfterActionExecution(entityToken, actionToken, flowToken);

            IManagementConsoleMessageService managementConsoleMessageService = flowControllerServicesContainer
                                                                               .GetService <IManagementConsoleMessageService>();
            if (managementConsoleMessageService != null)
            {
                FlowControllerFacade.RegisterNewFlowInformation(flowToken, entityToken, actionToken,
                                                                managementConsoleMessageService.CurrentConsoleId);
            }
            else
            {
                Log.LogWarning(nameof(ActionExecutorFacade), "Missing ManagementConsoleMessageService, can not register the flow");
            }

            return(flowToken);
        }
コード例 #26
0
        public override IEnumerable <EntityToken> GetEntityTokens(EntityToken childEntityToken, TreeNodeDynamicContext dynamicContext)
        {
            EntityToken possibleCurrentEntityToken;

            TreeSimpleElementEntityToken treeSimpleElementEntityToken = childEntityToken as TreeSimpleElementEntityToken;

            if (treeSimpleElementEntityToken != null)
            {
                possibleCurrentEntityToken = treeSimpleElementEntityToken.ParentEntityToken;
            }
            else
            {
                possibleCurrentEntityToken = childEntityToken;
            }

            foreach (EntityToken entityToken in this.ParentNode.GetEntityTokens(possibleCurrentEntityToken, dynamicContext))
            {
                yield return(new TreeSimpleElementEntityToken(this.Id, this.Tree.TreeId, EntityTokenSerializer.Serialize(entityToken)));
            }
        }
コード例 #27
0
 /// <exclude />
 public string Serialize(object objectToSerialize)
 {
     return(EntityTokenSerializer.Serialize(((RefreshTreeMessageQueueItem)objectToSerialize).EntityToken));
 }
コード例 #28
0
 public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
 {
     return(Execute(EntityTokenSerializer.Serialize(entityToken), ActionTokenSerializer.Serialize(actionToken), actionToken, flowControllerServicesContainer));
 }
コード例 #29
0
        private static void UpgradeStoredData()
        {
            const string _ET  = "EntityToken";
            const string _DSI = "DataSourceId";

            List <string> magicPropertyNames = new List <string> {
                _ET, _DSI
            };
            Func <DataFieldDescriptor, bool> isSerializedFieldFunc = g => magicPropertyNames.Any(s => g.Name.Contains(s));
            var descriptors = DataMetaDataFacade.AllDataTypeDescriptors.Where(f => f.Fields.Any(isSerializedFieldFunc));

            foreach (var descriptor in descriptors)
            {
                Type dataType = descriptor.GetInterfaceType();

                if (dataType == null)
                {
                    continue;
                }

                var propertiesToUpdate = new List <PropertyInfo>();
                foreach (var tokenField in descriptor.Fields.Where(isSerializedFieldFunc))
                {
                    var tokenProperty = dataType.GetProperty(tokenField.Name);
                    propertiesToUpdate.Add(tokenProperty);
                }

                using (new DataConnection(PublicationScope.Unpublished))
                {
                    var allRows = DataFacade.GetData(dataType).ToDataList();

                    var toUpdate = new List <IData>();

                    int errors = 0, updated = 0;

                    foreach (var rowItem in allRows)
                    {
                        bool rowChange = false;

                        foreach (var tokenProperty in propertiesToUpdate)
                        {
                            string token = tokenProperty.GetValue(rowItem) as string;

                            try
                            {
                                string tokenReserialized;

                                if (tokenProperty.Name.Contains(_ET))
                                {
                                    var entityToken = EntityTokenSerializer.Deserialize(token);
                                    tokenReserialized = EntityTokenSerializer.Serialize(entityToken);
                                }
                                else if (tokenProperty.Name.Contains(_DSI))
                                {
                                    token = EnsureValidDataSourceId(token);
                                    var dataSourceId = DataSourceId.Deserialize(token);
                                    tokenReserialized = dataSourceId.Serialize();
                                }
                                else
                                {
                                    throw new InvalidOperationException("This line should not be reachable");
                                }

                                if (tokenReserialized != token)
                                {
                                    tokenProperty.SetValue(rowItem, tokenReserialized);
                                    rowChange = true;
                                }
                            }
                            catch (Exception ex)
                            {
                                errors++;
                                if (errors <= MaxErrorMessagesPerType)
                                {
                                    _log.LogError(LogTitle, $"Failed to upgrade old token '{token}' from data type '{dataType.FullName}' as EntityToken.\n{ex}");
                                }
                            }
                        }

                        if (rowChange)
                        {
                            updated++;
                            toUpdate.Add(rowItem);

                            if (toUpdate.Count >= 1000)
                            {
                                DataFacade.Update(toUpdate, true, false, false);
                                toUpdate.Clear();
                            }
                        }
                    }

                    if (toUpdate.Count > 0)
                    {
                        DataFacade.Update(toUpdate, true, false, false);
                        toUpdate.Clear();
                    }

                    _log.LogInformation(LogTitle, $"Finished updating serialized tokens for data type '{dataType.FullName}'. Rows: {allRows.Count}, Updated: {updated}, Errors: {errors}");
                }
            }
        }
コード例 #30
0
    private void PrettyPrintEntityToken(EntityToken entityToken, string color)
    {
        var idList = new List <object>();

        if (entityToken.Id.Contains("="))
        {
            Dictionary <string, string> dic = StringConversionServices.ParseKeyValueCollection(entityToken.Id);

            idList.Add(new XElement("br"));

            foreach (KeyValuePair <string, string> kvp in dic)
            {
                idList.Add(new XElement("span", new XAttribute("style", "padding-left: 15px; color: " + color),
                                        string.Format("{0} = {1}", kvp.Key, kvp.Value)));
                idList.Add(new XElement("br"));
            }
        }
        else
        {
            idList.Add(entityToken.Id);
        }


        var userPermissionsDefinedHere  = new List <object>();
        var currentUsersPermissionTypes = new List <object>();

        string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken);

        var usernames = UserValidationFacade.AllUsernames.OrderBy(u => u).ToList();

        foreach (string username in usernames)
        {
            IEnumerable <PermissionType> userPermissionTypes = PermissionTypeFacade.GetLocallyDefinedUserPermissionTypes(
                new UserToken(username), entityToken);

            AddPersissionsLine(userPermissionsDefinedHere, username, userPermissionTypes);

            var currentPermissionTypes = PermissionTypeFacade.GetCurrentPermissionTypes(
                new UserToken(username), entityToken,
                PermissionTypeFacade.GetUserPermissionDefinitions(username),
                PermissionTypeFacade.GetUserGroupPermissionDefinitions(username));

            AddPersissionsLine(currentUsersPermissionTypes, username, currentPermissionTypes);
        }


        var userGroupPermissionsDefinedHere = new List <object>();
        var inheritedGroupPermissions       = new List <object>();

        var userGroups = DataFacade.GetData <IUserGroup>().OrderBy(ug => ug.Name).ToList();

        foreach (IUserGroup userGroup in userGroups)
        {
            var userGroupPermissionTypes = PermissionTypeFacade.GetLocallyDefinedUserGroupPermissionTypes(userGroup.Id, entityToken);

            AddPersissionsLine(userGroupPermissionsDefinedHere, userGroup.Name, userGroupPermissionTypes);

            IEnumerable <PermissionType> inheritedUserGroupPermissionTypes = PermissionTypeFacade.GetInheritedGroupPermissionsTypes(userGroup.Id, entityToken);

            AddPersissionsLine(inheritedGroupPermissions, userGroup.Name, inheritedUserGroupPermissionTypes);
        }



        var element =
            new XElement("div",
                         new XAttribute("style",
                                        string.Format(
                                            "border:2px; border-style: solid; border-color: {0}; margin-bottom: 2px; margin-left:5px; margin-right:5px; padding: 3px;",
                                            color)),
                         new XElement("b", "Runtime type: "),
                         entityToken.GetType().ToString(),
                         new XElement("br"),
                         new XElement("b", "Hashcode: "),
                         entityToken.GetHashCode().ToString(),
                         new XElement("br"),
                         new XElement("b", "Source: "),
                         entityToken.Source,
                         new XElement("br"),
                         new XElement("b", "Type: "),
                         entityToken.Type,
                         new XElement("br"),
                         new XElement("b", "Id: "),
                         idList,
                         new XElement("br"),
                         new XElement("b", "Serialized entity token: "),
                         serializedEntityToken,
                         new XElement("br"),
                         new XElement("br"));


        if (currentUsersPermissionTypes.Any())
        {
            element.Add(
                new XElement("b", "Resolved users permissions here: "),
                new XElement("br"),
                currentUsersPermissionTypes,
                new XElement("br"));
        }


        if (userPermissionsDefinedHere.Any())
        {
            element.Add(
                new XElement("b", "Users permissions defined here: "),
                new XElement("br"),
                userPermissionsDefinedHere,
                new XElement("br"));
        }

        if (inheritedGroupPermissions.Any())
        {
            element.Add(
                new XElement("b", "Inherted user group permissions: "),
                new XElement("br"),
                inheritedGroupPermissions,
                new XElement("br"));
        }

        if (userGroupPermissionsDefinedHere.Any())
        {
            element.Add(
                new XElement("b", "User group permissions defined here: "),
                new XElement("br"),
                userGroupPermissionsDefinedHere,
                new XElement("br"));
        }


        RelationshipGraphHolder.Controls.Add(new LiteralControl(element.ToString()));
    }