/// <exclude />
        public override IEnumerable <PackageFragmentValidationResult> Validate()
        {
            var validationResult = new List <PackageFragmentValidationResult>();

            if (this.Configuration.Count(f => f.Name == "Files") > 1)
            {
                validationResult.AddFatal(Texts.FilePackageFragmentInstaller_OnlyOneFilesElement,
                                          this.ConfigurationParent);
                return(validationResult);
            }

            XElement filesElement = this.Configuration.SingleOrDefault(f => f.Name == "Files");

            _filesToCopy = new List <FileToCopy>();

            if (filesElement != null)
            {
                foreach (XElement fileElement in filesElement.Elements("File"))
                {
                    XAttribute sourceFilenameAttribute = fileElement.Attribute("sourceFilename");
                    XAttribute targetFilenameAttribute = fileElement.Attribute("targetFilename");

                    if (sourceFilenameAttribute == null)
                    {
                        validationResult.AddFatal(
                            Texts.FilePackageFragmentInstaller_MissingAttribute("sourceFilename"), fileElement);
                        continue;
                    }

                    if (targetFilenameAttribute == null)
                    {
                        validationResult.AddFatal(
                            Texts.FilePackageFragmentInstaller_MissingAttribute("targetFilename"), fileElement);
                        continue;
                    }

                    XAttribute allowOverwriteAttribute     = fileElement.Attribute("allowOverwrite");
                    XAttribute assemblyLoadAttribute       = fileElement.Attribute("assemblyLoad");
                    XAttribute onlyUpdateAttribute         = fileElement.Attribute("onlyUpdate");
                    XAttribute addAssemblyBindingAttribute = fileElement.Attribute("addAssemblyBinding");


                    bool allowOverwrite = false;
                    if (!ParseBoolAttribute(allowOverwriteAttribute, validationResult, ref allowOverwrite))
                    {
                        continue;
                    }

                    bool loadAssembly = false;
                    if (!ParseBoolAttribute(assemblyLoadAttribute, validationResult, ref loadAssembly))
                    {
                        continue;
                    }

                    bool onlyUpdate = false;
                    if (!ParseBoolAttribute(onlyUpdateAttribute, validationResult, ref onlyUpdate))
                    {
                        continue;
                    }

                    bool addAssemblyBinding = false;
                    if (!ParseBoolAttribute(addAssemblyBindingAttribute, validationResult, ref addAssemblyBinding))
                    {
                        continue;
                    }

                    string sourceFilename = sourceFilenameAttribute.Value;
                    if (!this.InstallerContext.ZipFileSystem.ContainsFile(sourceFilename))
                    {
                        validationResult.AddFatal(Texts.FilePackageFragmentInstaller_MissingFile(sourceFilename),
                                                  sourceFilenameAttribute);
                        continue;
                    }

                    if (loadAssembly && onlyUpdate)
                    {
                        validationResult.AddFatal(
                            Texts.FilePackageFragmentInstaller_OnlyUpdateNotAllowedWithLoadAssemlby, onlyUpdateAttribute);
                        continue;
                    }

                    string targetFilename = PathUtil.Resolve(targetFilenameAttribute.Value);
                    if (C1File.Exists(targetFilename))
                    {
                        if (!allowOverwrite && !onlyUpdate)
                        {
                            validationResult.AddFatal(Texts.FilePackageFragmentInstaller_FileExists(targetFilename),
                                                      targetFilenameAttribute);
                            continue;
                        }

                        if (((C1File.GetAttributes(targetFilename) & FileAttributes.ReadOnly) > 0) && !allowOverwrite)
                        {
                            validationResult.AddFatal(Texts.FilePackageFragmentInstaller_FileReadOnly(targetFilename),
                                                      targetFilenameAttribute);
                            continue;
                        }
                    }
                    else if (onlyUpdate)
                    {
                        Log.LogVerbose(LogTitle, "Skipping updating of the file '{0}' because it does not exist",
                                       targetFilename);
                        continue; // Target file does not, so skip this
                    }

                    var fileToCopy = new FileToCopy
                    {
                        SourceFilename         = sourceFilename,
                        TargetRelativeFilePath = targetFilenameAttribute.Value,
                        TargetFilePath         = targetFilename,
                        Overwrite          = allowOverwrite || onlyUpdate,
                        AddAssemblyBinding = addAssemblyBinding
                    };

                    _filesToCopy.Add(fileToCopy);

                    if (loadAssembly)
                    {
                        string tempFilename = Path.Combine(this.InstallerContext.TempDirectory,
                                                           Path.GetFileName(targetFilename));

                        this.InstallerContext.ZipFileSystem.WriteFileToDisk(sourceFilename, tempFilename);

                        PackageAssemblyHandler.AddAssembly(tempFilename);
                    }
                }
            }


            if (validationResult.Count > 0)
            {
                _filesToCopy = null;
            }

            return(validationResult);
        }
