protected void Page_Load(object sender, EventArgs e)
        {
            _templateId = int.Parse(Request["id"]);
            var t = new Template(_templateId);

            if (Skinning.StarterKitGuid(_templateId).HasValue)
            {
                p_apply.Visible = true;

                var currentSkin = Skinning.GetCurrentSkinAlias(_templateId);
                var templateRoot = FindTemplateRoot(t);

                dd_skins.Items.Add("Choose...");
                foreach (var kvp in Skinning.AllowedSkins(templateRoot))
                {
                    var li = new ListItem(kvp.Value, kvp.Key);
                    if (kvp.Key == currentSkin)
                        li.Selected = true;

                    dd_skins.Items.Add(li);
                }

                if (!string.IsNullOrEmpty(Skinning.GetCurrentSkinAlias(_templateId)))
                {
                    ph_rollback.Visible = true;
                }
            }
        }
Esempio n. 2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            templateID = int.Parse(Request["id"]);
            Template t = new Template(templateID);

            if (Skinning.StarterKitGuid(templateID).HasValue)
            {
                p_apply.Visible = true;

                string currentSkin = Skinning.GetCurrentSkinAlias(templateID);
                int templateRoot = FindTemplateRoot((CMSNode)t);

                dd_skins.Items.Add("Choose...");
                foreach (KeyValuePair<string,string> kvp in Skinning.AllowedSkins(templateRoot))
                {
                    ListItem li = new ListItem(kvp.Value, kvp.Key);
                    if (kvp.Key == currentSkin)
                        li.Selected = true;

                    dd_skins.Items.Add(li);
                }

                if (!string.IsNullOrEmpty(Skinning.GetCurrentSkinAlias(templateID)))
                {
                    ph_rollback.Visible = true;
                }
            }
        }
Esempio n. 3
0
        internal static string UpdateViewFile(Template t, string currentAlias = null)
        {
            var path = IOHelper.MapPath(ViewPath(t.Alias));

			if (string.IsNullOrEmpty(currentAlias) == false && currentAlias != t.Alias)
			{
				//NOTE: I don't think this is needed for MVC, this was ported over from the
				// masterpages helper but I think only relates to when templates are stored in the db.
				////Ensure that child templates have the right master masterpage file name
				//if (t.HasChildren)
				//{
				//	var c = t.Children;
				//	foreach (CMSNode cmn in c)
				//		UpdateViewFile(new Template(cmn.Id), null);
				//}

				//then kill the old file.. 
				var oldFile = IOHelper.MapPath(ViewPath(currentAlias));
				if (File.Exists(oldFile))
					File.Delete(oldFile);
			}

            File.WriteAllText(path, t.Design, Encoding.UTF8);
            return t.Design;
        }
Esempio n. 4
0
 private void checkForMaster(int templateID)
 {
     // Get template design
     if (_masterTemplate != 0 && _masterTemplate != templateID)
     {
         template masterTemplateDesign = new template(_masterTemplate);
         if (masterTemplateDesign.TemplateContent.IndexOf("<?UMBRACO_TEMPLATE_LOAD_CHILD/>") > -1 ||
             masterTemplateDesign.TemplateContent.IndexOf("<?UMBRACO_TEMPLATE_LOAD_CHILD />") > -1)
         {
             _templateOutput.Append(
                 masterTemplateDesign.TemplateContent.Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD/>",
                                                              _templateDesign).Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD />", _templateDesign)
                 );
         }
         else
         {
             _templateOutput.Append(_templateDesign);
         }
     }
     else
     {
         if (_masterTemplate == templateID)
         {
             cms.businesslogic.template.Template t = cms.businesslogic.template.Template.GetTemplate(templateID);
             string templateName = (t != null) ? t.Text : string.Format("'Template with id: '{0}", templateID);
             System.Web.HttpContext.Current.Trace.Warn("template",
                                                       String.Format("Master template is the same as the current template. It would cause an endless loop! Make sure that the current template '{0}' has another Master Template than itself. You can change this in the template editor under 'Settings'", templateName));
             _templateOutput.Append(_templateDesign);
         }
     }
 }
