Example #1
0
        /// <summary>
        /// Extract the contents of a zip file held in a stream.
        /// </summary>
        /// <param name="inputStream">The seekable input stream containing the zip to extract from.</param>
        /// <param name="targetDirectory">The directory to save extracted information in.</param>
        /// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
        /// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
        /// <param name="fileFilter">A filter to apply to files.</param>
        /// <param name="directoryFilter">A filter to apply to directories.</param>
        /// <param name="restoreDateTime">Flag indicating whether to restore the date and time for extracted files.</param>
        /// <param name="isStreamOwner">Flag indicating whether the inputStream will be closed by this method.</param>
        public void ExtractZip(Stream inputStream, string targetDirectory,
                               Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate,
                               string fileFilter, string directoryFilter, bool restoreDateTime,
                               bool isStreamOwner)
        {
            if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null))
            {
                throw new ArgumentNullException("confirmDelegate");
            }

            continueRunning_      = true;
            overwrite_            = overwrite;
            confirmDelegate_      = confirmDelegate;
            extractNameTransform_ = new WindowsNameTransform(targetDirectory);

            fileFilter_               = new NameFilter(fileFilter);
            directoryFilter_          = new NameFilter(directoryFilter);
            restoreDateTimeOnExtract_ = restoreDateTime;

            using (zipFile_ = new ZipFile(inputStream)) {
#if !NETCF_1_0
                if (password_ != null)
                {
                    zipFile_.Password = password_;
                }
#endif
                zipFile_.IsStreamOwner = isStreamOwner;
                System.Collections.IEnumerator enumerator = zipFile_.GetEnumerator();
                while (continueRunning_ && enumerator.MoveNext())
                {
                    ZipEntry entry = (ZipEntry)enumerator.Current;
                    if (entry.IsFile)
                    {
                        // TODO Path.GetDirectory can fail here on invalid characters.
                        if (directoryFilter_.IsMatch(Path.GetDirectoryName(entry.Name)) && fileFilter_.IsMatch(entry.Name))
                        {
                            ExtractEntry(entry);
                        }
                    }
                    else if (entry.IsDirectory)
                    {
                        if (directoryFilter_.IsMatch(entry.Name) && CreateEmptyDirectories)
                        {
                            ExtractEntry(entry);
                        }
                    }
                    else
                    {
                        // Do nothing for volume labels etc...
                    }
                }
            }
        }
Example #2
0
        public void WritePermissions(DdlRules rules, StringWriter writer)
        {
            var template = _mapping.DdlTemplate.IsNotEmpty()
                ? rules.Templates[_mapping.DdlTemplate.ToLower()]
                : rules.Templates["default"];

            Table.WriteTemplate(template, writer);
            Upsert.WriteTemplate(rules, template, writer);
            Update.WriteTemplate(rules, template, writer);
            Insert.WriteTemplate(rules, template, writer);
            Overwrite?.WriteTemplate(rules, template, writer);
        }
Example #3
0
 public override IEnumerable <StateVariable> GetState()
 {
     return(new[] {
         new StateVariable
         {
             Name = nameof(InputPath),
             Value = InputPath,
             Type = StateVariable.StateType.Input
         },
         new StateVariable
         {
             Name = nameof(Username),
             Value = Username,
             Type = StateVariable.StateType.Input
         },
         new StateVariable
         {
             Name = nameof(PrivateKeyFile),
             Value = PrivateKeyFile,
             Type = StateVariable.StateType.Input
         },
         new StateVariable
         {
             Name = nameof(OutputPath),
             Value = OutputPath,
             Type = StateVariable.StateType.Output
         },
         new StateVariable
         {
             Name = nameof(DestinationUsername),
             Value = DestinationUsername,
             Type = StateVariable.StateType.Input
         },
         new StateVariable
         {
             Name = nameof(DestinationPrivateKeyFile),
             Value = DestinationPrivateKeyFile,
             Type = StateVariable.StateType.Input
         },
         new StateVariable
         {
             Name = nameof(Overwrite),
             Value = Overwrite.ToString(),
             Type = StateVariable.StateType.Input
         },
         new StateVariable
         {
             Name = nameof(Result),
             Value = Result,
             Type = StateVariable.StateType.Output
         }
     });
 }
Example #4
0
 public override IEnumerable <StateVariable> GetState()
 {
     return(new[] {
         new StateVariable
         {
             Name = nameof(OutputPath),
             Value = OutputPath,
             Type = StateVariable.StateType.Output
         },
         new StateVariable
         {
             Name = nameof(Overwrite),
             Value = Overwrite.ToString(),
             Type = StateVariable.StateType.Input
         },
         new StateVariable
         {
             Name = nameof(AppendTop),
             Value = AppendTop.ToString(),
             Type = StateVariable.StateType.Input
         },
         new StateVariable
         {
             Name = nameof(AppendBottom),
             Value = AppendBottom.ToString(),
             Type = StateVariable.StateType.Input
         },
         new StateVariable
         {
             Name = nameof(FileContents),
             Value = FileContents,
             Type = StateVariable.StateType.InputOutput
         },
         new StateVariable
         {
             Name = nameof(Username),
             Value = Username,
             Type = StateVariable.StateType.Input
         },
         new StateVariable
         {
             Name = nameof(PrivateKeyFile),
             Value = PrivateKeyFile,
             Type = StateVariable.StateType.Input
         },
         new StateVariable
         {
             Name = nameof(Result),
             Value = Result,
             Type = StateVariable.StateType.Output
         }
     });
 }
Example #5
0
 public override IEnumerable <StateVariable> GetState()
 {
     return(new[] {
         new StateVariable
         {
             Name = "InputPath",
             Type = StateVariable.StateType.Input,
             Value = InputPath
         },
         new StateVariable
         {
             Name = "Username",
             Type = StateVariable.StateType.Input,
             Value = Username
         },
         new StateVariable
         {
             Name = "PrivateKeyFile",
             Type = StateVariable.StateType.Input,
             Value = PrivateKeyFile
         },
         new StateVariable
         {
             Name = "OutputPath",
             Type = StateVariable.StateType.Output,
             Value = OutputPath
         },
         new StateVariable
         {
             Name = "DestinationUsername",
             Type = StateVariable.StateType.Input,
             Value = DestinationUsername
         },
         new StateVariable
         {
             Name = "DestinationPrivateKeyFile",
             Type = StateVariable.StateType.Input,
             Value = DestinationPrivateKeyFile
         },
         new StateVariable
         {
             Name = "Overwrite",
             Type = StateVariable.StateType.Input,
             Value = Overwrite.ToString()
         },
         new StateVariable
         {
             Name = "Result",
             Type = StateVariable.StateType.Output,
             Value = Result
         }
     });
 }
