Exemple #1
0
        void WriteFileContext(string path)
        {
            string fileContent;

            if (!File.Exists(path))
            {
                return;
            }

            if (Path.GetExtension(path) == Constants.PackageExtension)
            {
                var pkg  = new OptimizedZipPackage(path);
                var ver1 = pkg.Version.ToString();
                var ver2 = pkg.Version.Version.ToString();
                if (ver1 == ver2 || $"{ver1}.0" == ver2)
                {
                    fileContent = ver2;
                }
                else
                {
                    fileContent = $"{ver1} (normalized: {ver2})";
                }
            }
            else
            {
                fileContent = File.ReadAllText(path);
            }

            string shortPath = InstallContext.NormalizeMessage(path);

            LogService.console.Info($"{shortPath}: {fileContent}");
        }
Exemple #2
0
        public string hash_file(string filePath)
        {
            if (!_fileSystem.file_exists(filePath))
            {
                return(string.Empty);
            }

            try
            {
                var hash = _hashAlgorithm.ComputeHash(_fileSystem.read_file_bytes(filePath));

                return(BitConverter.ToString(hash).Replace("-", string.Empty));
            }
            catch (IOException ex)
            {
                this.Log().Warn(() => "Error computing hash for '{0}'{1} Hash will be special code for locked file or file too big instead.{1} Captured error:{1}  {2}".format_with(
                                    InstallContext.NormalizeMessage(filePath), Environment.NewLine, InstallContext.NormalizeMessage(ex.Message)));

                if (file_is_locked(ex))
                {
                    return(ApplicationParameters.HashProviderFileLocked);
                }

                //IO.IO_FileTooLong2GB (over Int32.MaxValue)
                return(ApplicationParameters.HashProviderFileTooBig);
            }
        }
        public string ToStringFull(string prefix = "")
        {
            StringBuilder sb          = new StringBuilder();
            List <string> ignoreProps = new[] {
                nameof(InstallDate),            // changing everytime.
                nameof(RegistryView),           // not sure if test machine is 32 or 64 bit.
                nameof(InstallerType),          // don't care ...
                nameof(SystemComponent),
                nameof(WindowsInstaller),
            }.ToList();

            foreach (var prop in GetType().GetProperties().OrderBy(x => x.MetadataToken))
            {
                object obj = prop.GetValue(this);
                if (obj == null)
                {
                    continue;
                }

                if (ignoreProps.Contains(prop.Name))
                {
                    continue;
                }

                string value = InstallContext.NormalizeMessage(obj.ToString());
                if (!string.IsNullOrEmpty(value))
                {
                    sb.AppendLine($"{prefix}{prop.Name}: {value}");
                }
            }

            return(sb.ToString());
        }
Exemple #4
0
        public override void move_directory(string directoryPath, string newDirectoryPath)
        {
            if (string.IsNullOrWhiteSpace(directoryPath) || string.IsNullOrWhiteSpace(newDirectoryPath))
            {
                throw new ApplicationException("You must provide a directory to move from or to.");
            }

            //Linux/MacOS do not have a SystemDrive environment variable, instead, everything is under "/"
            var systemDrive = Platform.get_platform() == PlatformType.Windows ? Environment.GetEnvironmentVariable("SystemDrive") : "/";

            if (combine_paths(directoryPath, "").is_equal_to(combine_paths(systemDrive, "")))
            {
                throw new ApplicationException("Cannot move or delete the root of the system drive");
            }

            try
            {
                this.Log().Debug(ChocolateyLoggers.Verbose, "Moving '{0}'{1} to '{2}'".format_with(directoryPath, Environment.NewLine, newDirectoryPath));
                allow_retries(
                    () =>
                {
                    try
                    {
                        Directory.Move(directoryPath, newDirectoryPath);
                    }
                    catch (IOException)
                    {
                        System_IO.Directory.Move(directoryPath, newDirectoryPath);
                    }
                });
            }
            catch (Exception ex)
            {
                this.Log().Warn(ChocolateyLoggers.Verbose, "Move failed with message:{0} {1}{0} Attempting backup move method.".format_with(
                                    Environment.NewLine, InstallContext.NormalizeMessage(ex.Message)));

                create_directory_if_not_exists(newDirectoryPath, ignoreError: true);
                foreach (var file in get_files(directoryPath, "*.*", SearchOption.AllDirectories).or_empty_list_if_null())
                {
                    var destinationFile = file.Replace(directoryPath, newDirectoryPath);
                    if (file_exists(destinationFile))
                    {
                        delete_file(destinationFile);
                    }

                    create_directory_if_not_exists(get_directory_name(destinationFile), ignoreError: true);
                    this.Log().Debug(ChocolateyLoggers.Verbose, "Moving '{0}'{1} to '{2}'".format_with(file, Environment.NewLine, destinationFile));
                    move_file(file, destinationFile);
                }

                Thread.Sleep(1000); // let the moving files finish up
                delete_directory_if_exists(directoryPath, recursive: true);
            }

            Thread.Sleep(2000); // sleep for enough time to allow the folder to be cleared
        }
