Esempio n. 1
0
        public void Test_Cycles()
        {
            var o = new TypeWithCycles();

            o.Self       = o;
            o.MyProperty = 5;
            o.Child      = new Sub1
            {
                Parent   = o,
                SubChild = new Sub1
                {
                    Parent   = o,
                    Prop1    = 7,
                    SubChild = new Sub1 {
                    }
                }
            };

            var c = ContentFactory.Default.CreateFrom(o);

            var arr = c.Visit().ToArray();

            Assert.IsTrue(arr.Any(p => p.Path.Equals(ContentPath.Parse("$.Child.SubChild.SubChild")) &&
                                  p.Value is ContentObject));

            Assert.IsTrue(arr.Any(p => p.Path.Equals(ContentPath.Parse("$.Child.SubChild.SubChild.Prop1")) &&
                                  p.Value is ContentNumber));

            Assert.IsTrue(arr.Any(p => p.Path.Equals(ContentPath.Parse("$.Child.SubChild.Prop1")) &&
                                  p.Value is ContentNumber));

            Assert.AreEqual(10, arr.Length);
        }
Esempio n. 2
0
        private IContentInfo GetContentOrNewRoot(ContentPath path)
        {
            try
            {
                return(GetContent(path));
            }
            catch (ContentNotFoundException)
            {
                if (path == ContentPath.Root)
                {
                    var content = (IContent)Activator.CreateInstance(_contentRepository.RootContentType);

                    ReflectionUtility
                    .GetGenericMethod(() => _contentRepository.AddContent <IContent>(null))
                    .MakeGenericMethod(_contentRepository.RootContentType)
                    .Invoke(_contentRepository, new object[] { content });

                    return(ContentInfo.Create(content, _contentRepository.RootContentType, null));
                }
                else
                {
                    throw;
                }
            }
        }
Esempio n. 3
0
        private IContentInfo <TContent> GetContentInfo <TContent>(int contentId, ContentPath path)
            where TContent : class, IContent
        {
            var content = _contentRepository.GetContentById <TContent>(contentId);

            return(new ContentInfo <TContent>(content, path));
        }
Esempio n. 4
0
        public void Test_Expressions()
        {
            var d = new Dictionary <string, object>
            {
                { "name", "John" }
            };

            var scope = new ContentObject(d, d, ContentFactory.Default);

            var e = new CreateObjectExpression(new List <CreateObjectExpression.Element>
            {
                new CreateObjectExpression.Attribute
                {
                    Name  = "name",
                    Value = new PathExpression(new ScopeRootExpression(), ContentPath.Parse("$.name"))
                },

                new CreateObjectExpression.Attribute
                {
                    Name  = "age",
                    Value = new ConstantExpression(new ContentNumber(45))
                }
            });

            var issue = e.TryEvaluate(scope, out IContentNode result);

            Assert.IsNull(issue);

            var jToken = result.ToJson();

            var poco = jToken.ToObject <R>();

            Assert.AreEqual("John", poco.name);
            Assert.AreEqual(45, poco.age);
        }
