Template CreateTemplate(string alias)
 {
     var template = new Template(alias, alias, alias);
     template.Content = ""; // else saving throws with a dirty internal error
     ApplicationContext.Services.FileService.SaveTemplate(template);
     return template;
 }
        public void Can_Perform_Add_MasterPage()
        {
            // Arrange
            var provider = new PetaPocoUnitOfWorkProvider();
            var unitOfWork = provider.GetUnitOfWork();
            var repository = new TemplateRepository(unitOfWork, NullCacheProvider.Current, _masterPageFileSystem, _viewsFileSystem);

            // Act
            var template = new Template("test-add-masterpage.master", "test", "test") { Content = @"<%@ Master Language=""C#"" %>" };
            repository.AddOrUpdate(template);
            unitOfWork.Commit();

            //Assert
            Assert.That(repository.Get("test"), Is.Not.Null);
            Assert.That(_masterPageFileSystem.FileExists("test.master"), Is.True);
        }
        /// <summary>
        /// Creates a View if specified in the attribute
        /// </summary>
        /// <param name="fileService"></param>
        /// <param name="attribute"></param>
        /// <param name="type"></param>
        /// <param name="newContentType"></param>
        private static void CreateMatchingView(IFileService fileService, UmbracoContentTypeAttribute attribute, Type type, IContentType newContentType)
        {
            Template currentTemplate = fileService.GetTemplate(attribute.ContentTypeAlias) as Template;
            if (currentTemplate == null)
            {
                currentTemplate = new Template("~/Views/" + attribute.ContentTypeAlias + ".cshtml", attribute.ContentTypeName, attribute.ContentTypeAlias);
                CreateViewFile(attribute.ContentTypeAlias, attribute.MasterTemplate, currentTemplate, type, fileService);
            }

            newContentType.AllowedTemplates = new ITemplate[] { currentTemplate };
            newContentType.SetDefaultTemplate(currentTemplate);

            //TODO: in Umbraco 7.1 it will be possible to set the master template of the newly created template
            //https://github.com/umbraco/Umbraco-CMS/pull/294
        }
Exemplo n.º 4
0
 private static Template ImportTemplate(ServiceContext svces, string filepath, string name, string alias, string text, ITemplate master = null)
 {
     var t = new Template(filepath, name, alias) { Content = text };
     if (master != null)
         t.SetMasterTemplate(master);
     svces.FileService.SaveTemplate(t);
     return t;
 }
        /// <summary>
        /// Convention to resolve referenced templates
        /// </summary>
        /// <param name="templateNames"></param>
        /// <returns></returns>
        private static IEnumerable<ITemplate> AllowedTemplatesConvention(IEnumerable<string> templateNames)
        {
            var templates = new List<ITemplate>();
            var engine = UmbracoSettings.DefaultRenderingEngine;
            foreach (var templateName in templateNames)
            {
                var @alias = engine == RenderingEngine.Mvc
                               ? templateName.Replace(".cshtml", "").Replace(".vbhtml", "")
                               : templateName.Replace(".masterpage", "");

				var template = ApplicationContext.Current.Services.FileService.GetTemplate(@alias);
                if(template == null)
                {
                    var name = engine == RenderingEngine.Mvc
                               ? string.Concat(@alias, ".cshtml")
                               : string.Concat(@alias, ".masterpage");

                    template = new Template(string.Empty, name, @alias) { CreatorId = 0, Content = string.Empty};
					ApplicationContext.Current.Services.FileService.SaveTemplate(template);
                }
                templates.Add(template);
            }
            return templates;
        }
