System.Exception.ToString()

Here are the examples of the csharp api System.Exception.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

9382 Examples 7

19 Source : GitSourceProvider.cs
with MIT License
from actions

public async Task GetSourceAsync(
            RunnerActionPluginExecutionContext executionContext,
            string repositoryPath,
            string repoFullName,
            string sourceBranch,
            string sourceVersion,
            bool clean,
            string submoduleInput,
            int fetchDepth,
            bool gitLfsSupport,
            string accessToken,
            CancellationToken cancellationToken)
        {
            // Validate args.
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            executionContext.Output($"Syncing repository: {repoFullName}");

            // Repository URL
            var githubUrl = executionContext.GetGitHubContext("server_url");
            var githubUri = new Uri(!string.IsNullOrEmpty(githubUrl) ? githubUrl : "https://github.com");
            var portInfo = githubUri.IsDefaultPort ? string.Empty : $":{githubUri.Port}";
            Uri repositoryUrl = new Uri($"{githubUri.Scheme}://{githubUri.Host}{portInfo}/{repoFullName}");
            if (!repositoryUrl.IsAbsoluteUri)
            {
                throw new InvalidOperationException("Repository url need to be an absolute uri.");
            }

            string targetPath = repositoryPath;

            // input Submodules can be ['', true, false, recursive]
            // '' or false indicate don't checkout submodules
            // true indicate checkout top level submodules
            // recursive indicate checkout submodules recursively 
            bool checkoutSubmodules = false;
            bool checkoutNestedSubmodules = false;
            if (!string.IsNullOrEmpty(submoduleInput))
            {
                if (string.Equals(submoduleInput, Pipelines.PipelineConstants.CheckoutTaskInputs.SubmodulesOptions.Recursive, StringComparison.OrdinalIgnoreCase))
                {
                    checkoutSubmodules = true;
                    checkoutNestedSubmodules = true;
                }
                else
                {
                    checkoutSubmodules = StringUtil.ConvertToBoolean(submoduleInput);
                }
            }

            executionContext.Debug($"repository url={repositoryUrl}");
            executionContext.Debug($"targetPath={targetPath}");
            executionContext.Debug($"sourceBranch={sourceBranch}");
            executionContext.Debug($"sourceVersion={sourceVersion}");
            executionContext.Debug($"clean={clean}");
            executionContext.Debug($"checkoutSubmodules={checkoutSubmodules}");
            executionContext.Debug($"checkoutNestedSubmodules={checkoutNestedSubmodules}");
            executionContext.Debug($"fetchDepth={fetchDepth}");
            executionContext.Debug($"gitLfsSupport={gitLfsSupport}");

            // Initialize git command manager with additional environment variables.
            Dictionary<string, string> gitEnv = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            // Disable prompting for git credential manager
            gitEnv["GCM_INTERACTIVE"] = "Never";

            // Git-lfs will try to pull down replacedet if any of the local/user/system setting exist.
            // If customer didn't enable `LFS` in their pipeline definition, we will use ENV to disable LFS fetch/checkout.
            if (!gitLfsSupport)
            {
                gitEnv["GIT_LFS_SKIP_SMUDGE"] = "1";
            }

            // Add the public variables.
            foreach (var variable in executionContext.Variables)
            {
                // Add the variable using the formatted name.
                string formattedKey = (variable.Key ?? string.Empty).Replace('.', '_').Replace(' ', '_').ToUpperInvariant();
                gitEnv[formattedKey] = variable.Value?.Value ?? string.Empty;
            }

            GitCliManager gitCommandManager = new GitCliManager(gitEnv);
            await gitCommandManager.LoadGitExecutionInfo(executionContext);

            // Make sure the build machine met all requirements for the git repository
            // For now, the requirement we have are:
            // 1. git version greater than 2.9 since we need to use auth header.
            // 2. git-lfs version greater than 2.1 since we need to use auth header.
            // 3. git version greater than 2.14.2 if use SChannel for SSL backend (Windows only)
            RequirementCheck(executionContext, gitCommandManager, gitLfsSupport);

            // prepare askpreplaced for client cert private key, if the repository's endpoint url match the runner config url
            var systemConnection = executionContext.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));

            // Check the current contents of the root folder to see if there is already a repo
            // If there is a repo, see if it matches the one we are expecting to be there based on the remote fetch url
            // if the repo is not what we expect, remove the folder
            if (!await IsRepositoryOriginUrlMatch(executionContext, gitCommandManager, targetPath, repositoryUrl))
            {
                // Delete source folder
                IOUtil.DeleteDirectory(targetPath, cancellationToken);
            }
            else
            {
                // delete the index.lock file left by previous canceled build or any operation cause git.exe crash last time.
                string lockFile = Path.Combine(targetPath, ".git\\index.lock");
                if (File.Exists(lockFile))
                {
                    try
                    {
                        File.Delete(lockFile);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug($"Unable to delete the index.lock file: {lockFile}");
                        executionContext.Debug(ex.ToString());
                    }
                }

                // delete the shallow.lock file left by previous canceled build or any operation cause git.exe crash last time.		
                string shallowLockFile = Path.Combine(targetPath, ".git\\shallow.lock");
                if (File.Exists(shallowLockFile))
                {
                    try
                    {
                        File.Delete(shallowLockFile);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug($"Unable to delete the shallow.lock file: {shallowLockFile}");
                        executionContext.Debug(ex.ToString());
                    }
                }

                // When repo.clean is selected for a git repo, execute git clean -ffdx and git reset --hard HEAD on the current repo.
                // This will help us save the time to reclone the entire repo.
                // If any git commands exit with non-zero return code or any exception happened during git.exe invoke, fall back to delete the repo folder.
                if (clean)
                {
                    Boolean softCleanSucceed = true;

                    // git clean -ffdx
                    int exitCode_clean = await gitCommandManager.GitClean(executionContext, targetPath);
                    if (exitCode_clean != 0)
                    {
                        executionContext.Debug($"'git clean -ffdx' failed with exit code {exitCode_clean}, this normally caused by:\n    1) Path too long\n    2) Permission issue\n    3) File in use\nFor futher investigation, manually run 'git clean -ffdx' on repo root: {targetPath} after each build.");
                        softCleanSucceed = false;
                    }

                    // git reset --hard HEAD
                    if (softCleanSucceed)
                    {
                        int exitCode_reset = await gitCommandManager.GitReset(executionContext, targetPath);
                        if (exitCode_reset != 0)
                        {
                            executionContext.Debug($"'git reset --hard HEAD' failed with exit code {exitCode_reset}\nFor futher investigation, manually run 'git reset --hard HEAD' on repo root: {targetPath} after each build.");
                            softCleanSucceed = false;
                        }
                    }

                    // git clean -ffdx and git reset --hard HEAD for each submodule
                    if (checkoutSubmodules)
                    {
                        if (softCleanSucceed)
                        {
                            int exitCode_submoduleclean = await gitCommandManager.GitSubmoduleClean(executionContext, targetPath);
                            if (exitCode_submoduleclean != 0)
                            {
                                executionContext.Debug($"'git submodule foreach git clean -ffdx' failed with exit code {exitCode_submoduleclean}\nFor futher investigation, manually run 'git submodule foreach git clean -ffdx' on repo root: {targetPath} after each build.");
                                softCleanSucceed = false;
                            }
                        }

                        if (softCleanSucceed)
                        {
                            int exitCode_submodulereset = await gitCommandManager.GitSubmoduleReset(executionContext, targetPath);
                            if (exitCode_submodulereset != 0)
                            {
                                executionContext.Debug($"'git submodule foreach git reset --hard HEAD' failed with exit code {exitCode_submodulereset}\nFor futher investigation, manually run 'git submodule foreach git reset --hard HEAD' on repo root: {targetPath} after each build.");
                                softCleanSucceed = false;
                            }
                        }
                    }

                    if (!softCleanSucceed)
                    {
                        //fall back
                        executionContext.Warning("Unable to run \"git clean -ffdx\" and \"git reset --hard HEAD\" successfully, delete source folder instead.");
                        IOUtil.DeleteDirectory(targetPath, cancellationToken);
                    }
                }
            }

            // if the folder is missing, create it
            if (!Directory.Exists(targetPath))
            {
                Directory.CreateDirectory(targetPath);
            }

            // if the folder contains a .git folder, it means the folder contains a git repo that matches the remote url and in a clean state.
            // we will run git fetch to update the repo.
            if (!Directory.Exists(Path.Combine(targetPath, ".git")))
            {
                // init git repository
                int exitCode_init = await gitCommandManager.GitInit(executionContext, targetPath);
                if (exitCode_init != 0)
                {
                    throw new InvalidOperationException($"Unable to use git.exe init repository under {targetPath}, 'git init' failed with exit code: {exitCode_init}");
                }

                int exitCode_addremote = await gitCommandManager.GitRemoteAdd(executionContext, targetPath, "origin", repositoryUrl.AbsoluteUri);
                if (exitCode_addremote != 0)
                {
                    throw new InvalidOperationException($"Unable to use git.exe add remote 'origin', 'git remote add' failed with exit code: {exitCode_addremote}");
                }
            }

            cancellationToken.ThrowIfCancellationRequested();

            // disable git auto gc
            int exitCode_disableGC = await gitCommandManager.GitDisableAutoGC(executionContext, targetPath);
            if (exitCode_disableGC != 0)
            {
                executionContext.Warning("Unable turn off git auto garbage collection, git fetch operation may trigger auto garbage collection which will affect the performance of fetching.");
            }

            // always remove any possible left extraheader setting from git config.
            if (await gitCommandManager.GitConfigExist(executionContext, targetPath, $"http.{repositoryUrl.AbsoluteUri}.extraheader"))
            {
                executionContext.Debug("Remove any extraheader setting from git config.");
                await RemoveGitConfig(executionContext, gitCommandManager, targetPath, $"http.{repositoryUrl.AbsoluteUri}.extraheader", string.Empty);
            }

            List<string> additionalFetchArgs = new List<string>();
            List<string> additionalLfsFetchArgs = new List<string>();

            // add accessToken as basic auth header to handle auth challenge. 
            if (!string.IsNullOrEmpty(accessToken))
            {
                additionalFetchArgs.Add($"-c http.extraheader=\"AUTHORIZATION: {GenerateBasicAuthHeader(executionContext, accessToken)}\"");
            }

            // Prepare gitlfs url for fetch and checkout
            if (gitLfsSupport)
            {
                // Initialize git lfs by execute 'git lfs install'
                executionContext.Debug("Setup the local Git hooks for Git LFS.");
                int exitCode_lfsInstall = await gitCommandManager.GitLFSInstall(executionContext, targetPath);
                if (exitCode_lfsInstall != 0)
                {
                    throw new InvalidOperationException($"Git-lfs installation failed with exit code: {exitCode_lfsInstall}");
                }

                if (!string.IsNullOrEmpty(accessToken))
                {
                    string authorityUrl = repositoryUrl.AbsoluteUri.Replace(repositoryUrl.PathAndQuery, string.Empty);
                    additionalLfsFetchArgs.Add($"-c http.{authorityUrl}.extraheader=\"AUTHORIZATION: {GenerateBasicAuthHeader(executionContext, accessToken)}\"");
                }
            }

            List<string> additionalFetchSpecs = new List<string>();
            additionalFetchSpecs.Add("+refs/heads/*:refs/remotes/origin/*");

            if (IsPullRequest(sourceBranch))
            {
                additionalFetchSpecs.Add($"+{sourceBranch}:{GetRemoteRefName(sourceBranch)}");
            }

            int exitCode_fetch = await gitCommandManager.GitFetch(executionContext, targetPath, "origin", fetchDepth, additionalFetchSpecs, string.Join(" ", additionalFetchArgs), cancellationToken);
            if (exitCode_fetch != 0)
            {
                throw new InvalidOperationException($"Git fetch failed with exit code: {exitCode_fetch}");
            }

            // Checkout
            // sourceToBuild is used for checkout
            // if sourceBranch is a PR branch or sourceVersion is null, make sure branch name is a remote branch. we need checkout to detached head. 
            // (change refs/heads to refs/remotes/origin, refs/pull to refs/remotes/pull, or leave it as it when the branch name doesn't contain refs/...)
            // if sourceVersion provide, just use that for checkout, since when you checkout a commit, it will end up in detached head.
            cancellationToken.ThrowIfCancellationRequested();
            string sourcesToBuild;
            if (IsPullRequest(sourceBranch) || string.IsNullOrEmpty(sourceVersion))
            {
                sourcesToBuild = GetRemoteRefName(sourceBranch);
            }
            else
            {
                sourcesToBuild = sourceVersion;
            }

            // fetch lfs object upfront, this will avoid fetch lfs object during checkout which cause checkout taking forever
            // since checkout will fetch lfs object 1 at a time, while git lfs fetch will fetch lfs object in parallel.
            if (gitLfsSupport)
            {
                int exitCode_lfsFetch = await gitCommandManager.GitLFSFetch(executionContext, targetPath, "origin", sourcesToBuild, string.Join(" ", additionalLfsFetchArgs), cancellationToken);
                if (exitCode_lfsFetch != 0)
                {
                    // local repository is shallow repository, lfs fetch may fail due to lack of commits history.
                    // this will happen when the checkout commit is older than tip -> fetchDepth
                    if (fetchDepth > 0)
                    {
                        executionContext.Warning($"Git lfs fetch failed on shallow repository, this might because of git fetch with depth '{fetchDepth}' doesn't include the lfs fetch commit '{sourcesToBuild}'.");
                    }

                    // git lfs fetch failed, get lfs log, the log is critical for debug.
                    int exitCode_lfsLogs = await gitCommandManager.GitLFSLogs(executionContext, targetPath);
                    throw new InvalidOperationException($"Git lfs fetch failed with exit code: {exitCode_lfsFetch}. Git lfs logs returned with exit code: {exitCode_lfsLogs}.");
                }
            }

            // Finally, checkout the sourcesToBuild (if we didn't find a valid git object this will throw)
            int exitCode_checkout = await gitCommandManager.GitCheckout(executionContext, targetPath, sourcesToBuild, cancellationToken);
            if (exitCode_checkout != 0)
            {
                // local repository is shallow repository, checkout may fail due to lack of commits history.
                // this will happen when the checkout commit is older than tip -> fetchDepth
                if (fetchDepth > 0)
                {
                    executionContext.Warning($"Git checkout failed on shallow repository, this might because of git fetch with depth '{fetchDepth}' doesn't include the checkout commit '{sourcesToBuild}'.");
                }

                throw new InvalidOperationException($"Git checkout failed with exit code: {exitCode_checkout}");
            }

            // Submodule update
            if (checkoutSubmodules)
            {
                cancellationToken.ThrowIfCancellationRequested();

                int exitCode_submoduleSync = await gitCommandManager.GitSubmoduleSync(executionContext, targetPath, checkoutNestedSubmodules, cancellationToken);
                if (exitCode_submoduleSync != 0)
                {
                    throw new InvalidOperationException($"Git submodule sync failed with exit code: {exitCode_submoduleSync}");
                }

                List<string> additionalSubmoduleUpdateArgs = new List<string>();

                if (!string.IsNullOrEmpty(accessToken))
                {
                    string authorityUrl = repositoryUrl.AbsoluteUri.Replace(repositoryUrl.PathAndQuery, string.Empty);
                    additionalSubmoduleUpdateArgs.Add($"-c http.{authorityUrl}.extraheader=\"AUTHORIZATION: {GenerateBasicAuthHeader(executionContext, accessToken)}\"");
                }

                int exitCode_submoduleUpdate = await gitCommandManager.GitSubmoduleUpdate(executionContext, targetPath, fetchDepth, string.Join(" ", additionalSubmoduleUpdateArgs), checkoutNestedSubmodules, cancellationToken);
                if (exitCode_submoduleUpdate != 0)
                {
                    throw new InvalidOperationException($"Git submodule update failed with exit code: {exitCode_submoduleUpdate}");
                }
            }
        }