Example #6
0
        public static void CreateEmptyFile(String filename, Overwrite overwrite)
        {
            filename.Name("filename").NotNullEmptyOrOnlyWhitespace();

            if ((overwrite == Overwrite.Yes) || !File.Exists(filename))
            {
                using (var fs = File.Create(filename))
                {
                    /* Create an empty file. */
                }
            }
        }
        /// <summary>
        /// Generates the steps required to ensure the database.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public IEnumerable <SqlDeploymentAction> Compile(SqlDeploymentCompileContext context)
        {
            // creates the database if it does not exist
            yield return(new SqlDeploymentCreateDatabaseAction(
                             context.InstanceName,
                             Name.Expand(context),
                             DefaultDataFilePath?.Expand(context),
                             DefaultLogFilePath?.Expand(context),
                             Overwrite?.Expand <bool>(context) ?? false));

            // potentially deploy a DAC package
            if (Package != null)
            {
                foreach (var s in Package.Compile(context, Name.Expand(context)))
                {
                    yield return(s);
                }
            }

            // potentially alter the owner
            if (Owner != null)
            {
                yield return(new SqlDeploymentDatabaseOwnerAction(context.InstanceName, Name.Expand(context), Owner?.Expand(context)));
            }

            // apply any extended properties
            foreach (var extendedProperty in ExtendedProperties)
            {
                foreach (var s in extendedProperty.Compile(context, Name.Expand(context)))
                {
                    yield return(s);
                }
            }

            // apply any publications
            foreach (var publication in Publications)
            {
                foreach (var s in publication.Compile(context, Name.Expand(context)))
                {
                    yield return(s);
                }
            }

            // apply any subscriptions
            foreach (var subscription in Subscriptions)
            {
                foreach (var s in subscription.Compile(context, Name.Expand(context)))
                {
                    yield return(s);
                }
            }
        }
        public async Task StopProposalsAsync()
        {
            var photoBot = Service.PhotoBot;

            var winnerProposal = photoBot.Config.Proposals
                                 .OrderBy(element => Guid.NewGuid())
                                 .ThenByDescending(element => element.Score)
                                 .First();

            var proposalsChannel = photoBot.SocketGuild.GetTextChannel(photoBot.Config.CurrentProposalsChannelId);
            var winnersChannel   = photoBot.SocketGuild.GetTextChannel(photoBot.Config.WinnerChannelId);

            using var client = new WebClient();
            await client.DownloadFileTaskAsync(new Uri(winnerProposal.ImageUrl), "winner_proposal.png");

            try
            {
                await winnersChannel.SendFileAsync("winner_proposal.png", $"Thema: {winnerProposal.Topic}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            var users = photoBot.Config.PhotoUserIds;

            photoBot.Config.UserIdToPhotoChannelId = new Dictionary <ulong, ulong>();

            foreach (var userId in users)
            {
                var user         = photoBot.SocketGuild.GetUser(userId);
                var photoChannel = await ChannelCreator.CreateChannelAsync($"photo-{user.Username}", photoBot.Config.PhotoCategoryId);

                var denyAllPermissions = new Overwrite(photoBot.Config.EveryoneRoleId, PermissionTarget.Role,
                                                       OverwritePermissions.DenyAll(photoChannel));

                var allowUserPermissions = new Overwrite(userId, PermissionTarget.User,
                                                         OverwritePermissions.AllowAll(photoChannel));

                var permissions = new List <Overwrite> {
                    denyAllPermissions, allowUserPermissions
                };

                await photoChannel.ModifyAsync(prop => prop.PermissionOverwrites = permissions);

                photoBot.Config.UserIdToPhotoChannelId.Add(userId, photoChannel.Id);
            }

            await Archiver.ArchiveChannelAsync(proposalsChannel);

            await PhotoConfig.SaveAsync();
        }
Example #9
0
        /// <summary>
        /// Transmits a block of data
        /// </summary>
        /// <param name="startIndex">Start index within the byte array</param>
        /// <param name="count">The number of bytes to send</param>
        /// <param name="final">Indicates whether this is the final packet</param>
        private void Transmit(long startIndex, long count, bool final)
        {
            string content = string.Empty;
            string mode    = "new";
            string url     = WebserviceURL + "/" + WebserviceMethod;
            Comms  helper  = null;

            if (_current.DataStream != null)
            {
                byte[] buffer = new byte[count];

                _current.DataStream.Read(buffer, 0, (int)count);
                content = Convert.ToBase64String(buffer);
            }
            else
            {
                content = Convert.ToBase64String(_current.Data, (int)startIndex, (int)count);
            }

            if (startIndex > 0)
            {
                mode = "append";
            }

            if (_current.TargetFileName.Length > 0)
            {
                helper = new Comms(new Uri(url), "POST", false,
                                   new KeyValuePair <string, string>("id", HttpUtility.UrlEncode(_current.ID)),
                                   new KeyValuePair <string, string>("mode", HttpUtility.UrlEncode(mode)),
                                   new KeyValuePair <string, string>("path", HttpUtility.UrlEncode(_current.TargetPath)),
                                   new KeyValuePair <string, string>("name", HttpUtility.UrlEncode(_current.FileName)),
                                   new KeyValuePair <string, string>("targetname", HttpUtility.UrlEncode(_current.TargetFileName)),
                                   new KeyValuePair <string, string>("filedata", HttpUtility.UrlEncode(content)),
                                   new KeyValuePair <string, string>("overwrite", Overwrite.ToString()),
                                   new KeyValuePair <string, string>("tag", HttpUtility.UrlEncode(_current.Tag)),
                                   new KeyValuePair <string, string>("final", final.ToString()));
            }
            else
            {
                helper = new Comms(new Uri(url), "POST", false,
                                   new KeyValuePair <string, string>("id", HttpUtility.UrlEncode(_current.ID)),
                                   new KeyValuePair <string, string>("mode", HttpUtility.UrlEncode(mode)),
                                   new KeyValuePair <string, string>("path", HttpUtility.UrlEncode(_current.TargetPath)),
                                   new KeyValuePair <string, string>("name", HttpUtility.UrlEncode(_current.FileName)),
                                   new KeyValuePair <string, string>("filedata", HttpUtility.UrlEncode(content)),
                                   new KeyValuePair <string, string>("overwrite", Overwrite.ToString()),
                                   new KeyValuePair <string, string>("tag", HttpUtility.UrlEncode(_current.Tag)),
                                   new KeyValuePair <string, string>("final", final.ToString()));
            }
            helper.ResponseComplete += new HttpResponseCompleteEventHandler(this.CommandComplete);
            helper.Execute();
        }
Example #10
0
        /// <summary>
        /// Extracts a single file from a zip file
        /// </summary>
        /// <param name="file">
        /// The zip entry we are pulling the file from
        /// </param>
        /// <param name="destinationPath">
        /// The root of where the file is going
        /// </param>
        /// <param name="overwriteMethod">
        /// Specifies how we are going to handle an existing file.
        /// The default is Overwrite.IfNewer.
        /// </param>
        private static void ExtractToFile(ZipArchiveEntry file,
                                          string destinationPath,
                                          Overwrite overwriteMethod = Overwrite.IfNewer)
        {
            // Gets the complete path for the destination file, including any
            // relative paths that were in the zip file
            var destinationFileName = Path.Combine(destinationPath, file.FullName);

            // Gets just the new path, minus the file name so we can create the
            // directory if it does not exist
            var destinationFilePath = Path.GetDirectoryName(destinationFileName);

            // Creates the directory (if it doesn't exist) for the new path
            Directory.CreateDirectory(destinationFilePath);

            // The zipfile is a directory.
            if (file.ToString().EndsWith("\\"))
            {
                return;
            }

            // Determines what to do with the file based upon the
            // method of overwriting chosen
            switch (overwriteMethod)
            {
            case Overwrite.Always:
                // Just put the file in and overwrite anything that is found
                file.ExtractToFile(destinationFileName, true);
                break;

            case Overwrite.IfNewer:
                // Checks to see if the file exists, and if so, if it should
                // be overwritten
                if (!File.Exists(destinationFileName) || File.GetLastWriteTime(destinationFileName) < file.LastWriteTime)
                {
                    file.ExtractToFile(destinationFileName, true);
                }
                break;

            case Overwrite.Never:
                // Put the file in if it is new but ignores the
                // file if it already exists
                if (!File.Exists(destinationFileName))
                {
                    file.ExtractToFile(destinationFileName);
                }
                break;

            default:
                break;
            }
        }
Example #11
0
        // -------------------------------------------------------------------------------------------
        // -------------------------------------------------------------------------------------------
        // METHODS
        // -------------------------------------------------------------------------------------------
        // -------------------------------------------------------------------------------------------

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="time"></param>
        /// <param name="useFrames"></param>
        public Tween(object target, int time, bool useFrames)
        {
            _duration   = time;
            _elapsed    = 0;
            _delay      = 0;
            _numRepeats = 0;
            _target     = target;
            _useFrames  = useFrames;
            _state      = TweenState.START;
            _easing     = Easing.QuadEaseOut;
            _overwrite  = Overwrite.OVERWRITE_DEFAULT;
            _procedures = new List <ITweenProcedure>();
        }
Example #12
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = base.GetHashCode();
         hashCode = (hashCode * 397) ^ (ServerInputPathFrom != null ? ServerInputPathFrom.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ServerInputPathTo != null ? ServerInputPathTo.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ Overwrite.GetHashCode();
         hashCode = (hashCode * 397) ^ (SharepointSource != null ? SharepointSource.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ SharepointServerResourceId.GetHashCode();
         return(hashCode);
     }
 }
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = base.GetHashCode();
         hashCode = (hashCode * 397) ^ (DestinationPassword != null ? DestinationPassword.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ Overwrite.GetHashCode();
         hashCode = (hashCode * 397) ^ (InputPath != null ? InputPath.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (OutputPath != null ? OutputPath.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (DestinationUsername != null ? DestinationUsername.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (DestinationPrivateKeyFile != null ? DestinationPrivateKeyFile.GetHashCode() : 0);
         return(hashCode);
     }
 }
 /// <summary>
 /// Unzips the specified file to the given folder in a safe
 /// manner.  This plans for missing paths and existing files
 /// and handles them gracefully.
 /// </summary>
 /// <param name="sourceArchiveFileName">
 /// The name of the zip file to be extracted
 /// </param>
 /// <param name="destinationDirectoryName">
 /// The directory to extract the zip file to
 /// </param>
 /// <param name="overwriteMethod">
 /// Specifies how we are going to handle an existing file.
 /// The default is IfNewer.
 /// </param>
 public static void ImprovedExtractToDirectory(string sourceArchiveFileName,
                                               string destinationDirectoryName,
                                               Overwrite overwriteMethod = Overwrite.IfNewer)
 {
     //Opens the zip file up to be read
     using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
     {
         //Loops through each file in the zip file
         foreach (ZipArchiveEntry file in archive.Entries)
         {
             ImprovedExtractToFile(file, destinationDirectoryName, overwriteMethod);
         }
     }
 }
Example #15
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = base.GetHashCode();
         hashCode = (hashCode * 397) ^ Append.GetHashCode();
         hashCode = (hashCode * 397) ^ (FileContents != null ? FileContents.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (OutputPath != null ? OutputPath.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ Overwrite.GetHashCode();
         hashCode = (hashCode * 397) ^ AppendTop.GetHashCode();
         hashCode = (hashCode * 397) ^ AppendBottom.GetHashCode();
         return(hashCode);
     }
 }
Example #16
0
        public async Task UnMuteAsync([CheckUserHierarchy][CheckBotHierarchy]
                                      SocketGuildUser user, [Remainder] string reason = null)
        {
            var roleName = $"{Context.Client.CurrentUser.Username}-Muted";
            var role     = Context.Guild.Roles.All(x => x.Name != roleName)
                ? Context.Guild.GetRole(
                (await Context.Guild.CreateRoleAsync(roleName,
                                                     new GuildPermissions(sendMessages: false))).Id)
                : Context.Guild.Roles.FirstOrDefault(x => x.Name == roleName);

            if (!user.Roles.Contains(role))
            {
                await ReplyEmbedAsync("Not Muted", $"{user.Mention} is already unmuted");

                return;
            }

            await user.RemoveRoleAsync(role);

            var logItem = _serverService.AddLogItem(Server, ActionType.Unmute, reason, Context.User.Id, user.Id);
            await _logService.SendLog(Context.Guild, "User Unmuted",
                                      $"Responsible User ❯ {Context.User.Mention}\nUser ❯ {user.Mention} ({user.Nickname ?? user.Username}#{user.Discriminator})\nReason ❯ {reason ?? $"none, {Context.User.Mention} use {$"reason {logItem.LogId} <reason>".InlineCode()}"}\nId ❯ {logItem.LogId}",
                                      server : Server);

            await ReplyEmbedAsync("User Unmuted",
                                  $"Responsible User ❯ {Context.User.Mention}\nReason ❯ {reason ?? $"none, {Context.User.Mention} use {$"reason {logItem.LogId} <reason>".InlineCode()}"}");

            try
            {
                await user.SendMessageAsync(embed : NormalizeEmbed("You Got Unmuted",
                                                                   $"Responsible User ❯ {Context.User.Mention} ({(Context.User as IGuildUser)?.Nickname ?? Context.User.Username})")
                                            .Build());
            }
            catch (Exception)
            {
                // ignored
            }

            var overwritePermissions = new OverwritePermissions(sendMessages: PermValue.Deny,
                                                                addReactions: PermValue.Deny, speak: PermValue.Deny);
            var overwrite = new Overwrite(role.Id, PermissionTarget.Role, overwritePermissions);

            foreach (var channel in Context.Guild.Channels)
            {
                if (!channel.PermissionOverwrites.Contains(overwrite))
                {
                    await channel.AddPermissionOverwriteAsync(role, overwritePermissions);
                }
            }
        }
Example #17
0
 /// <summary>
 /// Unzips the specified file to the given folder in a safe
 /// manner.  This plans for missing paths and existing files
 /// and handles them gracefully.
 /// </summary>
 /// <param name="sourceArchiveFileName">
 /// The name of the zip file to be extracted
 /// </param>
 /// <param name="destinationDirectoryName">
 /// The directory to extract the zip file to
 /// </param>
 /// <param name="overwriteMethod">
 /// Specifies how we are going to handle an existing file.
 /// The default is IfNewer.
 /// </param>
 public static void ExtractToDirectory(string sourceArchiveFileName,
                                       string destinationDirectoryName,
                                       Overwrite overwriteMethod = Overwrite.IfNewer)
 {
     //Opens the zip file up to be read
     using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
     {
         //Loops through each file in the zip file
         foreach (ZipArchiveEntry file in archive.Entries)
         {
             ExtractToFile(file, destinationDirectoryName, overwriteMethod);
         }
     }
 }
Example #18
0
        /// <summary>
        /// Extract the contents of a zip file.
        /// </summary>
        /// <param name="zipFileName">The zip file to extract from.</param>
        /// <param name="targetDirectory">The directory to save extracted information in.</param>
        /// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
        /// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
        /// <param name="fileFilter">A filter to apply to files.</param>
        /// <param name="directoryFilter">A filter to apply to directories.</param>
        /// <param name="restoreDateTime">Flag indicating wether to restore the date and time for extracted files.</param>
        public void ExtractZip(string zipFileName, string targetDirectory,
                               Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate,
                               string fileFilter, string directoryFilter, bool restoreDateTime)
        {
            if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null))
            {
                throw new ArgumentNullException("confirmDelegate");
            }

            continueRunning_          = true;
            overwrite_                = overwrite;
            confirmDelegate_          = confirmDelegate;
            targetDirectory_          = targetDirectory;
            fileFilter_               = new NameFilter(fileFilter);
            directoryFilter_          = new NameFilter(directoryFilter);
            restoreDateTimeOnExtract_ = restoreDateTime;

            using (zipFile_ = new ZipFile(zipFileName)) {
#if !NETCF_1_0
                if (password_ != null)
                {
                    zipFile_.Password = password_;
                }
#endif

                System.Collections.IEnumerator enumerator = zipFile_.GetEnumerator();
                while (continueRunning_ && enumerator.MoveNext())
                {
                    ZipEntry entry = (ZipEntry)enumerator.Current;
                    if (entry.IsFile)
                    {
                        //if ( directoryFilter_.IsMatch(Path.GetDirectoryName(entry.Name)) && fileFilter_.IsMatch(entry.Name) ) {
                        ExtractEntry(entry);
                        //}
                    }
                    else if (entry.IsDirectory)
                    {
                        if (directoryFilter_.IsMatch(entry.Name) && CreateEmptyDirectories)
                        {
                            ExtractEntry(entry);
                        }
                    }
                    else
                    {
                        // Do nothing for volume labels etc...
                    }
                }
            }
        }
Example #19
0
 public bool AllowOverwrite()
 {
     if (String.IsNullOrWhiteSpace(Overwrite))
     {
         return(false);
     }
     else if (Overwrite.Equals("true", StringComparison.InvariantCultureIgnoreCase))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Example #20
0
        /// <summary>
        /// Exatract the contents of a zip file.
        /// </summary>
        /// <param name="zipFileName">The zip file to extract from.</param>
        /// <param name="targetDirectory">The directory to save extracted information in.</param>
        /// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
        /// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
        /// <param name="fileFilter">A filter to apply to files.</param>
        /// <param name="directoryFilter">A filter to apply to directories.</param>
        public void ExtractZip(string sSourceDir, string sDestinationDir,
                               Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate,
                               string fileFilter, string directoryFilter)
        {
            string zipFileName = sSourceDir.Substring(sSourceDir.LastIndexOf("\\") + 1, sSourceDir.Length - sSourceDir.LastIndexOf("\\") - 1);

            //For Password
            string[] Val    = zipFileName.Split('_');
            string   UniID  = Val[0];
            string   InstID = Val[1];

            string sPassword = UniID + "" + InstID;

            if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null))
            {
                throw new ArgumentNullException("confirmDelegate");
            }
            this.overwrite       = overwrite;
            this.confirmDelegate = confirmDelegate;
            this.targetDirectory = sDestinationDir;
            this.fileFilter      = new NameFilter(fileFilter);
            this.directoryFilter = new NameFilter(directoryFilter);

            inputStream = new ZipInputStream(File.OpenRead(sSourceDir));
            //Password for Zip File
            inputStream.Password = sPassword;
            try
            {
                if (password != null)
                {
                    inputStream.Password = password;
                }

                ZipEntry entry;
                while ((entry = inputStream.GetNextEntry()) != null)
                {
                    if (this.directoryFilter.IsMatch(Path.GetDirectoryName(entry.Name)) && this.fileFilter.IsMatch(entry.Name))
                    {
                        ExtractEntry(entry);
                    }
                }
            }
            finally
            {
                inputStream.Close();
            }
        }
Example #21
0
        public override void Install()
        {
            Console.WriteLine("");
            Console.WriteLine("Installing csAnt...");
            Console.WriteLine("");
            Console.WriteLine("Destination:");
            Console.WriteLine("  " + DestinationPath);
            Console.WriteLine("");
            Console.WriteLine("Clear: " + Clear.ToString());
            Console.WriteLine("Overwrite: " + Overwrite.ToString());
            Console.WriteLine("");
            Console.WriteLine("Clone: " + Clone.ToString());
            Console.WriteLine("Clone source:");
            Console.WriteLine("  " + CloneSource);
            Console.WriteLine("");
            Console.WriteLine("Import: " + Import.ToString());
            Console.WriteLine("Import path: ");
            Console.WriteLine("  " + ImportPath);

            if (Clear)
            {
                ClearFiles();
            }

            Retriever.Retrieve(PackageName, Version, Status);

            Unpacker.Unpack(
                DestinationPath, // TODO: Make this configurable
                PackageName,
                Version,
                Overwrite
                );

            if (Import)
            {
                ImportFiles();
            }

            if (Clone)
            {
                CloneFiles();
            }

            EnsureNode();

            RaiseInstallEvent();
        }
Example #22
0
        private IEnumerable <IUser> UsersWithIncorrectPermissions(
            OverwritePermissions correctPerms,
            ulong channelId,
            IEnumerable <IUser> users)
        {
            SocketTextChannel channel = _client.Guilds.SelectMany(g => g.TextChannels).FirstOrDefault(c => c.Id == channelId);

            return(users.Where(user =>
            {
                if (channel.PermissionOverwrites.All(overwrite => overwrite.TargetId != user.Id))
                {
                    return true;
                }
                Overwrite playerOverwrite = channel.PermissionOverwrites.First(overwrite => overwrite.TargetId == user.Id);
                return !ArePermissionsEqual(playerOverwrite.Permissions, correctPerms);
            }));
        }
        protected override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            foreach (string fullPath in ResolvePaths(_paths, _shouldExpandWildcards))
            {
                byte[] content = File.ReadAllBytes(fullPath);

                if (Async.ToBool() && CrmVersionManager.IsSupported(CrmVersion.CRM2015_RTM))
                {
                    ExecuteAction(fullPath, delegate
                    {
                        Guid importjobid = Guid.NewGuid();
                        OrganizationResponse response = _repository.ExecuteAsync("ImportSolution", new Hashtable()
                        {
                            { "CustomizationFile", content },
                            { "ImportJobId", importjobid },
                            { "ConvertToManaged", ConvertToManaged.ToBool() },
                            { "OverwriteUnmanagedCustomizations", Overwrite.ToBool() },
                            { "PublishWorkflows", PublishWorkflows.ToBool() },
                            { "SkipProductUpdateDependencies", SkipDependencies.ToBool() }
                        });

                        WriteObject(_repository.Get("asyncoperation", (Guid)response.Results["AsyncJobId"]));
                    });
                }
                else
                {
                    ExecuteAction(fullPath, delegate
                    {
                        Guid importjobid = Guid.NewGuid();
                        _repository.Execute("ImportSolution", new Hashtable()
                        {
                            { "CustomizationFile", content },
                            { "ImportJobId", importjobid },
                            { "ConvertToManaged", ConvertToManaged.ToBool() },
                            { "OverwriteUnmanagedCustomizations", Overwrite.ToBool() },
                            { "PublishWorkflows", PublishWorkflows.ToBool() },
                            { "SkipProductUpdateDependencies", SkipDependencies.ToBool() }
                        });

                        WriteObject(_repository.Get("importjob", importjobid));
                    });
                }
            }
        }
        /// <summary>
        /// Safely extracts a single file from a zip file
        /// </summary>
        /// <param name="file">
        /// The zip entry we are pulling the file from
        /// </param>
        /// <param name="destinationPath">
        /// The root of where the file is going
        /// </param>
        /// <param name="overwriteMethod">
        /// Specifies how we are going to handle an existing file.
        /// The default is Overwrite.IfNewer.
        /// </param>
        public static void ImprovedExtractToFile(ZipArchiveEntry file,
                                                 string destinationPath,
                                                 Overwrite overwriteMethod = Overwrite.IfNewer)
        {
            //Gets the complete path for the destination file, including any
            //relative paths that were in the zip file
            string destinationFileName = Path.Combine(destinationPath, file.FullName);

            //Gets just the new path, minus the file name so we can create the
            //directory if it does not exist
            string destinationFilePath = Path.GetDirectoryName(destinationFileName);

            //Creates the directory (if it doesn't exist) for the new path
            Directory.CreateDirectory(destinationFilePath);

            //Determines what to do with the file based upon the
            //method of overwriting chosen
            switch (overwriteMethod)
            {
                case Overwrite.Always:
                    //Just put the file in and overwrite anything that is found
                    file.ExtractToFile(destinationFileName, true);
                    break;
                case Overwrite.IfNewer:
                    //Checks to see if the file exists, and if so, if it should
                    //be overwritten
                    if (!File.Exists(destinationFileName) || File.GetLastWriteTime(destinationFileName) < file.LastWriteTime)
                    {
                        //Either the file didn't exist or this file is newer, so
                        //we will extract it and overwrite any existing file
                        file.ExtractToFile(destinationFileName, true);
                    }
                    break;
                case Overwrite.Never:
                    //Put the file in if it is new but ignores the 
                    //file if it already exists
                    if (!File.Exists(destinationFileName))
                    {
                        file.ExtractToFile(destinationFileName);
                    }
                    break;
                default:
                    break;
            }
        }
