Example #1
0
        private static XDocument ToXDocument(Content node)
        {
            if (TypeHelper.IsTypeAssignableFrom <Document>(node))
            {
                return(new XDocument(((Document)node).Content.ToXml()));
            }

            if (TypeHelper.IsTypeAssignableFrom <global::umbraco.cms.businesslogic.media.Media>(node))
            {
                return(new XDocument(((global::umbraco.cms.businesslogic.media.Media)node).MediaItem.ToXml()));
            }

            var xDoc  = new XmlDocument();
            var xNode = xDoc.CreateNode(XmlNodeType.Element, "node", "");

            node.XmlPopulate(xDoc, ref xNode, false);

            if (xNode.Attributes["nodeTypeAlias"] == null)
            {
                //we'll add the nodeTypeAlias ourselves
                XmlAttribute d = xDoc.CreateAttribute("nodeTypeAlias");
                d.Value = node.ContentType.Alias;
                xNode.Attributes.Append(d);
            }

            return(new XDocument(ExamineXmlExtensions.ToXElement(xNode)));
        }
Example #2
0
 private void DeleteCrops(Content sender)
 {
     //Remove all cropup files
     var context = HttpContext.Current;
     if (context != null)
     {
         foreach (var alias in Settings.PropertyAliases.Split(','))
         {
             var prop = sender.getProperty(alias);
             if (prop != null && prop.Value != null)
             {
                 var umbracoFile = prop.Value.ToString();
                 var path = context.Server.MapPath(umbracoFile);
                 var filename = Path.GetFileNameWithoutExtension(path);
                 var pattern = "*.cropup.*";
                 var dir = Path.GetDirectoryName(path);
                 var files = Directory.GetFiles(dir, pattern);
                 foreach (var file in files)
                 {
                     if (File.Exists(file))
                     {
                         File.Delete(file);
                     }
                 }
             }
         }
     }
 }
Example #3
0
        /// <summary>
        /// Constructor to set default properties.
        /// </summary>
        /// <param name="c"></param>
        /// <param name="CanPublish"></param>
        /// <param name="Id"></param>
        /// <remarks>
        /// This method used to create all of the child controls too which is BAD since
        /// the page hasn't started initializing yet. Control IDs were not being named
        /// correctly, etc... I've moved the child control setup/creation to the CreateChildControls
        /// method where they are suposed to be.
        /// </remarks>
        public ContentControl(Content c, publishModes CanPublish, string Id)
        {
            ID = Id;
            this.CanPublish = CanPublish;
            _content        = c;

            Width  = 350;
            Height = 350;

            SaveAndPublish += new EventHandler(standardSaveAndPublishHandler);
            Save           += new EventHandler(standardSaveAndPublishHandler);
            prntpage        = (UmbracoEnsuredPage)Page;

            // zb-00036 #29889 : load it only once
            if (virtualTabs == null)
            {
                virtualTabs = _content.ContentType.getVirtualTabs.ToList();
            }

            foreach (ContentType.TabI t in virtualTabs)
            {
                TabPage tp = NewTabPage(t.Caption);
                addSaveAndPublishButtons(ref tp);
            }
        }
        /// <summary>
        /// Adds sub nodes to the ListControl object passed into the method, based on the Content node passed in
        /// </summary>
        /// <param name="node">The node whos sub nodes are to be added to the ListControl</param>
        /// <param name="level">The level of the current node</param>
        /// <param name="showGrandChildren">Boolean determining if grand children should be displayed as well</param>
        /// <param name="control">The ListControl the nodes must be added to</param>
        /// <param name="documentAliasFilter">String representing the documentTypeAlias that should be filtered for. If empty no filter is applied</param>
        private void addListControlNode(umbraco.cms.businesslogic.Content node, int level, bool showGrandChildren, ListControl control, string[] documentAliasFilters)
        {
            if (node.HasChildren)
            {
                //store children array here because iterating over an Array property object is very inneficient.
                var c = node.Children;
                foreach (CMSNode child in c)
                {
                    umbraco.cms.businesslogic.Content doc = new umbraco.cms.businesslogic.Content(child.Id);
                    string preText = string.Empty;

                    for (int i = 1; i < level; i++)
                    {
                        preText += "- ";
                    }

                    //Run through the filters passed in
                    if (documentAliasFilters.Length > 0)
                    {
                        foreach (string filter in documentAliasFilters)
                        {
                            string trimmedFilter = filter.TrimStart(" ".ToCharArray());
                            trimmedFilter = trimmedFilter.TrimEnd(" ".ToCharArray());

                            if (doc.ContentType.Alias == trimmedFilter || trimmedFilter == string.Empty)
                            {
                                ListItem item = new ListItem(preText + doc.Text, doc.Id.ToString());
                                if (_data.Value.ToString().Contains(doc.Id.ToString()))
                                {
                                    item.Selected = true;
                                }
                                control.Items.Add(item);
                            }
                        }
                    }
                    else
                    {
                        ListItem item = new ListItem(preText + doc.Text, doc.Id.ToString());
                        if (_data.Value.ToString().Contains(doc.Id.ToString()))
                        {
                            item.Selected = true;
                        }
                        control.Items.Add(item);
                    }

                    if (showGrandChildren)
                    {
                        addListControlNode(doc, level + 1, showGrandChildren, control, documentAliasFilters);
                    }
                }
            }
        }
