private DocumentType UpdateAllowedTemplates(DocumentType documentType)
        {
            var tmp = new ArrayList();

            foreach (ListItem li in templateList.Items)
            {
                if (li.Selected)
                    tmp.Add(new cms.businesslogic.template.Template(int.Parse(li.Value)));
            }

            var tt = new cms.businesslogic.template.Template[tmp.Count];
            for (int i = 0; i < tt.Length; i++)
            {
                tt[i] = (cms.businesslogic.template.Template)tmp[i];
            }

            documentType.allowedTemplates = tt;

            if (documentType.allowedTemplates.Length > 0 && ddlTemplates.SelectedIndex >= 0)
            {
                documentType.DefaultTemplate = int.Parse(ddlTemplates.SelectedValue);
            }
            else
            {
                documentType.RemoveDefaultTemplate();
            }

            _dt = documentType;

            return documentType;
        }
Esempio n. 2
0
        public void Document_Delete_Heirarchy_Permanently()
        {
            var docList = new List<Document>();
            var total = 20;
            var dt = new DocumentType(GetExistingDocTypeId());
            //allow the doc type to be created underneath itself
            dt.AllowedChildContentTypeIDs = new int[] { dt.Id };
            dt.Save();

            //create 20 content nodes underneath each other, this will test deleting with heirarchy as well
            var lastParentId = -1;
            for (var i = 0; i < total; i++)
            {
                var newDoc = Document.MakeNew(i.ToString() + Guid.NewGuid().ToString("N"), dt, m_User, lastParentId);
                docList.Add(newDoc);
                Assert.IsTrue(docList[docList.Count - 1].Id > 0);
                lastParentId = newDoc.Id;
            }

            //now delete all of them permanently, since they are nested, we only need to delete one
            docList.First().delete(true);

            //make sure they are all gone
            foreach (var d in docList)
            {
                Assert.IsFalse(Document.IsNode(d.Id));
            }
            
        }
        public DataTable GetRelations(object id)
        {
            var currentDocType = new DocumentType(int.Parse(id.ToString()));

            var templates = currentDocType.allowedTemplates;

            return UmbracoObject.Template.ToDataTable(templates);
        }
        private static void LoadAllowedContentTypeChildrenIds(DocumentType nativeDocumentType, UmbracoDocumentType documentType)
        {
            documentType.AllowedContentTypeChildrenIds = new int[nativeDocumentType.AllowedChildContentTypeIDs.Count()];

            for (var idx = 0; idx < nativeDocumentType.AllowedChildContentTypeIDs.Count(); idx++)
            {
                documentType.AllowedContentTypeChildrenIds[idx] = nativeDocumentType.AllowedChildContentTypeIDs[idx];
            }
        }
Esempio n. 5
0
 public static string GetPath(DocumentType dt)
 {
     if (dt.MasterContentType != 0)
     {
         var parent = new DocumentType(dt.MasterContentType);
         return GetPath(parent) + "/" + dt.Alias;
     }
     return dt.Alias;
 }
        public SynchronizeTemplateFieldsTask(UmbracoDataContext context, XmlElement[] input, DocumentType container)
        {
            _context = context;
            _input = input;
            _container = container;
            _datatypes = DataTypeDefinition.GetAll().ToDictionary(dt => dt.Text);

            _tabIds = _context.cmsTabs.ToDictionary(t => DataHelper.GetPath(_context, t), t => t.id);
        }
 /// <summary>Create or get document if exist.</summary>
 public static Document CreateOrGetDocument(string newName, DocumentType newType, Document parent)
 {
     // Get document and validate existence.
     var cmsDocument = GetDocumentsByParentAndName(parent, newName, true).FirstOrDefault();
     if(cmsDocument != null) {
     return cmsDocument;
     } else {
     // Create document.
     return Document.MakeNew(newName, newType, parent.User, parent.Id);
     }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            _dt = new DocumentType(int.Parse(Request.QueryString["id"]));
            if (!Page.IsPostBack)
            {
                BindTemplates();

                ClientTools
                    .SetActiveTreeType(TreeDefinitionCollection.Instance.FindTree<loadNodeTypes>().Tree.Alias)
                     .SyncTree("-1,init," + _dt.Path.Replace("-1,", ""), false);
            }
        }
        /// <summary>
        /// Gets a document type, based on its id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public virtual UmbracoDocumentType GetById(int id)
        {
            var nativeDocumentType = new DocumentType(id);
            var documentType = new UmbracoDocumentType { Name = nativeDocumentType.Alias };

            LoadParentId(nativeDocumentType, documentType);
            LoadChildrenIds(nativeDocumentType, documentType);
            LoadAllowedContentTypeChildrenIds(nativeDocumentType, documentType);
            LoadPropertyTypes(nativeDocumentType, documentType);

            return documentType;
        }
Esempio n. 10
0
        private DocumentTypeItem BuildDocumentTypeItem(DocumentType documentType)
        {
            var documentTypeItem = new DocumentTypeItem();
            documentTypeItem.Alias = documentType.Alias;
            documentTypeItem.Id = documentType.Id;
            documentTypeItem.ParentId = documentType.MasterContentType;
            documentTypeItem.Text = documentType.Text;
            documentTypeItem.Description = documentType.Description;

            foreach (var property in documentType.PropertyTypes)
                documentTypeItem.Properties.Add(this.BuildPropertyTypeItem(property));

            return documentTypeItem;
        }
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			

			if (!(Page.Request.CurrentExecutionFilePath ?? string.Empty).Contains("editContent.aspx"))
				return;

			_dlTemplates = new DropDownList();

			var useDefaultText = library.GetDictionaryItem("UseDefault");
			if (string.IsNullOrEmpty(useDefaultText))
			{
				useDefaultText = "Use Default";
			}

			int currentId;

			int.TryParse(Page.Request.QueryString["id"], out currentId);


			if (currentId != 0)
			{
				var document = new Document(currentId);

				documentType = DocumentType.GetByAlias(document.ContentType.Alias);
			}

			_dlTemplates.Items.Add(new ListItem(useDefaultText, "0"));

			if (documentType != null)
			{
				foreach (var template in documentType.allowedTemplates)
				{
					_dlTemplates.Items.Add(new ListItem(template.Text, template.Id.ToString(CultureInfo.InvariantCulture)));
				}
			}
			else
			{
				foreach (var template in umbraco.cms.businesslogic.template.Template.GetAllAsList())
				{
					_dlTemplates.Items.Add(new ListItem(template.Text, template.Id.ToString(CultureInfo.InvariantCulture)));
				}
			}

			if (_data != null) _dlTemplates.SelectedValue = _data.Value.ToString();

			if (ContentTemplateContainer != null) ContentTemplateContainer.Controls.Add(_dlTemplates);
		}
 public override Node CreateNode(string name, string parentId, string templateId)
 {
     var parent = new Document(Convert.ToInt32(parentId));
     var template = new DocumentType(Convert.ToInt32(templateId));
     var author = umbraco.BusinessLogic.User.GetUser(0);
     var document = Document.MakeNew(name, template, author, parent.Id);
     umbraco.library.UpdateDocumentCache(document.Id);
     using (CmsContext.Editing)
     {
         var entity = CmsService.Instance.GetItem<Entity>(new Id(document.Id));
         var result = GetTreeNode(entity);
         return result;
     }
 }