Exemplo n.º 6
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);
		}
        private ITemplate CreateTemplate(TemplateAttribute attribute)
        {
            var path = "~/Views/" + attribute.TemplateAlias.ToPascalCase() + ".cshtml";
            var template = new Template(path, attribute.TemplateName, attribute.TemplateAlias);
            lock (_lock)
            {
                if (System.IO.File.Exists(HostingEnvironment.MapPath(path)))
                {
                    //get the existing content from the file so it isn't overwritten when we save the template.
                    template.Content = System.IO.File.ReadAllText(HostingEnvironment.MapPath(path));
                }
                else
                {
                    //TODO get this from a file resource containing a default view
                    var content = "@inherits Felinesoft.UmbracoCodeFirst.Views.UmbracoDocumentViewPage<" + attribute.DecoratedTypeFullName + ">" + Environment.NewLine + Environment.NewLine;
                    template.Content = content;
                }

                _fileService.SaveTemplate(template);
            }
            return template;
        }
        private static void CreateViewFile(string masterTemplate, Template template, Type type, IFileService fileService)
        {
            string physicalViewFileLocation = HostingEnvironment.MapPath(template.Path);
            if (string.IsNullOrEmpty(physicalViewFileLocation))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Failed to {0} to a physical location", template.Path));
            }

            var templateContent = CreateDefaultTemplateContent(masterTemplate, type);
            template.Content = templateContent;

            using (var sw = System.IO.File.CreateText(physicalViewFileLocation))
            {
                sw.Write(templateContent);
            }

            //This code doesn't work because template.MasterTemplateId is defined internal
            //I'll do a pull request to change this
            //TemplateNode rootTemplate = fileService.GetTemplateNode(master);
            //template.MasterTemplateId = new Lazy<int>(() => { return rootTemplate.Template.Id; });
            fileService.SaveTemplate(template, 0);

            //    //TODO: in Umbraco 7.1 it will be possible to set the master template of the newly created template
            //    //https://github.com/umbraco/Umbraco-CMS/pull/294
        }
        public void Can_Get_Template_Tree()
        {
            // Arrange
            var provider = new PetaPocoUnitOfWorkProvider();
            var unitOfWork = provider.GetUnitOfWork();
            var repository = new TemplateRepository(unitOfWork, NullCacheProvider.Current, _masterPageFileSystem, _viewsFileSystem);

            var parent = new Template("test-parent-masterpage.master", "parent", "parent") { Content = @"<%@ Master Language=""C#"" %>" };
            
            var child1 = new Template("test-child1-masterpage.master", "child1", "child1") { Content = @"<%@ Master Language=""C#"" %>" };
            var toddler1 = new Template("test-toddler1-masterpage.master", "toddler1", "toddler1") { Content = @"<%@ Master Language=""C#"" %>" };
            var toddler2 = new Template("test-toddler2-masterpage.master", "toddler2", "toddler2") { Content = @"<%@ Master Language=""C#"" %>" };
            var baby1 = new Template("test-baby1-masterpage.master", "baby1", "baby1") { Content = @"<%@ Master Language=""C#"" %>" };

            var child2 = new Template("test-child2-masterpage.master", "child2", "child2") { Content = @"<%@ Master Language=""C#"" %>" };
            var toddler3 = new Template("test-toddler3-masterpage.master", "toddler3", "toddler3") { Content = @"<%@ Master Language=""C#"" %>" };
            var toddler4 = new Template("test-toddler4-masterpage.master", "toddler4", "toddler4") { Content = @"<%@ Master Language=""C#"" %>" };
            var baby2 = new Template("test-baby2-masterpage.master", "baby2", "baby2") { Content = @"<%@ Master Language=""C#"" %>" };
            
            
            child1.MasterTemplateAlias = parent.Alias;
            child1.MasterTemplateId = new Lazy<int>(() => parent.Id);
            child2.MasterTemplateAlias = parent.Alias;
            child2.MasterTemplateId = new Lazy<int>(() => parent.Id);

            toddler1.MasterTemplateAlias = child1.Alias;
            toddler1.MasterTemplateId = new Lazy<int>(() => child1.Id);
            toddler2.MasterTemplateAlias = child1.Alias;
            toddler2.MasterTemplateId = new Lazy<int>(() => child1.Id);

            toddler3.MasterTemplateAlias = child2.Alias;
            toddler3.MasterTemplateId = new Lazy<int>(() => child2.Id);
            toddler4.MasterTemplateAlias = child2.Alias;
            toddler4.MasterTemplateId = new Lazy<int>(() => child2.Id);

            baby1.MasterTemplateAlias = toddler2.Alias;
            baby1.MasterTemplateId = new Lazy<int>(() => toddler2.Id);

            baby2.MasterTemplateAlias = toddler4.Alias;
            baby2.MasterTemplateId = new Lazy<int>(() => toddler4.Id);

            repository.AddOrUpdate(parent);
            repository.AddOrUpdate(child1);
            repository.AddOrUpdate(child2);
            repository.AddOrUpdate(toddler1);
            repository.AddOrUpdate(toddler2);
            repository.AddOrUpdate(toddler3);
            repository.AddOrUpdate(toddler4);
            repository.AddOrUpdate(baby1);
            repository.AddOrUpdate(baby2);
            unitOfWork.Commit();

            // Act
            var rootNode = repository.GetTemplateNode("parent");
            
            // Assert
            Assert.IsNotNull(repository.FindTemplateInTree(rootNode, "parent"));
            Assert.IsNotNull(repository.FindTemplateInTree(rootNode, "child1"));
            Assert.IsNotNull(repository.FindTemplateInTree(rootNode, "child2"));
            Assert.IsNotNull(repository.FindTemplateInTree(rootNode, "toddler1"));
            Assert.IsNotNull(repository.FindTemplateInTree(rootNode, "toddler2"));
            Assert.IsNotNull(repository.FindTemplateInTree(rootNode, "toddler3"));
            Assert.IsNotNull(repository.FindTemplateInTree(rootNode, "toddler4"));
            Assert.IsNotNull(repository.FindTemplateInTree(rootNode, "baby1"));
            Assert.IsNotNull(repository.FindTemplateInTree(rootNode, "baby2"));
        }
        public void Can_Perform_Delete()
        {
            // Arrange
            var provider = new PetaPocoUnitOfWorkProvider();
            var unitOfWork = provider.GetUnitOfWork();
            var repository = new TemplateRepository(unitOfWork, NullCacheProvider.Current, _masterPageFileSystem, _viewsFileSystem);

            var template = new Template("test-add-masterpage.master", "test", "test") { Content = @"<%@ Master Language=""C#"" %>" };
            repository.AddOrUpdate(template);
            unitOfWork.Commit();

            // Act
            var templates = repository.Get("test");
            repository.Delete(templates);
            unitOfWork.Commit();

            // Assert
            Assert.IsNull(repository.Get("test"));
        }
        public void Can_Perform_Delete_On_Nested_Templates()
        {
            // Arrange
            var provider = new PetaPocoUnitOfWorkProvider();
            var unitOfWork = provider.GetUnitOfWork();
            var repository = new TemplateRepository(unitOfWork, NullCacheProvider.Current, _masterPageFileSystem, _viewsFileSystem);

            var parent = new Template("test-parent-masterpage.master", "parent", "parent") { Content = @"<%@ Master Language=""C#"" %>" };
            var child = new Template("test-child-masterpage.master", "child", "child") { Content = @"<%@ Master Language=""C#"" %>" };
            var baby = new Template("test-baby-masterpage.master", "baby", "baby") { Content = @"<%@ Master Language=""C#"" %>" };            
            child.MasterTemplateAlias = parent.Alias;
            child.MasterTemplateId = new Lazy<int>(() => parent.Id);
            baby.MasterTemplateAlias = child.Alias;
            baby.MasterTemplateId = new Lazy<int>(() => child.Id);
            repository.AddOrUpdate(parent);
            repository.AddOrUpdate(child);
            repository.AddOrUpdate(baby);
            unitOfWork.Commit();

            // Act
            var templates = repository.Get("parent");
            repository.Delete(templates);
            unitOfWork.Commit();

            // Assert
            Assert.IsNull(repository.Get("test"));
        }
        private static void CreateViewFile(string masterTemplate, Template template, Type type, IFileService fileService)
        {
            string physicalViewFileLocation = HostingEnvironment.MapPath(template.Path);
            if (string.IsNullOrEmpty(physicalViewFileLocation))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Failed to {0} to a physical location", template.Path));
            }

            var templateContent = CreateDefaultTemplateContent(masterTemplate, type);
            template.Content = templateContent;

            using (var sw = System.IO.File.CreateText(physicalViewFileLocation))
            {
                sw.Write(templateContent);
            }
        }
        /// <summary>
        /// Creates an Umbraco template and associated view file.
        /// </summary>
        /// <param name="fileService">The file service.</param>
        /// <param name="displayName">The display name of the Umbraco template.</param>
        /// <param name="templateAlias">Alias of the template, also used as the name of the view file.</param>
        /// <param name="masterTemplate">The master page or MVC to inherit from.</param>
        /// <param name="type">An Inception type name used in the generated view file.</param>
        /// <param name="customDirectoryPath">The custom directory path if not ~/Views/.</param>
        /// <returns></returns>
        private static Template CreateTemplateIfNotExists(IFileService fileService, string displayName, string templateAlias, string masterTemplate=null, Type type=null, string customDirectoryPath=null)
        {
            var template = fileService.GetTemplate(templateAlias) as Template;
            if (template == null)
            {
                var defaultDirectoryPath = "~/Views/";
                var defaultFilePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}.cshtml", defaultDirectoryPath, templateAlias);

                string filePath;
                if (string.IsNullOrEmpty(customDirectoryPath))
                {
                    filePath = defaultFilePath;
                }
                else
                {
                    filePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}.cshtml",
                        customDirectoryPath, // The template location
                        customDirectoryPath.EndsWith("/") ? string.Empty : "/", // Ensure the template location ends with a "/"
                        templateAlias); // The alias
                }

                string physicalViewFileLocation = HostingEnvironment.MapPath(filePath);
                if (System.IO.File.Exists(physicalViewFileLocation))
                {
                    // If we create the template record in the database Umbraco will create a view file regardless, overwriting what's there. 
                    // If the MVC view is already there we can protect it by making a temporary copy which can then be moved back to the original location. 
                    System.IO.File.Copy(physicalViewFileLocation, physicalViewFileLocation + ".temp");

                    template = new Template(defaultDirectoryPath, displayName, templateAlias);
                    fileService.SaveTemplate(template, 0);

                    if (System.IO.File.Exists(physicalViewFileLocation) && System.IO.File.Exists(physicalViewFileLocation + ".temp"))
                    {
                        System.IO.File.Delete(physicalViewFileLocation);
                        System.IO.File.Move(physicalViewFileLocation + ".temp", physicalViewFileLocation);
                    }
                }
                else
                {
                    template = new Template(filePath, displayName, templateAlias);
                    CreateViewFile(masterTemplate, template, type, fileService);
                    fileService.SaveTemplate(template, 0);
                }
            }
            return template;
        }
        private static void AddToAllowedTemplates(Template template, IContentType documentType)
        {
            var allowedTemplates = new List<ITemplate>(documentType.AllowedTemplates);

            var alreadyAllowed = false;
            foreach (var allowedTemplate in allowedTemplates)
            {
                //  Use .Id because Umbraco 7.4.x throws an exception accessing .Alias due to an internal cast 
                if (allowedTemplate.Id == template.Id)
                {
                    alreadyAllowed = true;
                    break;
                }
            }

            if (!alreadyAllowed)
            {
                allowedTemplates.Add(template);
                documentType.AllowedTemplates = allowedTemplates;
            }
        }
        private static void CreateViewFile(string alias, string master, Template template, Type type, IFileService fileService)
        {
            string physicalView = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, ViewsFolder + "\\" + alias + ".cshtml");

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("@inherits Umbraco.Web.Mvc.UmbracoTemplatePage");
            sb.AppendLine("@*@using Qite.Umbraco.CodeFirst.Extensions;*@");
            sb.AppendLine("@{");
            sb.AppendLine("\tLayout = \"" + master + ".cshtml\";");
            sb.AppendLine("\t//" + type.Name + " model = Model.Content.ConvertToRealModel<" + type.Name + ">();");
            sb.AppendLine("}");

            using (StreamWriter sw = System.IO.File.CreateText(physicalView))
            {
                sw.Write(sb.ToString());
            }

            template.Content = sb.ToString();
            //This code doesn't work because template.MasterTemplateId is defined internal
            //I'll do a pull request to change this
            //TemplateNode rootTemplate = fileService.GetTemplateNode(master);
            //template.MasterTemplateId = new Lazy<int>(() => { return rootTemplate.Template.Id; });
            fileService.SaveTemplate(template, 0);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Import
        /// </summary>
        /// <param name="content">content</param>
        /// <param name="umbApplication">umb Application</param>
        /// <param name="appContext">app Context</param>
        /// <returns></returns>
        public void Import(Site site, ApplicationContext appContext)
        {
            references.Clear();
            
            var mediaService = appContext.Services.MediaService;
            var cts = appContext.Services.ContentTypeService;
            
            var folderTypeID = cts.GetMediaType(Constants.Conventions.MediaTypes.Folder).Id;
            var folders = mediaService.GetMediaOfMediaType(folderTypeID);
            foreach (var folder in folders)
            {
                if (folder.Name == site.Name)
                {
                    foreach (var media in mediaService.GetChildren(folder.Id))
                    {
                        mediaService.Delete(media);
                    }

                    mediaService.Delete(folder);
                    break;
                }
            }
            
            var serializer = new SiteSerializer();

            //Accents removal
            byte[] tempBytes;
            tempBytes = System.Text.Encoding.GetEncoding("ISO-8859-8").GetBytes(site.Name.ToLowerInvariant());            
            string siteAlias = System.Text.Encoding.UTF8.GetString(tempBytes);
            siteAlias = siteAlias.Replace(" ", string.Empty);
            //site.Root.Name = site.Name;

            var fileService = appContext.Services.FileService;
                        
            var scriptPath = HostingEnvironment.MapPath("/scripts") + Path.DirectorySeparatorChar;
            var cssPath = HostingEnvironment.MapPath("/css") + Path.DirectorySeparatorChar;
            var resourcePath = site.Name + '/';
            
            var mediaParent = mediaService.CreateMediaWithIdentity(site.Name, -1, Constants.Conventions.MediaTypes.Folder);

            foreach (var resource in site.Resources)
            {
                var filePath = resource.TextData;
                
                if (resource.ResourceType == ResourceType.Javascript)
                {
                    try
                    {
                        var scripts = fileService.GetScripts(resource.TextData.ToLowerInvariant());
                        if (scripts != null && scripts.Any())
                        {
                            foreach (var item in scripts)
                            {
                                fileService.DeleteScript(item.Name);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.StackTrace);
                    }

                    var newPath = scriptPath + Path.GetFileName(filePath);
                    if (!newPath.EndsWith(".js"))
                    {
                        newPath = newPath + ".js";
                    }
                    
                    var script = new Script(filePath);
                    fileService.SaveScript(script);
                    System.IO.File.Copy(filePath, newPath, true);
                    AddToReferences(resource.TemplateReference, newPath, true);
                }
                else if (resource.ResourceType == ResourceType.Stylesheet)
                {
                    try
                    {
                        var stylesheets = fileService.GetStylesheets(resource.TextData.ToLowerInvariant());
                        if (stylesheets != null && stylesheets.Any())
                        {
                            foreach (var item in stylesheets)
                            {
                                fileService.DeleteStylesheet(item.Name);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.StackTrace);
                    }

                    var newPath = cssPath + Path.GetFileName(filePath);
                    if (!newPath.EndsWith(".css"))
                    {
                        newPath = newPath + ".css";
                    }
                    var stylesheet = new Stylesheet(newPath);
                    fileService.SaveStylesheet(stylesheet);
                    System.IO.File.Copy(filePath, newPath, true);
                    AddToReferences(resource.TemplateReference, newPath, true);
                }
                else if (resource.ResourceType == ResourceType.Image)
                {                    
                    var media = mediaService.CreateMedia(resource.FileName, mediaParent.Id, Constants.Conventions.MediaTypes.Image);
                    using (var fs = System.IO.File.OpenRead(filePath))
                    {
                        media.SetValue(Constants.Conventions.Media.File, resource.FileName, fs);
                    }
                    mediaService.Save(media);
                    AddToReferences(resource.TemplateReference, media.GetValue<string>(Constants.Conventions.Media.File));
                }
                else if (resource.ResourceType == ResourceType.File)
                {
                    var media = mediaService.CreateMedia(resource.FileName, mediaParent.Id, Constants.Conventions.MediaTypes.File);
                    using (var fs = System.IO.File.OpenRead(filePath))
                    {
                        media.SetValue(Constants.Conventions.Media.File, resource.FileName, fs);
                    }
                    mediaService.Save(media);
                    AddToReferences(resource.TemplateReference, media.GetValue<string>(Constants.Conventions.Media.File));
                }
            }


            var rootCT = new ContentType(-1);
            rootCT.Name = site.Name;
            rootCT.Alias = siteAlias;

            var oldCT = cts.GetContentType(rootCT.Alias);

            if (oldCT != null)
            {
                foreach (var child in cts.GetContentTypeChildren(oldCT.Id))
                {
                    cts.Delete(child);
                }

                cts.Delete(oldCT);
            }

            cts.Save(rootCT);
            
            var templatePathFormat = HostingEnvironment
                    .MapPath("/Views") + Path.DirectorySeparatorChar + "{0}.cshtml";

            var templates = new Dictionary<Guid, ITemplate>();
            var templateTexts = new Dictionary<Guid, string>();
            foreach (var template in site.Templates.WhereNotNull())
            {
                var templateAlias = siteAlias + template.Name.ToLowerInvariant();
                if (fileService.GetTemplate(templateAlias) != null)
	            {
                    fileService.DeleteTemplate(templateAlias);
	            }

                var templatePath = string.Format(templatePathFormat, templateAlias);
                var templateModel = new Umbraco.Core.Models.Template(templatePath, template.Name, templateAlias);

                fileService.SaveTemplate(templateModel);

                templateTexts.Add(template.ID, template.Text);
                templates.Add(template.ID, templateModel);
            }
                        
            var contentTypes = new Dictionary<Guid, ContentType>();
            foreach (var pageType in site.PageTypes)
            {
                var contentType = new ContentType(rootCT);
                contentType.Name = pageType.Name;
                contentType.Alias = siteAlias + pageType.Name;
                contentType.Icon = "icon-umb-content";

                cts.Save(contentType);

                contentType.AddPropertyGroup(site.Name);
                var propertyGroup = contentType.PropertyGroups[site.Name];

                bool hasTemplate = pageType.TemplateID != Guid.Empty;

                string templateBody = null;
                ITemplate contentTypeTemplate = null; 
                if (hasTemplate)
                {
                    contentTypeTemplate = templates[pageType.TemplateID];
                    templateBody = templateTexts[pageType.TemplateID];   
                }

                foreach (var definition in pageType.Definitions)
                {
                    var def = appContext.Services.DataTypeService
                        .GetDataTypeDefinitionByPropertyEditorAlias(Constants.PropertyEditors.TinyMCEAlias)
                        .First();
                    var pt = new PropertyType(def);
                    pt.Alias = siteAlias + definition.Name;
                    pt.Name = definition.Name;
                    contentType.AddPropertyType(pt, site.Name);
                    if (hasTemplate)
                    {
                        templateBody = templateBody.Replace(definition.TemplateReference, "@Umbraco.Field(\"" + pt.Alias + "\")");   
                    }
                }

                if (hasTemplate)
                {
                    contentTypeTemplate.Content = templateBody;
                    contentType.AllowedTemplates = contentTypeTemplate.AsEnumerableOfOne();
                    contentType.SetDefaultTemplate(contentTypeTemplate);

                    var templatePath = string.Format(templatePathFormat, contentTypeTemplate.Alias);
                    System.IO.File.WriteAllText(templatePath, templateBody, Encoding.UTF8);
                }
                
                cts.Save(contentType);
                contentTypes.Add(pageType.ID, contentType);
            }

            IContent root = null;
            var cs = appContext.Services.ContentService;
            var pages = new Dictionary<Guid, IContent>();
            var pageReferences = new Dictionary<string, IContent>();
            foreach (var page in site.Root.GetDescendantsAndSelf())
            {
                if(page.Name == null)
                {
                    page.Name = "unknown";
                }
                var parentID = page.ParentID == Guid.Empty ? -1 : pages[page.ParentID].Id;
                var cnt = cs.CreateContent(page.Name, parentID, contentTypes[page.PageTypeID].Alias);
                pages.Add(page.ID, cnt);
                foreach (var prop in page.Properties)
                {
                    //Accents removal
                    tempBytes = System.Text.Encoding.GetEncoding("ISO-8859-8").GetBytes(prop.Name);
                    string propName = System.Text.Encoding.UTF8.GetString(tempBytes);
                    propName = propName.Replace(" ", string.Empty);
                    cnt.Properties[siteAlias + propName].Value = prop.Value;
                }
                cs.Save(cnt);
                if (page.ParentID == Guid.Empty)
	            {
		            root = cnt;
	            }
                if (!string.IsNullOrWhiteSpace(page.TemplateReference))
                {
                    pageReferences.Add(page.TemplateReference, cnt);   
                }
            }

            var pageRegex = new Regex(@"(@Raw\(Model\.Page\d+\))", RegexOptions.Compiled | RegexOptions.Multiline);
            var resourceRegex = new Regex(@"(@Raw\(Model\.Resource\d+\))", RegexOptions.Compiled | RegexOptions.Multiline);
            foreach (var page in root.Descendants().Where(c => c.Template != null))
	        {
		        foreach (var property in page.Properties)
	            {
                    var value = property.Value != null ? property.Value.ToString() : "";
                    value = pageRegex.Replace(value, m => "/{localLink:" + pageReferences[m.Value].Id + "}");
                    property.Value = resourceRegex.Replace(value, m => references[m.Value]);
	            }
                cs.Save(page);
	        }
            cs.PublishWithChildrenWithStatus(root, includeUnpublished: true);
            foreach (var template in templates.Values)
            {
                var sb = new StringBuilder();
                var templatePath = string.Format(templatePathFormat, template.Alias);
                var newContent = pageRegex.Replace(template.Content, m => string.Format("@Umbraco.NiceUrl({0})", pageReferences[m.Value].Id));
                newContent = resourceRegex.Replace(newContent, m => references[m.Value]);
                System.IO.File.WriteAllText(templatePath, templatePrefix + newContent, Encoding.UTF8);
            }
        }
        /// <summary>
        /// Update the existing content Type based on the data in the attributes
        /// </summary>
        /// <param name="contentTypeService"></param>
        /// <param name="fileService"></param>
        /// <param name="attribute"></param>
        /// <param name="contentType"></param>
        /// <param name="type"></param>
        /// <param name="dataTypeService"></param>
        private static void UpdateContentType(IContentTypeService contentTypeService, IFileService fileService, UmbracoContentTypeAttribute attribute, IContentType contentType, Type type, IDataTypeService dataTypeService)
        {
            contentType.Name = attribute.ContentTypeName;
            contentType.Alias = attribute.ContentTypeAlias;
            contentType.Icon = attribute.Icon;
            contentType.IsContainer = attribute.EnableListView;
            contentType.AllowedContentTypes = FetchAllowedContentTypes(attribute.AllowedChildren, contentTypeService);
            contentType.AllowedAsRoot = attribute.AllowedAtRoot;

            Type parentType = type.BaseType;
            if (parentType != null && parentType != typeof(UmbracoGeneratedBase) && parentType.GetBaseTypes(false).Any(x => x == typeof(UmbracoGeneratedBase)))
            {
                UmbracoContentTypeAttribute parentAttribute = parentType.GetCustomAttribute<UmbracoContentTypeAttribute>();
                if (parentAttribute != null)
                {
                    string parentAlias = parentAttribute.ContentTypeAlias;
                    IContentType parentContentType = contentTypeService.GetContentType(parentAlias);
                    contentType.ParentId = parentContentType.Id;
                }
                else
                {
                    throw new Exception("The given base class has no UmbracoContentTypeAttribute");
                }
            }

            if (attribute.CreateMatchingView)
            {
                Template currentTemplate = fileService.GetTemplate(attribute.ContentTypeAlias) as Template;
                if (currentTemplate == null)
                {
                    //there should be a template but there isn't so we create one
                    currentTemplate = new Template("~/Views/" + attribute.ContentTypeAlias + ".cshtml", attribute.ContentTypeName, attribute.ContentTypeAlias);
                    CreateViewFile(attribute.ContentTypeAlias, attribute.MasterTemplate, currentTemplate, type, fileService);
                    fileService.SaveTemplate(currentTemplate, 0);
                }
                contentType.AllowedTemplates = new ITemplate[] { currentTemplate };
                contentType.SetDefaultTemplate(currentTemplate);
            }

            VerifyProperties(contentType, type, dataTypeService);

            //verify if a tab has no properties, if so remove
            var propertyGroups = contentType.PropertyGroups.ToArray();
            int length = propertyGroups.Length;
            for (int i = 0; i < length; i++)
            {
                if (propertyGroups[i].PropertyTypes.Count == 0)
                {
                    //remove
                    contentType.RemovePropertyGroup(propertyGroups[i].Name);
                }
            }

            //persist
            contentTypeService.Save(contentType, 0);
        }
        /// <summary>
        /// Creates a View if specified in the attribute
        /// </summary>
        /// <param name="fileService"></param>
        /// <param name="attribute"></param>
        /// <param name="type"></param>
        /// <param name="newContentType"></param>
        private static void CreateMatchingView(IFileService fileService, UmbracoContentTypeAttribute attribute, Type type, IContentType newContentType)
        {
            var currentTemplate = fileService.GetTemplate(attribute.ContentTypeAlias) as Template;
            if (currentTemplate == null)
            {
                string templatePath;
                if (string.IsNullOrEmpty(attribute.TemplateLocation))
                {
                    templatePath = string.Format(CultureInfo.InvariantCulture, "~/Views/{0}.cshtml", attribute.ContentTypeAlias);
                }
                else
                {
                    templatePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}.cshtml",
                        attribute.TemplateLocation,                                     // The template location
                        attribute.TemplateLocation.EndsWith("/") ? string.Empty : "/",  // Ensure the template location ends with a "/"
                        attribute.ContentTypeAlias);                                    // The alias
                }

                currentTemplate = new Template(templatePath, attribute.ContentTypeName, attribute.ContentTypeAlias);
                CreateViewFile(attribute.MasterTemplate, currentTemplate, type, fileService);
            }

            newContentType.AllowedTemplates = new ITemplate[] { currentTemplate };
            newContentType.SetDefaultTemplate(currentTemplate);

            //TODO: in Umbraco 7.1 it will be possible to set the master template of the newly created template
            //https://github.com/umbraco/Umbraco-CMS/pull/294
        }