Пример #1
0
        private void DeleteOldTables(List <string> tables, Tuple <string, string, string>[] constraints)
        {
            if (tables.InvariantContains("umbracoUser2App"))
            {
                Delete.Table("umbracoUser2App");
            }

            if (tables.InvariantContains("umbracoUser2NodePermission"))
            {
                Delete.Table("umbracoUser2NodePermission");
            }

            if (tables.InvariantContains("umbracoUserType") && tables.InvariantContains("umbracoUser"))
            {
                if (constraints.Any(x => x.Item1.InvariantEquals("umbracoUser") && x.Item3.InvariantEquals("FK_umbracoUser_umbracoUserType_id")))
                {
                    Delete.ForeignKey("FK_umbracoUser_umbracoUserType_id").OnTable("umbracoUser");
                }
                //This is the super old constraint name of the FK for user type so check this one too
                if (constraints.Any(x => x.Item1.InvariantEquals("umbracoUser") && x.Item3.InvariantEquals("FK_user_userType")))
                {
                    Delete.ForeignKey("FK_user_userType").OnTable("umbracoUser");
                }

                Delete.Column("userType").FromTable("umbracoUser");
                Delete.Table("umbracoUserType");
            }
        }
Пример #2
0
        private bool AddNewTables(List <string> tables)
        {
            var updated = false;

            if (tables.InvariantContains("umbracoUserGroup") == false)
            {
                Create.Table <UserGroupDto>().Do();
                updated = true;
            }

            if (tables.InvariantContains("umbracoUser2UserGroup") == false)
            {
                Create.Table <User2UserGroupDto>().Do();
                updated = true;
            }

            if (tables.InvariantContains("umbracoUserGroup2App") == false)
            {
                Create.Table <UserGroup2AppDto>().Do();
                updated = true;
            }

            if (tables.InvariantContains("umbracoUserGroup2NodePermission") == false)
            {
                Create.Table <UserGroup2NodePermissionDto>().Do();
                updated = true;
            }

            return(updated);
        }
        /// <summary>
        /// Scans for all attributed trees and ensures they exist in the tree xml
        /// </summary>
        private static void ScanTrees(ApplicationContext applicationContext)
        {
            var added = new List<string>();

            // Load all Controller Trees by attribute and add them to the XML config
            // we also need to make sure that any alias added with the new trees is not also added
            // with the legacy trees.
            var types = PluginManager.Current.ResolveAttributedTreeControllers();

            //get all non-legacy application tree's
            var items = types
                .Select(x =>
                        new Tuple<Type, TreeAttribute>(x, x.GetCustomAttributes<TreeAttribute>(false).Single()))
                .Where(x => applicationContext.Services.ApplicationTreeService.GetByAlias(x.Item2.Alias) == null)
                .Select(x => new ApplicationTree(x.Item2.Initialize, x.Item2.SortOrder, x.Item2.ApplicationAlias, x.Item2.Alias, x.Item2.Title, x.Item2.IconClosed, x.Item2.IconOpen, x.Item1.GetFullNameWithAssembly()))
                .ToArray();
                
            added.AddRange(items.Select(x => x.Alias));

            //find the legacy trees
            var legacyTreeTypes = PluginManager.Current.ResolveAttributedTrees();

            var legacyItems = legacyTreeTypes
                .Select(x =>
                        new Tuple<Type, global::umbraco.businesslogic.TreeAttribute>(
                            x, 
                            x.GetCustomAttributes<global::umbraco.businesslogic.TreeAttribute>(false).Single()))
                .Where(x => applicationContext.Services.ApplicationTreeService.GetByAlias(x.Item2.Alias) == null
                    //make sure the legacy tree isn't added on top of the controller tree!        
                            && added.InvariantContains(x.Item2.Alias) == false)
                .Select(x => new ApplicationTree(x.Item2.Initialize, x.Item2.SortOrder, x.Item2.ApplicationAlias, x.Item2.Alias, x.Item2.Title, x.Item2.IconClosed, x.Item2.IconOpen, x.Item1.GetFullNameWithAssembly()));

            applicationContext.Services.ApplicationTreeService.Intitialize(items.Concat(legacyItems));

        }