Esempio n. 13
0
        /// <summary>
        /// Checks if the appropriate document types exist and if they are properly structured so that 
        /// translations for a given node can be created.
        /// </summary>
        /// <param name="nodeID">The id of the node for which the translations are going to be created</param>
        /// <returns>"ok" if everything is in order; otherwise a description of the problem which has been discovered </returns>
        public static string CheckTranslationInfrastructure(int nodeID)
        {
            var status = "ok";
            var nodeDoc = new Document(nodeID);

            try
            {
                var translationFolderContentType = GetTranslationFolderContentType(nodeID);
                if (translationFolderContentType != null)
                {
                    if (!translationFolderContentType.AllowedChildContentTypeIDs.Any())
                        throw new Exception(
                            "Translation document type does not exist, or it is not an allowed child nodetype of the translation folder document type.");

                    if (translationFolderContentType.AllowedChildContentTypeIDs.Count() > 1)
                        throw new Exception(
                            "Translation folder document type has more than one allowed child nodetypes. It should only have one.");

                    var translationContentType =
                        new DocumentType(translationFolderContentType.AllowedChildContentTypeIDs[0]);

                    if (!(from prop in translationContentType.PropertyTypes
                          where prop.Alias == LanguagePropertyAlias
                          select prop).Any())
                        throw new Exception("Translation document type does not contain the '" + LanguagePropertyAlias +
                                            "' (alias) property");

                    if ((from p in ContentType.GetPropertyList(translationContentType.Id)
                         where
                             !(from pr in ContentType.GetPropertyList(nodeDoc.ContentType.Id) select pr.Alias).Contains(
                                 p.Alias)
                             && p.Alias != GetHideFromNavigationPropertyAlias() && p.Alias != LanguagePropertyAlias
                         select p).Any())
                        throw new Exception(
                            "Translation document type contains properties that do not exist in the document type (apart from language and navigation hiding)");
                }
                else
                    throw new Exception("TranslationFolder document type " + new Document(nodeID).ContentType.Alias +
                                        TranslationFolderAliasSuffix +
                                        " does not exist, or it does not have the right alias or is not an allowed child nodetype");
            }
            catch (Exception ex)
            {
                status = ex.Message;
            }

            return status;
        }
Esempio n. 14
0
 public bool Save()
 {
     cms.businesslogic.web.DocumentType dt = new cms.businesslogic.web.DocumentType(TypeID);
     cms.businesslogic.web.Document     d  = cms.businesslogic.web.Document.MakeNew(Alias, dt, BusinessLogic.User.GetUser(_userID), ParentID);
     if (d == null)
     {
         //TODO: Slace - Fix this to use the language files
         BasePage.Current.ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.error, "Document Creation", "Document creation was canceled");
         return(false);
     }
     else
     {
         _returnUrl = "editContent.aspx?id=" + d.Id.ToString() + "&isNew=true";
         return(true);
     }
 }
 /// <summary>
 /// save a document type to the disk, the document type will be 
 /// saved as an xml file, in a folder structure that mimics 
 /// that of the document type structure in umbraco.
 ///  
 /// this makes it easier to read them back in
 /// </summary>
 /// <param name="item">DocumentType to save</param>
 public static void SaveToDisk(DocumentType item)
 {
     if (item != null)
     {
         try
         {
             XmlDocument xmlDoc = helpers.XmlDoc.CreateDoc();
             xmlDoc.AppendChild(item.ToXml(xmlDoc));
             helpers.XmlDoc.SaveXmlDoc(item.GetType().ToString(), GetDocPath(item), "def", xmlDoc);
         }
         catch (Exception e)
         {
             Log.Add(LogTypes.Error, 0, String.Format("uSync: Error Saving DocumentType {0} - {1}", item.Alias, e.ToString()));
         }
     }
 }