Esempio n. 5
0
        private ContentInfo CreateNewContent(ContentPath path, string container, string type)
        {
            var parentContentInfo = GetContent(path);

            var property = parentContentInfo.ContentType.GetProperty(container);

            if (property == null)
            {
                throw new HttpException(404, "Invalid container");
            }

            var collectionType = property.PropertyType.GetImplementationOf(typeof(ICollection <>));

            if (collectionType == null)
            {
                throw new HttpException(400, "Not a collection");
            }

            var collectionItemType = collectionType.GetGenericArguments().First();
            var contentType        = collectionItemType.Assembly
                                     .GetTypes()
                                     .Where(t => t.IsClass && !t.IsAbstract && collectionItemType.IsAssignableFrom(t))
                                     .Single(t => t.FullName == type);

            var content = (IContent)Activator.CreateInstance(contentType);

            // Add the new content to its parent collection.
            var collectionInstance = property.GetValue(parentContentInfo.Content, null);

            collectionType
            .GetMethod("Add")
            .Invoke(collectionInstance, new object[] { content });

            return(ContentInfo.Create(content, contentType, null));
        }
        private void OKBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (UseAlternateName.Checked && AlternateName.Text.Trim().Length == 0)
                {
                    MessageBox.Show(this, Strings.AlternateNameMissing, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    AlternateName.Focus();
                    return;
                }

                if (UseHeader.Checked && !System.IO.File.Exists(HeaderPath.Text))
                {
                    MessageBox.Show(this, Strings.HeaderFileMissing, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    HeaderPath.Focus();
                    return;
                }

                if (!System.IO.File.Exists(ContentPath.Text))
                {
                    MessageBox.Show(this, Strings.ContentFileMissing, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ContentPath.Focus();
                    return;
                }
            }
            catch (Exception ex)
            {
                string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                MessageBox.Show(this, string.Format(Strings.FilenameValidationError, msg), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.DialogResult = DialogResult.OK;
            this.Close();
        }
Esempio n. 7
0
        public void Test_Parser()
        {
            var left = new AndFilter(
                new EqualToFilter(
                    new PathExpression(new ScopeRootExpression(), ContentPath.Parse("$.Name")),
                    new ConstantExpression(new ContentText("Ahmad contains"))),
                new ContainsFilter(
                    new PathExpression(new ScopeRootExpression(), ContentPath.Parse("$.Friends")),
                    new ConstantExpression(new ContentText("Sameer"))));
            var issues = _parser.TryParse("$.Name EQUALS \"Ahmad contains\" AND $.Friends CONTAINS \"Sameer\"", out IContentExpression actual);

            Assert.AreEqual(left, actual);


            var right = new AndFilter(
                new EqualToFilter(
                    new PathExpression(new ScopeRootExpression(), ContentPath.Parse("$.Name")),
                    new ConstantExpression(new ContentText("Suzi 34"))),
                new ContainsFilter(
                    new PathExpression(new ScopeRootExpression(), ContentPath.Parse("$.Friends")),
                    new ConstantExpression(new ContentText("Sameer"))));

            issues = _parser.TryParse(
                "($.Name EQUALS \"Ahmad contains\" AND $.Friends CONTAINS \"Sameer\")" +
                " OR " +
                "($.Name EQUALS \"Suzi 34\" AND $.Friends CONTAINS \"Sameer\")",
                out actual);

            var combined = new OrFilter(left, right);

            Assert.AreEqual(combined, actual);
        }
        public ContentPath Create(ContentPath contentPath)
        {
            var path = _context.ContentPaths.Add(contentPath);

            _context.SaveChanges();
            return(path);
        }
        public ContentPath Delete(ContentPath contentPath)
        {
            var path = _context.ContentPaths.Remove(contentPath);

            _context.SaveChanges();
            return(path);
        }
Esempio n. 10
0
        public static IEnumerable <DocumentToken> GetTokens(DocumentSource source, object sourceData)
        {
            var visit      = ContentFactory.Default.CreateFrom(sourceData).Visit();
            var visitWhere = ContentFactory.Default.CreateFrom(sourceData).Visit().Where(p => p.Value is IContentPrimitive);

            var pairs = ContentFactory.Default.CreateFrom(sourceData).Visit()
                        .Where(p => p.Value is IContentPrimitive)
                        .Select(p => new ContentPathValue(
                                    ContentPath.Root
                                    .Append(p.Path
                                            .Select(n =>
                                                    n is ContentPath.ListIndex ? ContentPath.AnyIndex : n)), p.Value));
            ContentPath lastPath = null;
            var         offset   = 0;
            // filter pairs
            var filteredPairs = NullFilter(TokenFilter(TokenizePairs(pairs)))
                                // order by path
                                .OrderBy(p => p.Path.ToString());

            // build tokens from pairs
            foreach (var pair in filteredPairs)
            {
                // assign incremental offsets for similar paths
                offset = pair.Path.Equals(lastPath) ? offset + 1 : 0;
                var path = new DocumentSourcePath(pair.Path, offset);
                lastPath = pair.Path;
                yield return(new DocumentToken(source, sourceData, path, pair.Value, pair.Value));
            }
        }
Esempio n. 11
0
        public void InitialTest()
        {
            //var paths = new List<Path>()
            //{
            //    new Path()
            //    {
            //        id = 199,
            //        path = "$.Audit.CreatedOn",
            //    },
            //    new Path()
            //    {
            //        id = 150,
            //        path ="$.Name",
            //    }

            //    // ...etc.
            //};
            var paths = new Dictionary <string, int>
            {
                { "$.Audit.CreatedOn", 199 },
                { "$.Name", 150 },
                { "$.Id", 155 },
                // ...etc.
            };

            var docType    = new DocumentType(typeof(Employee));
            var queryLines = new List <SearchQuery.Line>()
            {
                new SearchQuery.Line(
                    ContentPath.Parse($"$.{nameof(Employee.Name)}")
                    , SearchQuery.Op.Equals, ContentFactory.Default.CreateFrom("John Smith")),
                new SearchQuery.Line(
                    ContentPath.Parse($"$.{nameof(Employee.Id)}")
                    , SearchQuery.Op.Equals, ContentFactory.Default.CreateFrom(1)),
            };
            var query              = new SearchQuery(docType, queryLines, ContentPath.Parse($"$.{nameof(Employee.Id)}"), false, 0, 20);
            var actual             = SqlResolver.ResolveSqlText(query, (s) => paths[s], "[search].[Docs]", "[search].[DocTokens]");
            var expectedWithSpaces = $@"SELECT [B].* FROM (SELECT DISTINCT filtered.DocumentId, Sorted.ValueAsAny FROM 
                ( SELECT f1.DocumentId FROM 
                    (    
                    SELECT DocumentId FROM [search].[DocTokens]  WITH (NOLOCK)
                    WHERE ([ValueAsAny]='John Smith' AND [PathId]=150) 
                     UNION ALL  
                    SELECT DocumentId FROM [search].[DocTokens] WITH (NOLOCK)
                    WHERE ([ValueAsAny]='011.000000' AND [PathId]=155) 
                    ) as f1 
			        group by f1.DocumentId HAVING count(*) >= {query.QueryLines.Length}               
                ) as filtered 
                LEFT JOIN (SELECT DocumentId,ValueAsAny FROM [search].[DocTokens] WITH (NOLOCK)
                WHERE [PathId] = {paths["$.Id"]}) as Sorted
                ON Sorted.DocumentId = filtered.DocumentId) AS [A] 
                INNER JOIN (SELECT * FROM [search].[Docs] WITH (NOLOCK)
                WHERE [SourceType] = '{query.DocumentType.Name}') AS [B] ON [A].DocumentId = [B].Id
                ORDER BY [A].ValueAsAny
                OFFSET {query.Offset} ROWS
                FETCH NEXT {query.Limit} ROWS ONLY";

            Assert.AreEqual(Regex.Replace(expectedWithSpaces, @"\s+", string.Empty), Regex.Replace(actual, @"\s+", string.Empty));
        }
 public SharedNestedTargetCmdGroup(
     IEnumerable <IInstallCmd> commands,
     InstallEntityPath targetPath,
     ContentPath nestedTargetPath)
 {
     this.commands         = new List <IInstallCmd>(commands);
     this.TargetPath       = targetPath;
     this.NestedTargetPath = nestedTargetPath;
 }
Esempio n. 13
0
        public void IsAncestorOrEqual()
        {
            var dirA  = new ContentPath("a");
            var itemB = dirA.CatDir("b");

            Assert.True(dirA.IsAncestorOrSelf(itemB));
            Assert.True(dirA.IsAncestorOrSelf(dirA));
            Assert.False(itemB.IsAncestorOrSelf(dirA));
        }
Esempio n. 14
0
        public ActionResult Create([ModelBinder(typeof(TypeConverterModelBinder))] ContentPath path, string container, string type, FormCollection formValues)
        {
            var contentInfo = CreateNewContent(path, container, type);

            return(UpdateContent(
                       contentInfo,
                       s => path.Append(s),
                       newPath => View("Celes.Created", newPath)
                       ));
        }
Esempio n. 15
0
        protected override void Execute(NativeActivityContext context)
        {
            var contentItem = Node.Load <GenericContent>(ContentPath.Get(context));

            using (InstanceManager.CreateRelatedContentProtector(contentItem, context))
            {
                contentItem["RejectReason"] = Reason == null ? string.Empty : (Reason.Get(context) ?? string.Empty);
                contentItem.Reject();
            }
        }
Esempio n. 16
0
 private void RenderRectangle(double width, double height)
 {
     Content = new Path
     {
         Data            = new RectangleGeometry(new Rect(0, 0, width, height)),
         StrokeThickness = 5,
         Stroke          = Brushes.DarkRed,
     };
     ContentPath.SetRoiPathFill();
 }
Esempio n. 17
0
 private IContentPathCacheEntry ParseCacheEntry(ContentPathCacheEntryDto entry)
 {
     return(new ContentPathCacheEntryAdapter
     {
         ContentId = entry.ContentId,
         ContentType = LoadType(entry.ContentType),
         Path = ContentPath.Parse(entry.Path),
         HasChildren = entry.HasChildren,
     });
 }
Esempio n. 18
0
        private IQueryable <ContentPathCacheEntry> GetEntryByPathQuery(ContentPath path)
        {
            var pathString = path.ToString();
            var pathHash   = KnuthHash.CalculateHash(pathString);

            var pathCacheEntryQuery = ContentPathCacheEntries
                                      .Where(e => e.Hash == pathHash && e.Path == pathString);

            return(pathCacheEntryQuery);
        }
Esempio n. 19
0
        public ActionResult Edit([ModelBinder(typeof(TypeConverterModelBinder))] ContentPath path, FormCollection formValues)
        {
            var contentInfo = GetContentOrNewRoot(path);

            return(UpdateContent(
                       contentInfo,
                       s => path.ReplaceLastSegment(s),
                       newPath => RedirectToAction("Edit", new { path = newPath })
                       ));
        }
Esempio n. 20
0
 public virtual bool TryGetSchema(ContentPath path, out IMust schema)
 {
     schema = null;
     if (path.Length > 0)
     {
         return(false);
     }
     schema = this;
     return(true);
 }
Esempio n. 21
0
        public void NotNull()
        {
            var paths = new Dictionary <string, int>
            {
                { "$.Audit.CreatedOn", 199 },
                { "$.Name", 150 },
                { "$.Id", 155 },
                { "$.StartDate", 156 }
                // ...etc.
            };
            var docType    = new DocumentType(typeof(Employee));
            var queryLines = new List <SearchQuery.Line>()
            {
                new SearchQuery.Line(
                    ContentPath.Parse($"$.{nameof(Employee.StartDate)}")
                    , SearchQuery.Op.NotEquals, ContentFactory.Default.CreateFrom(null)),
                new SearchQuery.Line(
                    ContentPath.Parse($"$.{nameof(Employee.Name)}")
                    , SearchQuery.Op.GreaterThanOrEquals, ContentFactory.Default.CreateFrom(new DateTime(2019, 08, 01))),

                new SearchQuery.Line(
                    ContentPath.Parse($"$.{nameof(Employee.Name)}")
                    , SearchQuery.Op.LessThanOrEquals, ContentFactory.Default.CreateFrom(new DateTime(2019, 11, 27)))
            };
            var query  = new SearchQuery(docType, queryLines, ContentPath.Parse($"$.{nameof(Employee.Id)}"), true, 0, 20);
            var actual = SqlResolver.ResolveSqlText(query, (s) => paths[s], "[search].[Docs]", "[search].[DocTokens]");

            var expectedWithSpaces = $@"SELECT [B].* FROM (SELECT DISTINCT filtered.DocumentId, Sorted.ValueAsAny FROM 
                (
                     SELECT f1.DocumentId FROM 
                    (    
                        SELECT DocumentId FROM [search].[DocTokens] WITH (NOLOCK) 
                        WHERE ([ValueAsAny] IS NOT NULL AND [PathId]=156)
                        UNION ALL
                        SELECT DocumentId FROM [search].[DocTokens] WITH (NOLOCK) 
                            WHERE ([ValueAsAny]>='2019-08-01T00:00:00.0000000' AND [PathId]=150)
                        UNION ALL
                        SELECT DocumentId FROM [search].[DocTokens] WITH (NOLOCK) 
                        WHERE ([ValueAsAny]<='2019-11-27T00:00:00.0000000' AND [PathId]=150)
                    ) as f1 
			        group by f1.DocumentId HAVING count(*) >= {query.QueryLines.Length} 
                     
                ) as filtered 
                LEFT JOIN (SELECT DocumentId,ValueAsAny FROM [search].[DocTokens] WITH (NOLOCK)
                WHERE [PathId] = {paths["$.Id"]}) as Sorted
                ON Sorted.DocumentId = filtered.DocumentId
                ) AS [A] 
                INNER JOIN (SELECT * FROM [search].[Docs] WITH (NOLOCK)
                WHERE [SourceType] = '{query.DocumentType}') AS [B] ON [A].DocumentId = [B].Id
                ORDER BY [A].ValueAsAny DESC 
                OFFSET {query.Offset} ROWS
                FETCH NEXT {query.Limit} ROWS ONLY";

            Assert.AreEqual(Regex.Replace(expectedWithSpaces, @"\s+", string.Empty), Regex.Replace(actual, @"\s+", string.Empty));
        }
Esempio n. 22
0
        protected override void Execute(NativeActivityContext context)
        {
            var bookMarkName = Guid.NewGuid().ToString();
            var content      = new WfContent {
                Path = ContentPath.Get(context)
            };

            notificationId.Set(context, context.GetExtension <ContentWorkflowExtension>().RegisterWait(content, bookMarkName));

            context.CreateBookmark(bookMarkName, Continue, BookmarkOptions.MultipleResume);
        }
Esempio n. 23
0
        public void Lineage2()
        {
            var cp      = new ContentPath();
            var lineage = cp.Lineage.ToArray();
            var expect  = new[]
            {
                new ContentPath()
            };

            Assert.True(lineage.SequenceEqual(expect));
        }
Esempio n. 24
0
 public void GetChildrenByPath()
 {
     foreach (var root in _testContext.Roots)
     {
         foreach (var child in root.Children)
         {
             var contentInfo = _contentManager.GetContentByPath(_testContext, ContentPath.Parse(child.Alias));
             Assert.Equal(child, contentInfo.Content);
         }
     }
 }
Esempio n. 25
0
        private ContentPathCacheEntry GetEntryByPath(ContentPath path)
        {
            var pathCacheEntryQuery = GetEntryByPathQuery(path);
            var cacheEntry          = pathCacheEntryQuery.FirstOrDefault();

            if (cacheEntry == null)
            {
                throw new ContentNotFoundException(path);
            }

            return(cacheEntry);
        }
        public ContentPath Update(ContentPath contentPath)
        {
            var contPath = _context.ContentPaths.FirstOrDefault(cp => cp.Id == contentPath.Id);

            if (contPath == null)
            {
                throw new ArgumentException();
            }
            _context.Entry(contentPath).State = System.Data.Entity.EntityState.Modified;
            _context.SaveChanges();
            return(contPath);
        }
Esempio n. 27
0
        void IContentPathCache.RemovePath(ContentPath path)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            var cacheEntry = GetEntryByPath(path);

            RemoveCacheEntryTree(cacheEntry);
            _dbContext.SaveChanges();
        }