Пример #4
0
        public override object ConvertIntermediateToObject(IPublishedElement owner, PublishedPropertyType propertyType, PropertyCacheLevel cacheLevel, object source, bool preview)
        {
            if (source == null)
            {
                return(null);
            }

            //TODO: Inject an UmbracoHelper and create a GetUmbracoHelper method based on either injected or singleton
            if (UmbracoContext.Current != null)
            {
                if (propertyType.EditorAlias.Equals(Constants.PropertyEditors.Aliases.MultiNodeTreePicker))
                {
                    var udis = (Udi[])source;

                    if ((propertyType.Alias != null && PropertiesToExclude.InvariantContains(propertyType.Alias)) == false)
                    {
                        var multiNodeTreePicker = new List <IPublishedContent>();

                        var objectType = UmbracoObjectTypes.Unknown;

                        foreach (var udi in udis)
                        {
                            var guidUdi = udi as GuidUdi;
                            if (guidUdi == null)
                            {
                                continue;
                            }

                            IPublishedContent multiNodeTreePickerItem = null;
                            switch (udi.EntityType)
                            {
                            case Constants.UdiEntityType.Document:
                                multiNodeTreePickerItem = GetPublishedContent(udi, ref objectType, UmbracoObjectTypes.Document, id => _publishedSnapshotAccessor.PublishedSnapshot.Content.GetById(guidUdi.Guid));
                                break;

                            case Constants.UdiEntityType.Media:
                                multiNodeTreePickerItem = GetPublishedContent(udi, ref objectType, UmbracoObjectTypes.Media, id => _publishedSnapshotAccessor.PublishedSnapshot.Media.GetById(guidUdi.Guid));
                                break;

                            case Constants.UdiEntityType.Member:
                                multiNodeTreePickerItem = GetPublishedContent(udi, ref objectType, UmbracoObjectTypes.Member, id => _publishedSnapshotAccessor.PublishedSnapshot.Members.GetByProviderKey(guidUdi.Guid));
                                break;
                            }

                            if (multiNodeTreePickerItem != null)
                            {
                                multiNodeTreePicker.Add(multiNodeTreePickerItem);
                            }
                        }

                        return(multiNodeTreePicker);
                    }

                    // return the first nodeId as this is one of the excluded properties that expects a single id
                    return(udis.FirstOrDefault());
                }
            }
            return(source);
        }
Пример #5
0
        private void DeleteOldTables(List <string> tables, Tuple <string, string, string>[] constraints)
        {
            if (tables.InvariantContains("umbracoUser2App"))
            {
                Delete.Table("umbracoUser2App").Do();
            }

            if (tables.InvariantContains("umbracoUser2NodePermission"))
            {
                Delete.Table("umbracoUser2NodePermission").Do();
            }

            if (tables.InvariantContains("umbracoUserType") && tables.InvariantContains("umbracoUser"))
            {
                if (DatabaseType.IsMySql())
                {
                    //In MySql, this will drop the FK according to it's special naming rules
                    Delete.ForeignKey().FromTable("umbracoUser").ForeignColumn("userType").ToTable("umbracoUserType").PrimaryColumn("id");
                }
                else
                {
                    //Delete the FK if it exists before dropping the column
                    if (constraints.Any(x => x.Item1.InvariantEquals("umbracoUser") && x.Item3.InvariantEquals("FK_umbracoUser_umbracoUserType_id")))
                    {
                        Delete.ForeignKey("FK_umbracoUser_umbracoUserType_id").OnTable("umbracoUser").Do();
                    }

                    //This is the super old constraint name of the FK for user type so check this one too
                    if (constraints.Any(x => x.Item1.InvariantEquals("umbracoUser") && x.Item3.InvariantEquals("FK_user_userType")))
                    {
                        Delete.ForeignKey("FK_user_userType").OnTable("umbracoUser").Do();
                    }
                }

                Delete.Column("userType").FromTable("umbracoUser").Do();
                Delete.Table("umbracoUserType").Do();
            }
        }
            public LazyEnumerableTrees()
            {
                _lazyTrees = new Lazy <IEnumerable <ApplicationTree> >(() =>
                {
                    var added = new List <string>();

                    // Load all Controller Trees by attribute
                    var types = PluginManager.Current.ResolveAttributedTreeControllers();
                    //convert them to ApplicationTree instances
                    var items = types
                                .Select(x =>
                                        new Tuple <Type, TreeAttribute>(x, x.GetCustomAttributes <TreeAttribute>(false).Single()))
                                .Select(x => new ApplicationTree(x.Item2.Initialize, x.Item2.SortOrder, x.Item2.ApplicationAlias, x.Item2.Alias, x.Item2.Title, x.Item2.IconClosed, x.Item2.IconOpen, x.Item1.GetFullNameWithAssembly()))
                                .ToArray();

                    added.AddRange(items.Select(x => x.Alias));

                    //find the legacy trees
                    var legacyTreeTypes = PluginManager.Current.ResolveAttributedTrees();
                    //convert them to ApplicationTree instances
                    var legacyItems = legacyTreeTypes
                                      .Select(x =>
                                              new Tuple <Type, global::umbraco.businesslogic.TreeAttribute, ObsoleteAttribute>(
                                                  x,
                                                  x.GetCustomAttributes <global::umbraco.businesslogic.TreeAttribute>(false).SingleOrDefault(),
                                                  x.GetCustomAttributes <ObsoleteAttribute>(false).SingleOrDefault()))
                                      //ensure that the legacy tree attribute exists
                                      .Where(x => x.Item2 != null)
                                      //ensure that it's not obsoleted, any obsoleted tree will not be auto added to the config
                                      .Where(x => x.Item3 == null)
                                      //make sure the legacy tree isn't added on top of the controller tree!
                                      .Where(x => added.InvariantContains(x.Item2.Alias) == false)
                                      .Select(x => new ApplicationTree(x.Item2.Initialize, x.Item2.SortOrder, x.Item2.ApplicationAlias, x.Item2.Alias, x.Item2.Title, x.Item2.IconClosed, x.Item2.IconOpen, x.Item1.GetFullNameWithAssembly()));

                    return(items.Concat(legacyItems).ToArray());
                });
            }