示例#2
0
        /// <exclude />
        public override IEnumerable <XElement> Install()
        {
            Verify.IsNotNull(_filesToCopy, "{0} has not been validated", this.GetType().Name);

            var asmBindingsToAdd = new List <AssemblyName>();


            var fileElements = new List <XElement>();

            foreach (FileToCopy fileToCopy in _filesToCopy)
            {
                Log.LogVerbose(LogTitle, "Installing the file '{0}' to the target filename '{1}'",
                               fileToCopy.SourceFilename, fileToCopy.TargetFilePath);

                // Extracting the dll file so version can be checked
                string tempFileName = Path.Combine(InstallerContext.TempDirectory, Path.GetRandomFileName());
                this.InstallerContext.ZipFileSystem.WriteFileToDisk(fileToCopy.SourceFilename, tempFileName);

                // Checking for dll version here:
                var sourceAssemblyName    = AssemblyName.GetAssemblyName(tempFileName);
                var sourceAssemblyVersion = sourceAssemblyName.Version;
                var sourceFileVersion     = GetDllFileVersion(tempFileName);

                string targetDirectory = Path.GetDirectoryName(fileToCopy.TargetFilePath);
                if (!Directory.Exists(targetDirectory))
                {
                    Directory.CreateDirectory(targetDirectory);
                }

                string backupFileName = null;

                bool addAssemblyBinding = fileToCopy.AddAssemblyBinding;

                if (C1File.Exists(fileToCopy.TargetFilePath) && fileToCopy.Overwrite)
                {
                    var existingAssemblyVersion = AssemblyName.GetAssemblyName(fileToCopy.TargetFilePath).Version;
                    var existingFileVersion     = GetDllFileVersion(fileToCopy.TargetFilePath);

                    if (existingAssemblyVersion == sourceAssemblyVersion &&
                        existingFileVersion >= sourceFileVersion)
                    {
                        Log.LogInformation(LogTitle,
                                           "Skipping installation for file '{0}' version '{1}'. An assembly with the same version already exists.",
                                           fileToCopy.TargetRelativeFilePath, sourceAssemblyVersion);
                        continue;
                    }

                    if (existingAssemblyVersion > sourceAssemblyVersion)
                    {
                        Log.LogInformation(LogTitle,
                                           "Skipping installation for file '{0}' version '{1}', as a file with a newer version '{2}' already exists.",
                                           fileToCopy.TargetRelativeFilePath, sourceAssemblyVersion, existingAssemblyVersion);
                        continue;
                    }

                    addAssemblyBinding = existingAssemblyVersion < sourceAssemblyVersion;

                    if ((C1File.GetAttributes(fileToCopy.TargetFilePath) & FileAttributes.ReadOnly) > 0)
                    {
                        FileUtils.RemoveReadOnly(fileToCopy.TargetFilePath);
                    }

                    if (InstallerContext.PackageInformation.CanBeUninstalled)
                    {
                        backupFileName = GetBackupFileName(fileToCopy.TargetFilePath);

                        string backupFilesFolder = this.InstallerContext.PackageDirectory + "\\FileBackup";

                        C1Directory.CreateDirectory(backupFilesFolder);

                        C1File.Copy(fileToCopy.TargetFilePath, backupFilesFolder + "\\" + backupFileName);
                    }

                    Log.LogInformation(LogTitle, "Overwriting existing file '{0}' version '{2}', new version is '{1}'",
                                       fileToCopy.TargetRelativeFilePath, sourceFileVersion, existingFileVersion);
                }

                if (addAssemblyBinding)
                {
                    asmBindingsToAdd.Add(sourceAssemblyName);
                }


                File.Delete(fileToCopy.TargetFilePath);
                File.Move(tempFileName, fileToCopy.TargetFilePath);

                var fileElement = new XElement("File",
                                               new XAttribute("filename", fileToCopy.TargetRelativeFilePath),
                                               new XAttribute("version", sourceFileVersion));

                if (backupFileName != null)
                {
                    fileElement.Add(new XAttribute("backupFile", backupFileName));
                }

                fileElements.Add(fileElement);
            }

            UpdateBindingRedirects(asmBindingsToAdd);

            yield return(new XElement("Files", fileElements));
        }