Esempio n. 28
0
        public void Test_Parser()
        {
            var subObject = new CreateObjectExpression(new List <CreateObjectExpression.Element>
            {
                new CreateObjectExpression.Attribute
                {
                    Name  = "subName",
                    Value = new PathExpression(new ScopeRootExpression(), ContentPath.Parse("$.name"))
                },

                new CreateObjectExpression.Attribute
                {
                    Name  = "subAge",
                    Value = new ConstantExpression(new ContentNumber(45))
                }
            });

            Test("{ name: $.name, age: 45, ...{ subName: $.name, subAge: 45 } }", new CreateObjectExpression(new List <CreateObjectExpression.Element>
            {
                new CreateObjectExpression.Attribute
                {
                    Name  = "name",
                    Value = new PathExpression(new ScopeRootExpression(), ContentPath.Parse("$.name"))
                },

                new CreateObjectExpression.Attribute
                {
                    Name  = "age",
                    Value = new ConstantExpression(new ContentNumber(45))
                },

                new CreateObjectExpression.Object
                {
                    SubObject = subObject
                }
            }));

            Test("{}", new CreateObjectExpression(new CreateObjectExpression.Element[] { }));

            Test("[]", new CreateListExpression(new CreateListExpression.Element[] { }));

            Test("\"Yaser\"", new ConstantExpression(ContentFactory.Default.CreateFrom("Yaser")));

            Test("[45]", new CreateListExpression(new CreateListExpression.Element[]
            {
                new CreateListExpression.ListItem
                {
                    Value = new ConstantExpression(ContentFactory.Default.CreateFrom(45))
                }
            }));
        }
        public void Test_QueryHandlerAnyOf()
        {
            var list = ContentFactory.Default.CreateFrom(new[] { "123", "456" });

            var a = (list as ContentList).ToArray();

            Assert.IsInstanceOfType(a[0], typeof(ContentText));

            Assert.IsInstanceOfType(a[1], typeof(ContentText));

            var line = new SearchQuery.Line(ContentPath.Parse("$.Number.Value"), SearchQuery.Op.AnyOf, list);

            //var expr = QueryConversionHelper.BuildCriteriaExpr(line);
        }