Пример #7
0
        public List <IssuesInPeriod> GetGroupedIssuesData(int fromDay, int fromMonth, int fromYear, int toDay,
                                                          int toMonth, int toYear, string repository = "")
        {
            var gitHubService = new GitHubService();
            var teamMembers   = new List <string>();

            foreach (var team in gitHubService.GetTeamMembers())
            {
                teamMembers.AddRange(team.Members);
            }

            if (fromDay == 0)
            {
                fromDay = 1;
            }
            if (toDay == 0)
            {
                toDay = DateTime.DaysInMonth(toYear, toMonth);
            }

            var fromDate = DateTime.Parse($"{fromYear}-{fromMonth}-{fromDay} 00:00:00");
            var toDate   = DateTime.Parse($"{toYear}-{toMonth}-{toDay} 23:59:59");

            var repoService        = new RepositoryManagementService();
            var allCommunityIssues = repoService.GetAllCommunityIssues(false)
                                     .Where(x => x.Labels.Any(l => l.Name == "status/idea") == false).ToList();

            if (string.IsNullOrWhiteSpace(repository) == false)
            {
                allCommunityIssues = allCommunityIssues.Where(x => x.RepositoryName == repository).ToList();
            }

            var issues = allCommunityIssues
                         .Where(x => x.CreateDateTime >= fromDate && x.CreateDateTime <= toDate)
                         .OrderBy(x => x.CreateDateTime)
                         .GroupBy(x => new { x.CreateDateTime.Year, x.CreateDateTime.Month })
                         .ToDictionary(x => x.Key, x => x.ToList());

            var groupedIssues = new List <IssuesInPeriod>();

            foreach (var issuesInPeriod in issues)
            {
                var period    = $"{issuesInPeriod.Key.Year}{issuesInPeriod.Key.Month:00}";
                var groupName =
                    $"{DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(issuesInPeriod.Key.Month)} {issuesInPeriod.Key.Year}";
                var issuesList = new IssuesInPeriod
                {
                    MonthYear = period,
                    GroupName = groupName,

                    AllIssueClosingTimesInHours    = string.Empty,
                    IssueAverageClosingTimeInHours = 0,
                    IssueMedianClosingTimeInHours  = 0,
                    TargetClosingTimeInHours       = 2880, // 120 business days

                    AllIssueFirstCommentTimesInHours     = string.Empty,
                    IssueAverageFirstCommentTimesInHours = 0,
                    IssueMedianFirstCommentTimesInHours  = 0,
                    TargetFirstCommentTimeInHours        = 48, // 2 business days

                    NumberClosed  = 0,
                    NumberOpen    = 0,
                    NumberCreated = issuesInPeriod.Value.Count
                };

                var year           = issuesInPeriod.Key.Year;
                var month          = issuesInPeriod.Key.Month;
                var periodFirstDay = new DateTime(year, month, 1);
                var periodLastDay  = new DateTime(year, month, DateTime.DaysInMonth(year, month));

                foreach (var issue in allCommunityIssues)
                {
                    if (issue.CreateDateTime <= periodLastDay && issue.State != "closed")
                    {
                        issuesList.NumberOpen = issuesList.NumberOpen + 1;
                    }
                }

                var allClosingTimesInHours      = new List <double>();
                var allFirstCommentTimesInHours = new List <double>();
                foreach (var issue in issuesInPeriod.Value)
                {
                    if (issue.State == "closed" && issue.ClosedDateTime.HasValue)
                    {
                        var createDateTime = issue.CreateDateTime;
                        var closedDateTime = issue.ClosedDateTime.Value;

                        if (closedDateTime < periodFirstDay || closedDateTime > periodLastDay)
                        {
                            continue;
                        }

                        issuesList.NumberClosed = issuesList.NumberClosed + 1;

                        var hoursOpen = createDateTime.BusinessHoursUntil(closedDateTime);
                        allClosingTimesInHours.Add(hoursOpen);
                    }
                    else
                    {
                        //var dateLastDayOfMonth = issue.CreateDateTime.GetDateLastDayOfMonth().AddDays(1).AddSeconds(-1);
                        var hoursOpen = issue.CreateDateTime.BusinessHoursUntil(DateTime.Now);
                        allClosingTimesInHours.Add(hoursOpen);
                    }

                    double hoursBeforeFirstReply = 0;
                    double hoursBeforeFirstLabel = 0;
                    foreach (var comment in issue.Comments.OrderBy(x => x.CreateDateTime))
                    {
                        if (teamMembers.InvariantContains(comment.User.Login))
                        {
                            hoursBeforeFirstReply = issue.CreateDateTime.BusinessHoursUntil(comment.CreateDateTime);
                        }
                        else
                        {
                            //var dateLastDayOfMonth = issue.CreateDateTime.GetDateLastDayOfMonth().AddDays(1).AddSeconds(-1);
                            hoursBeforeFirstReply = issue.CreateDateTime.BusinessHoursUntil(DateTime.Now);
                        }
                    }

                    if (issue.Events.Any())
                    {
                        var firstLabel = issue.Events.OrderBy(x => x.CreateDateTime)
                                         .FirstOrDefault(x => x.Name == "labeled");
                        if (firstLabel != null)
                        {
                            hoursBeforeFirstLabel = issue.CreateDateTime.BusinessDaysUntil(firstLabel.CreateDateTime);
                        }
                    }

                    if (hoursBeforeFirstLabel != 0 && hoursBeforeFirstReply != 0)
                    {
                        double hours;
                        if (hoursBeforeFirstLabel < hoursBeforeFirstReply)
                        {
                            hours = hoursBeforeFirstLabel;
                        }
                        else
                        {
                            hours = hoursBeforeFirstReply;
                        }

                        allFirstCommentTimesInHours.Add(hours);
                    }
                }

                issuesList.AllIssueClosingTimesInHours = string.Join(",", allClosingTimesInHours);
                if (allClosingTimesInHours.Any())
                {
                    issuesList.IssueAverageClosingTimeInHours = allClosingTimesInHours.Average();
                    issuesList.IssueMedianClosingTimeInHours  = allClosingTimesInHours.Median();
                }

                issuesList.AllIssueFirstCommentTimesInHours = string.Join(",", allFirstCommentTimesInHours);

                if (allFirstCommentTimesInHours.Any())
                {
                    issuesList.IssueAverageFirstCommentTimesInHours = allFirstCommentTimesInHours.Average();
                    issuesList.IssueMedianFirstCommentTimesInHours  = allFirstCommentTimesInHours.Median();
                }

                groupedIssues.Add(issuesList);
            }

            //foreach (var issuesInPeriod in issues)
            //{
            //    foreach (var issue in issuesInPeriod.Value)
            //    {
            //        if(issue.CreateDateTime >= fromDate && issue.CreateDateTime <= toDate)
            //        {
            //            var year = issuesInPeriod.Key.Year;
            //            var month = issuesInPeriod.Key.Month;
            //            if(issue.ClosedDateTime != null && issue.ClosedDateTime > new DateTime(year, month, DateTime.DaysInMonth(year, month))
            //               groupedIssues.Where(x => x.MonthYear == )
            //        }
            //    }
            //}

            return(groupedIssues.OrderBy(x => x.MonthYear).ToList());
        }