示例#3
0
        /// <exclude />
        public override IEnumerable <PackageFragmentValidationResult> Validate()
        {
            var validationResult = new List <PackageFragmentValidationResult>();

            if (this.Configuration.Count(f => f.Name == "Files") > 1)
            {
                validationResult.AddFatal(Texts.FilePackageFragmentUninstaller_OnlyOneFilesElement, ConfigurationParent);
                return(validationResult);
            }

            XElement filesElement = this.Configuration.SingleOrDefault(f => f.Name == "Files");


            _filesToDelete = new List <string>();
            _filesToCopy   = new List <Tuple <string, string> >();

            //  NOTE: Packages, that were installed on version earlier than C1 1.2 SP3 have absolute file path references, f.e.:
            //  <File filename="C:\inetpub\docs\Frontend\Composite\Forms\Renderer\CaptchaImageCreator.ashx" />
            //  <File filename="C:\inetpub\docs\Frontend\Composite\Forms\Renderer\Controls/FormsRender.ascx" />
            //  <File filename="C:\inetpub\docs\Frontend\Composite\Forms\Renderer\Controls/FormsRender.ascx.cs" />
            List <string> absoluteReferences = new List <string>();

            if (filesElement != null)
            {
                foreach (XElement fileElement in filesElement.Elements("File").Reverse())
                {
                    XAttribute filenameAttribute = fileElement.Attribute("filename");
                    if (filenameAttribute == null)
                    {
                        validationResult.AddFatal(Texts.FilePackageFragmentInstaller_MissingAttribute("filename"), fileElement);
                        continue;
                    }

                    string filePath = filenameAttribute.Value;
                    if (filePath.Contains(":\\"))
                    {
                        absoluteReferences.Add(filePath);
                        continue;
                    }

                    filePath = PathUtil.Resolve(filePath);

                    string backupFile = (string)fileElement.Attribute("backupFile");

                    if (backupFile != null)
                    {
                        var backupFilePath = Path.Combine(UninstallerContext.PackageDirectory, "FileBackup", backupFile);
                        if (!C1File.Exists(backupFilePath))
                        {
                            validationResult.AddFatal("Missing backup file '{0}'".FormatWith(backupFilePath), fileElement);
                            continue;
                        }

                        _filesToCopy.Add(new Tuple <string, string>(backupFilePath, filePath));
                    }
                    else
                    {
                        _filesToDelete.Add(filePath);
                    }
                }
            }

            if (absoluteReferences.Count > 0)
            {
                // Trying to resolve what was the old absolute path.
                // To do that the longest common beginning is calculated

                string longestCommonBegining;

                string firstPath = absoluteReferences[0];

                if (absoluteReferences.Count == 1)
                {
                    longestCommonBegining = firstPath;
                }
                else
                {
                    int shortestPathLength = absoluteReferences.Min(path => path.Length);

                    int commonStartLength = 0;
                    for (; commonStartLength < shortestPathLength; commonStartLength++)
                    {
                        bool match  = true;
                        char symbol = firstPath[commonStartLength];
                        for (int i = 1; i < absoluteReferences.Count; i++)
                        {
                            if (absoluteReferences[i][commonStartLength] != symbol)
                            {
                                match = false;
                                break;
                            }
                        }
                        if (!match)
                        {
                            break;
                        }
                    }

                    longestCommonBegining = firstPath.Substring(0, commonStartLength);
                }

                longestCommonBegining = longestCommonBegining.Replace('/', '\\');

                if (!longestCommonBegining.EndsWith("\\"))
                {
                    longestCommonBegining = longestCommonBegining.Substring(0, longestCommonBegining.LastIndexOf("\\", StringComparison.Ordinal) + 1);
                }

                string newRoot = PathUtil.BaseDirectory;
                if (!newRoot.EndsWith("\\"))
                {
                    newRoot += "\\";
                }

                // If the site hasn't been moved to another folder, just using the pathes
                if (longestCommonBegining.StartsWith(newRoot, StringComparison.OrdinalIgnoreCase))
                {
                    _filesToDelete.AddRange(absoluteReferences);
                }
                else
                {
                    // If the longest common path looks like C:\inetpub\docs\Frontend\Composite\
                    // than we will the following pathes as site roots:
                    //
                    // C:\inetpub\docs\Frontend\Composite\
                    // C:\inetpub\docs\Frontend\
                    // C:\inetpub\docs\
                    // C:\inetpub\
                    // C:\

                    string oldRoot = longestCommonBegining;

                    bool fileExists = false;
                    while (!string.IsNullOrEmpty(oldRoot))
                    {
                        for (int i = 0; i < absoluteReferences.Count; i++)
                        {
                            if (C1File.Exists(ReplaceFolder(absoluteReferences[0], oldRoot, newRoot)))
                            {
                                fileExists = true;
                                break;
                            }
                        }
                        if (fileExists)
                        {
                            break;
                        }

                        oldRoot = ReducePath(oldRoot);
                    }

                    if (!fileExists)
                    {
                        // Showing a message if we don't have a match
                        validationResult.AddFatal(Texts.FilePackageFragmentInstaller_WrongBasePath);
                    }
                    else
                    {
                        _filesToDelete.AddRange(absoluteReferences.Select(path => ReplaceFolder(path, oldRoot, newRoot)));
                    }
                }
            }

            if (validationResult.Count > 0)
            {
                _filesToDelete = null;
                _filesToCopy   = null;
            }

            return(validationResult);
        }
        /// <exclude />
        public override IEnumerable <XElement> Install()
        {
            Verify.IsNotNull(_filesToCopy, "{0} has not been validated", this.GetType().Name);

            foreach (string directoryToDelete in _directoriesToDelete)
            {
                Directory.Delete(directoryToDelete, true);
            }

            var fileElements = new List <XElement>();

            foreach (FileToCopy fileToCopy in _filesToCopy)
            {
                Log.LogVerbose(LogTitle, "Installing the file '{0}' to the target filename '{1}'", fileToCopy.SourceFilename, fileToCopy.TargetFilePath);

                string targetDirectory = Path.GetDirectoryName(fileToCopy.TargetFilePath);
                if (!Directory.Exists(targetDirectory))
                {
                    Directory.CreateDirectory(targetDirectory);
                }

                string backupFileName = null;

                if (C1File.Exists(fileToCopy.TargetFilePath) && fileToCopy.Overwrite)
                {
                    if ((C1File.GetAttributes(fileToCopy.TargetFilePath) & FileAttributes.ReadOnly) > 0)
                    {
                        FileUtils.RemoveReadOnly(fileToCopy.TargetFilePath);
                    }

                    if (InstallerContext.PackageInformation.CanBeUninstalled)
                    {
                        backupFileName = GetBackupFileName(fileToCopy.TargetFilePath);

                        string backupFilesFolder = this.InstallerContext.PackageDirectory + "\\FileBackup";

                        C1Directory.CreateDirectory(backupFilesFolder);

                        C1File.Copy(fileToCopy.TargetFilePath, backupFilesFolder + "\\" + backupFileName);
                    }
                }

                this.InstallerContext.ZipFileSystem.WriteFileToDisk(fileToCopy.SourceFilename, fileToCopy.TargetFilePath);

                // Searching for static IData interfaces
                string targetFilePath = fileToCopy.TargetFilePath;

                if (targetFilePath.StartsWith(Path.Combine(PathUtil.BaseDirectory, "Bin"), StringComparison.InvariantCultureIgnoreCase) &&
                    targetFilePath.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase))
                {
                    string fileName = Path.GetFileName(targetFilePath);

                    if (!DllsNotToLoad.Any(fileName.StartsWith))
                    {
                        Assembly assembly;

                        try
                        {
                            assembly = Assembly.LoadFrom(targetFilePath);
                        }
                        catch (Exception)
                        {
                            continue;
                        }

                        DataTypeTypesManager.AddNewAssembly(assembly, false);
                    }
                }

                var fileElement = new XElement("File", new XAttribute("filename", fileToCopy.TargetRelativeFilePath));

                if (backupFileName != null)
                {
                    fileElement.Add(new XAttribute("backupFile", backupFileName));
                }

                fileElements.Add(fileElement);
            }

            yield return(new XElement("Files", fileElements));
        }