19 Source : WhichUtil.cs
with MIT License
from actions

public static string Which(string command, bool require = false, ITraceWriter trace = null, string prependPath = null)
        {
            ArgUtil.NotNullOrEmpty(command, nameof(command));
            trace?.Info($"Which: '{command}'");
            if (Path.IsPathFullyQualified(command) && File.Exists(command))
            {
                trace?.Info($"Fully qualified path: '{command}'");
                return command;
            }
            string path = Environment.GetEnvironmentVariable(PathUtil.PathVariable);
            if (string.IsNullOrEmpty(path))
            {
                trace?.Info("PATH environment variable not defined.");
                path = path ?? string.Empty;
            }
            if (!string.IsNullOrEmpty(prependPath))
            {
                path = PathUtil.PrependPath(prependPath, path);
            }

            string[] pathSegments = path.Split(new Char[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < pathSegments.Length; i++)
            {
                pathSegments[i] = Environment.ExpandEnvironmentVariables(pathSegments[i]);
            }

            foreach (string pathSegment in pathSegments)
            {
                if (!string.IsNullOrEmpty(pathSegment) && Directory.Exists(pathSegment))
                {
                    string[] matches = null;
#if OS_WINDOWS
                    string pathExt = Environment.GetEnvironmentVariable("PATHEXT");
                    if (string.IsNullOrEmpty(pathExt))
                    {
                        // XP's system default value for PATHEXT system variable
                        pathExt = ".com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh";
                    }

                    string[] pathExtSegments = pathExt.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

                    // if command already has an extension.
                    if (pathExtSegments.Any(ext => command.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
                    {
                        try
                        {
                            matches = Directory.GetFiles(pathSegment, command);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            trace?.Info("Ignore UnauthorizedAccess exception during Which.");
                            trace?.Verbose(ex.ToString());
                        }

                        if (matches != null && matches.Length > 0)
                        {
                            trace?.Info($"Location: '{matches.First()}'");
                            return matches.First();
                        }
                    }
                    else
                    {
                        string searchPattern;
                        searchPattern = StringUtil.Format($"{command}.*");
                        try
                        {
                            matches = Directory.GetFiles(pathSegment, searchPattern);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            trace?.Info("Ignore UnauthorizedAccess exception during Which.");
                            trace?.Verbose(ex.ToString());
                        }

                        if (matches != null && matches.Length > 0)
                        {
                            // add extension.
                            for (int i = 0; i < pathExtSegments.Length; i++)
                            {
                                string fullPath = Path.Combine(pathSegment, $"{command}{pathExtSegments[i]}");
                                if (matches.Any(p => p.Equals(fullPath, StringComparison.OrdinalIgnoreCase)))
                                {
                                    trace?.Info($"Location: '{fullPath}'");
                                    return fullPath;
                                }
                            }
                        }
                    }
#else
                    try
                    {
                        matches = Directory.GetFiles(pathSegment, command);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        trace?.Info("Ignore UnauthorizedAccess exception during Which.");
                        trace?.Verbose(ex.ToString());
                    }

                    if (matches != null && matches.Length > 0)
                    {
                        trace?.Info($"Location: '{matches.First()}'");
                        return matches.First();
                    }
#endif
                }
            }

#if OS_WINDOWS
            trace?.Info($"{command}: command not found. Make sure '{command}' is installed and its location included in the 'Path' environment variable.");
#else
            trace?.Info($"{command}: command not found. Make sure '{command}' is installed and its location included in the 'PATH' environment variable.");
#endif
            if (require)
            {
                throw new FileNotFoundException(
                    message: $"{command}: command not found",
                    fileName: command);
            }

            return null;
        }

19 Source : FileContainerServer.cs
with MIT License
from actions

private async Task<UploadResult> UploadAsync(RunnerActionPluginExecutionContext context, int uploaderId, CancellationToken token)
        {
            List<string> failedFiles = new List<string>();
            long uploadedSize = 0;
            string fileToUpload;
            Stopwatch uploadTimer = new Stopwatch();
            while (_fileUploadQueue.TryDequeue(out fileToUpload))
            {
                token.ThrowIfCancellationRequested();
                try
                {
                    using (FileStream fs = File.Open(fileToUpload, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        string itemPath = (_containerPath.TrimEnd('/') + "/" + fileToUpload.Remove(0, _sourceParentDirectory.Length + 1)).Replace('\\', '/');
                        bool failAndExit = false;
                        try
                        {
                            uploadTimer.Restart();
                            using (HttpResponseMessage response = await _fileContainerHttpClient.UploadFileAsync(_containerId, itemPath, fs, _projectId, cancellationToken: token, chunkSize: 4 * 1024 * 1024))
                            {
                                if (response == null || response.StatusCode != HttpStatusCode.Created)
                                {
                                    context.Output($"Unable to copy file to server StatusCode={response?.StatusCode}: {response?.ReasonPhrase}. Source file path: {fileToUpload}. Target server path: {itemPath}");

                                    if (response?.StatusCode == HttpStatusCode.Conflict)
                                    {
                                        // fail upload task but continue with any other files
                                        context.Error($"Error '{fileToUpload}' has already been uploaded.");
                                    }
                                    else if (_fileContainerHttpClient.IsFastFailResponse(response))
                                    {
                                        // Fast fail: we received an http status code where we should abandon our efforts
                                        context.Output($"Cannot continue uploading files, so draining upload queue of {_fileUploadQueue.Count} items.");
                                        DrainUploadQueue(context);
                                        failedFiles.Clear();
                                        failAndExit = true;
                                        throw new UploadFailedException($"Critical failure uploading '{fileToUpload}'");
                                    }
                                    else
                                    {
                                        context.Debug($"Adding '{fileToUpload}' to retry list.");
                                        failedFiles.Add(fileToUpload);
                                    }
                                    throw new UploadFailedException($"Http failure response '{response?.StatusCode}': '{response?.ReasonPhrase}' while uploading '{fileToUpload}'");
                                }

                                uploadTimer.Stop();
                                context.Debug($"File: '{fileToUpload}' took {uploadTimer.ElapsedMilliseconds} milliseconds to finish upload");
                                uploadedSize += fs.Length;
                                OutputLogForFile(context, fileToUpload, $"Detail upload trace for file: {itemPath}", context.Debug);
                            }
                        }
                        catch (OperationCanceledException) when (token.IsCancellationRequested)
                        {
                            context.Output($"File upload has been cancelled during upload file: '{fileToUpload}'.");
                            throw;
                        }
                        catch (Exception ex)
                        {
                            context.Output($"Fail to upload '{fileToUpload}' due to '{ex.Message}'.");
                            context.Output(ex.ToString());

                            OutputLogForFile(context, fileToUpload, $"Detail upload trace for file that fail to upload: {itemPath}", context.Output);

                            if (failAndExit)
                            {
                                context.Debug("Exiting upload.");
                                throw;
                            }
                        }
                    }

                    Interlocked.Increment(ref _uploadFilesProcessed);
                }
                catch (Exception ex)
                {
                    context.Output($"File error '{ex.Message}' when uploading file '{fileToUpload}'.");
                    throw ex;
                }
            }

            return new UploadResult(failedFiles, uploadedSize);
        }

19 Source : RepositoryPlugin.cs
with MIT License
from actions

public async Task RunAsync(RunnerActionPluginExecutionContext executionContext, CancellationToken token)
        {
            string runnerWorkspace = executionContext.GetRunnerContext("workspace");
            ArgUtil.Directory(runnerWorkspace, nameof(runnerWorkspace));
            string tempDirectory = executionContext.GetRunnerContext("temp");
            ArgUtil.Directory(tempDirectory, nameof(tempDirectory));

            var repoFullName = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Repository);
            if (string.IsNullOrEmpty(repoFullName))
            {
                repoFullName = executionContext.GetGitHubContext("repository");
            }

            var repoFullNameSplit = repoFullName.Split("/", StringSplitOptions.RemoveEmptyEntries);
            if (repoFullNameSplit.Length != 2)
            {
                throw new ArgumentOutOfRangeException(repoFullName);
            }

            string expectRepoPath;
            var path = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Path);
            if (!string.IsNullOrEmpty(path))
            {
                expectRepoPath = IOUtil.ResolvePath(runnerWorkspace, path);
                if (!expectRepoPath.StartsWith(runnerWorkspace.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar))
                {
                    throw new ArgumentException($"Input path '{path}' should resolve to a directory under '{runnerWorkspace}', current resolved path '{expectRepoPath}'.");
                }
            }
            else
            {
                // When repository doesn't has path set, default to sources directory 1/repoName
                expectRepoPath = Path.Combine(runnerWorkspace, repoFullNameSplit[1]);
            }

            var workspaceRepo = executionContext.GetGitHubContext("repository");
            // for self repository, we need to let the worker knows where it is after checkout.
            if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
            {
                var workspaceRepoPath = executionContext.GetGitHubContext("workspace");

                executionContext.Debug($"Repository requires to be placed at '{expectRepoPath}', current location is '{workspaceRepoPath}'");
                if (!string.Equals(workspaceRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), expectRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), IOUtil.FilePathStringComparison))
                {
                    executionContext.Output($"Repository is current at '{workspaceRepoPath}', move to '{expectRepoPath}'.");
                    var count = 1;
                    var staging = Path.Combine(tempDirectory, $"_{count}");
                    while (Directory.Exists(staging))
                    {
                        count++;
                        staging = Path.Combine(tempDirectory, $"_{count}");
                    }

                    try
                    {
                        executionContext.Debug($"Move existing repository '{workspaceRepoPath}' to '{expectRepoPath}' via staging directory '{staging}'.");
                        IOUtil.MoveDirectory(workspaceRepoPath, expectRepoPath, staging, CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug("Catch exception during repository move.");
                        executionContext.Debug(ex.ToString());
                        executionContext.Warning("Unable move and reuse existing repository to required location.");
                        IOUtil.DeleteDirectory(expectRepoPath, CancellationToken.None);
                    }

                    executionContext.Output($"Repository will locate at '{expectRepoPath}'.");
                }

                executionContext.Debug($"Update workspace repository location.");
                executionContext.SetRepositoryPath(repoFullName, expectRepoPath, true);
            }

            string sourceBranch;
            string sourceVersion;
            string refInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Ref);
            if (string.IsNullOrEmpty(refInput))
            {
                sourceBranch = executionContext.GetGitHubContext("ref");
                sourceVersion = executionContext.GetGitHubContext("sha");
            }
            else
            {
                sourceBranch = refInput;
                sourceVersion = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Version);  // version get removed when checkout move to repo in the graph
                if (string.IsNullOrEmpty(sourceVersion) && RegexUtility.IsMatch(sourceBranch, WellKnownRegularExpressions.SHA1))
                {
                    sourceVersion = sourceBranch;

                    // If Ref is a SHA and the repo is self, we need to use github.ref as source branch since it might be refs/pull/*
                    if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceBranch = executionContext.GetGitHubContext("ref");
                    }
                    else
                    {
                        sourceBranch = "refs/heads/master";
                    }
                }
            }

            bool clean = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Clean), true);
            string submoduleInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Submodules);

            int fetchDepth = 0;
            if (!int.TryParse(executionContext.GetInput("fetch-depth"), out fetchDepth) || fetchDepth < 0)
            {
                fetchDepth = 0;
            }

            bool gitLfsSupport = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Lfs));
            string accessToken = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Token);
            if (string.IsNullOrEmpty(accessToken))
            {
                accessToken = executionContext.GetGitHubContext("token");
            }

            // register problem matcher
            string problemMatcher = @"    
{
    ""problemMatcher"": [
        {
            ""owner"": ""checkout-git"",
            ""pattern"": [
                {
                    ""regexp"": ""^fatal: (.*)$"",
                    ""message"": 1
                }
            ]
        }
    ]
}";
            string matcherFile = Path.Combine(tempDirectory, $"git_{Guid.NewGuid()}.json");
            File.WriteAllText(matcherFile, problemMatcher, new UTF8Encoding(false));
            executionContext.Output($"##[add-matcher]{matcherFile}");
            try
            {
                await new GitHubSourceProvider().GetSourceAsync(executionContext,
                                                                expectRepoPath,
                                                                repoFullName,
                                                                sourceBranch,
                                                                sourceVersion,
                                                                clean,
                                                                submoduleInput,
                                                                fetchDepth,
                                                                gitLfsSupport,
                                                                accessToken,
                                                                token);
            }
            finally
            {
                executionContext.Output("##[remove-matcher owner=checkout-git]");
            }
        }

19 Source : GitSourceProvider.cs
with MIT License
from actions