Пример #8
0
        private Task<HttpResponseMessage> ProcessRules(HttpRequestMessage request, CancellationToken cancellationToken, IEnumerable<Rule> rules)
        {
            return base.SendAsync(request, cancellationToken)
                    .ContinueWith(task =>
                    {
                        var response = task.Result;

                        try
                        {
                            //Check whether there are rules for the current content
                            var data = response.Content;
                            var content = ((ObjectContent)(data)).Value as ContentItemDisplay;
                            rules = rules.Where(r =>
                                r.Enabled == true
                                && (string.IsNullOrWhiteSpace(r.ContentTypes) || r.ContentTypes.ToDelimitedList().InvariantContains(content.ContentTypeAlias))
                                && (string.IsNullOrWhiteSpace(r.ContentIds) || r.ContentIds.ToDelimitedList().InvariantContains(content.Id.ToString()))
                                );

                            if (rules.Count() < 1)
                            {
                                return response;
                            }

                            List<string> hideProperties = new List<string>();
                            List<string> hideTabs = new List<string>();
                            List<string> hideButtons = new List<string>();
                            List<string> hidePanels = new List<string>();
                            List<string> hideLabels = new List<string>();
                            List<string> runScripts = new List<string>();

                            // Get properties to hide
                            foreach (var propertyRule in rules.Where(r =>
                                r.Type.InvariantEquals(RuleType.HideProperties.ToString())
                                && !string.IsNullOrWhiteSpace(r.Names)
                                ))
                            {
                                // Remove all properties that don't exist for the current ContentType (A rule can be very generic and include properties that don't belong to the current ContentType)
                                IEnumerable<string> currentContentTypeProperties = content.Properties.Select(p => p.Alias);
                                hideProperties
                                    .AddRangeUnique(propertyRule.Names.ToDelimitedList().ToList()
                                        .Where(n => currentContentTypeProperties.InvariantContains(n))
                                    );
                            }

                            // Get tabs to hide
                            foreach (var tabRule in rules.Where(r =>
                                r.Type.InvariantEquals(RuleType.HideTabs.ToString())
                                && !string.IsNullOrWhiteSpace(r.Names)
                                ))
                            {
                                // Remove all tabs that don't exist for the current ContentType (A rule can be very generic and include tabs that don't belong to the current ContentType)
                                IEnumerable<string> currentContentTypeTabs = content.Tabs.Select(t => t.Label);
                                hideTabs
                                    .AddRangeUnique(tabRule.Names.ToDelimitedList().ToList()
                                        .Where(n => currentContentTypeTabs.InvariantContains(n))
                                    );
                            }

                            // Get buttons to hide
                            foreach (var buttonRule in rules.Where(r =>
                                r.Type.InvariantEquals(RuleType.HideButtons.ToString())
                                && !string.IsNullOrWhiteSpace(r.Names)
                                ))
                            {
                                hideButtons.AddRangeUnique(buttonRule.Names.ToDelimitedList().ToList());
                            }

                            // Get panels to hide
                            foreach (var panelRule in rules.Where(r =>
                                r.Type.InvariantEquals(RuleType.HidePanels.ToString())
                                && !string.IsNullOrWhiteSpace(r.Names)
                                ))
                            {
                                hidePanels.AddRangeUnique(panelRule.Names.ToDelimitedList().ToList());
                            }

                            // Get labels to hide
                            foreach (var labelRule in rules.Where(r =>
                                r.Type.InvariantEquals(RuleType.HideLabels.ToString())
                                && !string.IsNullOrWhiteSpace(r.Names)
                                ))
                            {
                                // Remove all labels that don't exist for the current ContentType (A rule can be very generic and include labels that don't belong to the current ContentType)
                                IEnumerable<string> currentContentTypeProperties = content.Properties.Select(p => p.Alias);
                                hideLabels
                                    .AddRangeUnique(labelRule.Names.ToDelimitedList().ToList()
                                        .Where(n => currentContentTypeProperties.InvariantContains(n))
                                    );
                            }

                            // Get scripts to run
                            foreach (var scriptRule in rules.Where(r =>
                                r.Type.InvariantEquals(RuleType.RunScripts.ToString())
                                && !string.IsNullOrWhiteSpace(r.Names)
                                ))
                            {
                                runScripts.AddRangeUnique(scriptRule.Names.ToDelimitedList().ToList());
                            }


                            // Get the first property of the first visible tab in order to add to its config everything that should be run only once (hide tabs, hide buttons, hide panels)
                            var firstProperty = content.Tabs.FirstOrDefault(t => t.IsActive == true).Properties.FirstOrDefault();

                            // Tabs
                            if (hideTabs.Count() > 0)
                            {
                                firstProperty.Config.Add("hidetabs", string.Join(",", hideTabs.Select(x => x)));
                            }

                            // Properties
                            content.Properties.Where(p => hideProperties.InvariantContains(p.Alias)).ForEach(p =>
                            {
                                p.Config.Add("hide", true);
                            });

                            // Buttons
                            if (hideButtons.Count() > 0)
                            {
                                firstProperty.Config.Add("hidebuttons", string.Join(",", hideButtons.Select(x => x)));
                            }

                            // Panels
                            if (hidePanels.Count() > 0)
                            {
                                firstProperty.Config.Add("hidepanels", string.Join(",", hidePanels.Select(x => x)));
                            }

                            // Labels
                            content.Properties.Where(p => hideLabels.InvariantContains(p.Alias)).ForEach(p =>
                            {
                                p.HideLabel = true;
                            });

                            // Scripts
                            if (runScripts.Count() > 0)
                            {
                                firstProperty.Config.Add("runscripts", string.Join(",", runScripts.Select(x => x)));
                            }

                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error(typeof(RulesHandler), "Error processing rules.", ex);
                        }

                        return response;
                    });
        }
        /// <summary>
        /// Convert the source nodeId into a IEnumerable of IPublishedContent (or DynamicPublishedContent)
        /// </summary>
        /// <param name="propertyType">
        /// The published property type.
        /// </param>
        /// <param name="source">
        /// The value of the property
        /// </param>
        /// <param name="preview">
        /// The preview.
        /// </param>
        /// <returns>
        /// The <see cref="object"/>.
        /// </returns>
        public override object ConvertSourceToObject(PublishedPropertyType propertyType, object source, bool preview)
        {
            if (source == null)
            {
                return(null);
            }

            //TODO: Inject an UmbracoHelper and create a GetUmbracoHelper method based on either injected or singleton
            if (UmbracoContext.Current == null)
            {
                return(source);
            }

            var umbHelper = new UmbracoHelper(UmbracoContext.Current);

            if (propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.MultiNodeTreePickerAlias))
            {
                var nodeIds = (int[])source;

                if ((propertyType.PropertyTypeAlias != null && PropertiesToExclude.InvariantContains(propertyType.PropertyTypeAlias)) == false)
                {
                    var multiNodeTreePicker = new List <IPublishedContent>();

                    var objectType = UmbracoObjectTypes.Unknown;

                    foreach (var nodeId in nodeIds)
                    {
                        var multiNodeTreePickerItem =
                            GetPublishedContent(nodeId, ref objectType, UmbracoObjectTypes.Document, umbHelper.TypedContent)
                            ?? GetPublishedContent(nodeId, ref objectType, UmbracoObjectTypes.Media, umbHelper.TypedMedia)
                            ?? GetPublishedContent(nodeId, ref objectType, UmbracoObjectTypes.Member, umbHelper.TypedMember);

                        if (multiNodeTreePickerItem != null)
                        {
                            multiNodeTreePicker.Add(multiNodeTreePickerItem);
                        }
                    }

                    return(multiNodeTreePicker);
                }

                // return the first nodeId as this is one of the excluded properties that expects a single id
                return(nodeIds.FirstOrDefault());
            }

            if (propertyType.PropertyEditorAlias.Equals(Constants.PropertyEditors.MultiNodeTreePicker2Alias))
            {
                var udis = (Udi[])source;

                if ((propertyType.PropertyTypeAlias != null && PropertiesToExclude.InvariantContains(propertyType.PropertyTypeAlias)) == false)
                {
                    var multiNodeTreePicker = new List <IPublishedContent>();

                    var objectType = UmbracoObjectTypes.Unknown;
                    IPublishedContent multiNodeTreePickerItem = null;

                    foreach (var udi in udis)
                    {
                        switch (udi.EntityType)
                        {
                        case Constants.UdiEntityType.Document:
                            multiNodeTreePickerItem = GetPublishedContent(udi, ref objectType, UmbracoObjectTypes.Document, umbHelper.TypedContent);
                            break;

                        case Constants.UdiEntityType.Media:
                            multiNodeTreePickerItem = GetPublishedContent(udi, ref objectType, UmbracoObjectTypes.Media, umbHelper.TypedMedia);
                            break;

                        case Constants.UdiEntityType.Member:
                            multiNodeTreePickerItem = GetPublishedContent(udi, ref objectType, UmbracoObjectTypes.Member, umbHelper.TypedMember);
                            break;
                        }

                        if (multiNodeTreePickerItem != null)
                        {
                            multiNodeTreePicker.Add(multiNodeTreePickerItem);
                        }
                    }

                    return(multiNodeTreePicker);
                }

                // return the first nodeId as this is one of the excluded properties that expects a single id
                return(udis.FirstOrDefault());
            }
            return(source);
        }