示例#5
0
        /// <exclude />
        public static IEnumerable <InstalledPackageInformation> GetInstalledPackages()
        {
            string baseDirectory = PathUtil.Resolve(GlobalSettingsFacade.PackageDirectory);

            if (!C1Directory.Exists(baseDirectory))
            {
                yield break;
            }

            string[] packageDirectories = C1Directory.GetDirectories(baseDirectory);
            foreach (string packageDirectory in packageDirectories)
            {
                if (C1File.Exists(Path.Combine(packageDirectory, PackageSystemSettings.InstalledFilename)))
                {
                    string filename = Path.Combine(packageDirectory, PackageSystemSettings.PackageInformationFilename);

                    if (C1File.Exists(filename))
                    {
                        XDocument doc = XDocumentUtils.Load(filename);

                        XElement packageInfoElement = doc.Root;
                        if (packageInfoElement.Name != XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageInfoElementName))
                        {
                            throw new InvalidOperationException(string.Format("{0} is wrongly formattet", filename));
                        }

                        XAttribute nameAttribute                      = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_NameAttributeName);
                        XAttribute groupNameAttribute                 = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_GroupNameAttributeName);
                        XAttribute versionAttribute                   = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_VersionAttributeName);
                        XAttribute authorAttribute                    = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_AuthorAttributeName);
                        XAttribute websiteAttribute                   = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_WebsiteAttributeName);
                        XAttribute descriptionAttribute               = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_DescriptionAttributeName);
                        XAttribute installDateAttribute               = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_InstallDateAttributeName);
                        XAttribute installedByAttribute               = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_InstalledByAttributeName);
                        XAttribute isLocalInstalledAttribute          = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_IsLocalInstalledAttributeName);
                        XAttribute canBeUninstalledAttribute          = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_CanBeUninstalledAttributeName);
                        XAttribute flushOnCompletionAttribute         = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_FlushOnCompletionAttributeName);
                        XAttribute reloadConsoleOnCompletionAttribute = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_ReloadConsoleOnCompletionAttributeName);
                        XAttribute systemLockingAttribute             = GetAttributeNotNull(filename, packageInfoElement, PackageSystemSettings.PackageInfo_SystemLockingAttributeName);

                        XAttribute packageServerAddressAttribute = packageInfoElement.Attribute(PackageSystemSettings.PackageInfo_PackageServerAddressAttributeName);


                        SystemLockingType systemLockingType;
                        if (systemLockingAttribute.TryDeserialize(out systemLockingType) == false)
                        {
                            throw new InvalidOperationException("The systemLocking attibute value is wrong");
                        }

                        string path = packageDirectory.Remove(0, baseDirectory.Length);
                        if (path.StartsWith("\\"))
                        {
                            path = path.Remove(0, 1);
                        }

                        Guid packageId;
                        if (!Guid.TryParse(path, out packageId))
                        {
                            continue;
                        }

                        yield return(new InstalledPackageInformation
                        {
                            Id = packageId,
                            Name = nameAttribute.Value,
                            GroupName = groupNameAttribute.Value,
                            Version = versionAttribute.Value,
                            Author = authorAttribute.Value,
                            Website = websiteAttribute.Value,
                            Description = descriptionAttribute.Value,
                            InstallDate = (DateTime)installDateAttribute,
                            InstalledBy = installedByAttribute.Value,
                            IsLocalInstalled = (bool)isLocalInstalledAttribute,
                            CanBeUninstalled = (bool)canBeUninstalledAttribute,
                            FlushOnCompletion = (bool)flushOnCompletionAttribute,
                            ReloadConsoleOnCompletion = (bool)reloadConsoleOnCompletionAttribute,
                            SystemLockingType = systemLockingType,
                            PackageServerAddress = packageServerAddressAttribute != null ? packageServerAddressAttribute.Value : null,
                            PackageInstallPath = packageDirectory
                        });
                    }
                    else
                    {
                        throw new InvalidOperationException(string.Format("{0} does not exist", filename));
                    }
                }
                else
                {
                    // Make this cleanup in an other way, it works correctly if it is done between validation and installation.
                    //LoggingService.LogVerbose("PackageManager", string.Format("Uncomlete installed add on found ('{0}'), deleting it", Path.GetFileName(packageDirecoty)));
                    //try
                    //{
                    //    Directory.Delete(packageDirecoty, true);
                    //}
                    //catch (Exception)
                    //{
                    //}
                }
            }
        }
示例#6
0
        /// <exclude />
        public static PackageManagerUninstallProcess Uninstall(Guid id)
        {
            try
            {
                string absolutePath = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PackageDirectory), id.ToString());

                InstalledPackageInformation installedPackageInformation =
                    (from package in GetInstalledPackages()
                     where package.Id == id
                     select package).SingleOrDefault();

                if (installedPackageInformation == null)
                {
                    return(new PackageManagerUninstallProcess(new List <PackageFragmentValidationResult> {
                        new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingPackageDirectory"), absolutePath))
                    }));
                }

                Log.LogVerbose("PackageManager", "Uninstalling package: {0}, Id = {1}", installedPackageInformation.Name, installedPackageInformation.Id);

                if (installedPackageInformation.CanBeUninstalled == false)
                {
                    return(new PackageManagerUninstallProcess(new List <PackageFragmentValidationResult> {
                        new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, GetText("PackageManager.Uninstallable"))
                    }));
                }

                string zipFilePath = Path.Combine(absolutePath, PackageSystemSettings.ZipFilename);
                if (C1File.Exists(zipFilePath) == false)
                {
                    return(new PackageManagerUninstallProcess(new List <PackageFragmentValidationResult> {
                        new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingZipFile"), zipFilePath))
                    }));
                }

                string uninstallFilePath = Path.Combine(absolutePath, PackageSystemSettings.UninstallFilename);
                if (C1File.Exists(uninstallFilePath) == false)
                {
                    return(new PackageManagerUninstallProcess(new List <PackageFragmentValidationResult> {
                        new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format(GetText("PackageManager.MissingUninstallFile"), uninstallFilePath))
                    }));
                }

                PackageInformation packageInformation = new PackageInformation
                {
                    Id                        = installedPackageInformation.Id,
                    Name                      = installedPackageInformation.Name,
                    GroupName                 = installedPackageInformation.GroupName,
                    Author                    = installedPackageInformation.Author,
                    Website                   = installedPackageInformation.Website,
                    Description               = installedPackageInformation.Description,
                    Version                   = installedPackageInformation.Version,
                    CanBeUninstalled          = installedPackageInformation.CanBeUninstalled,
                    SystemLockingType         = installedPackageInformation.SystemLockingType,
                    FlushOnCompletion         = installedPackageInformation.FlushOnCompletion,
                    ReloadConsoleOnCompletion = installedPackageInformation.ReloadConsoleOnCompletion,
                };


                PackageUninstaller packageUninstaller = new PackageUninstaller(zipFilePath, uninstallFilePath, absolutePath, TempDirectoryFacade.CreateTempDirectory(), installedPackageInformation.FlushOnCompletion, installedPackageInformation.ReloadConsoleOnCompletion, true, packageInformation);

                PackageManagerUninstallProcess packageManagerUninstallProcess = new PackageManagerUninstallProcess(packageUninstaller, absolutePath, installedPackageInformation.SystemLockingType);
                return(packageManagerUninstallProcess);
            }
            catch (Exception ex)
            {
                return(new PackageManagerUninstallProcess(new List <PackageFragmentValidationResult> {
                    new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex)
                }));
            }
        }