Esempio n. 30
0
        public void AnyOf()
        {
            var paths = new Dictionary <string, int>
            {
                { "$.Audit.CreatedOn", 199 },
                { "$.Name", 150 },
                { "$.Id", 155 },
                { "$.Phones", 156 },
                // ...etc.
            };
            var docType    = new DocumentType(typeof(Employee));
            var queryLines = new List <SearchQuery.Line>()
            {
                new SearchQuery.Line(
                    ContentPath.Parse($"$.{nameof(Employee.Phones)}")
                    , SearchQuery.Op.AnyOf, ContentFactory.Default.CreateFrom(new string[] { "0001ddd", "0002ddd", "0003ddd" })),

                new SearchQuery.Line(
                    ContentPath.Parse($"$.{nameof(Employee.Name)}")
                    , SearchQuery.Op.AnyOf, ContentFactory.Default.CreateFrom(new int[] { 1, 2, 3 }))
            };
            var query = new SearchQuery(docType, queryLines, ContentPath.Parse($"$.{nameof(Employee.Id)}"), true, 0, 20);

            var actual             = SqlResolver.ResolveSqlText(query, (s) => paths[s], "[search].[Docs]", "[search].[DocTokens]");
            var expectedWithSpaces = $@"SELECT [B].* FROM (SELECT DISTINCT filtered.DocumentId, Sorted.ValueAsAny FROM 
                (
                    SELECT f1.DocumentId FROM 
                    (    
                        SELECT DocumentId FROM [search].[DocTokens] WITH (NOLOCK) 
                        WHERE ([ValueAsAny] IN ('0001ddd','0002ddd','0003ddd') AND [PathId]=156) 
                        UNION ALL
                        SELECT DocumentId FROM [search].[DocTokens] WITH (NOLOCK)
                        WHERE ([ValueAsAny] IN ('011.000000','012.000000','013.000000') AND [PathId]=150) 
                    ) as f1 
			        group by f1.DocumentId HAVING count(*) >= {query.QueryLines.Length}  
                ) as filtered 
                LEFT JOIN (SELECT DocumentId,ValueAsAny FROM [search].[DocTokens] WITH (NOLOCK)
                WHERE [PathId] = 155) as Sorted
                ON Sorted.DocumentId = filtered.DocumentId
               ) AS [A] 
                INNER JOIN (SELECT * FROM [search].[Docs] WITH (NOLOCK)
                WHERE [SourceType] = '{query.DocumentType.Name}') AS [B] ON [A].DocumentId = [B].Id
                ORDER BY [A].ValueAsAny DESC
                OFFSET {query.Offset} ROWS
                FETCH NEXT {query.Limit} ROWS ONLY";

            Assert.AreEqual(Regex.Replace(expectedWithSpaces, @"\s+", string.Empty), Regex.Replace(actual, @"\s+", string.Empty));
        }