Esempio n. 16
0
 public bool Save()
 {
     var dt = new cms.businesslogic.web.DocumentType(TypeID);
     var d = cms.businesslogic.web.Document.MakeNew(Alias, dt, User.GetUser(_userId), ParentID);
     if (d == null)
     {
         //TODO: Slace - Fix this to use the language files
         BasePage.Current.ClientTools.ShowSpeechBubble(BasePage.speechBubbleIcon.error, "Document Creation", "Document creation was canceled");
         return false;
     }
     else
     {
         _returnUrl = "editContent.aspx?id=" + d.Id.ToString() + "&isNew=true";
         return true;
     }
 }
        /// <summary>
        /// Gets for native node and property alias.
        /// </summary>
        /// <param name="id">The node id.</param>
        /// <param name="propertyTypeAlias">The property alias.</param>
        /// <returns></returns>
        public virtual UmbracoPropertyType GetForNativeDocumentTypePropertyAlias(int id, string propertyTypeAlias)
        {
            var documentType = new DocumentType(id);
            var nativePropertyType = documentType.getPropertyType(propertyTypeAlias);

            var umbracoPropertyType = new UmbracoPropertyType
                                          {
                                              Name = propertyTypeAlias,
                                              DataTypeName = nativePropertyType.DataTypeDefinition.DataType.DataTypeName,
                                              DatabaseType =
                                                  GetDatabaseType(
                                                      nativePropertyType.DataTypeDefinition.DataType.
                                                          DataTypeDefinitionId)
                                          };

            return umbracoPropertyType;
        }
        public override GridItem CreateItem(string name, string parentId, string templateId)
        {
            var parent = new Document(Convert.ToInt32(parentId));
            var template = new DocumentType(Convert.ToInt32(templateId));
            var author = umbraco.BusinessLogic.User.GetUser(0);

            Document modulesFolder;

            modulesFolder = GetModulesFolder(parent, author);
            var document = Document.MakeNew(name, template, author, modulesFolder.Id);
            umbraco.library.UpdateDocumentCache(document.Id);
            using (CmsContext.Editing)
            {
                var entity = CmsService.Instance.GetItem<Entity>(new Id(document.Id));
                var result = GetGridItem(entity);
                result.IsLocal = true;
                return result;
            }
        }
        /// <summary>
        /// works out what the folder stucture for a doctype should be.
        /// 
        /// recurses up the parent path of the doctype, adding a folder
        /// for each one, this then gives us a structure we can create
        /// on the disk, that mimics that of the umbraco internal one
        /// </summary>
        /// <param name="item">DocType path to find</param>
        /// <returns>folderstucture (relative to uSync folder)</returns>
        private static string GetDocPath(DocumentType item)
        {
            string path = "";

            if (item != null)
            {
                // does this documentType have a parent 
                if (item.MasterContentType != 0)
                {
                    // recurse in to the parent to build the path
                    path = GetDocPath(new DocumentType(item.MasterContentType));
                }

                // buld the final path (as path is "" to start with we always get
                // a preceeding '/' on the path, which is nice
                path = string.Format(@"{0}\{1}", path, helpers.XmlDoc.ScrubFile(item.Alias));
            }
         
            return path; 
        }
        private static void LoadChildrenIds(DocumentType nativeDocumentType, UmbracoDocumentType documentType)
        {
            documentType.InherritanceParentId = -1;

            var h = UmbracoSQLHelper.Get();
            using (
                var reader = UmbracoConfiguration.IsVersion6() ?
                    h.ExecuteReader("SELECT childContentTypeId from [cmsContentType2ContentType] WHERE parentContentTypeId = @parentContentTypeId",
                    h.CreateParameter("parentContentTypeId", nativeDocumentType.Id)) :
                    h.ExecuteReader("SELECT nodeId FROM [cmsContentType] WHERE masterContentType = @nodeId",
                                    h.CreateParameter("nodeId", nativeDocumentType.Id))
                    )
            {
                while (reader.Read())
                {
                    var result = reader.GetInt(UmbracoConfiguration.IsVersion6() ? "childContentTypeId" : "nodeId");
                    if (result > 0)
                        documentType.InherritanceChildrenIds.Add(result);
                }

            }
        }
        public int create(documentCarrier carrier, string username, string password)
        {
            Authenticate(username, password);

            // Some validation
            if (carrier == null) throw new Exception("No carrier specified");
            if (carrier.ParentID == 0) throw new Exception("Document needs a parent");
            if (carrier.DocumentTypeID == 0) throw new Exception("Documenttype must be specified");
            if (carrier.Id != 0) throw new Exception("ID cannot be specifed when creating. Must be 0");
            if (carrier.Name == null || carrier.Name.Length == 0) carrier.Name = "unnamed";

            umbraco.BusinessLogic.User user = GetUser(username, password);

            // We get the documenttype
            umbraco.cms.businesslogic.web.DocumentType docType = new umbraco.cms.businesslogic.web.DocumentType(carrier.DocumentTypeID);
            if (docType == null) throw new Exception("DocumenttypeID " + carrier.DocumentTypeID + " not found");

            // We create the document
            Document newDoc = Document.MakeNew(carrier.Name, docType, user, carrier.ParentID);
            newDoc.ReleaseDate = carrier.ReleaseDate;
            newDoc.ExpireDate = carrier.ExpireDate;

            // We iterate the properties in the carrier
            if (carrier.DocumentProperties != null)
            {
                foreach (documentProperty updatedproperty in carrier.DocumentProperties)
                {
                    umbraco.cms.businesslogic.property.Property property = newDoc.getProperty(updatedproperty.Key);
                    if (property == null) throw new Exception("property " + updatedproperty.Key + " was not found");
                    property.Value = updatedproperty.PropertyValue;
                }
            }

            // We check the publishaction and do the appropiate
            handlePublishing(newDoc, carrier, user);

            // We return the ID of the document..65
            return newDoc.Id;
        }
Esempio n. 22
0
        public bool Save()
        {
            cms.businesslogic.web.DocumentType dt = cms.businesslogic.web.DocumentType.MakeNew(BusinessLogic.User.GetUser(_userID), Alias.Replace("'", "''"));
            dt.IconUrl = "folder.gif";

            // Create template?
            if (ParentID == 1)
            {
                cms.businesslogic.template.Template[] t = { cms.businesslogic.template.Template.MakeNew(_alias, BusinessLogic.User.GetUser(_userID)) };
                dt.allowedTemplates = t;
                dt.DefaultTemplate  = t[0].Id;
            }

            // Master Content Type?
            if (TypeID != 0)
            {
                dt.MasterContentType = TypeID;
            }

            m_returnUrl = "settings/editNodeTypeNew.aspx?id=" + dt.Id.ToString();

            return(true);
        }