示例#7
0
        /// <exclude />
        public static bool UnbundledScriptsAvailable()
        {
            var filePath = HostingEnvironment.MapPath(UrlUtils.AdminRootPath + "/scripts/source/top/interfaces/IAcceptable.js");

            return(C1File.Exists(filePath));
        }
示例#8
0
        /// <exclude />
        public override IEnumerable <PackageFragmentValidationResult> Validate()
        {
            var validationResult = new List <PackageFragmentValidationResult>();

            if (this.Configuration.Count(f => f.Name == "Files") > 1)
            {
                validationResult.AddFatal(Texts.FilePackageFragmentUninstaller_OnlyOneFilesElement, ConfigurationParent);
                return(validationResult);
            }

            XElement filesElement = this.Configuration.SingleOrDefault(f => f.Name == "Files");


            _filesToDelete = new List <string>();
            _filesToCopy   = new List <FileToCopy>();

            if (filesElement != null)
            {
                foreach (XElement fileElement in filesElement.Elements("File").Reverse())
                {
                    XAttribute filenameAttribute = fileElement.Attribute("filename");
                    if (filenameAttribute == null)
                    {
                        validationResult.AddFatal(Texts.FilePackageFragmentInstaller_MissingAttribute("filename"), fileElement);
                        continue;
                    }

                    string relativeFilePath = filenameAttribute.Value;

                    string filePath = PathUtil.Resolve(relativeFilePath);

                    string backupFile = (string)fileElement.Attribute("backupFile");

                    if (backupFile != null)
                    {
                        var backupFilePath = Path.Combine(UninstallerContext.PackageDirectory, "FileBackup", backupFile);
                        if (!C1File.Exists(backupFilePath))
                        {
                            validationResult.AddFatal("Missing backup file '{0}'".FormatWith(backupFilePath), fileElement);
                            continue;
                        }

                        _filesToCopy.Add(new FileToCopy
                        {
                            BackupFilePath   = backupFilePath,
                            FilePath         = filePath,
                            RelativeFilePath = relativeFilePath
                        });
                    }
                    else
                    {
                        _filesToDelete.Add(filePath);
                    }
                }
            }

            if (validationResult.Count > 0)
            {
                _filesToDelete = null;
                _filesToCopy   = null;
            }

            return(validationResult);
        }
示例#9
0
            private RenderingResult RenderUrlImpl(HttpCookie authenticationCookie, string url, string outputImageFilePath, string mode)
            {
                Verify.ArgumentNotNull(authenticationCookie, "authenticationCookie");

                string cookieDomain = new Uri(url).Host;
                string cookieInfo   = authenticationCookie.Name + "," + authenticationCookie.Value + "," + cookieDomain;

                string requestLine = cookieInfo + "|" + url + "|" + outputImageFilePath + "|" + mode;

                // Async way:
                //Task<string> readerTask = Task.Run(async () =>
                //{
                //    await _stdin.WriteLineAsync(requestLine);
                //    return await _stdout.ReadLineAsync();
                //});

                Task <string> readerTask = Task.Run(() =>
                {
                    _stdin.WriteLine(requestLine);
                    return(_stdout.ReadLine());
                });

                double timeout = (DateTime.Now - _process.StartTime).TotalSeconds < 120 ? 65 : 30;

                readerTask.Wait(TimeSpan.FromSeconds(timeout));

                string output;

                switch (readerTask.Status)
                {
                case TaskStatus.RanToCompletion:
                    output = readerTask.Result;
                    break;

                default:
                    return(new RenderingResult
                    {
                        Status = RenderingResultStatus.PhantomServerTimeout,
                        Output = "Request failed to complete within expected time: " +
#if DEBUG
                                 requestLine
#else
                                 url + " " + mode
#endif
                    });
                }

                if (C1File.Exists(outputImageFilePath))
                {
                    return(new RenderingResult
                    {
                        Status = RenderingResultStatus.Success,
                        Output = output,
                        FilePath = outputImageFilePath
                    });
                }

                const string redirectResponsePrefix = "REDIRECT: ";
                if (output.StartsWith(redirectResponsePrefix))
                {
                    return(new RenderingResult
                    {
                        Status = RenderingResultStatus.Redirect,
                        Output = output,
                        RedirectUrl = output.Substring(redirectResponsePrefix.Length)
                    });
                }

                const string timeoutResponsePrefix = "TIMEOUT: ";
                if (output.StartsWith(timeoutResponsePrefix))
                {
                    return(new RenderingResult
                    {
                        Status = RenderingResultStatus.Timeout,
                        Output = output,
                        RedirectUrl = output.Substring(timeoutResponsePrefix.Length)
                    });
                }

                const string errorResponsePrefix = "ERROR: ";
                if (output.StartsWith(errorResponsePrefix))
                {
                    return(new RenderingResult
                    {
                        Status = RenderingResultStatus.Error,
                        Output = output,
                        RedirectUrl = output.Substring(errorResponsePrefix.Length)
                    });
                }

                return(new RenderingResult
                {
                    Status = RenderingResultStatus.PhantomServerIncorrectResponse,
                    Output = output
                });
            }