Esempio n. 31
0
        private IList<MenuItemModel> GetMenuItemForPath(ContentPath path, string viewNamePrefix, int depth)
        {
            if (depth <= 0)
            {
                return null;
            }

            return _contentPathCache.GetChildEntriesOfPath(path)
                .Select(e => new MenuItemModel
                {
                    ViewName = (viewNamePrefix ?? "") + e.ContentType.Name,
                    Content = GetContent(e),
                    ChildMenuItems = GetMenuItemForPath(e.Path, viewNamePrefix, depth - 1),
                })
                .ToList();
        }
Esempio n. 32
0
        void IContentPathCache.AddPath(ContentPath path, int contentId, Type contentType)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }

            var parentEntry = path != ContentPath.Root
                ? GetEntryByPath(path.GetParent())
                : null;

            var sortOrder = parentEntry != null && parentEntry.Children.Any()
                ? parentEntry.Children.Max(e => e.SortOrder) + 1
                : 0;

            var cacheEntry = CreateCacheEntry(contentId, contentType, path, parentEntry, sortOrder);
            _dbContext.SaveChanges();
        }
Esempio n. 33
0
 public ContentNotFoundException(ContentPath path)
     : base(string.Format("Content with path '{0}' not found.", path))
 {
     Path = path;
 }