Esempio n. 23
0
        public void Publish() {

            CreatedPackage package = this;
            PackageInstance pack = package.Data;

			try
			{

				PublishEventArgs e = new PublishEventArgs();
				package.FireBeforePublish(e);

				if (!e.Cancel)
				{
					int outInt = 0;

					//Path checking...
					string localPath = IOHelper.MapPath(SystemDirectories.Media + "/" + pack.Folder);

					if (!System.IO.Directory.Exists(localPath))
						System.IO.Directory.CreateDirectory(localPath);

					//Init package file...
					createPackageManifest();
					//Info section..
					appendElement(utill.PackageInfo(pack, _packageManifest));

					//Documents...
					int _contentNodeID = 0;
					if (!String.IsNullOrEmpty(pack.ContentNodeId) && int.TryParse(pack.ContentNodeId, out _contentNodeID))
					{
						XmlNode documents = _packageManifest.CreateElement("Documents");

						XmlNode documentSet = _packageManifest.CreateElement("DocumentSet");
						XmlAttribute importMode = _packageManifest.CreateAttribute("importMode", "");
						importMode.Value = "root";
						documentSet.Attributes.Append(importMode);
						documents.AppendChild(documentSet);

						//load content from umbraco.
						cms.businesslogic.web.Document umbDocument = new Document(_contentNodeID);
						documentSet.AppendChild(umbDocument.ToXml(_packageManifest, pack.ContentLoadChildNodes));

						appendElement(documents);
					}

					//Document types..
					List<DocumentType> dtl = new List<DocumentType>();
					XmlNode docTypes = _packageManifest.CreateElement("DocumentTypes");
					foreach (string dtId in pack.Documenttypes)
					{
						if (int.TryParse(dtId, out outInt))
						{
							DocumentType docT = new DocumentType(outInt);

							AddDocumentType(docT, ref dtl);

						}
					}
					foreach (DocumentType d in dtl)
					{
						docTypes.AppendChild(d.ToXml(_packageManifest));
					}

					appendElement(docTypes);

					//Templates
					XmlNode templates = _packageManifest.CreateElement("Templates");
					foreach (string templateId in pack.Templates)
					{
						if (int.TryParse(templateId, out outInt))
						{
							Template t = new Template(outInt);
							templates.AppendChild(t.ToXml(_packageManifest));
						}
					}
					appendElement(templates);

					//Stylesheets
					XmlNode stylesheets = _packageManifest.CreateElement("Stylesheets");
					foreach (string ssId in pack.Stylesheets)
					{
						if (int.TryParse(ssId, out outInt))
						{
							StyleSheet s = new StyleSheet(outInt);
							stylesheets.AppendChild(s.ToXml(_packageManifest));
						}
					}
					appendElement(stylesheets);

					//Macros
					XmlNode macros = _packageManifest.CreateElement("Macros");
					foreach (string macroId in pack.Macros)
					{
						if (int.TryParse(macroId, out outInt))
						{
							macros.AppendChild(utill.Macro(int.Parse(macroId), true, localPath, _packageManifest));
						}
					}
					appendElement(macros);

					//Dictionary Items
					XmlNode dictionaryItems = _packageManifest.CreateElement("DictionaryItems");
					foreach (string dictionaryId in pack.DictionaryItems)
					{
						if (int.TryParse(dictionaryId, out outInt))
						{
							Dictionary.DictionaryItem di = new Dictionary.DictionaryItem(outInt);
							dictionaryItems.AppendChild(di.ToXml(_packageManifest));
						}
					}
					appendElement(dictionaryItems);

					//Languages
					XmlNode languages = _packageManifest.CreateElement("Languages");
					foreach (string langId in pack.Languages)
					{
						if (int.TryParse(langId, out outInt))
						{
							language.Language lang = new umbraco.cms.businesslogic.language.Language(outInt);

							languages.AppendChild(lang.ToXml(_packageManifest));
						}
					}
					appendElement(languages);

					//Datatypes
					XmlNode dataTypes = _packageManifest.CreateElement("DataTypes");
					foreach (string dtId in pack.DataTypes)
					{
						if (int.TryParse(dtId, out outInt))
						{
							cms.businesslogic.datatype.DataTypeDefinition dtd = new umbraco.cms.businesslogic.datatype.DataTypeDefinition(outInt);
							dataTypes.AppendChild(dtd.ToXml(_packageManifest));
						}
					}
					appendElement(dataTypes);

					//Files
					foreach (string fileName in pack.Files)
					{
						utill.AppendFileToManifest(fileName, localPath, _packageManifest);
					}

					//Load control on install...
					if (!string.IsNullOrEmpty(pack.LoadControl))
					{
						XmlNode control = _packageManifest.CreateElement("control");
						control.InnerText = pack.LoadControl;
						utill.AppendFileToManifest(pack.LoadControl, localPath, _packageManifest);
						appendElement(control);
					}

					//Actions
					if (!string.IsNullOrEmpty(pack.Actions))
					{
						try
						{
							XmlDocument xd_actions = new XmlDocument();
							xd_actions.LoadXml("<Actions>" + pack.Actions + "</Actions>");
							XmlNode actions = xd_actions.DocumentElement.SelectSingleNode(".");


							if (actions != null)
							{
								actions = _packageManifest.ImportNode(actions, true).Clone();
								appendElement(actions);
							}
						}
						catch { }
					}

					string manifestFileName = localPath + "/package.xml";

					if (System.IO.File.Exists(manifestFileName))
						System.IO.File.Delete(manifestFileName);

					_packageManifest.Save(manifestFileName);
					_packageManifest = null;


					//string packPath = Settings.PackagerRoot.Replace(System.IO.Path.DirectorySeparatorChar.ToString(), "/") + "/" + pack.Name.Replace(' ', '_') + "_" + pack.Version.Replace(' ', '_') + "." + Settings.PackageFileExtension;

					// check if there's a packages directory below media
					string packagesDirectory = SystemDirectories.Media + "/created-packages";
					if (!System.IO.Directory.Exists(IOHelper.MapPath(packagesDirectory)))
						System.IO.Directory.CreateDirectory(IOHelper.MapPath(packagesDirectory));


					string packPath = packagesDirectory + "/" + (pack.Name + "_" + pack.Version).Replace(' ', '_') + "." + Settings.PackageFileExtension;
					utill.ZipPackage(localPath, IOHelper.MapPath(packPath));

					pack.PackagePath = packPath;

					if (pack.PackageGuid.Trim() == "")
						pack.PackageGuid = Guid.NewGuid().ToString();

					package.Save();

					//Clean up..
					System.IO.File.Delete(localPath + "/package.xml");
					System.IO.Directory.Delete(localPath, true);

					package.FireAfterPublish(e);
				}

			}
			catch (Exception ex)
			{
				LogHelper.Error<CreatedPackage>("An error occurred", ex);
			}
        }