Esempio n. 5
0
 internal static string SaveTemplateToFile(Template template, string currentAlias)
 {
     var design = EnsureInheritedLayout(template);
     File.WriteAllText(IOHelper.MapPath(ViewPath(template.Alias)), design, Encoding.UTF8);
     
     return template.Design;
 }
        internal static string UpdateMasterPageFile(Template t, string currentAlias)
        {
            var template = UpdateMasterPageContent(t, currentAlias);
            UpdateChildTemplates(t, currentAlias);
            SaveDesignToFile(t, currentAlias, template);

            return template;
        }
        public void delete(int id, string username, string password)
        {
            Authenticate(username, password);

            if (id == 0) throw new Exception("ID must be specifed when updating");

            cms.businesslogic.template.Template template = new cms.businesslogic.template.Template(id);
            template.delete();
        }
        public string RenderTemplate(int id)
        {
            const string urlPattern = "http://{0}/?altTemplate={1}";

            var t = new Template(id);
            var host = HttpContext.Current.Request.Url.Host;
            if (HttpContext.Current.Request.Url.Port != 80) host += ":" + HttpContext.Current.Request.Url.Port;

            var url = string.Format(urlPattern, host, t.Alias);
            return ReadUrl(url);
        }
Esempio n. 9
0
        internal static string GetFileContents(Template t)
        {
            string masterpageContent = "";
			if (File.Exists(GetFilePath(t)))
			{
				System.IO.TextReader tr = new StreamReader(GetFilePath(t));
                masterpageContent = tr.ReadToEnd();
                tr.Close();
            }

            return masterpageContent;
        }
Esempio n. 10
0
        internal static string GetFileContents(Template t)
        {
            string viewContent = "";
			string path = IOHelper.MapPath(ViewPath(t.Alias));

            if (File.Exists(path))
            {
                TextReader tr = new StreamReader(path);
                viewContent = tr.ReadToEnd();
                tr.Close();
            }

            return viewContent;
        }
Esempio n. 11
0
        private static string GetDocPath(Template item)
        {
            string path = "";
            if (item != null)
            {
                if (item.MasterTemplate != 0)
                {
                    path = GetDocPath(new Template(item.MasterTemplate));
                }

                path = string.Format("{0}//{1}", path, helpers.XmlDoc.ScrubFile(item.Alias));
            }
            return path;
        }
Esempio n. 12
0
	    internal static string CreateMasterPage(Template t, bool overWrite = false)
        {
            string masterpageContent = "";

			if (!File.Exists(GetFilePath(t)) || overWrite)
                masterpageContent = SaveTemplateToFile(t, t.Alias);
            else
            {
				System.IO.TextReader tr = new StreamReader(GetFilePath(t));
                masterpageContent = tr.ReadToEnd();
                tr.Close();
            }

            return masterpageContent;
        }
Esempio n. 13
0
        /// <summary>
        /// Converts an umbraco template to a package xml node
        /// </summary>
        /// <param name="templateId">The template id.</param>
        /// <param name="doc">The xml doc.</param>
        /// <returns></returns>
        public static XmlNode Template(int templateId, XmlDocument doc) {

            Template tmpl = new Template(templateId);

            XmlNode template = doc.CreateElement("Template");
            template.AppendChild(_node("Name", tmpl.Text, doc));
            template.AppendChild(_node("Alias", tmpl.Alias, doc));

            if (tmpl.MasterTemplate != 0) {
                template.AppendChild(_node("Master", new Template(tmpl.MasterTemplate).Alias, doc));
            }
            template.AppendChild(_node("Design", "<![CDATA[" + tmpl.Design + "]]>", doc));

            return template;
        }
Esempio n. 14
0
        internal static string CreateViewFile(Template t, bool overWrite = false)
        {
            string viewContent;
			string path = IOHelper.MapPath(ViewPath(t.Alias));

            if (File.Exists(path) == false || overWrite)
                viewContent = SaveTemplateToFile(t, t.Alias);
            else
            {
                TextReader tr = new StreamReader(path);
                viewContent = tr.ReadToEnd();
                tr.Close();
            }

            return viewContent;
        }
