コード例 #1
0
ファイル: TextContentBinder.cs プロジェクト: RameshGD/CMS
        public virtual TextContent Bind(Schema schema, TextContent textContent, System.Collections.Specialized.NameValueCollection values, bool update, bool thorwViolationException)
        {
            List<RuleViolation> violations = new List<RuleViolation>();
            schema = schema.AsActual();
            //do not to create a new content instance
            //it will interrupt the object state for ravendb.
            //textContent = new TextContent(textContent);

            foreach (Column column in ((ISchema)(schema.AsActual())).Columns.Where(it => !string.IsNullOrEmpty(it.ControlType)))
            {
                var value = values[column.Name];
                //IControl control = column.GetControlType();
                ////
                //if (control != null)
                //{
                //    value = control.GetValue(textContent[column.Name], value);
                //}
                // Update content will keep the old values;
                if (value == null && update == true)
                {
                    continue;
                }
                //postedData[column.Name] = value;

                ParseColumnValue(textContent, ref violations, column, value);

                ValidateColumn(schema, textContent, ref violations, column, update);
            }
            if (thorwViolationException && violations.Count > 0)
            {
                throw new RuleViolationException(textContent, violations);
            }
            return textContent;
        }
コード例 #2
0
ファイル: Context.cs プロジェクト: Mofangbao/gnoam
 /** Replaces the range from the given location to the current position with a text node. */
 public void Reduce(int from)
 {
     string reduction = Content.ToString(from, Position);
       Content.RemoveRange(from, Position - from);
       TextContent text = new TextContent(reduction);
       Content.Insert(from, text);
       Position = from;
 }
コード例 #3
0
        public void TextContent_SubMenu_ShouldReturnItsSubMenu()
        {
            var textContent = new TextContent
            {
                ParentContent = subMenu
            };

            Assert.That(textContent.SubMenu, Is.SameAs(subMenu));
        }
コード例 #4
0
        public void TextContentWithoutMenuShouldReturnNull()
        {
            var textContent = new TextContent
            {
                Text = "Hello World"
            };

            textContent.SubMenu.ShouldBeNull();
        }
コード例 #5
0
        public void TextContentWithoutSubMenu_SubMenu_ShouldReturnNull()
        {

            var textContent = new TextContent
            {
                ParentContent = mainMenu
            };

            Assert.That(textContent.SubMenu, Is.Null);
        }
コード例 #6
0
        public void UrlName_ShouldReturnAnyNonNameCharactersAsUnderscores()
        {
            const string name = "That's how (he &) I like £$$$";
            const string expectedName = "That_s_how__he____I_like_____";

            var textContent = new TextContent
            {
                Name = name
            };

            var urlName = textContent.UrlName;

            Assert.That(urlName, Is.EqualTo(expectedName));
        }
コード例 #7
0
ファイル: TextContentBinder.cs プロジェクト: Godoy/CMS
        public TextContent Default(Schema schema)
        {
            List<RuleViolation> violations = new List<RuleViolation>();
            TextContent textContent = new TextContent();

            foreach (Column column in ((ISchema)(schema.AsActual())).Columns)
            {
                if (!string.IsNullOrEmpty(column.DefaultValue))
                {
                    ParseColumnValue(textContent, ref violations, column, column.DefaultValue);
                }
                else
                {
                    textContent[column.Name] = DataTypeHelper.DefaultValue(column.DataType);
                }
            }

            return textContent;
        }
コード例 #8
0
        public void SetUp()
        {
            var menu1 = new Menu
            {
                Name = "menu1",
                IsActive = true,
                Position = 1
            };

            var text = new TextContent
            {
                Name = "text1",
                Text = "some text",
                IsActive = true,
                Position = 2
            };

            var action = new ActionContent
            {
                Name = "My Action",
                Controller = "controller",
                Action = "action",
                IsActive = true,
                Position = 3
            };

            var menu2 = new Menu
            {
                Name = "menu2",
                IsActive = true,
                Position = 4
            };

            InSession(session =>
            {
                session.Save(menu1);
                session.Save(text);
                session.Save(action);
                session.Save(menu2);
            });

            menu1Id = menu1.Id;
        }
コード例 #9
0
ファイル: TextContentPath.cs プロジェクト: Godoy/CMS
        public TextContentPath(TextContent content)
        {
            var repository = new Repository(content.Repository);

            var textContent = content;
            if (string.IsNullOrEmpty(textContent.FolderName))
            {
                var schemaPath = new SchemaPath(new Schema(repository, textContent.SchemaName));
                // Compatible with the ContentFolderName has been change (_contents=>.contents)
                //this.PhysicalPath = Path.Combine(schemaPath.PhysicalPath, ContentFolderName, content.UUID);
                //this.VirtualPath = UrlUtility.Combine(schemaPath.VirtualPath, ContentFolderName, content.UUID);

                //if (!Directory.Exists(this.PhysicalPath))
                //{
                    this.PhysicalPath = Path.Combine(schemaPath.PhysicalPath, ContentAttachementFolder, content.UUID);
                    this.VirtualPath = UrlUtility.Combine(schemaPath.VirtualPath, ContentAttachementFolder, content.UUID);
                //}
            }
            else
            {
                FolderPath folderPath = null;

                folderPath = new FolderPath(FolderHelper.Parse<TextFolder>(repository, content.FolderName));
                //// Compatible with the ContentFolderName has been change (_contents=>.contents)
                //this.PhysicalPath = Path.Combine(folderPath.PhysicalPath, ContentFolderName, content.UUID);
                //this.VirtualPath = UrlUtility.Combine(folderPath.VirtualPath, ContentFolderName, content.UUID);
                //if (!Directory.Exists(this.PhysicalPath))
                //{
                    this.PhysicalPath = Path.Combine(folderPath.PhysicalPath, ContentAttachementFolder, content.UUID);
                    this.VirtualPath = UrlUtility.Combine(folderPath.VirtualPath, ContentAttachementFolder, content.UUID);
                //}

            }
            var sysFolderName = Path.GetDirectoryName(this.PhysicalPath);
            if (!Directory.Exists(sysFolderName))
            {
                Directory.CreateDirectory(sysFolderName);
                var sysFolder = new DirectoryInfo(sysFolderName);
                sysFolder.Attributes = sysFolder.Attributes | FileAttributes.Hidden;
            }

        }
コード例 #10
0
        public void SetUp()
        {
            menu = new Menu
            {
                Name = "Main", 
                IsActive = true, 
                Position = 1
            };
            var textContent = new TextContent
            {
                Name = "Text", 
                Text = "Some text", 
                IsActive = true, 
                Position = 2,
                ParentContent = menu
            };
            var actionContent = new ActionContent
            {
                Name = "Action",
                Controller = "HomeController",
                Action = "Index",
                IsActive = true,
                Position = 3,
                ParentContent = menu
            };
            var topContent = new TopContent
            {
                Name = "Top content",
                Text = "Some more text",
                IsActive = true,
                Position = 4,
                ParentContent = menu
            };

            InSession(session =>
            {
                session.Save(menu);
                session.Save(textContent);
                session.Save(actionContent);
                session.Save(topContent);
            });
        }
