private void InitTitle() { ItemDefinition definition = Definitions.GetDefinition(ie.CurrentItemType); string definitionTitle = GetGlobalResourceString("Definitions", definition.Discriminator + ".Title") ?? definition.Title; if (ie.CurrentItem.ID == 0 && !ie.CurrentItem.VersionOf.HasValue) { string format = GetLocalResourceString("EditPage.TitleFormat.New", "New \"{0}\""); string template = Request["template"]; if (!string.IsNullOrEmpty(template)) { var info = Engine.Resolve <ITemplateAggregator>().GetTemplate(definition.ItemType, template); definitionTitle = info.Title; } Title = string.Format(format, definitionTitle); } else { string format = GetLocalResourceString("EditPage.TitleFormat.Update", "Edit \"{0}\""); Title = string.Format(format, string.IsNullOrEmpty(ie.CurrentItem.Title) ? definitionTitle : ie.CurrentItem.Title); } Items["HelpText"] = definition.HelpText; Items["EditingInstructions"] = definition.EditingInstructions; }
private ContentItem SaveAsMaster(ContentItem item, IDictionary <string, Control> addedEditors, IPrincipal user) { using (ITransaction tx = persister.Repository.BeginTransaction()) { ContentItem itemToUpdate = item.VersionOf; if (itemToUpdate == null) { throw new ArgumentException("Expected the current item to be a version of another item.", "item"); } if (ShouldCreateVersionOf(item)) { SaveVersion(itemToUpdate); } DateTime?published = itemToUpdate.Published; bool wasUpdated = UpdateItem(definitions.GetDefinition(itemToUpdate.GetContentType()), itemToUpdate, addedEditors, user).Length > 0; if (wasUpdated || IsNew(itemToUpdate)) { itemToUpdate.Published = published ?? Utility.CurrentTime(); stateChanger.ChangeTo(itemToUpdate, ContentState.Published); persister.Save(itemToUpdate); } tx.Commit(); OnItemSaved(new ItemEventArgs(itemToUpdate)); return(item.VersionOf); } }
private void InitTitle() { // get item title with fallback to definition title string caption = ie.CurrentItem.Title; if (string.IsNullOrEmpty(caption)) { ItemDefinition definition = Definitions.GetDefinition(ie.CurrentItemType); caption = GetGlobalResourceString("Definitions", definition.Discriminator + ".Title") ?? definition.Title; string template = Request["template"]; if (!string.IsNullOrEmpty(template)) { var info = Engine.Resolve <ITemplateAggregator>().GetTemplate(definition.ItemType, template); caption = info.Title; } } else { caption = '"' + caption + '"'; } string format = CreatingNew ? GetLocalResourceString("EditPage.TitleFormat.New", "New {0}") : GetLocalResourceString("EditPage.TitleFormat.Update", "Edit {0}"); Title = string.Format(format, caption); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); ParentItemDefinition = Definitions.GetDefinition(ActualItem.GetContentType()); if (!IsPostBack) { LoadZones(); } ZoneName = rblZone.SelectedValue; }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); ParentItemDefinition = Definitions.GetDefinition(ActualItem); if (!IsPostBack) { LoadZones(); } ZoneName = GetSelectedZone(); }
public IEnumerable <DiscriminatorCount> FindDescendantDiscriminators(ContentItem ancestor) { var discriminators = new Dictionary <string, int>(); if (ancestor != null) { var exploredList = new List <ContentItem>(); var exploreList = new Queue <ContentItem>(); exploreList.Enqueue(ancestor); while (exploreList.Count > 0) { var current = exploreList.Dequeue(); if (exploredList.Contains(current)) { continue; } exploredList.Add(current); var discriminator = definitions.GetDefinition(current).Discriminator; if (discriminators.ContainsKey(discriminator)) { discriminators[discriminator]++; } else { discriminators.Add(discriminator, 1); } foreach (var child in current.Children) { exploreList.Enqueue(child); } } } else { foreach (var discriminator in AllContentItems.Select(current => definitions.GetDefinition(current).Discriminator)) { if (discriminators.ContainsKey(discriminator)) { discriminators[discriminator]++; } else { discriminators.Add(discriminator, 1); } } } return(discriminators.Select(x => new DiscriminatorCount { Count = x.Value, Discriminator = x.Key }).OrderByDescending(dc => dc.Count)); }
protected virtual void OnItemCreating(ItemEventArgs e) { EventHandler <ItemEventArgs> handler = base.Events[EventItemCreating] as EventHandler <ItemEventArgs>; if (handler != null) { handler.Invoke(this, e); } if (e.AffectedItem != null) { IDefinitionManager definitions = Engine.Definitions; ISecurityManager security = Engine.SecurityManager; ContentActivator activator = Engine.Resolve <ContentActivator>(); ItemDefinition parentDefinition = definitions.GetDefinition(parentItem); if (parentDefinition.IsChildAllowed(definitions, parentItem, parentDefinition)) { e.AffectedItem = Engine.Resolve <ContentActivator>().CreateInstance(parentItem.GetContentType(), parentItem); return; } foreach (ItemDefinition definition in definitions.GetAllowedChildren(parentItem, null).WhereAuthorized(security, HttpContext.Current.User, parentItem)) { e.AffectedItem = activator.CreateInstance(definition.ItemType, parentItem); return; } throw new N2.Definitions.NoItemAllowedException(parentItem); } }
public ActionResult Create(string name, int width, int depth, string discriminator, string background) { var definition = definitions.GetDefinition(discriminator); if (background == "on") { Interlocked.Add(ref remainingItems, Enumerable.Range(0, depth).Select(d => (int)Math.Pow(width, d)).Sum()); Engine.Resolve <IWorker>().DoWork(() => { CreateChildren(CurrentPage, definition.ItemType, name, width, depth, true, (n) => { Interlocked.Decrement(ref remainingItems); }); }); return(RedirectToParentPage()); } else { CreateChildren(CurrentPage, definition.ItemType, name, width, depth, true, (n) => { HttpContext.Response.Write(n + " 0-" + width + " (" + depth + ")" + "<br/>"); HttpContext.Response.Flush(); }); return(Content("<script type='text/javascript'>window.location = '" + CurrentPage.Url + "'</script>")); } }
/// <summary>Generates subclasses nhibernate xml configuration as an alternative to NHibernate definition file and adds them to the configuration.</summary> /// <param name="cfg">The nhibernate configuration to build.</param> protected virtual void GenerateMappings(NHibernate.Cfg.Configuration cfg) { Debug.Write("Adding"); StringBuilder mappings = new StringBuilder(mappingStartTag); var allTypes = definitions.GetDefinitions() .Select(d => d.ItemType) .SelectMany(t => Utility.GetBaseTypesAndSelf(t)) .Distinct() .OrderBy(t => Utility.GetBaseTypes(t).Count()) .Where(t => t.IsSubclassOf(typeof(ContentItem))) .ToList(); foreach (var type in allTypes) { string discriminator = type.Name; var definition = definitions.GetDefinition(type); if (definition != null) { discriminator = definition.Discriminator ?? discriminator; } string classMapping = generator.GetMapping(type, type.BaseType, discriminator); mappings.Append(classMapping); } mappings.Append(mappingEndTag); cfg.AddXml(FormatMapping(mappings.ToString())); }
/// <summary>Checks the root node in the database. Throws an exception if there is something really wrong with it.</summary> /// <returns>A diagnostic string about the root node.</returns> public string CheckRootItem() { int rootID = host.DefaultSite.RootItemID; ContentItem rootItem = persister.Get(rootID); if (rootItem != null) { return(String.Format("Root node OK, id: {0}, name: {1}, type: {2}, discriminator: {3}, published: {4} - {5}", rootItem.ID, rootItem.Name, rootItem.GetContentType(), definitions.GetDefinition(rootItem.GetContentType()), rootItem.Published, rootItem.Expires)); } else { return("No root item found with the id: " + rootID); } }
protected virtual void WriteDefaultAttributes(ElementWriter itemElement, ContentItem item) { if (itemElement == null) { throw new ArgumentNullException("itemElement"); } if (item == null) { throw new ArgumentNullException("item"); } itemElement.WriteAttribute("id", item.ID); itemElement.WriteAttribute("name", item.ID.ToString() == item.Name ? "" : item.Name); if (item.Parent != null) { if (item.Parent.ID != 0) { itemElement.WriteAttribute("parent", item.Parent.ID.ToString()); } else { itemElement.WriteAttribute("parent", item.Parent.VersionOf.ID.ToString()); if (item.Parent.GetVersionKey() != null) { itemElement.WriteAttribute("parentVersionKey", item.Parent.GetVersionKey()); } } } itemElement.WriteAttribute("title", item.Title); itemElement.WriteAttribute("zoneName", item.ZoneName); itemElement.WriteAttribute("templateKey", item.TemplateKey); if (item.TranslationKey.HasValue) { itemElement.WriteAttribute("translationKey", item.TranslationKey.Value); } itemElement.WriteAttribute("state", (int)item.State); itemElement.WriteAttribute("created", item.Created); itemElement.WriteAttribute("updated", item.Updated); itemElement.WriteAttribute("published", item.Published); itemElement.WriteAttribute("expires", item.Expires); itemElement.WriteAttribute("sortOrder", item.SortOrder); itemElement.WriteAttribute("url", parser == null ? item.Url : (string)parser.BuildUrl(item)); itemElement.WriteAttribute("visible", item.Visible); itemElement.WriteAttribute("savedBy", item.SavedBy); itemElement.WriteAttribute("typeName", SerializationUtility.GetTypeAndAssemblyName(item.GetContentType())); itemElement.WriteAttribute("discriminator", definitions.GetDefinition(item).Discriminator); itemElement.WriteAttribute("versionIndex", item.VersionIndex); itemElement.WriteAttribute("ancestralTrail", item.AncestralTrail); itemElement.WriteAttribute("alteredPermissions", (int)item.AlteredPermissions); itemElement.WriteAttribute("childState", (int)item.ChildState); if (item.VersionOf.HasValue) { Debug.Assert(item.VersionOf.ID != null, "item.VersionOf.ID != null"); itemElement.WriteAttribute("versionOf", item.VersionOf.ID.Value); } }
protected virtual ItemDefinition FindDefinition(Dictionary <string, string> attributes) { var definition = definitions.GetDefinition(attributes["discriminator"]); if (definition == null) { throw new DefinitionNotFoundException(string.Format("No definition found for '{0}' with name '{1}' and discriminator '{2}'", attributes["title"], attributes["name"], attributes["discriminator"]), attributes); } return(definition); }
public IEnumerable <TranslateSpecification> GetEditTranslations(ContentItem item, bool includeCurrent, bool generateNonTranslated) { ILanguage itemlanguage = GetLanguage(item); if (itemlanguage == null) { yield break; } IEnumerable <ContentItem> translations = FindTranslations(item); IEnumerable <ILanguage> languages = GetAvailableLanguages(); var itemSite = host.GetSite(item); foreach (ILanguage language in languages) { if (language != itemlanguage || includeCurrent) { ContentItem translation = GetTranslation(translations, language); if (translation == null && language == itemlanguage) { translation = item; } ItemDefinition definition = definitions.GetDefinition(item); if (translation != null) { string url = editUrlManager.GetEditExistingItemUrl(translation); yield return(new TranslateSpecification(url, language, translation, definition, host.GetSite(translation))); } else { ContentItem translatedParent = GetTranslatedParent(item, language); if (translatedParent == null) { if (generateNonTranslated) { yield return(new TranslateSpecification("#", language, translation, definition, host.GetSite(language as ContentItem)) { IsTranslatable = false }); } continue; } Url url = editUrlManager.GetEditNewPageUrl(translatedParent, definition, item.ZoneName, CreationPosition.Below); url = url.AppendQuery(TranslationKey, item.TranslationKey ?? item.ID); yield return(new TranslateSpecification(url, language, translation, definition, host.GetSite(translatedParent))); } } } }
public ActionResult Random(string name, int amount, string discriminator) { var definition = definitions.GetDefinition(discriminator); List <ContentItem> created = new List <ContentItem> { CurrentPage }; Random r = new Random(); for (int i = 0; i < amount; i++) { var child = Create(created[r.Next(created.Count)], definition.ItemType, name, 1, i); Engine.Persister.Save(child); created.Add(child); HttpContext.Response.Write(name + " " + i + "<br/>"); HttpContext.Response.Flush(); } return(Content("<script type='text/javascript'>window.location = '" + CurrentPage.Url + "'</script>")); }
public virtual TemplateDefinition GetTemplate(string discriminatorWithTemplateKey) { if (discriminatorWithTemplateKey == null) { return(null); } var pair = discriminatorWithTemplateKey.Split('/'); var definition = definitions.GetDefinition(pair[0]); return(GetTemplate(definition.ItemType, pair.Length > 1 ? pair[1] : null)); }
private TemplateDefinition GetTemplate(string discriminator, string templateName) { return(templates.GetTemplate(definitions.GetDefinition(discriminator).ItemType, templateName)); //foreach (ItemDefinition definition in definitions.GetDefinitions()) //{ // if (definition.Discriminator == discriminator) // { // return definition; // } //} //throw new N2Exception("Definition not found: " + discriminator); }
private void InitTitle() { if (ie.CurrentItem.ID == 0) { ItemDefinition definition = Definitions.GetDefinition(ie.CurrentItemType); string definitionTitle = GetGlobalResourceString("Definitions", definition.Discriminator + ".Title") ?? definition.Title; string format = GetLocalResourceString("EditPage.TitleFormat.New", "New \"{0}\""); string template = Request["template"]; if (!string.IsNullOrEmpty(template)) { var info = Definitions.GetTemplate(definition.ItemType, template); definitionTitle = info.Title; } Title = string.Format(format, definitionTitle); } else { string format = GetLocalResourceString("EditPage.TitleFormat.Update", "Edit \"{0}\""); Title = string.Format(format, ie.CurrentItem.Title); } }
public void WriteTitleBar(TextWriter writer, ContentItem item, string returnUrl) { var definition = definitions.GetDefinition(item); writer.Write("<div class='titleBar "); writer.Write(definition.Discriminator); writer.Write("'>"); WriteCommand(writer, "Edit part", "command edit n2-icon-edit-sign", Url.Parse(managementUrls.GetEditExistingItemUrl(item)).AppendQuery("returnUrl", returnUrl).Encode()); WriteCommand(writer, "Delete part", "command delete n2-icon-trash", Url.Parse(managementUrls.GetDeleteUrl(item)).AppendQuery("returnUrl", returnUrl).Encode()); WriteTitle(writer, definition); writer.Write("</div>"); }
public string GetDiscriminator(Type value) { if (value == null) { throw new ArgumentNullException("value"); } ItemDefinition definition = definitions.GetDefinition(value); if (definition == null) { throw new ArgumentException("Could not find the definition associated with the type '" + value.FullName + "'. Please ensure this is a non-abstract class deriving from N2.ContentItem and that it is decorated by the [Definition] attribute."); } return(definition.Discriminator); }
protected virtual ItemDefinition FindDefinition(Dictionary <string, string> attributes) { var discriminator = attributes.ContainsKey("discriminator") ? attributes["discriminator"] : null; var title = attributes.ContainsKey("title") ? attributes["title"] : null; var name = attributes.ContainsKey("name") ? attributes["name"] : null; if (discriminator != null) { var definition = definitions.GetDefinition(discriminator); if (definition != null) { return(definition); } } throw new DefinitionNotFoundException(string.Format("No definition found for '{0}' with name '{1}' and discriminator '{2}'", title, name, discriminator), attributes); }
private void IncrementDiscriminatorCount(Dictionary <Type, DiscriminatorCount> counts, ContentItem item) { DiscriminatorCount count; if (counts.TryGetValue(item.GetContentType(), out count)) { count.Count++; } else { counts[item.GetContentType()] = count = new DiscriminatorCount { Discriminator = definitions.GetDefinition(item).Discriminator, Count = 1 } }; } }
public IEnumerable <IndexableContent> Extract(ContentItem item) { foreach (var indexable in definitions.GetDefinition(item).NamedOperators.OfType <IIndexableProperty>()) { if (indexable.IsIndexable) { yield return new IndexableContent { Name = indexable.Name, TextContent = indexable.GetIndexableText(item) } } ; } } #endregion }
public IEnumerable <IndexableField> Extract(ContentItem item) { foreach (var indexable in definitions.GetDefinition(item).NamedOperators.OfType <IIndexableProperty>()) { if (indexable.IsIndexable) { yield return new IndexableField { Name = indexable.Name, Value = indexable.GetIndexableText(item), Analyzed = true, Stored = false } } ; } } #endregion }
public void Write(ContentItem item, System.Xml.XmlTextWriter writer) { using (ElementWriter propertiesElement = new ElementWriter("properties", writer)) { foreach (var persistable in definitions.GetDefinition(item).NamedOperators.OfType <PersistableAttribute>()) { string name = ((IUniquelyNamed)persistable).Name; object value = item[name]; if (value == null) { continue; } using (ElementWriter detailElement = new ElementWriter("property", writer)) { detailElement.WriteAttribute("name", name); Type type = value.GetType(); if (type == typeof(string)) { Write(detailElement, type, (string)value, true); } else if (type == typeof(short) || type == typeof(int) || type == typeof(long) || type == typeof(double) || type == typeof(decimal)) { Write(detailElement, type, value.ToString(), false); } else if (type == typeof(DateTime)) { Write(detailElement, type, SerializationUtility.ToUniversalString(((DateTime)value)), false); } else if (type.IsEnum) { Write(detailElement, type, ((int)value).ToString(), false); } else if (typeof(ContentItem).IsAssignableFrom(type)) { Write(detailElement, typeof(ContentItem), (((ContentItem)value).ID).ToString(), false); } else { Write(detailElement, typeof(object), SerializationUtility.ToBase64String(value), false); } } } } }
protected override IEnumerable <ContentDetail> GetDetails(ContentItem item) { ItemDefinition definition = definitions.GetDefinition(item); foreach (ContentDetail detail in item.Details.Values) { foreach (IEditable editable in definition.Editables) { if (detail.Name == editable.Name) { yield return(detail); break; } } } }
protected virtual void WriteDefaultAttributes(ElementWriter itemElement, ContentItem item) { itemElement.WriteAttribute("id", item.ID); itemElement.WriteAttribute("name", item.ID.ToString() == item.Name ? "" : item.Name); itemElement.WriteAttribute("parent", item.Parent != null ? item.Parent.ID.ToString() : string.Empty); itemElement.WriteAttribute("title", item.Title); itemElement.WriteAttribute("zoneName", item.ZoneName); itemElement.WriteAttribute("created", item.Created); itemElement.WriteAttribute("updated", item.Updated); itemElement.WriteAttribute("published", item.Published); itemElement.WriteAttribute("expires", item.Expires); itemElement.WriteAttribute("sortOrder", item.SortOrder); itemElement.WriteAttribute("url", parser.BuildUrl(item)); itemElement.WriteAttribute("visible", item.Visible); itemElement.WriteAttribute("savedBy", item.SavedBy); itemElement.WriteAttribute("typeName", SerializationUtility.GetTypeAndAssemblyName(item.GetContentType())); itemElement.WriteAttribute("discriminator", definitions.GetDefinition(item.GetContentType()).Discriminator); }
public void IsCheckedForSecurity(string userInterface, bool useVersion) { DynamicPermissionMap.SetRoles(item, Permission.Read, "None"); if (useVersion) item = MakeVersion(item); var context = new CommandContext(definitions.GetDefinition(item.GetContentType()), item, userInterface, CreatePrincipal("someone"), new NullBinder<CommandContext>(), new NullValidator<CommandContext>()); var command = CreateCommand(context); dispatcher.Execute(command, context); Assert.That(context.ValidationErrors.Count, Is.EqualTo(1)); Assert.That(context.ValidationErrors.First().Name, Is.EqualTo("Unauthorized")); }
public void WriteTitleBar(TextWriter writer, ContentItem item, string returnUrl) { var definition = definitions.GetDefinition(item); writer.Write("<div class='titleBar "); writer.Write(definition.Discriminator); writer.Write("'>"); string editUrl = Url.Parse(managementUrls.GetEditExistingItemUrl(item)).AppendQuery("returnUrl", returnUrl).Encode(); WriteTitle(writer, definition, editUrl); writer.Write("<span class='commands'>"); WriteCommand(writer, "Delete part", "command delete", "fa fa-trash-o", Url.Parse(managementUrls.GetDeleteUrl(item)).AppendQuery("returnUrl", returnUrl).Encode()); WriteCommand(writer, "Edit part", "command edit", "fa fa-pencil-square", editUrl); WriteCommand(writer, "Move part", "command move", "fa fa-arrows", "#"); writer.Write("</span>"); writer.Write("</div>"); }
private TemplateDefinition CreateTemplateInfo(ContentItem template) { var clone = template.Clone(true); clone.SetDetail(TemplateDescription, null, typeof(string)); clone.Title = ""; clone.Name = null; clone["TemplateName"] = template.Name; var info = new TemplateDefinition { Name = template.Name, Title = template.Title, Description = template.GetDetail(TemplateDescription, ""), TemplateUrl = template.Url, Definition = definitions.GetDefinition(template.GetContentType()).Clone(), Template = clone, Original = template }; info.Definition.Template = template.Name; return(info); }
public void Write(ContentItem item, System.Xml.XmlTextWriter writer) { using (ElementWriter propertiesElement = new ElementWriter("properties", writer)) { foreach (var persistable in definitions.GetDefinition(item).NamedOperators.OfType <PersistableAttribute>()) { string name = ((IUniquelyNamed)persistable).Name; object value = item[name]; if (value == null) { continue; } WriteProperty(writer, name, value); } //foreach (var property in item.GetContentType().GetProperties().Where(pi => pi.IsInterceptable())) //{ // WriteProperty(writer, property.Name, item[property.Name]); //} } }