示例#10
0
        private IEnumerable <PackageFragmentValidationResult> LoadPackageFragmentInstallerBinaries(XElement packageFragmentInstallerBinariesElement)
        {
            var binaryElements = packageFragmentInstallerBinariesElement.Elements(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace,
                                                                                                    PackageSystemSettings.PackageFragmentInstallerBinariesAddElementName)).ToList();

            if (!binaryElements.Any())
            {
                return(new PackageFragmentValidationResult[0]);
            }

            string binariesDirectory = Path.Combine(this.PackageInstallDirectory, PackageSystemSettings.BinariesDirectoryName);

            if (!C1Directory.Exists(binariesDirectory))
            {
                C1Directory.CreateDirectory(binariesDirectory);
            }

            var result = new List <PackageFragmentValidationResult>();

            foreach (XElement element in binaryElements)
            {
                XAttribute pathAttribute = element.Attribute(PackageSystemSettings.PathAttributeName);

                string sourceFilename = pathAttribute.Value;
                string targetFilename = Path.Combine(binariesDirectory, Path.GetFileName(sourceFilename));

                ZipFileSystem zipFileSystem = new ZipFileSystem(this.ZipFilename);
                if (!zipFileSystem.ContainsFile(sourceFilename))
                {
                    result.AddFatal(string.Format("The file '{0}' is missing from the zipfile", sourceFilename));
                    continue;
                }

                // Extracting dll to package temp folder
                if (C1File.Exists(targetFilename))
                {
                    bool success = false;
                    try
                    {
                        FileUtils.Delete(targetFilename);
                        success = true;
                    }
                    catch (UnauthorizedAccessException) {}

                    if (!success)
                    {
                        result.AddFatal("Access denied to file '{0}'".FormatWith(targetFilename));
                        continue;
                    }
                }

                zipFileSystem.WriteFileToDisk(sourceFilename, targetFilename);

                string newTargetFilename = Path.Combine(this.TempDirectory, Path.GetFileName(targetFilename));
                C1File.Copy(targetFilename, newTargetFilename);

                Log.LogVerbose("PackageInstaller", "Loading package uninstaller fragment assembly '{0}'", newTargetFilename);

                PackageAssemblyHandler.AddAssembly(newTargetFilename);
            }

            return(result);
        }
        private void codeActivity1_ExecuteCode(object sender, EventArgs e)
        {
            IXmlPageTemplate pageTemplate       = this.GetBinding <IXmlPageTemplate>("PageTemplate");
            string           pageTemplateMarkup = this.GetBinding <string>("PageTemplateMarkup");

            bool   xhtmlParseable = true;
            string parseError     = null;

            try
            {
                XDocument parsedElement = XDocument.Parse(pageTemplateMarkup);

                ValidatePageTemplate(parsedElement);
            }
            catch (Exception ex)
            {
                xhtmlParseable = false;
                parseError     = ex.Message;
            }

            if (!xhtmlParseable)
            {
                FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);
                var consoleMessageService = serviceContainer.GetService <IManagementConsoleMessageService>();
                consoleMessageService.ShowMessage(
                    DialogType.Error,
                    GetString("EditXmlPageTemplateWorkflow.InvalidXmlTitle"),
                    GetString("EditXmlPageTemplateWorkflow.InvalidXmlMessage").FormatWith(parseError));
                return;
            }

            // Renaming related file if necessary
            string fileName = GetTemplateFileName(pageTemplate);

            if (Path.GetFileName(pageTemplate.PageTemplateFilePath) != fileName)
            {
                IPageTemplateFile file          = IFileServices.GetFile <IPageTemplateFile>(pageTemplate.PageTemplateFilePath);
                string            systemPath    = (file as FileSystemFileBase).SystemPath;
                string            newSystemPath = Path.Combine(Path.GetDirectoryName(systemPath), fileName);

                if (string.Compare(systemPath, newSystemPath, true) != 0 && C1File.Exists(newSystemPath))
                {
                    FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);
                    var consoleMessageService = serviceContainer.GetService <IManagementConsoleMessageService>();
                    consoleMessageService.ShowMessage(
                        DialogType.Error,
                        GetString("EditXmlPageTemplateWorkflow.InvalidXmlTitle"),
                        GetString("EditXmlPageTemplateWorkflow.CannotRenameFileExists").FormatWith(newSystemPath));
                    return;
                }

                C1File.Move(systemPath, newSystemPath);

                string newRelativePath = Path.Combine(Path.GetDirectoryName(pageTemplate.PageTemplateFilePath), fileName);
                pageTemplate.PageTemplateFilePath = newRelativePath;
            }

            IPageTemplateFile templateFile = IFileServices.GetFile <IPageTemplateFile>(pageTemplate.PageTemplateFilePath);

            templateFile.SetNewContent(pageTemplateMarkup);
            DataFacade.Update(templateFile);

            DataFacade.Update(pageTemplate);

            UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken);

            updateTreeRefresher.PostRefreshMesseges(pageTemplate.GetDataEntityToken());

            SetSaveStatus(true);
        }
        private static void LoadAllControls()
        {
            try
            {
                const string configFileFilePath = "~/App_Data/Composite/Composite.config";
                var          config             = XDocument.Load(PathUtil.Resolve(configFileFilePath));

                var controlPathes = (from element in config.Descendants()
                                     let userControlVirtualPath = (string)element.Attribute("userControlVirtualPath")
                                                                  where userControlVirtualPath != null
                                                                  select userControlVirtualPath).ToList();

                var stopWatch = new Stopwatch();
                stopWatch.Start();

                Log.LogVerbose(LogTitle, "Preloading all the controls, starting");

                foreach (var controlPath in controlPathes)
                {
                    if (!C1File.Exists(PathUtil.Resolve(controlPath)))
                    {
                        Log.LogWarning(LogTitle, "Missing a control file '{0}' referenced in '{1}'", controlPath, configFileFilePath);
                        continue;
                    }

                    try
                    {
                        BuildManagerHelper.GetCompiledType(controlPath);
                    }
                    catch (ThreadAbortException)
                    {
                        // this exception is automatically rethrown after this catch
                    }
                    catch (Exception ex)
                    {
                        Log.LogWarning(LogTitle, ex);
                    }
                }

                stopWatch.Stop();

                Log.LogVerbose(LogTitle, "Preloading all the controls: " + stopWatch.ElapsedMilliseconds + "ms");

                Func <string, bool> isAshxAsmxPath = f => f == ".ashx" || f == ".asmx";
                Func <string, bool> isAspNetPath   = f => f == ".aspx" || isAshxAsmxPath(f);
                var aspnetPaths = DirectoryUtils.GetFilesRecursively(PathUtil.Resolve("~/Composite")).Where(f => isAshxAsmxPath(Path.GetExtension(f)))
                                  .Concat(DirectoryUtils.GetFilesRecursively(PathUtil.Resolve("~/Renderers")).Where(f => isAspNetPath(Path.GetExtension(f))))
                                  .ToList();

                stopWatch.Reset();
                stopWatch.Start();

                foreach (var aspnetPath in aspnetPaths)
                {
                    try
                    {
                        BuildManagerHelper.GetCompiledType(PathUtil.GetWebsitePath(aspnetPath));
                    }
                    catch (ThreadAbortException)
                    {
                        // this exception is automatically rethrown after this catch
                    }
                    catch (Exception ex)
                    {
                        Log.LogWarning("BuildManagerHelper", ex);
                    }
                }

                stopWatch.Stop();

                Log.LogVerbose(LogTitle, "Preloading all asp.net files: " + stopWatch.ElapsedMilliseconds + "ms");
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                Log.LogWarning(LogTitle, ex);
            }
        }