Example #25
0
 public override void Parse(string arg)
 {
     if (arg.StartsWith("--data=", StringComparison.InvariantCultureIgnoreCase))
     {
         this.dataAsString = arg.Substring("--data=".Length);
     }
     else if (arg.Equals("--overwrite:no", StringComparison.InvariantCultureIgnoreCase))
     {
         this.overwrite = Overwrite.No;
     }
     else if (arg.Equals("--overwrite:prompt", StringComparison.InvariantCultureIgnoreCase))
     {
         this.overwrite = Overwrite.Prompt;
     }
     else if (arg.Equals("--overwrite:yes", StringComparison.InvariantCultureIgnoreCase))
     {
         this.overwrite = Overwrite.Yes;
     }
     else if (arg.StartsWith("--type=", StringComparison.InvariantCultureIgnoreCase))
     {
         string argValue = arg.Substring("--type=".Length);
         try
         {
             this.dataType = AppDataType.ToAppDataType(argValue, supportedAppDataTypes);
         }
         catch (NotSupportedException)
         {
             FatalError(String.Format("Unknown type ({0}); use 'APPDATA {1} --help' for usage", arg, GetCommandName()));
         }
     }
     else if (arg.StartsWith("--value=", StringComparison.InvariantCultureIgnoreCase))
     {
         string argValue = arg.Substring("--value=".Length);
         if (argValue.IsEmpty())
         {
             FatalError(String.Format("Invalid key ({0}); use 'APPDATA {1} --help' for usage", arg, GetCommandName()));
         }
         this.valueKey = argValue;
     }
     else
     {
         base.Parse(arg);
     }
 }