コード例 #11
0
        private void UpdateAdditional(Dictionary <string, string> additionalData, TextContent content, ContentFolder folder, SiteDb siteDb)
        {
            List <EmbeddedBy> embeddedby = null;

            foreach (var item in additionalData)
            {
                Guid ValueId = default(Guid);
                if (!String.IsNullOrWhiteSpace(item.Value))
                {
                    ValueId = Kooboo.Lib.Helper.IDHelper.GetOrParseKey(item.Value);
                }

                var category = GetCatFolder(item.Key);
                if (category != null)
                {
                    if (ValueId == default(Guid))
                    {
                        //To remove item..
                        var currentItems = siteDb.ContentCategories.GetCategories(category.FolderId, content.Id);
                        foreach (var cat in currentItems)
                        {
                            siteDb.ContentCategories.Delete(cat.Id);
                        }
                    }
                    else
                    {
                        var catitem = siteDb.TextContent.Get(ValueId);
                        if (catitem != null)
                        {
                            siteDb.ContentCategories.AddOrUpdate(new ContentCategory()
                            {
                                ContentId = content.Id, CategoryFolder = category.FolderId, CategoryId = ValueId
                            });
                        }
                    }
                }
                else
                {
                    var by = GetBY();

                    if (by.Any())
                    {
                        var beEmbedded = by.Find(o => Kooboo.Lib.Helper.StringHelper.IsSameValue(o.FolderName, item.Key));

                        if (beEmbedded == null && (item.Key.ToLower() == "parent" || item.Key.ToLower() == "parentid"))
                        {
                            beEmbedded = by.First();
                        }
                        if (beEmbedded != null)
                        {
                            if (ValueId != default(Guid))
                            {
                                var parentcontent = siteDb.TextContent.Get(ValueId);
                                if (parentcontent != null)
                                {
                                    if (parentcontent.Embedded.ContainsKey(folder.Id))
                                    {
                                        var list = parentcontent.Embedded[folder.Id];
                                        if (list == null)
                                        {
                                            list = new List <Guid>();
                                        }
                                        if (!list.Contains(content.Id))
                                        {
                                            list.Add(content.Id);
                                        }
                                    }
                                    else
                                    {
                                        List <Guid> ids = new List <Guid>();
                                        ids.Add(content.Id);
                                        parentcontent.Embedded[folder.Id] = ids;
                                    }

                                    siteDb.TextContent.AddOrUpdate(parentcontent);
                                }
                            }
                            else
                            {
                                // TODO:
                                // this is to remove one item from the embedded...This is not happening often.
                                // only we need to find out which item embed this one which is not easy... as we need to check every items.
                            }
                        }
                    }
                }
            }


            List <EmbeddedBy> GetBY()
            {
                if (embeddedby == null)
                {
                    embeddedby = siteDb.ContentFolders.GetEmbeddedBy(folder.Id);
                }
                return(embeddedby);
            }

            CategoryFolder GetCatFolder(string foldername)
            {
                var category = folder.Category.Find(o => Kooboo.Lib.Helper.StringHelper.IsSameValue(o.Alias, foldername));

                if (category != null)
                {
                    return(category);
                }
                else
                {
                    foreach (var item in folder.Category)
                    {
                        var catfolder = siteDb.ContentFolders.Get(item.FolderId);
                        if (catfolder != null)
                        {
                            if (Kooboo.Lib.Helper.StringHelper.IsSameValue(catfolder.Name, foldername))
                            {
                                return(item);
                            }
                        }
                    }
                }
                return(null);
            }
        }
コード例 #12
0
ファイル: QueryTests.cs プロジェクト: zhq0131/CMS
        public QueryTests()
        {
            EmptyUserKeyGenerator.DefaultGenerator = new EmptyUserKeyGenerator();
            Providers.DefaultProviderFactory       = new MongoDB.ProviderFactory();

            repository = new Repository(Kooboo.UniqueIdGenerator.GetInstance().GetBase32UniqueId(10).ToString());
            Providers.DefaultProviderFactory.GetProvider <IRepositoryProvider>().Add(repository);
            categorySchema = new Schema(repository, "category")
            {
                IsDummy = false
            };
            categorySchema.AddColumn(new Column()
            {
                Name = "Title"
            });
            categoryFolder = new TextFolder(repository, "Category")
            {
                SchemaName = categorySchema.Name, IsDummy = false
            };
            Providers.DefaultProviderFactory.GetProvider <ITextFolderProvider>().Add(categoryFolder);

            newsSchema = new Schema(repository, "News")
            {
                IsDummy = false
            };
            newsSchema.AddColumn(new Column()
            {
                Name = "title", DataType = Common.DataType.String
            });
            newsSchema.AddColumn(new Column()
            {
                Name = "Body", DataType = Common.DataType.String
            });
            newsSchema.AddColumn(new Column()
            {
                Name = "Comments", DataType = Common.DataType.Int
            });
            Providers.DefaultProviderFactory.GetProvider <ISchemaProvider>().Add(newsSchema);

            newsFolder = new TextFolder(repository, "News")
            {
                SchemaName = newsSchema.Name, Categories = new List <CategoryFolder>()
                {
                    new CategoryFolder()
                    {
                        FolderName = categoryFolder.FullName, SingleChoice = false
                    }
                }, OrderSetting = new OrderSetting()
                {
                    FieldName = "Sequence", Direction = OrderDirection.Descending
                }
            };
            Providers.DefaultProviderFactory.GetProvider <ITextFolderProvider>().Add(newsFolder);

            commentSchema = new Schema(repository, "Comment")
            {
                IsDummy = false
            };
            commentSchema.AddColumn(new Column()
            {
                Name = "Title"
            });
            Providers.DefaultProviderFactory.GetProvider <ISchemaProvider>().Add(commentSchema);

            category1          = new TextContent(repository.Name, categorySchema.Name, categoryFolder.FullName);
            category1["title"] = "category1";
            provider.Add(category1);

            category2          = new TextContent(repository.Name, categorySchema.Name, categoryFolder.FullName);
            category2["title"] = "category2";
            provider.Add(category2);

            newsContent             = new TextContent(repository.Name, newsSchema.Name, newsFolder.FullName);
            newsContent["title"]    = "news1";
            newsContent["body"]     = "body";
            newsContent["comments"] = 1;
            provider.Add(newsContent);

            news2             = new TextContent(repository.Name, newsSchema.Name, newsFolder.FullName);
            news2["title"]    = "news2";
            news2["body"]     = "body";
            news2["comments"] = 0;
            provider.Add(news2);

            news3             = new TextContent(repository.Name, newsSchema.Name, newsFolder.FullName);
            news3["title"]    = "news2";
            news3["body"]     = "body";
            news3["comments"] = 5;
            provider.Add(news3);

            provider.AddCategories(newsContent, new Category()
            {
                ContentUUID = newsContent.UUID, CategoryUUID = category1.UUID, CategoryFolder = category1.FolderName
            });
            provider.AddCategories(newsContent, new Category()
            {
                ContentUUID = newsContent.UUID, CategoryUUID = category2.UUID, CategoryFolder = category2.FolderName
            });

            commenContent = new TextContent(repository.Name, commentSchema.Name, "");
            commenContent.ParentFolder = newsContent.FolderName;
            commenContent.ParentUUID   = newsContent.UUID;
            commenContent["title"]     = "comment1";
            provider.Add(commenContent);
        }
コード例 #13
0
 public TextContentExtensionDuck(TextContent textContent)
     : this(textContent, EXTENSION_TYPES)
 {
 }
