Example #1
0
        public OpenFolderAction(string path, IFileExplorer fileExplorer)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (fileExplorer == null)
            {
                throw new ArgumentNullException(nameof(fileExplorer));
            }

            _fileExplorer = fileExplorer;

            _task = Task.Run(() =>
            {
                if (!FileEx.Exists(path, TimeSpan.FromSeconds(1)))
                {
                    FullFoldername = FileEx.FindClosestExistingFolder(path);
                    _fileExplorer.OpenFolder(FullFoldername);
                }
                else
                {
                    FullFoldername = path;
                    _fileExplorer.SelectFile(path);
                }
            })
                    .ContinueWith(OnFolderOpened);
        }
Example #2
0
        public void Initialize()
        {
            string asmDir = PathEx.GetDirectoryName(typeof(GitTests).Assembly.Location);

            this.rootDir = PathEx.Combine(asmDir, "test-root");
            DirectoryEx.Create(this.rootDir);
            DirectoryEx.Clear(this.rootDir);

            if (FileEx.Exists(credentialsFilePath))
            {
                var lines = File.ReadAllLines(credentialsFilePath);
                this.userName = lines[0];
                this.password = SecureStringExtensions.ToSecureString(lines[1]);
            }

            var fileOps = new TestFileOperationsExecuter(Path.Combine(this.rootDir, "agent"));

            //var fileOps = new SimulatedFileOperationsExecuter(fileOps);
            //fileOps.MessageLogged += (s, e) => TestLogger.Instance.Log(e.Level, e.Message);

            this.fileOps = fileOps;

            this.processExecuter = new TestRemoteProcessExecuter();
            this.jobExecuter     = new TestRemoteJobExecuter();
        }
        protected override async Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            var client = new ProGetClient(this.Server, this.FeedName, this.UserName, this.Password, this, context.CancellationToken);

            try
            {
                this.LogInformation($"Pushing package {this.Name} to ProGet...");

                string path = context.ResolvePath(this.FilePath);

                this.LogDebug("Using package file: " + path);

                if (!FileEx.Exists(path))
                {
                    this.LogError(this.FilePath + " does not exist.");
                    return(null);
                }

                if (string.IsNullOrWhiteSpace(this.Name) || string.IsNullOrWhiteSpace(this.Version))
                {
                    try
                    {
                        using (var package = new UniversalPackage(path))
                        {
                            if (string.IsNullOrWhiteSpace(package.Name) || package.Version == null)
                            {
                                this.LogError("Name and Version properties are required unless pushing a package that already has those properties set.");
                                return(null);
                            }
                        }
                    }
                    catch
                    {
                        this.LogError("Name and Version properties are required unless pushing a package that already has those properties set.");
                        return(null);
                    }
                }

                using (var file = FileEx.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var data = new ProGetPackagePushData
                    {
                        Title        = this.Title,
                        Description  = this.Description,
                        Icon         = this.Icon,
                        Dependencies = this.Dependencies?.ToArray()
                    };

                    await client.PushPackageAsync(this.Group, this.Name, this.Version, data, file);
                }
            }
            catch (ProGetException ex)
            {
                this.LogError(ex.FullMessage);
                return(null);
            }

            this.LogInformation("Package pushed.");
            return(null);
        }
Example #4
0
        protected override string ProcessRemoteCommand(string name, string[] args)
        {
            if (name != "SetReleaseNotes")
            {
                throw new ArgumentException("Invalid command.");
            }
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            var nuspecFile = PathEx.Combine(this.Context.SourceDirectory, this.NuspecFileName);

            if (!FileEx.Exists(nuspecFile))
            {
                this.LogError("Nuspec file {0} does not exist.", nuspecFile);
                return(string.Empty);
            }
            else
            {
                this.LogDebug("Editing nuspec file {0}...", nuspecFile);
            }

            var xdoc = XDocument.Load(nuspecFile);
            var ns   = xdoc.Root.GetDefaultNamespace();

            var releaseNotesElement = xdoc.Descendants(ns + "releaseNotes").FirstOrDefault();

            if (releaseNotesElement == null)
            {
                var metadataElement = xdoc.Descendants(ns + "metadata").FirstOrDefault();
                if (metadataElement == null)
                {
                    this.LogError("Invalid format for nuspec file {0}: Could not find /package/metadata element.", nuspecFile);
                    return(string.Empty);
                }

                releaseNotesElement = new XElement(ns + "releaseNotes");
                metadataElement.Add(releaseNotesElement);
            }

            var notesText = string.Join(Environment.NewLine, args);

            if (string.IsNullOrEmpty(notesText))
            {
                this.LogInformation("No release notes to write for this release.");
            }
            else
            {
                this.LogInformation("Writing release notes to nuspec file.");
            }

            releaseNotesElement.Value = notesText ?? string.Empty;

            xdoc.Save(nuspecFile);
            this.LogDebug("Release notes written to nuspec file.");

            return(string.Empty);
        }