public async Task GetSourceAsync(
            RunnerActionPluginExecutionContext executionContext,
            string repositoryPath,
            string repoFullName,
            string sourceBranch,
            string sourceVersion,
            bool clean,
            string submoduleInput,
            int fetchDepth,
            bool gitLfsSupport,
            string accessToken,
            CancellationToken cancellationToken)
        {
            // Validate args.
            ArgUtil.NotNull(executionContext, nameof(executionContext));
            Dictionary<string, string> configModifications = new Dictionary<string, string>();
            executionContext.Output($"Syncing repository: {repoFullName}");
            Uri repositoryUrl = new Uri($"https://github.com/{repoFullName}");
            if (!repositoryUrl.IsAbsoluteUri)
            {
                throw new InvalidOperationException("Repository url need to be an absolute uri.");
            }

            string targetPath = repositoryPath;

            // input Submodules can be ['', true, false, recursive]
            // '' or false indicate don't checkout submodules
            // true indicate checkout top level submodules
            // recursive indicate checkout submodules recursively 
            bool checkoutSubmodules = false;
            bool checkoutNestedSubmodules = false;
            if (!string.IsNullOrEmpty(submoduleInput))
            {
                if (string.Equals(submoduleInput, Pipelines.PipelineConstants.CheckoutTaskInputs.SubmodulesOptions.Recursive, StringComparison.OrdinalIgnoreCase))
                {
                    checkoutSubmodules = true;
                    checkoutNestedSubmodules = true;
                }
                else
                {
                    checkoutSubmodules = StringUtil.ConvertToBoolean(submoduleInput);
                }
            }

            executionContext.Debug($"repository url={repositoryUrl}");
            executionContext.Debug($"targetPath={targetPath}");
            executionContext.Debug($"sourceBranch={sourceBranch}");
            executionContext.Debug($"sourceVersion={sourceVersion}");
            executionContext.Debug($"clean={clean}");
            executionContext.Debug($"checkoutSubmodules={checkoutSubmodules}");
            executionContext.Debug($"checkoutNestedSubmodules={checkoutNestedSubmodules}");
            executionContext.Debug($"fetchDepth={fetchDepth}");
            executionContext.Debug($"gitLfsSupport={gitLfsSupport}");

            // Initialize git command manager with additional environment variables.
            Dictionary<string, string> gitEnv = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            // Disable git prompt
            gitEnv["GIT_TERMINAL_PROMPT"] = "0";

            // Disable prompting for git credential manager
            gitEnv["GCM_INTERACTIVE"] = "Never";

            // Git-lfs will try to pull down replacedet if any of the local/user/system setting exist.
            // If customer didn't enable `LFS` in their pipeline definition, we will use ENV to disable LFS fetch/checkout.
            if (!gitLfsSupport)
            {
                gitEnv["GIT_LFS_SKIP_SMUDGE"] = "1";
            }

            // Add the public variables.
            foreach (var variable in executionContext.Variables)
            {
                // Add the variable using the formatted name.
                string formattedKey = (variable.Key ?? string.Empty).Replace('.', '_').Replace(' ', '_').ToUpperInvariant();
                gitEnv[formattedKey] = variable.Value?.Value ?? string.Empty;
            }

            GitCliManager gitCommandManager = new GitCliManager(gitEnv);
            await gitCommandManager.LoadGitExecutionInfo(executionContext);

            // Make sure the build machine met all requirements for the git repository
            // For now, the requirement we have are:
            // 1. git version greater than 2.9 since we need to use auth header.
            // 2. git-lfs version greater than 2.1 since we need to use auth header.
            // 3. git version greater than 2.14.2 if use SChannel for SSL backend (Windows only)
            RequirementCheck(executionContext, gitCommandManager, gitLfsSupport);

            // prepare askpreplaced for client cert private key, if the repository's endpoint url match the runner config url
            var systemConnection = executionContext.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));

            // Check the current contents of the root folder to see if there is already a repo
            // If there is a repo, see if it matches the one we are expecting to be there based on the remote fetch url
            // if the repo is not what we expect, remove the folder
            if (!await IsRepositoryOriginUrlMatch(executionContext, gitCommandManager, targetPath, repositoryUrl))
            {
                // Delete source folder
                IOUtil.DeleteDirectory(targetPath, cancellationToken);
            }
            else
            {
                // delete the index.lock file left by previous canceled build or any operation cause git.exe crash last time.
                string lockFile = Path.Combine(targetPath, ".git\\index.lock");
                if (File.Exists(lockFile))
                {
                    try
                    {
                        File.Delete(lockFile);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug($"Unable to delete the index.lock file: {lockFile}");
                        executionContext.Debug(ex.ToString());
                    }
                }

                // delete the shallow.lock file left by previous canceled build or any operation cause git.exe crash last time.		
                string shallowLockFile = Path.Combine(targetPath, ".git\\shallow.lock");
                if (File.Exists(shallowLockFile))
                {
                    try
                    {
                        File.Delete(shallowLockFile);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug($"Unable to delete the shallow.lock file: {shallowLockFile}");
                        executionContext.Debug(ex.ToString());
                    }
                }

                // When repo.clean is selected for a git repo, execute git clean -ffdx and git reset --hard HEAD on the current repo.
                // This will help us save the time to reclone the entire repo.
                // If any git commands exit with non-zero return code or any exception happened during git.exe invoke, fall back to delete the repo folder.
                if (clean)
                {
                    Boolean softCleanSucceed = true;

                    // git clean -ffdx
                    int exitCode_clean = await gitCommandManager.GitClean(executionContext, targetPath);
                    if (exitCode_clean != 0)
                    {
                        executionContext.Debug($"'git clean -ffdx' failed with exit code {exitCode_clean}, this normally caused by:\n    1) Path too long\n    2) Permission issue\n    3) File in use\nFor futher investigation, manually run 'git clean -ffdx' on repo root: {targetPath} after each build.");
                        softCleanSucceed = false;
                    }

                    // git reset --hard HEAD
                    if (softCleanSucceed)
                    {
                        int exitCode_reset = await gitCommandManager.GitReset(executionContext, targetPath);
                        if (exitCode_reset != 0)
                        {
                            executionContext.Debug($"'git reset --hard HEAD' failed with exit code {exitCode_reset}\nFor futher investigation, manually run 'git reset --hard HEAD' on repo root: {targetPath} after each build.");
                            softCleanSucceed = false;
                        }
                    }

                    // git clean -ffdx and git reset --hard HEAD for each submodule
                    if (checkoutSubmodules)
                    {
                        if (softCleanSucceed)
                        {
                            int exitCode_submoduleclean = await gitCommandManager.GitSubmoduleClean(executionContext, targetPath);
                            if (exitCode_submoduleclean != 0)
                            {
                                executionContext.Debug($"'git submodule foreach git clean -ffdx' failed with exit code {exitCode_submoduleclean}\nFor futher investigation, manually run 'git submodule foreach git clean -ffdx' on repo root: {targetPath} after each build.");
                                softCleanSucceed = false;
                            }
                        }

                        if (softCleanSucceed)
                        {
                            int exitCode_submodulereset = await gitCommandManager.GitSubmoduleReset(executionContext, targetPath);
                            if (exitCode_submodulereset != 0)
                            {
                                executionContext.Debug($"'git submodule foreach git reset --hard HEAD' failed with exit code {exitCode_submodulereset}\nFor futher investigation, manually run 'git submodule foreach git reset --hard HEAD' on repo root: {targetPath} after each build.");
                                softCleanSucceed = false;
                            }
                        }
                    }

                    if (!softCleanSucceed)
                    {
                        //fall back
                        executionContext.Warning("Unable to run \"git clean -ffdx\" and \"git reset --hard HEAD\" successfully, delete source folder instead.");
                        IOUtil.DeleteDirectory(targetPath, cancellationToken);
                    }
                }
            }

            // if the folder is missing, create it
            if (!Directory.Exists(targetPath))
            {
                Directory.CreateDirectory(targetPath);
            }

            // if the folder contains a .git folder, it means the folder contains a git repo that matches the remote url and in a clean state.
            // we will run git fetch to update the repo.
            if (!Directory.Exists(Path.Combine(targetPath, ".git")))
            {
                // init git repository
                int exitCode_init = await gitCommandManager.GitInit(executionContext, targetPath);
                if (exitCode_init != 0)
                {
                    throw new InvalidOperationException($"Unable to use git.exe init repository under {targetPath}, 'git init' failed with exit code: {exitCode_init}");
                }

                int exitCode_addremote = await gitCommandManager.GitRemoteAdd(executionContext, targetPath, "origin", repositoryUrl.AbsoluteUri);
                if (exitCode_addremote != 0)
                {
                    throw new InvalidOperationException($"Unable to use git.exe add remote 'origin', 'git remote add' failed with exit code: {exitCode_addremote}");
                }
            }

            cancellationToken.ThrowIfCancellationRequested();

            // disable git auto gc
            int exitCode_disableGC = await gitCommandManager.GitDisableAutoGC(executionContext, targetPath);
            if (exitCode_disableGC != 0)
            {
                executionContext.Warning("Unable turn off git auto garbage collection, git fetch operation may trigger auto garbage collection which will affect the performance of fetching.");
            }

            // always remove any possible left extraheader setting from git config.
            if (await gitCommandManager.GitConfigExist(executionContext, targetPath, $"http.{repositoryUrl.AbsoluteUri}.extraheader"))
            {
                executionContext.Debug("Remove any extraheader setting from git config.");
                await RemoveGitConfig(executionContext, gitCommandManager, targetPath, $"http.{repositoryUrl.AbsoluteUri}.extraheader", string.Empty);
            }

            List<string> additionalFetchArgs = new List<string>();
            List<string> additionalLfsFetchArgs = new List<string>();

            // Add http.https://github.com.extraheader=... to gitconfig
            // accessToken as basic auth header to handle any auth challenge from github.com 
            string configKey = $"http.https://github.com/.extraheader";
            string configValue = $"\"AUTHORIZATION: {GenerateBasicAuthHeader(executionContext, accessToken)}\"";
            configModifications[configKey] = configValue.Trim('\"');
            int exitCode_config = await gitCommandManager.GitConfig(executionContext, targetPath, configKey, configValue);
            if (exitCode_config != 0)
            {
                throw new InvalidOperationException($"Git config failed with exit code: {exitCode_config}");
            }

            // Prepare gitlfs url for fetch and checkout
            if (gitLfsSupport)
            {
                // Initialize git lfs by execute 'git lfs install'
                executionContext.Debug("Setup the local Git hooks for Git LFS.");
                int exitCode_lfsInstall = await gitCommandManager.GitLFSInstall(executionContext, targetPath);
                if (exitCode_lfsInstall != 0)
                {
                    throw new InvalidOperationException($"Git-lfs installation failed with exit code: {exitCode_lfsInstall}");
                }
            }

            List<string> additionalFetchSpecs = new List<string>();
            additionalFetchSpecs.Add("+refs/heads/*:refs/remotes/origin/*");

            if (IsPullRequest(sourceBranch))
            {
                additionalFetchSpecs.Add($"+{sourceBranch}:{GetRemoteRefName(sourceBranch)}");
            }

            int exitCode_fetch = await gitCommandManager.GitFetch(executionContext, targetPath, "origin", fetchDepth, additionalFetchSpecs, string.Join(" ", additionalFetchArgs), cancellationToken);
            if (exitCode_fetch != 0)
            {
                throw new InvalidOperationException($"Git fetch failed with exit code: {exitCode_fetch}");
            }

            // Checkout
            // sourceToBuild is used for checkout
            // if sourceBranch is a PR branch or sourceVersion is null, make sure branch name is a remote branch. we need checkout to detached head. 
            // (change refs/heads to refs/remotes/origin, refs/pull to refs/remotes/pull, or leave it as it when the branch name doesn't contain refs/...)
            // if sourceVersion provide, just use that for checkout, since when you checkout a commit, it will end up in detached head.
            cancellationToken.ThrowIfCancellationRequested();
            string sourcesToBuild;
            if (IsPullRequest(sourceBranch) || string.IsNullOrEmpty(sourceVersion))
            {
                sourcesToBuild = GetRemoteRefName(sourceBranch);
            }
            else
            {
                sourcesToBuild = sourceVersion;
            }

            // fetch lfs object upfront, this will avoid fetch lfs object during checkout which cause checkout taking forever
            // since checkout will fetch lfs object 1 at a time, while git lfs fetch will fetch lfs object in parallel.
            if (gitLfsSupport)
            {
                int exitCode_lfsFetch = await gitCommandManager.GitLFSFetch(executionContext, targetPath, "origin", sourcesToBuild, string.Join(" ", additionalLfsFetchArgs), cancellationToken);
                if (exitCode_lfsFetch != 0)
                {
                    // local repository is shallow repository, lfs fetch may fail due to lack of commits history.
                    // this will happen when the checkout commit is older than tip -> fetchDepth
                    if (fetchDepth > 0)
                    {
                        executionContext.Warning($"Git lfs fetch failed on shallow repository, this might because of git fetch with depth '{fetchDepth}' doesn't include the lfs fetch commit '{sourcesToBuild}'.");
                    }

                    // git lfs fetch failed, get lfs log, the log is critical for debug.
                    int exitCode_lfsLogs = await gitCommandManager.GitLFSLogs(executionContext, targetPath);
                    throw new InvalidOperationException($"Git lfs fetch failed with exit code: {exitCode_lfsFetch}. Git lfs logs returned with exit code: {exitCode_lfsLogs}.");
                }
            }

            // Finally, checkout the sourcesToBuild (if we didn't find a valid git object this will throw)
            int exitCode_checkout = await gitCommandManager.GitCheckout(executionContext, targetPath, sourcesToBuild, cancellationToken);
            if (exitCode_checkout != 0)
            {
                // local repository is shallow repository, checkout may fail due to lack of commits history.
                // this will happen when the checkout commit is older than tip -> fetchDepth
                if (fetchDepth > 0)
                {
                    executionContext.Warning($"Git checkout failed on shallow repository, this might because of git fetch with depth '{fetchDepth}' doesn't include the checkout commit '{sourcesToBuild}'.");
                }

                throw new InvalidOperationException($"Git checkout failed with exit code: {exitCode_checkout}");
            }

            // Submodule update
            if (checkoutSubmodules)
            {
                cancellationToken.ThrowIfCancellationRequested();

                int exitCode_submoduleSync = await gitCommandManager.GitSubmoduleSync(executionContext, targetPath, checkoutNestedSubmodules, cancellationToken);
                if (exitCode_submoduleSync != 0)
                {
                    throw new InvalidOperationException($"Git submodule sync failed with exit code: {exitCode_submoduleSync}");
                }

                List<string> additionalSubmoduleUpdateArgs = new List<string>();

                int exitCode_submoduleUpdate = await gitCommandManager.GitSubmoduleUpdate(executionContext, targetPath, fetchDepth, string.Join(" ", additionalSubmoduleUpdateArgs), checkoutNestedSubmodules, cancellationToken);
                if (exitCode_submoduleUpdate != 0)
                {
                    throw new InvalidOperationException($"Git submodule update failed with exit code: {exitCode_submoduleUpdate}");
                }
            }

            // Set intra-task variable for post job cleanup
            executionContext.SetIntraActionState("repositoryPath", targetPath);
            executionContext.SetIntraActionState("modifiedgitconfig", JsonUtility.ToString(configModifications.Keys));
            foreach (var config in configModifications)
            {
                executionContext.SetIntraActionState(config.Key, config.Value);
            }
        }

19 Source : ProcessInvoker.cs
with MIT License
from actions

private void NixKillProcessTree()
        {
            try
            {
                if (_proc?.HasExited == false)
                {
                    _proc?.Kill();
                }
            }
            catch (InvalidOperationException ex)
            {
                Trace.Info("Ignore InvalidOperationException during Process.Kill().");
                Trace.Info(ex.ToString());
            }
        }

19 Source : RunnerService.cs
with MIT License
from actions

private void WriteException(Exception exception)
        {
            WriteToEventLog(exception.ToString(), EventLogEntryType.Error);
        }

19 Source : ExecutionContext.cs
with MIT License
from actions

public void CancelToken()
        {
            try
            {
                _cancellationTokenSource.Cancel();
            }
            catch (ObjectDisposedException e)
            {
                Trace.Info($"Attempted to cancel a disposed token, the execution is already complete: {e.ToString()}");
            }
        }

19 Source : JobExtension.cs
with MIT License
from actions