Esempio n. 34
0
        private IContentInfo GetContentOrNewRoot(ContentPath path)
        {
            try
            {
                return GetContent(path);
            }
            catch (ContentNotFoundException)
            {
                if (path == ContentPath.Root)
                {
                    var content = (IContent)Activator.CreateInstance(_contentRepository.RootContentType);

                    ReflectionUtility
                        .GetGenericMethod(() => _contentRepository.AddContent<IContent>(null))
                        .MakeGenericMethod(_contentRepository.RootContentType)
                        .Invoke(_contentRepository, new object[] { content });

                    return ContentInfo.Create(content, _contentRepository.RootContentType, null);
                }
                else
                {
                    throw;
                }
            }
        }
Esempio n. 35
0
        IEnumerable<IContentPathCacheEntry> IContentPathCache.GetChildEntriesOfPath(ContentPath path)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            EnsureCacheIsBuilt();

            return GetEntryByPathQuery(path)
                .SelectMany(e => e.Children)
                .OrderBy(e => e.SortOrder)
                .ToContentPathCacheEntryDto()
                .AsEnumerable()
                .Select(ParseCacheEntry);
        }
Esempio n. 36
0
 private void SetPath(ContentPathCacheEntry cacheEntry, ContentPath path)
 {
     SetPath(cacheEntry, path.ToString());
 }