示例#13
0
        /// <exclude/>
        public override IEnumerable <PackageFragmentValidationResult> Validate()
        {
            var validationResult = new List <PackageFragmentValidationResult>();

            _contentToAdd = new List <ContentToAdd>();

            foreach (var element in this.Configuration)
            {
                if (element.Name != AppendText_ElementName)
                {
                    validationResult.AddFatal(Texts.PackageFragmentInstaller_IncorrectElement(element.Name.LocalName, AppendText_ElementName), element);
                    continue;
                }

                var pathAttr = element.Attribute(TargetXml_AttributeName);
                if (pathAttr == null)
                {
                    validationResult.AddFatal(Texts.PackageFragmentInstaller_MissingAttribute(TargetXml_AttributeName), element);
                    continue;
                }

                string path = (string)pathAttr;

                var actionOnMissingFile = ActionOnMissingFile.Fail;

                var whenNotExistsAttr = element.Attribute(WhenNotExist_AttributeName);
                if (whenNotExistsAttr != null)
                {
                    actionOnMissingFile = (ActionOnMissingFile)Enum.Parse(typeof(ActionOnMissingFile), whenNotExistsAttr.Value, true);
                }

                string filePath = PathUtil.Resolve(path);
                if (!C1File.Exists(filePath))
                {
                    if (actionOnMissingFile == ActionOnMissingFile.Fail)
                    {
                        validationResult.AddFatal(Texts.FileModifyPackageFragmentInstaller_FileDoesNotExist(filePath), pathAttr);
                        continue;
                    }

                    if (actionOnMissingFile == ActionOnMissingFile.Ignore)
                    {
                        continue;
                    }
                }

                _contentToAdd.Add(new ContentToAdd
                {
                    Path    = filePath,
                    Content = element.Value
                });
            }


            if (validationResult.Any())
            {
                _contentToAdd = null;
            }

            return(validationResult);
        }