Esempio n. 15
0
 public static void SaveToDisk(Template 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 ex)
         {
             helpers.uSyncLog.ErrorLog(ex, "uSync: Error Saving Template {0} - {1}", item.Text, ex.ToString());
         }
     }
 }
        /// <summary>
        /// Tries to find and assign an Umbraco document to a <c>PublishedContentRequest</c>.
        /// </summary>
        /// <param name="docRequest">The <c>PublishedContentRequest</c>.</param>
        /// <returns>A value indicating whether an Umbraco document was found and assigned.</returns>
        /// <remarks>If successful, also assigns the template.</remarks>
        public override bool TrySetDocument(PublishedContentRequest docRequest)
        {
            IPublishedContent node = null;
            string            path = docRequest.Uri.GetAbsolutePathDecoded();

            if (docRequest.HasDomain)
            {
                path = DomainHelper.PathRelativeToDomain(docRequest.DomainUri, path);
            }

            if (path != "/")             // no template if "/"
            {
                var pos           = path.LastIndexOf('/');
                var templateAlias = path.Substring(pos + 1);
                path = pos == 0 ? "/" : path.Substring(0, pos);

                //TODO: We need to check if the altTemplate is for MVC or not, though I'm not exactly sure how the best
                // way to do that would be since the template is just an alias and if we are not having a flag on the
                // doc type for rendering engine and basing it only on template name, then how would we handle this?

                var template = Template.GetByAlias(templateAlias);
                if (template != null)
                {
                    LogHelper.Debug <LookupByNiceUrlAndTemplate>("Valid template: \"{0}\"", () => templateAlias);

                    var route = docRequest.HasDomain ? (docRequest.Domain.RootNodeId.ToString() + path) : path;
                    node = LookupDocumentNode(docRequest, route);

                    if (node != null)
                    {
                        docRequest.Template = template;
                    }
                }
                else
                {
                    LogHelper.Debug <LookupByNiceUrlAndTemplate>("Not a valid template: \"{0}\"", () => templateAlias);
                }
            }
            else
            {
                LogHelper.Debug <LookupByNiceUrlAndTemplate>("No template in path \"/\"");
            }

            return(node != null);
        }
Esempio n. 17
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. 18
0
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			//check if a templateId is assigned, meaning we are editing a template
			if (!Request.QueryString["templateID"].IsNullOrWhiteSpace())
			{
				_template = new Template(int.Parse(Request.QueryString["templateID"]));
                TemplateTreeSyncPath = "-1,init," + _template.Path.Replace("-1,", "");
			}
			else if (!Request.QueryString["file"].IsNullOrWhiteSpace())
			{
				//we are editing a view (i.e. partial view)
				OriginalFileName = HttpUtility.UrlDecode(Request.QueryString["file"]);
                TemplateTreeSyncPath = "-1,init," + Path.GetFileName(OriginalFileName);
			}
			else
			{
				throw new InvalidOperationException("Cannot render the editor without a supplied templateId or a file");
			}
			
			Panel1.hasMenu = true;

			SaveButton = Panel1.Menu.NewIcon();
			SaveButton.ImageURL = SystemDirectories.Umbraco + "/images/editor/save.gif";
			SaveButton.AltText = ui.Text("save");
			SaveButton.ID = "save";

			Panel1.Text = ui.Text("edittemplate");
			pp_name.Text = ui.Text("name", base.getUser());
			pp_alias.Text = ui.Text("alias", base.getUser());
			pp_masterTemplate.Text = ui.Text("mastertemplate", base.getUser());

			// Editing buttons
			Panel1.Menu.InsertSplitter();
			MenuIconI umbField = Panel1.Menu.NewIcon();
			umbField.ImageURL = UmbracoPath + "/images/editor/insField.gif";
			umbField.OnClickCommand =
				ClientTools.Scripts.OpenModalWindow(
					IOHelper.ResolveUrl(SystemDirectories.Umbraco) + "/dialogs/umbracoField.aspx?objectId=" +
					editorSource.ClientID + "&tagName=UMBRACOGETDATA&mvcView=true", ui.Text("template", "insertPageField"), 640, 550);
			umbField.AltText = ui.Text("template", "insertPageField");


			// TODO: Update icon
			MenuIconI umbDictionary = Panel1.Menu.NewIcon();
			umbDictionary.ImageURL = GlobalSettings.Path + "/images/editor/dictionaryItem.gif";
			umbDictionary.OnClickCommand =
				ClientTools.Scripts.OpenModalWindow(
					IOHelper.ResolveUrl(SystemDirectories.Umbraco) + "/dialogs/umbracoField.aspx?objectId=" +
                    editorSource.ClientID + "&tagName=UMBRACOGETDICTIONARY&mvcView=true", ui.Text("template", "insertDictionaryItem"),
					640, 550);
			umbDictionary.AltText = "Insert umbraco dictionary item";

			var macroSplitButton = new InsertMacroSplitButton
				{
					ClientCallbackInsertMacroMarkup = "function(alias) {editViewEditor.insertMacroMarkup(alias);}",
					ClientCallbackOpenMacroModel = "function(alias) {editViewEditor.openMacroModal(alias);}"
				};
			Panel1.Menu.InsertNewControl(macroSplitButton, 40);
			
			if (_template == null)
			{
				InitializeEditorForPartialView();
			}
			else
			{
				InitializeEditorForTemplate();	
			}
			
		}