public void FinalizeJob(IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message, DateTime jobStartTimeUtc)
        {
            Trace.Entering();
            ArgUtil.NotNull(jobContext, nameof(jobContext));

            // create a new timeline record node for 'Finalize job'
            IExecutionContext context = jobContext.CreateChild(Guid.NewGuid(), "Complete job", $"{nameof(JobExtension)}_Final", null, null, ActionRunStage.Post);
            using (var register = jobContext.CancellationToken.Register(() => { context.CancelToken(); }))
            {
                try
                {
                    context.Start();
                    context.Debug("Starting: Complete job");

                    Trace.Info("Initialize Env context");

#if OS_WINDOWS
                    var envContext = new DictionaryContextData();
#else
                    var envContext = new CaseSensitiveDictionaryContextData();
#endif
                    context.ExpressionValues["env"] = envContext;
                    foreach (var pair in context.Global.EnvironmentVariables)
                    {
                        envContext[pair.Key] = new StringContextData(pair.Value ?? string.Empty);
                    }

                    // Populate env context for each step
                    Trace.Info("Initialize steps context");
                    context.ExpressionValues["steps"] = context.Global.StepsContext.GetScope(context.ScopeName);

                    var templateEvaluator = context.ToPipelineTemplateEvaluator();
                    // Evaluate job outputs
                    if (message.JobOutputs != null && message.JobOutputs.Type != TokenType.Null)
                    {
                        try
                        {
                            context.Output($"Evaluate and set job outputs");

                            // Populate env context for each step
                            Trace.Info("Initialize Env context for evaluating job outputs");

                            var outputs = templateEvaluator.EvaluateJobOutput(message.JobOutputs, context.ExpressionValues, context.ExpressionFunctions);
                            foreach (var output in outputs)
                            {
                                if (string.IsNullOrEmpty(output.Value))
                                {
                                    context.Debug($"Skip output '{output.Key}' since it's empty");
                                    continue;
                                }

                                if (!string.Equals(output.Value, HostContext.SecretMasker.MaskSecrets(output.Value)))
                                {
                                    context.Warning($"Skip output '{output.Key}' since it may contain secret.");
                                    continue;
                                }

                                context.Output($"Set output '{output.Key}'");
                                jobContext.JobOutputs[output.Key] = output.Value;
                            }
                        }
                        catch (Exception ex)
                        {
                            context.Result = TaskResult.Failed;
                            context.Error($"Fail to evaluate job outputs");
                            context.Error(ex);
                            jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, TaskResult.Failed);
                        }
                    }

                    // Evaluate environment data
                    if (jobContext.ActionsEnvironment?.Url != null && jobContext.ActionsEnvironment?.Url.Type != TokenType.Null)
                    {
                        try
                        {
                            context.Output($"Evaluate and set environment url");

                            var environmentUrlToken = templateEvaluator.EvaluateEnvironmentUrl(jobContext.ActionsEnvironment.Url, context.ExpressionValues, context.ExpressionFunctions);
                            var environmentUrl = environmentUrlToken.replacedertString("environment.url");
                            if (!string.Equals(environmentUrl.Value, HostContext.SecretMasker.MaskSecrets(environmentUrl.Value)))
                            {
                                context.Warning($"Skip setting environment url as environment '{jobContext.ActionsEnvironment.Name}' may contain secret.");
                            }
                            else
                            {
                                context.Output($"Evaluated environment url: {environmentUrl}");
                                jobContext.ActionsEnvironment.Url = environmentUrlToken;
                            }
                        }
                        catch (Exception ex)
                        {
                            context.Result = TaskResult.Failed;
                            context.Error($"Failed to evaluate environment url");
                            context.Error(ex);
                            jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, TaskResult.Failed);
                        }
                    }

                    if (context.Global.Variables.GetBoolean(Constants.Variables.Actions.RunnerDebug) ?? false)
                    {
                        Trace.Info("Support log upload starting.");
                        context.Output("Uploading runner diagnostic logs");

                        IDiagnosticLogManager diagnosticLogManager = HostContext.GetService<IDiagnosticLogManager>();

                        try
                        {
                            diagnosticLogManager.UploadDiagnosticLogs(executionContext: context, parentContext: jobContext, message: message, jobStartTimeUtc: jobStartTimeUtc);

                            Trace.Info("Support log upload complete.");
                            context.Output("Completed runner diagnostic log upload");
                        }
                        catch (Exception ex)
                        {
                            // Log the error but make sure we continue gracefully.
                            Trace.Info("Error uploading support logs.");
                            context.Output("Error uploading runner diagnostic logs");
                            Trace.Error(ex);
                        }
                    }

                    if (_processCleanup)
                    {
                        context.Output("Cleaning up orphan processes");

                        // Only check environment variable for any process that doesn't run before we invoke our process.
                        Dictionary<int, Process> currentProcesses = SnapshotProcesses();
                        foreach (var proc in currentProcesses)
                        {
                            if (proc.Key == Process.GetCurrentProcess().Id)
                            {
                                // skip for current process.
                                continue;
                            }

                            if (_existingProcesses.Contains($"{proc.Key}_{proc.Value.ProcessName}"))
                            {
                                Trace.Verbose($"Skip existing process. PID: {proc.Key} ({proc.Value.ProcessName})");
                            }
                            else
                            {
                                Trace.Info($"Inspecting process environment variables. PID: {proc.Key} ({proc.Value.ProcessName})");

                                string lookupId = null;
                                try
                                {
                                    lookupId = proc.Value.GetEnvironmentVariable(HostContext, Constants.ProcessTrackingId);
                                }
                                catch (Exception ex)
                                {
                                    Trace.Warning($"Ignore exception during read process environment variables: {ex.Message}");
                                    Trace.Verbose(ex.ToString());
                                }

                                if (string.Equals(lookupId, _processLookupId, StringComparison.OrdinalIgnoreCase))
                                {
                                    context.Output($"Terminate orphan process: pid ({proc.Key}) ({proc.Value.ProcessName})");
                                    try
                                    {
                                        proc.Value.Kill();
                                    }
                                    catch (Exception ex)
                                    {
                                        Trace.Error("Catch exception during orphan process cleanup.");
                                        Trace.Error(ex);
                                    }
                                }
                            }
                        }
                    }

                    if (_diskSpaceCheckTask != null)
                    {
                        _diskSpaceCheckToken.Cancel();
                    }
                }
                catch (Exception ex)
                {
                    // Log and ignore the error from JobExtension finalization.
                    Trace.Error($"Caught exception from JobExtension finalization: {ex}");
                    context.Output(ex.Message);
                }
                finally
                {
                    context.Debug("Finishing: Complete job");
                    context.Complete();
                }
            }
        }

19 Source : OutputManager.cs
with MIT License
from actions

public void OnDataReceived(object sender, ProcessDataReceivedEventArgs e)
        {
            var line = e.Data;

            // ## commands
            if (!String.IsNullOrEmpty(line) &&
                (line.IndexOf(ActionCommand.Prefix) >= 0 || line.IndexOf(ActionCommand._commandKey) >= 0))
            {
                // This does not need to be inside of a critical section.
                // The logging queues and command handlers are thread-safe.
                if (_commandManager.TryProcessCommand(_executionContext, line, _container))
                {
                    return;
                }
            }

            // Problem matchers
            if (_matchers.Length > 0)
            {
                // Copy the reference
                var matchers = _matchers;

                // Strip color codes
                var stripped = line.Contains(_colorCodePrefix) ? _colorCodeRegex.Replace(line, string.Empty) : line;

                foreach (var matcher in matchers)
                {
                    IssueMatch match = null;
                    for (var attempt = 1; attempt <= _maxAttempts; attempt++)
                    {
                        // Match
                        try
                        {
                            match = matcher.Match(stripped);

                            break;
                        }
                        catch (RegexMatchTimeoutException ex)
                        {
                            if (attempt < _maxAttempts)
                            {
                                // Debug
                                _executionContext.Debug($"Timeout processing issue matcher '{matcher.Owner}' against line '{stripped}'. Exception: {ex.ToString()}");
                            }
                            else
                            {
                                // Warn
                                _executionContext.Warning($"Removing issue matcher '{matcher.Owner}'. Matcher failed {_maxAttempts} times. Error: {ex.Message}");

                                // Remove
                                Remove(matcher);
                            }
                        }
                    }

                    if (match != null)
                    {
                        // Reset other matchers
                        foreach (var otherMatcher in matchers.Where(x => !object.ReferenceEquals(x, matcher)))
                        {
                            otherMatcher.Reset();
                        }

                        // Convert to issue
                        var issue = ConvertToIssue(match);

                        if (issue != null)
                        {
                            // Log issue
                            _executionContext.AddIssue(issue, stripped);

                            return;
                        }
                    }
                }
            }

            // Regular output
            _executionContext.Output(line);
        }

19 Source : OutputManager.cs
with MIT License
from actions

private DTWebApi.Issue ConvertToIssue(IssueMatch match)
        {
            // Validate the message
            if (string.IsNullOrWhiteSpace(match.Message))
            {
                _executionContext.Debug("Skipping logging an issue for the matched line because the message is empty.");
                return null;
            }

            // Validate the severity
            DTWebApi.IssueType issueType;
            if (string.IsNullOrEmpty(match.Severity) || string.Equals(match.Severity, "error", StringComparison.OrdinalIgnoreCase))
            {
                issueType = DTWebApi.IssueType.Error;
            }
            else if (string.Equals(match.Severity, "warning", StringComparison.OrdinalIgnoreCase))
            {
                issueType = DTWebApi.IssueType.Warning;
            }
            else if (string.Equals(match.Severity, "notice", StringComparison.OrdinalIgnoreCase))
            {
                issueType = DTWebApi.IssueType.Notice;
            }
            else
            {
                _executionContext.Debug($"Skipped logging an issue for the matched line because the severity '{match.Severity}' is not supported.");
                return null;
            }

            var issue = new DTWebApi.Issue
            {
                Message = match.Message,
                Type = issueType,
            };

            // Line
            if (!string.IsNullOrEmpty(match.Line))
            {
                if (int.TryParse(match.Line, NumberStyles.None, CultureInfo.InvariantCulture, out var line))
                {
                    issue.Data["line"] = line.ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    _executionContext.Debug($"Unable to parse line number '{match.Line}'");
                }
            }

            // Column
            if (!string.IsNullOrEmpty(match.Column))
            {
                if (int.TryParse(match.Column, NumberStyles.None, CultureInfo.InvariantCulture, out var column))
                {
                    issue.Data["col"] = column.ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    _executionContext.Debug($"Unable to parse column number '{match.Column}'");
                }
            }

            // Code
            if (!string.IsNullOrWhiteSpace(match.Code))
            {
                issue.Data["code"] = match.Code.Trim();
            }

            // File
            try
            {
                if (!string.IsNullOrWhiteSpace(match.File))
                {
                    var file = match.File;
                    var translate = _container != null;

                    // Root using fromPath
                    if (!string.IsNullOrWhiteSpace(match.FromPath) && !Path.IsPathFullyQualified(file))
                    {
                        var fromDirectory = Path.GetDirectoryName(match.FromPath);
                        if (!string.IsNullOrWhiteSpace(fromDirectory))
                        {
                            file = Path.Combine(fromDirectory, file);
                        }
                    }

                    // Root using workspace
                    if (!Path.IsPathFullyQualified(file))
                    {
                        var workspace = _executionContext.GetGitHubContext("workspace");
                        ArgUtil.NotNullOrEmpty(workspace, "workspace");

                        file = Path.Combine(workspace, file);
                        translate = false;
                    }

                    // Remove relative pathing and normalize slashes
                    file = Path.GetFullPath(file);

                    // Translate to host
                    if (translate)
                    {
                        file = _container.TranslateToHostPath(file);
                        file = Path.GetFullPath(file);
                    }

                    // Check whether the file exists
                    if (File.Exists(file))
                    {
                        // Check whether the file is under the workflow repository
                        var repositoryPath = GetRepositoryPath(file);
                        if (!string.IsNullOrEmpty(repositoryPath))
                        {
                            // Get the relative file path
                            var relativePath = file.Substring(repositoryPath.Length).TrimStart(Path.DirectorySeparatorChar);

                            // Prefer `/` on all platforms
                            issue.Data["file"] = relativePath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                        }
                        else
                        {
                            _executionContext.Debug($"Dropping file value '{file}'. Path is not under the workflow repo.");
                        }
                    }
                    else
                    {
                        _executionContext.Debug($"Dropping file value '{file}'. Path does not exist");
                    }
                }
            }
            catch (Exception ex)
            {
                _executionContext.Debug($"Dropping file value '{match.File}' and fromPath value '{match.FromPath}'. Exception during validation: {ex.ToString()}");
            }

            return issue;
        }

19 Source : TemplateValidationErrors.cs
with MIT License
from actions

public void Add(String messagePrefix, Exception ex)
        {
            for (int i = 0; i < 50; i++)
            {
                String message = !String.IsNullOrEmpty(messagePrefix) ? $"{messagePrefix} {ex.Message}" : ex.ToString();
                Add(new TemplateValidationError(message));
                if (ex.InnerException == null)
                {
                    break;
                }

                ex = ex.InnerException;
            }
        }

19 Source : Program.cs
with MIT License
from actions

public static async Task<int> MainAsync(IHostContext context, string[] args)
        {
            Tracing trace = context.GetTrace(nameof(GitHub.Runner.Worker));
            if (StringUtil.ConvertToBoolean(Environment.GetEnvironmentVariable("GITHUB_ACTIONS_RUNNER_ATTACH_DEBUGGER")))
            {
                await WaitForDebugger(trace);
            }

            // We may want to consider registering this handler in Worker.cs, similiar to the unloading/SIGTERM handler
            //ITerminal registers a CTRL-C handler, which keeps the Runner.Worker process running
            //and lets the Runner.Listener handle gracefully the exit.
            var term = context.GetService<ITerminal>();
            try
            {
                trace.Info($"Version: {BuildConstants.RunnerPackage.Version}");
                trace.Info($"Commit: {BuildConstants.Source.CommitHash}");
                trace.Info($"Culture: {CultureInfo.CurrentCulture.Name}");
                trace.Info($"UI Culture: {CultureInfo.CurrentUICulture.Name}");
                context.WritePerfCounter("WorkerProcessStarted");

                // Validate args.
                ArgUtil.NotNull(args, nameof(args));
                ArgUtil.Equal(3, args.Length, nameof(args.Length));
                ArgUtil.NotNullOrEmpty(args[0], $"{nameof(args)}[0]");
                ArgUtil.Equal("spawnclient", args[0].ToLowerInvariant(), $"{nameof(args)}[0]");
                ArgUtil.NotNullOrEmpty(args[1], $"{nameof(args)}[1]");
                ArgUtil.NotNullOrEmpty(args[2], $"{nameof(args)}[2]");
                var worker = context.GetService<IWorker>();

                // Run the worker.
                return await worker.RunAsync(
                    pipeIn: args[1],
                    pipeOut: args[2]);
            }
            catch (Exception ex)
            {
                // Populate any exception that cause worker failure back to runner.
                Console.WriteLine(ex.ToString());
                try
                {
                    trace.Error(ex);
                }
                catch (Exception e)
                {
                    // make sure we don't crash the app on trace error.
                    // since IOException will throw when we run out of disk space.
                    Console.WriteLine(e.ToString());
                }
            }

            return 1;
        }

19 Source : VssHttpEventSource.cs
with MIT License
from actions

[NonEvent]
        public void AuthenticationError(
            VssTraceActivity activity,
            IssuedTokenProvider provider,
            Exception exception)
        {
            if (IsEnabled(EventLevel.Error, Keywords.Authentication))
            {
                if (exception is AggregateException)
                {
                    exception = ((AggregateException)exception).Flatten().InnerException;
                }

                AuthenticationError(activity, provider, exception.ToString());
            }
        }

19 Source : RepositoryPlugin.cs
with MIT License
from actions

