Exemple #1
0
        private ITemplate ConfigureTemplate(Type docType, ref ITemplate defaultTemplate, TemplateAttribute attribute)
        {
            var template = _fileService.GetTemplates().FirstOrDefault(x => string.Equals(x.Alias, attribute.TemplateAlias, StringComparison.InvariantCultureIgnoreCase));

            if (template == null)
            {
                template = CreateTemplate(attribute);
            }
            if (attribute.IsDefault)
            {
                if (defaultTemplate == null)
                {
                    defaultTemplate = template;
                }
                else
                {
                    throw new CodeFirstException("More than one default template specified for " + docType.FullName);
                }
            }
            if (attribute.TemplateName != template.Name)
            {
                var t = new umbraco.cms.businesslogic.template.Template(template.Id);
                t.Text = attribute.TemplateName;
                t.Save();
                template = _fileService.GetTemplates().FirstOrDefault(x => x.Alias == attribute.TemplateAlias); //re-get the template to pick up the changes
            }
            return(template);
        }
Exemple #2
0
        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();

                return(Success(ui.Text("speechBubbles", "templateSavedText"), ui.Text("speechBubbles", "templateSavedHeader")));
            }
            catch (Exception ex)
            {
                return(Failed(ui.Text("speechBubbles", "templateErrorText"), ui.Text("speechBubbles", "templateErrorHeader"), ex));
            }
        }
Exemple #3
0
        public JsonResult SaveTemplate(string templateName, string templateAlias, string templateContents, int templateId, int masterTemplateId)
        {
            //TODO: Change this over to use the new API - Also this will be migrated to a TemplateEditor or ViewEditor when it's all moved to angular

            Template t;
            bool     pathChanged = false;

            try
            {
                t = new Template(templateId)
                {
                    Text   = templateName.CleanForXss('[', ']', '(', ')', ':'),
                    Alias  = templateAlias.CleanForXss('[', ']', '(', ')', ':'),
                    Design = templateContents
                };

                //check if the master page has changed - we need to normalize both - if it's 0 or -1, then make it 0... this is easy
                // to do with Math.Max
                if (Math.Max(t.MasterTemplate, 0) != Math.Max(masterTemplateId, 0))
                {
                    t.MasterTemplate = Math.Max(masterTemplateId, 0);
                    pathChanged      = true;
                }
            }
            catch (ArgumentException ex)
            {
                //the template does not exist
                return(Failed("Template does not exist", ui.Text("speechBubbles", "templateErrorHeader"), ex));
            }

            try
            {
                t.Save();

                //ensure the correct path is synced as the parent might have been changed
                // http://issues.umbraco.org/issue/U4-2300
                if (pathChanged)
                {
                    //need to re-look it up
                    t = new Template(templateId);
                }
                var syncPath = "-1,init," + t.Path.Replace("-1,", "");

                return(Success(ui.Text("speechBubbles", "templateSavedText"), ui.Text("speechBubbles", "templateSavedHeader"),
                               new
                {
                    path = syncPath,
                    contents = t.Design,
                    alias = t.Alias     // might have been updated!
                }));
            }
            catch (Exception ex)
            {
                return(Failed(ui.Text("speechBubbles", "templateErrorText"), ui.Text("speechBubbles", "templateErrorHeader"), ex));
            }
        }
Exemple #4
0
        /// <summary>
        ///  oldscool calls to get the master id
        /// </summary>
        private int GetMasterId(ITemplate item)
        {
            global::umbraco.cms.businesslogic.template.Template t =
                new umbraco.cms.businesslogic.template.Template(item.Id);

            if (t.MasterTemplate > 0)
            {
                return(t.MasterTemplate);
            }

            return(-1);
        }