Пример #10
0
        private Task <HttpResponseMessage> ProcessRules(HttpRequestMessage request, CancellationToken cancellationToken, IEnumerable <Rule> rules)
        {
            return(base.SendAsync(request, cancellationToken)
                   .ContinueWith(task =>
            {
                var response = task.Result;

                try
                {
                    //Check whether there are rules for the current content
                    var data = response.Content;
                    var content = ((ObjectContent)(data)).Value as ContentItemDisplay;
                    rules = rules.Where(r =>
                                        r.Enabled == true &&
                                        (string.IsNullOrWhiteSpace(r.ContentTypes) || r.ContentTypes.ToDelimitedList().InvariantContains(content.ContentTypeAlias)) &&
                                        (string.IsNullOrWhiteSpace(r.ContentIds) || r.ContentIds.ToDelimitedList().InvariantContains(content.Id.ToString()))
                                        );

                    if (rules.Count() < 1)
                    {
                        return response;
                    }

                    List <string> hideProperties = new List <string>();
                    List <string> disableProperties = new List <string>();
                    List <string> hideTabs = new List <string>();
                    List <string> hideButtons = new List <string>();
                    List <string> hidePanels = new List <string>();
                    List <string> hideLabels = new List <string>();
                    List <string> runScripts = new List <string>();

                    // Get properties to hide
                    foreach (var hidePropertyRule in rules.Where(r =>
                                                                 r.Type.InvariantEquals(RuleType.HideProperties.ToString()) &&
                                                                 !string.IsNullOrWhiteSpace(r.Names)
                                                                 ))
                    {
                        // Remove all properties that don't exist for the current ContentType (A rule can be very generic and include properties that don't belong to the current ContentType)
                        IEnumerable <string> currentContentTypeProperties = content.Properties.Select(p => p.Alias);
                        hideProperties
                        .AddRangeUnique(hidePropertyRule.Names.ToDelimitedList().ToList()
                                        .Where(n => currentContentTypeProperties.InvariantContains(n))
                                        );
                    }

                    // Get properties to disable
                    foreach (var disablePropertyRule in rules.Where(r =>
                                                                    r.Type.InvariantEquals(RuleType.DisableProperties.ToString()) &&
                                                                    !string.IsNullOrWhiteSpace(r.Names)
                                                                    ))
                    {
                        // Remove all properties that don't exist for the current ContentType (A rule can be very generic and include properties that don't belong to the current ContentType)
                        IEnumerable <string> currentContentTypeProperties = content.Properties.Select(p => p.Alias);
                        disableProperties
                        .AddRangeUnique(disablePropertyRule.Names.ToDelimitedList().ToList()
                                        .Where(n => currentContentTypeProperties.InvariantContains(n))
                                        );
                    }

                    // Get tabs to hide
                    foreach (var tabRule in rules.Where(r =>
                                                        r.Type.InvariantEquals(RuleType.HideTabs.ToString()) &&
                                                        !string.IsNullOrWhiteSpace(r.Names)
                                                        ))
                    {
                        // Remove all tabs that don't exist for the current ContentType (A rule can be very generic and include tabs that don't belong to the current ContentType)
                        IEnumerable <string> currentContentTypeTabs = content.Tabs.Select(t => t.Label);
                        hideTabs
                        .AddRangeUnique(tabRule.Names.ToDelimitedList().ToList()
                                        .Where(n => currentContentTypeTabs.InvariantContains(n))
                                        );
                    }

                    // Get buttons to hide
                    foreach (var buttonRule in rules.Where(r =>
                                                           r.Type.InvariantEquals(RuleType.HideButtons.ToString()) &&
                                                           !string.IsNullOrWhiteSpace(r.Names)
                                                           ))
                    {
                        hideButtons.AddRangeUnique(buttonRule.Names.ToDelimitedList().ToList());
                    }

                    // Get panels to hide
                    foreach (var panelRule in rules.Where(r =>
                                                          r.Type.InvariantEquals(RuleType.HidePanels.ToString()) &&
                                                          !string.IsNullOrWhiteSpace(r.Names)
                                                          ))
                    {
                        hidePanels.AddRangeUnique(panelRule.Names.ToDelimitedList().ToList());
                    }

                    // Get labels to hide
                    foreach (var labelRule in rules.Where(r =>
                                                          r.Type.InvariantEquals(RuleType.HideLabels.ToString()) &&
                                                          !string.IsNullOrWhiteSpace(r.Names)
                                                          ))
                    {
                        // Remove all labels that don't exist for the current ContentType (A rule can be very generic and include labels that don't belong to the current ContentType)
                        IEnumerable <string> currentContentTypeProperties = content.Properties.Select(p => p.Alias);
                        hideLabels
                        .AddRangeUnique(labelRule.Names.ToDelimitedList().ToList()
                                        .Where(n => currentContentTypeProperties.InvariantContains(n))
                                        );
                    }

                    // Get scripts to run
                    foreach (var scriptRule in rules.Where(r =>
                                                           r.Type.InvariantEquals(RuleType.RunScripts.ToString()) &&
                                                           !string.IsNullOrWhiteSpace(r.Names)
                                                           ))
                    {
                        runScripts.AddRangeUnique(scriptRule.Names.ToDelimitedList().ToList());
                    }


                    // Get the first property of the first visible tab in order to add to its config everything that should be run only once (hide tabs, hide buttons, hide panels)
                    var firstProperty = content.Tabs.FirstOrDefault(t => t.IsActive == true).Properties.FirstOrDefault();

                    // Tabs
                    if (hideTabs.Count() > 0)
                    {
                        firstProperty.Config.Add("hidetabs", string.Join(",", hideTabs.Select(x => x)));
                    }

                    // Hide Properties
                    content.Properties.Where(p => hideProperties.InvariantContains(p.Alias)).ForEach(p =>
                    {
                        p.Config.Add("hideproperties", true);
                    });

                    // Disable Properties
                    content.Properties.Where(p => disableProperties.InvariantContains(p.Alias)).ForEach(p =>
                    {
                        p.Config.Add("disableproperties", true);
                    });

                    // Buttons
                    if (hideButtons.Count() > 0)
                    {
                        firstProperty.Config.Add("hidebuttons", string.Join(",", hideButtons.Select(x => x)));
                    }

                    // Panels
                    if (hidePanels.Count() > 0)
                    {
                        firstProperty.Config.Add("hidepanels", string.Join(",", hidePanels.Select(x => x)));
                    }

                    // Labels
                    content.Properties.Where(p => hideLabels.InvariantContains(p.Alias)).ForEach(p =>
                    {
                        p.HideLabel = true;
                    });

                    // Scripts
                    if (runScripts.Count() > 0)
                    {
                        firstProperty.Config.Add("runscripts", string.Join(",", runScripts.Select(x => x)));
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(typeof(RulesHandler), "Error processing rules.", ex);
                }

                return response;
            }));
        }
        public override object?ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel cacheLevel, object?source, bool preview)
        {
            if (source == null)
            {
                return(null);
            }

            // TODO: Inject an UmbracoHelper and create a GetUmbracoHelper method based on either injected or singleton
            if (_umbracoContextAccessor.TryGetUmbracoContext(out _))
            {
                if (propertyType.EditorAlias.Equals(Constants.PropertyEditors.Aliases.MultiNodeTreePicker))
                {
                    var udis = (Udi[])source;
                    var isSingleNodePicker = IsSingleNodePicker(propertyType);

                    if ((propertyType.Alias != null && PropertiesToExclude.InvariantContains(propertyType.Alias)) == false)
                    {
                        var multiNodeTreePicker = new List <IPublishedContent>();

                        var objectType        = UmbracoObjectTypes.Unknown;
                        var publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();
                        foreach (var udi in udis)
                        {
                            var guidUdi = udi as GuidUdi;
                            if (guidUdi is null)
                            {
                                continue;
                            }

                            IPublishedContent?multiNodeTreePickerItem = null;
                            switch (udi.EntityType)
                            {
                            case Constants.UdiEntityType.Document:
                                multiNodeTreePickerItem = GetPublishedContent(udi, ref objectType, UmbracoObjectTypes.Document, id => publishedSnapshot.Content?.GetById(guidUdi.Guid));
                                break;

                            case Constants.UdiEntityType.Media:
                                multiNodeTreePickerItem = GetPublishedContent(udi, ref objectType, UmbracoObjectTypes.Media, id => publishedSnapshot.Media?.GetById(guidUdi.Guid));
                                break;

                            case Constants.UdiEntityType.Member:
                                multiNodeTreePickerItem = GetPublishedContent(udi, ref objectType, UmbracoObjectTypes.Member, id =>
                                {
                                    IMember?m = _memberService.GetByKey(guidUdi.Guid);
                                    if (m == null)
                                    {
                                        return(null);
                                    }
                                    IPublishedContent?member = publishedSnapshot?.Members?.Get(m);
                                    return(member);
                                });
                                break;
                            }

                            if (multiNodeTreePickerItem != null && multiNodeTreePickerItem.ContentType.ItemType != PublishedItemType.Element)
                            {
                                multiNodeTreePicker.Add(multiNodeTreePickerItem);
                                if (isSingleNodePicker)
                                {
                                    break;
                                }
                            }
                        }

                        if (isSingleNodePicker)
                        {
                            return(multiNodeTreePicker.FirstOrDefault());
                        }
                        return(multiNodeTreePicker);
                    }

                    // return the first nodeId as this is one of the excluded properties that expects a single id
                    return(udis.FirstOrDefault());
                }
            }
            return(source);
        }