public async Task RunAsync(RunnerActionPluginExecutionContext executionContext, CancellationToken token)
        {
            string runnerWorkspace = executionContext.GetRunnerContext("workspace");
            ArgUtil.Directory(runnerWorkspace, nameof(runnerWorkspace));
            string tempDirectory = executionContext.GetRunnerContext("temp");
            ArgUtil.Directory(tempDirectory, nameof(tempDirectory));

            var repoFullName = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Repository);
            if (string.IsNullOrEmpty(repoFullName))
            {
                repoFullName = executionContext.GetGitHubContext("repository");
            }

            var repoFullNameSplit = repoFullName.Split("/", StringSplitOptions.RemoveEmptyEntries);
            if (repoFullNameSplit.Length != 2)
            {
                throw new ArgumentOutOfRangeException(repoFullName);
            }

            string expectRepoPath;
            var path = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Path);
            if (!string.IsNullOrEmpty(path))
            {
                expectRepoPath = IOUtil.ResolvePath(runnerWorkspace, path);
                if (!expectRepoPath.StartsWith(runnerWorkspace.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar))
                {
                    throw new ArgumentException($"Input path '{path}' should resolve to a directory under '{runnerWorkspace}', current resolved path '{expectRepoPath}'.");
                }
            }
            else
            {
                // When repository doesn't has path set, default to sources directory 1/repoName
                expectRepoPath = Path.Combine(runnerWorkspace, repoFullNameSplit[1]);
            }

            var workspaceRepo = executionContext.GetGitHubContext("repository");
            // for self repository, we need to let the worker knows where it is after checkout.
            if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
            {
                var workspaceRepoPath = executionContext.GetGitHubContext("workspace");

                executionContext.Debug($"Repository requires to be placed at '{expectRepoPath}', current location is '{workspaceRepoPath}'");
                if (!string.Equals(workspaceRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), expectRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), IOUtil.FilePathStringComparison))
                {
                    executionContext.Output($"Repository is current at '{workspaceRepoPath}', move to '{expectRepoPath}'.");
                    var count = 1;
                    var staging = Path.Combine(tempDirectory, $"_{count}");
                    while (Directory.Exists(staging))
                    {
                        count++;
                        staging = Path.Combine(tempDirectory, $"_{count}");
                    }

                    try
                    {
                        executionContext.Debug($"Move existing repository '{workspaceRepoPath}' to '{expectRepoPath}' via staging directory '{staging}'.");
                        IOUtil.MoveDirectory(workspaceRepoPath, expectRepoPath, staging, CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug("Catch exception during repository move.");
                        executionContext.Debug(ex.ToString());
                        executionContext.Warning("Unable move and reuse existing repository to required location.");
                        IOUtil.DeleteDirectory(expectRepoPath, CancellationToken.None);
                    }

                    executionContext.Output($"Repository will locate at '{expectRepoPath}'.");
                }

                executionContext.Debug($"Update workspace repository location.");
                executionContext.SetRepositoryPath(repoFullName, expectRepoPath, true);
            }

            string sourceBranch;
            string sourceVersion;
            string refInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Ref);
            if (string.IsNullOrEmpty(refInput))
            {
                sourceBranch = executionContext.GetGitHubContext("ref");
                sourceVersion = executionContext.GetGitHubContext("sha");
            }
            else
            {
                sourceBranch = refInput;
                sourceVersion = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Version);  // version get removed when checkout move to repo in the graph
                if (string.IsNullOrEmpty(sourceVersion) && RegexUtility.IsMatch(sourceBranch, WellKnownRegularExpressions.SHA1))
                {
                    sourceVersion = sourceBranch;
                    // If Ref is a SHA and the repo is self, we need to use github.ref as source branch since it might be refs/pull/*
                    if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceBranch = executionContext.GetGitHubContext("ref");
                    }
                    else
                    {
                        sourceBranch = "refs/heads/master";
                    }
                }
            }

            bool clean = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Clean), true);
            string submoduleInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Submodules);

            int fetchDepth = 0;
            if (!int.TryParse(executionContext.GetInput("fetch-depth"), out fetchDepth) || fetchDepth < 0)
            {
                fetchDepth = 0;
            }

            bool gitLfsSupport = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Lfs));
            string accessToken = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Token);
            if (string.IsNullOrEmpty(accessToken))
            {
                accessToken = executionContext.GetGitHubContext("token");
            }

            // register problem matcher
            string matcherFile = Path.Combine(tempDirectory, $"git_{Guid.NewGuid()}.json");
            File.WriteAllText(matcherFile, GitHubSourceProvider.ProblemMatcher, new UTF8Encoding(false));
            executionContext.Output($"##[add-matcher]{matcherFile}");
            try
            {
                await new GitHubSourceProvider().GetSourceAsync(executionContext,
                                                                expectRepoPath,
                                                                repoFullName,
                                                                sourceBranch,
                                                                sourceVersion,
                                                                clean,
                                                                submoduleInput,
                                                                fetchDepth,
                                                                gitLfsSupport,
                                                                accessToken,
                                                                token);
            }
            finally
            {
                executionContext.Output("##[remove-matcher owner=checkout-git]");
            }
        }

19 Source : ExecutionContext.cs
with MIT License
from actions

public static void Error(this IExecutionContext context, Exception ex)
        {
            context.Error(ex.Message);
            context.Debug(ex.ToString());
        }

19 Source : FileContainerHttpClient.cs
with MIT License
from actions

[EditorBrowsable(EditorBrowsableState.Never)]
        public async Task<HttpResponseMessage> UploadFileAsync(
            Int64 containerId,
            String itemPath,
            Stream fileStream,
            byte[] contentId,
            Int64 fileLength,
            Boolean isGzipped,
            Guid scopeIdentifier,
            CancellationToken cancellationToken = default(CancellationToken),
            int chunkSize = c_defaultChunkSize,
            int chunkRetryTimes = c_defaultChunkRetryTimes,
            bool uploadFirstChunk = false,
            Object userState = null)
        {
            if (containerId < 1)
            {
                throw new ArgumentException(WebApiResources.ContainerIdMustBeGreaterThanZero(), "containerId");
            }

            if (chunkSize > c_maxChunkSize)
            {
                chunkSize = c_maxChunkSize;
            }

            // if a contentId is specified but the chunk size is not a 2mb multiple error
            if (contentId != null && (chunkSize % c_ContentChunkMultiple) != 0)
            {
                throw new ArgumentException(FileContainerResources.ChunksizeWrongWithContentId(c_ContentChunkMultiple), "chunkSize");
            }

            ArgumentUtility.CheckForNull(fileStream, "fileStream");

            ApiResourceVersion gzipSupportedVersion = new ApiResourceVersion(new Version(1, 0), 2);
            ApiResourceVersion requestVersion = await NegotiateRequestVersionAsync(FileContainerResourceIds.FileContainer, s_currentApiVersion, userState, cancellationToken).ConfigureAwait(false);

            if (isGzipped
                && (requestVersion.ApiVersion < gzipSupportedVersion.ApiVersion
                    || (requestVersion.ApiVersion == gzipSupportedVersion.ApiVersion && requestVersion.ResourceVersion < gzipSupportedVersion.ResourceVersion)))
            {
                throw new ArgumentException(FileContainerResources.GzipNotSupportedOnServer(), "isGzipped");
            }

            if (isGzipped && fileStream.Length >= fileLength)
            {
                throw new ArgumentException(FileContainerResources.BadCompression(), "fileLength");
            }

            HttpRequestMessage requestMessage = null;
            List<KeyValuePair<String, String>> query = AppendItemQueryString(itemPath, scopeIdentifier);

            if (fileStream.Length == 0)
            {
                // zero byte upload
                FileUploadTrace(itemPath, $"Upload zero byte file '{itemPath}'.");
                requestMessage = await CreateRequestMessageAsync(HttpMethod.Put, FileContainerResourceIds.FileContainer, routeValues: new { containerId = containerId }, version: s_currentApiVersion, queryParameters: query, userState: userState, cancellationToken: cancellationToken).ConfigureAwait(false);
                return await SendAsync(requestMessage, userState, cancellationToken).ConfigureAwait(false);
            }

            bool multiChunk = false;
            int totalChunks = 1;
            if (fileStream.Length > chunkSize)
            {
                totalChunks = (int)Math.Ceiling(fileStream.Length / (double)chunkSize);
                FileUploadTrace(itemPath, $"Begin chunking upload file '{itemPath}', chunk size '{chunkSize} Bytes', total chunks '{totalChunks}'.");
                multiChunk = true;
            }
            else
            {
                FileUploadTrace(itemPath, $"File '{itemPath}' will be uploaded in one chunk.");
                chunkSize = (int)fileStream.Length;
            }

            StreamParser streamParser = new StreamParser(fileStream, chunkSize);
            SubStream currentStream = streamParser.GetNextStream();
            HttpResponseMessage response = null;

            Byte[] dataToSend = new Byte[chunkSize];
            int currentChunk = 0;
            Stopwatch uploadTimer = new Stopwatch();
            while (currentStream.Length > 0 && !cancellationToken.IsCancellationRequested)
            {
                currentChunk++;

                for (int attempt = 1; attempt <= chunkRetryTimes && !cancellationToken.IsCancellationRequested; attempt++)
                {
                    if (attempt > 1)
                    {
                        TimeSpan backoff = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10));
                        FileUploadTrace(itemPath, $"Backoff {backoff.TotalSeconds} seconds before attempt '{attempt}' chunk '{currentChunk}' of file '{itemPath}'.");
                        await Task.Delay(backoff, cancellationToken).ConfigureAwait(false);
                        currentStream.Seek(0, SeekOrigin.Begin);
                    }

                    FileUploadTrace(itemPath, $"Attempt '{attempt}' for uploading chunk '{currentChunk}' of file '{itemPath}'.");

                    // inorder for the upload to be retryable, we need the content to be re-readable
                    // to ensure this we copy the chunk into a byte array and send that
                    // chunk size ensures we can convert the length to an int
                    int bytesToCopy = (int)currentStream.Length;
                    using (MemoryStream ms = new MemoryStream(dataToSend))
                    {
                        await currentStream.CopyToAsync(ms, bytesToCopy, cancellationToken).ConfigureAwait(false);
                    }

                    // set the content and the Content-Range header
                    HttpContent byteArrayContent = new ByteArrayContent(dataToSend, 0, bytesToCopy);
                    byteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                    byteArrayContent.Headers.ContentLength = currentStream.Length;
                    byteArrayContent.Headers.ContentRange = new System.Net.Http.Headers.ContentRangeHeaderValue(currentStream.StartingPostionOnOuterStream,
                                                                                                             currentStream.EndingPostionOnOuterStream,
                                                                                                             streamParser.Length);
                    FileUploadTrace(itemPath, $"Generate new HttpRequest for uploading file '{itemPath}', chunk '{currentChunk}' of '{totalChunks}'.");

                    try
                    {
                        if (requestMessage != null)
                        {
                            requestMessage.Dispose();
                            requestMessage = null;
                        }

                        requestMessage = await CreateRequestMessageAsync(
                            HttpMethod.Put,
                            FileContainerResourceIds.FileContainer,
                            routeValues: new { containerId = containerId },
                            version: s_currentApiVersion,
                            content: byteArrayContent,
                            queryParameters: query,
                            userState: userState,
                            cancellationToken: cancellationToken).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
                    {
                        // stop re-try on cancellation.
                        throw;
                    }
                    catch (Exception ex) when (attempt < chunkRetryTimes) // not the last attempt
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' fail to create HttpRequest. Error: {ex.ToString()}.");
                        continue;
                    }

                    if (isGzipped)
                    {
                        //add gzip header info
                        byteArrayContent.Headers.ContentEncoding.Add("gzip");
                        byteArrayContent.Headers.Add("x-tfs-filelength", fileLength.ToString(System.Globalization.CultureInfo.InvariantCulture));
                    }

                    if (contentId != null)
                    {
                        byteArrayContent.Headers.Add("x-vso-contentId", Convert.ToBase64String(contentId)); // Base64FormattingOptions.None is default when not supplied
                    }

                    FileUploadTrace(itemPath, $"Start uploading file '{itemPath}' to server, chunk '{currentChunk}'.");
                    uploadTimer.Restart();

                    try
                    {
                        if (response != null)
                        {
                            response.Dispose();
                            response = null;
                        }

                        response = await SendAsync(requestMessage, userState, cancellationToken).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
                    {
                        // stop re-try on cancellation.
                        throw;
                    }
                    catch (Exception ex) when (attempt < chunkRetryTimes) // not the last attempt
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' fail to send request to server. Error: {ex.ToString()}.");
                        continue;
                    }

                    uploadTimer.Stop();
                    FileUploadTrace(itemPath, $"Finished upload chunk '{currentChunk}' of file '{itemPath}', elapsed {uploadTimer.ElapsedMilliseconds} (ms), response code '{response.StatusCode}'.");

                    if (multiChunk)
                    {
                        FileUploadProgress(itemPath, currentChunk, (int)Math.Ceiling(fileStream.Length / (double)chunkSize));
                    }

                    if (response.IsSuccessStatusCode)
                    {
                        break;
                    }
                    else if (IsFastFailResponse(response))
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' received non-success status code {response.StatusCode} for sending request and cannot continue.");
                        break;
                    }
                    else
                    {
                        FileUploadTrace(itemPath, $"Chunk '{currentChunk}' attempt '{attempt}' of file '{itemPath}' received non-success status code {response.StatusCode} for sending request.");
                        continue;
                    }
                }

                // if we don't have success then bail and return the failed response
                if (!response.IsSuccessStatusCode)
                {
                    break;
                }

                if (contentId != null && response.StatusCode == HttpStatusCode.Created)
                {
                    // no need to keep uploading since the server said it has all the content
                    FileUploadTrace(itemPath, $"Stop chunking upload the rest of the file '{itemPath}', since server already has all the content.");
                    break;
                }

                currentStream = streamParser.GetNextStream();
                if (uploadFirstChunk)
                {
                    break;
                }
            }

            cancellationToken.ThrowIfCancellationRequested();

            return response;
        }

19 Source : FileCommandManager.cs
with MIT License
from actions

private bool TryDeleteFile(string path)
        {
            if (!File.Exists(path))
            {
                return true;
            }
            try
            {
                File.Delete(path);
            }
            catch (Exception e)
            {
                _trace.Warning($"Unable to delete file {path} for reason: {e.ToString()}");
                return false;
            }
            return true;
        }

19 Source : VssHttpEventSource.cs
with MIT License
from actions

[NonEvent]
        public Exception HttpRequestFailed(
            VssTraceActivity activity,
            HttpRequestMessage request,
            Exception exception)
        {
            if (IsEnabled())
            {
                HttpRequestFailed(activity, request, exception.ToString());
            }
            return exception;
        }

19 Source : UserAgentUtility.cs
with MIT License
from actions