Example #5
0
        private static bool HasImageCropper(Content node)
        {
            bool hasImageCropper = false;
              foreach (var p in node.GenericProperties)
              {
            if (p.PropertyType.DataTypeDefinition.DataType.ToString() == "umbraco.editorControls.imagecropper.DataType")
            {
              hasImageCropper = true;
            }
              }

              return hasImageCropper;
        }
Example #6
0
        /// <summary>
        /// Retrive a list of Content sharing the ContentType
        /// </summary>
        /// <param name="ct">The ContentType</param>
        /// <returns>A list of Content objects sharing the ContentType defined.</returns>
        public static Content[] getContentOfContentType(ContentType ct)
        {
            IRecordsReader dr = SqlHelper.ExecuteReader("Select nodeId from  cmsContent INNER JOIN umbracoNode ON cmsContent.nodeId = umbracoNode.id where ContentType = " + ct.Id + " ORDER BY umbracoNode.text ");
            System.Collections.ArrayList tmp = new System.Collections.ArrayList();

            while (dr.Read()) tmp.Add(dr.GetInt("nodeId"));
            dr.Close();

            Content[] retval = new Content[tmp.Count];
            for (int i = 0; i < tmp.Count; i++) retval[i] = new Content((int)tmp[i]);

            return retval;
        }
Example #7
0
        /// <summary>
        /// Constructor to set default properties.
        /// </summary>
        /// <param name="c"></param>
        /// <param name="CanPublish"></param>
        /// <param name="Id"></param>
        /// <remarks>
        /// This method used to create all of the child controls too which is BAD since
        /// the page hasn't started initializing yet. Control IDs were not being named
        /// correctly, etc... I've moved the child control setup/creation to the CreateChildControls
        /// method where they are suposed to be.
        /// </remarks>
        public ContentControl(Content c, publishModes CanPublish, string Id)
        {
            ID = Id;
            this.CanPublish = CanPublish;
            _content = c;

            Width = 350;
            Height = 350;

            SaveAndPublish += new EventHandler(standardSaveAndPublishHandler);
            Save += new EventHandler(standardSaveAndPublishHandler);
            prntpage = (UmbracoEnsuredPage)Page;

            // zb-00036 #29889 : load it only once
            if (virtualTabs == null)
                virtualTabs = _content.ContentType.getVirtualTabs.ToList();

            foreach (ContentType.TabI t in virtualTabs)
            {
                TabPage tp = NewTabPage(t.Caption);
                addSaveAndPublishButtons(ref tp);
            }
        }
		/// <summary>
		/// Clears any existing relations when deleting a node with a PickerRelations datatype
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="umbraco.cms.businesslogic.DeleteEventArgs"/> instance containing the event data.</param>
		private void BeforeDelete(Content sender, DeleteEventArgs e)
		{
			Guid pickerRelationsId = new Guid(DataTypeGuids.PickerRelationsId);

			// Clean up any relations

			// For each PickerRelations datatype
			foreach (Property pickerRelationsProperty in from property in sender.GenericProperties
															  where property.PropertyType.DataTypeDefinition.DataType.Id == pickerRelationsId
															  select property)
			{
				// used to identify this datatype instance - relations created are marked with this in the comment field
				string instanceIdentifier = "[\"PropertyTypeId\":" + pickerRelationsProperty.PropertyType.Id.ToString() + "]";

				// get configuration options for datatype
				PickerRelationsOptions options = ((PickerRelationsPreValueEditor)pickerRelationsProperty.PropertyType.DataTypeDefinition.DataType.PrevalueEditor).Options;

				// get relationType from options
				RelationType relationType = RelationType.GetById(options.RelationTypeId);

				if (relationType != null)
				{
					// clear all exisitng relations
					DeleteRelations(relationType, sender.Id, options.ReverseIndexing, instanceIdentifier);
				}
			}
		}