Esempio n. 24
0
        private void AddDocumentType(DocumentType dt, ref List<DocumentType> dtl)
        {
            if (dt.MasterContentType != 0)
            {
                //first add masters
                DocumentType mDocT = new DocumentType(dt.MasterContentType);

                AddDocumentType(mDocT, ref dtl);

            }

            if (!dtl.Contains(dt))
                dtl.Add(dt);
        }
Esempio n. 25
0
        public XmlElement ToXml(XmlDocument xd)
        {
            XmlElement doc = xd.CreateElement("DocumentType");

            // info section
            XmlElement info = xd.CreateElement("Info");
            doc.AppendChild(info);
            info.AppendChild(XmlHelper.AddTextNode(xd, "Name", GetRawText()));
            info.AppendChild(XmlHelper.AddTextNode(xd, "Alias", Alias));
            info.AppendChild(XmlHelper.AddTextNode(xd, "Icon", IconUrl));
            info.AppendChild(XmlHelper.AddTextNode(xd, "Thumbnail", Thumbnail));
            info.AppendChild(XmlHelper.AddTextNode(xd, "Description", GetRawDescription()));
            info.AppendChild(XmlHelper.AddTextNode(xd, "AllowAtRoot", AllowAtRoot.ToString()));

            //TODO: Add support for mixins!
            if (this.MasterContentType > 0)
            {
                DocumentType dt = new DocumentType(this.MasterContentType);

                if (dt != null)
                    info.AppendChild(XmlHelper.AddTextNode(xd, "Master", dt.Alias));
            }


            // templates
            XmlElement allowed = xd.CreateElement("AllowedTemplates");
            foreach (template.Template t in allowedTemplates)
                allowed.AppendChild(XmlHelper.AddTextNode(xd, "Template", t.Alias));
            info.AppendChild(allowed);
            if (DefaultTemplate != 0)
                info.AppendChild(
                    XmlHelper.AddTextNode(xd, "DefaultTemplate", new template.Template(DefaultTemplate).Alias));
            else
                info.AppendChild(XmlHelper.AddTextNode(xd, "DefaultTemplate", ""));

            // structure
            XmlElement structure = xd.CreateElement("Structure");
            doc.AppendChild(structure);

            foreach (int cc in AllowedChildContentTypeIDs.ToList())
                structure.AppendChild(XmlHelper.AddTextNode(xd, "DocumentType", new DocumentType(cc).Alias));

            // generic properties
            XmlElement pts = xd.CreateElement("GenericProperties");
            foreach (PropertyType pt in PropertyTypes)
            {
                //only add properties that aren't from master doctype
                if (pt.ContentTypeId == this.Id)
                {
                    XmlElement ptx = xd.CreateElement("GenericProperty");
                    ptx.AppendChild(XmlHelper.AddTextNode(xd, "Name", pt.GetRawName()));
                    ptx.AppendChild(XmlHelper.AddTextNode(xd, "Alias", pt.Alias));
                    ptx.AppendChild(XmlHelper.AddTextNode(xd, "Type", pt.DataTypeDefinition.DataType.Id.ToString()));

                    //Datatype definition guid was added in v4 to enable datatype imports
                    ptx.AppendChild(XmlHelper.AddTextNode(xd, "Definition", pt.DataTypeDefinition.UniqueId.ToString()));

                    ptx.AppendChild(XmlHelper.AddTextNode(xd, "Tab", Tab.GetCaptionById(pt.TabId)));
                    ptx.AppendChild(XmlHelper.AddTextNode(xd, "Mandatory", pt.Mandatory.ToString()));
                    ptx.AppendChild(XmlHelper.AddTextNode(xd, "Validation", pt.ValidationRegExp));
                    ptx.AppendChild(XmlHelper.AddCDataNode(xd, "Description", pt.GetRawDescription()));
                    pts.AppendChild(ptx);
                }
            }
            doc.AppendChild(pts);

            // tabs
            var tabs = xd.CreateElement("Tabs");

            foreach (var propertyTypeGroup in PropertyTypeGroups)
            {
                //only add tabs that aren't from a master doctype
                if (propertyTypeGroup.ContentTypeId == this.Id)
                {
                    var tabx = xd.CreateElement("Tab");
                    tabx.AppendChild(XmlHelper.AddTextNode(xd, "Id", propertyTypeGroup.Id.ToString()));
                    tabx.AppendChild(XmlHelper.AddTextNode(xd, "Caption", propertyTypeGroup.Name));
                    tabs.AppendChild(tabx);
                }
            }

            doc.AppendChild(tabs);
            return doc;
        }