private static List<ProductInfoHeaderValue> ConstructDefaultRestUserAgent()
        {
            // Pick up the replacedembly version from this dll
            String fileVersion = "unavailable";
            try
            {
                replacedemblyFileVersionAttribute attr = typeof(UserAgentUtility).GetTypeInfo().replacedembly.GetCustomAttribute<replacedemblyFileVersionAttribute>();
                if (attr != null)
                {
                    fileVersion = attr.Version;
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine("DefaultUserAgent: Unable to get fileVersion: " + e.ToString());
            }

            String commentValue = string.Format("(NetStandard; {0})", RuntimeInformation.OSDescription.Replace('(', '[').Replace(')', ']').Trim());

            return new List<ProductInfoHeaderValue> {
                new ProductInfoHeaderValue("VSServices", fileVersion),
                new ProductInfoHeaderValue(commentValue) };
        }

19 Source : ActionCommandL0.cs
with MIT License
from actions

private bool IsEqualCommand(IHostContext hc, ActionCommand e1, ActionCommand e2)
        {
            try
            {
                if (!string.Equals(e1.Command, e2.Command, StringComparison.OrdinalIgnoreCase))
                {
                    hc.GetTrace("CommandEqual").Info("Command 1={0}, Command 2={1}", e1.Command, e2.Command);
                    return false;
                }

                if (!string.Equals(e1.Data, e2.Data, StringComparison.OrdinalIgnoreCase) && (!string.IsNullOrEmpty(e1.Data) && !string.IsNullOrEmpty(e2.Data)))
                {
                    hc.GetTrace("CommandEqual").Info("Data 1={0}, Data 2={1}", e1.Data, e2.Data);
                    return false;
                }

                if (e1.Properties.Count != e2.Properties.Count)
                {
                    hc.GetTrace("CommandEqual").Info("Logging events contain different numbers of Properties,{0} to {1}", e1.Properties.Count, e2.Properties.Count);
                    return false;
                }

                if (!e1.Properties.SequenceEqual(e2.Properties))
                {
                    hc.GetTrace("CommandEqual").Info("Logging events contain different Properties");
                    hc.GetTrace("CommandEqual").Info("Properties for event 1:");
                    foreach (var data in e1.Properties)
                    {
                        hc.GetTrace("CommandEqual").Info("Key={0}, Value={1}", data.Key, data.Value);
                    }

                    hc.GetTrace("CommandEqual").Info("Properties for event 2:");
                    foreach (var data in e2.Properties)
                    {
                        hc.GetTrace("CommandEqual").Info("Key={0}, Value={1}", data.Key, data.Value);
                    }

                    return false;
                }
            }
            catch (Exception ex)
            {
                hc.GetTrace("CommandEqual").Info("Catch Exception during compare:{0}", ex.ToString());
                return false;
            }

            return true;
        }

19 Source : LoggingTest.cs
with MIT License
from adams85

private async Task LoggingToMemoryWithoutDICore(LogFileAccessMode accessMode)
        {
            const string logsDirName = "Logs";

            var fileProvider = new MemoryFileProvider();

            var filterOptions = new LoggerFilterOptions { MinLevel = LogLevel.Trace };

            var options = new FileLoggerOptions
            {
                FileAppender = new MemoryFileAppender(fileProvider),
                BasePath = logsDirName,
                FileAccessMode = accessMode,
                FileEncoding = Encoding.UTF8,
                MaxQueueSize = 100,
                DateFormat = "yyMMdd",
                CounterFormat = "000",
                MaxFileSize = 10,
                Files = new[]
                {
                    new LogFileOptions
                    {
                        Path = "<date>/<date:MM>/logger.log",
                        DateFormat = "yyyy",
                        MinLevel = new Dictionary<string, LogLevel>
                        {
                            ["Karambolo.Extensions.Logging.File"] = LogLevel.None,
                            [LogFileOptions.DefaultCategoryName] = LogLevel.Information,
                        }
                    },
                    new LogFileOptions
                    {
                        Path = "test-<date>-<counter>.log",
                        MinLevel = new Dictionary<string, LogLevel>
                        {
                            ["Karambolo.Extensions.Logging.File"] = LogLevel.Information,
                            [LogFileOptions.DefaultCategoryName] = LogLevel.None,
                        }

                    },
                },
                TextBuilder = new CustomLogEntryTextBuilder(),
                IncludeScopes = true,
            };

            var completeCts = new CancellationTokenSource();
            var context = new TestFileLoggerContext(completeCts.Token, completionTimeout: Timeout.InfiniteTimeSpan);

            context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            var diagnosticEventReceived = false;
            context.DiagnosticEvent += _ => diagnosticEventReceived = true;

            var ex = new Exception();

            var provider = new FileLoggerProvider(context, Options.Create(options));

            await using (provider)
            using (var loggerFactory = new LoggerFactory(new[] { provider }, filterOptions))
            {
                ILogger<LoggingTest> logger1 = loggerFactory.CreateLogger<LoggingTest>();

                logger1.LogInformation("This is a nice logger.");
                using (logger1.BeginScope("SCOPE"))
                {
                    logger1.LogWarning(1, "This is a smart logger.");
                    logger1.LogTrace("This won't make it.");

                    using (logger1.BeginScope("NESTED SCOPE"))
                    {
                        ILogger logger2 = loggerFactory.CreateLogger("X");
                        logger2.LogWarning("Some warning.");
                        logger2.LogError(0, ex, "Some failure!");
                    }
                }
            }

            replacedert.True(provider.Completion.IsCompleted);

            replacedert.False(diagnosticEventReceived);

            var logFile = (MemoryFileInfo)fileProvider.GetFileInfo($"{logsDirName}/test-{context.GetTimestamp().ToLocalTime():yyMMdd}-000.log");
            replacedert.True(logFile.Exists && !logFile.IsDirectory);

            var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            replacedert.Equal(Encoding.UTF8, encoding);
            replacedert.Equal(new[]
            {
                $"[info]: {typeof(LoggingTest)}[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"        This is a nice logger.",
                ""
            }, lines);

            logFile = (MemoryFileInfo)fileProvider.GetFileInfo($"{logsDirName}/test-{context.GetTimestamp().ToLocalTime():yyMMdd}-001.log");
            replacedert.True(logFile.Exists && !logFile.IsDirectory);

            lines = logFile.ReadAllText(out encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            replacedert.Equal(Encoding.UTF8, encoding);
            replacedert.Equal(new[]
            {
                $"[warn]: {typeof(LoggingTest)}[1] @ {context.GetTimestamp().ToLocalTime():o}",
                $"        => SCOPE",
                $"        This is a smart logger.",
                ""
            }, lines);

            logFile = (MemoryFileInfo)fileProvider.GetFileInfo(
                $"{logsDirName}/{context.GetTimestamp().ToLocalTime():yyyy}/{context.GetTimestamp().ToLocalTime():MM}/logger.log");
            replacedert.True(logFile.Exists && !logFile.IsDirectory);

            lines = logFile.ReadAllText(out encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            replacedert.Equal(Encoding.UTF8, encoding);
            replacedert.Equal(new[]
            {
                $"[warn]: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"        => SCOPE => NESTED SCOPE",
                $"        Some warning.",
                $"[fail]: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"        => SCOPE => NESTED SCOPE",
                $"        Some failure!",
            }
            .Concat(ex.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None))
            .Append(""), lines);
        }

19 Source : FileLogEntryTextBuilder.cs
with MIT License
from adams85

protected virtual void AppendException(StringBuilder sb, Exception exception)
        {
            sb.AppendLine(exception.ToString());
        }

19 Source : Logging.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static void LogException(Exception ex, string message)
		{
			string toLog = (ex == null) ? Environment.NewLine + "Application encountered an error" : ex.ToString();

			if (!string.IsNullOrWhiteSpace(message))
				toLog += ": " + message;
			else
				toLog += "!";

			toLog += Environment.NewLine + Environment.NewLine;


			CreateLogFileIfNotExists(OutputFilename);
			File.AppendAllText(OutputFilename, GetTimestamp() + toLog);
			LogTextbox(toLog);
		}

19 Source : AdColonyUtils.cs
with Apache License 2.0
from AdColony

public static object Decode(string json)
        {
            if (json == null)
            {
                return null;
            }

            // save the string for debug information
            AdColonyJson.instance.lastDecode = json;

            object value = null;
            try
            {
                char[] charArray = json.ToCharArray();
                int index = 0;
                bool success = true;
                value = AdColonyJson.instance.ParseValue(charArray, ref index, ref success);
                if (success)
                {
                    AdColonyJson.instance.lastErrorIndex = -1;
                }
                else
                {
                    AdColonyJson.instance.lastErrorIndex = index;
                }
            }
            catch (System.Exception e)
            {
                UnityEngine.Debug.LogError(e.ToString());
            }

            return value;
        }

19 Source : LoggingTest.cs
with MIT License
from adams85

private async Task LoggingToPhysicalUsingDICore(LogFileAccessMode accessMode)
        {
            var logsDirName = Guid.NewGuid().ToString("D");

            var configData = new Dictionary<string, string>
            {
                [$"{nameof(FileLoggerOptions.BasePath)}"] = logsDirName,
                [$"{nameof(FileLoggerOptions.FileEncodingName)}"] = "UTF-16",
                [$"{nameof(FileLoggerOptions.DateFormat)}"] = "yyMMdd",
                [$"{nameof(FileLoggerOptions.FileAccessMode)}"] = accessMode.ToString(),
                [$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.Path)}"] = "logger-<date>.log",
                [$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.MinLevel)}:Karambolo.Extensions.Logging.File"] = LogLevel.None.ToString(),
                [$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.MinLevel)}:{LogFileOptions.DefaultCategoryName}"] = LogLevel.Information.ToString(),
                [$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.Path)}"] = "test-<date>.log",
                [$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.MinLevel)}:Karambolo.Extensions.Logging.File.Test"] = LogLevel.Information.ToString(),
                [$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.MinLevel)}:{LogFileOptions.DefaultCategoryName}"] = LogLevel.None.ToString(),
            };

            var cb = new ConfigurationBuilder();
            cb.AddInMemoryCollection(configData);
            IConfigurationRoot config = cb.Build();

            var tempPath = Path.Combine(Path.GetTempPath());
            var logPath = Path.Combine(tempPath, logsDirName);

            var fileProvider = new PhysicalFileProvider(tempPath);

            var cts = new CancellationTokenSource();
            var context = new TestFileLoggerContext(cts.Token, completionTimeout: Timeout.InfiniteTimeSpan);

            context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            var diagnosticEventReceived = false;
            context.DiagnosticEvent += _ => diagnosticEventReceived = true;

            var services = new ServiceCollection();
            services.AddOptions();
            services.AddLogging(b => b.AddFile(context, o => o.FileAppender = new PhysicalFileAppender(fileProvider)));
            services.Configure<FileLoggerOptions>(config);

            if (Directory.Exists(logPath))
                Directory.Delete(logPath, recursive: true);

            try
            {
                var ex = new Exception();

                FileLoggerProvider[] providers;

                using (ServiceProvider sp = services.BuildServiceProvider())
                {
                    providers = context.GetProviders(sp).ToArray();
                    replacedert.Equal(1, providers.Length);

                    ILogger<LoggingTest> logger1 = sp.GetService<ILogger<LoggingTest>>();

                    logger1.LogInformation("This is a nice logger.");
                    using (logger1.BeginScope("SCOPE"))
                    {
                        logger1.LogWarning(1, "This is a smart logger.");
                        logger1.LogTrace("This won't make it.");

                        using (logger1.BeginScope("NESTED SCOPE"))
                        {
                            ILoggerFactory loggerFactory = sp.GetService<ILoggerFactory>();
                            ILogger logger2 = loggerFactory.CreateLogger("X");
                            logger2.LogError(0, ex, "Some failure!");
                        }
                    }

                    cts.Cancel();

                    // ensuring that all entries are processed
                    await context.GetCompletion(sp);
                    replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
                }

                replacedert.False(diagnosticEventReceived);

                IFileInfo logFile = fileProvider.GetFileInfo($"{logsDirName}/test-{context.GetTimestamp().ToLocalTime():yyMMdd}.log");
                replacedert.True(logFile.Exists && !logFile.IsDirectory);

                var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                replacedert.Equal(Encoding.Unicode, encoding);
                replacedert.Equal(new[]
                {
                    $"info: {typeof(LoggingTest)}[0] @ {context.GetTimestamp().ToLocalTime():o}",
                    $"      This is a nice logger.",
                    $"warn: {typeof(LoggingTest)}[1] @ {context.GetTimestamp().ToLocalTime():o}",
                    $"      This is a smart logger.",
                    ""
                }, lines);

                logFile = fileProvider.GetFileInfo(
                    $"{logsDirName}/logger-{context.GetTimestamp().ToLocalTime():yyMMdd}.log");
                replacedert.True(logFile.Exists && !logFile.IsDirectory);

                lines = logFile.ReadAllText(out encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                replacedert.Equal(Encoding.Unicode, encoding);
                replacedert.Equal(new[]
                {
                    $"fail: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                    $"      Some failure!",
                }
                .Concat(ex.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None))
                .Append(""), lines);
            }
            finally
            {
                if (Directory.Exists(logPath))
                    Directory.Delete(logPath, recursive: true);
            }
        }

19 Source : AdColonyUtils.cs
with Apache License 2.0
from AdColony

public static string Encode(object json)
        {
            if (json == null)
            {
                return null;
            }

            bool success = false;
            StringBuilder builder = new StringBuilder(BUILDER_CAPACITY);
            try
            {
                success = AdColonyJson.instance.SerializeValue(json, builder);
            }
            catch (System.Exception e)
            {
                UnityEngine.Debug.LogError(e.ToString());
            }

            return (success ? builder.ToString() : null);
        }

19 Source : UploadController.cs
with MIT License
from ADefWebserver

[HttpPost("[action]")]
        public async Task<IActionResult> UpgradeAsync(
            IFormFile file, string Filereplacedle)
        {
            try
            {
                if (HttpContext.Request.Form.Files.Any())
                {
                    // Only accept .zip files
                    if (file.ContentType == "application/x-zip-compressed")
                    {
                        string UploadPath =
                            Path.Combine(
                                environment.ContentRootPath,
                                "Uploads");

                        string UploadPathAndFile =
                            Path.Combine(
                                environment.ContentRootPath,
                                "Uploads",
                                "BlazorBlogsUpgrade.zip");

                        string UpgradePath = Path.Combine(
                            environment.ContentRootPath,
                            "Upgrade");

                        // Upload Upgrade package to Upload Folder
                        if (!Directory.Exists(UpgradePath))
                        {
                            Directory.CreateDirectory(UpgradePath);
                        }

                        using (var stream =
                            new FileStream(UploadPathAndFile, FileMode.Create))
                        {
                            await file.CopyToAsync(stream);
                        }

                        DeleteFiles(UpgradePath);

                        // Unzip files to Upgrade folder
                        ZipFile.ExtractToDirectory(UploadPathAndFile, UpgradePath, true);

                        #region Check upgrade - Get current version
                        Version objVersion = new Version();
                        var GeneralSettings = await generalSettingsService.GetGeneralSettingsAsync();
                        objVersion.VersionNumber = GeneralSettings.VersionNumber;
                        #endregion

                        #region Examine the manifest file
                        objVersion = ReadManifest(objVersion, UpgradePath);

                        try
                        {
                            if (objVersion.ManifestLowestVersion == "")
                            {
                                // Delete the files
                                DeleteFiles(UpgradePath);
                                return Ok("Error: could not find manifest");
                            }
                        }
                        catch (Exception ex)
                        {
                            return Ok(ex.ToString());
                        }
                        #endregion

                        #region Show error if needed and delete upgrade files 
                        if
                            (
                            (ConvertToInteger(objVersion.VersionNumber) > ConvertToInteger(objVersion.ManifestHighestVersion)) ||
                            (ConvertToInteger(objVersion.VersionNumber) < ConvertToInteger(objVersion.ManifestLowestVersion))
                            )
                        {
                            // Delete the files
                            DeleteFiles(UpgradePath);

                            // Return the error response
                            return Ok(objVersion.ManifestFailure);
                        }
                        #endregion

                        // Proceed with upgrade...

                        DeleteFiles(UpgradePath);

                        // Unzip files to final paths
                        ZipFile.ExtractToDirectory(UploadPathAndFile, environment.ContentRootPath, true);

                        Task.Delay(4000).Wait(); // Wait 4 seconds with blocking
                    }
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }

            return Ok();
        }

19 Source : LoggingServiceCoverletLogger.cs
with MIT License
from ademanuele

public void LogError(Exception exception)
    {
      loggingService.Error(exception.ToString());
    }

19 Source : JobDispatcher.cs
with MIT License
from AdemCatamak

public async Task<bool> HandleNextJobAsync(CancellationToken cancellationToken = default)
        {
            IJobRepository jobRepository = _repositoryFactory.CreateJobRepository();
            Job? job = await jobRepository.SetFirstQueuedJobToInProgressAsync(cancellationToken);

            if (job == null) return false;

            try
            {
                using IMessageHandler messageHandler = _messageHandlerProvider.Create(job.MessageHandlerTypeName);
                await messageHandler.BaseHandleOperationAsync(job.Message.Payload, cancellationToken);
                job.SetCompleted();
            }
            catch (Exception e)
            {
                job.SetFailed(e.ToString());
            }

            await jobRepository.UpdateJobStatusAsync(job, cancellationToken);

            return true;
        }

19 Source : DynamicDataContextDriver.cs
with BSD 2-Clause "Simplified" License
from adospace

public override List<ExplorerItem> GetSchemaAndBuildreplacedembly(IConnectionInfo cxInfo, replacedemblyName replacedemblyToBuild, ref string @namespace, ref string typeName)
        {
            try
            {
                return InternalGetSchemaAndBuildreplacedembly(cxInfo, replacedemblyToBuild, ref @namespace, ref typeName);
            }
            catch(Exception ex)
            {
                Log(ex.ToString());
                throw;
            }
        }

19 Source : Program.cs
with MIT License
from adospace

private static bool ExecutePortForwardCommmand()
        {
            var adbCommandLine = "\"" + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Android", "sdk", "platform-tools", "adb" + (IsWindows ? ".exe" : "")) + "\" "
                + "forward tcp:45820 tcp:45820";
            var adbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Android", "android-sdk", "platform-tools", "adb.exe");

            var process = new System.Diagnostics.Process();

            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.Arguments = "forward tcp:45820 tcp:45820";
            process.StartInfo.FileName = adbPath;

            try
            {
                process.Start();

                var adb_output = process.StandardOutput.ReadToEnd();

                if (adb_output.Length > 0 && adb_output != "45820" + Environment.NewLine)
                    throw new InvalidOperationException($"Unable to forward tcp port from emulator (executing '{adbPath} forward tcp:45820 tcp:45820' adb tool returned '{adb_output}')");
            }
            catch (Exception ex)
            {
                Console.WriteLine(process.StandardOutput.ReadToEnd());
                Console.WriteLine(process.StandardError.ReadToEnd());
                Console.WriteLine(ex.ToString());
                return false;
            }

            return true;
        }

19 Source : AppDataPortalBusProvider.cs
with MIT License
from Adoxio

protected virtual Task WriteMessage(TimeSpan timeout, string subscriptionPath, TMessage message)
		{
			// clean up expired files

			var directory = this.Options.RetryPolicy.GetDirectory(subscriptionPath);

			var expired =
				this.Options.RetryPolicy.GetFiles(directory, "*.msg")
				.Where(file => file.LastAccessTimeUtc + timeout < DateTime.UtcNow)
				.ToArray();

			foreach (var file in expired)
			{
				try
				{
					this.Options.RetryPolicy.FileDelete(file);
				}
				catch (Exception e)
				{
					ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString());
				}
			}

			var name = GetFilename(message);
			var tempPath = Path.Combine(subscriptionPath, name + ".lock.msg");
			var messagePath = Path.Combine(subscriptionPath, name + ".msg");

			// write to a temporary file

			using (var fs = this.Options.RetryPolicy.Open(tempPath, FileMode.CreateNew))
			using (var sw = new StreamWriter(fs))
			using (var jw = new JsonTextWriter(sw))
			{
				jw.Formatting = Formatting.Indented;

				_serializer.Serialize(jw, message);
			}

			// rename to the destination file

			this.Options.RetryPolicy.FileMove(tempPath, messagePath);

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("messagePath={0}", messagePath));
			
			return Task.FromResult(0);
		}