Esempio n. 19
0
        private HtmlNode FindModule(int template, string id, bool remove)
        {
            Template t = new Template(template);
            string TargetFile = t.MasterPageFile;
            string TargetID = id;

            HtmlDocument doc = new HtmlDocument();
            doc.Load(TargetFile);

            if (doc.DocumentNode.SelectSingleNode(string.Format("//*[@id = '{0}']", TargetID)) != null)
            {
                if (!remove)
                    return doc.DocumentNode.SelectSingleNode(string.Format("//*[@id = '{0}']", TargetID));
                else
                {
                    HtmlNode r = doc.DocumentNode.SelectSingleNode(string.Format("//*[@id = '{0}']", TargetID)).Clone();

                    doc.DocumentNode.SelectSingleNode(string.Format("//*[@id = '{0}']", TargetID)).RemoveAll();

                    doc.Save(TargetFile);

                    return r;
                }
            }
            else
            {
                if (t.HasMasterTemplate)
                    return FindModule(template,id,remove);
                else
                    return null;
            }
        }
Esempio n. 20
0
        private bool InsertModule(int template, string targetId, string tag, bool prepend)
        {
            Template t = new Template(template);

            string TargetFile = t.MasterPageFile;
            string TargetID = targetId;

            HtmlDocument doc = new HtmlDocument();
            doc.Load(TargetFile);

            if (doc.DocumentNode.SelectNodes(string.Format("//*[@id = '{0}']", TargetID)) != null)
            {
                foreach (HtmlNode target in doc.DocumentNode.SelectNodes(string.Format("//*[@id = '{0}']", TargetID)))
                {
                    HtmlNode macrotag = HtmlNode.CreateNode(tag);

                    if (prepend)
                        target.PrependChild(macrotag);
                    else
                        target.AppendChild(macrotag);
                }
                doc.Save(TargetFile);

                return true;
            }
            else
            {
                //might be on master template
                if (t.HasMasterTemplate)
                    return InsertModule(t.MasterTemplate, targetId, tag, prepend);
                else
                    return false;
            }
        }
Esempio n. 21
0
        private bool CanInsertModules(int template)
        {
            Template t = new Template(template);

            HtmlDocument doc = new HtmlDocument();
            doc.Load(t.MasterPageFile);

            if (doc.DocumentNode.SelectNodes(string.Format("//*[@class = '{0}']", "umbModuleContainer")) != null)
                return true;
            else
            {
                if (t.HasMasterTemplate)
                    return CanInsertModules(t.MasterTemplate);
                else
                    return false;
            }

        }