Example #26
0
        //static string GetFileNameFromUrl(string url)
        //{
        //    Uri uri;
        //    if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
        //        uri = new Uri(url);
        //    return System.IO.Path.GetFileName(uri.LocalPath);
        //}
        protected async override Task <object> ExecuteAsync(AsyncCodeActivityContext context)
        {
            var username       = Username.Get(context);
            var password       = Password.Get(context);
            var url            = URL.Get(context);
            var filepath       = LocalPath.Get(context);
            var overwrite      = Overwrite.Get(context);
            var ignoresecurity = IgnoreSecurity.Get(context);

            filepath = Environment.ExpandEnvironmentVariables(filepath);
            // if(string.IsNullOrEmpty(filename)) filename = "temp."
            if (System.IO.File.Exists(filepath) && !overwrite)
            {
                return(42);
            }
            using (var client = new System.Net.WebClient())
            {
                var Expect100Continue = System.Net.ServicePointManager.Expect100Continue;
                var SecurityProtocol  = System.Net.ServicePointManager.SecurityProtocol;
                if (ignoresecurity)
                {
                    System.Net.ServicePointManager.Expect100Continue = true;
                    System.Net.ServicePointManager.SecurityProtocol  = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Ssl3;
                }
                if (!string.IsNullOrEmpty(username) || !string.IsNullOrEmpty(password))
                {
                    client.Credentials = new System.Net.NetworkCredential(username, password);
                }
                var dir = System.IO.Path.GetDirectoryName(filepath);
                if (!System.IO.Directory.Exists(dir))
                {
                    System.IO.Directory.CreateDirectory(dir);
                }
                await client.DownloadFileTaskAsync(new Uri(url), filepath);

                if (ignoresecurity)
                {
                    System.Net.ServicePointManager.Expect100Continue = Expect100Continue;
                    System.Net.ServicePointManager.SecurityProtocol  = SecurityProtocol;
                }
            }
            return(42);
        }
Example #27
0
        /// <summary>
        /// Extract the contents of a zip file held in a stream.
        /// </summary>
        /// <param name="inputStream">The seekable input stream containing the zip to extract from.</param>
        /// <param name="targetDirectory">The directory to save extracted information in.</param>
        /// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
        /// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
        /// <param name="fileFilter">A filter to apply to files.</param>
        /// <param name="directoryFilter">A filter to apply to directories.</param>
        /// <param name="restoreDateTime">Flag indicating whether to restore the date and time for extracted files.</param>
        /// <param name="isStreamOwner">Flag indicating whether the inputStream will be closed by this method.</param>
        public void ExtractZip(Stream inputStream, string targetDirectory,
                               Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate,
                               string fileFilter, string directoryFilter, bool restoreDateTime,
                               bool isStreamOwner)
        {
            if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null))
            {
                throw new ArgumentNullException("confirmDelegate");
            }

            continueRunning_      = true;
            overwrite_            = overwrite;
            confirmDelegate_      = confirmDelegate;
            extractNameTransform_ = new WindowsNameTransform(targetDirectory);

            fileFilter_               = new NameFilter(fileFilter);
            directoryFilter_          = new NameFilter(directoryFilter);
            restoreDateTimeOnExtract_ = restoreDateTime;

            using (zipFile_ = new ZipFile(inputStream))
            {
                                #if !NETCF_1_0
                if (password_ != null)
                {
                    zipFile_.Password = password_;
                }
                                #endif
                zipFile_.IsStreamOwner = isStreamOwner;
                extractEnum_           = zipFile_.GetEnumerator();
                totalCount_            = 0;
                while (continueRunning_ && extractEnum_.MoveNext())
                {
                    ZipEntry entry = (ZipEntry)extractEnum_.Current;
                    totalCount_ += entry.Size;
                }
                extractEnum_.Reset();

                doneCount_ = 0;
                ExtractUpdate();
            }
        }
Example #28
0
 /// <summary>
 /// Unzips the specified file to the given folder in a safe
 /// manner.  This plans for missing paths and existing items
 /// and handles them gracefully.
 /// </summary>
 /// <param name="sourceZipFilePath">
 /// The name of the zip file to be extracted
 /// </param>
 /// <param name="destinationDirectoryName">
 /// The directory to extract the zip file to
 /// </param>
 /// <param name="overwriteMethod">
 /// Specifies how we are going to handle an existing file.
 /// The default is IfNewer.
 /// </param>
 public static void Uncompress(string sourceZipFilePath,
                               string destinationDirectoryName,
                               Overwrite overwriteMethod = Overwrite.IfNewer)
 {
     try
     {
         // Opens the zip file up to be read
         using (var archive = ZipFile.OpenRead(sourceZipFilePath))
         {
             // Loops through each file in the zip file
             foreach (var file in archive.Entries)
             {
                 ExtractToFile(file, destinationDirectoryName, overwriteMethod);
             }
         }
     }
     catch (Exception ex)
     {
         throw new Exception("Error un-compressing archive: " + RecurseExceptionText(ex));
     }
 }
Example #29
0
 public void ExtractZip(Stream inputStream, string targetDirectory, Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, string fileFilter, string directoryFilter, bool restoreDateTime, bool isStreamOwner)
 {
     if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null))
     {
         throw new ArgumentNullException("confirmDelegate");
     }
     this.continueRunning_          = true;
     this.overwrite_                = overwrite;
     this.confirmDelegate_          = confirmDelegate;
     this.extractNameTransform_     = new WindowsNameTransform(targetDirectory);
     this.fileFilter_               = new NameFilter(fileFilter);
     this.directoryFilter_          = new NameFilter(directoryFilter);
     this.restoreDateTimeOnExtract_ = restoreDateTime;
     using (this.zipFile_ = new ZipFile(inputStream))
     {
         if (this.password_ != null)
         {
             this.zipFile_.Password = this.password_;
         }
         this.zipFile_.IsStreamOwner = isStreamOwner;
         IEnumerator enumerator = this.zipFile_.GetEnumerator();
         while (this.continueRunning_ && enumerator.MoveNext())
         {
             ZipEntry current = (ZipEntry)enumerator.Current;
             if (current.IsFile)
             {
                 if (!this.directoryFilter_.IsMatch(Path.GetDirectoryName(current.Name)) || !this.fileFilter_.IsMatch(current.Name))
                 {
                     continue;
                 }
                 this.ExtractEntry(current);
                 continue;
             }
             if (current.IsDirectory && (this.directoryFilter_.IsMatch(current.Name) && this.CreateEmptyDirectories))
             {
                 this.ExtractEntry(current);
             }
         }
     }
 }
Example #30
0
        public List <KeyValuePair <string, string> > ToKeyValuePairs()
        {
            var result = new List <KeyValuePair <string, string> >(10);

            // leave out null values, but string.Empty is preserved
            if (FileName != null)
            {
                result.Add("FileName", FileName);
            }

            if (ContentId > 0)
            {
                result.Add("ContentId", ContentId.ToString());
            }

            if (ContentType != null)
            {
                result.Add("ContentType", ContentType);
            }
            if (PropertyName != null)
            {
                result.Add("PropertyName", PropertyName);
            }

            result.Add("UseChunk", UseChunk.ToString());
            result.Add("Overwrite", Overwrite.ToString());
            result.Add("FileLength", FileLength.ToString());

            if (ChunkToken != null)
            {
                result.Add("ChunkToken", ChunkToken);
            }

            if (FileText != null)
            {
                result.Add("FileText", FileText);
            }

            return(result);
        }