示例#14
0
        private RenderingResult RenderUrlImpl(HttpCookie[] cookies, string url, string outputImageFilePath, string mode)
        {
            Verify.ArgumentNotNull(cookies, nameof(cookies));

            string cookieDomain = new Uri(url).Host;

            var request = new RenderPreviewRequest
            {
                requestId      = "1",
                mode           = mode,
                url            = url,
                outputFilePath = outputImageFilePath,
                cookies        = cookies.Select(cookie => new CookieInformation
                {
                    name   = cookie.Name,
                    value  = cookie.Value,
                    domain = cookieDomain
                }).ToArray()
            };

            var ms  = new MemoryStream();
            var ser = new DataContractJsonSerializer(typeof(RenderPreviewRequest));

            ser.WriteObject(ms, request);

            var json = Encoding.UTF8.GetString(ms.ToArray());

            var output = new List <string>();

            Task readerTask = Task.Run(() =>
            {
                _stdin.WriteLine(json);

                string line;

                do
                {
                    line = _stdout.ReadLine();
                    lock (output)
                    {
                        output.Add(line);
                    }
                } while (!IsEndOfReply(line));
            });

            var    secondsSinceStartup = (DateTime.Now - _process.StartTime).TotalSeconds;
            double timeout             = secondsSinceStartup < 120 || mode == "test" ? 65 : 30;

            readerTask.Wait(TimeSpan.FromSeconds(timeout));

            // TODO: check for theother task statuses
            switch (readerTask.Status)
            {
            case TaskStatus.RanToCompletion:
                if (output.Count == 0)
                {
                    return(new RenderingResult
                    {
                        Status = RenderingResultStatus.PhantomServerNoOutput,
                        Output = new [] { "(null)" }
                    });
                }
                break;

            default:
                string[] outputCopy;
                lock (output)
                {
                    outputCopy = output.ToArray();
                }

                string logMessage = "Request failed to complete within expected time: " +
#if DEBUG
                                    json
#else
                                    url + " " + mode
#endif
                ;


                return(new RenderingResult
                {
                    Status = RenderingResultStatus.PhantomServerTimeout,
                    Output = new [] { logMessage }.Concat(outputCopy).ToArray(),
                    FilePath = outputImageFilePath
                });
            }

            if (C1File.Exists(outputImageFilePath))
            {
                return(new RenderingResult
                {
                    Status = RenderingResultStatus.Success,
                    Output = output,
                    FilePath = outputImageFilePath
                });
            }

            var lastMessage = output.Last();

            if (!lastMessage.StartsWith(EndOfReplyMarker))
            {
                Log.LogError(LogTitle, $"Missing {EndOfReplyMarker} in the response");
            }

            string redirectUrl           = null;
            RenderingResultStatus?status = null;

            foreach (var line in output)
            {
                const string redirectResponsePrefix = "REDIRECT: ";

                if (line == "SUCCESS")
                {
                    status = RenderingResultStatus.Success;
                }
                else if (line.StartsWith(redirectResponsePrefix))
                {
                    status      = RenderingResultStatus.Redirect;
                    redirectUrl = line.Substring(redirectResponsePrefix.Length);
                }
                else if (line.StartsWith("TIMEOUT: "))
                {
                    status = RenderingResultStatus.Timeout;
                }
                else if (line.StartsWith("ERROR: "))
                {
                    status = RenderingResultStatus.Error;
                }
            }

            status = status ?? RenderingResultStatus.PhantomServerIncorrectResponse;

            return(new RenderingResult
            {
                Status = status.Value,
                Output = output,
                RedirectUrl = redirectUrl
            });
        }
        /// <summary>
        /// Gets the resized image.
        /// </summary>
        /// <param name="httpServerUtility">An instance of <see cref="System.Web.HttpServerUtility" />.</param>
        /// <param name="file">The media file.</param>
        /// <param name="resizingOptions">The resizing options.</param>
        /// <param name="targetImageFormat">The target image format.</param>
        /// <returns>A full file path to a resized image; null if there's no need to resize the image</returns>
        public static string GetResizedImage(HttpServerUtility httpServerUtility, IMediaFile file, ResizingOptions resizingOptions, ImageFormat targetImageFormat)
        {
            Verify.ArgumentNotNull(file, "file");
            Verify.That(ImageFormatIsSupported(targetImageFormat), "Unsupported image format '{0}'", targetImageFormat);

            if (_resizedImagesDirectoryPath == null)
            {
                _resizedImagesDirectoryPath = httpServerUtility.MapPath(ResizedImagesCacheDirectory);

                if (!C1Directory.Exists(_resizedImagesDirectoryPath))
                {
                    C1Directory.CreateDirectory(_resizedImagesDirectoryPath);
                }
            }

            string imageKey = file.CompositePath;

            bool isNativeProvider = file is FileSystemFileBase;

            string imageSizeCacheKey = "ShowMedia.ashx image size " + imageKey;
            Size?  imageSize         = HttpRuntime.Cache.Get(imageSizeCacheKey) as Size?;

            Bitmap bitmap     = null;
            Stream fileStream = null;

            try
            {
                if (imageSize == null)
                {
                    fileStream = file.GetReadStream();

                    Size calculatedSize;
                    if (!ImageSizeReader.TryGetSize(fileStream, out calculatedSize))
                    {
                        fileStream.Dispose();
                        fileStream = file.GetReadStream();

                        bitmap         = new Bitmap(fileStream);
                        calculatedSize = new Size {
                            Width = bitmap.Width, Height = bitmap.Height
                        };
                    }
                    imageSize = calculatedSize;

                    // We can provider cache dependency only for the native media provider
                    var cacheDependency = isNativeProvider ? new CacheDependency((file as FileSystemFileBase).SystemPath) : null;

                    HttpRuntime.Cache.Add(imageSizeCacheKey, imageSize, cacheDependency, DateTime.MaxValue, CacheExpirationTimeSpan, CacheItemPriority.Normal, null);
                }

                int  newWidth, newHeight;
                bool centerCrop;
                bool needToResize = CalculateSize(imageSize.Value.Width, imageSize.Value.Height, resizingOptions, out newWidth, out newHeight, out centerCrop);

                needToResize = needToResize || resizingOptions.CustomQuality;

                if (!needToResize)
                {
                    return(null);
                }

                int filePathHash = imageKey.GetHashCode();

                string centerCroppedString = centerCrop ? "c" : string.Empty;

                string fileExtension        = _ImageFormat2Extension[targetImageFormat];
                string resizedImageFileName = string.Format("{0}x{1}_{2}{3}_{4}.{5}", newWidth, newHeight, filePathHash, centerCroppedString, resizingOptions.Quality, fileExtension);

                string imageFullPath = Path.Combine(_resizedImagesDirectoryPath, resizedImageFileName);

                if (!C1File.Exists(imageFullPath) || C1File.GetLastWriteTime(imageFullPath) != file.LastWriteTime)
                {
                    if (bitmap == null)
                    {
                        fileStream = file.GetReadStream();
                        bitmap     = new Bitmap(fileStream);
                    }

                    ResizeImage(bitmap, imageFullPath, newWidth, newHeight, centerCrop, targetImageFormat, resizingOptions.Quality);

                    if (file.LastWriteTime.HasValue)
                    {
                        C1File.SetLastWriteTime(imageFullPath, file.LastWriteTime.Value);
                    }
                }

                return(imageFullPath);
            }
            finally
            {
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }

                if (fileStream != null)
                {
                    fileStream.Dispose();
                }
            }
        }