Esempio n. 37
0
        private IQueryable<ContentPathCacheEntry> GetEntryByPathQuery(ContentPath path)
        {
            var pathString = path.ToString();
            var pathHash = KnuthHash.CalculateHash(pathString);

            var pathCacheEntryQuery = ContentPathCacheEntries
                .Where(e => e.Hash == pathHash && e.Path == pathString);
            return pathCacheEntryQuery;
        }
Esempio n. 38
0
        private void RebuildPathCache(IEnumerable<IContent> contents, ContentPath parentPath, ContentPathCacheEntry parentEntry)
        {
            var cachedContents = contents.ToList();
            if (cachedContents.Count == 0)
            {
                return;
            }

            foreach (var item in cachedContents.Select((c, i) => new { Content = c, Index = i }))
            {
                var content = item.Content;

                var path = parentPath != null
                    ? parentPath.Append(content.Alias)
                    : ContentPath.Root;

                var actualContentType = ObjectContext.GetObjectType(content.GetType());

                var collectionProperties = _collectionPropertiesByType.GetOrAdd(actualContentType, t => t
                    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                    .Select(p => new { Property = p, CollectionType = p.PropertyType.GetImplementationOf(typeof(IEnumerable<>)) })
                    .Where(p => p.CollectionType != null)
                    .Select(p => new { Property = p.Property, ChildType = p.CollectionType.GetGenericArguments().First() })
                    .Where(p => typeof(IContent).IsAssignableFrom(p.ChildType))
                    .Select(p => p.Property)
                    .ToList());

                var cacheEntry = CreateCacheEntry(content.Id, actualContentType, path, parentEntry, item.Index);

                foreach (var collectionProperty in collectionProperties)
                {
                    var children = (IEnumerable<IContent>)collectionProperty.GetValue(content, null);
                    RebuildPathCache(children, path, cacheEntry);
                }
            }
        }