コード例 #14
0
        public static TextContentViewModel ToListDisplayView(TextContent Content, ContentType ContentType, string lang = null)
        {
            Dictionary <string, string> displayFields = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            var fields = ContentType.Properties.FindAll(o => o.IsSummaryField && !o.IsSystemField);

            if (fields == null || fields.Count() == 0)
            {
                fields = ContentType.Properties.FindAll(o => !o.IsSystemField && o.DataType == Data.Definition.DataTypes.String);
            }

            if (fields == null || fields.Count() == 0)
            {
                fields = ContentType.Properties.FindAll(o => !o.IsSystemField);
            }

            foreach (var item in fields)
            {
                if (!displayFields.ContainsKey(item.Name))
                {
                    displayFields.Add(item.Name, item.DisplayName);
                }
            }


            if (Content == null)
            {
                return(null);
            }
            TextContentViewModel model = new TextContentViewModel();

            model.Id            = Content.Id;
            model.ParentId      = Content.ParentId;
            model.FolderId      = Content.FolderId;
            model.ContentTypeId = Content.ContentTypeId;
            model.UserKey       = Content.UserKey;
            model.LastModified  = Content.LastModified;
            model.Order         = Content.Order;
            model.Online        = Content.Online;
            model.Embedded      = Content.Embedded;
            model.CreationDate  = Content.CreationDate;

            var content = Content.GetContentStore(lang);

            if (content != null)
            {
                foreach (var item in content.FieldValues)
                {
                    if (displayFields.ContainsKey(item.Key))
                    {
                        var displayname = displayFields[item.Key];

                        model.TextValues[displayname] = item.Value;
                    }
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(Content.UserKey))
                {
                    var userKeyField = ContentType.Properties.Find(o => o.Name == "UserKey");
                    model.TextValues[userKeyField.DisplayName] = Content.UserKey;
                }
            }
            return(model);
        }
コード例 #15
0
ファイル: WorkflowPath.cs プロジェクト: Godoy/CMS
 public WorkflowHistoryPath(TextContent content)
 {
     ContentPath = new TextContentPath(content);
     PhysicalPath = Path.Combine(ContentPath.PhysicalPath, PATH_NAME);
     VirtualPath = UrlUtility.Combine(ContentPath.VirtualPath, PATH_NAME);
 }
コード例 #16
0
        public void Edit_ShouldDisplayEditViewWithExistingContent()
        {
            const int contentId = 22;

            var content = new TextContent { ContentId = contentId };
            contentRepository.Stub(cr => cr.GetById(contentId)).Return(content);

            var menus = new List<Content>().AsQueryable();
            contentRepository.Stub(cr => cr.GetAll()).Return(menus);

            cmsController.Edit(contentId)
                .ReturnsViewResult()
                .ForView("Edit")
                .WithModel<CmsViewData>()
                .AssertAreEqual(contentId, vd => vd.Content.ContentId)
                .AssertNotNull(vd => vd.Menus);
        }
コード例 #17
0
ファイル: TextContentQuery.cs プロジェクト: nguyenhuy2911/CMS
        public static IContentQuery <TextContent> Children(this TextContent parent, TextFolder embeddedFolder)
        {
            var parentSchema = new Schema(new Repository(parent.Repository), parent.SchemaName);

            return(parentSchema.CreateQuery().WhereEquals("UUID", parent.UUID).Children(embeddedFolder));
        }
コード例 #18
0
 public ExampleCategory(TextContent textContent)
     : base(textContent)
 {
 }