Exemple #5
0
        /// <summary>
        /// Tries a function the specified number of tries, warning on each failure and raises error on the last attempt.
        /// </summary>
        /// <typeparam name="T">The type of the return value from the function.</typeparam>
        /// <param name="numberOfTries">The number of tries.</param>
        /// <param name="function">The function.</param>
        /// <param name="waitDurationMilliseconds">The wait duration in milliseconds.</param>
        /// <param name="increaseRetryByMilliseconds">The time for each try to increase the wait duration by in milliseconds.</param>
        /// <returns>The return value from the function</returns>
        /// <exception cref="System.ApplicationException">You must specify a number of retries greater than zero.</exception>
        /// <param name="isSilent">Log messages?</param>
        public static T retry <T>(int numberOfTries, Func <T> function, int waitDurationMilliseconds = 100, int increaseRetryByMilliseconds = 0, bool isSilent = false)
        {
            if (function == null)
            {
                return(default(T));
            }
            if (numberOfTries == 0)
            {
                throw new ApplicationException("You must specify a number of tries greater than zero.");
            }
            var returnValue = default(T);

            var debugging   = log_is_in_debug_mode();
            var logLocation = ChocolateyLoggers.Normal;

            if (isSilent)
            {
                logLocation = ChocolateyLoggers.LogFileOnly;
            }

            for (int i = 1; i <= numberOfTries; i++)
            {
                try
                {
                    returnValue = function.Invoke();
                    break;
                }
                catch (Exception ex)
                {
                    if (i == numberOfTries)
                    {
                        "chocolatey".Log().Error(logLocation, "Maximum tries of {0} reached. Throwing error.".format_with(numberOfTries));
                        throw;
                    }

                    int retryWait = waitDurationMilliseconds + (i * increaseRetryByMilliseconds);

                    var exceptionMessage = debugging ? ex.ToString() : ex.Message;

                    "chocolatey".Log().Warn(logLocation, "This is try {3}/{4}. Retrying after {2} milliseconds.{0} Error converted to warning:{0} {1}".format_with(
                                                Environment.NewLine,
                                                InstallContext.NormalizeMessage(exceptionMessage),
                                                retryWait,
                                                i,
                                                numberOfTries));
                    Thread.Sleep(retryWait);
                }
            }

            return(returnValue);
        }
