public async Task <string> CallServer(string path, ServerPostData postData, bool callSync)
        {
            await EnsureNodeProcessIsRunning(callSync);

            string url  = $"{BASE_URL}:{BasePort}/{path.ToLowerInvariant()}";
            string json = JsonConvert.SerializeObject(postData);

            try
            {
                using (WebClient client = new WebClient())
                {
                    if (callSync)
                    {
                        Task <string> task = Task.Run(async() =>
                                                      await client.UploadStringTaskAsync(url, json));
                        bool completed = task.Wait(5000);
                        if (!completed)
                        {
                            throw new Exception("TsLint call on build timed out.  Timeout is 5 seconds.");
                        }
                        return(completed ? task.Result : null);
                    }
                    else
                    {
                        return(await client.UploadStringTaskAsync(url, json));
                    }
                }
            }
            catch (WebException ex)
            {
                Debug.WriteLine(ex.Message);
                Down();
                return(string.Empty);
            }
        }
Exemple #2
0
        protected async Task <string> RunProcess(params FileInfo[] files)
        {
            var postMessage = new ServerPostData
            {
                Config = Path.Combine(FindWorkingDirectory(files[0]), ConfigFileName),
                Files  = files.Select(f => f.FullName)
            };

            return(await Server.CallServerAsync(Name, postMessage));
        }
Exemple #3
0
        protected async Task<string> RunProcess(params FileInfo[] files)
        {
            var postMessage = new ServerPostData
            {
                Config = Path.Combine(FindWorkingDirectory(files[0]), ConfigFileName),
                Files = files.Select(f => f.FullName)
            };

            return await Server.CallServerAsync(Name, postMessage);
        }
Exemple #4
0
        private async Task <LintingResult> Lint(bool callSync, params FileInfo[] files)
        {
            // The ng lint runner doesn't need the files list, does need tslint.json
            ServerPostData postData = CreatePostData(files);
            string         output   = _settings.UseProjectNGLint ? await _localNgLintRunner.Run(Name, postData, callSync) :
                                      await Server.CallServer(Name, postData, callSync);

            if (!string.IsNullOrEmpty(output))
            {
                ParseErrors(output);
            }
            return(_result);
        }
        private ServerPostData CreatePostData(string[] files)
        {
            ServerPostData postData = new ServerPostData
            {
                Config      = Path.Combine(FindWorkingDirectory(files[0]), ConfigFileName),
                Files       = files,
                FixErrors   = _fixErrors,
                UseTSConfig = _settings.UseTsConfig
            };

#if DEBUG
            postData.Debug = true;
#endif
            return(postData);
        }
Exemple #6
0
        private ServerPostData CreatePostData(FileInfo[] files)
        {
            ServerPostData postData = new ServerPostData
            {
                Config      = Path.Combine(FindWorkingDirectory(files[0]), ConfigFileName).Replace("\\", "/"),
                Files       = files.Select(f => f.FullName.Replace("\\", "/")),
                FixErrors   = _fixErrors,
                UseTSConfig = _settings.UseTsConfig
            };

#if DEBUG
            postData.Debug = true;
#endif
            return(postData);
        }
Exemple #7
0
        protected async Task <string> RunProcess(bool callSync, params FileInfo[] files)
        {
            var postMessage = new ServerPostData
            {
                Config      = Path.Combine(FindWorkingDirectory(files[0]), ConfigFileName).Replace("\\", "/"),
                Files       = files.Select(f => f.FullName.Replace("\\", "/")),
                FixErrors   = FixErrors,
                UseTSConfig = Settings.UseTsConfig
            };

#if DEBUG
            postMessage.Debug = true;
#endif

            return(await Server.CallServer(Name, postMessage, callSync));
        }
        public async Task <LintingResult> Lint(bool callSync, params string[] files)
        {
            _result = new LintingResult(files);
            if (!_settings.TSLintEnable || !files.Any())
            {
                return(_result);
            }
            ServerPostData postData = CreatePostData(files);
            string         output   = _settings.UseProjectNGLint ? await _localNgLintRunner.Run(Name, postData, callSync) :
                                      await Server.CallServer(Name, postData, callSync, _log);

            if (!string.IsNullOrEmpty(output))
            {
                ParseErrors(output, isCalledFromBuild: callSync);
            }
            return(_result);
        }
        private async Task <string> RunLocalProcess(bool callSync, ServerPostData postData)
        {
            FileInfo         configFile = new FileInfo(postData.Config);
            ProcessStartInfo startInfo  = new ProcessStartInfo()
            {
                FileName               = "cmd.exe",
                Arguments              = $"/c \"ng lint --type-check {(postData.FixErrors ? "--fix " : "")} --format JSON \"",
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                WindowStyle            = ProcessWindowStyle.Hidden,
                CreateNoWindow         = true,
                WorkingDirectory       = configFile.DirectoryName,
                UseShellExecute        = false
            };
            string stdOut = "";
            string stdErr = "";

            if (callSync)
            {
                // Actually I think the old process blocks the UI thread anyway
                // so we can use RunLocalProcessSync in the async case as well
                stdOut = RunLocalProcessSync(startInfo, out stdErr);
            }
            else
            {
                Process localLintProcess = new Process {
                    StartInfo = startInfo, EnableRaisingEvents = true
                };
                localLintProcess.Start();
                stdOut = await Task.Run(() => { return(localLintProcess.StandardOutput.ReadToEnd()); });

                stdErr = await Task.Run(() => { return(localLintProcess.StandardError.ReadToEnd()); });

                localLintProcess.WaitForExit();
            }

            if (!string.IsNullOrWhiteSpace(stdErr))
            {
                string message = $@"Unable to LOCAL ng lint. : config: { configFile }, dir: { configFile.DirectoryName }
tslint Output: {stdErr} ";
                throw new FormatException(message, new InvalidOperationException(stdErr));
            }

            return(stdOut);
        }
        internal async Task <string> Run(string name, ServerPostData postData, bool callSync)
        {
            string output = null;

            try
            {
                output = await RunLocalProcess(callSync, postData);

                CallLog("Lint with local 'ng lint' succeeded", showWarning: false);
            }
            catch (Exception ex)
            {
                string message = "Attempted to lint with local 'ng lint' and failed.  Falling back to regular lint call.  ";
                message += $"Error message:\n{ex.Message}";
                CallLog(message, showWarning: true);
                output = await Linter.Server.CallServer(name, postData, callSync, _log);
            }
            return(output);
        }