Esempio n. 26
0
        public static DocumentType MakeNew(User u, string Text)
        {
            int ParentId = -1;
            int level = 1;
            Guid uniqueId = Guid.NewGuid();
            CMSNode n = MakeNew(ParentId, _objectType, u.Id, level, Text, uniqueId);

            Create(n.Id, Text, "");
            DocumentType newDt = new DocumentType(n.Id);

            //event
            NewEventArgs e = new NewEventArgs();
            newDt.OnNew(e);

            return newDt;
        }
        public XmlElement ToXml(XmlDocument xd, MediaType mt)
        {
            XmlElement doc = xd.CreateElement("MediaType");

            // info section
            XmlElement info = xd.CreateElement("Info");
            doc.AppendChild(info);
            info.AppendChild(xmlHelper.addTextNode(xd, "Name", mt.Text));
            info.AppendChild(xmlHelper.addTextNode(xd, "Alias", mt.Alias));
            info.AppendChild(xmlHelper.addTextNode(xd, "Icon", mt.IconUrl));
            info.AppendChild(xmlHelper.addTextNode(xd, "Thumbnail", mt.Thumbnail));
            info.AppendChild(xmlHelper.addTextNode(xd, "Description", mt.Description));

            if (mt.MasterContentType > 0)
            {
                DocumentType dt = new DocumentType(mt.MasterContentType);

                if (dt != null)
                    info.AppendChild(xmlHelper.addTextNode(xd, "Master", dt.Alias));
            }

            // structure
            XmlElement structure = xd.CreateElement("Structure");
            doc.AppendChild(structure);

            foreach (int cc in mt.AllowedChildContentTypeIDs.ToList())
                structure.AppendChild(xmlHelper.addTextNode(xd, "MediaType", new DocumentType(cc).Alias));

            // generic properties
            XmlElement pts = xd.CreateElement("GenericProperties");
            foreach (PropertyType pt in mt.PropertyTypes)
            {
                //only add properties that aren't from master doctype
                if (pt.ContentTypeId == mt.Id)
                {
                    XmlElement ptx = xd.CreateElement("GenericProperty");
                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Name", pt.Name));
                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Alias", pt.Alias));
                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Type", pt.DataTypeDefinition.DataType.Id.ToString()));

                    //Datatype definition guid was added in v4 to enable datatype imports
                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Definition", pt.DataTypeDefinition.UniqueId.ToString()));

                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Tab", umbraco.cms.businesslogic.ContentType.Tab.GetCaptionById(pt.TabId)));
                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Mandatory", pt.Mandatory.ToString()));
                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Validation", pt.ValidationRegExp));
                    ptx.AppendChild(xmlHelper.addCDataNode(xd, "Description", pt.Description));
                    pts.AppendChild(ptx);
                }
            }
            doc.AppendChild(pts);

            // tabs
            XmlElement tabs = xd.CreateElement("Tabs");
            foreach (umbraco.cms.businesslogic.ContentType.TabI t in mt.getVirtualTabs.ToList())
            {
                //only add tabs that aren't from a master doctype
                if (t.ContentType == mt.Id)
                {
                    XmlElement tabx = xd.CreateElement("Tab");
                    tabx.AppendChild(xmlHelper.addTextNode(xd, "Id", t.Id.ToString()));
                    tabx.AppendChild(xmlHelper.addTextNode(xd, "Caption", t.Caption));
                    tabs.AppendChild(tabx);
                }
            }
            doc.AppendChild(tabs);
            return doc;
        }
Esempio n. 28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            JTree.DataBind();

            // Put user code to initialize the page here
            if (IsPostBack == false)
            {
                pp_relate.Text = ui.Text("moveOrCopy", "relateToOriginal");

                //Document Type copy Hack...                

                if (CurrentApp == Constants.Applications.Settings)
                {
                    pane_form.Visible = false;
                    pane_form_notice.Visible = false;
                    pane_settings.Visible = true;

                    ok.Text = ui.Text("general", "ok", UmbracoUser);
                    ok.Attributes.Add("style", "width: 60px");

                    var documentType = new DocumentType(int.Parse(Request.GetItemAsString("id")));

                    //Load master types... 
                    masterType.Attributes.Add("style", "width: 350px;");
                    masterType.Items.Add(new ListItem(ui.Text("none") + "...", "0"));
                    foreach (var docT in DocumentType.GetAllAsList())
                    {
                        masterType.Items.Add(new ListItem(docT.Text, docT.Id.ToString()));
                    }

                    masterType.SelectedValue = documentType.MasterContentType.ToString();

                    rename.Text = documentType.Text + " (copy)";
                    pane_settings.Text = "Make a copy of the document type '" + documentType.Text + "' and save it under a new name";

                }
                else
                {
                    pane_form.Visible = true;
                    pane_form_notice.Visible = true;

                    pane_settings.Visible = false;

                    // Caption and properies on BUTTON
                    ok.Text = ui.Text("general", "ok", UmbracoUser);
                    ok.Attributes.Add("style", "width: 60px");
                    ok.Attributes.Add("disabled", "true");

                    IContentBase currContent;
                    if (CurrentApp == "content")
                    {
                        currContent = Services.ContentService.GetById(Request.GetItemAs<int>("id"));
                    }
                    else
                    {
                        currContent = Services.MediaService.GetById(Request.GetItemAs<int>("id"));
                    }

                    var validAction = true;
                    if (CurrentApp == Constants.Applications.Content && Umbraco.Core.Models.ContentExtensions.HasChildren(currContent, Services))
                    {
                        validAction = ValidAction(currContent, Request.GetItemAsString("mode") == "cut" ? 'M' : 'O');
                    }

                    if (Request.GetItemAsString("mode") == "cut")
                    {
                        pane_form.Text = ui.Text("moveOrCopy", "moveTo", currContent.Name, UmbracoUser);
                        pp_relate.Visible = false;
                    }
                    else
                    {
                        pane_form.Text = ui.Text("moveOrCopy", "copyTo", currContent.Name, UmbracoUser);
                        pp_relate.Visible = true;
                    }

                    if (validAction == false)
                    {
                        panel_buttons.Visible = false;
                        ScriptManager.RegisterStartupScript(this, GetType(), "notvalid", "notValid();", true);
                    }
                }
            }

        }
