public void SetupViewModel(FrontendContext frontendContext, IContent node, NodeViewModel viewModel)
        {
            if (node.ContentItem.ContentType != "WikipediaPage") return;

            viewModel.name = node.As<ITitleAspect>().Title;
            viewModel.data["url"] = node.As<WikipediaPagePart>().Url;
        }
        public static string GetContentName(this IContent content)
        {
            if (content.Has <TitlePart>())
            {
                return(content.As <TitlePart>().Title);
            }
            if (content.Has <WidgetPart>())
            {
                return(content.As <WidgetPart>().Title);
            }
            if (content.Has <UserPart>())
            {
                return(content.As <UserPart>().UserName);
            }
            if (content.Has <WidgetPart>())
            {
                return(content.As <WidgetPart>().Title);
            }
            if (content.Has <LayerPart>())
            {
                return(content.As <LayerPart>().Name);
            }

            return("Unknown");
        }
        public bool CanApply(IContent content, ICRMContentOwnershipService contentOwnershipService)
        {
            var folderPart     = content.As <FolderPart>();
            var attachToFolder = content.As <AttachToFolderPart>();

            return(folderPart != null || attachToFolder != null);
        }
        public TermPart NewTerm(TaxonomyPart taxonomy, IContent parent)
        {
            if (taxonomy == null)
            {
                throw new ArgumentNullException("taxonomy");
            }

            if (parent != null)
            {
                var parentAsTaxonomy = parent.As <TaxonomyPart>();
                if (parentAsTaxonomy != null && parentAsTaxonomy != taxonomy)
                {
                    throw new ArgumentException("The parent of a term can't be a different taxonomy", "parent");
                }

                var parentAsTerm = parent.As <TermPart>();
                if (parentAsTerm != null && parentAsTerm.TaxonomyId != taxonomy.Id)
                {
                    throw new ArgumentException("The parent of a term can't be a from a different taxonomy", "parent");
                }
            }

            var term = _contentManager.New <TermPart>(taxonomy.TermTypeName);

            term.Container  = parent ?? taxonomy;
            term.TaxonomyId = taxonomy.Id;
            ProcessPath(term);

            return(term);
        }
Example #5
0
        /// <summary>
        /// Combining watchers from this item and its containers
        /// </summary>
        private static IEnumerable <int> CumulatedWatcherIds(IContent content)
        {
            var watcherIds = new List <int>();

            for (int i = 0; i < 3; i++) // Only going three levels up
            {
                if (content == null)
                {
                    return(watcherIds);
                }

                if (content.Has <WatchablePart>())
                {
                    watcherIds.AddRange(content.As <WatchablePart>().WatcherIds);
                }

                var commonPart = content.As <ICommonPart>();
                if (commonPart == null)
                {
                    return(watcherIds);
                }
                content = commonPart.Container;
            }

            return(watcherIds);
        }
        private static bool HasOwnership(IUser user, IContent content)
        {
            if (user == null || content == null)
            {
                return(false);
            }

            if (content.Is <CustomerPart>())
            {
                var customer = content.As <CustomerPart>();
                return(customer != null && user.Id == customer.UserId);
            }
            else if (content.Is <CustomerAddressPart>())
            {
                var address = content.As <CustomerAddressPart>();
                return(address != null && address.Customer != null && user.Id == address.Customer.UserId);
            }
            else if (content.Is <CustomerOrderPart>())
            {
                var order = content.As <CustomerOrderPart>();
                return(order != null && order.Customer != null && user.Id == order.Customer.UserId);
            }

            return(false);
        }
 public void SetupViewModel(FrontendContext frontendContext, IContent node, Frontends.Engines.Jit.ViewModels.NodeViewModel viewModel)
 {
     if (node.ContentItem.ContentType == "AssociativyTagNode")
     {
         viewModel.name = node.As<IAssociativyNodeLabelAspect>().Label;
     }
     else viewModel.name = node.As<ITitleAspect>().Title;
 }
Example #8
0
 ActionResult RedirectToEdit(IContent item)
 {
     if (item == null || item.As <BlogPostPart>() == null)
     {
         return(HttpNotFound());
     }
     return(RedirectToAction("Edit", new { BlogId = item.As <BlogPostPart>().BlogPart.Id, PostId = item.ContentItem.Id }));
 }
Example #9
0
        public static ForumPart GetForum(IContent content) {
            var postPart = content.As<PostPart>();
            var threadPart = content.As<ThreadPart>();

            if (postPart == null) {
                return threadPart == null ? null : threadPart.ForumPart;
            }
            return postPart.ThreadPart.ForumPart;
        }
 public INotification ConvertBatchToNotification(IContent notificationBatch, IUser recipient)
 {
     return new Notification
     {
         Id = notificationBatch.ContentItem.Id,
         ContentItem = notificationBatch.ContentItem,
         TitleLazy = new Lazy<string>(() => _tokenizer.Replace(notificationBatch.As<TitlePart>().Title, new { User = recipient })),
         BodyLazy = new Lazy<string>(() => _tokenizer.Replace(notificationBatch.As<BodyPart>().Text, new { User = recipient }))
     };
 }
Example #11
0
 public INotification ConvertBatchToNotification(IContent notificationBatch, IUser recipient)
 {
     return(new Notification
     {
         Id = notificationBatch.ContentItem.Id,
         ContentItem = notificationBatch.ContentItem,
         TitleLazy = new Lazy <string>(() => _tokenizer.Replace(notificationBatch.As <TitlePart>().Title, new { User = recipient })),
         BodyLazy = new Lazy <string>(() => _tokenizer.Replace(notificationBatch.As <BodyPart>().Text, new { User = recipient }))
     });
 }
        /// <summary>
        /// Saves a value to the transient context of the content. This context will be preserved as long as the content object
        /// lives.
        /// </summary>
        /// <typeparam name="T">Type of the value to save.</typeparam>
        /// <param name="key">The key to identify the value. If there is a value already saved under this key it will be overwritten.</param>
        /// <param name="value">The value to store in the context.</param>
        public static void SetContext <T>(this IContent content, string key, T value)
        {
            var contextPart = content.As <TransientContextPart>();

            if (contextPart == null)
            {
                content.Weld <TransientContextPart>();
                contextPart = content.As <TransientContextPart>();
            }
            contextPart.Context[key] = value;
        }