Example #9
0
        protected virtual string GetContentFromDatabase(AttributeCollectionAdapter itemAttributes, int nodeIdInt, string currentField)
        {
            var c = new Content(nodeIdInt);

            var property = c.getProperty(currentField);
            if (property == null)
                throw new ArgumentException(String.Format("Could not find property {0} of node {1}.", currentField, nodeIdInt));

            var umbItem = new item(property.Value.ToString(), itemAttributes);
            var tempElementContent = umbItem.FieldContent;

            // If the current content object is a document object, we'll only output it if it's published
            if (c.nodeObjectType == Document._objectType)
            {
                try
                {
                    var d = (Document)c;
                    if (!d.Published)
                        tempElementContent = "";
                }
                catch { }
            }

            // Add the content to the cache
            if (!string.IsNullOrEmpty(tempElementContent))
            {
                ApplicationContext.Current.ApplicationCache.InsertCacheItem(
                    string.Format("{0}{1}_{2}", CacheKeys.ContentItemCacheKey, nodeIdInt, currentField),
                    CacheItemPriority.Default, () => tempElementContent);
            }
            return tempElementContent;
        }
Example #10
0
        // add elements to the <macro> root node, corresponding to parameters
        private void AddMacroXmlNode(XmlDocument umbracoXml, XmlDocument macroXml,
            string macroPropertyAlias, string macroPropertyType, string macroPropertyValue)
        {
            XmlNode macroXmlNode = macroXml.CreateNode(XmlNodeType.Element, macroPropertyAlias, string.Empty);
            var x = new XmlDocument();

            // if no value is passed, then use the current "pageID" as value
            var contentId = macroPropertyValue == string.Empty ? UmbracoContext.Current.PageId.ToString() : macroPropertyValue;

	        TraceInfo("umbracoMacro",
	                  "Xslt node adding search start (" + macroPropertyAlias + ",'" +
	                  macroPropertyValue + "')");
            switch (macroPropertyType)
            {
                case "contentTree":
                    var nodeId = macroXml.CreateAttribute("nodeID");
                    nodeId.Value = contentId;
                    macroXmlNode.Attributes.SetNamedItem(nodeId);

                    // Get subs
                    try
                    {
                        macroXmlNode.AppendChild(macroXml.ImportNode(umbracoXml.GetElementById(contentId), true));
                    }
                    catch
                    { }
                    break;

                case "contentCurrent":
                    var importNode = macroPropertyValue == string.Empty
                        ? umbracoXml.GetElementById(contentId)
                        : umbracoXml.GetElementById(macroPropertyValue);

                    var currentNode = macroXml.ImportNode(importNode, true);

                    // remove all sub content nodes
                    foreach (XmlNode n in currentNode.SelectNodes("node|*[@isDoc]"))
                        currentNode.RemoveChild(n);

                    macroXmlNode.AppendChild(currentNode);

                    break;

                case "contentSubs": // disable that one, it does not work anyway...
                    //x.LoadXml("<nodes/>");
                    //x.FirstChild.AppendChild(x.ImportNode(umbracoXml.GetElementById(contentId), true));
                    //macroXmlNode.InnerXml = TransformMacroXml(x, "macroGetSubs.xsl");
                    break;

                case "contentAll":
                    macroXmlNode.AppendChild(macroXml.ImportNode(umbracoXml.DocumentElement, true));
                    break;

                case "contentRandom":
                    XmlNode source = umbracoXml.GetElementById(contentId);
					if (source != null)
					{
						var sourceList = source.SelectNodes("node|*[@isDoc]");
						if (sourceList.Count > 0)
						{
							int rndNumber;
							var r = library.GetRandom();
							lock (r)
							{
								rndNumber = r.Next(sourceList.Count);
							}
							var node = macroXml.ImportNode(sourceList[rndNumber], true);
							// remove all sub content nodes
							foreach (XmlNode n in node.SelectNodes("node|*[@isDoc]"))
								node.RemoveChild(n);

							macroXmlNode.AppendChild(node);
						}
						else
							TraceWarn("umbracoMacro",
									  "Error adding random node - parent (" + macroPropertyValue +
									  ") doesn't have children!");
					}
					else
						TraceWarn("umbracoMacro",
						          "Error adding random node - parent (" + macroPropertyValue +
						          ") doesn't exists!");
                    break;

                case "mediaCurrent":
                    var c = new Content(int.Parse(macroPropertyValue));
                    macroXmlNode.AppendChild(macroXml.ImportNode(c.ToXml(umbraco.content.Instance.XmlContent, false), true));
                    break;

                default:
                    macroXmlNode.InnerText = HttpContext.Current.Server.HtmlDecode(macroPropertyValue);
                    break;
            }
            macroXml.FirstChild.AppendChild(macroXmlNode);
        }
        /// <summary>
        /// Adds sub nodes to the ListControl object passed into the method, based on the Content node passed in
        /// </summary>
        /// <param name="node">The node whos sub nodes are to be added to the ListControl</param>
        /// <param name="level">The level of the current node</param>
        /// <param name="showGrandChildren">Boolean determining if grand children should be displayed as well</param>
        /// <param name="control">The ListControl the nodes must be added to</param>
        /// <param name="documentAliasFilter">String representing the documentTypeAlias that should be filtered for. If empty no filter is applied</param>
        private void addListControlNode(umbraco.cms.businesslogic.Content node, int level, bool showGrandChildren, ListControl control, string[] documentAliasFilters)
        {
            if (node.HasChildren)
            {
                //store children array here because iterating over an Array property object is very inneficient.
                var c = node.Children;
                foreach (CMSNode child in c)
                {
                    umbraco.cms.businesslogic.Content doc = new umbraco.cms.businesslogic.Content(child.Id);
                    string preText = string.Empty;

                    for (int i = 1; i < level; i++)
                    {
                        preText += "- ";
                    }

                    //Run through the filters passed in
                    if (documentAliasFilters.Length > 0)
                    {
                        foreach (string filter in documentAliasFilters)
                        {
                            string trimmedFilter = filter.TrimStart(" ".ToCharArray());
                            trimmedFilter = trimmedFilter.TrimEnd(" ".ToCharArray());

                            if (doc.ContentType.Alias == trimmedFilter || trimmedFilter == string.Empty)
                            {
                                ListItem item = new ListItem(preText + doc.Text, doc.Id.ToString());
                                if (_data.Value.ToString().Contains(doc.Id.ToString()))
                                {
                                    item.Selected = true;
                                }
                                control.Items.Add(item);
                            }
                        }
                    }
                    else
                    {
                        ListItem item = new ListItem(preText + doc.Text, doc.Id.ToString());
                        if (_data.Value.ToString().Contains(doc.Id.ToString()))
                        {
                            item.Selected = true;
                        }
                        control.Items.Add(item);
                    }

                    if (showGrandChildren)
                    {
                        addListControlNode(doc, level + 1, showGrandChildren, control, documentAliasFilters);
                    }
                }
            }
        }