Esempio n. 22
0
        private bool MoveModule(int template, HtmlNode module, string targetId, int index)
        {
            Template t = new Template(template);

            string TargetFile = t.MasterPageFile;
            string TargetID = targetId;

            HtmlDocument doc = new HtmlDocument();
            doc.Load(TargetFile);

            if (doc.DocumentNode.SelectNodes(string.Format("//*[@id = '{0}']", TargetID)) != null)
            {
                HtmlNode parent = doc.DocumentNode.SelectSingleNode(string.Format("//*[@id = '{0}']", TargetID));

                if (index > 0 && parent.ChildNodes.Count > 0)
                {
                    parent.InsertAfter(module, parent.ChildNodes[index - 1]);
                }
                else if (index == 0 && parent.ChildNodes.Count > 0)
                {
                    parent.InsertBefore(module, parent.ChildNodes[0]);
                }
                else
                {
                    parent.AppendChild(module);
                    //parent.ChildNodes.Add(module);
                }

                doc.Save(TargetFile);

                return true;

            }
            else
            {
                //might be on master template
                if (t.HasMasterTemplate)
                    return MoveModule(template, module, targetId,index);
                else
                    return false;
            }
        }
Esempio n. 23
0
		/// <summary>
		/// Return a new RoutingContext
		/// </summary>
		/// <param name="url"></param>
		/// <param name="template"></param>
		/// <param name="routeData"></param>
		/// <returns></returns>
		protected RoutingContext GetRoutingContext(string url, Template template, RouteData routeData = null)
		{
			return GetRoutingContext(url, template.Id, routeData);
		}
		public JsonResult SaveTemplate(string templateName, string templateAlias, string templateContents, int templateId, int masterTemplateId)
		{
			Template t;
			try
			{
				t = new Template(templateId)
						{
							Text = templateName,
							Alias = templateAlias,
							MasterTemplate = masterTemplateId,
							Design = templateContents
						};
			}
			catch (ArgumentException ex)
			{
				//the template does not exist
				return Failed("Template does not exist", ui.Text("speechBubbles", "templateErrorHeader"), ex);
			}

			try
			{
				t.Save();

				// Clear cache in rutime
				if (UmbracoSettings.UseDistributedCalls)
					dispatcher.Refresh(new Guid("dd12b6a0-14b9-46e8-8800-c154f74047c8"), t.Id);
				else
					template.ClearCachedTemplate(t.Id);

				return Success(ui.Text("speechBubbles", "templateSavedText"), ui.Text("speechBubbles", "templateSavedHeader"));
			}
			catch (Exception ex)
			{
				return Failed(ui.Text("speechBubbles", "templateErrorText"), ui.Text("speechBubbles", "templateErrorHeader"), ex);
			}
		}