Example #13
0
        public static ForumPart GetForum(IContent content)
        {
            var postPart   = content.As <PostPart>();
            var threadPart = content.As <ThreadPart>();

            if (postPart == null)
            {
                return(threadPart == null ? null : threadPart.ForumPart);
            }
            return(postPart.ThreadPart.ForumPart);
        }
        public void SetupViewModel(FrontendContext frontendContext, IContent node, NodeViewModel viewModel)
        {
            // .Has<> doesn't work here
            if (node.As<ITitleAspect>() != null) viewModel.name = node.As<ITitleAspect>().Title;

            if (node.As<IAliasAspect>() != null)
            {
                viewModel.data["url"] = new UrlHelper(_orchardServices.WorkContext.HttpContext.Request.RequestContext)
                                            .RouteUrl(_orchardServices.ContentManager.GetItemMetadata(node).DisplayRouteValues);
            }
        }
Example #15
0
 private ContentItem GetTheContentOwnerOrUser(IContent content)
 {
     if (content.As <CommonPart>() != null)
     {
         return(content.As <CommonPart>().Owner != null?content.As <CommonPart>().Owner.ContentItem : null);
     }
     else if (content.As <UserPart>() != null)
     {
         return(content.ContentItem);
     }
     return(null);
 }
Example #16
0
 private string GetTheValue(IContent content)
 {
     if (content.As <CommonPart>() != null)
     {
         return(content.As <CommonPart>().Owner != null?content.As <CommonPart>().Owner.Email : null);
     }
     else if (content.As <UserPart>() != null)
     {
         return(content.As <UserPart>().Email);
     }
     return(null);
 }
Example #17
0
/*
 *  Old version prior to versioning simplification:
 *      public IEnumerable<SocketsPart> RightItemsFromConnectors(IEnumerable<ConnectorPart> connectors, params string[] types)
 *      {
 *          var ids = connectors.Select(c => new { VersionId = c.RightContentVersionId, Id = c.RightContentVersionId.HasValue ? null : (int?)c.RightContentItemId }).ToList();
 *          var rightIds = ids.Where(c=>c.Id.HasValue).Select(c=>c.Id.Value);
 *          var rightVersionIds = ids.Where(c => c.VersionId.HasValue).Select(c => c.VersionId.Value);
 *          // TODO: Stuck between a rock and a hard place with QueryHints. WithQueryHintsFor actually generates a new content item in memory to figure out the parts to be expanded.
 *          // We possibly can't assume this will be optimal in all scenarios. On the other hand, we need to do something fairly complex to get the generic types from all the drivers.
 *          var qh = QueryHints.Empty; // QueryHintsForTypes(types);
 *          var content = Services.ContentManager.GetManyByVersionId<SocketsPart>(rightVersionIds, qh)
 *              .Concat(Services.ContentManager.GetMany<SocketsPart>(rightIds, VersionOptions.Latest, qh));
 *          return content;
 *      }
 *      public IEnumerable<SocketsPart> LeftItemsFromConnectors(IEnumerable<ConnectorPart> connectors, params string[] types)
 *      {
 *          var ids = connectors.Select(c => new { VersionId = c.LeftContentVersionId, Id = c.LeftContentVersionId.HasValue ? null : (int?)c.LeftContentItemId }).ToList();
 *          var leftIds = ids.Where(c => c.Id.HasValue).Select(c => c.Id.Value);
 *          var leftVersionIds = ids.Where(c => c.VersionId.HasValue).Select(c => c.VersionId.Value);
 *          // TODO: Stuck between a rock and a hard place with QueryHints. WithQueryHintsFor actually generates a new content item in memory to figure out the parts to be expanded.
 *          // We possibly can't assume this will be optimal in all scenarios. On the other hand, we need to do something fairly complex to get the generic types from all the drivers.
 *          var qh = QueryHintsForTypes(types);
 *          var content = Services.ContentManager.GetManyByVersionId<SocketsPart>(leftVersionIds, qh)
 *              .Concat(Services.ContentManager.GetMany<SocketsPart>(leftIds, VersionOptions.Latest, qh));
 *          return content;
 *      }
 */
        public IEnumerable <ConnectorDescriptor> AllowableConnectorTypes(IContent content)
        {
            // Enforce sockets part.
            // TODO: Throw an error - this shouldn't be called on anything without sockets
            var part = content.As <SocketsPart>();

            if (part == null)
            {
                return(Enumerable.Empty <ConnectorDescriptor>());
            }

            var ConnectorTypes = ConnectorTypeDefinitions();

            // TODO: PERF: This can't be optimal with a lot of content types floating around, need a lookup.
            return(ConnectorTypes.Select(d => {
                var s = d.Parts.First(p => p.PartDefinition.Name == typeof(ConnectorPart).Name).Settings.GetModel <ConnectorTypePartSettings>();
                var allowTypes = s == null ? Enumerable.Empty <string>() : s.ListAllowedContentLeft();
                return new {
                    Settings = s,
                    Definition = d,
                    Allowed = (s != null && (!allowTypes.Any() || allowTypes.Any(t => t == part.TypeDefinition.Name)))
                };
            }).Where(s => s.Allowed).Select(s => {
                var def = new ConnectorDescriptor(s.Definition, s.Settings);
                return def;
            }));
        }
        public OutputCacheSettings(IContent content)
        {
            var cachePart = content.As <OutputCachePart>();
            var settings  = cachePart.TypePartDefinition.Settings.GetModel <OutputCachePartSettings>();

            if (settings.AllowOverride && cachePart.EnableOverride)
            {
                EnableCache    = cachePart.EnableCache;
                CacheDuration  = cachePart.CacheDuration;
                CacheGraceTime = cachePart.CacheGraceTime;
                VaryByQueryStringParameters = String.IsNullOrWhiteSpace(cachePart.VaryByQueryStringParameters) ? new HashSet <string>() : new HashSet <string>(cachePart.VaryByQueryStringParameters.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray());
                VaryByRequestHeaders        = String.IsNullOrWhiteSpace(cachePart.VaryByRequestHeaders) ? new HashSet <string>() : new HashSet <string>(cachePart.VaryByRequestHeaders.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray());
                VaryByCulture             = cachePart.VaryByCulture;
                VaryByAuthenticationState = cachePart.VaryByAuthenticationState;
                VaryByUser = cachePart.VaryByUser;
                VaryByUrl  = cachePart.VaryByUrl;
            }
            else
            {
                EnableCache    = settings.EnableCache;
                CacheDuration  = settings.CacheDuration;
                CacheGraceTime = settings.CacheGraceTime;
                VaryByQueryStringParameters = String.IsNullOrWhiteSpace(settings.VaryByQueryStringParameters) ? new HashSet <string>() : new HashSet <string>(settings.VaryByQueryStringParameters.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray());
                VaryByRequestHeaders        = String.IsNullOrWhiteSpace(settings.VaryByRequestHeaders) ? new HashSet <string>() : new HashSet <string>(settings.VaryByRequestHeaders.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray());
                VaryByCulture             = settings.VaryByCulture;
                VaryByAuthenticationState = settings.VaryByAuthenticationState;
                VaryByUser = settings.VaryByUser;
                VaryByUrl  = settings.VaryByUrl;
            }
        }
        IEnumerable<LocalizationPart> ILocalizationService.GetLocalizations(IContent content, VersionOptions versionOptions) {
            if (content.ContentItem.Id == 0)
                return Enumerable.Empty<LocalizationPart>();

            var localized = content.As<LocalizationPart>();

            var query = versionOptions == null
                ? _contentManager.Query<LocalizationPart>(localized.ContentItem.ContentType)
                : _contentManager.Query<LocalizationPart>(versionOptions, localized.ContentItem.ContentType);

            int contentItemId = localized.ContentItem.Id;

            if (localized.HasTranslationGroup) {
                int masterContentItemId = localized.MasterContentItem.ContentItem.Id;

                query = query.Where<LocalizationPartRecord>(l =>
                    l.Id != contentItemId // Exclude the content
                    && (l.Id == masterContentItemId || l.MasterContentItemId == masterContentItemId));
            }
            else {
                query = query.Where<LocalizationPartRecord>(l =>
                    l.MasterContentItemId == contentItemId);
            }

            // Warning: May contain more than one localization of the same culture.
            return query.List().ToList();
        }