Example #12
0
        private void addMacroXmlNode(XmlDocument umbracoXML, XmlDocument macroXML, String macroPropertyAlias,
                                     String macroPropertyType, String macroPropertyValue)
        {
            XmlNode macroXmlNode = macroXML.CreateNode(XmlNodeType.Element, macroPropertyAlias, string.Empty);
            var x = new XmlDocument();

            int currentID = -1;
            // If no value is passed, then use the current pageID as value
            if (macroPropertyValue == string.Empty)
            {
                var umbPage = (page)HttpContext.Current.Items["umbPageObject"];
                if (umbPage == null)
                    return;
                currentID = umbPage.PageID;
            }

	        TraceInfo("umbracoMacro",
	                  "Xslt node adding search start (" + macroPropertyAlias + ",'" +
	                  macroPropertyValue + "')");
            switch (macroPropertyType)
            {
                case "contentTree":
                    XmlAttribute nodeID = macroXML.CreateAttribute("nodeID");
                    if (macroPropertyValue != string.Empty)
                        nodeID.Value = macroPropertyValue;
                    else
                        nodeID.Value = currentID.ToString();
                    macroXmlNode.Attributes.SetNamedItem(nodeID);

                    // Get subs
                    try
                    {
                        macroXmlNode.AppendChild(macroXML.ImportNode(umbracoXML.GetElementById(nodeID.Value), true));
                    }
                    catch
                    {
                        break;
                    }
                    break;
                case "contentCurrent":
                    x.LoadXml("<nodes/>");
                    XmlNode currentNode;
                    if (macroPropertyValue != string.Empty)
                        currentNode = macroXML.ImportNode(umbracoXML.GetElementById(macroPropertyValue), true);
                    else
                        currentNode = macroXML.ImportNode(umbracoXML.GetElementById(currentID.ToString()), true);

                    // remove all sub content nodes
                    foreach (XmlNode n in currentNode.SelectNodes("node|*[@isDoc]"))
                        currentNode.RemoveChild(n);

                    macroXmlNode.AppendChild(currentNode);

                    break;
                case "contentSubs":
                    x.LoadXml("<nodes/>");
                    if (macroPropertyValue != string.Empty)
                        x.FirstChild.AppendChild(x.ImportNode(umbracoXML.GetElementById(macroPropertyValue), true));
                    else
                        x.FirstChild.AppendChild(x.ImportNode(umbracoXML.GetElementById(currentID.ToString()), true));
                    macroXmlNode.InnerXml = transformMacroXML(x, "macroGetSubs.xsl");
                    break;
                case "contentAll":
                    x.ImportNode(umbracoXML.DocumentElement.LastChild, true);
                    break;
                case "contentRandom":
                    XmlNode source = umbracoXML.GetElementById(macroPropertyValue);
					if (source != null)
					{
						XmlNodeList sourceList = source.SelectNodes("node|*[@isDoc]");
						if (sourceList.Count > 0)
						{
							int rndNumber;
							Random r = library.GetRandom();
							lock (r)
							{
								rndNumber = r.Next(sourceList.Count);
							}
							XmlNode node = macroXML.ImportNode(sourceList[rndNumber], true);
							// remove all sub content nodes
							foreach (XmlNode n in node.SelectNodes("node|*[@isDoc]"))
								node.RemoveChild(n);

							macroXmlNode.AppendChild(node);
							break;
						}
						else
							TraceWarn("umbracoMacro",
									  "Error adding random node - parent (" + macroPropertyValue +
									  ") doesn't have children!");
					}
					else
						TraceWarn("umbracoMacro",
						          "Error adding random node - parent (" + macroPropertyValue +
						          ") doesn't exists!");
                    break;
                case "mediaCurrent":
                    var c = new Content(int.Parse(macroPropertyValue));
                    macroXmlNode.AppendChild(macroXML.ImportNode(c.ToXml(content.Instance.XmlContent, false), true));
                    break;
                default:
                    macroXmlNode.InnerText = HttpContext.Current.Server.HtmlDecode(macroPropertyValue);
                    break;
            }
            macroXML.FirstChild.AppendChild(macroXmlNode);
        }
		/// <summary>
		/// Event after all properties have been saved
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void AfterSave(Content sender, SaveEventArgs e)
		{
			Guid pickerRelationsId  = new Guid(DataTypeGuids.PickerRelationsId);

			// For each PickerRelations datatype
			foreach (Property pickerRelationsProperty in from property in sender.GenericProperties
															  where property.PropertyType.DataTypeDefinition.DataType.Id == pickerRelationsId
															  select property)
			{
				// used to identify this datatype instance - relations created are marked with this in the comment field
				string instanceIdentifier = "[\"PropertyTypeId\":" + pickerRelationsProperty.PropertyType.Id.ToString() + "]";

				// get configuration options for datatype
				PickerRelationsOptions options = ((PickerRelationsPreValueEditor)pickerRelationsProperty.PropertyType.DataTypeDefinition.DataType.PrevalueEditor).Options;

				// find Picker source propertyAlias field on sender
				Property pickerProperty = sender.getProperty(options.PropertyAlias);

				if (pickerProperty != null)
				{
					// get relationType from options
					RelationType relationType = RelationType.GetById(options.RelationTypeId);

					if (relationType != null)
					{
						// validate: 1) check current type of sender matches that expected by the relationType, validation method is in the DataEditor
						uQuery.UmbracoObjectType contextObjectType = uQuery.UmbracoObjectType.Unknown;
						switch (sender.GetType().ToString())
						{
							case "umbraco.cms.businesslogic.web.Document": contextObjectType = uQuery.UmbracoObjectType.Document; break;
							case "umbraco.cms.businesslogic.media.Media": contextObjectType = uQuery.UmbracoObjectType.Media; break;
							case "umbraco.cms.businesslogic.member.Member": contextObjectType = uQuery.UmbracoObjectType.Member; break;
						}

						if (((PickerRelationsDataEditor)pickerRelationsProperty.PropertyType.DataTypeDefinition.DataType.DataEditor)
							.IsContextUmbracoObjectTypeValid(contextObjectType, relationType))
						{

							uQuery.UmbracoObjectType pickerUmbracoObjectType = uQuery.UmbracoObjectType.Unknown;

							// Get the object type expected by the associated relation type and if this datatype has been configures as a rever index
							pickerUmbracoObjectType = ((PickerRelationsDataEditor)pickerRelationsProperty.PropertyType.DataTypeDefinition.DataType.DataEditor)
														.GetPickerUmbracoObjectType(relationType);


							// clear all exisitng relations (or look to see previous verion of sender to delete changes ?)
							DeleteRelations(relationType, sender.Id, options.ReverseIndexing, instanceIdentifier);

							string pickerPropertyValue = pickerProperty.Value.ToString();

							var pickerStorageFormat = PickerStorageFormat.Csv; // Assume default of csv

                            if (xmlHelper.CouldItBeXml(pickerPropertyValue))
							{
                                pickerStorageFormat = PickerStorageFormat.Xml;
							}

							// Creating instances of Documents / Media / Members ensures the IDs are of a valid type - be quicker to check with GetUmbracoObjectType(int)
							Dictionary<int, string> pickerItems = null;
							switch (pickerUmbracoObjectType)
							{
								case uQuery.UmbracoObjectType.Document:
									switch (pickerStorageFormat)
									{
                                        case PickerStorageFormat.Csv:
											pickerItems = uQuery.GetDocumentsByCsv(pickerPropertyValue).ToNameIds();
											break;
                                        case PickerStorageFormat.Xml:
											pickerItems = uQuery.GetDocumentsByXml(pickerPropertyValue).ToNameIds();
											break;
									}

									break;
								case uQuery.UmbracoObjectType.Media:
									switch (pickerStorageFormat)
									{
                                        case PickerStorageFormat.Csv:
											pickerItems = uQuery.GetMediaByCsv(pickerPropertyValue).ToNameIds();
											break;
                                        case PickerStorageFormat.Xml:
											pickerItems = uQuery.GetMediaByXml(pickerPropertyValue).ToNameIds();
											break;
									}
									break;
								case uQuery.UmbracoObjectType.Member:
									switch (pickerStorageFormat)
									{
                                        case PickerStorageFormat.Csv:
											pickerItems = uQuery.GetMembersByCsv(pickerPropertyValue).ToNameIds();
											break;
                                        case PickerStorageFormat.Xml:
											pickerItems = uQuery.GetMembersByXml(pickerPropertyValue).ToNameIds();
											break;
									}
									break;
							}
							if (pickerItems != null)
							{
								foreach (KeyValuePair<int, string> pickerItem in pickerItems)
								{
									CreateRelation(relationType, sender.Id, pickerItem.Key, options.ReverseIndexing, instanceIdentifier);
								}
							}
						}
						else
						{
							// Error: content object type invalid with relation type
						}
					}
					else
					{
						// Error: relation type is null
					}
				}
				else
				{
					// Error: pickerProperty alias not found
				}
			}
		}
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            try
            {
                int parentNodeId = Convert.ToInt32(config[1]);
                umbraco.cms.businesslogic.Content parentNode = new umbraco.cms.businesslogic.Content(parentNodeId);
                string   documentAliasFilter  = config[2];
                string[] documentAliasFilters = documentAliasFilter.Split(",".ToCharArray());

                bool showChildren = Convert.ToBoolean(config[3]);

                string[] datavalues = _data.Value.ToString().Split(",".ToCharArray());

                switch (controlType)
                {
                case "AutoComplete":
                    setupAutoComplete(parentNodeId);
                    break;

                case "auto-suggest":
                    goto case "AutoComplete";

                case "CheckBoxList":
                    checkboxlistNodes = new CheckBoxList();
                    //checkboxlistNodes.ID = "nodes";
                    addListControlNode(parentNode, 1, showChildren, checkboxlistNodes, documentAliasFilters);
                    base.ContentTemplateContainer.Controls.Add(checkboxlistNodes);

                    break;

                case "checkbox":
                    goto case "CheckBoxList";

                case "DropDownList":
                    dropdownlistNodes = new DropDownList();
                    //dropdownlistNodes.ID = "nodes";
                    ListItem empty = new ListItem("");
                    dropdownlistNodes.Items.Add(empty);
                    addListControlNode(parentNode, 1, showChildren, dropdownlistNodes, documentAliasFilters);
                    foreach (string datavalue in datavalues)
                    {
                        dropdownlistNodes.SelectedValue = datavalue;
                    }
                    base.ContentTemplateContainer.Controls.Add(dropdownlistNodes);
                    break;

                case "dropdown":
                    goto case "DropDownList";

                case "ListBox":
                    listboxNodes = new ListBox();
                    //listboxNodes.ID = "nodes";
                    listboxNodes.SelectionMode = ListSelectionMode.Multiple;
                    listboxNodes.Width         = 300;
                    listboxNodes.Height        = 200;

                    addListControlNode(parentNode, 1, showChildren, listboxNodes, documentAliasFilters);
                    base.ContentTemplateContainer.Controls.Add(listboxNodes);
                    break;

                case "listbox":
                    goto case "ListBox";

                case "RadioButtonList":
                    radiobuttonlistNodes = new RadioButtonList();
                    radiobuttonlistNodes.AutoPostBack          = true;
                    radiobuttonlistNodes.SelectedIndexChanged += new EventHandler(radiobuttonlistNodes_SelectedIndexChanged);
                    //radiobuttonlistNodes.ID = "nodes";
                    addListControlNode(parentNode, 1, showChildren, radiobuttonlistNodes, documentAliasFilters);

                    clearRadiobuttonlist        = new Button();
                    clearRadiobuttonlist.Click += new EventHandler(clearRadiobuttonlist_Click);
                    clearRadiobuttonlist.Text   = "Clear";

                    clearRadiobuttons         = new CheckBox();
                    clearRadiobuttons.Visible = false;

                    base.ContentTemplateContainer.Controls.Add(radiobuttonlistNodes);
                    base.ContentTemplateContainer.Controls.Add(clearRadiobuttonlist);
                    base.ContentTemplateContainer.Controls.Add(clearRadiobuttons);
                    break;

                case "radiobox":
                    goto case "RadioButtonList";
                }
            }
            catch { }
        }
        public static void ReadProperties(Type contentType, Content content, object output)
        {
            foreach (PropertyInfo propInfo in contentType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    DocumentTypePropertyAttribute propAttr = Util.GetAttribute<DocumentTypePropertyAttribute>(propInfo);
                    if (propAttr == null)
                    {
                        continue; // skip this property - not part of a Document Type
                    }

                    string propertyName;
                    string propertyAlias;
                    DocumentTypeManager.ReadPropertyNameAndAlias(propInfo, propAttr, out propertyName, out propertyAlias);

                    umbraco.cms.businesslogic.property.Property property = content.getProperty(propertyAlias);

                    object value = null;
                    try
                    {
                        if (property == null)
                        {
                            value = null;
                        }
                        else if (propInfo.PropertyType.Equals(typeof(System.Boolean)))
                        {
                            if (String.IsNullOrEmpty(Convert.ToString(property.Value)) || Convert.ToString(property.Value) == "0")
                            {
                                value = false;
                            }
                            else
                            {
                                value = true;
                            }
                        }
                        else if (PropertyConvertors.ContainsKey(propInfo.PropertyType))
                        {
                            value = ContentUtil.GetInnerXml(content.Id.ToString(), propertyAlias);
                        }
                        else if (String.IsNullOrEmpty(Convert.ToString(property.Value)))
                        {
                            // if property type is string or if it's some custom type, try to get the inner xml of this property within a node.
                            if (propInfo.PropertyType == typeof(string) ||
                                PropertyConvertors.ContainsKey(propInfo.PropertyType))
                            {
                                value = ContentUtil.GetInnerXml(content.Id.ToString(), propertyAlias);
                                if (value == null && propInfo.PropertyType == typeof(string))
                                {
                                    value = string.Empty;
                                }
                            }
                            else
                            {
                                value = null;
                            }
                        }
                        else if (propInfo.PropertyType.IsGenericType &&
                                 propInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                        {
                            value = Convert.ChangeType(property.Value, Nullable.GetUnderlyingType(propInfo.PropertyType));

                            // TODO: If data type is DateTime and is nullable and is less than 1.1.1000 than set it to NULL
                        }
                        else
                        {
                            value = Convert.ChangeType(property.Value, propInfo.PropertyType);
                        }

                        if (PropertyConvertors.ContainsKey(propInfo.PropertyType))
                        {
                            value = PropertyConvertors[propInfo.PropertyType].ConvertValueWhenRead(value);
                        }

                        propInfo.SetValue(output, value, null);
                    }
                    catch (Exception exc)
                    {
                        throw new Exception(string.Format("Cannot set the value of a document type property {0}.{1} (document type: {2}) to value: '{3}' (value type: {4}). Error: {5}",
                            contentType.Name, propInfo.Name, propInfo.PropertyType.FullName,
                            value, value != null ? value.GetType().FullName : "", exc.Message));
                    }
                }
        }
Example #16
0
 public static XDocument ToXDocument(Content node, bool cacheOnly)
 {
     return(ToXDocument(node));
 }
Example #17
0
		/// <summary>
		/// Gets the field content from database instead of the published XML via the APIs.
		/// </summary>
		/// <param name="nodeIdInt">The node id.</param>
		/// <param name="currentField">The field that should be fetched.</param>
		/// <returns>The contents of the <paramref name="currentField"/> from the <paramref name="nodeIdInt"/> content object</returns>
        protected virtual string GetContentFromDatabase(AttributeCollectionAdapter itemAttributes, int nodeIdInt, string currentField)
		{
			Content c = new Content(nodeIdInt);

			Property property = c.getProperty(currentField);
			if (property == null)
				throw new ArgumentException(String.Format("Could not find property {0} of node {1}.", currentField, nodeIdInt));

			item umbItem = new item(property.Value.ToString(), itemAttributes);
			string tempElementContent = umbItem.FieldContent;

			// If the current content object is a document object, we'll only output it if it's published
			if (c.nodeObjectType == cms.businesslogic.web.Document._objectType)
			{
				try
				{
					Document d = (Document)c;
					if (!d.Published)
						tempElementContent = "";
				}
				catch { }
			}

			// Add the content to the cache
			if (!String.IsNullOrEmpty(tempElementContent))
				HttpContext.Current.Cache.Insert(String.Format("contentItem{0}_{1}", nodeIdInt.ToString(), currentField), tempElementContent);
			return tempElementContent;
		}
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            try
            {
                int parentNodeId = Convert.ToInt32(config[1]);
                umbraco.cms.businesslogic.Content parentNode = new umbraco.cms.businesslogic.Content(parentNodeId);
                string documentAliasFilter = config[2];
                string[] documentAliasFilters = documentAliasFilter.Split(",".ToCharArray());

                bool showChildren = Convert.ToBoolean(config[3]);

                string[] datavalues = _data.Value.ToString().Split(",".ToCharArray());

                switch (controlType)
                {
                    case "AutoComplete":
                        setupAutoComplete(parentNodeId);
                        break;
                    case "auto-suggest":
                        goto case "AutoComplete";
                    case "CheckBoxList":
                        checkboxlistNodes = new CheckBoxList();
                        //checkboxlistNodes.ID = "nodes";
                        addListControlNode(parentNode, 1, showChildren, checkboxlistNodes, documentAliasFilters);
                        base.ContentTemplateContainer.Controls.Add(checkboxlistNodes);

                        break;
                    case "checkbox":
                        goto case "CheckBoxList";
                    case "DropDownList":
                        dropdownlistNodes = new DropDownList();
                        //dropdownlistNodes.ID = "nodes";
                        ListItem empty = new ListItem("");
                        dropdownlistNodes.Items.Add(empty);
                        addListControlNode(parentNode, 1, showChildren, dropdownlistNodes, documentAliasFilters);
                        foreach (string datavalue in datavalues)
                        {
                            dropdownlistNodes.SelectedValue = datavalue;
                        }
                        base.ContentTemplateContainer.Controls.Add(dropdownlistNodes);
                        break;
                    case "dropdown":
                        goto case "DropDownList";
                    case "ListBox":
                        listboxNodes = new ListBox();
                        //listboxNodes.ID = "nodes";
                        listboxNodes.SelectionMode = ListSelectionMode.Multiple;
                        listboxNodes.Width = 300;
                        listboxNodes.Height = 200;

                        addListControlNode(parentNode, 1, showChildren, listboxNodes, documentAliasFilters);
                        base.ContentTemplateContainer.Controls.Add(listboxNodes);
                        break;
                    case "listbox":
                        goto case "ListBox";
                    case "RadioButtonList":
                        radiobuttonlistNodes = new RadioButtonList();
                        radiobuttonlistNodes.AutoPostBack = true;
                        radiobuttonlistNodes.SelectedIndexChanged += new EventHandler(radiobuttonlistNodes_SelectedIndexChanged);
                        //radiobuttonlistNodes.ID = "nodes";
                        addListControlNode(parentNode, 1, showChildren, radiobuttonlistNodes, documentAliasFilters);

                        clearRadiobuttonlist = new Button();
                        clearRadiobuttonlist.Click += new EventHandler(clearRadiobuttonlist_Click);
                        clearRadiobuttonlist.Text = "Clear";

                        clearRadiobuttons = new CheckBox();
                        clearRadiobuttons.Visible = false;

                        base.ContentTemplateContainer.Controls.Add(radiobuttonlistNodes);
                        base.ContentTemplateContainer.Controls.Add(clearRadiobuttonlist);
                        base.ContentTemplateContainer.Controls.Add(clearRadiobuttons);
                        break;
                    case "radiobox":
                        goto case "RadioButtonList";
                }
            }
            catch { }
        }