Exemple #6
0
        /// <summary>
        /// Wraps a function with a try/catch, logging an error when it fails.
        /// </summary>
        /// <typeparam name="T">The type of the return value from the function.</typeparam>
        /// <param name="function">The function.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <param name="throwError">if set to <c>true</c> [throw error].</param>
        /// <param name="logWarningInsteadOfError">if set to <c>true</c> log as warning instead of error.</param>
        /// <param name="logDebugInsteadOfError">Log to debug</param>
        /// <param name="isSilent">Log messages?</param>
        /// <returns>The return value from the function</returns>
        public static T try_catch_with_logging_exception <T>(Func <T> function, string errorMessage, bool throwError = false, bool logWarningInsteadOfError = false, bool logDebugInsteadOfError = false, bool isSilent = false)
        {
            if (function == null)
            {
                return(default(T));
            }
            var returnValue = default(T);

            var logLocation = ChocolateyLoggers.Normal;

            if (isSilent)
            {
                logLocation = ChocolateyLoggers.LogFileOnly;
            }

            try
            {
                returnValue = function.Invoke();
            }
            catch (Exception ex)
            {
                var exceptionMessage = log_is_in_debug_mode() ? ex.ToString() : ex.Message;

                exceptionMessage = InstallContext.NormalizeMessage(exceptionMessage);
                errorMessage     = InstallContext.NormalizeMessage(errorMessage);

                if (logDebugInsteadOfError)
                {
                    "chocolatey".Log().Debug(logLocation, "{0}:{1} {2}".format_with(errorMessage, Environment.NewLine, exceptionMessage));
                }
                else if (logWarningInsteadOfError)
                {
                    "chocolatey".Log().Warn(logLocation, "{0}:{1} {2}".format_with(errorMessage, Environment.NewLine, exceptionMessage));
                }
                else
                {
                    "chocolatey".Log().Error(logLocation, "{0}:{1} {2}".format_with(errorMessage, Environment.NewLine, exceptionMessage));
                }

                if (throwError)
                {
                    throw;
                }
            }

            return(returnValue);
        }
Exemple #7
0
        private void output_tostring(StringBuilder propertyValues, IEnumerable <PropertyInfo> properties, object obj, object secondobj, string prepend)
        {
            foreach (var propertyInfo in properties.or_empty_list_if_null())
            {
                // skip sensitive data info
                if (!ApplicationParameters.runningUnitTesting)
                {
                    if (propertyInfo.Name.contains("password") || propertyInfo.Name.contains("sensitive") || propertyInfo.Name == "Key" || propertyInfo.Name == "ConfigValue" || propertyInfo.Name == "MachineSources")
                    {
                        continue;
                    }
                }

                var    objectValue       = propertyInfo.GetValue(obj, null);
                object secondObjectValue = null;
                if (secondobj != null)
                {
                    secondObjectValue = propertyInfo.GetValue(secondobj, null);
                }

                if (propertyInfo.PropertyType.is_built_in_system_type())
                {
                    bool doAppend = !string.IsNullOrWhiteSpace(objectValue.to_string());

                    if (doAppend)
                    {
                        doAppend = !Object.Equals(objectValue, secondObjectValue);
                    }

                    if (doAppend)
                    {
                        var output = "{0}{1}='{2}'".format_with(
                            string.IsNullOrWhiteSpace(prepend) ? "" : prepend + ".",
                            propertyInfo.Name,
                            objectValue.to_string());

                        if (propertyInfo.Name == "Sources")
                        {
                            // Can contain paths
                            output = InstallContext.NormalizeMessage(output);
                        }

                        append_output(propertyValues, output);
                    }
                }
                else if (propertyInfo.PropertyType.is_collections_type())
                {
                    var list       = (objectValue as IDictionary <string, string>).or_empty_list_if_null().ToList();
                    var secondlist = (secondObjectValue as IDictionary <string, string>).or_empty_list_if_null().ToList();

                    for (int i = 0; i < list.Count; i++)
                    {
                        if (i < secondlist.Count && Object.Equals(list[i], secondlist[i]))
                        {
                            continue;
                        }

                        var item   = list[i];
                        var output = "{0}{1}.{2}='{3}'".format_with(
                            string.IsNullOrWhiteSpace(prepend) ? "" : prepend + ".",
                            propertyInfo.Name,
                            item.Key,
                            item.Value);

                        append_output(propertyValues, output);
                    }
                }
                else
                {
                    output_tostring(propertyValues, propertyInfo.PropertyType.GetProperties(), objectValue, secondObjectValue, propertyInfo.Name);
                }
            }
        }