19 Source : ServiceDefinitionPortalBusProvider.cs
with MIT License
from Adoxio

protected virtual async Task SendRequest(IEnumerable<Role> roles, IEnumerable<RoleSite> sites, IPAddress localAddress, string internalEndpointName, TMessage message)
		{
			// send out the remote invalidation messages

			// if the advanced settings are used do not resolve the full application path since it will be defined directly in the settings

			var virtualPath = Options.CallbackPath.ToString();
			var path = sites == null ? VirtualPathUtility.ToAbsolute(virtualPath) : virtualPath;

			// trim the leading slash (treat as a relative path) so that the parent path is preserved

			path = path.TrimStart('/');

			var client = new HttpClient();
			var endpoints = GetRemoteEndpoints(roles, sites, localAddress, internalEndpointName).ToArray();

			foreach (var endpoint in endpoints)
			{
				var uri = new Uri(endpoint, path);

                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("uri={0}", uri));

				try
				{
					var response = await client.PostAsync(uri, message, new JsonMediaTypeFormatter()).WithCurrentCulture();

                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("StatusCode={0}, uri={1}", response.StatusCode, uri));
                }
				catch (Exception e)
				{
                    ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("uri={0}", uri));
                    ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString());
                }
			}
		}

19 Source : MetadataHelper.cs
with MIT License
from Adoxio

public static EnreplacedyMetadata GetEnreplacedyMetadata(OrganizationServiceContext serviceContext, string logicalName)
		{
			try
			{
				var response = (RetrieveEnreplacedyResponse)serviceContext.Execute(new RetrieveEnreplacedyRequest
				{
					LogicalName = logicalName,
					EnreplacedyFilters = EnreplacedyFilters.Enreplacedy | EnreplacedyFilters.Attributes | EnreplacedyFilters.Relationships
				});

				return response.EnreplacedyMetadata;
			}
			catch (Exception ex)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, ex.ToString());

                return new EnreplacedyMetadata();
			}
		}

19 Source : EntityFormFunctions.cs
with MIT License
from Adoxio

internal static void TrySetState(OrganizationServiceContext context, EnreplacedyReference enreplacedyReference, int state)
		{
			try
			{
				context.SetState(state, -1, enreplacedyReference);
			}
			catch (Exception ex)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Failed to set statecode. {0}", ex.ToString()));
			}
		}

19 Source : EntityFormFunctions.cs
with MIT License
from Adoxio

internal static void replacedociate(OrganizationServiceContext serviceContext, EnreplacedyReference related)
		{
			var targetEnreplacedyLogicalName = HttpContext.Current.Request["refenreplacedy"];
			var targetEnreplacedyId = HttpContext.Current.Request["refid"];
			var relationshipName = HttpContext.Current.Request["refrel"];
			var relationshipRole = HttpContext.Current.Request["refrelrole"];
			Guid targetId;

			if (string.IsNullOrWhiteSpace(targetEnreplacedyLogicalName) || string.IsNullOrWhiteSpace(targetEnreplacedyId) ||
				string.IsNullOrWhiteSpace(relationshipName) || related == null)
			{
				ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Request did not contain parameters 'refenreplacedy', 'refid', 'refrel'");
				return;
			}

			if (!Guid.TryParse(targetEnreplacedyId, out targetId))
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, "Request did not contain a valid guid 'refid'");

				return;
			}

			try
			{
				var relationship = new Relationship(relationshipName);

				if (!string.IsNullOrWhiteSpace(relationshipRole))
				{
					switch (relationshipRole)
					{
						case "Referenced":
							relationship.PrimaryEnreplacedyRole = EnreplacedyRole.Referenced;
							break;
						case "Referencing":
							relationship.PrimaryEnreplacedyRole = EnreplacedyRole.Referencing;
							return;
							break;
						default:
							ADXTrace.Instance.TraceError(TraceCategory.Application, "Relationship Primary Enreplacedy Role provided by parameter named 'refrelrole' is not valid.");
							break;
					}
				}

				var replacedociateRequest = new replacedociateRequest
				{
					Target = new EnreplacedyReference(targetEnreplacedyLogicalName, targetId),
					Relationship = relationship,
					RelatedEnreplacedies = new EnreplacedyReferenceCollection { related }
				};

				serviceContext.Execute(replacedociateRequest);
			}
			catch (Exception ex)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, ex.ToString());

			}
		}

19 Source : EntityFormFunctions.cs
with MIT License
from Adoxio

internal static void replacedociateEnreplacedy(OrganizationServiceContext context, Enreplacedy enreplacedyform, Guid sourceEnreplacedyId)
		{
			var setEnreplacedyReference = enreplacedyform.GetAttributeValue<bool?>("adx_setenreplacedyreference") ?? false;

			if (!setEnreplacedyReference) return;

			var targetEnreplacedyId = Guid.Empty;
			var targetEnreplacedyPrimaryKey = string.Empty;
			var sourceEnreplacedyName = enreplacedyform.GetAttributeValue<string>("adx_enreplacedyname");
			var sourceEnreplacedyPrimaryKey = enreplacedyform.GetAttributeValue<string>("adx_primarykeyname");
			var targetEnreplacedyName = enreplacedyform.GetAttributeValue<string>("adx_referenceenreplacedylogicalname");
			var relationshipName = enreplacedyform.GetAttributeValue<string>("adx_referenceenreplacedyrelationshipname") ?? string.Empty;

			if (string.IsNullOrWhiteSpace(relationshipName))
			{
				ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Enreplacedy Relationship Name not provided. Enreplacedy replacedociation not required.");
				return;
			}

			try
			{
				var referenceQueryStringName = enreplacedyform.GetAttributeValue<string>("adx_referencequerystringname") ?? string.Empty;
				var referenceQueryStringValue = HttpContext.Current.Request[referenceQueryStringName];
				var querystringIsPrimaryKey = enreplacedyform.GetAttributeValue<bool?>("adx_referencequerystringisprimarykey") ?? false;

				if (!querystringIsPrimaryKey)
				{
					var referenceQueryAttributeName = enreplacedyform.GetAttributeValue<string>("adx_referencequeryattributelogicalname");
					var enreplacedy =
						context.CreateQuery(targetEnreplacedyName).FirstOrDefault(
							o => o.GetAttributeValue<string>(referenceQueryAttributeName) == referenceQueryStringValue);

					if (enreplacedy != null) { targetEnreplacedyId = enreplacedy.Id; }
				}
				else
				{
					Guid.TryParse(referenceQueryStringValue, out targetEnreplacedyId);
				}

				if (sourceEnreplacedyId == Guid.Empty || targetEnreplacedyId == Guid.Empty)
				{
					ADXTrace.Instance.TraceError(TraceCategory.Application, "Source and Target enreplacedy ids must not be null or empty.");
					return;
				}

				// get the source enreplacedy

				if (string.IsNullOrWhiteSpace(sourceEnreplacedyName))
				{
					ADXTrace.Instance.TraceError(TraceCategory.Application, "adx_enreplacedyform.adx_targetenreplacedylogicalname must not be null.");
					return;
				}

				if (string.IsNullOrWhiteSpace(sourceEnreplacedyPrimaryKey))
				{
					sourceEnreplacedyPrimaryKey = MetadataHelper.GetEnreplacedyPrimaryKeyAttributeLogicalName(context, sourceEnreplacedyName);
				}

				if (string.IsNullOrWhiteSpace(sourceEnreplacedyPrimaryKey))
				{
					ADXTrace.Instance.TraceError(TraceCategory.Application, "Failed to determine source enreplacedy primary key logical name.");
					return;
				}

				var sourceEnreplacedy = context.CreateQuery(sourceEnreplacedyName).FirstOrDefault(o => o.GetAttributeValue<Guid>(sourceEnreplacedyPrimaryKey) == sourceEnreplacedyId);

				if (sourceEnreplacedy == null)
				{
					ADXTrace.Instance.TraceError(TraceCategory.Application, "Source enreplacedy is null.");
					return;
				}

				// Get the target enreplacedy

				if (string.IsNullOrWhiteSpace(targetEnreplacedyName))
				{
					ADXTrace.Instance.TraceError(TraceCategory.Application, "Target enreplacedy name must not be null or empty.");
					return;
				}

				if (string.IsNullOrWhiteSpace(targetEnreplacedyPrimaryKey))
				{
					targetEnreplacedyPrimaryKey = MetadataHelper.GetEnreplacedyPrimaryKeyAttributeLogicalName(context, targetEnreplacedyName);
				}

				if (string.IsNullOrWhiteSpace(targetEnreplacedyPrimaryKey))
				{
					ADXTrace.Instance.TraceError(TraceCategory.Application, "Failed to determine target enreplacedy primary key logical name.");
					return;
				}

				var targetEnreplacedy = context.CreateQuery(targetEnreplacedyName).FirstOrDefault(o => o.GetAttributeValue<Guid>(targetEnreplacedyPrimaryKey) == targetEnreplacedyId);

				if (targetEnreplacedy == null)
				{
					ADXTrace.Instance.TraceError(TraceCategory.Application, "Target enreplacedy is null.");
					return;
				}

				context.AddLink(sourceEnreplacedy, relationshipName, targetEnreplacedy);
			}
			catch (Exception ex)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("{0}", ex.ToString()));
			}
		}

19 Source : OrganizationServiceCacheService.cs
with MIT License
from Adoxio

public virtual void Remove(OrganizationServiceCachePluginMessage message)
		{
			try
			{
				message.ThrowOnNull("message");

                ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("MessageName={0}, ServiceCacheName={1}, ConnectionStringName={2}", message.MessageName, message.ServiceCacheName, message.ConnectionStringName));

				if (message.Target != null && message.Relationship == null)
				{
					var enreplacedy = message.Target.ToEnreplacedyReference();

                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Id={0}, LogicalName={1}", enreplacedy.Id, EnreplacedyNamePrivacy.GetEnreplacedyName(enreplacedy.LogicalName)));
				}

				if (message.Category != null)
				{
					var category = message.Category.Value;

                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("category={0}", category));
				}

				if (message.Target != null && message.Relationship != null && message.RelatedEnreplacedies != null)
				{
					var target = message.Target.ToEnreplacedyReference();
					var relationship = message.Relationship.ToRelationship();
					var relatedEnreplacedies = message.RelatedEnreplacedies.ToEnreplacedyReferenceCollection();

                    ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Target: Id={0}, LogicalName={1}", target.Id, EnreplacedyNamePrivacy.GetEnreplacedyName(target.LogicalName)));
                    foreach (var enreplacedy in relatedEnreplacedies)
					{
                        ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Related: Id={0}, LogicalName={1}", enreplacedy.Id, EnreplacedyNamePrivacy.GetEnreplacedyName(enreplacedy.LogicalName)));
                    }
				}

				_cache.ExtendedRemoveLocal(message);
			}
			catch (Exception error)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, error.ToString());
			}
		}

19 Source : EntityListPackageRepositoryDataAdapter.cs
with MIT License
from Adoxio

private IEnumerable<PackageVersion> GetPackageVersions(IGrouping<Guid, Enreplacedy> enreplacedyGrouping, Guid websiteId)
		{
			var groupings = enreplacedyGrouping
				.GroupBy(e => e.GetAttributeAliasedValue<Guid?>("adx_packageversionid", "version"))
				.Where(e => e.Key != null);

			foreach (var grouping in groupings)
			{
				var enreplacedy = grouping.FirstOrDefault();

				if (enreplacedy == null)
				{
					continue;
				}

				var versionId = enreplacedy.GetAttributeAliasedValue<Guid?>("adx_packageversionid", "version");

				if (versionId == null)
				{
					continue;
				}

				var configurationJson = enreplacedy.GetAttributeAliasedValue<string>("adx_configuration", "version");
				var configuration = new PackageConfiguration();
				if (!string.IsNullOrWhiteSpace(configurationJson))
				{
					try
					{
						configuration = JsonConvert.DeserializeObject<PackageConfiguration>(configurationJson,
							new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, Binder = new PackageConfigurationSerializationBinder() });
					}
					catch (Exception e)
					{
						ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("GetPackageVersions", "{0}", e.ToString()));
                    }
				}

				yield return new PackageVersion
				{
					Description = enreplacedy.GetAttributeAliasedValue<string>("adx_description", "version"),
					DisplayName = enreplacedy.GetAttributeAliasedValue<string>("adx_name", "version"),
					ReleaseDate = enreplacedy.GetAttributeAliasedValue<DateTime?>("adx_releasedate", "version").GetValueOrDefault(),
					RequiredInstallerVersion = enreplacedy.GetAttributeAliasedValue<string>("adx_requiredinstallerversion", "version"),
					Url = GetPackageVersionUrl(websiteId, versionId.Value),
					Version = enreplacedy.GetAttributeAliasedValue<string>("adx_version", "version"),
					Configuration = configuration
				};
			}
		}

19 Source : EntityListDataAdapter.cs
with MIT License
from Adoxio