Esempio n. 29
0
        public XmlElement ToXml(XmlDocument xd)
        {
            XmlElement doc = xd.CreateElement("DocumentType");

            // info section
            XmlElement info = xd.CreateElement("Info");

            doc.AppendChild(info);
            info.AppendChild(xmlHelper.addTextNode(xd, "Name", Text));
            info.AppendChild(xmlHelper.addTextNode(xd, "Alias", Alias));
            info.AppendChild(xmlHelper.addTextNode(xd, "Icon", IconUrl));
            info.AppendChild(xmlHelper.addTextNode(xd, "Thumbnail", Thumbnail));
            info.AppendChild(xmlHelper.addTextNode(xd, "Description", Description));

            if (this.MasterContentType > 0)
            {
                DocumentType dt = new DocumentType(this.MasterContentType);

                if (dt != null)
                {
                    info.AppendChild(xmlHelper.addTextNode(xd, "Master", dt.Alias));
                }
            }


            // templates
            XmlElement allowed = xd.CreateElement("AllowedTemplates");

            foreach (template.Template t in allowedTemplates)
            {
                allowed.AppendChild(xmlHelper.addTextNode(xd, "Template", t.Alias));
            }
            info.AppendChild(allowed);
            if (DefaultTemplate != 0)
            {
                info.AppendChild(
                    xmlHelper.addTextNode(xd, "DefaultTemplate", new template.Template(DefaultTemplate).Alias));
            }
            else
            {
                info.AppendChild(xmlHelper.addTextNode(xd, "DefaultTemplate", ""));
            }

            // structure
            XmlElement structure = xd.CreateElement("Structure");

            doc.AppendChild(structure);

            foreach (int cc in AllowedChildContentTypeIDs.ToList())
            {
                structure.AppendChild(xmlHelper.addTextNode(xd, "DocumentType", new DocumentType(cc).Alias));
            }

            // generic properties
            XmlElement pts = xd.CreateElement("GenericProperties");

            foreach (PropertyType pt in PropertyTypes)
            {
                //only add properties that aren't from master doctype
                if (pt.ContentTypeId == this.Id)
                {
                    XmlElement ptx = xd.CreateElement("GenericProperty");
                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Name", pt.Name));
                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Alias", pt.Alias));
                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Type", pt.DataTypeDefinition.DataType.Id.ToString()));

                    //Datatype definition guid was added in v4 to enable datatype imports
                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Definition", pt.DataTypeDefinition.UniqueId.ToString()));

                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Tab", Tab.GetCaptionById(pt.TabId)));
                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Mandatory", pt.Mandatory.ToString()));
                    ptx.AppendChild(xmlHelper.addTextNode(xd, "Validation", pt.ValidationRegExp));
                    ptx.AppendChild(xmlHelper.addCDataNode(xd, "Description", pt.Description));
                    pts.AppendChild(ptx);
                }
            }
            doc.AppendChild(pts);

            // tabs
            XmlElement tabs = xd.CreateElement("Tabs");

            foreach (TabI t in getVirtualTabs.ToList())
            {
                //only add tabs that aren't from a master doctype
                if (t.ContentType == this.Id)
                {
                    XmlElement tabx = xd.CreateElement("Tab");
                    tabx.AppendChild(xmlHelper.addTextNode(xd, "Id", t.Id.ToString()));
                    tabx.AppendChild(xmlHelper.addTextNode(xd, "Caption", t.Caption));
                    tabs.AppendChild(tabx);
                }
            }
            doc.AppendChild(tabs);
            return(doc);
        }
Esempio n. 30
0
        override protected void OnInit(EventArgs e)
        {
            base.OnInit(e);

            //validate!
            int id;
            if (int.TryParse(Request.QueryString["id"], out id) == false)
            {
                //if this is invalid show an error
                this.DisplayFatalError("Invalid query string");
                return;
            }
            _contentId = id;


            _unPublish.Click += UnPublishDo;

            //Loading Content via new public service to ensure that the Properties are loaded correct
            var content = ApplicationContext.Current.Services.ContentService.GetById(id);
            _document = new Document(content);

            //check if the doc exists
            if (string.IsNullOrEmpty(_document.Path))
            {
                //if this is invalid show an error
                this.DisplayFatalError("No document found with id " + _contentId);
                //reset the content id to null so processing doesn't continue on OnLoad
                _contentId = null;
                return;
            }

            // we need to check if there's a published version of this document
            _documentHasPublishedVersion = _document.Content.HasPublishedVersion();

            // Check publishing permissions
            if (!UmbracoUser.GetPermissions(_document.Path).Contains(ActionPublish.Instance.Letter.ToString()))
            {
                // Check to see if the user has send to publish permissions
                if (!UmbracoUser.GetPermissions(_document.Path).Contains(ActionToPublish.Instance.Letter.ToString()))
                {
                    //If no send to publish permission then revert to NoPublish mode
                    _canPublish = controls.ContentControl.publishModes.NoPublish;
                }
                else
                {
                    _canPublish = controls.ContentControl.publishModes.SendToPublish;
                }
            }

            _cControl = new controls.ContentControl(_document, _canPublish, "TabView1");

            _cControl.ID = "TabView1";

            _cControl.Width = Unit.Pixel(666);
            _cControl.Height = Unit.Pixel(666);

            // Add preview button

            foreach (uicontrols.TabPage tp in _cControl.GetPanels())
            {
                AddPreviewButton(tp.Menu, _document.Id);
            }

            plc.Controls.Add(_cControl);


            var publishStatus = new PlaceHolder();
            if (_documentHasPublishedVersion)
            {
                _littPublishStatus.Text = ui.Text("content", "lastPublished", UmbracoUser) + ": " + _document.VersionDate.ToShortDateString() + " &nbsp; ";

                publishStatus.Controls.Add(_littPublishStatus);
                if (UmbracoUser.GetPermissions(_document.Path).IndexOf("U") > -1)
                    _unPublish.Visible = true;
                else
                    _unPublish.Visible = false;
            }
            else
            {
                _littPublishStatus.Text = ui.Text("content", "itemNotPublished", UmbracoUser);
                publishStatus.Controls.Add(_littPublishStatus);
                _unPublish.Visible = false;
            }

            _unPublish.Text = ui.Text("content", "unPublish", UmbracoUser);
            _unPublish.ID = "UnPublishButton";
            _unPublish.Attributes.Add("onClick", "if (!confirm('" + ui.Text("defaultdialogs", "confirmSure", UmbracoUser) + "')) return false; ");
            publishStatus.Controls.Add(_unPublish);

            _publishProps.addProperty(ui.Text("content", "publishStatus", UmbracoUser), publishStatus);

            // Template
            var template = new PlaceHolder();
            var documentType = new DocumentType(_document.ContentType.Id);
            _cControl.PropertiesPane.addProperty(ui.Text("documentType"), new LiteralControl(documentType.Text));


            //template picker
            _cControl.PropertiesPane.addProperty(ui.Text("template"), template);
            int defaultTemplate;
            if (_document.Template != 0)
                defaultTemplate = _document.Template;
            else
                defaultTemplate = documentType.DefaultTemplate;

            if (UmbracoUser.UserType.Name == "writer")
            {
                if (defaultTemplate != 0)
                    template.Controls.Add(new LiteralControl(businesslogic.template.Template.GetTemplate(defaultTemplate).Text));
                else
                    template.Controls.Add(new LiteralControl(ui.Text("content", "noDefaultTemplate")));
            }
            else
            {
                _ddlDefaultTemplate.Items.Add(new ListItem(ui.Text("choose") + "...", ""));
                foreach (var t in documentType.allowedTemplates)
                {

                    var tTemp = new ListItem(t.Text, t.Id.ToString());
                    if (t.Id == defaultTemplate)
                        tTemp.Selected = true;
                    _ddlDefaultTemplate.Items.Add(tTemp);
                }
                template.Controls.Add(_ddlDefaultTemplate);
            }


            // Editable update date, release date and expire date added by NH 13.12.04
            _dp.ID = "updateDate";
            _dp.Text = _document.UpdateDate.ToShortDateString() + " " + _document.UpdateDate.ToShortTimeString();
            _publishProps.addProperty(ui.Text("content", "updateDate", UmbracoUser), _dp);

            _dpRelease.ID = "releaseDate";
            _dpRelease.DateTime = _document.ReleaseDate;
            _dpRelease.ShowTime = true;
            _publishProps.addProperty(ui.Text("content", "releaseDate", UmbracoUser), _dpRelease);

            _dpExpire.ID = "expireDate";
            _dpExpire.DateTime = _document.ExpireDate;
            _dpExpire.ShowTime = true;
            _publishProps.addProperty(ui.Text("content", "expireDate", UmbracoUser), _dpExpire);

            _cControl.Save += Save;
            _cControl.SaveAndPublish += Publish;
            _cControl.SaveToPublish += SendToPublish;

            // Add panes to property page...
            _cControl.tpProp.Controls.AddAt(1, _publishProps);
            _cControl.tpProp.Controls.AddAt(2, _linkProps);

            // add preview to properties pane too
            AddPreviewButton(_cControl.tpProp.Menu, _document.Id);


        }