Example #5
0
 public MusicInfo(string filePath)
 {
     UniqueId = Guid.NewGuid();
     if (!FileEx.Exists(filePath))
     {
         throw new FileNotFoundException("File not found: " + filePath);
     }
     FilePath = filePath;
     GetInfoFromTag();
 }
        protected override async Task PerformRequestAsync(CancellationToken cancellationToken)
        {
            if (!FileEx.Exists(this.ResolvedFilePath))
            {
                this.LogDebug($"The file \"{this.ResolvedFilePath}\" does not exist.");
                return;
            }

            using (var fileStream = new FileStream(this.ResolvedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
            {
                await this.PerformRequestAsync(fileStream, cancellationToken);
            }
        }
        protected override async Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            var client = new ProGetClient(this.Server, this.FeedName, this.UserName, this.Password, this);

            try
            {
                this.LogInformation($"Pushing package {this.Name} to ProGet...");

                string path = context.ResolvePath(this.FilePath);

                this.LogDebug("Using package file: " + path);

                if (!FileEx.Exists(path))
                {
                    this.LogError(this.FilePath + " does not exist.");
                    return(null);
                }

                using (var file = FileEx.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var data = new ProGetPackagePushData
                    {
                        Title        = this.Title,
                        Description  = this.Description,
                        Icon         = this.Icon,
                        Dependencies = this.Dependencies?.ToArray()
                    };

                    await client.PushPackageAsync(this.Group, this.Name, this.Version, data, file).ConfigureAwait(false);
                }
            }
            catch (ProGetException ex)
            {
                this.LogError(ex.FullMessage);
                return(null);
            }

            this.LogInformation("Package pushed.");
            return(null);
        }
        /// <summary>   Gets the password for the given key file, if available. </summary>
        /// <param name="keyFilePath">  The full path to the key file to get the password for.</param>
        /// <returns>   The password or an empty string. </returns>
        public string GetKeyFilePassword(string keyFilePath)
        {
            if (string.IsNullOrWhiteSpace(keyFilePath))
            {
                throw new ArgumentException("Argument is null or whitespace", nameof(keyFilePath));
            }
            if (!FileEx.Exists(keyFilePath))
            {
                throw new FileNotFoundException($"The key file [{keyFilePath}] does not exist !", keyFilePath);
            }

            var pwPath = Path.ChangeExtension(keyFilePath, ".pw");

            if (!FileEx.Exists(pwPath))
            {
                return(string.Empty);
            }

            using (var file = FileEx.Open(pwPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (var reader = new StreamReader(file))
                    return(reader.ReadToEnd( ));
        }
Example #9
0
 public override async Task <IEntryModel> ParseAsync(string path)
 {
     return(await Task <IEntryModel> .Factory.StartNew(() =>
     {
         IEntryModel retVal = null;
         if (String.IsNullOrEmpty(path))
         {
             retVal = new FileSystemInfoExModel(this, DirectoryInfoEx.DesktopDirectory);
         }
         else
         if (path.StartsWith("::"))
         {
             if (DirectoryEx.Exists(path))
             {
                 retVal = new FileSystemInfoExModel(this, createDirectoryInfo(path));
             }
             else
             if (FileEx.Exists(path))
             {
                 retVal = new FileSystemInfoExModel(this, createFileInfo(path));
             }
         }
         else
         {
             if (Directory.Exists(path))
             {
                 retVal = new FileSystemInfoExModel(this, createDirectoryInfo(path));
             }
             else
             if (File.Exists(path))
             {
                 retVal = new FileSystemInfoExModel(this, createFileInfo(path));
             }
         }
         return Converters.Convert(retVal);
     }));
 }
        public string DownloadTrack(MusicTrack track, string levelPath)
        {
            var err = track.GetError();

            if (err != null)
            {
                return(null);
            }

            if (track.FileLocation != null || track.Attempted)
            {
                return(track.FileLocation);
            }

            track.Attempted = true;
            var trackPath = $"{levelPath}.{track.FileName}{track.FileType}";
            var statePath = $"{levelPath}.{track.FileName}.musicstate";
            var upToDate  = false;

            try
            {
                if (FileEx.Exists(statePath) && FileEx.Exists(trackPath))
                {
                    var stateStr = FileEx.ReadAllText(statePath);

                    if (stateStr == track.Version)
                    {
                        upToDate = true;
                    }
                }
            }
            catch (Exception e)
            {
                Mod.Instance.Logger.Error($"Failed to read music state file {statePath} because {e}");
                Mod.Instance.Logger.Exception(e);

                return(null);
            }

            if (upToDate)
            {
                track.FileLocation = trackPath;
                return(trackPath);
            }

            if (track.Embedded.Length > 0)
            {
                try
                {
                    FileEx.WriteAllBytes(trackPath, track.Embedded);
                    track.FileLocation = trackPath;
                }
                catch (Exception e)
                {
                    Mod.Instance.Logger.Error($"Failed to write track {trackPath} (embed) because {e}");
                    Mod.Instance.Logger.Exception(e);

                    return(null);
                }
            }
            else if (!string.IsNullOrEmpty(track.DownloadUrl))
            {
                var    request   = UnityEngine.Networking.UnityWebRequest.Get(track.DownloadUrl);
                byte[] file      = new byte[0];
                var    stopwatch = System.Diagnostics.Stopwatch.StartNew();

                var operation = request.Send();

                while (!operation.isDone)
                {
                    if (stopwatch.ElapsedMilliseconds > mod_.Config.MaxMusicDownloadTimeMilli)
                    {
                        request.Abort();
                        Mod.Instance.Logger.Warning($"Failed to download {track.Name}: it took too long!");
                        break;
                    }
                    else if (request.downloadedBytes >= (ulong)mod_.Config.MaxMusicDownloadSizeBytes)
                    {
                        request.Abort();
                        Mod.Instance.Logger.Warning($"Failed to download {track.Name}: it is too big!");
                        break;
                    }
                }

                stopwatch.Stop();

                if (operation.isDone)
                {
                    if (request.isError)
                    {
                        Mod.Instance.Logger.Error($"Failed to download {track.Name}: Error {request.error}");
                    }
                    else
                    {
                        file = request.downloadHandler.data;
                    }
                }

                request.Dispose();

                if (file.Length > 0)
                {
                    try
                    {
                        FileEx.WriteAllBytes(trackPath, file);
                        track.FileLocation = trackPath;
                    }
                    catch (Exception e)
                    {
                        Mod.Instance.Logger.Error($"Failed to write track {trackPath} (download) because {e}");
                        Mod.Instance.Logger.Exception(e);
                        return(null);
                    }
                }
                else
                {
                    Mod.Instance.Logger.Error($"Failed to download {track.Name}: no data!");
                }
            }
            else
            {
                Mod.Instance.Logger.Warning($"Impossible state when saving custom music track {track.Name}");
            }

            try
            {
                FileEx.WriteAllText(statePath, track.Version);
            }
            catch (Exception e)
            {
                Mod.Instance.Logger.Error($"Failed to write music state file {statePath} because {e}");
                Mod.Instance.Logger.Exception(e);
            }

            return(trackPath);
        }
Example #11
0
        internal static void Associate(LocalAppData appData, bool quiet = false, Form owner = default)
        {
            if (appData?.Settings?.FileTypes?.Any() != true)
            {
                if (!quiet)
                {
                    MessageBoxEx.Show(owner, Language.GetText(nameof(en_US.associateBtnMsg)), Resources.GlobalTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                return;
            }

            if (!Elevation.IsAdministrator)
            {
                if (owner != default)
                {
                    owner.TopMost = false;
                    owner.Enabled = false;
                    TaskBarProgress.SetState(owner.Handle, TaskBarProgressState.Indeterminate);
                }
                _bw?.Dispose();
                _bw         = new BackgroundWorker();
                _bw.DoWork += (sender, args) =>
                {
                    using (var process = ProcessEx.Start(PathEx.LocalPath, $"{ActionGuid.FileTypeAssociation} \"{appData.Key}\"", true, false))
                        if (!process?.HasExited == true)
                        {
                            process.WaitForExit();
                        }
                };
                _bw.RunWorkerCompleted += (sender, args) =>
                {
                    if (owner == default)
                    {
                        return;
                    }
                    TaskBarProgress.SetState(owner.Handle, TaskBarProgressState.NoProgress);
                    if (WinApi.NativeHelper.GetForegroundWindow() != owner.Handle)
                    {
                        WinApi.NativeHelper.SetForegroundWindow(owner.Handle);
                    }
                    owner.Enabled = true;
                    owner.TopMost = true;
                };
                _bw.RunWorkerAsync();
                return;
            }

            var assocData = new FileTypeAssocData
            {
                AppKey    = appData.Key,
                InstallId = Settings.SystemInstallId
            };

            using (var dialog = new IconBrowserDialog(Settings.IconResourcePath, Settings.Window.Colors.BaseDark, Settings.Window.Colors.ControlText, Settings.Window.Colors.Button, Settings.Window.Colors.ButtonText, Settings.Window.Colors.ButtonHover))
            {
                dialog.TopMost = true;
                dialog.Plus();
                dialog.ShowDialog();
                if (!string.IsNullOrEmpty(dialog.IconPath))
                {
                    assocData.IconPath = dialog.IconPath;
                    assocData.IconId   = dialog.IconId.ToString(CultureInfo.InvariantCulture);
                }
            }

            if (!FileEx.Exists(assocData.IconPath) || string.IsNullOrEmpty(assocData.IconId))
            {
                goto Cancel;
            }

            MessageBoxEx.ButtonText.OverrideEnabled = true;
            MessageBoxEx.ButtonText.Yes             = "App";
            MessageBoxEx.ButtonText.No     = "Launcher";
            MessageBoxEx.ButtonText.Cancel = Language.GetText(nameof(en_US.Cancel));
            var result = !quiet?MessageBoxEx.Show(Language.GetText(nameof(en_US.AssociateAppWayQuestion)), Resources.GlobalTitle, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) : DialogResult.Yes;

            switch (result)
            {
            case DialogResult.Yes:
                assocData.StarterPath = EnvironmentEx.GetVariablePathFull(appData.FilePath, false, false);
                break;

            case DialogResult.No:
                assocData.StarterPath = EnvironmentEx.GetVariablePathFull(PathEx.LocalPath, false, false);
                break;

            default:
                goto Cancel;
            }

            if (FileEx.Exists(assocData.StarterPath))
            {
                appData.Settings.FileTypeAssoc = assocData;
            }
            else
            {
                goto Cancel;
            }

            assocData = appData.Settings?.FileTypeAssoc;
            assocData?.SystemRegistryAccess?.AssociateFileTypes(false);
            return;

Cancel:
            if (!quiet)
            {
                MessageBoxEx.Show(owner, Language.GetText(nameof(en_US.OperationCanceledMsg)), MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        protected override async Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            var packagePath = context.ResolvePath(this.PackagePath);

            this.LogInformation($"Pushing {packagePath} to {this.ServerUrl}...");

            if (!FileEx.Exists(packagePath))
            {
                this.LogError(packagePath + " does not exist.");
                return(null);
            }

            var handler = new HttpClientHandler {
                Proxy = WebRequest.DefaultWebProxy
            };

            if (string.IsNullOrWhiteSpace(this.UserName) || string.IsNullOrEmpty(this.Password))
            {
                this.LogDebug("No credentials specified; sending default credentials.");
                handler.PreAuthenticate       = true;
                handler.UseDefaultCredentials = true;
            }

            using (var client = new HttpClient(handler))
            {
                client.DefaultRequestHeaders.UserAgent.Clear();
                client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("BuildMaster", typeof(Operation).Assembly.GetName().Version.ToString()));
                client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("NuGet-Extension", typeof(PublishPackageOperation).Assembly.GetName().Version.ToString()));

                if (!string.IsNullOrWhiteSpace(this.ApiKey))
                {
                    this.LogDebug("API key is specified; adding X-NuGet-ApiKey request header.");
                    client.DefaultRequestHeaders.Add("X-NuGet-ApiKey", this.ApiKey);
                }

                if (!string.IsNullOrWhiteSpace(this.UserName) && !string.IsNullOrEmpty(this.Password))
                {
                    this.LogDebug($"Sending basic auth credentials (user={this.UserName}).");
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(InedoLib.UTF8Encoding.GetBytes(this.UserName + ":" + this.Password)));
                }

                using (var packageStream = FileEx.Open(packagePath, FileMode.Open, FileAccess.Read, FileShare.Read, FileOptions.SequentialScan | FileOptions.Asynchronous))
                    using (var contentStream = new StreamContent(packageStream))
                        using (var formData = new MultipartFormDataContent())
                        {
                            contentStream.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                            formData.Add(contentStream, "package", "package");
                            using (var response = await client.PutAsync(this.ServerUrl, formData, context.CancellationToken).ConfigureAwait(false))
                            {
                                if (response.IsSuccessStatusCode)
                                {
                                    this.LogInformation("Package pushed!");
                                }
                                else
                                {
                                    this.LogError($"Server responded with {(int)response.StatusCode}: {response.ReasonPhrase}");
                                    this.LogError(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
                                }
                            }
                        }
            }

            return(null);
        }
Example #13
0
 /// <summary>
 ///     Combines <see cref="Directory.Exists(string)"/> and <see cref="File.Exists(string)"/>
 ///     to determine whether the specified path element exists.
 /// </summary>
 /// <param name="path">
 ///     The file or directory to check.
 /// </param>
 public static bool DirOrFileExists(string path) =>
 DirectoryEx.Exists(path) || FileEx.Exists(path);
Example #14
0
 /// <summary>
 ///     Determines whether the specified path is specified as file.
 /// </summary>
 /// <param name="path">
 ///     The path to check.
 /// </param>
 public static bool IsFile(string path) =>
 FileEx.Exists(path) && !FileEx.MatchAttributes(path, FileAttributes.Directory);
Example #15
0
        public override Task TagAsync(string tag, string commit, string message, bool force = false)
        {
            try
            {
                this.BeginOperation();

                this.log.LogDebug($"Using repository at '{this.repository.LocalRepositoryPath}'...");
                using (var repository = new Repository(this.repository.LocalRepositoryPath))
                {
                    Tag createdTag;
                    if (string.IsNullOrEmpty(message))
                    {
                        // lightweight tag
                        if (string.IsNullOrEmpty(commit))
                        {
                            this.log.LogDebug($"Creating lightweight tag \"{tag}\"...");
                            createdTag = repository.Tags.Add(tag, repository.Head.Tip, force);
                        }
                        else
                        {
                            this.log.LogDebug($"Creating lightweight tag \"{tag}\" for commit {commit}...");
                            createdTag = repository.Tags.Add(tag, commit, force);
                        }
                    }
                    else
                    {
                        var signature = repository.Config.BuildSignature(DateTimeOffset.Now);
                        if (signature == null)
                        {
                            var hostname = "example.com";
                            if (Uri.TryCreate(SDK.BaseUrl, UriKind.Absolute, out var baseUrl))
                            {
                                hostname = baseUrl.Host;
                            }

                            signature = new Signature(SDK.ProductName, SDK.ProductName.ToLower() + "@" + hostname, DateTimeOffset.Now);

                            var gitConfigPath = PathEx.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".gitconfig");
                            this.log.LogWarning($"git is not configured on this server. Using default values for name and email.");
                            this.log.LogDebug($"To change these values, {(FileEx.Exists(gitConfigPath) ? "edit" : "create")} '{gitConfigPath}' {(FileEx.Exists(gitConfigPath) ? "to add" : "with")} contents similar to the following:");
                            this.log.LogDebug($"[user]\n\tname = {signature.Name}\n\temail = {signature.Email}");
                        }

                        // annotated tag
                        if (string.IsNullOrEmpty(commit))
                        {
                            this.log.LogDebug($"Creating annotated tag \"{tag}\" with message \"{message}\"...");
                            createdTag = repository.Tags.Add(tag, repository.Head.Tip, signature, message, force);
                        }
                        else
                        {
                            this.log.LogDebug($"Creating annotated tag \"{tag}\" for commit {commit} with message \"{message}\"...");
                            createdTag = repository.Tags.Add(tag, commit, signature, message, force);
                        }
                    }

                    this.log.LogDebug($"Pushing '{createdTag.CanonicalName}' to remote 'origin'...");

                    var pushRef = $"{createdTag.CanonicalName}:{createdTag.CanonicalName}";

                    repository.Network.Push(
                        repository.Network.Remotes["origin"],
                        force ? '+' + pushRef : pushRef,
                        new PushOptions {
                        CredentialsProvider = this.CredentialsHandler
                    }
                        );
                }

                return(Complete);
            }
            catch (Exception ex)
            {
                // gitsharp exceptions are not always serializable
                throw new ExecutionFailureException("Tag failed: " + ex.Message);
            }
            finally
            {
                this.EndOperation();
            }
        }