Example #31
0
 public void ExtractZip(Stream inputStream, string targetDirectory, Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, string fileFilter, string directoryFilter, bool restoreDateTime, bool isStreamOwner)
 {
     //IL_000c: Unknown result type (might be due to invalid IL or missing references)
     if (overwrite == Overwrite.Prompt && confirmDelegate == null)
     {
         throw new ArgumentNullException("confirmDelegate");
     }
     continueRunning_          = true;
     overwrite_                = overwrite;
     confirmDelegate_          = confirmDelegate;
     extractNameTransform_     = new WindowsNameTransform(targetDirectory);
     fileFilter_               = new NameFilter(fileFilter);
     directoryFilter_          = new NameFilter(directoryFilter);
     restoreDateTimeOnExtract_ = restoreDateTime;
     using (zipFile_ = new ZipFile(inputStream))
     {
         if (password_ != null)
         {
             zipFile_.Password = password_;
         }
         zipFile_.IsStreamOwner = isStreamOwner;
         global::System.Collections.IEnumerator enumerator = zipFile_.GetEnumerator();
         while (continueRunning_ && enumerator.MoveNext())
         {
             ZipEntry zipEntry = (ZipEntry)enumerator.get_Current();
             if (zipEntry.IsFile)
             {
                 if (directoryFilter_.IsMatch(Path.GetDirectoryName(zipEntry.Name)) && fileFilter_.IsMatch(zipEntry.Name))
                 {
                     ExtractEntry(zipEntry);
                 }
             }
             else if (zipEntry.IsDirectory && directoryFilter_.IsMatch(zipEntry.Name) && CreateEmptyDirectories)
             {
                 ExtractEntry(zipEntry);
             }
         }
     }
 }