コード例 #19
0
ファイル: RelationManager.cs プロジェクト: weedkiller/Kooboo
        public static string GetTextContentBody(TextContent content, SiteDb sitedb)
        {
            var contenttype = sitedb.ContentTypes.GetByFolder(content.FolderId);

            if (contenttype == null)
            {
                return(content.Body);
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                foreach (var item in content.Contents)
                {
                    sb.Append($"<KooobooLanguage name=\"{item.Lang}\">");

                    if (item.FieldValues != null)
                    {
                        foreach (var field in item.FieldValues)
                        {
                            var property = contenttype.GetProperty(field.Key);
                            if (property != null && property.IsMedia())
                            {
                                if (property.MultipleValue)
                                {
                                    if (!string.IsNullOrEmpty(field.Value))
                                    {
                                        List <string> values = Lib.Helper.JsonHelper.Deserialize <List <string> >(field.Value);
                                        foreach (var value in values)
                                        {
                                            if (Lib.Helper.IOHelper.MimeType(value).ToLower().Contains("image"))
                                            {
                                                sb.Append($"<KoobooField name=\"{field.Key}\"><img src=\"{value}\" /></KoobooField>");
                                            }
                                            else
                                            {
                                                sb.Append($"<KoobooField name=\"{field.Key}\">{field.Value}</KoobooField>");
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    if (Lib.Helper.IOHelper.MimeType(field.Value).ToLower().Contains("image"))
                                    {
                                        sb.Append($"<KoobooField name=\"{field.Key}\"><img src=\"{field.Value}\" /></KoobooField>");
                                    }
                                    else
                                    {
                                        sb.Append($"<KoobooField name=\"{field.Key}\">{field.Value}</KoobooField>");
                                    }
                                }
                            }
                            else
                            {
                                sb.Append($"<KoobooField name=\"{field.Key}\">{field.Value}</KoobooField>");
                            }
                        }
                    }
                    sb.Append("</KooobooLanguage>");
                }
                return(sb.ToString());
            }
        }
コード例 #20
0
ファイル: ManipulatorTests.cs プロジェクト: J0hnLiu/vrs
 protected TextContent GetResponseContent()
 {
     return(TextContent.Load(_Environment.ResponseBodyBytes));
 }
コード例 #21
0
ファイル: ManipulatorTests.cs プロジェクト: J0hnLiu/vrs
            public void ManipulateTextResponse(IDictionary <string, object> environment, TextContent textContent)
            {
                Environment = environment;
                TextContent = textContent;
                ++CallCount;

                if (Callback != null)
                {
                    Callback(environment, textContent);
                }
            }
コード例 #22
0
ファイル: ViewHelper.cs プロジェクト: zhq0131/CMS
 public static IHtmlString Edit(TextContent data)
 {
     return(EditItemAttributes(data));
 }
コード例 #23
0
ファイル: ViewHelper.cs プロジェクト: zhq0131/CMS
 public static IHtmlString EditFieldAttributes(TextContent data, string fieldName)
 {
     return(EditFieldAttributes(data, fieldName, FieldDataType.Auto));
 }
コード例 #24
0
        public virtual ActionResult SelectTextContent(string siteName, string folderName, string selected, int?page, int?pageSize, string search,
                                                      string sortField = null, string sortDir = null)
        {
            var site       = SiteHelper.Parse(siteName);
            var repository = site.GetRepository();
            var textFolder = (TextFolder)(FolderHelper.Parse <TextFolder>(repository, folderName).AsActual());

            var singleChoice = string.Equals("True", Request.RequestContext.GetRequestValue("SingleChoice"), StringComparison.OrdinalIgnoreCase);

            Schema     schema     = new Schema(repository, textFolder.SchemaName).AsActual();
            SchemaPath schemaPath = new SchemaPath(schema);

            ViewData["Folder"]   = textFolder;
            ViewData["Schema"]   = schema;
            ViewData["Template"] = textFolder.GetFormTemplate(FormType.Selectable);
            //ViewData["WhereClause"] = whereClause;

            IEnumerable <TextFolder> childFolders = new TextFolder[0];

            //Skip the child folders on the embedded folder grid.
            if (!page.HasValue || page.Value <= 1)
            {
                childFolders = Kooboo.CMS.Content.Services.ServiceFactory.TextFolderManager.ChildFoldersWithSameSchema(textFolder).Select(it => it.AsActual());
            }

            var query = textFolder.CreateQuery().DefaultOrder();

            query = query.SortBy(sortField, sortDir);


            bool showTreeStyle = schema.IsTreeStyle;

            if (showTreeStyle)
            {
                query = query.Where(new OrElseExpression(new WhereEqualsExpression(null, "ParentUUID", null), new WhereEqualsExpression(null, "ParentUUID", "")));
            }

            if (!string.IsNullOrEmpty(search))
            {
                IWhereExpression exp = new FalseExpression();
                foreach (var item in schema.Columns.Where(it => it.ShowInGrid))
                {
                    exp = new OrElseExpression(exp, (new WhereContainsExpression(null, item.Name, search)));
                }
                if (exp != null)
                {
                    query = query.Where(exp);
                }
                showTreeStyle = false;
            }

            var contents = query.ToPageList(page ?? 1, pageSize ?? textFolder.PageSize, textFolder.EnablePaging.HasValue ? textFolder.EnablePaging.Value : true);
            SelectableViewModel viewModel = new SelectableViewModel()
            {
                ShowTreeStyle = showTreeStyle, ChildFolders = childFolders, Contents = contents, SingleChoice = singleChoice
            };

            if (Request.IsAjaxRequest())
            {
                return(PartialView("", viewModel));
            }
            else
            {
                IEnumerable <TextContent> selectedContents = new TextContent[0];
                if (!string.IsNullOrEmpty(selected))
                {
                    string[] selectedArr = selected.Split(',');
                    IContentQuery <TextContent> selectedQuery = textFolder.CreateQuery().DefaultOrder();
                    foreach (var userKey in selectedArr)
                    {
                        selectedQuery = selectedQuery.Or((IWhereExpression)textFolder.CreateQuery().DefaultOrder().WhereEquals("UUID", userKey).Expression);
                    }

                    selectedContents = selectedQuery;
                }
                viewModel.Selected = selectedContents;
            }

            return(View(viewModel));
        }
コード例 #25
0
ファイル: TextContentQuery.cs プロジェクト: nguyenhuy2911/CMS
        public static IContentQuery <TextContent> Parent(this TextContent childContent, Schema parentSchema)
        {
            var childSchema = new Schema(new Repository(childContent.Repository), childContent.SchemaName);

            return(childSchema.CreateQuery().WhereEquals("UUID", childContent.UUID).Parent(parentSchema));
        }
コード例 #26
0
 public static string GetTextContentFilePath(this TextContent textContent, ContentFile contentFile)
 {
     return(UrlUtility.Combine(GetTextContentDirectoryPath(textContent), StorageNamesEncoder.EncodeBlobName(contentFile.FileName)));
 }
コード例 #27
0
 internal static RenderedNode getNodeFromTextContent(TextContent textContent)
 {
     RenderedNode node = RenderedNode.CreateDefault();
     node.TechnicalSource = NodeSourceTypeTextContent;
     node.Title = textContent.Title;
     node.Excerpt = textContent.Excerpt;
     if (textContent.ImageData != null)
     {
         node.ImageBaseUrl = textContent.ImageData.ContentUrlBase;
         node.ImageExt = textContent.ImageData.AdditionalFormatFileExt;
     }
     node.ActualContentUrl = "../" + textContent.SemanticDomainName + "/" + textContent.Name + "/" + textContent.ID;
     if (textContent.Categories != null)
     {
         node.Categories.CollectionContent.AddRange(getCategoryCollectionTexts(textContent.Categories, getTitleOrNameFromCategory));
         node.CategoryNames.CollectionContent.AddRange(getCategoryCollectionTexts(textContent.Categories, cat => cat.CategoryName));
         node.CategoryIDList = textContent.Categories.SelectedIDCommaSeparated;
     }
     if(textContent.Locations != null)
         node.Locations.CollectionContent.AddRange(getLocationCollectionTexts(textContent.Locations));
     node.Authors.CollectionContent.Add(getShortTextObject(textContent.Author));
     //node.MainSortableText = textContent.SortOrderNumber.ToString();
     node.MainSortableText = textContent.Published.ToString("s");
     node.TimestampText = getTimeStampText(textContent.Published);
     return node;
 }
コード例 #28
0
 private string GetPath(TextContent content)
 {
     return(new WorkflowHistoryPath(content).PhysicalPath);
 }
コード例 #29
0
		public void AddWithPost_ShouldAddNewContent()
		{
			var content = new TextContent() { ParentContentId = 4 };
			cmsController.Add(content)
				.ReturnsRedirectToRouteResult()
				.ToController("Menu")
				.ToAction("List")
				.WithRouteValue("id", "4");

			contentRepository.AssertWasCalled(x => x.InsertOnSubmit(content));
		}
コード例 #30
0
 public static string CompositePostId(TextContent content)
 {
     return(content.FolderName + "$$$" + content.UUID + "$$$" + content.UserKey);
 }
コード例 #31
0
ファイル: ViewHelper.cs プロジェクト: zhq0131/CMS
 public static IHtmlString Edit(TextContent data, string fieldName)
 {
     return(EditFieldAttributes(data, fieldName));
 }
コード例 #32
0
 /*
 internal static void Update_Category_ParentCategories(Category category, CategoryCollection localCollection, CategoryCollection masterCollection)
 {
     if (localCollection == null)
     {
         category.ParentCategories = CategoryCollection.CreateDefault();
         localCollection = category.ParentCategories;
     }
     localCollection.CollectionContent = masterCollection.CollectionContent;
     if (localCollection.OrderFilterIDList == null)
         localCollection.OrderFilterIDList = new List<string>();
 }*/
 internal static void Update_TextContent_Locations(TextContent textContent, AddressAndLocationCollection localCollection, AddressAndLocationCollection masterCollection)
 {
     // TODO: Remove objects, that are no longer available in master
 }
コード例 #33
0
        public void RoundTripTextContent()
        {
            Token token = new Token()
            {
                ApplicationId = Guid.NewGuid()
            };
            TextContent data = new TextContent()
            {
                Active    = true,
                Content   = Guid.NewGuid().ToString(),
                CreatedOn = DateTime.UtcNow,
                Deleted   = true,
                UpdatedOn = DateTime.UtcNow,
                Token     = token
            };

            Assert.AreEqual <Guid>(Guid.Empty, data.Id);

            ContentCore core     = new ContentCore();
            TextContent returned = core.Store(data);

            Assert.IsNotNull(returned);
            Assert.AreNotEqual <Guid>(Guid.Empty, returned.Id);

            TextContent query = new TextContent()
            {
                Token = token,
                Id    = returned.Id
            };

            TextContent filled = core.Get(query);

            Assert.IsNotNull(filled);
            Assert.AreEqual <Guid>(returned.Id, filled.Id);
            Assert.AreEqual <bool>(data.Active, filled.Active, "Data Mismatch");
            Assert.AreEqual <string>(data.Content, filled.Content, "Data Mismatch");
            Assert.AreEqual <DateTime>(data.CreatedOn.Date, filled.CreatedOn.Date, "Data Mismatch");
            Assert.AreEqual <bool>(data.Deleted, filled.Deleted, "Data Mismatch");
            Assert.AreEqual <DateTime>(data.UpdatedOn.Date, filled.UpdatedOn.Date, "Data Mismatch");

            filled.Active    = false;
            filled.Content   = Guid.NewGuid().ToString();
            filled.CreatedOn = DateTime.UtcNow;
            filled.Deleted   = false;
            filled.UpdatedOn = DateTime.UtcNow;
            filled.Token     = token;

            returned = core.Store(filled);
            Assert.IsNotNull(returned);
            Assert.AreEqual <Guid>(filled.Id, returned.Id);

            returned.Token = token;
            TextContent updated = core.Get(returned);

            Assert.IsNotNull(updated);
            Assert.AreEqual <Guid>(filled.Id, updated.Id);
            Assert.AreEqual <bool>(filled.Active, updated.Active, "Data Mismatch");
            Assert.AreEqual <string>(filled.Content, updated.Content, "Data Mismatch");
            Assert.AreEqual <DateTime>(filled.CreatedOn.Date, updated.CreatedOn.Date, "Data Mismatch");
            Assert.AreEqual <bool>(filled.Deleted, updated.Deleted, "Data Mismatch");
            Assert.AreEqual <DateTime>(filled.UpdatedOn.Date, updated.UpdatedOn.Date, "Data Mismatch");
        }
コード例 #34
0
ファイル: TextContentProvider.cs プロジェクト: webrot/CMS
 public void ClearCategories(TextContent content)
 {
     MysqlHelper.BatchExecuteNonQuery(content.GetRepository(),
                                      dbCommands.ClearCategories(content));
 }
コード例 #35
0
 public TextContentExtensionDuck(TextContent textContent, params Type[] extentionTypes)
     : base(textContent, extentionTypes)
 {
 }
コード例 #36
0
 public virtual void ClearCategories(Repository repository, TextContent textContent)
 {
     TextContentProvider.ClearCategories(textContent);
 }
コード例 #37
0
        private void PrepareSetValues(Dictionary <string, string> initdata, TextContent content, string culture, ContentType type, ContentFolder folder, SiteDb siteDb)
        {
            List <EmbeddedBy> embeddedby = null;

            Dictionary <string, string> nonfields = new Dictionary <string, string>();

            foreach (var item in initdata)
            {
                if (type.Properties.Find(o => Kooboo.Lib.Helper.StringHelper.IsSameValue(o.Name, item.Key)) != null)
                {
                    content.SetValue(item.Key, item.Value, culture);
                }
                else
                {
                    nonfields.Add(item.Key, item.Value);
                }
            }

            siteDb.TextContent.EnsureUserKey(content);

            foreach (var item in nonfields)
            {
                Guid ValueId = Kooboo.Lib.Helper.IDHelper.GetOrParseKey(item.Value);

                var category = GetCatFolder(item.Key);
                if (category != null)
                {
                    var catitem = siteDb.TextContent.Get(ValueId);
                    if (catitem != null)
                    {
                        siteDb.ContentCategories.AddOrUpdate(new ContentCategory()
                        {
                            ContentId = content.Id, CategoryFolder = category.FolderId, CategoryId = ValueId
                        });
                    }
                }
                else
                {
                    var by = GetBY();

                    if (by.Any())
                    {
                        var beEmbedded = by.Find(o => Kooboo.Lib.Helper.StringHelper.IsSameValue(o.FolderName, item.Key));

                        if (beEmbedded == null && (item.Key.ToLower() == "parent" || item.Key.ToLower() == "parentid"))
                        {
                            beEmbedded = by.First();
                        }
                        if (beEmbedded != null)
                        {
                            var parentcontent = siteDb.TextContent.Get(ValueId);
                            if (parentcontent != null)
                            {
                                if (parentcontent.Embedded.ContainsKey(folder.Id))
                                {
                                    var list = parentcontent.Embedded[folder.Id];
                                    if (list == null)
                                    {
                                        list = new List <Guid>();
                                    }
                                    if (!list.Contains(content.Id))
                                    {
                                        list.Add(content.Id);
                                    }
                                }
                                else
                                {
                                    List <Guid> ids = new List <Guid>();
                                    ids.Add(content.Id);
                                    parentcontent.Embedded[folder.Id] = ids;
                                }

                                siteDb.TextContent.AddOrUpdate(parentcontent);
                            }
                        }
                    }
                }
            }


            List <EmbeddedBy> GetBY()
            {
                if (embeddedby == null)
                {
                    embeddedby = siteDb.ContentFolders.GetEmbeddedBy(folder.Id);
                }
                return(embeddedby);
            }

            CategoryFolder GetCatFolder(string foldername)
            {
                var category = folder.Category.Find(o => Kooboo.Lib.Helper.StringHelper.IsSameValue(o.Alias, foldername));

                if (category != null)
                {
                    return(category);
                }
                else
                {
                    foreach (var item in folder.Category)
                    {
                        var catfolder = siteDb.ContentFolders.Get(item.FolderId);
                        if (catfolder != null)
                        {
                            if (Kooboo.Lib.Helper.StringHelper.IsSameValue(catfolder.Name, foldername))
                            {
                                return(item);
                            }
                        }
                    }
                }
                return(null);
            }
        }
コード例 #38
0
        public virtual ContentBase Copy(TextContent originalContent, TextFolder textFolder, bool keepStatus, bool keepUUID, NameValueCollection values)
        {
            textFolder = textFolder.AsActual();
            var repository    = textFolder.Repository;
            var schema        = new Schema(repository, textFolder.SchemaName);
            var copyedContent = new TextContent(originalContent);

            copyedContent.Id   = "";
            copyedContent.UUID = "";
            if (keepUUID)
            {
                copyedContent.UUID = originalContent.UUID;
            }
            copyedContent.UtcCreationDate    = DateTime.Now.ToUniversalTime();
            copyedContent.Repository         = textFolder.Repository.Name;
            copyedContent.FolderName         = textFolder.FullName;
            copyedContent.SchemaName         = textFolder.SchemaName;
            copyedContent.OriginalUUID       = originalContent.UUID;
            copyedContent.OriginalRepository = originalContent.Repository;
            copyedContent.OriginalFolder     = originalContent.FolderName;
            copyedContent.IsLocalized        = false;
            copyedContent.Sequence           = 0;
            copyedContent.UserId             = originalContent.UserId;

            if (values != null)
            {
                originalContent = Binder.Bind(schema, copyedContent, values);
            }

            if (!keepStatus)
            {
                copyedContent.Published = false;
            }
            //如果没有Content event,那么在发送设置的“转发”功能就会失效。
            EventBus.Content.ContentEvent.Fire(ContentAction.PreAdd, copyedContent);


            TextContentProvider.Add(copyedContent);


            if (textFolder.Categories != null && textFolder.Categories.Count > 0)
            {
                var originalRepository = originalContent.GetRepository();
                var originalFolder     = originalContent.GetFolder().AsActual();
                var originalCategories = QueryCategories(originalRepository, originalFolder.FullName, originalContent.UUID);

                List <TextContent> categories = new List <TextContent>();

                foreach (var category in originalCategories)
                {
                    foreach (var originalCategoryContent in category.Contents)
                    {
                        foreach (var categoryFolder in textFolder.Categories)
                        {
                            var categoryContent = (new TextFolder(textFolder.Repository, categoryFolder.FolderName)).CreateQuery()
                                                  .WhereEquals("UUID", originalCategoryContent.UUID).FirstOrDefault();
                            if (categoryContent != null)
                            {
                                categories.Add(categoryContent);
                                break;
                            }
                        }
                    }
                }

                AddCategories(repository, copyedContent, categories.ToArray());
            }

            EventBus.Content.ContentEvent.Fire(ContentAction.Add, copyedContent);

            return(copyedContent);
        }
コード例 #39
0
        internal bool CheckItem(TextContent TextContent, List <Kooboo.IndexedDB.Dynamic.ConditionItem> conditions, ContentType contenttype, ContentFolder folder = null)
        {
            foreach (var item in conditions)
            {
                var col = contenttype.Properties.Find(o => o.Name == item.Field);

                if (col != null)
                {
                    var clrtype = Kooboo.Data.Helper.DataTypeHelper.ToClrType(col.DataType);

                    if (col.MultipleLanguage)
                    {
                        bool isPassed = false;
                        foreach (var cul in this.context.WebSite.Culture)
                        {
                            var value = TextContent.GetValue(col.Name, cul.Key);

                            if (value != null && FilterHelper.Check(value.ToString(), ToFilterCompare(item.Comparer), item.Value, clrtype))
                            {
                                isPassed = true;
                                break;
                            }
                        }
                        return(isPassed);
                    }
                    else
                    {
                        var value = TextContent.GetValue(col.Name);
                        if (value != null)
                        {
                            if (FilterHelper.Check(value.ToString(), ToFilterCompare(item.Comparer), item.Value, clrtype))
                            {
                                continue;
                            }
                            else
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            return(false);
                        }
                    }
                }
                else
                {
                    // TODO: Should check for category fields...
                    ///-----------------------------------------
                    if (folder != null)
                    {
                        //check category.
                        string fieldname    = item.Field;
                        string subfieldname = null;
                        var    category     = folder.Category.Find(o => o.Alias == fieldname);
                        if (category == null && fieldname.IndexOf(".") > -1)
                        {
                            var partone = fieldname.Substring(0, fieldname.IndexOf("."));
                            category = folder.Category.Find(o => o.Alias == partone);
                            if (category != null)
                            {
                                subfieldname = fieldname.Substring(fieldname.IndexOf(".") + 1);
                            }
                        }

                        if (category != null)
                        {
                            var ids = this.context.WebSite.SiteDb().ContentCategories.Query.Where(o => o.ContentId == TextContent.Id && o.CategoryFolder == category.FolderId).SelectAll().Select(o => o.CategoryId).ToList();

                            foreach (var catid in ids)
                            {
                                var catcontent = this.context.WebSite.SiteDb().TextContent.Get(catid);

                                if (catcontent != null)
                                {
                                    if (subfieldname != null)
                                    {
                                        var value = catcontent.GetValue(subfieldname);
                                        if (value != null)
                                        {
                                            if (FilterHelper.Check(value.ToString(), ToFilterCompare(item.Comparer), item.Value))
                                            {
                                                return(true);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        var value = catcontent.GetValue("UserKey");
                                        if (value != null)
                                        {
                                            if (FilterHelper.Check(value.ToString(), ToFilterCompare(item.Comparer), item.Value, typeof(string)))
                                            {
                                                return(true);
                                            }
                                        }

                                        value = catcontent.GetValue("Id");
                                        if (value != null)
                                        {
                                            if (FilterHelper.Check(value.ToString(), ToFilterCompare(item.Comparer), item.Value, typeof(Guid)))
                                            {
                                                return(true);
                                            }
                                        }


                                        value = catcontent.GetValue("name");
                                        if (value != null)
                                        {
                                            if (FilterHelper.Check(value.ToString(), ToFilterCompare(item.Comparer), item.Value, typeof(Guid)))
                                            {
                                                return(true);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    ///----------------


                    return(false);
                }
            }

            return(true);
        }
コード例 #40
0
        public async Task <ActionResult> EditPost(TextContent content)
        {
            content = await ContentService.Save(content);

            return(RedirectToRoute("Admin", new { path = content.Path, action = "edit" }));
        }
コード例 #41
0
 public TextMessage(string content, string[] mentionedList = null, string[] mentionedMobileList = null)
     : base(MessageType.Text)
 {
     Text = new TextContent(content, mentionedList, mentionedMobileList);
 }
コード例 #42
0
		public void AddWithPost_ShouldAddNewContent()
		{
            contentRepository.Stub(cr => cr.GetAll()).Return(new List<Content>().AsQueryable());
			var content = new TextContent
			{
                ParentContent = new Menu { Id = 4 }
			};

			cmsController.Add(content)
				.ReturnsRedirectToRouteResult()
				.ToController("Menu")
				.ToAction("List")
				.WithRouteValue("id", "4");

			contentRepository.AssertWasCalled(x => x.SaveOrUpdate(content));
		}
コード例 #43
0
ファイル: TextContentQuery.cs プロジェクト: nguyenhuy2911/CMS
        public static IContentQuery <TextContent> Categories(this TextContent content, string categoryFolder)
        {
            var repository = content.GetRepository();

            return(Categories(content, new TextFolder(repository, categoryFolder)));
        }
コード例 #44
0
        public void AddWithPost_should_RejectContentWithDuplicateName()
        {
            var existingContent = new List<Content>
            {
                new Menu { Id = 3, Name = "Gadget"},
                new Menu { Id = 10, Name = "Widget"},
            };

            contentRepository.Stub(cr => cr.GetAll()).Return(existingContent.AsQueryable());

            var content = new TextContent
            {
                ParentContent = new Menu { Id = 4 },
                Name = "Widget"
            };

            cmsController.Add(content)
                .ReturnsViewResult()
                .ForView("Edit")
                .WithModel<CmsViewData>()
                .AssertAreSame(content, x => x.Content);

            contentRepository.AssertWasNotCalled(x => x.SaveOrUpdate(content));
        }
コード例 #45
0
    public IEnumerator showTextUi(MainObject mainObject, bool hideOnTouchNothing, System.Action explorerButtonClick)
    {
        if (currentManinObject != null && currentManinObject.Equals(mainObject) && currentTextUIGameObject.activeSelf)
        {
            if (Debug.isDebugBuild)
            {
                Debug.Log("[DisplayTextUiController-showTextUi] show text already!");
            }
            hideTextUi();
            yield break;
        }
        currentManinObject      = mainObject;
        this.hideOnTouchNothing = hideOnTouchNothing;
        TextContent textContent  = mainObject.texts[mainObject.currentTextIndex];
        GameObject  uiGameobject = null;
        string      textui       = textContent.displayUI;

        if (loadedPrefab.ContainsKey(textui))
        {
            if (Debug.isDebugBuild)
            {
                Debug.Log("[DisplayTextUiController-showTextUi] Got uiGameobject from cache!");
            }
            uiGameobject = loadedPrefab[textui];
        }
        else
        {
            if (Debug.isDebugBuild)
            {
                Debug.Log("[DisplayTextUiController-showTextUi] Load uiGameobject from assetBundle!");
            }
            GameObject prefab = null;
            string[]   assetBundleMetaData   = textui.Split(new string[] { "/" }, System.StringSplitOptions.RemoveEmptyEntries);
            string     commonAssetBundleName = assetBundleMetaData[0];
            string     assetName             = assetBundleMetaData[1];

            yield return(AssetBundleHelper.getInstance().LoadAsset <GameObject>(commonAssetBundleName, assetName, prefabLoaded =>
            {
                prefab = prefabLoaded;
            }));

            if (prefab != null)
            {
                uiGameobject = (GameObject)GameObject.Instantiate(prefab, mainCanvas.transform, false);
                loadedPrefab.Add(textui, uiGameobject);
            }
            AddEventTriggerToButtons(uiGameobject);
        }
        if (uiGameobject != null)
        {
            currentTextUIGameObject = uiGameobject;
            // now we add eventtrigger for explorerButton
            AddEventTrigeerToExplorerButton(uiGameobject, explorerButtonClick);
            yield return(loadTextToUi(uiGameobject, textContent));

            if (Camera.main.GetComponent <CameraController_1>())
            {
                Camera.main.GetComponent <CameraController_1> ().OnShowUi();
            }
        }
    }
コード例 #46
0
ファイル: TextContentBinder.cs プロジェクト: RameshGD/CMS
        private static void ParseColumnValue(TextContent textContent, ref List<RuleViolation> violations, Column column, string value)
        {
            switch (column.DataType)
            {
                case DataType.String:
                    if (!string.IsNullOrEmpty(value) && column.Length > 0 && value.Length > column.Length)
                    {
                        value = value.Substring(0, column.Length);
                    }
                    textContent[column.Name] = value;
                    break;
                case DataType.Int:
                    int intValue;
                    if (int.TryParse(value, out intValue))
                    {
                        textContent[column.Name] = intValue;
                    }
                    else
                    {
                        violations.Add(new RuleViolation(column.Name, value, string.Format("The field {0} is a invalid int value.".Localize(), column.Name)));
                    }
                    break;
                case DataType.Decimal:
                    decimal decValue;
                    if (decimal.TryParse(value, out decValue))
                    {
                        textContent[column.Name] = decValue;
                    }
                    else
                    {
                        violations.Add(new RuleViolation(column.Name, value, string.Format("The field {0} is a invalid decimal value.".Localize(), column.Name)));
                    }
                    break;
                case DataType.DateTime:
                    DateTime dateTime;
                    if (DateTimeHelper.TryParse(value, out dateTime))
                    {
                        textContent[column.Name] = dateTime;
                    }
                    else
                    {
                        violations.Add(new RuleViolation(column.Name, value, string.Format("The field {0} is a invalid date value.".Localize(), column.Name)));
                    }
                    break;
                case DataType.Bool:

                    if (!string.IsNullOrEmpty(value))
                    {
                        value = value.Split(',').First();
                        bool boolValue;
                        if (bool.TryParse(value, out boolValue))
                        {
                            textContent[column.Name] = boolValue;
                        }
                        else
                        {
                            violations.Add(new RuleViolation(column.Name, value, string.Format("The field {0} is a invalid bool value.".Localize(), column.Name)));
                        }
                    }
                    else
                    {
                        if (!column.AllowNull)
                        {
                            textContent[column.Name] = false;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
コード例 #47
0
    	public void EditWithPost_ShouldRedirectOnSuccessfulBinding()
    	{
    		var content = new TextContent {ParentContentId = 4};

			cmsController.Add(content)
				.ReturnsRedirectToRouteResult()
				.ToController("Menu")
				.ToAction("List")
				.WithRouteValue("id", "4");
    	}
コード例 #48
0
ファイル: TextContentBinder.cs プロジェクト: RameshGD/CMS
 public virtual TextContent Bind(Schema schema, TextContent textContent, System.Collections.Specialized.NameValueCollection values)
 {
     return Bind(schema, textContent, values, false, true);
 }
コード例 #49
0
 internal static void Update_TextContent_Categories(TextContent textContent, CategoryCollection localCollection, CategoryCollection masterCollection)
 {
     // TODO: Remove objects, that are no longer available in master
 }
コード例 #50
0
        public string newPost(string blogid, string username, string password, Post post, bool publish)
        {
            ValidateUser(username, password);

            var content = new TextContent
            {
                ParentContentId = 1,
                Position = contentOrderableService.NextPosition,
                ContentTypeId = ContentType.TextContentId,
                IsActive = publish,
                Name = post.title,
                Text = post.description
            };

            contentRepository.InsertOnSubmit(content);
            contentRepository.SubmitChanges();

            return content.ContentId.ToString();
        }
コード例 #51
0
	public void PresentText(TextContent content)
	{
		_lastAdvance = Time.time;
		_currentContent = content;

		DebugMessage("Options to be shown: " + _currentContent.Options.Count);

		SpeakerName.Text = _currentContent.Speaker;
		SpeakerText.Text = _currentContent.Dialogue;

		foreach(AsvarduilButton button in AdvanceButtons)
		{
			button.ButtonText = string.Empty;
			button.TargetTint.a = 0;
		}

		int i = 0;
		foreach(DialogueOption option in _currentContent.Options)
		{
			if(string.IsNullOrEmpty(option.Text))
				continue;

		    AdvanceButtons[i].ButtonText = option.Text;
			AdvanceButtons[i].TargetTint.a = 1;
			i++;
		}

		foreach(DialogueEvent dialogueEvent in content.DialogueEvents)
		{
			DebugMessage("Firing conversation event: " + dialogueEvent.MessageName + "...");
			_dialogueController.SendMessage(dialogueEvent.MessageName, dialogueEvent.Args, SendMessageOptions.DontRequireReceiver);
		}
	}
コード例 #52
0
        public void getUpdatesTest()
        {
            // Conversation
            Conversation conversation1 = new Conversation("Konfa 1", 1);

            // Users
            IUser user1 = new User("Mr. X");
            IUser user2 = new User("Ms. Y");

            // Matching
            conversation1.MatchWithUser(user1);
            conversation1.MatchWithUser(user2);
            user1.MatchWithConversation(conversation1);
            user2.MatchWithConversation(conversation1);

            // Messages
            //  Content
            IMessageContent msgContent1 = new TextContent("Heeejoooo");
            IMessageContent msgContent2 = new TextContent("No cześć");
            IMessageContent msgContent3 = new TextContent("Co tam słychać?");
            //  Timestamps
            DateTime datetime  = DateTime.Now;
            DateTime datetime2 = datetime + TimeSpan.FromSeconds(5);
            DateTime datetime3 = datetime + TimeSpan.FromSeconds(19);
            //  Sending
            Message sentMessage1 = conversation1.AddMessage(user1, -1, msgContent1, datetime);
            Message sentMessage2 = conversation1.AddMessage(user2, 1, msgContent2, datetime2);
            Message sentMessage3 = conversation1.AddMessage(user1, 2, msgContent3, datetime3);

            // Checks
            bool hasMessage2     = false;
            bool hasMessage3     = false;
            bool hasWrongMessage = false;

            foreach (var message in conversation1.GetUpdates(1).Messages)
            {
                if (message.ID == sentMessage2.ID)
                {
                    hasMessage2 = true;
                    Assert.IsTrue(message.Author.Name == sentMessage2.Author.Name);
                    Assert.IsTrue(message.TargetId == 1);
                    Assert.IsTrue(message.Content.getData() == sentMessage2.Content.getData());
                    Assert.IsTrue(message.SentTime == sentMessage2.SentTime);
                }
                else if (message.ID == sentMessage3.ID)
                {
                    hasMessage3 = true;
                    Assert.IsTrue(message.Author.Name == sentMessage3.Author.Name);
                    Assert.IsTrue(message.Parent.ID == 2);
                    Assert.IsTrue(message.Content.getData() == sentMessage3.Content.getData());
                    Assert.IsTrue(message.SentTime == sentMessage3.SentTime);
                }
                else
                {
                    hasWrongMessage = true;
                }
            }
            Assert.IsTrue(hasMessage2);
            Assert.IsTrue(hasMessage3);
            Assert.IsFalse(hasWrongMessage);
        }
コード例 #53
0
        public void Edit_ShouldDisplayEditViewWithExistingContent()
        {
            const int contentId = 22;

            var content = new TextContent { Id = contentId };
            contentRepository.Stub(cr => cr.GetById(contentId)).Return(content);

    	    cmsController.EditText(contentId)
    	        .ReturnsViewResult()
    	        .ForView("Edit")
    	        .WithModel<CmsViewData>()
    	        .AssertAreEqual(contentId, vd => vd.Content.Id);
        }
コード例 #54
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="node"></param>
        /// <param name="mgr"></param>
        /// <returns></returns>
        public override IFeature FromXml(XmlNode node, XmlNamespaceManager mgr)
        {
            if (node != null && node.HasChildNodes)
            {
                if (node.FirstChild.Attributes.Count > 0)
                {
                    Id = node.FirstChild.Attributes["gml:id"].InnerText;
                }
            }

            var periodicDateRangeNodes = node.FirstChild.SelectNodes("periodicDateRange", mgr);

            if (periodicDateRangeNodes != null && periodicDateRangeNodes.Count > 0)
            {
                var dateRanges = new List <DateRange>();
                foreach (XmlNode periodicDateRangeNode in periodicDateRangeNodes)
                {
                    var newDateRange = new DateRange();
                    newDateRange.FromXml(periodicDateRangeNode, mgr);
                    dateRanges.Add(newDateRange);
                }
                PeriodicDateRange = dateRanges.ToArray();
            }

            var fixedDateRangeNode = node.FirstChild.SelectSingleNode("fixedDateRange", mgr);

            if (fixedDateRangeNode != null && fixedDateRangeNode.HasChildNodes)
            {
                FixedDateRange = new DateRange();
                FixedDateRange.FromXml(fixedDateRangeNode, mgr);
            }

            var featureNameNodes = node.FirstChild.SelectNodes("featureName", mgr);

            if (featureNameNodes != null && featureNameNodes.Count > 0)
            {
                var featureNames = new List <FeatureName>();
                foreach (XmlNode featureNameNode in featureNameNodes)
                {
                    var newFeatureName = new FeatureName();
                    newFeatureName.FromXml(featureNameNode, mgr);
                    featureNames.Add(newFeatureName);
                }
                FeatureName = featureNames.ToArray();
            }

            var sourceIndication = node.FirstChild.SelectSingleNode("sourceIndication", mgr);

            if (sourceIndication != null && sourceIndication.HasChildNodes)
            {
                SourceIndication = new SourceIndication();
                SourceIndication.FromXml(sourceIndication, mgr);
            }

            var textContentNodes = node.FirstChild.SelectNodes("textContent", mgr);

            if (textContentNodes != null && textContentNodes.Count > 0)
            {
                var textContents = new List <TextContent>();
                foreach (XmlNode textContentNode in textContentNodes)
                {
                    if (textContentNode != null && textContentNode.HasChildNodes)
                    {
                        var content = new TextContent();
                        content.FromXml(textContentNode, mgr);
                        textContents.Add(content);
                    }
                }
                TextContent = textContents.ToArray();
            }

            var ispsLevelNode = node.FirstChild.SelectSingleNode("ispsLevel", mgr);

            if (ispsLevelNode != null && ispsLevelNode.HasChildNodes)
            {
                IspsLevel = ispsLevelNode.FirstChild.InnerText;
            }

            var linkNodes = node.FirstChild.SelectNodes("*[boolean(@xlink:href)]", mgr);

            if (linkNodes != null && linkNodes.Count > 0)
            {
                var links = new List <Link>();
                foreach (XmlNode linkNode in linkNodes)
                {
                    var newLink = new Link();
                    newLink.FromXml(linkNode, mgr);
                    links.Add(newLink);
                }
                Links = links.ToArray();
            }

            return(this);
        }
コード例 #55
0
ファイル: TextContentBinder.cs プロジェクト: RameshGD/CMS
        private static void ValidateColumn(Schema schema, TextContent textContent, ref List<RuleViolation> violations, Column column, bool update = false)
        {
            var controlType = Kooboo.CMS.Form.Html.ControlHelper.Resolve(column.ControlType);
            if (controlType != null && controlType.IsFile == true)//ignore the file control type validations.
            {
                return;
            }
            var validations = column.GetValidations();
            foreach (var validation in validations)
            {
                switch (validation.ValidationType)
                {
                    case ValidationType.Required:
                        if (textContent[column.Name] == null || string.IsNullOrEmpty(textContent[column.Name].ToString()))
                        {
                            violations.Add(new RuleViolation(column.Name, null, string.Format(validation.ErrorMessage, column.Name)));
                        }
                        break;
                    case ValidationType.Unique:
                        var value = textContent[column.Name];

                        int hasitems = 0;
                        if ((value == null) || string.IsNullOrEmpty(value.ToString()))
                            hasitems = 1;
                        else
                        {
                            //判断数据是否已经存在
                            if (update == true)
                            {
                                hasitems = schema.CreateQuery().WhereEquals(column.Name, value)
                                                               .WhereNotEquals(Column.UUID.Name, textContent[Column.UUID.Name]).Count();
                            }
                            else
                            {
                                hasitems = schema.CreateQuery().WhereEquals(column.Name, value).Count();
                            }
                        }
                        if (hasitems > 0)
                            violations.Add(new RuleViolation(column.Name, null, string.Format(validation.ErrorMessage, column.Name)));
                        break;
                    case ValidationType.StringLength:
                        var stringLength = (StringLengthValidation)validation;
                        if (column.DataType == DataType.String && textContent[column.Name] != null)
                        {
                            var length = textContent[column.Name].ToString().Length;
                            if (length < stringLength.Min || length > stringLength.Max)
                            {
                                violations.Add(new RuleViolation(column.Name, null, string.Format(validation.ErrorMessage, column.Name)));
                            }

                        }
                        break;
                    case ValidationType.Range:
                        var rangeValidation = (RangeValidation)validation;
                        if (textContent.ContainsKey(column.Name) && textContent[column.Name] != null)
                        {
                            if ((column.DataType == DataType.Int || column.DataType == DataType.Decimal))
                            {
                                decimal decimalValue = Convert.ToDecimal(textContent[column.Name]);

                                decimal start = Convert.ToDecimal(rangeValidation.Start);
                                decimal end = Convert.ToDecimal(rangeValidation.End);

                                if (start > decimalValue || end < decimalValue)
                                {
                                    violations.Add(new RuleViolation(column.Name, null, string.Format(validation.ErrorMessage, column.Name)));
                                }

                            }
                        }
                        break;
                    case ValidationType.Regex:
                        var regexValidation = (RegexValidation)validation;
                        if (textContent.ContainsKey(column.Name) && textContent[column.Name] != null)
                        {
                            string pattern = regexValidation.Pattern;
                            if (!string.IsNullOrEmpty(pattern))
                            {
                                if (!Regex.IsMatch(textContent[column.Name].ToString(), pattern))
                                {
                                    violations.Add(new RuleViolation(column.Name, null, string.Format(validation.ErrorMessage, column.Name)));
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }
コード例 #56
0
    	public void EditWithPost_ShouldRenderViewWithError()
    	{
			contentRepository.Stub(cr => cr.GetAll()).Return(new List<Content>().AsQueryable());
			cmsController.ModelState.AddModelError("foo", "bar");

			var content = new TextContent();
			cmsController.EditText(content)
				.ReturnsViewResult()
				.WithModel<CmsViewData>()
				.AssertAreSame(content, x => x.Content);
    	}
コード例 #57
0
ファイル: TextContentBinder.cs プロジェクト: RameshGD/CMS
 public virtual TextContent Bind(Schema schema, TextContent textContent, System.Collections.Specialized.NameValueCollection values, bool thorwViolationException)
 {
     return Bind(schema, textContent, values, false, thorwViolationException);
 }
コード例 #58
0
    	public void EditWithPost_ShouldRedirectOnSuccessfulBinding()
    	{
            contentRepository.Stub(cr => cr.GetAll()).Return(new List<Content>().AsQueryable());
    		var content = new TextContent
    		{
                ParentContent = new Menu { Id = 4 }
    		};

			cmsController.Add(content)
				.ReturnsRedirectToRouteResult()
				.ToController("Menu")
				.ToAction("List")
				.WithRouteValue("id", "4");
    	}
コード例 #59
0
        /// <summary>
        /// Creates a new post.  The publish boolean is used to determine whether the item 
        /// should be published or not.
        /// </summary>
        /// <param name="blogid">The blogid.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <param name="post">The post.</param>
        /// <param name="publish">if set to <c>true</c> [publish].</param>
        /// <returns></returns>
        public string newPost(string blogid, string username, string password, Post post, bool publish)
        {
            CreateServices();

            ValidateUser(username, password);

            var parent = menuRepository.GetById(1); // hack assumes that root content has id = 1
            var content = new TextContent
            {
                ParentContent = parent,
                Position = contentOrderableService.NextPosition,
                IsActive = publish,
                Name = post.title,
                Text = post.description
            };

            contentRepository.SaveOrUpdate(content);
            unitOfWorkManager.Commit();

            return content.Id.ToString();
        }
コード例 #60
0
        public void EditWithPost_should_Fail_on_duplicate_name()
        {
            var existingContent = new List<Content>
            {
                new Menu { Id = 3, Name = "Gadget"},
                new Menu { Id = 7, Name = "OldWidget"},
                new Menu { Id = 10, Name = "Widget"},
            };

            contentRepository.Stub(cr => cr.GetAll()).Return(existingContent.AsQueryable());

            var content = new TextContent
            {
                ParentContent = new Menu { Id = 4 },
                Id = 7,
                Name = "Widget"
            };

            cmsController.EditText(content)
                .ReturnsViewResult()
                .WithModel<CmsViewData>()
                .AssertAreSame(content, x => x.Content);
        }