Exemple #11
0
        public async Task <string> CallServerAsync(string path, ServerPostData postData)
        {
            await EnsureInitializedAsync();

            string url  = $"{BASE_URL}:{BasePort}/{path.ToLowerInvariant()}";
            string json = JsonConvert.SerializeObject(postData);

            try
            {
                using (WebClient client = new WebClient())
                {
                    return(await client.UploadStringTaskAsync(url, json));
                }
            }
            catch (WebException)
            {
                Down();
                return(string.Empty);
            }
        }
Exemple #12
0
        public async Task<string> CallServerAsync(string path, ServerPostData postData)
        {
            await EnsureInitializedAsync();

            string url = $"{BASE_URL}:{BasePort}/{path.ToLowerInvariant()}";
            string json = JsonConvert.SerializeObject(postData);

            try
            {
                using (WebClient client = new WebClient())
                {
                    return await client.UploadStringTaskAsync(url, json);
                }
            }
            catch (WebException ex)
            {
                Telemetry.TrackException(ex);
                Down();
                return string.Empty;
            }
        }
        public async Task <string> CallServer(string path, ServerPostData postData, bool callSync, Action <string, bool> log)
        {
            try
            {
                await EnsureNodeProcessIsRunning(callSync);

                string url  = $"{BASE_URL}:{BasePort}/{path.ToLowerInvariant()}";
                string json = JsonConvert.SerializeObject(postData);

                using (WebClient client = new WebClient())
                {
                    if (callSync)
                    {
                        Task <string> task = Task.Run(async() =>
                                                      await client.UploadStringTaskAsync(url, json));
                        bool completed = task.Wait(60000);
                        if (!completed)
                        {
                            throw new Exception("TsLint call on build timed out.  Timeout is 60 seconds.");
                        }
                        return(completed ? task.Result : null);
                    }
                    else
                    {
                        Benchmark.Log("Before server call");
                        var result = await client.UploadStringTaskAsync(url, json);

                        Benchmark.Log("After server call");
                        return(result);
                    }
                }
            }
            catch (WebException ex)
            {
                try
                {
                    if (ex.Response == null)
                    {
                        log?.Invoke(ex.ToString(), true);
                        // e.g. if firewall blocks connection: "Unable to connect to the remote server"
                        return("Failed to communicate with TsLint server: " + ex.Message + (ex.InnerException != null ? " --> " + ex.InnerException.Message : ""));
                    }

                    var     resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                    dynamic obj  = JsonConvert.DeserializeObject(resp);
                    if (obj.error == true)
                    {
                        string  exceptionString = obj.exception;
                        dynamic exception       = JsonConvert.DeserializeObject(exceptionString);
                        log?.Invoke("TsLint reported error: " + Environment.NewLine
                                    + JsonConvert.SerializeObject(exception, Formatting.Indented).Replace("\\n", "\n"), true);
                        string messageFromServer = obj.message;
                        return(messageFromServer);
                    }
                    log?.Invoke("WebException without error from TsLint. Response: " + resp, true);
                    return("Internal error");
                }
                catch (Exception innerEx)
                {
                    // This should never happen, since server.js always returns JSON object
                    log?.Invoke("Invalid response from TsLint server: " + innerEx.ToString(), true);
                    return("Internal error");
                }
                finally
                {
                    Down();
                }
            }
            catch (Exception ex)
            {
                log?.Invoke(ex.ToString(), true);
                // e.g. if EXE not found or fails to start due to port-in-use error
                Down();
                return("Failed to start TsLint server: " + ex.Message + (ex.InnerException != null ? " --> " + ex.InnerException.Message : ""));
            }
        }