Esempio n. 31
0
        public static DocumentType MakeNew(User u, string Text)
        {
            var contentType = new Umbraco.Core.Models.ContentType(-1) { Name = Text, Alias = Text, CreatorId = u.Id, Thumbnail = "folder.png", Icon = "folder.gif" };
            ApplicationContext.Current.Services.ContentTypeService.Save(contentType, u.Id);
            var newDt = new DocumentType(contentType);

            //event
            NewEventArgs e = new NewEventArgs();
            newDt.OnNew(e);

            return newDt;
        }
Esempio n. 32
0
        public static List<DocumentType> GetAllAsList()
        {

            var documentTypes = new List<DocumentType>();

            using (IRecordsReader dr =
                SqlHelper.ExecuteReader(m_SQLOptimizedGetAll.Trim(), SqlHelper.CreateParameter("@nodeObjectType", DocumentType._objectType)))
            {
                while (dr.Read())
                {
                    //check if the document id has already been added
                    if (documentTypes.Where(x => x.Id == dr.Get<int>("id")).Count() == 0)
                    {
                        //create the DocumentType object without setting up
                        DocumentType dt = new DocumentType(dr.Get<int>("id"), true);
                        //populate it's CMSNode properties
                        dt.PopulateCMSNodeFromReader(dr);
                        //populate it's ContentType properties
                        dt.PopulateContentTypeNodeFromReader(dr);
                        //populate from it's DocumentType properties
                        dt.PopulateDocumentTypeNodeFromReader(dr);

                        documentTypes.Add(dt);
                    }
                    else
                    {
                        //we've already created the document type with this id, so we'll add the rest of it's templates to itself
                        var dt = documentTypes.Where(x => x.Id == dr.Get<int>("id")).Single();
                        dt.PopulateDocumentTypeNodeFromReader(dr);
                    }
                }
            }

            return documentTypes.OrderBy(x => x.Text).ToList();

        }
        public int create(documentCarrier carrier, string username, string password)
        {
            Authenticate(username, password);

            // Some validation
            if (carrier == null)
            {
                throw new Exception("No carrier specified");
            }
            if (carrier.ParentID == 0)
            {
                throw new Exception("Document needs a parent");
            }
            if (carrier.DocumentTypeID == 0)
            {
                throw new Exception("Documenttype must be specified");
            }
            if (carrier.Id != 0)
            {
                throw new Exception("ID cannot be specifed when creating. Must be 0");
            }
            if (carrier.Name == null || carrier.Name.Length == 0)
            {
                carrier.Name = "unnamed";
            }

            umbraco.BusinessLogic.User user = GetUser(username, password);

            // We get the documenttype
            umbraco.cms.businesslogic.web.DocumentType docType = new umbraco.cms.businesslogic.web.DocumentType(carrier.DocumentTypeID);
            if (docType == null)
            {
                throw new Exception("DocumenttypeID " + carrier.DocumentTypeID + " not found");
            }

            // We create the document
            Document newDoc = Document.MakeNew(carrier.Name, docType, user, carrier.ParentID);

            newDoc.ReleaseDate = carrier.ReleaseDate;
            newDoc.ExpireDate  = carrier.ExpireDate;

            // We iterate the properties in the carrier
            if (carrier.DocumentProperties != null)
            {
                foreach (documentProperty updatedproperty in carrier.DocumentProperties)
                {
                    umbraco.cms.businesslogic.property.Property property = newDoc.getProperty(updatedproperty.Key);
                    if (property == null)
                    {
                        throw new Exception("property " + updatedproperty.Key + " was not found");
                    }
                    property.Value = updatedproperty.PropertyValue;
                }
            }

            // We check the publishaction and do the appropiate
            handlePublishing(newDoc, carrier, user);

            // We return the ID of the document..65
            return(newDoc.Id);
        }
Esempio n. 34
0
 /// <summary>
 /// Handles the <c>MessageReceived</c> event of the manager.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="e">The e.</param>
 protected override void Manager_MessageReceived(object sender, MesssageReceivedArgs e)
 {
     switch (e.Type)
     {
         case "createcontent":      
             var userid = BasePages.UmbracoEnsuredPage.GetUserId(BasePages.UmbracoEnsuredPage.umbracoUserContextID);
             var typeToCreate = new DocumentType(Convert.ToInt32(m_AllowedDocTypesDropdown.SelectedValue));
             var newDoc = Document.MakeNew(m_NameTextBox.Text, typeToCreate, new BusinessLogic.User(userid), (int)UmbracoContext.Current.PageId);
             newDoc.SaveAndPublish(new BusinessLogic.User(userid));
             Page.Response.Redirect(library.NiceUrl(newDoc.Id), false);
             break;
     }
 }