Пример #12
0
        private void ExamineEvents_GatheringNodeData(object sender, IndexingNodeDataEventArgs e, UmbracoHelper umbracoHelper)
        {
            try
            {
                // Get the properties which type is "uDynamic.DropdownListSql" or "uDynamic.CheckboxListSql"
                var contentType = ApplicationContext.Current.Services.ContentTypeService.GetAllContentTypes().FirstOrDefault(ct => ct.Alias == e.Node.ExamineNodeTypeAlias());
                if (contentType == null)
                {
                    return;
                }
                var properties = contentType.PropertyTypes
                                 .Where(pt => pt.PropertyEditorAlias == uDynamic.Constants.Datatype.PropertyEditorAlias.DropdownListSql || pt.PropertyEditorAlias == uDynamic.Constants.Datatype.PropertyEditorAlias.CheckboxListSql);
                if (properties.Count() < 1)
                {
                    return;
                }

                // Add new fields to the index
                object content = null;
                if (umbracoHelper != null)
                {
                    content = umbracoHelper.Content(e.NodeId);
                }
                if (content == null)
                {
                    content = ApplicationContext.Current.Services.ContentService.GetById(e.NodeId);
                }
                if (content == null)
                {
                    return;
                }
                foreach (var property in properties)
                {
                    // Get the prevalues
                    var prevalues = ApplicationContext.Current.Services.DataTypeService.GetPreValuesCollectionByDataTypeId(property.DataTypeDefinitionId);

                    // Check whether the prevalues contain all the required settings
                    if (prevalues.PreValuesAsDictionary.ContainsKey("sqlCommand") && prevalues.PreValuesAsDictionary["sqlCommand"].Value != null &&
                        prevalues.PreValuesAsDictionary.ContainsKey("dbKeyColumnName") &&
                        prevalues.PreValuesAsDictionary.ContainsKey("dbTextColumnName") &&
                        prevalues.PreValuesAsDictionary.ContainsKey("dbTabsColumnName") &&
                        prevalues.PreValuesAsDictionary.ContainsKey("dbPropertiesColumnName") &&
                        prevalues.PreValuesAsDictionary.ContainsKey("cacheDuration") &&
                        prevalues.PreValuesAsDictionary.ContainsKey("searchIndexAddFields") && prevalues.PreValuesAsDictionary["searchIndexAddFields"].Value != null
                        )
                    {
                        List <string> propertyValues = new List <string>();
                        // Check whether the property contains a value
                        string propertyRawValue = ContentHelper.GetPropertyValueAsString(content, property.Alias);
                        if (string.IsNullOrWhiteSpace(propertyRawValue))
                        {
                            continue;
                        }
                        // For backward compatibility with the previous versions of SQLDropdownList, we convert the single value into an array
                        if (!propertyRawValue.Contains("["))
                        {
                            propertyValues.Add(propertyRawValue);
                        }
                        else
                        {
                            propertyValues = JsonConvert.DeserializeObject <IEnumerable <string> >(propertyRawValue).ToList();
                        }
                        if (propertyValues.Count() < 1)
                        {
                            continue;
                        }

                        // Get the values from database (list items)
                        int cacheDuration = 0;
                        int.TryParse(prevalues.PreValuesAsDictionary["cacheDuration"].Value, out cacheDuration);
                        if (cacheDuration < 1)
                        {
                            // Force a 2 seconds cache in order to improve slightly the performance when indexing a lot of nodes
                            cacheDuration = 2;
                        }
                        IEnumerable <ListItem> listItems = uDynamic.Controllers.uDynamicController.GetSqlListItems(prevalues.PreValuesAsDictionary["sqlCommand"].Value, prevalues.PreValuesAsDictionary["dbKeyColumnName"].Value, prevalues.PreValuesAsDictionary["dbTextColumnName"].Value, prevalues.PreValuesAsDictionary["dbTabsColumnName"].Value, prevalues.PreValuesAsDictionary["dbPropertiesColumnName"].Value, cacheDuration);
                        // Lookup in the list the item that matches the id (key) saved in content node property (if it is a checkbox list then it could be more than one id)
                        // Each listItem is a list of columns in which the Column[0] contains the id (key)
                        listItems = listItems.Where(item => propertyValues.InvariantContains(item.columns[0].columnValue));
                        if (listItems.Count() < 1)
                        {
                            continue;
                        }

                        // Add fields to the index
                        var indexFields = prevalues.PreValuesAsDictionary["searchIndexAddFields"].Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var indexField in indexFields)
                        {
                            string indexFieldValue = string.Empty;
                            foreach (var listItem in listItems)
                            {
                                var value = listItem.columns.Values.FirstOrDefault(c => c.columnName == indexField.Trim());
                                if (value != null)
                                {
                                    indexFieldValue += value.columnValue + " ";
                                }
                            }
                            if (!string.IsNullOrWhiteSpace(indexFieldValue))
                            {
                                var indexFielName = property.Alias + indexField.Trim();
                                if (e.Fields.ContainsKey(indexFielName))
                                {
                                    e.Fields[indexFielName] = indexFieldValue.Trim();
                                }
                                else
                                {
                                    e.Fields.Add(indexFielName, indexFieldValue.Trim());
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error <UmbracoStartupEvent>("Error adding values to the search index for a property editor 'uDynamic.DropdownListSql' or 'uDynamic.CheckboxListSql'", ex);
            }
        }