Example #19
0
		public static XDocument ToXDocument(Content node, bool cacheOnly)
		{			
			return ToXDocument(node);
		}
Example #20
0
		private static XDocument ToXDocument(Content node)
		{
            if (TypeHelper.IsTypeAssignableFrom<Document>(node))
            {
                return new XDocument(((Document) node).Content.ToXml());
            }

            if (TypeHelper.IsTypeAssignableFrom<global::umbraco.cms.businesslogic.media.Media>(node))
            {
                return new XDocument(((global::umbraco.cms.businesslogic.media.Media) node).MediaItem.ToXml());
            }

			var xDoc = new XmlDocument();
			var xNode = xDoc.CreateNode(XmlNodeType.Element, "node", "");
			node.XmlPopulate(xDoc, ref xNode, false);

			if (xNode.Attributes["nodeTypeAlias"] == null)
			{
				//we'll add the nodeTypeAlias ourselves                                
				XmlAttribute d = xDoc.CreateAttribute("nodeTypeAlias");
				d.Value = node.ContentType.Alias;
				xNode.Attributes.Append(d);
			}

			return new XDocument(ExamineXmlExtensions.ToXElement(xNode));
		}
Example #21
0
        private void SetDescription(Content content, bool hasLowKarma, ref bool hasAnchors)
        {
            content.getProperty("description").Value = tb_desc.Text;

            // Filter out links when karma is low, probably a spammer
            if (hasLowKarma)
            {
                var doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(tb_desc.Text);

                var anchorNodes = doc.DocumentNode.SelectNodes("//a");
                if (anchorNodes != null)
                {
                    hasAnchors = true;

                    foreach (var anchor in anchorNodes)
                        anchor.ParentNode.RemoveChild(anchor, true);
                }

                content.getProperty("description").Value = doc.DocumentNode.OuterHtml;
            }
        }