protected static bool TryGetViewId(Enreplacedy enreplacedyList, EnreplacedyReference viewReference, out Guid? viewId)
		{
			// First, try get the view from the newer view configuration JSON.
			var viewMetadataJson = enreplacedyList.GetAttributeValue<string>("adx_views");

			if (!string.IsNullOrWhiteSpace(viewMetadataJson))
			{
				try
				{
					var viewMetadata = ViewMetadata.Parse(viewMetadataJson);

					var view = viewMetadata.Views.FirstOrDefault(e => e.ViewId == viewReference.Id);

					if (view != null)
					{
						viewId = view.ViewId;

						return true;
					}
				}
				catch (Exception e)
				{
					ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error parsing adx_views JSON: {0}", e.ToString()));
				}
			}

			// Fall back to the legacy comma-delimited list of IDs.
			var viewIds = (enreplacedyList.GetAttributeValue<string>("adx_view") ?? string.Empty)
				.Split(',')
				.Select(s =>
				{
					Guid id;

					return Guid.TryParse(s, out id) ? new Guid?(id) : null;
				})
				.Where(id => id != null);

			viewId = viewIds.FirstOrDefault(id => id == viewReference.Id);

			return viewId != null;
		}

19 Source : CrmSubscriptionMessage.cs
with MIT License
from Adoxio

protected static ICrmSubscriptionMessage DeserializeMessage(string messageBody, Type t)
		{
			try
			{
				var x = JsonConvert.DeserializeObject(messageBody, t) as ICrmSubscriptionMessage;
				return x;
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString());
			}
			return null;
		}

19 Source : CrmChangeTrackingManager.cs
with MIT License
from Adoxio

internal TimeBasedChangedData RequestRecordDeltaFromCrm(Dictionary<string, string> enreplacediesWithLastTimestamp, CrmDbContext context, Guid websiteId)
		{
			try
			{
				//Keep a local refrence of the Processing table
				processingEnreplacedies = NotificationUpdateManager.Instance.ProcessingEnreplacediesTable();

				UpdateTimeStamp(enreplacediesWithLastTimestamp);
				var request = ExecuteMultipleRequest(enreplacediesWithLastTimestamp);

				ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Running 'ExecuteMultipleRequest' with {0} requests.", request.Requests.Count().ToString()));

				var enreplacedies = string.Join(",", enreplacediesWithLastTimestamp.Keys);
				ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Retrieving changes for enreplacedies = {0}.", enreplacedies));

				var response = (ExecuteMultipleResponse)context.Service.Execute(request);

				if (response == null || response.Responses == null)
				{
					ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Got null response while processing the requests"));
					return null;
				}

				if (response.IsFaulted)
				{
					ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("Got faulted response from '{0}' while processing atleast one of the message requests", response.ResponseName));
				}

				var responseCollection = new Dictionary<string, RetrieveEnreplacedyChangesResponse>();

				for (var i = 0; i < request.Requests.Count && i < response.Responses.Count; i++)
				{
					var enreplacedyChangeRequest = request.Requests[i] as RetrieveEnreplacedyChangesRequest;
					var resp = response.Responses[i];

					if (resp.Fault != null)
					{
						ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("RetrieveEnreplacedyChangesRequest faulted for enreplacedy '{0}'. Message: '{1}' ", enreplacedyChangeRequest.EnreplacedyName, resp.Fault.Message));
						continue;
					}
					responseCollection.Add(enreplacedyChangeRequest.EnreplacedyName, response.Responses[i].Response as RetrieveEnreplacedyChangesResponse);
				}

				return ParseBusinessEnreplacedyChangesResponse(responseCollection, context, websiteId);
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString());
			}
			return null;
		}

19 Source : EventHubJob.cs
with MIT License
from Adoxio

protected override void ExecuteInternal(Guid id)
		{
			bool isSearchSubscription = this.Manager.Settings.SubscriptionType == EventHubSubscriptionType.SearchSubscription;
			if (this.Manager.SubscriptionClient != null)
			{
				lock (JobLock)
				{
					try
					{
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Subscription = '{0}' Topic = '{1}'", this.Manager.Subscription.Name, this.Manager.Subscription.TopicPath));

						// take N at a time
						var messages = this.Manager.SubscriptionClient
							.ReceiveBatch(this.Manager.Settings.ReceiveBatchMessageCount, this.Manager.Settings.ReceiveBatchServerWaitTime)
							.Where(message => message != null);

						foreach (var message in messages)
						{
							message.Complete();

							var crmSubscriptionMessage = CrmSubscriptionMessageFactory.Create(message);

							if (crmSubscriptionMessage != null)
							{
								NotificationUpdateManager.Instance.UpdateNotificationMessageTable(crmSubscriptionMessage, isSearchSubscription);
							}
						}
					}
					catch (Exception e)
					{
						this.Manager.Reset();
						ADXTrace.Instance.TraceInfo(TraceCategory.Application, e.ToString());
					}
				}
			}
		}

19 Source : PortalCacheInvalidatorThread.cs
with MIT License
from Adoxio

private List<string> PostRequest(IEnumerable<PluginMessage> messages, bool isMetadataChangeMessage, bool isSearchIndexInvalidation = false)
		{
			List<string> enreplacediesWithSuccessfulInvalidation = new List<string>();
			try
			{
				var batchedMessages = messages
					.Where(mesg => mesg != null)
					.GroupBy(mesg => mesg.Target == null ? string.Empty : mesg.Target.LogicalName);

				foreach (var batchedmessage in batchedMessages)
				{
					List<OrganizationServiceCachePluginMessage> batchedPluginMessage = new List<OrganizationServiceCachePluginMessage>();
					var searchInvalidationDatum = new Dictionary<Guid, SearchIndexBuildRequest.SearchIndexInvalidationData>();

					foreach (var changedItem in batchedmessage)
					{
						if (changedItem != null)
						{
							if (changedItem.Target != null)
							{
								ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Posting Request for message with Enreplacedy: {0} and ChangeType: {1}", changedItem.Target.LogicalName, changedItem.MessageName));
							}

							var restartMessage = new ApplicationRestartPortalBusMessage();
							
							// Conversion to OrganizationServiceCachePluginMessage type
							var message = new OrganizationServiceCachePluginMessage();
							message.MessageName = changedItem.MessageName;
							message.RelatedEnreplacedies = changedItem.RelatedEnreplacedies;
							message.Relationship = changedItem.Relationship;
							message.Target = changedItem.Target;

							if (restartMessage.Validate(changedItem))
							{
								// The restart messages should be processed only once when the message is received from Cache subscription.
								if (!isSearchIndexInvalidation)
								{
									// restart the web application
									var task = restartMessage.InvokeAsync(new OwinContext()).WithCurrentCulture();
									task.GetAwaiter().GetResult();
									SearchIndexBuildRequest.ProcessMessage(message);
								}
							}
							else
							{
								if (!isSearchIndexInvalidation && FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching) && message.Target != null && message.Target.Id != Guid.Empty)
								{
									// Get relevant info for search index invalidation from content map before cache invalidation
									// MUST OCCUR BEFORE CACHE INVALIDATION
									if (!searchInvalidationDatum.ContainsKey(message.Target.Id))
									{
										searchInvalidationDatum.Add(message.Target.Id, GetSearchIndexInvalidationData(message));
									}
								}
								batchedPluginMessage.Add(message);
							}
						}
						else
						{
							//logging
							ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("ChangedItem Record is Null "));
						}
					}
					if (batchedPluginMessage.Count > 0)
					{
						if (isMetadataChangeMessage)
						{
							// Invalidate both search index as well as cache
							try
							{
								InvalidateSearchIndex(batchedPluginMessage, searchInvalidationDatum);
							}
							catch (Exception e)
							{
								// Even if exception occurs, we still need to invalidate cache, hence cathing exception here and logging error.
								ADXTrace.Instance.TraceError(TraceCategory.Exception, e.ToString());
							}
							InvalidateCache(batchedPluginMessage);
						}
						else if (isSearchIndexInvalidation)
						{
							InvalidateSearchIndex(batchedPluginMessage, searchInvalidationDatum);
						}
						else
						{
							// Invalidate cache
							InvalidateCache(batchedPluginMessage);
						}
					}

					enreplacediesWithSuccessfulInvalidation.Add(batchedmessage.Key);
				}
				return enreplacediesWithSuccessfulInvalidation;
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString());
				return enreplacediesWithSuccessfulInvalidation;
			}
		}

19 Source : WebAppConfigurationProvider.cs
with MIT License
from Adoxio

private static T GetAppSetting<T>(string appSetting)
		{
			try
			{
				//We are storing the appSetting in Azure app settings section.
				//ConfigurationManager reads the setting from Azure if it's running on cloud otherwise from app.config.
				string appSettingValue = ConfigurationManager.AppSettings[appSetting];
				if (appSettingValue != null)
				{
					return (T)Convert.ChangeType(appSettingValue, typeof(T));
				}
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString());
			}

			return default(T);
		}

19 Source : BingMapLookup.cs
with MIT License
from Adoxio

public virtual void SetGeoLocationCoordinates(OrganizationServiceContext context, Enreplacedy enreplacedy, string query)
		{
			var geocodeResult = GetGeocodeLocationByQuery(query);

			if (geocodeResult == null
				|| geocodeResult.resourceSets == null
				|| !geocodeResult.resourceSets.Any()
				|| geocodeResult.resourceSets.First().resources == null
				|| !geocodeResult.resourceSets.First().resources.Any()
				|| geocodeResult.resourceSets.First().resources.First().address == null
				|| geocodeResult.resourceSets.First().resources.First().point == null
				|| geocodeResult.resourceSets.First().resources.First().point.coordinates == null
				|| !geocodeResult.resourceSets.First().resources.First().point.coordinates.Any())
			{
				return;
			}

			var street = geocodeResult.resourceSets.First().resources.First().address.addressLine;
			var city = geocodeResult.resourceSets.First().resources.First().address.locality;
			var state = geocodeResult.resourceSets.First().resources.First().address.adminDistrict;
			var country = geocodeResult.resourceSets.First().resources.First().address.countryRegion;
			var formattedaddress = geocodeResult.resourceSets.First().resources.First().address.formattedAddress;
			var county = geocodeResult.resourceSets.First().resources.First().address.adminDistrict2;
			var postalcode = geocodeResult.resourceSets.First().resources.First().address.postalCode;

			decimal lareplacedude;

			if (!decimal.TryParse(geocodeResult.resourceSets.First().resources.First().point.coordinates[0], out lareplacedude))
			{
				return;
			}

			decimal longitude;

			if (!decimal.TryParse(geocodeResult.resourceSets.First().resources.First().point.coordinates[1], out longitude))
			{
				return;
			}

			try
			{
				enreplacedy.Attributes["adx_lareplacedude"] = lareplacedude;
				enreplacedy.Attributes["adx_longitude"] = longitude;
				enreplacedy.Attributes["adx_city"] = city;
				enreplacedy.Attributes["adx_stateprovince"] = state;
				enreplacedy.Attributes["adx_country"] = country;
				enreplacedy.Attributes["adx_formattedaddress"] = formattedaddress;
				enreplacedy.Attributes["adx_addressline"] = street;
				enreplacedy.Attributes["adx_county"] = county;
				enreplacedy.Attributes["adx_postalcode"] = postalcode;
				context.UpdateObject(enreplacedy);
				context.SaveChanges();
			}
			catch (Exception ex)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("SetGeoLocationCoordinates", "{0}", ex.ToString()));
            }
		}

19 Source : PortalSearchResultFactory.cs
with MIT License
from Adoxio

protected override Uri GetUrl(OrganizationServiceContext context, Doreplacedent doreplacedent, float score, int number, Enreplacedy enreplacedy)
		{
			if (enreplacedy == null)
			{
				return null;
			}

			var urlProvider = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<IEnreplacedyUrlProvider>();

			try
			{
				var url = urlProvider.GetUrl(context, enreplacedy);

				return url == null
					? null
					: new Uri(url, UriKind.RelativeOrAbsolute);
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error generating search result URL, returning null URL: {0}", e.ToString()));

                return null;
			}
		}

19 Source : RoleInstanceEndpointPortalSearchProvider.cs
with MIT License
from Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (config == null)
			{
				throw new ArgumentNullException("config");
			}

			if (string.IsNullOrEmpty(name))
			{
				name = GetType().Name;
			}

			base.Initialize(name, config);

			PortalName = config["portalName"];
			BindingConfiguration = config["bindingConfiguration"];

			var recognizedAttributes = new List<string>
			{
				"name",
				"description",
				"portalName",
				"bindingConfiguration"
			};

			// Remove all of the known configuration values. If there are any left over, they are unrecognized.
			recognizedAttributes.ForEach(config.Remove);

			if (config.Count > 0)
			{
				var unrecognizedAttribute = config.GetKey(0);

				if (!string.IsNullOrEmpty(unrecognizedAttribute))
				{
					throw new ProviderException("The search provider {0} does not currently recognize or support the attribute {1}.".FormatWith(name, unrecognizedAttribute));
				}
			}

			try
			{
				var serviceRoleName = RoleEnvironment.GetConfigurationSettingValue("Adxstudio.Xrm.Search.WindowsAzure.ServiceRole");

				if (string.IsNullOrEmpty(serviceRoleName))
				{
					throw new ProviderException("Configuration value Adxstudio.Xrm.Search.WindowsAzure.ServiceRole cannot be null or empty.");
				}

				Role serviceRole;

				if (!RoleEnvironment.Roles.TryGetValue(serviceRoleName, out serviceRole))
				{
					throw new ProviderException("Unable to retrieve the role {0}.".FormatWith(serviceRoleName));
				}

				var serviceEndpointName = RoleEnvironment.GetConfigurationSettingValue("Adxstudio.Xrm.Search.WindowsAzure.ServiceEndpoint");

				if (string.IsNullOrEmpty(serviceEndpointName))
				{
					throw new ProviderException("Configuration value Adxstudio.Xrm.Search.WindowsAzure.ServiceEndpoint cannot be null or empty.");
				}

				var serviceEndpoint = serviceRole.Instances.Select(instance =>
				{
					RoleInstanceEndpoint endpoint;

					return instance.InstanceEndpoints.TryGetValue(serviceEndpointName, out endpoint) ? endpoint : null;
				}).FirstOrDefault(endpoint => endpoint != null);

				if (serviceEndpoint == null)
				{
					throw new ProviderException("Unable to retrieve the endpoint {0} from role {1}.".FormatWith(serviceEndpointName, serviceRole.Name));
				}

				ServiceEndpointAddress = new EndpointAddress(string.Format(CultureInfo.InvariantCulture, "net.tcp://{0}/search", serviceEndpoint.IPEndpoint));

				var binding = string.IsNullOrEmpty(BindingConfiguration)
					? new NetTcpBinding(SecurityMode.None) { ReceiveTimeout = TimeSpan.FromDays(1), SendTimeout = TimeSpan.FromDays(1) }
					: new NetTcpBinding(BindingConfiguration);

				ServiceChannelFactory = new ChannelFactory<ISearchService>(binding);

				ServiceChannelFactory.Faulted += OnServiceChannelFactoryFaulted;
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format(@"Error initializing provider ""{0}"": {1}", name, e.ToString()));

                throw;
			}
		}

19 Source : RoleInstanceEndpointPortalSearchProvider.cs
with MIT License
from Adoxio

protected TResult UsingService<TResult>(Func<ISearchService, TResult> action, bool close = false)
		{
			try
			{
				var channel = ServiceChannelFactory.CreateChannel(ServiceEndpointAddress);

				try
				{
					return action(channel);
				}
				finally
				{
					if (close)
					{
						try
						{
							((IClientChannel)channel).Close();
						}
						catch
						{
							((IClientChannel)channel).Abort();
						}
					}
				}
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Service exception: {0}", e.ToString()));

                throw;
			}
		}

See More Examples