Example #32
0
 public void ExtractZip(Stream inputStream, string targetDirectory, Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, string fileFilter, string directoryFilter, bool restoreDateTime, bool isStreamOwner)
 {
     if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null))
     {
         throw new ArgumentNullException(nameof(confirmDelegate));
     }
     _continueRunning          = true;
     _overwrite                = overwrite;
     _confirmDelegate          = confirmDelegate;
     _extractNameTransform     = new WindowsNameTransform(targetDirectory);
     _fileFilter               = new NameFilter(fileFilter);
     _directoryFilter          = new NameFilter(directoryFilter);
     _restoreDateTimeOnExtract = restoreDateTime;
     using (_zipFile = new ZipFile(inputStream))
     {
         if (_password != null)
         {
             _zipFile.Password = _password;
         }
         _zipFile.IsStreamOwner = isStreamOwner;
         IEnumerator enumerator = _zipFile.GetEnumerator();
         while (_continueRunning && enumerator.MoveNext())
         {
             ZipEntry current = (ZipEntry)enumerator.Current;
             if (current.IsFile)
             {
                 if (_directoryFilter.IsMatch(Path.GetDirectoryName(current.Name)) && _fileFilter.IsMatch(current.Name))
                 {
                     ExtractEntry(current);
                 }
             }
             else if ((current.IsDirectory && _directoryFilter.IsMatch(current.Name)) && CreateEmptyDirectories)
             {
                 ExtractEntry(current);
             }
         }
     }
 }
		/// <summary>
		/// Extract the contents of a zip file.
		/// </summary>
		/// <param name="zipFileName">The zip file to extract from.</param>
		/// <param name="targetDirectory">The directory to save extracted information in.</param>
		/// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
		/// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
		/// <param name="fileFilter">A filter to apply to files.</param>
		/// <param name="directoryFilter">A filter to apply to directories.</param>
		/// <param name="restoreDateTime">Flag indicating whether to restore the date and time for extracted files.</param>
		public void ExtractZip(string zipFileName, string targetDirectory, Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, string fileFilter, string directoryFilter, bool restoreDateTime)
		{
		    Stream inputStream;
		    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
		    {
		        inputStream = store.OpenFile(zipFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
		    }
		    ExtractZip(inputStream, targetDirectory, overwrite, confirmDelegate, fileFilter, directoryFilter, restoreDateTime, true);
		}
Example #34
0
 public static void Move(FileSet files, DirectoryPath toDir, Overwrite overwrite, bool flatten = false, bool failOnError = true)
 {
     new MoveTask(files) { ToDir = toDir, Overwrite = overwrite, Flatten = flatten, FailOnError = failOnError }.Execute();
 }
Example #35
0
 public static void Move(FilePath file, DirectoryPath toDir, Overwrite overwrite, bool failOnError = true)
 {
     new MoveTask(file) { ToDir = toDir, Overwrite = overwrite, FailOnError = failOnError }.Execute();
 }
Example #36
0
 public static void Move(string file, DirectoryPath toDir, Overwrite overwrite, bool failOnError = true)
 {
     Move((FilePath)file, toDir, overwrite, failOnError);
 }
        /// <summary>
        /// Allows you to add files to an archive, whether the archive
        /// already exists or not
        /// </summary>
        /// <param name="archiveFullName">
        /// The name of the archive to you want to add your files to
        /// </param>
        /// <param name="files">
        /// A set of file names that are to be added
        /// </param>
        /// <param name="action">
        /// Specifies how we are going to handle an existing archive
        /// </param>
        /// <param name="compression">
        /// Specifies what type of compression to use - defaults to Optimal
        /// </param>
        public static void AddToArchive(string archiveFullName,
                                        List<string> files,
                                        ArchiveAction action = ArchiveAction.Replace,
                                        Overwrite fileOverwrite = Overwrite.IfNewer,
                                        CompressionLevel compression = CompressionLevel.Optimal)
        {
            //Identifies the mode we will be using - the default is Create
            ZipArchiveMode mode = ZipArchiveMode.Create;

            //Determines if the zip file even exists
            bool archiveExists = File.Exists(archiveFullName);

            //Figures out what to do based upon our specified overwrite method
            switch (action)
            {
                case ArchiveAction.Merge:
                    //Sets the mode to update if the file exists, otherwise
                    //the default of Create is fine
                    if (archiveExists)
                    {
                        mode = ZipArchiveMode.Update;
                    }
                    break;
                case ArchiveAction.Replace:
                    //Deletes the file if it exists.  Either way, the default
                    //mode of Create is fine
                    if (archiveExists)
                    {
                        File.Delete(archiveFullName);
                    }
                    break;
                case ArchiveAction.Error:
                    //Throws an error if the file exists
                    if (archiveExists)
                    {
                        throw new IOException(String.Format("The zip file {0} already exists.", archiveFullName));
                    }
                    break;
                case ArchiveAction.Ignore:
                    //Closes the method silently and does nothing
                    if (archiveExists)
                    {
                        return;
                    }
                    break;
                default:
                    break;
            }

            //Opens the zip file in the mode we specified
            using (ZipArchive zipFile = ZipFile.Open(archiveFullName, mode))
            {
                //This is a bit of a hack and should be refactored - I am
                //doing a similar foreach loop for both modes, but for Create
                //I am doing very little work while Update gets a lot of
                //code.  This also does not handle any other mode (of
                //which there currently wouldn't be one since we don't
                //use Read here).
                if (mode == ZipArchiveMode.Create)
                {
                    foreach (string file in files)
                    {
                        //Adds the file to the archive
                        zipFile.CreateEntryFromFile(file, Path.GetFileName(file), compression);
                    }
                }
                else
                {
                    foreach (string file in files)
                    {
                        var fileInZip = (from f in zipFile.Entries
                                         where f.Name == Path.GetFileName(file)
                                         select f).FirstOrDefault();

                        switch (fileOverwrite)
                        {
                            case Overwrite.Always:
                                //Deletes the file if it is found
                                if (fileInZip != null)
                                {
                                    fileInZip.Delete();
                                }

                                //Adds the file to the archive
                                zipFile.CreateEntryFromFile(file, Path.GetFileName(file), compression);

                                break;
                            case Overwrite.IfNewer:
                                //This is a bit trickier - we only delete the file if it is
                                //newer, but if it is newer or if the file isn't already in
                                //the zip file, we will write it to the zip file
                                if (fileInZip != null)
                                {
                                    //Deletes the file only if it is older than our file.
                                    //Note that the file will be ignored if the existing file
                                    //in the archive is newer.
                                    if (fileInZip.LastWriteTime < File.GetLastWriteTime(file))
                                    {
                                        fileInZip.Delete();

                                        //Adds the file to the archive
                                        zipFile.CreateEntryFromFile(file, Path.GetFileName(file), compression);
                                    }
                                }
                                else
                                {
                                    //The file wasn't already in the zip file so add it to the archive
                                    zipFile.CreateEntryFromFile(file, Path.GetFileName(file), compression);
                                }
                                break;
                            case Overwrite.Never:
                                //Don't do anything - this is a decision that you need to
                                //consider, however, since this will mean that no file will
                                //be writte.  You could write a second copy to the zip with
                                //the same name (not sure that is wise, however).
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        }
Example #38
0
        /// <summary>
        /// Parse command line arguments.
        /// This is fairly flexible without using any custom classes.  Arguments and options can appear
        /// in any order and are case insensitive.  Arguments for options are indicated with an '='
        /// as in -demo=argument, sometimes the '=' can be omitted as well secretly.
        /// Grouping of single character options is supported.
        /// 
        /// The actual arguments and their handling is however a grab bag of ad-hoc things and its a bit messy.  Could be a 
        /// bit more rigorous about how things are done.  Up side is almost anything is/can be allowed
        /// </summary>		
        /// <returns>
        /// <c>true</c> if arguments are valid such that processing should continue
        /// </returns>
        bool SetArgs(string[] args)
        {
            bool result = true;
            int argIndex = 0;

            while (argIndex < args.Length) {
                if (args[argIndex][0] == '-' || args[argIndex][0] == '/') {

                    string option = args[argIndex].Substring(1).ToLower();
                    string optArg = "";

                    int parameterIndex = option.IndexOf('=');

                    if (parameterIndex >= 0) {
                        if (parameterIndex < option.Length - 1) {
                            optArg = option.Substring(parameterIndex + 1);
                        }
                        option = option.Substring(0, parameterIndex);
                    }

                    if (option.Length == 0) {
                        Console.WriteLine("Invalid argument {0}", args[argIndex]);
                        result = false;
                    }
                    else {
                        int optionIndex = 0;
                        while (optionIndex < option.Length) {
                            switch(option[optionIndex]) {
                                case '-': // long option
                                    optionIndex = option.Length;

                                    switch (option) {
                                        case "-abs":
                                            relativePathInfo = false;
                                            break;

                                        case "-add":
                                            operation = Operation.Add;
                                            break;

                                        case "-create":
                                            operation = Operation.Create;
                                            break;

                                        case "-list":
                                            operation = Operation.List;
                                            useZipFileWhenListing = true;
                                            break;

                                        case "-extract":
                                            operation = Operation.Extract;
                                            if (optArg.Length > 0) {
                                                targetOutputDirectory = optArg;
                                            }
                                            break;

                                        case "-delete":
                                            operation = Operation.Delete;
                                            break;

                                        case "-test":
                                            operation = Operation.Test;
                                            break;

                                        case "-info":
                                            ShowEnvironment();
                                            break;

                                        case "-emptydirs":
                                            addEmptyDirectoryEntries = true;
                                            break;

                                        case "-data":
                                            testData = true;
                                            break;

                                        case "-extractdir":
                                            if (optArg.Length > 0) {
                                                targetOutputDirectory = optArg;
                                            } else {
                                                result = false;
                                                Console.WriteLine("Invalid extractdir " + args[argIndex]);
                                            }
                                            break;

                                        case "-zip64":
                                            if ( optArg.Length > 0 ) {
                                                switch ( optArg ) {
                                                    case "on":
                                                        useZip64_ = UseZip64.On;
                                                        break;

                                                    case "off":
                                                        useZip64_ = UseZip64.Off;
                                                        break;

                                                    case "auto":
                                                        useZip64_ = UseZip64.Dynamic;
                                                        break;
                                                }
                                            }
                                            break;

                                        case "-encoding":
                                            if (optArg.Length > 0) {
                                                if (IsNumeric(optArg)) {
                                                    try {
                                                        int enc = int.Parse(optArg);
                                                        if (Encoding.GetEncoding(enc) != null) {
                                                            ZipConstants.DefaultCodePage = enc;
                                                        } else {
                                                            result = false;
                                                            Console.WriteLine("Invalid encoding " + args[argIndex]);
                                                        }
                                                    }
                                                    catch (Exception) {
                                                        result = false;
                                                        Console.WriteLine("Invalid encoding " + args[argIndex]);
                                                    }
                                                } else {
                                                    try {
                                                        ZipConstants.DefaultCodePage = Encoding.GetEncoding(optArg).CodePage;
                                                    }
                                                    catch (Exception) {
                                                        result = false;
                                                        Console.WriteLine("Invalid encoding " + args[argIndex]);
                                                    }
                                                }
                                            } else {
                                                result = false;
                                                Console.WriteLine("Missing encoding parameter");
                                            }
                                            break;

                                        case "-store":
                                            useZipStored = true;
                                            break;

                                        case "-deflate":
                                            useZipStored = false;
                                            break;

                                        case "-version":
                                            ShowVersion();
                                            break;

                                        case "-help":
                                            ShowHelp();
                                            break;
            #if !NETCF
                                        case "-restore-dates":
                                            restoreDateTime = true;
                                            break;
            #endif

                                        default:
                                            Console.WriteLine("Invalid long argument " + args[argIndex]);
                                            result = false;
                                            break;
                                    }
                                    break;

                                case '?':
                                    ShowHelp();
                                    break;

                                case 's':
                                    if (optionIndex != 0) {
                                        result = false;
                                        Console.WriteLine("-s cannot be in a group");
                                    } else {
                                        if (optArg.Length > 0) {
                                            password = optArg;
                                        } else if (option.Length > 1) {
                                            password = option.Substring(1);
                                        } else {
                                            Console.WriteLine("Missing argument to " + args[argIndex]);
                                        }
                                    }
                                    optionIndex = option.Length;
                                    break;

                                case 'c':
                                    operation = Operation.Create;
                                    break;

                                case 'l':
                                    if (optionIndex != 0) {
                                        result = false;
                                        Console.WriteLine("-l cannot be in a group");
                                    } else {
                                        if (optArg.Length > 0) {
                                            try {
                                                compressionLevel = int.Parse(optArg);
                                            }
                                            catch (Exception) {
                                                Console.WriteLine("Level invalid");
                                            }
                                        }
                                    }
                                    optionIndex = option.Length;
                                    break;

                                case 'o':
                                    optionIndex += 1;
                                    overwriteFiles = (optionIndex < option.Length) ? (option[optionIndex] == '+') ? Overwrite.Always : Overwrite.Never : Overwrite.Never;
                                    break;

                                case 'p':
                                    relativePathInfo = true;
                                    break;

                                case 'q':
                                    silent = true;
                                    if (overwriteFiles == Overwrite.Prompt) {
                                        overwriteFiles = Overwrite.Never;
                                    }
                                    break;

                                case 'r':
                                    recursive = true;
                                    break;

                                case 'v':
                                    operation = Operation.List;
                                    break;

                                case 'x':
                                    if (optionIndex != 0) {
                                        result = false;
                                        Console.WriteLine("-x cannot be in a group");
                                    } else {
                                        operation = Operation.Extract;
                                        if (optArg.Length > 0) {
                                            targetOutputDirectory = optArg;
                                        }
                                    }
                                    optionIndex = option.Length;
                                    break;

                                default:
                                    Console.WriteLine("Invalid argument: " + args[argIndex]);
                                    result = false;
                                    break;
                            }
                            ++optionIndex;
                        }
                    }
                }
                else {
                    fileSpecs.Add(args[argIndex]);
                }
                ++argIndex;
            }

            if (fileSpecs.Count > 0 && operation == Operation.Create) {
                var checkPath = (string)fileSpecs[0];
                int deviceCheck = checkPath.IndexOf(':');
            #if NETCF_1_0
                if (checkPath.IndexOfAny(Path.InvalidPathChars) >= 0
            #else
                if (checkPath.IndexOfAny(Path.GetInvalidPathChars()) >= 0
            #endif
                    || checkPath.IndexOf('*') >= 0 || checkPath.IndexOf('?') >= 0
                    || (deviceCheck >= 0 && deviceCheck != 1)) {
                        Console.WriteLine("There are invalid characters in the specified zip file name");
                        result = false;
                    }
            }
            return result && (fileSpecs.Count > 0);
        }
        /// <summary>
        /// Parse command line arguments.
        /// This is fairly flexible without using any custom classes.  Arguments and options can appear
        /// in any order and are case insensitive.  Arguments for options are signalled with an '='
        /// as in -demo=argument, sometimes the '=' can be omitted as well secretly.
        /// Grouping of single character options is supported.
        /// </summary>		
        /// <returns>
        /// true if arguments are valid such that processing should continue
        /// </returns>
        bool SetArgs(string[] args)
        {
            bool result = true;
            int argIndex = 0;

            while (argIndex < args.Length)
            {
                if (args[argIndex][0] == '-' || args[argIndex][0] == '/')
                {

                    string option = args[argIndex].Substring(1).ToLower();
                    string optArg = "";

                    int parameterIndex = option.IndexOf('=');

                    if (parameterIndex >= 0)
                    {
                        if (parameterIndex < option.Length - 1)
                        {
                            optArg = option.Substring(parameterIndex + 1);
                        }
                        option = option.Substring(0, parameterIndex);
                    }

            #if OPTIONTEST
                    Console.WriteLine("args index [{0}] option [{1}] argument [{2}]", argIndex, option, optArg);
            #endif
                    if (option.Length == 0)
                    {
                        System.Console.Error.WriteLine("Invalid argument (0}", args[argIndex]);
                        result = false;
                    }
                    else
                    {
                        int optionIndex = 0;
                        while (optionIndex < option.Length)
                        {
            #if OPTIONTEST
                            Console.WriteLine("optionIndex {0}", optionIndex);
            #endif
                            switch(option[optionIndex])
                            {
                                case '-': // long option
                                    optionIndex = option.Length;

                                    switch (option)
                                    {
                                        case "-add":
                                            operation_ = Operation.Add;
                                            break;

                                        case "-create":
                                            operation_ = Operation.Create;
                                            break;

                                        case "-list":
                                            operation_ = Operation.List;
                                            break;

                                        case "-extract":
                                            operation_ = Operation.Extract;
                                            if (optArg.Length > 0)
                                            {
                                                targetOutputDirectory_ = optArg;
                                            }
                                            break;

                                        case "-delete":
                                            operation_ = Operation.Delete;
                                            break;

                                        case "-test":
                                            operation_ = Operation.Test;
                                            break;

                                        case "-env":
                                            ShowEnvironment();
                                            break;

                                        case "-emptydirs":
                                            addEmptyDirectoryEntries_ = true;
                                            break;

                                        case "-data":
                                            testData_ = true;
                                            break;

                                        case "-zip64":
                                            if ( optArg.Length > 0 )
                                            {
                                                switch ( optArg )
                                                {
                                                    case "on":
                                                        useZip64_ = UseZip64.On;
                                                        break;

                                                    case "off":
                                                        useZip64_ = UseZip64.Off;
                                                        break;

                                                    case "auto":
                                                        useZip64_ = UseZip64.Dynamic;
                                                        break;
                                                }
                                            }
                                            break;

                                        case "-encoding":
                                            if (optArg.Length > 0)
                                            {
                                                if (IsNumeric(optArg))
                                                {
                                                    try
                                                    {
                                                        int enc = int.Parse(optArg);
                                                        if (Encoding.GetEncoding(enc) != null)
                                                        {
            #if OPTIONTEST
                                                            Console.WriteLine("Encoding set to {0}", enc);
            #endif
                                                            ZipConstants.DefaultCodePage = enc;
                                                        }
                                                        else
                                                        {
                                                            result = false;
                                                            System.Console.Error.WriteLine("Invalid encoding " + args[argIndex]);
                                                        }
                                                    }
                                                    catch (Exception)
                                                    {
                                                        result = false;
                                                        System.Console.Error.WriteLine("Invalid encoding " + args[argIndex]);
                                                    }
                                                }
                                                else
                                                {
                                                    try
                                                    {
                                                        ZipConstants.DefaultCodePage = Encoding.GetEncoding(optArg).CodePage;
                                                    }
                                                    catch (Exception)
                                                    {
                                                        result = false;
                                                        System.Console.Error.WriteLine("Invalid encoding " + args[argIndex]);
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                result = false;
                                                System.Console.Error.WriteLine("Missing encoding parameter");
                                            }
                                            break;

                                        case "-version":
                                            ShowVersion();
                                            break;

                                        case "-help":
                                            ShowHelp();
                                            break;

                                        case "-restore-dates":
                                            restoreDateTime_ = true;
                                            break;

                                        default:
                                            System.Console.Error.WriteLine("Invalid long argument " + args[argIndex]);
                                            result = false;
                                            break;
                                    }
                                    break;

                                case '?':
                                    ShowHelp();
                                    break;

                                case 's':
                                    if (optionIndex != 0)
                                    {
                                        result = false;
                                        System.Console.Error.WriteLine("-s cannot be in a group");
                                    }
                                    else
                                    {
                                        if (optArg.Length > 0)
                                        {
                                            password_ = optArg;
                                        }
                                        else if (option.Length > 1)
                                        {
                                            password_ = option.Substring(1);
                                        }
                                        else
                                        {
                                            System.Console.Error.WriteLine("Missing argument to " + args[argIndex]);
                                        }
                                    }
                                    optionIndex = option.Length;
                                    break;

                                case 't':
                                    operation_ = Operation.Test;
                                    break;

                                case 'c':
                                    operation_ = Operation.Create;
                                    break;

                                case 'e':
                                    if (optionIndex != 0)
                                    {
                                        result = false;
                                        System.Console.Error.WriteLine("-e cannot be in a group");
                                    }
                                    else
                                    {
                                        optionIndex = option.Length;
                                        if (optArg.Length > 0)
                                        {
                                            try
                                            {
                                                compressionLevel_ = int.Parse(optArg);
                                            }
                                            catch (Exception)
                                            {
                                                System.Console.Error.WriteLine("Level invalid");
                                            }
                                        }
                                    }
                                    optionIndex = option.Length;
                                    break;

                                case 'o':
                                    optionIndex += 1;
                                    overwriteFiles = optionIndex < option.Length ? (option[optionIndex] == '+') ? Overwrite.Always : Overwrite.Never : Overwrite.Never;
                                    break;

                                case 'q':
                                    silent_ = true;
                                    if (overwriteFiles == Overwrite.Prompt)
                                    {
                                        overwriteFiles = Overwrite.Never;
                                    }
                                    break;

                                case 'r':
                                    recursive_ = true;
                                    break;

                                case 'v':
                                    operation_ = Operation.List;
                                    break;

                                case 'x':
                                    if (optionIndex != 0)
                                    {
                                        result = false;
                                        System.Console.Error.WriteLine("-x cannot be in a group");
                                    }
                                    else
                                    {
                                        operation_ = Operation.Extract;
                                        if (optArg.Length > 0)
                                        {
                                            targetOutputDirectory_ = optArg;
                                        }
                                    }
                                    optionIndex = option.Length;
                                    break;

                                default:
                                    System.Console.Error.WriteLine("Invalid argument: " + args[argIndex]);
                                    result = false;
                                    break;
                            }
                            ++optionIndex;
                        }
                    }
                }
                else
                {
            #if OPTIONTEST
                    Console.WriteLine("file spec {0} = '{1}'", argIndex, args[argIndex]);
            #endif
                    fileSpecs_.Add(args[argIndex]);
                }
                ++argIndex;
            }

            if (fileSpecs_.Count > 0)
            {
                string checkPath = (string)fileSpecs_[0];
                int deviceCheck = checkPath.IndexOf(':');
            #if NET_VER_1
                if (checkPath.IndexOfAny(Path.InvalidPathChars) >= 0
            #else
                if (checkPath.IndexOfAny(Path.GetInvalidPathChars()) >= 0
            #endif
                    || checkPath.IndexOf('*') >= 0 || checkPath.IndexOf('?') >= 0
                    || ((deviceCheck >= 0) && (deviceCheck != 1)))
                {
                    Console.WriteLine("There are invalid characters in the specified zip file name");
                    result = false;
                }
            }
            return result && (fileSpecs_.Count > 0);
        }
Example #40
0
        /// <summary>
        /// Extract the contents of a zip file.
        /// </summary>
        /// <param name="zipFileName">The zip file to extract from.</param>
        /// <param name="targetDirectory">The directory to save extracted information in.</param>
        /// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
        /// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
        /// <param name="fileFilter">A method-filter to apply to files.</param>
        /// <param name="directoryFilter">A method-filter to apply to directories.</param>
        public void ExtractZip(
            string zipFileName,
            string targetDirectory,
            Overwrite overwrite,
            ConfirmOverwriteDelegate confirmDelegate,
            Func<string, bool> fileFilter,
            Func<string, bool> directoryFilter)
        {
            if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null))
            {
                throw new ArgumentNullException("confirmDelegate");
            }

            continueRunning_ = true;
            overwrite_ = overwrite;
            confirmDelegate_ = confirmDelegate;
            extractNameTransform_ = new WindowsNameTransform(targetDirectory);

            restoreDateTimeOnExtract_ = true;

            Stream inputStream = File.Open(zipFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            using (zipFile_ = new ZipFile(inputStream))
            {

            #if !NETCF_1_0
                if (password_ != null)
                {
                    zipFile_.Password = password_;
                }
            #endif
                zipFile_.IsStreamOwner = true;
                System.Collections.IEnumerator enumerator = zipFile_.GetEnumerator();
                while (continueRunning_ && enumerator.MoveNext())
                {
                    ZipEntry entry = (ZipEntry)enumerator.Current;
                    if (entry.IsFile)
                    {
                        // TODO Path.GetDirectory can fail here on invalid characters.
                        if (directoryFilter(Path.GetDirectoryName(entry.Name)) && fileFilter(entry.Name))
                        {
                            ExtractEntry(entry);
                        }
                    }
                    else if (entry.IsDirectory)
                    {
                        if (directoryFilter(entry.Name) && CreateEmptyDirectories)
                        {
                            ExtractEntry(entry);
                        }
                    }
                }
            }
        }
Example #41
0
		/// <summary>
		/// Extract the contents of a zip file.
		/// </summary>
		/// <param name="zipFileName">The zip file to extract from.</param>
		/// <param name="targetDirectory">The directory to save extracted information in.</param>
		/// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
		/// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
		/// <param name="fileFilter">A filter to apply to files.</param>
		/// <param name="directoryFilter">A filter to apply to directories.</param>
		/// <param name="restoreDateTime">Flag indicating whether to restore the date and time for extracted files.</param>
		public void ExtractZip(string zipFileName, string targetDirectory, 
							   Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, 
							   string fileFilter, string directoryFilter, bool restoreDateTime)
		{
			Stream inputStream = File.Open(zipFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
			ExtractZip(inputStream, targetDirectory, overwrite, confirmDelegate, fileFilter, directoryFilter, restoreDateTime, true);
		}
Example #42
0
        /// <summary>
        /// Extract the contents of a zip file held in a stream.
        /// </summary>
        /// <param name="inputStream">The seekable input stream containing the zip to extract from.</param>
        /// <param name="targetDirectory">The directory to save extracted information in.</param>
        /// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
        /// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
        /// <param name="fileFilter">A filter to apply to files.</param>
        /// <param name="directoryFilter">A filter to apply to directories.</param>
        /// <param name="restoreDateTime">Flag indicating whether to restore the date and time for extracted files.</param>
        /// <param name="isStreamOwner">Flag indicating whether the inputStream will be closed by this method.</param>
        public void ExtractZip(Stream inputStream, string targetDirectory,
                       Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate,
                       string fileFilter, string directoryFilter, bool restoreDateTime,
                       bool isStreamOwner)
        {
            if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null)) {
                throw new ArgumentNullException("confirmDelegate");
            }

            continueRunning_ = true;
            overwrite_ = overwrite;
            confirmDelegate_ = confirmDelegate;
            extractNameTransform_ = new WindowsNameTransform(targetDirectory);

            fileFilter_ = new NameFilter(fileFilter);
            directoryFilter_ = new NameFilter(directoryFilter);
            restoreDateTimeOnExtract_ = restoreDateTime;

            using (zipFile_ = new ZipFile(inputStream)) {

#if !NETCF_1_0
                if (password_ != null) {
                    zipFile_.Password = password_;
                }
#endif
                zipFile_.IsStreamOwner = isStreamOwner;
                IEnumerator enumerator = zipFile_.GetEnumerator();
                while (continueRunning_ && enumerator.MoveNext()) {
                    ZipEntry entry = (ZipEntry)enumerator.Current;
                    if (entry.IsFile)
                    {
                        // TODO Path.GetDirectory can fail here on invalid characters.
                        if (directoryFilter_.IsMatch(Path.GetDirectoryName(entry.Name)) && fileFilter_.IsMatch(entry.Name)) {
                            ExtractEntry(entry);
                        }
                    }
                    else if (entry.IsDirectory) {
                        if (directoryFilter_.IsMatch(entry.Name) && CreateEmptyDirectories) {
                            ExtractEntry(entry);
                        }
                    }
                    else {
                        // Do nothing for volume labels etc...
                    }
                }
            }
        }
Example #43
0
        public static void CreateEmptyFile(String filename, Overwrite overwrite)
        {
            filename.Name("filename").NotNullEmptyOrOnlyWhitespace();

              if ((overwrite == Overwrite.Yes) || !File.Exists(filename))
              {
            using (var fs = File.Create(filename))
            {
              /* Create an empty file. */
            }
              }
        }
Example #44
0
        /// <summary>
        /// Extract the contents of a zip file.
        /// </summary>
        /// <param name="zipFileName">The zip file to extract from.</param>
        /// <param name="targetDirectory">The directory to save extracted information in.</param>
        /// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
        /// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
        /// <param name="fileFilter">A filter to apply to files.</param>
        /// <param name="directoryFilter">A filter to apply to directories.</param>
        /// <param name="restoreDateTime">Flag indicating wether to restore the date and time for extracted files.</param>
        public void ExtractZip(string zipFileName, string targetDirectory, 
            Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate,
            string fileFilter, string directoryFilter, bool restoreDateTime)
        {
            if ( (overwrite == Overwrite.Prompt) && (confirmDelegate == null) ) {
                throw new ArgumentNullException("confirmDelegate");
            }

            continueRunning_ = true;
            overwrite_ = overwrite;
            confirmDelegate_ = confirmDelegate;
            targetDirectory_ = targetDirectory;
            fileFilter_ = new NameFilter(fileFilter);
            directoryFilter_ = new NameFilter(directoryFilter);
            restoreDateTimeOnExtract_ = restoreDateTime;

            using ( inputStream_ = new ZipInputStream(File.OpenRead(zipFileName)) ) {
                if (password_ != null) {
                    inputStream_.Password = password_;
                }

                ZipEntry entry;
                while ( continueRunning_ && (entry = inputStream_.GetNextEntry()) != null ) {
                    if ( directoryFilter_.IsMatch(Path.GetDirectoryName(entry.Name)) && fileFilter_.IsMatch(entry.Name) ) {
                        ExtractEntry(entry);
                    }
                }
            }
        }
Example #45
0
		/// <summary>
		/// Exatract the contents of a zip file.
		/// </summary>
		/// <param name="zipFileName">The zip file to extract from.</param>
		/// <param name="targetDirectory">The directory to save extracted information in.</param>
		/// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
		/// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
		/// <param name="fileFilter">A filter to apply to files.</param>
		/// <param name="directoryFilter">A filter to apply to directories.</param>
		public void ExtractZip(string zipFileName, string targetDirectory, 
		                       Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, 
		                       string fileFilter, string directoryFilter)
		{
			if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null)) {
				throw new ArgumentNullException("confirmDelegate");
			}
			this.overwrite = overwrite;
			this.confirmDelegate = confirmDelegate;
			this.targetDirectory = targetDirectory;
			this.fileFilter = new NameFilter(fileFilter);
			this.directoryFilter = new NameFilter(directoryFilter);
			
			inputStream = new ZipInputStream(File.OpenRead(zipFileName));
			
			try {
				
				if (password != null) {
					inputStream.Password = password;
				}

				ZipEntry entry;
				while ( (entry = inputStream.GetNextEntry()) != null ) {
					if ( this.directoryFilter.IsMatch(Path.GetDirectoryName(entry.Name)) && this.fileFilter.IsMatch(entry.Name) ) {
						ExtractEntry(entry);
					}
				}
			}
			finally {
				inputStream.Close();
			}
		}
Example #46
0
 public void ExtractZip(Stream inputStream, string targetDirectory, Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, string fileFilter, string directoryFilter, bool restoreDateTime, bool isStreamOwner)
 {
     if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null))
     {
         throw new ArgumentNullException(nameof(confirmDelegate));
     }
     _continueRunning = true;
     _overwrite = overwrite;
     _confirmDelegate = confirmDelegate;
     _extractNameTransform = new WindowsNameTransform(targetDirectory);
     _fileFilter = new NameFilter(fileFilter);
     _directoryFilter = new NameFilter(directoryFilter);
     _restoreDateTimeOnExtract = restoreDateTime;
     using (_zipFile = new ZipFile(inputStream))
     {
         if (_password != null)
         {
             _zipFile.Password = _password;
         }
         _zipFile.IsStreamOwner = isStreamOwner;
         IEnumerator enumerator = _zipFile.GetEnumerator();
         while (_continueRunning && enumerator.MoveNext())
         {
             ZipEntry current = (ZipEntry)enumerator.Current;
             if (current.IsFile)
             {
                 if (_directoryFilter.IsMatch(Path.GetDirectoryName(current.Name)) && _fileFilter.IsMatch(current.Name))
                 {
                     ExtractEntry(current);
                 }
             }
             else if ((current.IsDirectory && _directoryFilter.IsMatch(current.Name)) && CreateEmptyDirectories)
             {
                 ExtractEntry(current);
             }
         }
     }
 }
Example #47
0
 public void ExtractZip(Stream inputStream, string targetDirectory, Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, string fileFilter, string directoryFilter, bool restoreDateTime, bool isStreamOwner)
 {
     if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null))
     {
         throw new ArgumentNullException("confirmDelegate");
     }
     this.continueRunning_ = true;
     this.overwrite_ = overwrite;
     this.confirmDelegate_ = confirmDelegate;
     this.extractNameTransform_ = new WindowsNameTransform(targetDirectory);
     this.fileFilter_ = new NameFilter(fileFilter);
     this.directoryFilter_ = new NameFilter(directoryFilter);
     this.restoreDateTimeOnExtract_ = restoreDateTime;
     using (this.zipFile_ = new ZipFile(inputStream))
     {
         if (this.password_ != null)
         {
             this.zipFile_.Password = this.password_;
         }
         this.zipFile_.IsStreamOwner = isStreamOwner;
         IEnumerator enumerator = this.zipFile_.GetEnumerator();
         while (this.continueRunning_ && enumerator.MoveNext())
         {
             ZipEntry current = (ZipEntry) enumerator.Current;
             if (current.IsFile)
             {
                 if (this.directoryFilter_.IsMatch(Path.GetDirectoryName(current.Name)) && this.fileFilter_.IsMatch(current.Name))
                 {
                     this.ExtractEntry(current);
                 }
             }
             else if ((current.IsDirectory && this.directoryFilter_.IsMatch(current.Name)) && this.CreateEmptyDirectories)
             {
                 this.ExtractEntry(current);
             }
         }
     }
 }
Example #48
0
 public static void CopyToFile(FilePath file, FilePath toFile, Overwrite overwrite = Overwrite.IfNewer, bool failOnError = true)
 {
     new CopyTask(file) { ToFile = toFile, Overwrite = overwrite, FailOnError = failOnError }.Execute();
 }
Example #49
0
 public static void CopyToDir(FileSet files, DirectoryPath toDir, Overwrite overwrite)
 {
     new CopyTask(files) { ToDir = toDir, Overwrite = overwrite}.Execute();
 }
Example #50
0
 public static void Rename(FilePath file, FilePath toFile, Overwrite overwrite)
 {
     new MoveTask(file) { ToFile = toFile, Overwrite = overwrite }.Execute();
 }
Example #51
0
        /// <summary>
        /// Extract the contents of a zip file.
        /// </summary>
        /// <param name="zipFileName">The zip file to extract from.</param>
        /// <param name="targetDirectory">The directory to save extracted information in.</param>
        /// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
        /// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
        /// <param name="fileFilter">A filter to apply to files.</param>
        /// <param name="directoryFilter">A filter to apply to directories.</param>
        /// <param name="restoreDateTime">Flag indicating wether to restore the date and time for extracted files.</param>
        public void ExtractZip(string zipFileName, string targetDirectory, 
							   Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, 
							   string fileFilter, string directoryFilter, bool restoreDateTime)
        {
            if ( (overwrite == Overwrite.Prompt) && (confirmDelegate == null) ) {
                throw new ArgumentNullException("confirmDelegate");
            }

            continueRunning_ = true;
            overwrite_ = overwrite;
            confirmDelegate_ = confirmDelegate;
            targetDirectory_ = targetDirectory;
            fileFilter_ = new NameFilter(fileFilter);
            directoryFilter_ = new NameFilter(directoryFilter);
            restoreDateTimeOnExtract_ = restoreDateTime;

            using ( zipFile_ = new ZipFile(zipFileName) ) {

            #if !NETCF_1_0
                if (password_ != null) {
                    zipFile_.Password = password_;
                }
            #endif

                System.Collections.IEnumerator enumerator = zipFile_.GetEnumerator();
                while ( continueRunning_ && enumerator.MoveNext()) {
                    ZipEntry entry = (ZipEntry) enumerator.Current;
                    if ( entry.IsFile )
                    {
                        if ( directoryFilter_.IsMatch(Path.GetDirectoryName(entry.Name)) && fileFilter_.IsMatch(entry.Name) ) {
                            ExtractEntry(entry);
                        }
                    }
                    else if ( entry.IsDirectory ) {
                        if ( directoryFilter_.IsMatch(entry.Name) && CreateEmptyDirectories ) {
                            ExtractEntry(entry);
                        }
                    }
                    else {
                        // Do nothing for volume labels etc...
                    }
                }
            }
        }
Example #52
0
        /// <summary>
        /// Extract the contents of a zip file.
        /// </summary>
        /// <param name="zipFileName">The zip file to extract from.</param>
        /// <param name="targetDirectory">The directory to save extracted information in.</param>
        /// <param name="overwrite">The style of <see cref="Overwrite">overwriting</see> to apply.</param>
        /// <param name="confirmDelegate">A delegate to invoke when confirming overwriting.</param>
        /// <param name="fileFilter">A filter to apply to files.</param>
        /// <param name="directoryFilter">A filter to apply to directories.</param>
        /// <param name="restoreDateTime">Flag indicating wether to restore the date and time for extracted files.</param>
        public void ExtractZip(string zipFileName, string targetDirectory,
                               Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate,
                               string fileFilter, string directoryFilter, bool restoreDateTime)
        {
            if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null))
            {
                throw new ArgumentNullException("confirmDelegate");
            }

            continueRunning = true;
            this.overwrite = overwrite;
            this.confirmDelegate = confirmDelegate;
            this.targetDirectory = targetDirectory;
            this.fileFilter = new NameFilter(fileFilter);
            this.directoryFilter = new NameFilter(directoryFilter);
            restoreDateTimeOnExtract = restoreDateTime;

            using (zipFile = new ZipFile(zipFileName))
            {
            #if !NETCF_1_0
                if (password != null)
                {
                    zipFile.Password = password;
                }
            #endif

                IEnumerator enumerator = zipFile.GetEnumerator();
                while (continueRunning && enumerator.MoveNext())
                {
                    var entry = (ZipEntry) enumerator.Current;
                    if (entry.IsFile)
                    {
                        if (this.directoryFilter.IsMatch(Path.GetDirectoryName(entry.Name)) &&
                            this.fileFilter.IsMatch(entry.Name))
                        {
                            if (events == null || events.OnProcessFile(entry.Name))
                            {
                                ExtractEntry(entry);
                            }
                        }
                    }
                    else if (entry.IsDirectory)
                    {
                        if (this.directoryFilter.IsMatch(entry.Name) && CreateEmptyDirectories)
                        {
                            if (events == null || events.OnProcessDirectory(entry.Name, true))
                            {
                                ExtractEntry(entry);
                            }
                        }
                    }
                }
            }
        }