Esempio n. 39
0
        private ContentPathCacheEntry CreateCacheEntry(int contentId, Type contentType, ContentPath path, ContentPathCacheEntry parent, int sortOrder)
        {
            var cacheEntry = new ContentPathCacheEntry
            {
                ContentId = contentId,
                ContentType = contentType.FullName,
                Parent = parent,
                SortOrder = sortOrder,
            };

            SetPath(cacheEntry, path);

            ContentPathCacheEntries.Add(cacheEntry);

            return cacheEntry;
        }
Esempio n. 40
0
        private ContentPathCacheEntry GetEntryByPath(ContentPath path)
        {
            var pathCacheEntryQuery = GetEntryByPathQuery(path);
            var cacheEntry = pathCacheEntryQuery.FirstOrDefault();
            if (cacheEntry == null)
            {
                throw new ContentNotFoundException(path);
            }

            return cacheEntry;
        }
Esempio n. 41
0
        void IContentPathCache.UpdatePath(ContentPath oldPath, ContentPath newPath)
        {
            if (oldPath == null)
            {
                throw new ArgumentNullException("oldPath");
            }

            if (newPath == null)
            {
                throw new ArgumentNullException("newPath");
            }

            var cacheEntry = GetEntryByPath(oldPath);
            UpdatePathRecursive(oldPath.ToString(), newPath.ToString(), cacheEntry);
            _dbContext.SaveChanges();
        }
Esempio n. 42
0
        bool IContentPathCache.ReorderPath(ContentPath path, bool moveUp)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (path == ContentPath.Root)
            {
                return false;
            }

            EnsureCacheIsBuilt();

            var entryToMove = GetEntryByPath(path);

            ContentPathCacheEntry siblingEntry;
            if (moveUp)
            {
                siblingEntry = GetEntryByPathQuery(path.GetParent())
                    .SelectMany(p => p.Children)
                    .Where(p => p.SortOrder < entryToMove.SortOrder)
                    .OrderByDescending(p => p.SortOrder)
                    .FirstOrDefault();
            }
            else
            {
                siblingEntry = GetEntryByPathQuery(path.GetParent())
                    .SelectMany(p => p.Children)
                    .Where(p => p.SortOrder > entryToMove.SortOrder)
                    .OrderBy(p => p.SortOrder)
                    .FirstOrDefault();
            }

            if (siblingEntry != null)
            {
                var tmp = entryToMove.SortOrder;
                entryToMove.SortOrder = siblingEntry.SortOrder;
                siblingEntry.SortOrder = tmp;

                _dbContext.SaveChanges();
                return true;
            }

            return false;
        }
Esempio n. 43
0
        void IContentPathCache.RemovePath(ContentPath path)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            var cacheEntry = GetEntryByPath(path);
            RemoveCacheEntryTree(cacheEntry);
            _dbContext.SaveChanges();
        }
Esempio n. 44
0
        IContentPathCacheEntry IContentPathCache.GetEntryByPath(ContentPath path)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            EnsureCacheIsBuilt();

            var cacheEntry = GetEntryByPathQuery(path)
                .ToContentPathCacheEntryDto()
                .FirstOrDefault();

            if (cacheEntry == null)
            {
                throw new ContentNotFoundException(path);
            }

            return ParseCacheEntry(cacheEntry);
        }
Esempio n. 45
0
        private ContentInfo CreateNewContent(ContentPath path, string container, string type)
        {
            var parentContentInfo = GetContent(path);

            var property = parentContentInfo.ContentType.GetProperty(container);
            if (property == null)
            {
                throw new HttpException(404, "Invalid container");
            }

            var collectionType = property.PropertyType.GetImplementationOf(typeof(ICollection<>));
            if (collectionType == null)
            {
                throw new HttpException(400, "Not a collection");
            }

            var collectionItemType = collectionType.GetGenericArguments().First();
            var contentType = collectionItemType.Assembly
                .GetTypes()
                .Where(t => t.IsClass && !t.IsAbstract && collectionItemType.IsAssignableFrom(t))
                .Single(t => t.FullName == type);

            var content = (IContent)Activator.CreateInstance(contentType);

            // Add the new content to its parent collection.
            var collectionInstance = property.GetValue(parentContentInfo.Content, null);
            collectionType
                .GetMethod("Add")
                .Invoke(collectionInstance, new object[] { content });

            return ContentInfo.Create(content, contentType, null);
        }