Example #20
0
        public bool CurrentUserCanEditContent(IContent item)
        {
            bool isCustomer = this.IsCurrentUserCustomer();
            bool isOperator = this.orchardServices.Authorizer.Authorize(Permissions.OperatorPermission);
            bool isAdmin    = this.orchardServices.Authorizer.Authorize(Permissions.AdvancedOperatorPermission);

            if (isAdmin)
            {
                return(true);
            }

            var contentPermissionPart = item.As <ContentItemPermissionPart>();

            if (contentPermissionPart == null)
            {
                return(true);
            }

            if (this.orchardServices.WorkContext.CurrentUser == null)
            {
                return(false);
            }

            foreach (var extension in this.contentOwnershipServiceExtensions)
            {
                if (extension.CanApply(item, this))
                {
                    if (!extension.HasAccessTo(item, this))
                    {
                        return(false);
                    }
                }
            }

            bool isAssignee =
                contentPermissionPart.Record.Items != null &&
                contentPermissionPart.Record.Items.Count > 0 &&
                contentPermissionPart.Record.Items.Any(c => c.AccessType == ContentItemPermissionAccessTypes.Assignee);

            if (!isAssignee && CRMContentOwnershipService.ContentTypesThatOperatorsHasAcceesToUnAssigneds.Any(c => c == item.ContentItem.ContentType))
            {
                if (isOperator || isAdmin)
                {
                    return(true);
                }
            }

            int userId = this.orchardServices.WorkContext.CurrentUser.Id;
            var allCurrentUserPermissions = this.GetUserPermissionRecordsForItem(item, userId);

            if (allCurrentUserPermissions.Count(c => c.AccessType == ContentItemPermissionAccessTypes.Assignee ||
                                                c.AccessType == ContentItemPermissionAccessTypes.SharedForEdit) > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        IEnumerable <LocalizationPart> ILocalizationService.GetLocalizations(IContent content, VersionOptions versionOptions)
        {
            if (content.ContentItem.Id == 0)
            {
                return(Enumerable.Empty <LocalizationPart>());
            }

            var localized = content.As <LocalizationPart>();

            var query = versionOptions == null
                ? _contentManager.Query <LocalizationPart>(localized.ContentItem.ContentType)
                : _contentManager.Query <LocalizationPart>(versionOptions, localized.ContentItem.ContentType);

            int contentItemId = localized.ContentItem.Id;

            if (localized.HasTranslationGroup)
            {
                int masterContentItemId = localized.MasterContentItem.ContentItem.Id;

                query = query.Where <LocalizationPartRecord>(l =>
                                                             l.Id != contentItemId && // Exclude the content
                                                             (l.Id == masterContentItemId || l.MasterContentItemId == masterContentItemId));
            }
            else
            {
                query = query.Where <LocalizationPartRecord>(l =>
                                                             l.MasterContentItemId == contentItemId);
            }

            // Warning: May contain more than one localization of the same culture.
            return(query.List().ToList());
        }
Example #22
0
        protected static TPart GetCurrentPart(EvaluateContext context)
        {
            IContent current     = context.Data["Content"] as IContent;
            TPart    currentPart = current == null ? default(TPart) : current.As <TPart>();

            return(currentPart);
        }
        LocalizationPart ILocalizationService.GetLocalizedContentItem(IContent content, string culture, VersionOptions versionOptions)
        {
            var cultureRecord = _cultureManager.GetCultureByName(culture);

            if (cultureRecord == null)
            {
                return(null);
            }

            var localized = content.As <LocalizationPart>();

            if (localized == null)
            {
                return(null);
            }

            // Warning: Returns only the first of same culture localizations.
            return(_contentManager
                   .Query <LocalizationPart>(versionOptions, content.ContentItem.ContentType)
                   .Where <LocalizationPartRecord>(l =>
                                                   (l.Id == content.ContentItem.Id || l.MasterContentItemId == content.ContentItem.Id) &&
                                                   l.CultureId == cultureRecord.Id)
                   .Slice(1)
                   .FirstOrDefault());
        }
Example #24
0
        public void GetMenu(IContent menu, NavigationBuilder builder)
        {
            if (menu.As <TitlePart>().Title == "Main Menu")
            {
                var menuParts = _contentManager
                                .Query <MenuPart, MenuPartRecord>()
                                .Where(x => x.MenuId == menu.Id)
                                .OrderBy(x => x.MenuPosition)
                                .List();

                var itemCount = menuParts.Last().MenuPosition + 1;

                if (_orchardServices.WorkContext.CurrentUser != null)
                {
                    builder.Add(T(_orchardServices.WorkContext.CurrentUser.UserName), itemCount.ToString(), item => item.Url("#").AddClass("menuUserName"));
                    builder.Add(T("Change Password"), itemCount.ToString() + ".1", item => item.Action("ChangePassword", "Account", new { area = "Orchard.Users" }));
                    builder.Add(T("Sign Out"), itemCount.ToString() + ".2", item => item.Action("LogOff", "Account", new { area = "Orchard.Users" }));
                    if (_orchardServices.Authorizer.Authorize(Orchard.Security.StandardPermissions.AccessAdminPanel))
                    {
                        builder.Add(T("Dashboard"), itemCount.ToString() + ".3", item => item.Action("Index", "Admin", new { area = "Dashboard" }));
                    }
                }
                else
                {
                    builder.Add(T("Sign In"), itemCount.ToString(), item => item.Action("LogOn", "Account", new { area = "Orchard.Users" }));
                }
            }
        }
Example #25
0
        /*
         * This Key generated used to be in the PolicyPartDriver. It is reproduced here because
         * its logic was replicating what is already done here. However it was adding some potentially
         * useful bits to the cachekey, so those are moved here.
         *
         * public void KeyGenerated(StringBuilder key) {
         *  var part = _currentContentAccessor.CurrentContentItem.As<PolicyPart>();
         *  if (part == null) return;
         *
         *  if (_policyServices.HasPendingPolicies(part.ContentItem) ?? false) {
         *      _additionalCacheKey = "policy-not-accepted;";
         *      _additionalCacheKey += "pendingitempolicies=" + String.Join("_", _policyServices.PendingPolicies(part.ContentItem).Select(s => s.Id)) + ";";
         *  }
         *  else {
         *      _additionalCacheKey = "policy-accepted;";
         *  }
         *
         *  key.Append(_additionalCacheKey);
         * }
         */

        private void SetPendingPolicies()
        {
            if (pendingPolicies != null)
            {
                return;
            }

            IContent content = CurrentContent();

            //_maxLevel = maxLevel;
            if (content != null)
            {
                // content would be null if rather than on a content item we are trying
                // to go to a controller aciton. Those should manage their own permissions
                // and caching so they would not have to be handled here
                var policy = content.As <Models.PolicyPart>();
                if (policy != null && (_policyServices.HasPendingPolicies(content.ContentItem) ?? false))   // Se l'oggetto ha delle pending policies allora devo scrivere la lista delle pending policies
                {
                    pendingPolicies = _policyServices.PendingPolicies(content.ContentItem);
                }
                else
                {
                    pendingPolicies = new List <IContent>();
                }
            }
        }
        /// <summary>
        /// Called by OutpuCache after the default cache key has been defined
        /// </summary>
        /// <param name="key">default cache key such as defined in Orchard.OutpuCache</param>
        /// <returns>The new cache key</returns>
        public void KeyGenerated(StringBuilder key)
        {
            var values = _request.RequestContext.RouteData.Values;

            if (values.ContainsKey("area") && values.ContainsKey("controller") && values.ContainsKey("action"))
            {
                if (values["area"].ToString().ToLowerInvariant().Equals("laser.orchard.webservices") &&
                    values["controller"].ToString().ToLowerInvariant().Equals("json") &&
                    values["action"].ToString().ToLowerInvariant().Equals("getbyalias"))
                {
                    IContent item = GetContentByAlias(_request.QueryString["displayalias"]);
                    if (item != null)
                    {
                        var policy = item.As <Policy.Models.PolicyPart>();
                        if (policy != null && (_policyServices.HasPendingPolicies(item.ContentItem) ?? false))
                        {
                            key.Append("policy-not-accepted;");
                        }
                        else if (policy != null && !(_policyServices.HasPendingPolicies(item.ContentItem) ?? false))
                        {
                            key.Append("policy-accepted;");
                        }
                    }
                }
            }
        }
        public bool ValidateAttributes(IContent product, IDictionary <int, ProductAttributeValueExtended> attributeIdsToValues)
        {
            var attributesPart = product.As <ProductAttributesPart>();

            //if (attributeIdsToValues.Count == 1 &&
            //    attributeIdsToValues[0].)
            // If the part isn't there, there must be no attributes
            if (attributesPart == null)
            {
                return(attributeIdsToValues == null || !attributeIdsToValues.Any());
            }
            // If the part is there, it must have as many attributes as were passed in
            if (attributesPart.AttributeIds.Count() != attributeIdsToValues.Count)
            {
                //Attributes may have been deleted
                attributesPart.AttributeIds = _attributeService.GetAttributes(attributesPart.AttributeIds).Select(pap => pap.Id);
                if (attributesPart.AttributeIds.Count() != attributeIdsToValues.Count)
                {
                    return(false);
                }
            }
            // The same attributes must be present
            if (!attributesPart.AttributeIds.All(attributeIdsToValues.ContainsKey))
            {
                return(false);
            }
            // Get the actual attributes in order to verify the values
            var attributes = _attributeService.GetAttributes(attributeIdsToValues.Keys);

            // The values that got passed in must exist
            return(attributes.All(attribute => attribute.AttributeValues.Any(v => v.Text == attributeIdsToValues[attribute.Id].Value)));
        }
Example #28
0
        public IEnumerable <IUser> GetCustomersWhoHaveAccessToThisContent(IContent content)
        {
            if (content == null)
            {
                return(null);
            }

            var contentPermissionPart = content.As <ContentItemPermissionPart>();

            if (contentPermissionPart == null)
            {
                return(new List <IUser>());
            }

            var items = contentPermissionPart.Record.Items;

            if (items == null || items.Count == 0)
            {
                return(new List <IUser>());
            }

            var userIds = items.Where(c => c.User != null).Select(c => c.User.Id).ToArray();

            var roles = this.rolesPermissionsRepository.Table.Where(c =>
                                                                    c.Permission.Name == Permissions.CustomerPermission.Name &&
                                                                    c.Permission.FeatureName == "Orchard.CRM.Core").ToList();

            var customerRoles = roles.ConvertAll(c => c.Role.Id).ToArray();
            var customerUsers = this.userRolesRepository.Table.Where(c => customerRoles.Contains(c.Role.Id) && userIds.Contains(c.UserId)).Select(c => c.UserId).ToList();

            return(this.orchardServices.ContentManager.GetMany <IUser>(customerUsers, VersionOptions.Published, new QueryHints()));
        }
Example #29
0
        public void GetMenu(IContent menu, NavigationBuilder builder)
        {
            if (menu.As <TitlePart>().Title == "Main Menu")
            {
                var maxPosition = _contentManager
                                  .Query <MenuPart, MenuPartRecord>()
                                  .Where(x => x.MenuId == menu.Id)
                                  .List()
                                  .Select(x => Convert.ToInt32(decimal.Parse(x.MenuPosition)))
                                  .Max();

                var itemCount = maxPosition + 1;

                if (_orchardServices.WorkContext.CurrentUser != null)
                {
                    builder.Add(T(_orchardServices.WorkContext.CurrentUser.UserName), itemCount.ToString(), item => item.Url("#").AddClass("menuUserName"));
                    builder.Add(T("Change Password"), itemCount.ToString() + ".1", item => item.Action("ChangePassword", "Account", new { area = "Orchard.Users" }));
                    builder.Add(T("Sign Out"), itemCount.ToString() + ".2", item => item.Action("LogOff", "Account", new { area = "Orchard.Users", ReturnUrl = _orchardServices.WorkContext.HttpContext.Request.RawUrl }));
                    if (_orchardServices.Authorizer.Authorize(Orchard.Security.StandardPermissions.AccessAdminPanel))
                    {
                        builder.Add(T("Dashboard"), itemCount.ToString() + ".3", item => item.Action("Index", "Admin", new { area = "Dashboard" }));
                    }
                }
                else
                {
                    builder.Add(T("Sign In"), itemCount.ToString(), item => item.Action("LogOn", "Account", new { area = "Orchard.Users", ReturnUrl = (_orchardServices.WorkContext.HttpContext.Request.QueryString["ReturnUrl"] ?? _orchardServices.WorkContext.HttpContext.Request.RawUrl) }));
                }
            }
        }
Example #30
0
        void ILocalizationService.SetContentCulture(IContent content, string culture) {
            var localized = content.As<LocalizationPart>();
            if (localized == null || localized.MasterContentItem == null)
                return;

            localized.Culture = _cultureManager.GetCultureByName(culture);
        }
        public static string GetTextDirection(this WorkContext workContext, IContent content) {
            var culture = workContext.CurrentSite.SiteCulture;
            if (content != null && content.Has<ILocalizableAspect>()) {
                culture = content.As<ILocalizableAspect>().Culture ?? culture;
            }

            return CultureInfo.GetCultureInfo(culture).TextInfo.IsRightToLeft ? "rtl" : "ltr"; ;
        }
Example #32
0
        public ContentItem Import(ImportSettings importSettings, object objectToImport, IContent parentContent)
        {
            Comments commentsToImport = (Comments)objectToImport;

            foreach (var commentToImport in commentsToImport.CommentList)
            {
                var author      = (commentToImport.UserName ?? string.Empty).Truncate(255);
                var dateCreated = commentToImport.DateCreated;

                var comment = _commentService.GetCommentsForCommentedContent(parentContent.Id)
                              .Where(o => o.Author == author)
                              .List()
                              .FirstOrDefault(o => o.Record.CommentDateUtc.HasValue && o.Record.CommentDateUtc.Value.Equals(dateCreated));

                if (comment != null)
                {
                    return(comment.ContentItem);
                }
                else
                {
                    comment = _orchardServices.ContentManager.New <CommentPart>("Comment");
                }

                comment.Author         = author;
                comment.CommentText    = (_dataCleaner.Clean(commentToImport.Content.Value, importSettings) ?? string.Empty).Truncate(10000);
                comment.Email          = (commentToImport.UserEmail ?? string.Empty).Truncate(255);
                comment.SiteName       = (commentToImport.UserURL ?? string.Empty).Truncate(255);
                comment.CommentedOn    = parentContent.Id;
                comment.CommentDateUtc = dateCreated;
                comment.UserName       = (commentToImport.UserName ?? "Anonymous").Truncate(255);

                if (parentContent.As <CommentsPart>().Record.CommentPartRecords == null)
                {
                    parentContent.As <CommentsPart>().Record.CommentPartRecords = new List <CommentPartRecord>();
                }

                _orchardServices.ContentManager.Create(comment);

                if (commentToImport.Approved)
                {
                    _commentService.ApproveComment(comment.Id);
                }
            }

            return(null);
        }
        string ILocalizationService.GetContentCulture(IContent content)
        {
            var localized = content.As <LocalizationPart>();

            return(localized != null && localized.Culture != null
                ? localized.Culture.Culture
                : _cultureManager.GetSiteCulture());
        }
Example #34
0
        private IHtmlString AuthorName(IContent content)
        {
            var author = content.As <ICommonPart>().Owner;

            // todo: encoding should be done at a higher level automatically and should be configurable via an options param
            // so it can be disabled
            return(author == null ? (IHtmlString)T("Anonymous") : new HtmlString(HttpUtility.HtmlEncode(author.UserName)));
        }
Example #35
0
        public int DeleteConnector(IContent left, IContent content, bool ignorePermissions = false, bool deleteInverseIfPossible = true, bool definitelyDelete = false)
        {
            var count     = 0;
            var connector = content.As <ConnectorPart>();

            if (connector == null)
            {
                return(count);
            }
            var connectorPart = connector.TypePartDefinition;

            if (connectorPart != null)
            {
                // Security check
                if (!ignorePermissions)
                {
                    if (!Services.Authorizer.Authorize(Permissions.DeleteContent, content, T("Could not delete connector")))
                    {
                        return(count);
                    }
                }

                if (connector.LeftContentItemId != left.Id)
                {
                    throw new OrchardException(T("Attempted to delete connector from wrong join"));
                }

                count++;

                // Versioning. If we delete the connector immediately from a draft then it'll also disappear from the published version.
                // Can't delete connectors from old versions.
                if (left.ContentItem.VersionRecord != null)
                {
                    if (left.IsPublished() || definitelyDelete)
                    {
                        // Do a proper remove
                        Services.ContentManager.Remove(content.ContentItem);

                        // TODO: Events to hook into CRUD operations on connectors (so we could delete other related things for example)
                        // TODO: Actually this as well as Create inverse should be done in content handler so we can hook into all normal
                        // content events...?
                        // Check for existing inverse Connector
                        // Note: We don't check permissions on inverse connector, if they can delete one way they have to be able to delete the other.
                        if (deleteInverseIfPossible && connector.InverseConnector != null)
                        {
                            Services.ContentManager.Remove(connector.InverseConnector.ContentItem);
                            count++;
                        }
                    }
                    else
                    {
                        // Flag to delete when published
                        connector.DeleteWhenLeftPublished = true;
                    }
                }
            }
            return(count);
        }
        //protected override void Activating(ActivatingContentContext context)
        //{
        //    context.Builder.Weld<VersionInfoSettings>();
        //}

        private void UpdateVersionInfo(IContent item, UpdateContentContext context)
        {
            var settings = item.As <VersionInfoSettings>();

            if (!String.IsNullOrWhiteSpace(settings.ModifiedBy))
            {
                settings.ModifiedBy = _utilities.GetUser();
            }
        }
Example #37
0
        public static void With <T>(this IContent content, Action <T> action) where T : IContent
        {
            T with = content.As <T>();

            if (with != null)
            {
                action.Invoke(with);
            }
        }
Example #38
0
        public bool HasDifferentCulture(IContent ci, LocalizationPart locPart)
        {
            var lP = ci.As <LocalizationPart>();

            return(lP != null &&                                      //has a LocalizationPart AND
                   (lP.Culture == null ||                             //culture undefined OR
                    (string.IsNullOrWhiteSpace(lP.Culture.Culture) || //culture undefined OR
                     (lP.Culture != locPart.Culture))));              //culture different than the product's
        }
Example #39
0
        private IList<LayoutPart> GetTemplates(IContent content = null) {
            var query = _layoutManager.GetTemplates();
            var layoutPart = content != null ? content.As<LayoutPart>() : null;

            if (layoutPart != null) {
                query = query.Where(x => x.Id != layoutPart.Id);
            }

            return query.ToList();
        }
        private static bool HasOwnership(IUser user, IContent content) {
            if (user == null || content == null)
                return false;

            var common = content.As<ICommonPart>();
            if (common == null || common.Owner == null)
                return false;

            return user.Id == common.Owner.Id;
        }
        private static bool HasOwnership(IUser user, IContent content)
        {
            if (user == null || content == null)
                return false;

            if (content.Is<CustomerPart>()) {
                var customer = content.As<CustomerPart>();
                return customer != null && user.Id == customer.UserId;
            }
            else if (content.Is<CustomerAddressPart>()) {
                var address = content.As<CustomerAddressPart>();
                return address != null && address.Customer != null && user.Id == address.Customer.UserId;
            }
            else if (content.Is<CustomerOrderPart>()) {
                var order = content.As<CustomerOrderPart>();
                return order != null && order.Customer != null && user.Id == order.Customer.UserId;
            }

            return false;
        }
        private void Invalidate(IContent content) {
            // remove any page tagged with this content item id
            _cacheService.RemoveByTag(content.ContentItem.Id.ToString(CultureInfo.InvariantCulture));

            // search the cache for containers too
            var commonPart = content.As<CommonPart>();
            if (commonPart != null) {
                if (commonPart.Container != null) {
                    _cacheService.RemoveByTag(commonPart.Container.Id.ToString(CultureInfo.InvariantCulture));
                }
            }
        }
Example #43
0
 public void BuildOrder(IShoppingCartService ShoppingCartService, IContent Order)
 {
     // Attach VAT infos to OrderDetails
     var orderPart = Order.As<OrderPart>();
     if (orderPart != null) {
         var vatParts = _contentManager.GetMany<VatPart>(orderPart.Details.Select(d => d.ContentId), VersionOptions.Published, QueryHints.Empty);
         foreach(var vatDetailPair in orderPart.Details.Join(vatParts, od => od.ContentId, vat => vat.Id, (od, vat) => new { Detail = od, Vat = vat})) {
             if (vatDetailPair.Vat.VatRate != null) {
                 vatDetailPair.Detail.SetProperty("VAT", new Tax(vatDetailPair.Vat.VatRate));
             }
         }
     }
 }
Example #44
0
        public void BuildOrder(IShoppingCartService ShoppingCartService, IContent Order)
        {
            var orderPart = Order.As<OrderPart>();
            if (orderPart != null) {
                var cartRecords = ShoppingCartService.ListItems();
                var products = ListProducts(cartRecords);
                foreach (var cartRecord in cartRecords.Where(cr => cr.ItemType == ProductPart.PartItemType)) {
                    var product = products.Where(p => p.Id == cartRecord.ItemId).FirstOrDefault();

                    if (product != null) {
                        orderPart.Details.Add(new OrderDetail(product, cartRecord.Quantity));
                    }
                }
            }
        }
Example #45
0
 public void OrderDetailUpdated(IContent order, OrderDetailRecord originalDetail, OrderDetailRecord updatedDetail)
 {
     if(originalDetail.ContentId == updatedDetail.ContentId) {
         var orderPart = order.As<OrderPart>();
         var stockPart = _contentManager.Get(updatedDetail.ContentId).As<StockPart>();
         if (stockPart != null && stockPart.EnableStockMgmt && orderPart != null) {
             if(orderPart.OriginalStatus != orderPart.OrderStatus) {
                 // OrderStatus changed
                 if (orderPart.OriginalStatus == OrderStatus.Canceled) {
                     if(orderPart.OrderStatus < OrderStatus.Completed) {
                         stockPart.InOrderQty += updatedDetail.Quantity;
                     }
                     else {
                         stockPart.InStockQty -= updatedDetail.Quantity;
                     }
                 }
                 else if (orderPart.OriginalStatus < OrderStatus.Completed) {
                     if (orderPart.OrderStatus == OrderStatus.Canceled) {
                         stockPart.InOrderQty -= originalDetail.Quantity;
                     }
                     else if (orderPart.OrderStatus == OrderStatus.Completed) {
                         stockPart.InOrderQty -= originalDetail.Quantity;
                         stockPart.InStockQty -= updatedDetail.Quantity;
                     }
                     else {
                         stockPart.InOrderQty += updatedDetail.Quantity - originalDetail.Quantity;
                     }
                 }
                 else {
                     stockPart.InStockQty += originalDetail.Quantity;
                     if (orderPart.OrderStatus != OrderStatus.Canceled) {
                         stockPart.InOrderQty += updatedDetail.Quantity;
                     }
                 }
             }
             else {
                 // OrderStatus unchanged
                 if (originalDetail.Quantity != updatedDetail.Quantity) {
                     stockPart.InOrderQty += updatedDetail.Quantity - originalDetail.Quantity;
                 }
             }
         }
     }
     else {
         OrderDetailDeleted(order, originalDetail);
         OrderDetailCreated(order, updatedDetail);
     }
 }
Example #46
0
 public void OrderDetailDeleted(IContent order, OrderDetailRecord deletedDetail)
 {
     var stockPart = _contentManager.Get(deletedDetail.ContentId).As<StockPart>();
     var orderPart = order.As<OrderPart>();
     if (stockPart != null && stockPart.EnableStockMgmt && orderPart != null) {
         if (orderPart.OrderStatus == OrderStatus.Canceled) {
             return;
         }
         else if (orderPart.OrderStatus < OrderStatus.Completed) {
             stockPart.InOrderQty -= deletedDetail.Quantity;
         }
         else {
             stockPart.InStockQty += deletedDetail.Quantity;
         }
     }
 }
Example #47
0
        IEnumerable<LocalizationPart> ILocalizationService.GetLocalizations(IContent content, VersionOptions versionOptions) {
            var localized = content.As<LocalizationPart>();

            if (localized.MasterContentItem != null)
                return _contentManager.Query(versionOptions, localized.ContentItem.ContentType)
                    .Where<LocalizationPartRecord>(l =>
                        l.Id != localized.ContentItem.Id
                        && (l.Id == localized.MasterContentItem.ContentItem.Id
                            || l.MasterContentItemId == localized.MasterContentItem.ContentItem.Id))
                    .List()
                    .Select(i => i.As<LocalizationPart>());

            return _contentManager.Query(versionOptions, localized.ContentItem.ContentType)
                .Where<LocalizationPartRecord>(l => l.MasterContentItemId == localized.ContentItem.Id)
                .List()
                .Select(i => i.As<LocalizationPart>());
        }
Example #48
0
 public SocketEventContext(IContent leftContent, ConnectorDescriptor connectorDefinition,SocketsModel socketsContext)
 {
     Left = leftContent.As<SocketsPart>().Endpoint;
     Connector = connectorDefinition;
     SocketFilters = new List<ISocketFilter>();
     SocketSorters= new List<ISocketFilter>();
     RootModel = socketsContext;
     RenderSocket = true;
     SocketMetadata = new SocketMetadata() {
         SocketName = connectorDefinition.Name,
         SocketTitle = Connector.Settings.SocketDisplayName
     };
     QueryFactory = new Lazy<SocketQuery>(() => {
         var query = Left.ContentPart.Sockets[Connector.Name];
         return query;
     });
 }
        public string ItemVirtualPath(IContent content, string tenantName)
        {
            var workContext = _wca.GetContext();
            string virtualPath = null;

            if (tenantName == _shellSettings.Name)
            {
                virtualPath = _urlHelper.ItemDisplayUrl(content);
            }
            else if (_shellSettings.Name == ShellSettings.DefaultName)
            {
                // from the default tenant
                virtualPath = _urlHelper.Action("DisplayOnDependent", "TenantContent", new { area = "MainBit.MultiTenancy", masterContentItemId = content.Id });
            }
            else
            {
                // from an dependent tenant
                var tenantContent = content.As<TenantContentPart>();
                if (tenantContent != null)
                {
                    if (tenantName == ShellSettings.DefaultName)
                    {
                        // to the default tenant
                        virtualPath = _urlHelper.Action("DisplayOnDefault", "TenantContent", new { area = "MainBit.MultiTenancy", id = tenantContent.MasterContentItemId });
                    }
                    else
                    {
                        // to an other dependent tenant
                        virtualPath = _urlHelper.Action("DisplayOnDependent", "TenantContent", new { area = "MainBit.MultiTenancy", masterContentItemId = tenantContent.MasterContentItemId });
                    }
                }
                else
                {
                    virtualPath = "";
                }
            }

            virtualPath = virtualPath.Substring(workContext.HttpContext.Request.ApplicationPath.Length).TrimStart('/');

            if (_urlPrefix != null)
                virtualPath = _urlPrefix.RemoveLeadingSegments(virtualPath);

            return virtualPath;
        }
        LocalizationPart ILocalizationService.GetLocalizedContentItem(IContent content, string culture, VersionOptions versionOptions) {
            var cultureRecord = _cultureManager.GetCultureByName(culture);

            if (cultureRecord == null)
                return null;

            var localized = content.As<LocalizationPart>();

            if (localized == null)
                return null;

            // Warning: Returns only the first of same culture localizations.
            return _contentManager
                .Query<LocalizationPart>(versionOptions, content.ContentItem.ContentType)
                .Where<LocalizationPartRecord>(l =>
                (l.Id == content.ContentItem.Id || l.MasterContentItemId == content.ContentItem.Id)
                && l.CultureId == cultureRecord.Id)
                .Slice(1)
                .FirstOrDefault();
        }
Example #51
0
        public void GetMenu(IContent menu, NavigationBuilder builder) {
            var workContext = _orchardServices.WorkContext;
            var bootstrapSettings = workContext.CurrentSite.As<BootstrapThemeSettingsPart>();

           
            if (menu.As<TitlePart>().Title == "Main Menu")
            {
                var menuParts = _contentManager.Query<MenuPart, MenuPartRecord>().Where(x => x.MenuId == menu.Id).List();
                var itemCount = menuParts.Select(x => GetFirstInteger(x.MenuPosition)).Max() + 1;

                //do we want to display admin menu?
                if (bootstrapSettings.ShowLogInLinksInMenu)
                {
                    if (_orchardServices.WorkContext.CurrentUser != null)
                    {

                        builder.Add(T(FirstWord(_orchardServices.WorkContext.CurrentUser.UserName, bootstrapSettings)), itemCount.ToString(), item => item.Url("#").AddClass("menuUserName"));
                        builder.Add(T("Change Password"), itemCount.ToString() + ".1", item => item.Action("ChangePassword", "Account", new { area = "Orchard.Users" }));
                        builder.Add(T("Sign Out"), itemCount.ToString() + ".2", item => item.Action("LogOff", "Account", new { area = "Orchard.Users", ReturnUrl = _orchardServices.WorkContext.HttpContext.Request.RawUrl }));
                        if (_orchardServices.Authorizer.Authorize(Orchard.Security.StandardPermissions.AccessAdminPanel))
                        {
                            builder.Add(T("Dashboard"), itemCount.ToString() + ".3", item => item.Action("Index", "Admin", new { area = "Dashboard" }));

                            // HACK: for CBCA, add a Help menu item to the menu
                            if (bootstrapSettings.Swatch == "cbca")
                            {
                                builder.Add(T("Help"), itemCount.ToString() + ".4", item => item.Url("Help"));
                            }
                        }
                    }

                    else if (bootstrapSettings.ShowLogInLinksInMenuWhenLoggedIn)
                    {
                        builder.Add(T("Sign In"), itemCount.ToString(), item => item.Action("LogOn", "Account", new { area = "Orchard.Users", ReturnUrl = (_orchardServices.WorkContext.HttpContext.Request.QueryString["ReturnUrl"] ?? _orchardServices.WorkContext.HttpContext.Request.RawUrl) }));
                    }

                }
            }
        }
Example #52
0
        public void GetMenu(IContent menu, NavigationBuilder builder) {
            if (menu.As<TitlePart>().Title == "Main Menu") {
                var maxPosition = _contentManager
                    .Query<MenuPart, MenuPartRecord>()
                    .Where(x => x.MenuId == menu.Id)
                    .List()
                    .Select(x => Convert.ToInt32(decimal.Parse(x.MenuPosition)))
                    .Max();

                var itemCount = maxPosition + 1;

                if (_orchardServices.WorkContext.CurrentUser != null) {
                    builder.Add(T(_orchardServices.WorkContext.CurrentUser.UserName), itemCount.ToString(), item => item.Url("#").AddClass("menuUserName"));
                    builder.Add(T("Change Password"), itemCount.ToString() + ".1", item => item.Action("ChangePassword", "Account", new { area = "Orchard.Users" }));
                    builder.Add(T("Sign Out"), itemCount.ToString() + ".2", item => item.Action("LogOff", "Account", new { area = "Orchard.Users", ReturnUrl = _orchardServices.WorkContext.HttpContext.Request.RawUrl }));
                    if (_orchardServices.Authorizer.Authorize(Orchard.Security.StandardPermissions.AccessAdminPanel)) {
                        builder.Add(T("Dashboard"), itemCount.ToString() + ".3", item => item.Action("Index", "Admin", new { area = "Dashboard" }));
                    }
                }
                else {
                    builder.Add(T("Sign In"), itemCount.ToString(), item => item.Action("LogOn", "Account", new { area = "Orchard.Users", ReturnUrl = (_orchardServices.WorkContext.HttpContext.Request.QueryString["ReturnUrl"] ?? _orchardServices.WorkContext.HttpContext.Request.RawUrl) }));
                }
            }
        }
        private string Body(IContent content) {
            if (content == null) {
                return String.Empty;
            }

            var bodyPart = content.As<BodyPart>();
            if (bodyPart == null) {
                return String.Empty;
            }

            return bodyPart.Text;
        }
 private object Date(IContent content) {
     return content != null ? content.As<ICommonPart>().CreatedUtc : null;
 }
        private IContent Container(IContent content) {
            var commonPart = content.As<ICommonPart>();
            if (commonPart == null) {
                return null;
            }

            return commonPart.Container;
        }
        private IHtmlString AuthorName(IContent content) {
            if (content == null) {
                return new HtmlString(String.Empty); // Null content isn't "Anonymous"
            }

            var commonPart = content.As<ICommonPart>();
            var author = commonPart != null ? commonPart.Owner : null;
            // todo: encoding should be done at a higher level automatically and should be configurable via an options param
            // so it can be disabled
            return author == null ? (IHtmlString)T("Anonymous") : new HtmlString(HttpUtility.HtmlEncode(author.UserName));
        }
 private CultureInfo GetContentCultureInfo(IContent content)
 {
     var localizationPart = content != null ? content.As<LocalizationPart>() : null;
     if (localizationPart == null || localizationPart.Culture == null || string.IsNullOrEmpty(localizationPart.Culture.Culture)) return new CultureInfo(_cultureManager.GetSiteCulture());
     return new CultureInfo(localizationPart.Culture.Culture);
 }
        private IEnumerable<IContent> FlattenOneLevel(IContent container)
        {
            var items = new List<IContent>();

            items.Add(container);

            var containedItems = container.ContentItem.ContentManager
                .Query()
                .Where<CommonPartRecord>(record => record.Container.Id == container.ContentItem.Id)
                .OrderBy<CommonPartRecord>(record => record.Id)
                .List<IContent>();

            // If the contained items are linked from the container, take the links' order into account. Also if links are present only linked items
            // will be processed.
            if (containedItems.Any())
            {
                var aliases = containedItems
                    .Where(content => content.As<IAliasAspect>() != null)
                    .Select(content => new
                    {
                        Content = content,
                        Path = content.As<IAliasAspect>().Path
                    })
                    .ToDictionary(alias => alias.Path);

                var siteUri = new Uri(_siteService.GetSiteSettings().BaseUrl);
                var doc = new HtmlDocument();
                Stream outputStream = _shapeOutputGenerator.GenerateOutput(container.ContentItem.ContentManager.BuildDisplay(container, "File-ContainerFlattening"));
                doc.Load(outputStream);

                var aliasAspect = container.As<IAliasAspect>();
                if (aliasAspect != null)
                {
                    var itemUri = new Uri(siteUri, aliasAspect.Path);

                    var links = doc.DocumentNode.SelectNodes("//a[@href]");
                    if (links != null) // See: https://htmlagilitypack.codeplex.com/workitem/29175
                    {
                        foreach (var link in links)
                        {
                            var href = link.GetAttributeValue("href", null);
                            if (href != null)
                            {
                                Uri uri;
                                if (UrlHelper.UrlIsInternal(itemUri, href, out uri))
                                {
                                    var alias = uri.LocalPath.TrimStart('/');
                                    if (aliases.ContainsKey(alias))
                                    {
                                        items.AddRange(FlattenOneLevel(aliases[alias].Content));
                                    }
                                }
                            }
                        }
                    }
                }

                if (items.Count == 1) // No contained item was linked
                {
                    foreach (var item in containedItems)
                    {
                        items.AddRange(FlattenOneLevel(item));
                    }
                }
            }

            return items;
        }
Example #59
0
 private static string CommentAuthor(IContent comment) {
     var commentPart = comment.As<CommentPart>();
     return String.IsNullOrWhiteSpace(commentPart.UserName) ? commentPart.Author : commentPart.UserName;
 }
        public TermPart NewTerm(TaxonomyPart taxonomy, IContent parent) {
            if (taxonomy == null) {
                throw new ArgumentNullException("taxonomy");
            }

            if (parent != null) {
                var parentAsTaxonomy = parent.As<TaxonomyPart>();
                if (parentAsTaxonomy != null && parentAsTaxonomy != taxonomy) {
                    throw new ArgumentException("The parent of a term can't be a different taxonomy", "parent");
                }

                var parentAsTerm = parent.As<TermPart>();
                if (parentAsTerm != null && parentAsTerm.TaxonomyId != taxonomy.Id) {
                    throw new ArgumentException("The parent of a term can't be a from a different taxonomy", "parent");
                }
            }

            var term = _contentManager.New<TermPart>(taxonomy.TermTypeName);
            term.Container = parent ?? taxonomy;
            term.TaxonomyId = taxonomy.Id;
            ProcessPath(term);

            return term;
        }