Exemple #5
0
        public JsonResult SaveTemplate(string templateName, string templateAlias, string templateContents, int templateId, int masterTemplateId)
        {
            Template t;
            bool     pathChanged = false;

            try
            {
                t = new Template(templateId)
                {
                    Text   = templateName,
                    Alias  = templateAlias,
                    Design = templateContents
                };

                //check if the master page has changed
                if (t.MasterTemplate != masterTemplateId)
                {
                    pathChanged      = true;
                    t.MasterTemplate = masterTemplateId;
                }
            }
            catch (ArgumentException ex)
            {
                //the template does not exist
                return(Failed("Template does not exist", ui.Text("speechBubbles", "templateErrorHeader"), ex));
            }

            try
            {
                t.Save();

                //ensure the correct path is synced as the parent might have been changed
                // http://issues.umbraco.org/issue/U4-2300
                if (pathChanged)
                {
                    //need to re-look it up
                    t = new Template(templateId);
                }
                var syncPath = "-1,init," + t.Path.Replace("-1,", "");

                return(Success(ui.Text("speechBubbles", "templateSavedText"), ui.Text("speechBubbles", "templateSavedHeader"),
                               new { path = syncPath }));
            }
            catch (Exception ex)
            {
                return(Failed(ui.Text("speechBubbles", "templateErrorText"), ui.Text("speechBubbles", "templateErrorHeader"), ex));
            }
        }
        public void Publish()
        {
            var package = this;
            var pack    = package.Data;

            var e = new PublishEventArgs();

            package.FireBeforePublish(e);

            if (e.Cancel == false)
            {
                var outInt = 0;

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

                if (Directory.Exists(localPath) == false)
                {
                    Directory.CreateDirectory(localPath);
                }

                //Init package file...
                CreatePackageManifest();
                //Info section..
                AppendElement(utill.PackageInfo(pack, _packageManifest));

                //Documents and tags...
                var contentNodeId = 0;
                if (string.IsNullOrEmpty(pack.ContentNodeId) == false && int.TryParse(pack.ContentNodeId, out contentNodeId))
                {
                    if (contentNodeId > 0)
                    {
                        //Create the Documents/DocumentSet node
                        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.
                        var umbDocument = new Document(contentNodeId);

                        documentSet.AppendChild(umbDocument.ToXml(_packageManifest, pack.ContentLoadChildNodes));

                        AppendElement(documents);

                        ////Create the TagProperties node - this is used to store a definition for all
                        //// document properties that are tags, this ensures that we can re-import tags properly
                        //XmlNode tagProps = _packageManifest.CreateElement("TagProperties");

                        ////before we try to populate this, we'll do a quick lookup to see if any of the documents
                        //// being exported contain published tags.
                        //var allExportedIds = documents.SelectNodes("//@id").Cast<XmlNode>()
                        //    .Select(x => x.Value.TryConvertTo<int>())
                        //    .Where(x => x.Success)
                        //    .Select(x => x.Result)
                        //    .ToArray();
                        //var allContentTags = new List<ITag>();
                        //foreach (var exportedId in allExportedIds)
                        //{
                        //    allContentTags.AddRange(
                        //        ApplicationContext.Current.Services.TagService.GetTagsForEntity(exportedId));
                        //}

                        ////This is pretty round-about but it works. Essentially we need to get the properties that are tagged
                        //// but to do that we need to lookup by a tag (string)
                        //var allTaggedEntities = new List<TaggedEntity>();
                        //foreach (var group in allContentTags.Select(x => x.Group).Distinct())
                        //{
                        //    allTaggedEntities.AddRange(
                        //        ApplicationContext.Current.Services.TagService.GetTaggedContentByTagGroup(group));
                        //}

                        ////Now, we have all property Ids/Aliases and their referenced document Ids and tags
                        //var allExportedTaggedEntities = allTaggedEntities.Where(x => allExportedIds.Contains(x.EntityId))
                        //    .DistinctBy(x => x.EntityId)
                        //    .OrderBy(x => x.EntityId);

                        //foreach (var taggedEntity in allExportedTaggedEntities)
                        //{
                        //    foreach (var taggedProperty in taggedEntity.TaggedProperties.Where(x => x.Tags.Any()))
                        //    {
                        //        XmlNode tagProp = _packageManifest.CreateElement("TagProperty");
                        //        var docId = _packageManifest.CreateAttribute("docId", "");
                        //        docId.Value = taggedEntity.EntityId.ToString(CultureInfo.InvariantCulture);
                        //        tagProp.Attributes.Append(docId);

                        //        var propertyAlias = _packageManifest.CreateAttribute("propertyAlias", "");
                        //        propertyAlias.Value = taggedProperty.PropertyTypeAlias;
                        //        tagProp.Attributes.Append(propertyAlias);

                        //        var group = _packageManifest.CreateAttribute("group", "");
                        //        group.Value = taggedProperty.Tags.First().Group;
                        //        tagProp.Attributes.Append(group);

                        //        tagProp.AppendChild(_packageManifest.CreateCDataSection(
                        //            JsonConvert.SerializeObject(taggedProperty.Tags.Select(x => x.Text).ToArray())));

                        //        tagProps.AppendChild(tagProp);
                        //    }
                        //}

                        //AppendElement(tagProps);
                    }
                }

                //Document types..
                var dtl      = new List <DocumentType>();
                var docTypes = _packageManifest.CreateElement("DocumentTypes");
                foreach (var 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
                var templates = _packageManifest.CreateElement("Templates");
                foreach (var templateId in pack.Templates)
                {
                    if (int.TryParse(templateId, out outInt))
                    {
                        var t = new Template(outInt);
                        templates.AppendChild(t.ToXml(_packageManifest));
                    }
                }
                AppendElement(templates);

                //Stylesheets
                var stylesheets = _packageManifest.CreateElement("Stylesheets");
                foreach (var stylesheetName in pack.Stylesheets)
                {
                    if (stylesheetName.IsNullOrWhiteSpace())
                    {
                        continue;
                    }
                    var stylesheetXmlNode = utill.Stylesheet(stylesheetName, true, _packageManifest);
                    if (stylesheetXmlNode != null)
                    {
                        stylesheets.AppendChild(stylesheetXmlNode);
                    }
                }
                AppendElement(stylesheets);

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

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

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

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

                //Datatypes
                var dataTypes = _packageManifest.CreateElement("DataTypes");
                foreach (var dtId in pack.DataTypes)
                {
                    if (int.TryParse(dtId, out outInt))
                    {
                        datatype.DataTypeDefinition dtd = new datatype.DataTypeDefinition(outInt);
                        dataTypes.AppendChild(dtd.ToXml(_packageManifest));
                    }
                }
                AppendElement(dataTypes);

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

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

                //Actions
                if (string.IsNullOrEmpty(pack.Actions) == false)
                {
                    try
                    {
                        var xdActions = new XmlDocument();
                        xdActions.LoadXml("<Actions>" + pack.Actions + "</Actions>");
                        var actions = xdActions.DocumentElement.SelectSingleNode(".");


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

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

                if (File.Exists(manifestFileName))
                {
                    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
                var packagesDirectory = SystemDirectories.Media + "/created-packages";
                if (Directory.Exists(IOHelper.MapPath(packagesDirectory)) == false)
                {
                    Directory.CreateDirectory(IOHelper.MapPath(packagesDirectory));
                }


                var 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..
                File.Delete(localPath + "/package.xml");
                Directory.Delete(localPath, true);

                package.FireAfterPublish(e);
            }
        }
		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();

				return Success(ui.Text("speechBubbles", "templateSavedText"), ui.Text("speechBubbles", "templateSavedHeader"));
			}
			catch (Exception ex)
			{
				return Failed(ui.Text("speechBubbles", "templateErrorText"), ui.Text("speechBubbles", "templateErrorHeader"), ex);
			}
		}
 private ITemplate ConfigureTemplate(Type docType, ref ITemplate defaultTemplate, TemplateAttribute attribute)
 {
     var template = _fileService.GetTemplates().FirstOrDefault(x => string.Equals(x.Alias, attribute.TemplateAlias, StringComparison.InvariantCultureIgnoreCase));
     if (template == null)
     {
         template = CreateTemplate(attribute);
     }
     if (attribute.IsDefault)
     {
         if (defaultTemplate == null)
         {
             defaultTemplate = template;
         }
         else
         {
             throw new CodeFirstException("More than one default template specified for " + docType.FullName);
         }
     }
     if (attribute.TemplateName != template.Name)
     {
         var t = new umbraco.cms.businesslogic.template.Template(template.Id);
         t.Text = attribute.TemplateName;
         t.Save();
         template = _fileService.GetTemplates().FirstOrDefault(x => x.Alias == attribute.TemplateAlias); //re-get the template to pick up the changes
     }
     return template;
 }
		public JsonResult SaveTemplate(string templateName, string templateAlias, string templateContents, int templateId, int masterTemplateId)
		{
			Template t;
		    bool pathChanged = false;
			try
			{
				t = new Template(templateId)
						{
							Text = templateName,
							Alias = templateAlias,							
							Design = templateContents
						};

                //check if the master page has changed
                if (t.MasterTemplate != masterTemplateId)
                {
                    pathChanged = true;
                    t.MasterTemplate = masterTemplateId;
                }
			}
			catch (ArgumentException ex)
			{
				//the template does not exist
				return Failed("Template does not exist", ui.Text("speechBubbles", "templateErrorHeader"), ex);
			}

			try
			{
				t.Save();

                //ensure the correct path is synced as the parent might have been changed
                // http://issues.umbraco.org/issue/U4-2300                
                if (pathChanged)
                {
                    //need to re-look it up
                    t = new Template(templateId);
                }
                var syncPath = "-1,init," + t.Path.Replace("-1,", "");

			    return Success(ui.Text("speechBubbles", "templateSavedText"), ui.Text("speechBubbles", "templateSavedHeader"), 
                    new {path = syncPath});
			}
			catch (Exception ex)
			{
				return Failed(ui.Text("speechBubbles", "templateErrorText"), ui.Text("speechBubbles", "templateErrorHeader"), ex);
			}
		}
 /// <summary>
 /// Removes cache for template
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 static void TemplateAfterDelete(Template sender, DeleteEventArgs e)
 {
     DistributedCache.Instance.RemoveTemplateCache(sender.Id);
 }
        protected void confirmUnInstall(object sender, EventArgs e)
        {
            var refreshCache = false;

            //Uninstall Stylesheets
            foreach (ListItem li in stylesheets.Items)
            {
                if (li.Selected)
                {
                    int nId;

                    if (int.TryParse(li.Value, out nId))
                    {
                        var s = new StyleSheet(nId);
                        s.delete();
                        _pack.Data.Stylesheets.Remove(nId.ToString());
                    }
                }
            }

            //Uninstall templates
            foreach (ListItem li in templates.Items)
            {
                if (li.Selected)
                {
                    int nId;

                    if (int.TryParse(li.Value, out nId))
                    {
                        var s = new Template(nId);
                        s.RemoveAllReferences();
                        s.delete();
                        _pack.Data.Templates.Remove(nId.ToString());
                    }
                }
            }

            //Uninstall macros
            foreach (ListItem li in macros.Items)
            {
                if (li.Selected)
                {
                    int nId;

                    if (int.TryParse(li.Value, out nId))
                    {
                        var s = new Macro(nId);
                        if (!string.IsNullOrEmpty(s.Name))
                        {
                            s.Delete();
                        }

                        _pack.Data.Macros.Remove(nId.ToString());
                    }
                }
            }

            //Remove Document Types
            var contentTypes       = new List <IContentType>();
            var contentTypeService = ApplicationContext.Current.Services.ContentTypeService;

            foreach (ListItem li in documentTypes.Items)
            {
                if (li.Selected)
                {
                    int nId;

                    if (int.TryParse(li.Value, out nId))
                    {
                        var contentType = contentTypeService.GetContentType(nId);
                        if (contentType != null)
                        {
                            contentTypes.Add(contentType);
                            _pack.Data.Documenttypes.Remove(nId.ToString(CultureInfo.InvariantCulture));
                            // refresh content cache when document types are removed
                            refreshCache = true;
                        }
                    }
                }
            }
            //Order the DocumentTypes before removing them
            if (contentTypes.Any())
            {
                var orderedTypes = (from contentType in contentTypes
                                    orderby contentType.ParentId descending, contentType.Id descending
                                    select contentType);

                foreach (var contentType in orderedTypes)
                {
                    contentTypeService.Delete(contentType);
                }
            }

            //Remove Dictionary items
            foreach (ListItem li in dictionaryItems.Items)
            {
                if (li.Selected)
                {
                    int nId;

                    if (int.TryParse(li.Value, out nId))
                    {
                        var di = new cms.businesslogic.Dictionary.DictionaryItem(nId);
                        di.delete();
                        _pack.Data.DictionaryItems.Remove(nId.ToString());
                    }
                }
            }

            //Remove Data types
            foreach (ListItem li in dataTypes.Items)
            {
                if (li.Selected)
                {
                    int nId;

                    if (int.TryParse(li.Value, out nId))
                    {
                        var dtd = new cms.businesslogic.datatype.DataTypeDefinition(nId);
                        dtd.delete();
                        _pack.Data.DataTypes.Remove(nId.ToString());
                    }
                }
            }

            _pack.Save();

            if (!IsManifestEmpty())
            {
                Response.Redirect(Request.RawUrl);
            }
            else
            {
                // uninstall actions
                try
                {
                    var actionsXml = new XmlDocument();
                    actionsXml.LoadXml("<Actions>" + _pack.Data.Actions + "</Actions>");

                    LogHelper.Debug <installedPackage>("executing undo actions: {0}", () => actionsXml.OuterXml);

                    foreach (XmlNode n in actionsXml.DocumentElement.SelectNodes("//Action"))
                    {
                        try
                        {
                            cms.businesslogic.packager.PackageAction.UndoPackageAction(_pack.Data.Name, n.Attributes["alias"].Value, n);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error <installedPackage>("An error occurred running undo actions", ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error <installedPackage>("An error occurred running undo actions", ex);
                }

                //moved remove of files here so custom package actions can still undo
                //Remove files
                foreach (ListItem li in files.Items)
                {
                    if (li.Selected)
                    {
                        //here we need to try to find the file in question as most packages does not support the tilde char

                        var file = IOHelper.FindFile(li.Value);

                        var filePath = IOHelper.MapPath(file);
                        if (System.IO.File.Exists(filePath))
                        {
                            System.IO.File.Delete(filePath);
                            _pack.Data.Files.Remove(li.Value);
                        }
                    }
                }
                _pack.Save();

                _pack.Delete();

                packageUninstalled.Visible    = true;
                installedPackagePanel.Visible = false;
            }

            // refresh cache
            if (refreshCache)
            {
                library.RefreshContent();
            }

            //ensure that all tree's are refreshed after uninstall
            ClientTools.ClearClientTreeCache()
            .RefreshTree();

            TreeDefinitionCollection.Instance.ReRegisterTrees();

            BizLogicAction.ReRegisterActionsAndHandlers();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["id"] != null)
            {
                _pack = cms.businesslogic.packager.InstalledPackage.GetById(int.Parse(Request.QueryString["id"]));

                lt_packagename.Text    = _pack.Data.Name;
                lt_packageVersion.Text = _pack.Data.Version;
                lt_packageAuthor.Text  = _pack.Data.Author;
                lt_readme.Text         = library.ReplaceLineBreaks(_pack.Data.Readme);

                bt_confirmUninstall.Attributes.Add("onClick", "jQuery('#buttons').hide(); jQuery('#loadingbar').show();; return true;");


                if (!Page.IsPostBack)
                {
                    //temp list to contain failing items...
                    var tempList = new List <string>();

                    foreach (var str in _pack.Data.Documenttypes)
                    {
                        var tId = 0;
                        if (int.TryParse(str, out tId))
                        {
                            try
                            {
                                var dc = new DocumentType(tId);
                                var li = new ListItem(dc.Text, dc.Id.ToString());
                                li.Selected = true;
                                documentTypes.Items.Add(li);
                            }
                            catch
                            {
                                tempList.Add(str);
                            }
                        }
                    }
                    //removing failing documentTypes items from the uninstall manifest
                    SyncLists(_pack.Data.Documenttypes, tempList);


                    foreach (var str in _pack.Data.Templates)
                    {
                        var tId = 0;
                        if (int.TryParse(str, out tId))
                        {
                            try
                            {
                                var t  = new Template(tId);
                                var li = new ListItem(t.Text, t.Id.ToString());
                                li.Selected = true;
                                templates.Items.Add(li);
                            }
                            catch
                            {
                                tempList.Add(str);
                            }
                        }
                    }
                    //removing failing template items from the uninstall manifest
                    SyncLists(_pack.Data.Templates, tempList);

                    foreach (string str in _pack.Data.Stylesheets)
                    {
                        int tId = 0;
                        if (int.TryParse(str, out tId))
                        {
                            try
                            {
                                var      s  = new StyleSheet(tId);
                                ListItem li = new ListItem(s.Text, s.Id.ToString());
                                li.Selected = true;
                                stylesheets.Items.Add(li);
                            }
                            catch
                            {
                                tempList.Add(str);
                            }
                        }
                    }
                    //removing failing stylesheet items from the uninstall manifest
                    SyncLists(_pack.Data.Stylesheets, tempList);

                    foreach (var str in _pack.Data.Macros)
                    {
                        var tId = 0;
                        if (int.TryParse(str, out tId))
                        {
                            try
                            {
                                var m = new Macro(tId);
                                if (!string.IsNullOrEmpty(m.Name))
                                {
                                    //Macros need an extra check to see if they actually exists. For some reason the macro does not return null, if the id is not found...
                                    var li = new ListItem(m.Name, m.Id.ToString());
                                    li.Selected = true;
                                    macros.Items.Add(li);
                                }
                                else
                                {
                                    tempList.Add(str);
                                }
                            }
                            catch
                            {
                                tempList.Add(str);
                            }
                        }
                    }
                    //removing failing macros items from the uninstall manifest
                    SyncLists(_pack.Data.Macros, tempList);

                    foreach (var str in _pack.Data.Files)
                    {
                        try
                        {
                            if (!string.IsNullOrEmpty(str) && System.IO.File.Exists(IOHelper.MapPath(str)))
                            {
                                var li = new ListItem(str, str);
                                li.Selected = true;
                                files.Items.Add(li);
                            }
                            else
                            {
                                tempList.Add(str);
                            }
                        }
                        catch
                        {
                            tempList.Add(str);
                        }
                    }

                    //removing failing files from the uninstall manifest
                    SyncLists(_pack.Data.Files, tempList);

                    foreach (string str in _pack.Data.DictionaryItems)
                    {
                        var tId = 0;

                        if (int.TryParse(str, out tId))
                        {
                            try
                            {
                                var di = new cms.businesslogic.Dictionary.DictionaryItem(tId);

                                var li = new ListItem(di.key, di.id.ToString());
                                li.Selected = true;

                                dictionaryItems.Items.Add(li);
                            }
                            catch
                            {
                                tempList.Add(str);
                            }
                        }
                    }

                    //removing failing files from the uninstall manifest
                    SyncLists(_pack.Data.DictionaryItems, tempList);


                    foreach (var str in _pack.Data.DataTypes)
                    {
                        var tId = 0;

                        if (int.TryParse(str, out tId))
                        {
                            try
                            {
                                var dtd = new cms.businesslogic.datatype.DataTypeDefinition(tId);

                                if (dtd != null)
                                {
                                    var li = new ListItem(dtd.Text, dtd.Id.ToString());
                                    li.Selected = true;

                                    dataTypes.Items.Add(li);
                                }
                                else
                                {
                                    tempList.Add(str);
                                }
                            }
                            catch
                            {
                                tempList.Add(str);
                            }
                        }
                    }

                    //removing failing files from the uninstall manifest
                    SyncLists(_pack.Data.DataTypes, tempList);

                    //save the install manifest, so even tho the user doesn't uninstall, it stays uptodate.
                    _pack.Save();


                    //Look for updates on packages.
                    if (!string.IsNullOrEmpty(_pack.Data.RepositoryGuid) && !string.IsNullOrEmpty(_pack.Data.PackageGuid))
                    {
                        try
                        {
                            _repo = cms.businesslogic.packager.repositories.Repository.getByGuid(_pack.Data.RepositoryGuid);

                            if (_repo != null)
                            {
                                hl_packageRepo.Text        = _repo.Name;
                                hl_packageRepo.NavigateUrl = "BrowseRepository.aspx?repoGuid=" + _repo.Guid;
                                pp_repository.Visible      = true;
                            }

                            var repoPackage = _repo.Webservice.PackageByGuid(_pack.Data.PackageGuid);

                            if (repoPackage != null)
                            {
                                if (repoPackage.HasUpgrade && repoPackage.UpgradeVersion != _pack.Data.Version)
                                {
                                    bt_update.Visible            = true;
                                    bt_update.Text               = "Update available: version: " + repoPackage.UpgradeVersion;
                                    lt_upgradeReadme.Text        = repoPackage.UpgradeReadMe;
                                    bt_gotoUpgrade.OnClientClick = "window.location.href = 'browseRepository.aspx?url=" + repoPackage.Url + "'; return true;";
                                    lt_noUpdate.Visible          = false;
                                }
                                else
                                {
                                    bt_update.Visible   = false;
                                    lt_noUpdate.Visible = true;
                                }

                                if (!string.IsNullOrEmpty(repoPackage.Demo))
                                {
                                    lb_demoLink.OnClientClick = "openDemo(this, '" + _pack.Data.PackageGuid + "'); return false;";
                                    pp_documentation.Visible  = true;
                                }

                                if (!string.IsNullOrEmpty(repoPackage.Documentation))
                                {
                                    hl_docLink.NavigateUrl   = repoPackage.Documentation;
                                    hl_docLink.Target        = "_blank";
                                    pp_documentation.Visible = true;
                                }
                            }
                        }
                        catch
                        {
                            bt_update.Visible   = false;
                            lt_noUpdate.Visible = true;
                        }
                    }


                    var deletePackage = true;
                    //sync the UI to match what is in the package
                    if (macros.Items.Count == 0)
                    {
                        pp_macros.Visible = false;
                    }
                    else
                    {
                        deletePackage = false;
                    }

                    if (documentTypes.Items.Count == 0)
                    {
                        pp_docTypes.Visible = false;
                    }
                    else
                    {
                        deletePackage = false;
                    }

                    if (files.Items.Count == 0)
                    {
                        pp_files.Visible = false;
                    }
                    else
                    {
                        deletePackage = false;
                    }

                    if (templates.Items.Count == 0)
                    {
                        pp_templates.Visible = false;
                    }
                    else
                    {
                        deletePackage = false;
                    }

                    if (stylesheets.Items.Count == 0)
                    {
                        pp_css.Visible = false;
                    }
                    else
                    {
                        deletePackage = false;
                    }

                    if (dictionaryItems.Items.Count == 0)
                    {
                        pp_di.Visible = false;
                    }
                    else
                    {
                        deletePackage = false;
                    }

                    if (dataTypes.Items.Count == 0)
                    {
                        pp_dt.Visible = false;
                    }
                    else
                    {
                        deletePackage = false;
                    }


                    if (deletePackage)
                    {
                        pane_noItems.Visible   = true;
                        bt_uninstall.Visible   = false;
                        pane_uninstall.Visible = false;
                    }

                    // List the package version history [LK 2013-067-10]
                    Version v;
                    var     packageVersionHistory = cms.businesslogic.packager.InstalledPackage.GetAllInstalledPackages()
                                                    .Where(x => x.Data.Id != _pack.Data.Id && string.Equals(x.Data.Name, _pack.Data.Name, StringComparison.OrdinalIgnoreCase))
                                                    .OrderBy(x => Version.TryParse(x.Data.Version, out v) ? v : new Version());

                    if (packageVersionHistory != null && packageVersionHistory.Count() > 0)
                    {
                        rptr_versions.DataSource = packageVersionHistory;
                        rptr_versions.DataBind();

                        pane_versions.Visible = true;
                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Request.QueryString["id"] != null)
            {
                _pack = cms.businesslogic.packager.InstalledPackage.GetById(int.Parse(Request.QueryString["id"]));

                lt_packagename.Text = _pack.Data.Name;
                lt_packageVersion.Text = _pack.Data.Version;
                lt_packageAuthor.Text = _pack.Data.Author;
                lt_readme.Text = library.ReplaceLineBreaks( _pack.Data.Readme );

                bt_confirmUninstall.Attributes.Add("onClick", "jQuery('#buttons').hide(); jQuery('#loadingbar').show();; return true;");


                if (!Page.IsPostBack)
                {
                    //temp list to contain failing items... 
                    var tempList = new List<string>();

                    foreach (var str in _pack.Data.Documenttypes)
                    {
                        var tId = 0;
                        if (int.TryParse(str, out tId))
                        {
                            try
                            {
                                var dc = new DocumentType(tId);
                                var li = new ListItem(dc.Text, dc.Id.ToString());
                                li.Selected = true;
                                documentTypes.Items.Add(li);
                            }
                            catch
                            {
                                tempList.Add(str);
                            }
                        }
                    }
                    //removing failing documentTypes items from the uninstall manifest
                    SyncLists(_pack.Data.Documenttypes, tempList);


                    foreach (var str in _pack.Data.Templates)
                    {
                        var tId = 0;
                        if (int.TryParse(str, out tId))
                        {
                            try
                            {
                                var t = new Template(tId);
                                var li = new ListItem(t.Text, t.Id.ToString());
                                li.Selected = true;
                                templates.Items.Add(li);
                            }
                            catch
                            {
                                tempList.Add(str);
                            }
                        }
                    }
                    //removing failing template items from the uninstall manifest
                    SyncLists(_pack.Data.Templates, tempList);

                    foreach (string str in _pack.Data.Stylesheets)
                    {
                        int tId = 0;
                        if (int.TryParse(str, out tId))
                        {
                            try
                            {
                                var s = new StyleSheet(tId);
                                ListItem li = new ListItem(s.Text, s.Id.ToString());
                                li.Selected = true;
                                stylesheets.Items.Add(li);
                            }
                            catch
                            {
                                tempList.Add(str);
                            }
                        }
                    }
                    //removing failing stylesheet items from the uninstall manifest
                    SyncLists(_pack.Data.Stylesheets, tempList);

                    foreach (var str in _pack.Data.Macros)
                    {
                        var tId = 0;
                        if (int.TryParse(str, out tId))
                        {
                            try
                            {
                                var m = new Macro(tId);
                                if (!string.IsNullOrEmpty(m.Name))
                                { 
                                    //Macros need an extra check to see if they actually exists. For some reason the macro does not return null, if the id is not found... 
                                    var li = new ListItem(m.Name, m.Id.ToString());
                                    li.Selected = true;
                                    macros.Items.Add(li);
                                }
                                else
                                {
                                    tempList.Add(str);
                                }
                            }
                            catch
                            {
                                tempList.Add(str);
                            }
                        }
                    }
                    //removing failing macros items from the uninstall manifest
                    SyncLists(_pack.Data.Macros, tempList);

                    foreach (var str in _pack.Data.Files)
                    {
                        try
                        {                            
                            if (!string.IsNullOrEmpty(str) && System.IO.File.Exists(IOHelper.MapPath(str) ))
                            {
                                var li = new ListItem(str, str);
                                li.Selected = true;
                                files.Items.Add(li);
                            }
                            else
                            {
                                tempList.Add(str);
                            }

                        }
                        catch
                        {
                            tempList.Add(str);
                        }
                    }

                    //removing failing files from the uninstall manifest
                    SyncLists(_pack.Data.Files, tempList);

                    foreach (string str in _pack.Data.DictionaryItems)
                    {
                        var tId = 0;

                        if (int.TryParse(str, out tId))
                        {
                            try
                            {
                                var di = new cms.businesslogic.Dictionary.DictionaryItem(tId);

                                var li = new ListItem(di.key, di.id.ToString());
                                li.Selected = true;

                                dictionaryItems.Items.Add(li);
                            }
                            catch
                            {
                                tempList.Add(str);
                            }
                        }
                    }

                    //removing failing files from the uninstall manifest
                    SyncLists(_pack.Data.DictionaryItems, tempList);


                    foreach (var str in _pack.Data.DataTypes)
                    {
                        var tId = 0;

                        if (int.TryParse(str, out tId))
                        {
                            try
                            {
                                var dtd = new cms.businesslogic.datatype.DataTypeDefinition(tId);

                                if (dtd != null)
                                {
                                    var li = new ListItem(dtd.Text, dtd.Id.ToString());
                                    li.Selected = true;

                                    dataTypes.Items.Add(li);
                                }
                                else
                                {
                                    tempList.Add(str);
                                }
                            }
                            catch
                            {
                                tempList.Add(str);
                            }
                        }
                    }

                    //removing failing files from the uninstall manifest
                    SyncLists(_pack.Data.DataTypes, tempList);

                    //save the install manifest, so even tho the user doesn't uninstall, it stays uptodate.
                    _pack.Save();


                    //Look for updates on packages.
                    if (!string.IsNullOrEmpty(_pack.Data.RepositoryGuid) && !string.IsNullOrEmpty(_pack.Data.PackageGuid))
                    {
                        try
                        {
                            
                            _repo = cms.businesslogic.packager.repositories.Repository.getByGuid(_pack.Data.RepositoryGuid);

                            if (_repo != null)
                            {
                                hl_packageRepo.Text = _repo.Name;
                                hl_packageRepo.NavigateUrl = "BrowseRepository.aspx?repoGuid=" + _repo.Guid;
                                pp_repository.Visible = true;
                            }

                            var repoPackage = _repo.Webservice.PackageByGuid(_pack.Data.PackageGuid);

                            if (repoPackage != null)
                            {
                                if (repoPackage.HasUpgrade && repoPackage.UpgradeVersion != _pack.Data.Version)
                                {
                                    bt_update.Visible = true;
                                    bt_update.Text = "Update available: version: " + repoPackage.UpgradeVersion;
                                    lt_upgradeReadme.Text = repoPackage.UpgradeReadMe;
                                    bt_gotoUpgrade.OnClientClick = "window.location.href = 'browseRepository.aspx?url=" + repoPackage.Url + "'; return true;";
                                    lt_noUpdate.Visible = false;
                                }
                                else
                                {
                                    bt_update.Visible = false;
                                    lt_noUpdate.Visible = true;
                                }

                                if (!string.IsNullOrEmpty(repoPackage.Demo))
                                {
                                    lb_demoLink.OnClientClick = "openDemo(this, '" + _pack.Data.PackageGuid + "'); return false;";
                                    pp_documentation.Visible = true;
                                }

                                if (!string.IsNullOrEmpty(repoPackage.Documentation))
                                {
                                    hl_docLink.NavigateUrl = repoPackage.Documentation;
                                    hl_docLink.Target = "_blank";
                                    pp_documentation.Visible = true;
                                }
                            }
                        }
                        catch
                        {
                            bt_update.Visible = false;
                            lt_noUpdate.Visible = true;
                        }
                    }


                    var deletePackage = true;
                    //sync the UI to match what is in the package
                    if (macros.Items.Count == 0)
                        pp_macros.Visible = false;
                    else
                        deletePackage = false;

                    if (documentTypes.Items.Count == 0)
                        pp_docTypes.Visible = false;
                    else
                        deletePackage = false;

                    if (files.Items.Count == 0)
                        pp_files.Visible = false;
                    else
                        deletePackage = false;

                    if (templates.Items.Count == 0)
                        pp_templates.Visible = false;
                    else
                        deletePackage = false;

                    if (stylesheets.Items.Count == 0)
                        pp_css.Visible = false;
                    else
                        deletePackage = false;

                    if (dictionaryItems.Items.Count == 0)
                        pp_di.Visible = false;
                    else
                        deletePackage = false;

                    if (dataTypes.Items.Count == 0)
                        pp_dt.Visible = false;
                    else
                        deletePackage = false;


                    if (deletePackage)
                    {
                        pane_noItems.Visible = true;
                        bt_uninstall.Visible = false;
                        pane_uninstall.Visible = false;
                    }
                }
            }
        }
        protected void confirmUnInstall(object sender, EventArgs e)
        {
            var refreshCache = false;

            //Uninstall Stylesheets
            foreach (ListItem li in stylesheets.Items)
            {
                if (li.Selected)
                {
                    int nId;

                    if (int.TryParse(li.Value, out nId))
                    {
                        var s = new StyleSheet(nId);
                        s.delete();
                        _pack.Data.Stylesheets.Remove(nId.ToString());
                    }
                }
            }

            //Uninstall templates
            foreach (ListItem li in templates.Items)
            {
                if (li.Selected)
                {
                    int nId;

                    if (int.TryParse(li.Value, out nId))
                    {
                        var s = new Template(nId);
                        s.RemoveAllReferences();
                        s.delete();
                        _pack.Data.Templates.Remove(nId.ToString());
                    }
                }
            }

            //Uninstall macros
            foreach (ListItem li in macros.Items)
            {
                if (li.Selected)
                {
                    int nId;

                    if (int.TryParse(li.Value, out nId))
                    {
                        var s = new Macro(nId);
                        if (!string.IsNullOrEmpty(s.Name))
                        {
                            // remove from cache
                            runtimeMacro.GetMacro(s.Id).removeFromCache();
                            s.Delete();
                        }

                        _pack.Data.Macros.Remove(nId.ToString());
                    }
                }
            }
            
            //Remove Document Types
            var contentTypes = new List<IContentType>();
            var contentTypeService = ApplicationContext.Current.Services.ContentTypeService;
            foreach (ListItem li in documentTypes.Items)
            {
                if (li.Selected)
                {
                    int nId;

                    if (int.TryParse(li.Value, out nId))
                    {
                        var contentType = contentTypeService.GetContentType(nId);
                        if (contentType != null)
                        {
                            contentTypes.Add(contentType);
                            _pack.Data.Documenttypes.Remove(nId.ToString(CultureInfo.InvariantCulture));
                            // refresh content cache when document types are removed
                            refreshCache = true;
                        }
                    }
                }
            }
            //Order the DocumentTypes before removing them
            if (contentTypes.Any())
            {
                var orderedTypes = (from contentType in contentTypes
                                    orderby contentType.ParentId descending, contentType.Id descending 
                                    select contentType);

                foreach (var contentType in orderedTypes)
                {
                    contentTypeService.Delete(contentType);
                }
            }

            //Remove Dictionary items
            foreach (ListItem li in dictionaryItems.Items)
            {
                if (li.Selected)
                {
                    int nId;

                    if (int.TryParse(li.Value, out nId))
                    {
                        var di = new cms.businesslogic.Dictionary.DictionaryItem(nId);
                        di.delete();
                        _pack.Data.DictionaryItems.Remove(nId.ToString());
                    }
                }
            }

            //Remove Data types
            foreach (ListItem li in dataTypes.Items)
            {
                if (li.Selected)
                {
                    int nId;

                    if (int.TryParse(li.Value, out nId))
                    {
                        var dtd = new cms.businesslogic.datatype.DataTypeDefinition(nId);
                        dtd.delete();
                        _pack.Data.DataTypes.Remove(nId.ToString());
                    }
                }
            }

            _pack.Save();

            if (!IsManifestEmpty())
            {
                Response.Redirect(Request.RawUrl);
            }
            else
            {
                
                // uninstall actions
                try
                {
                    var actionsXml = new XmlDocument();
                    actionsXml.LoadXml("<Actions>" + _pack.Data.Actions + "</Actions>");

                    LogHelper.Debug<installedPackage>("executing undo actions: {0}", () => actionsXml.OuterXml);

                    foreach (XmlNode n in actionsXml.DocumentElement.SelectNodes("//Action"))
                    {
                        try
                        {
                            cms.businesslogic.packager.PackageAction.UndoPackageAction(_pack.Data.Name, n.Attributes["alias"].Value, n);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error<installedPackage>("An error occurred running undo actions", ex);
						}
					}
                }
                catch (Exception ex)
                {
                    LogHelper.Error<installedPackage>("An error occurred running undo actions", ex);
				}

	            //moved remove of files here so custom package actions can still undo
                //Remove files
                foreach (ListItem li in files.Items)
                {
                    if (li.Selected)
                    {
                        //here we need to try to find the file in question as most packages does not support the tilde char

                        var file = IOHelper.FindFile(li.Value);

                        var filePath = IOHelper.MapPath(file);
                        if (System.IO.File.Exists(filePath))
                        {
                            System.IO.File.Delete(filePath);
                            _pack.Data.Files.Remove(li.Value);
                        }
                    }
                }
                _pack.Save();

                _pack.Delete();

                packageUninstalled.Visible = true;
                installedPackagePanel.Visible = false;
            }

            // refresh cache
            if (refreshCache)
            {
                library.RefreshContent();
            }

            //ensure that all tree's are refreshed after uninstall
            ClientTools.ClearClientTreeCache()
                .RefreshTree();

            TreeDefinitionCollection.Instance.ReRegisterTrees();

            BizLogicAction.ReRegisterActionsAndHandlers();
            
        }
 /// <summary>
 /// Removes cache for template
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 static void TemplateAfterDelete(Template sender, DeleteEventArgs e)
 {
     DistributedCache.Instance.RemoveTemplateCache(sender.Id);
 }
 /// <summary>
 /// Refresh cache for template
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 static void TemplateAfterSave(Template sender, SaveEventArgs e)
 {
     DistributedCache.Instance.RefreshTemplateCache(sender.Id);
 } 
 /// <summary>
 /// Refresh cache for template
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 static void TemplateAfterSave(Template sender, SaveEventArgs e)
 {
     DistributedCache.Instance.RefreshTemplateCache(sender.Id);
 }