Esempio n. 25
0
        public void SaveMasterPageFile(string masterPageContent)
        {
            // Add header to master page if it doesn't exist
            if (!masterPageContent.StartsWith("<%@"))
            {
                masterPageContent = getMasterPageHeader() + "\n" + masterPageContent;
            }
            else
            {
                // verify that the masterpage attribute is the same as the masterpage
                string masterHeader = masterPageContent.Substring(0, masterPageContent.IndexOf("%>") + 2).Trim(Environment.NewLine.ToCharArray());
                // find the masterpagefile attribute
                MatchCollection m = Regex.Matches(masterHeader, "(?<attributeName>\\S*)=\"(?<attributeValue>[^\"]*)\"",
                                  RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
                foreach (Match attributeSet in m)
                {
                    if (attributeSet.Groups["attributeName"].Value.ToLower() == "masterpagefile")
                    {
                        // validate the masterpagefile
                        string currentMasterPageFile = attributeSet.Groups["attributeValue"].Value;
                        string currentMasterTemplateFile = currentMasterTemplateFileName();
                        if (currentMasterPageFile != currentMasterTemplateFile)
                        {
                            masterPageContent =
                                masterPageContent.Replace(
                                attributeSet.Groups["attributeName"].Value + "=\"" + currentMasterPageFile + "\"",
                                attributeSet.Groups["attributeName"].Value + "=\"" + currentMasterTemplateFile + "\"");

                        }
                    }
                }

            }

            //we have a Old Alias if the alias and therefor the masterpage file name has changed...
            //so before we save the new masterfile, we'll clear the old one, so we don't up with
            //Unused masterpage files
            if (!string.IsNullOrEmpty(_oldAlias) && _oldAlias != _alias)
            {

                //Ensure that child templates have the right master masterpage file name
                if (HasChildren)
                {
                    //store children array here because iterating over an Array property object is very inneficient.
                    var c = Children;
                    foreach (CMSNode cmn in c)
                    {
                        Template t = new Template(cmn.Id);
                        t.SaveAsMasterPage();
                        t.Save();
                    }
                }

                //then kill the old file..
                string _oldFile = IOHelper.MapPath(SystemDirectories.Masterpages + "/" + _oldAlias.Replace(" ", "") + ".master");

                if (System.IO.File.Exists(_oldFile))
                    System.IO.File.Delete(_oldFile);
            }

            // save the file in UTF-8

            File.WriteAllText(MasterPageFile, masterPageContent, System.Text.Encoding.UTF8);
        }
Esempio n. 26
0
 public string GetMasterContentElement(int masterTemplateId)
 {
     if (masterTemplateId != 0)
     {
         string masterAlias = new Template(masterTemplateId).Alias.Replace(" ", "");
         return
             String.Format("<asp:Content ContentPlaceHolderID=\"{1}ContentPlaceHolder\" runat=\"server\">",
             Alias.Replace(" ", ""), masterAlias);
     }
     else
         return
             String.Format("<asp:Content ContentPlaceHolderID=\"ContentPlaceHolderDefault\" runat=\"server\">",
             Alias.Replace(" ", ""));
 }
Esempio n. 27
0
        public static Template MakeNew(string Name, BusinessLogic.User u)
        {
            //ensure unique alias
            if (GetByAlias(Name) != null)
                Name = EnsureUniqueAlias(Name, 1);

            // CMSNode MakeNew(int parentId, Guid objectType, int userId, int level, string text, Guid uniqueID)
            CMSNode n = CMSNode.MakeNew(-1, _objectType, u.Id, 1, Name, Guid.NewGuid());
            Name = Name.Replace("/", ".").Replace("\\", "");

            if (Name.Length > 100)
                Name = Name.Substring(0, 95) + "...";

            SqlHelper.ExecuteNonQuery("INSERT INTO cmsTemplate (NodeId, Alias, design, master) VALUES (@nodeId, @alias, @design, @master)",
                                      SqlHelper.CreateParameter("@nodeId", n.Id),
                                      SqlHelper.CreateParameter("@alias", Name),
                                      SqlHelper.CreateParameter("@design", ' '),
                                      SqlHelper.CreateParameter("@master", DBNull.Value));

            Template t = new Template(n.Id);
            NewEventArgs e = new NewEventArgs();
            t.OnNew(e);

            return t;
        }
Esempio n. 28
0
        public static Template MakeNew(string Name, BusinessLogic.User u, Template master)
        {
            //ensure unique alias
            if (GetByAlias(Name) != null)
                Name = EnsureUniqueAlias(Name, 1);

            Template t = MakeNew(Name, u);
            t.MasterTemplate = master.Id;
            t.Design = "";

            if (UmbracoSettings.UseAspNetMasterPages)
            {
                string design = t.getMasterPageHeader() + "\n";

                foreach (string cpId in master.contentPlaceholderIds())
                {
                    design += "<asp:content ContentPlaceHolderId=\"" + cpId + "\" runat=\"server\">\n\t\n</asp:content>\n\n";
                }

                t.Design = design;
            }

            t.Save();
            return t;
        }
Esempio n. 29
0
        protected void SelectStarterKitDesign(object sender, EventArgs e)
        {
            if (((Button)sender).CommandName == "apply")
            {
                Skin s = Skin.CreateFromName(((Button)sender).CommandArgument);
                Skinning.ActivateAsCurrentSkin(s);

                Page.Response.Redirect(library.NiceUrl(int.Parse(UmbracoContext.Current.PageId.ToString())));
            }
            else if (((Button)sender).CommandName == "remove")
            {
                NodeFactory.Node n = NodeFactory.Node.GetCurrent();

                Template t = new Template(n.template);
                Skinning.RollbackSkin(t.Id);

                Page.Response.Redirect(library.NiceUrl(int.Parse(UmbracoContext.Current.PageId.ToString())));
            }
            else
            {

                Guid kitGuid = new Guid(((Button)sender).CommandArgument);

                cms.businesslogic.packager.Installer installer = new cms.businesslogic.packager.Installer();

                if (repo.HasConnection())
                {
                    cms.businesslogic.packager.Installer p = new cms.businesslogic.packager.Installer();

                    string tempFile = p.Import(repo.fetch(kitGuid.ToString()));
                    p.LoadConfig(tempFile);
                    int pID = p.CreateManifest(tempFile, kitGuid.ToString(), repoGuid);

                    p.InstallFiles(pID, tempFile);
                    p.InstallBusinessLogic(pID, tempFile);
                    p.InstallCleanUp(pID, tempFile);

                    library.RefreshContent();

                    if (cms.businesslogic.skinning.Skinning.GetAllSkins().Count > 0)
                    {
                        cms.businesslogic.skinning.Skinning.ActivateAsCurrentSkin(cms.businesslogic.skinning.Skinning.GetAllSkins()[0]);
                    }


                    Page.Response.Redirect(library.NiceUrl(int.Parse(UmbracoContext.Current.PageId.ToString())));
                }
                else
                {
                    //ShowConnectionError();
                }
            }
        }
Esempio n. 30
0
		protected override void OnInit(EventArgs e)
		{
			_template = new Template(int.Parse(Request.QueryString["templateID"]));
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			Panel1.hasMenu = true;

			SaveButton = Panel1.Menu.NewIcon();
			SaveButton.ImageURL = SystemDirectories.Umbraco + "/images/editor/save.gif";
			//SaveButton.OnClickCommand = "doSubmit()";
			SaveButton.AltText = ui.Text("save");
			SaveButton.ID = "save";

			Panel1.Text = ui.Text("edittemplate");
			pp_name.Text = ui.Text("name", base.getUser());
			pp_alias.Text = ui.Text("alias", base.getUser());
			pp_masterTemplate.Text = ui.Text("mastertemplate", base.getUser());

			// Editing buttons
			Panel1.Menu.InsertSplitter();
			MenuIconI umbField = Panel1.Menu.NewIcon();
			umbField.ImageURL = UmbracoPath + "/images/editor/insField.gif";
			umbField.OnClickCommand =
				ClientTools.Scripts.OpenModalWindow(
					IOHelper.ResolveUrl(SystemDirectories.Umbraco) + "/dialogs/umbracoField.aspx?objectId=" +
					editorSource.ClientID + "&tagName=UMBRACOGETDATA&mvcView=true", ui.Text("template", "insertPageField"), 640, 550);
			umbField.AltText = ui.Text("template", "insertPageField");


			// TODO: Update icon
			MenuIconI umbDictionary = Panel1.Menu.NewIcon();
			umbDictionary.ImageURL = GlobalSettings.Path + "/images/editor/dictionaryItem.gif";
			umbDictionary.OnClickCommand =
				ClientTools.Scripts.OpenModalWindow(
					IOHelper.ResolveUrl(SystemDirectories.Umbraco) + "/dialogs/umbracoField.aspx?objectId=" +
                    editorSource.ClientID + "&tagName=UMBRACOGETDICTIONARY&mvcView=true", ui.Text("template", "insertDictionaryItem"),
					640, 550);
			umbDictionary.AltText = "Insert umbraco dictionary item";

			//uicontrols.MenuIconI umbMacro = Panel1.Menu.NewIcon();
			//umbMacro.ImageURL = UmbracoPath + "/images/editor/insMacro.gif";
			//umbMacro.AltText = ui.Text("template", "insertMacro");
			//umbMacro.OnClickCommand = umbraco.BasePages.ClientTools.Scripts.OpenModalWindow(umbraco.IO.IOHelper.ResolveUrl(umbraco.IO.SystemDirectories.Umbraco) + "/dialogs/editMacro.aspx?objectId=" + editorSource.ClientID, ui.Text("template", "insertMacro"), 470, 530);

			Panel1.Menu.NewElement("div", "splitButtonMacroPlaceHolder", "sbPlaceHolder", 40);

			if (UmbracoSettings.UseAspNetMasterPages)
			{
				Panel1.Menu.InsertSplitter();

				MenuIconI umbContainer = Panel1.Menu.NewIcon();
				umbContainer.ImageURL = UmbracoPath + "/images/editor/masterpagePlaceHolder.gif";
				umbContainer.AltText = ui.Text("template", "insertContentAreaPlaceHolder");
				umbContainer.OnClickCommand =
					ClientTools.Scripts.OpenModalWindow(
						IOHelper.ResolveUrl(SystemDirectories.Umbraco) +
						"/dialogs/insertMasterpagePlaceholder.aspx?&id=" + _template.Id,
						ui.Text("template", "insertContentAreaPlaceHolder"), 470, 320);

				MenuIconI umbContent = Panel1.Menu.NewIcon();
				umbContent.ImageURL = UmbracoPath + "/images/editor/masterpageContent.gif";
				umbContent.AltText = ui.Text("template", "insertContentArea");
				umbContent.OnClickCommand =
					ClientTools.Scripts.OpenModalWindow(
						IOHelper.ResolveUrl(SystemDirectories.Umbraco) + "/dialogs/insertMasterpageContent.aspx?id=" +
						_template.Id, ui.Text("template", "insertContentArea"), 470, 300);
			}


			//Spit button
			Panel1.Menu.InsertSplitter();
			Panel1.Menu.NewElement("div", "splitButtonPlaceHolder", "sbPlaceHolder", 40);

			// Help
			Panel1.Menu.InsertSplitter();

			MenuIconI helpIcon = Panel1.Menu.NewIcon();
			helpIcon.OnClickCommand =
				ClientTools.Scripts.OpenModalWindow(
					IOHelper.ResolveUrl(SystemDirectories.Umbraco) + "/settings/modals/showumbracotags.aspx?alias=" +
					_template.Alias, ui.Text("template", "quickGuide"), 600, 580);
			helpIcon.ImageURL = UmbracoPath + "/images/editor/help.png";
			helpIcon.AltText = ui.Text("template", "quickGuide");
		}
Esempio n. 31
0
 public static Template MakeNew(string Name, BusinessLogic.User u, Template master)
 {
     return MakeNew(Name, u, master, null);
 }
Esempio n. 32
0
        private static Template MakeNew(string name, BusinessLogic.User u, Template master, string design)
        {

            // CMSNode MakeNew(int parentId, Guid objectType, int userId, int level, string text, Guid uniqueID)
            CMSNode n = CMSNode.MakeNew(-1, _objectType, u.Id, 1, name, Guid.NewGuid());

            //ensure unique alias 
            name = helpers.Casing.SafeAlias(name);
            if (GetByAlias(name) != null)
                name = EnsureUniqueAlias(name, 1);
            name = name.Replace("/", ".").Replace("\\", "");

            if (name.Length > 100)
                name = name.Substring(0, 95) + "...";

          
            SqlHelper.ExecuteNonQuery("INSERT INTO cmsTemplate (NodeId, Alias, design, master) VALUES (@nodeId, @alias, @design, @master)",
                                      SqlHelper.CreateParameter("@nodeId", n.Id),
                                      SqlHelper.CreateParameter("@alias", name),
                                      SqlHelper.CreateParameter("@design", ' '),
                                      SqlHelper.CreateParameter("@master", DBNull.Value));

            Template t = new Template(n.Id);
            NewEventArgs e = new NewEventArgs();
            t.OnNew(e);

            if (master != null)
                t.MasterTemplate = master.Id;

			switch (DetermineRenderingEngine(t, design))
			{
				case RenderingEngine.Mvc:
					ViewHelper.CreateViewFile(t);
					break;
				case RenderingEngine.WebForms:
					MasterPageHelper.CreateMasterPage(t);
					break;
			}

			//if a design is supplied ensure it is updated.
			if (!design.IsNullOrWhiteSpace())
			{
				t.ImportDesign(design);
			}

            return t;
        }
Esempio n. 33
0
 public static Template MakeNew(string Name, BusinessLogic.User u, Template master)
 {
     return(MakeNew(Name, u, master, null));
 }