public override ICommandLineParserResult ParseArgs(string[] args) { Parser .Setup <int>('p', "port") .WithDescription($"Local port to listen on. Default: {DefaultPort}") .SetDefault(DefaultPort) .Callback(p => Port = p); Parser .Setup <int>('n', "nodeDebugPort") .WithDescription($"Port for node debugger to use. Default: value from launch.json or {DebuggerHelper.DefaultNodeDebugPort}") .SetDefault(DebuggerHelper.GetNodeDebuggerPort()) .Callback(p => NodeDebugPort = p); Parser .Setup <TraceLevel>('d', "debugLevel") .WithDescription($"Console trace level (off, verbose, info, warning or error). Default: {DefaultDebugLevel}") .SetDefault(DefaultDebugLevel) .Callback(p => ConsoleTraceLevel = p); Parser .Setup <string>("cors") .WithDescription($"A comma separated list of CORS origins with no spaces. Example: https://functions.azure.com,https://functions-staging.azure.com") .SetDefault(string.Empty) .Callback(c => CorsOrigins = c); Parser .Setup <int>('t', "timeout") .WithDescription($"Timeout for on the functions host to start in seconds. Default: {DefaultTimeout} seconds.") .SetDefault(DefaultTimeout) .Callback(t => Timeout = t); Parser .Setup <bool>("useHttps") .WithDescription("Bind to https://localhost:{port} rather than http://localhost:{port}. By default it creates and trusts a certificate.") .SetDefault(false) .Callback(s => UseHttps = s); Parser .Setup <bool>("ignoreHostJsonNotFound") .WithDescription($"Default is false. Ignores the check for {ScriptConstants.HostMetadataFileName} in current directory then up until it finds one.") .SetDefault(false) .Callback(f => IgnoreHostJsonNotFound = f); Parser .Setup <DebuggerType>("debug") .WithDescription("Default is None. Options are VSCode and VS") .SetDefault(DebuggerType.None) .Callback(d => Debugger = d); return(Parser.Parse(args)); }
public void OnDestroyTest() { var app = DebuggerHelper.GetApplication(); var console = app.Make <HttpDebuggerConsole>(); app.Release <HttpDebuggerConsole>(); string ret; ExceptionAssert.Throws <WebException>(() => { var statu = HttpHelper.Get("http://localhost:9478/", out ret); }); }
public void TestRepeatRegisterMonitor() { var app = DebuggerHelper.GetApplication(); var console = app.Make <HttpDebuggerConsole>(); var monitor = app.Make <IMonitor>(); var handler = new OnceRecordMonitorHandler("title", "ms", new[] { "tags" }, () => "helloworld"); monitor.Monitor(handler); console.Stop(); ExceptionAssert.Throws <RuntimeException>(() => { monitor.Monitor(handler); }); }
public override ICommandLineParserResult ParseArgs(string[] args) { var hostSettings = _secretsManager.GetHostStartSettings(); Parser .Setup <int>('p', "port") .WithDescription($"Local port to listen on. Default: {DefaultPort}") .SetDefault(hostSettings.LocalHttpPort == default(int) ? DefaultPort : hostSettings.LocalHttpPort) .Callback(p => Port = p); Parser .Setup <int>('n', "nodeDebugPort") .WithDescription($"Port for node debugger to use. Default: value from launch.json or {DebuggerHelper.DefaultNodeDebugPort}") .SetDefault(DebuggerHelper.GetNodeDebuggerPort()) .Callback(p => NodeDebugPort = p); Parser .Setup <TraceLevel>('d', "debugLevel") .WithDescription($"Console trace level (off, verbose, info, warning or error). Default: {DefaultDebugLevel}") .SetDefault(DefaultDebugLevel) .Callback(p => ConsoleTraceLevel = p); Parser .Setup <string>("cors") .WithDescription($"A comma separated list of CORS origins with no spaces. Example: https://functions.azure.com,https://functions-staging.azure.com") .SetDefault(hostSettings.Cors ?? string.Empty) .Callback(c => CorsOrigins = c); Parser .Setup <int>('t', "timeout") .WithDescription($"Timeout for on the functions host to start in seconds. Default: {DefaultTimeout} seconds.") .SetDefault(DefaultTimeout) .Callback(t => Timeout = t); Parser .Setup <bool>("useHttps") .WithDescription("Bind to https://localhost:{port} rather than http://localhost:{port}. By default it creates and trusts a certificate.") .SetDefault(false) .Callback(s => UseHttps = s); Parser .Setup <DebuggerType>("debug") .WithDescription("Default is None. Options are VSCode and VS") .SetDefault(DebuggerType.None) .Callback(d => Debugger = d); return(Parser.Parse(args)); }
public override bool Execute() { // report to VS output window what step the build is Log.LogMessage(MessageImportance.Normal, "Generating binary output file..."); // wait for debugger on var DebuggerHelper.WaitForDebuggerIfEnabled(TasksConstants.BuildTaskDebugVar); // default with null, indicating that we've generated nothing FileWritten = null; // get paths for PE files // rename extension .dll with .pe List <string> peCollection = new List <string>(); peCollection = AssemblyReferences?.Select(a => { return(a.GetMetadata("FullPath").Replace(".dll", ".pe").Replace(".exe", ".pe")); }).ToList(); // add executable PE peCollection.Add(AssemblyPE); // get executable path and file name // rename executable extension .exe with .bin var binOutputFile = Assembly.Replace(".exe", ".bin"); using (FileStream binFile = new FileStream(binOutputFile, FileMode.Create)) { // now we will re-deploy all system assemblies foreach (string peItem in peCollection) { // append to the deploy blob the assembly using (FileStream fs = File.Open(peItem, FileMode.Open, FileAccess.Read)) { long length = (fs.Length + 3) / 4 * 4; byte[] buffer = new byte[length]; fs.Read(buffer, 0, (int)fs.Length); // copy this assembly to the bin file too binFile.Write(buffer, 0, (int)length); } } } // bin file written FileWritten = new TaskItem(binOutputFile); return(true); }
public void TestGetMonitor() { var app = DebuggerHelper.GetApplication(); var console = app.Make <HttpDebuggerConsole>(); var monitor = app.Make <IMonitor>(); var handler = new OnceRecordMonitorHandler("title", "ms", new [] { "tags" }, () => "helloworld"); monitor.Monitor(handler); string ret; var statu = HttpHelper.Get("http://localhost:9478/debug/monitor/get-monitors", out ret); console.Stop(); Assert.AreEqual(HttpStatusCode.OK, statu); Assert.AreEqual("{\"Response\":[{\"name\":\"title\",\"value\":\"helloworld\",\"unit\":\"ms\",\"tags\":[\"tags\"]}]}", ret); }
public void TestForEachMonitor() { var app = DebuggerHelper.GetApplication(); var console = app.Make <HttpDebuggerConsole>(); var monitor = app.Make <MonitorStore>(); console.Stop(); var handler = new OnceRecordMonitorHandler("title", "ms", new[] { "tags" }, () => "helloworld"); monitor.Monitor(handler); foreach (var result in monitor) { Assert.AreEqual(handler, result); break; } }
protected override string GenerateInitialization() { var stringBuilder = new StringBuilder(); var membersCount = int.Parse(DebuggerHelper.GetValue(ExpressionsHelper.ItemsCount(_variableName))); var type = DebuggerHelper.GetValue(ExpressionsHelper.TypeFullName(_variableName)).Replace("\"", String.Empty).Replace("+", ".").Replace("[]", "()"); stringBuilder.AppendLine(String.Concat(Indentation.ToString(), "New ", type, " {")); var membersInitialization = MembersInitializationHelper.GetMembersInitialization(_variableName, membersCount); stringBuilder.Append(membersInitialization); stringBuilder.Append(String.Concat(Indentation.ToString(), "}")); return(stringBuilder.ToString()); }
static void Main(string[] args) { var nunit = Process.Start(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "NUnit 2.6.4", "bin", "nunit-x86.exe"), Assembly.GetEntryAssembly().Location); var existingAgents = Process.GetProcessesByName("nunit-agent-x86").Select(x => x.Id).ToList(); Process nunitAgentProcess = null; while (nunitAgentProcess == null) { nunitAgentProcess = Process.GetProcessesByName("nunit-agent-x86").Where(x => !existingAgents.Contains(x.Id)).FirstOrDefault(); Thread.Sleep(100); } var vs = DebuggerHelper.GetCurrentVSInstance(); if (vs != null) { DebuggerHelper.AttachDebuggerToProcess(vs, nunitAgentProcess, "Managed (v4.5, v4.0)"); } }
public void TestSetSkip() { logLevel = string.Empty; var app = DebuggerHelper.GetApplication(false); var logger = app.Make <ILogger>(); ExceptionAssert.DoesNotThrow(() => { (logger as Logger).SetSkip(0); }); ExceptionAssert.DoesNotThrow(() => { (logger as Logger).SetSkip(10, () => { }); }); }
private async Task WriteLaunchJson() { var setupNodeDebugResult = await DebuggerHelper.TrySetupDebuggerAsync(); if (setupNodeDebugResult == DebuggerStatus.Created) { ColoredConsole.WriteLine("Created launch.json"); } else if (setupNodeDebugResult == DebuggerStatus.Updated) { ColoredConsole.WriteLine("Added Azure Functions attach target to existing launch.json"); } else if (setupNodeDebugResult == DebuggerStatus.AlreadyCreated) { ColoredConsole.WriteLine("launch.json already configured. Skipped!"); } else if (setupNodeDebugResult == DebuggerStatus.Error) { ColoredConsole.Error.WriteLine(ErrorColor("Unable to configure launch.json. Check the file for more info")); } }
public void RepeatStartTest() { var app = DebuggerHelper.GetApplication(); var console = app.Make <HttpDebuggerConsole>(); console.Start(); string ret; HttpStatusCode statu; try { statu = HttpHelper.Get("http://localhost:9478/", out ret); } finally { console.Stop(); } Assert.AreEqual(HttpStatusCode.OK, statu); }
protected override string GenerateInitialization() { var stringBuilder = new StringBuilder(); var membersType = ListInitializationHelper.GetListMembersType(_variableName); var membersCount = int.Parse(DebuggerHelper.GetValue(ExpressionsHelper.ItemsCount(_variableName))); stringBuilder.AppendLine(string.Concat("new System.Collections.Generic.List<", membersType, ">()")); if (membersCount > 0) { stringBuilder.AppendLine(string.Concat(Indentation.ToString(), "{")); var membersInitialization = MembersInitializationHelper.GetMembersInitialization(_variableName, membersCount); stringBuilder.AppendLine(membersInitialization); stringBuilder.Append(string.Concat(Indentation.ToString(), "}")); } return(stringBuilder.ToString()); }
public void TestSetSkip() { logLevel = string.Empty; var app = DebuggerHelper.GetApplication(false); var logger = app.Make <ILogger>(); ExceptionAssert.DoesNotThrow(() => { (logger as Logger).SetSkip(0); }); ExceptionAssert.DoesNotThrow(() => { (logger as Logger).SetSkip(10, () => { var flag = BindingFlags.Instance | BindingFlags.NonPublic; var type = logger.GetType(); var field = type.GetField("skipFrames", flag); Assert.AreEqual(10, (int)field.GetValue(logger)); }); }); }
public void TestMissingMethodExceptionMonitor() { var app = DebuggerHelper.GetApplication(); var console = app.Make <HttpDebuggerConsole>(); var monitor = app.Make <IMonitor>(); App.Instance("Debugger.WebMonitor.Monitor.IndexMonitor", new List <string> { "test", }); monitor.Monitor(new ThrowMissingMethodExceptionHandler()); string ret; var statu = HttpHelper.Get("http://localhost:9478/debug/monitor/get-monitors-index", out ret); console.Stop(); Assert.AreEqual(HttpStatusCode.OK, statu); Assert.AreEqual( "{\"Response\":[{\"name\":\"test\",\"value\":\"code.notSupport\",\"unit\":\"\",\"tags\":[\"tag\"]}]}", ret); }
public virtual IHttpActionResult CheckRequestSuspendedByDebugger(string requestToken) { AppInfo appInfo = null; HeContext context = null; try { appInfo = AppInfo.GetAppInfo(); if (appInfo == null || !appInfo.IsApplicationEnabled) { return(GetErrorResponseResult("Application Backend Unavailable", HttpStatusCode.ServiceUnavailable)); } ValidateRequestSecurity(); context = appInfo.OsContext; var isRequestSupended = DebuggerHelper.HasSuspendedThreadWithRequestToken(requestToken); return(GetResponseResult(typeof(bool), isRequestSupended)); } catch (Exception ex) { DatabaseAccess.FreeupResources(false); var licensingException = ex as LicensingException; if (licensingException != null) { return(GetErrorResponseResult("Application Backend Unavailable", HttpStatusCode.ServiceUnavailable)); } var exposeRestException = ex as ExposeRestException; if (exposeRestException != null) { ErrorLog.LogApplicationError(exposeRestException, appInfo, context, "Module Services"); return(GetErrorResponseResult(exposeRestException.Message, exposeRestException.StatusCode)); } ErrorLog.LogApplicationError(ex, appInfo, context, "Module Services"); return(GetErrorResponseResult("Internal Server Error", HttpStatusCode.InternalServerError)); } }
public void TestNotFound() { var app = DebuggerHelper.GetApplication(); var console = app.Make <HttpDebuggerConsole>(); bool isThrow = false; try { string ret; var statu = HttpHelper.Get("http://localhost:9478/notfound/notfound/notfound", out ret); } catch (WebException ex) { Assert.AreEqual(WebExceptionStatus.ProtocolError, ex.Status); isThrow = true; } finally { console.Stop(); } Assert.AreEqual(true, isThrow); }
public static string GetListMembersType(string variableName) { return(DebuggerHelper.GetValue(ExpressionsHelper.ListMembersType(variableName)).Replace("\"", string.Empty).Replace("+", ".")); }
public override bool Execute() { // report to VS output window what step the build is Log.LogMessage(MessageImportance.Normal, "Generating nanoResources nanoFramework assembly..."); // wait for debugger on var DebuggerHelper.WaitForDebuggerIfEnabled(TasksConstants.BuildTaskDebugVar); try { // If there are no sources to process, just return (with success) and report the condition. if ((Sources == null) || (Sources.Length == 0)) { Log.LogMessage(MessageImportance.Low, "GenerateResource.NoSources"); // Indicate we generated nothing OutputResources = null; return(true); } if (!ValidateParameters()) { // Indicate we generated nothing OutputResources = null; return(false); } // In the case that OutputResources wasn't set, build up the outputs by transforming the Sources if (!CreateOutputResourcesNames()) { // Indicate we generated nothing OutputResources = null; return(false); } // First we look to see if we have a resgen linked files cache. If so, then we can use that // cache to speed up processing. ReadStateFile(); bool nothingOutOfDate = true; List <ITaskItem> inputsToProcess = new List <ITaskItem>(); List <ITaskItem> outputsToProcess = new List <ITaskItem>(); // decide what sources we need to build for (int i = 0; i < Sources.Length; ++i) { // Attributes from input items are forwarded to output items. //Sources[i].CopyMetadataTo(OutputResources[i]); if (!File.Exists(Sources[i].ItemSpec)) { // Error but continue with the files that do exist Log.LogError("GenerateResource.ResourceNotFound", Sources[i].ItemSpec); UnsuccessfullyCreatedOutFiles.Add(OutputResources[i].ItemSpec); } else { // check to see if the output resources file (and, if it is a .resx, any linked files) // is up to date compared to the input file if (ShouldRebuildResgenOutputFile(Sources[i].ItemSpec, OutputResources[i].ItemSpec)) { nothingOutOfDate = false; inputsToProcess.Add(Sources[i]); outputsToProcess.Add(OutputResources[i]); } } } if (nothingOutOfDate) { Log.LogMessage("GenerateResource.NothingOutOfDate"); } else { // Prepare list of referenced assemblies AssemblyName[] assemblyList; try { //only load system.drawing, mscorlib. no parameters needed here?!! assemblyList = LoadReferences(); } catch (ArgumentException e) { Log.LogError("GenerateResource.ReferencedAssemblyNotFound - {0}: {1}", e.ParamName, e.Message); OutputResources = null; return(false); } // always create a separate AppDomain because an assembly would be locked. AppDomain appDomain = null; ProcessResourceFiles process = null; try { appDomain = AppDomain.CreateDomain ( "generateResourceAppDomain", null, AppDomain.CurrentDomain.SetupInformation ); object obj = appDomain.CreateInstanceFromAndUnwrap ( typeof(ProcessResourceFiles).Module.FullyQualifiedName, typeof(ProcessResourceFiles).FullName ); Type processType = obj.GetType(); process = (ProcessResourceFiles)obj; //setup strongly typed class name?? process.Run(Log, assemblyList, (ITaskItem[])inputsToProcess.ToArray(), (ITaskItem[])outputsToProcess.ToArray(), UseSourcePath); if (null != process.UnsuccessfullyCreatedOutFiles) { foreach (string item in process.UnsuccessfullyCreatedOutFiles) { UnsuccessfullyCreatedOutFiles.Add(item); } } process = null; } finally { if (appDomain != null) { AppDomain.Unload(appDomain); process = null; appDomain = null; } } } // And now we serialize the cache to save our resgen linked file resolution for later use. WriteStateFile(); RemoveUnsuccessfullyCreatedResourcesFromOutputResources(); RecordFilesWritten(); } catch (Exception ex) { Log.LogError("nanoFramework GenerateNanoResourceTask error: " + ex.Message); } // if we've logged any errors that's because there were errors (WOW!) return(!Log.HasLoggedErrors); }
public override async Task RunAsync() { using (var client = await _scriptServer.ConnectAsync(Timeout, NoInteractive)) { var hostStatusResponse = await client.GetAsync("admin/host/status"); var functionStatusResponse = await client.GetAsync($"admin/functions/{FunctionName}/status"); if (!hostStatusResponse.IsSuccessStatusCode) { ColoredConsole .Error .WriteLine(ErrorColor($"Error calling the functions host: {hostStatusResponse.StatusCode}")); return; } else if (!functionStatusResponse.IsSuccessStatusCode) { ColoredConsole .Error .WriteLine(ErrorColor($"Error calling function {FunctionName}: {functionStatusResponse.StatusCode}")); return; } var functionMetadata = ScriptHostHelpers.GetFunctionMetadata(FunctionName); var hostStatus = await hostStatusResponse.Content.ReadAsAsync <HostStatus>(); Func <IEnumerable <string>, string, bool> printError = (errors, title) => { if (errors?.Any() == true) { ColoredConsole .Error .WriteLine(ErrorColor(title)); foreach (var error in errors) { ColoredConsole .Error .WriteLine(ErrorColor($"\t{error}")); } return(true); } return(false); }; if (printError(hostStatus.Errors, "The function host has the following errors:") || printError(hostStatus.Errors, $"Function {FunctionName} has the following errors:")) { return; } if (Debug) { var scriptType = functionMetadata.ScriptType; if (scriptType != ScriptType.CSharp && scriptType != ScriptType.Javascript) { ColoredConsole .Error .WriteLine(ErrorColor($"Only C# and Javascript functions are currently supported for debugging.")); return; } if (scriptType == ScriptType.CSharp) { ColoredConsole .WriteLine("Debugger launching...") .WriteLine("Setup your break points, and hit continue!"); await DebuggerHelper.AttachManagedAsync(client); } else if (scriptType == ScriptType.Javascript) { var nodeDebugger = await DebuggerHelper.TrySetupNodeDebuggerAsync(); if (nodeDebugger == NodeDebuggerStatus.Error) { ColoredConsole .Error .WriteLine(ErrorColor("Unable to configure node debugger. Check your launch.json.")); return; } else if (!NoInteractive) { ColoredConsole.WriteLine("launch.json configured."); } else { ColoredConsole .Write("launch.json configured. Setup your break points, launch debugger (F5), and press any key to continue..."); Console.ReadKey(); } } } var invocation = string.IsNullOrEmpty(FileName) ? Content : await FileSystemHelpers.ReadAllTextFromFileAsync(FileName); invocation = invocation ?? string.Empty; var adminInvocation = JsonConvert.SerializeObject(new FunctionInvocation { Input = invocation }); if (functionMetadata.IsHttpFunction()) { ColoredConsole.WriteLine(WarningColor("NOTE: the 'func run' command only supports POST for HTTP triggers. For other verbs, consider a REST client like cURL or Postman.")); } var response = functionMetadata.IsHttpFunction() ? await client.PostAsync($"api/{FunctionName}", new StringContent(invocation, Encoding.UTF8, invocation.IsJson() ? "application/json" : "plain/text")) : await client.PostAsync($"admin/functions/{FunctionName}", new StringContent(adminInvocation, Encoding.UTF8, "application/json")); ColoredConsole.WriteLine($"{TitleColor($"Response Status Code:")} {response.StatusCode}"); var contentTask = response.Content?.ReadAsStringAsync(); if (contentTask != null) { var content = await contentTask; if (!response.IsSuccessStatusCode) { try { var exception = JsonConvert.DeserializeObject <JObject>(content); if (exception?["InnerException"]?["ExceptionMessage"]?.ToString() == "Script compilation failed.") { ColoredConsole.Error.WriteLine(ErrorColor("Script compilation failed.")); return; } } catch { } } ColoredConsole.WriteLine(await contentTask); } } }
public override async Task RunAsync() { if (SourceControl != SourceControl.Git) { throw new Exception("Only Git is supported right now for vsc"); } if (!string.IsNullOrEmpty(FolderName)) { var folderPath = Path.Combine(Environment.CurrentDirectory, FolderName); FileSystemHelpers.EnsureDirectory(folderPath); Environment.CurrentDirectory = folderPath; } foreach (var pair in fileToContentMap) { if (!FileSystemHelpers.FileExists(pair.Key.Value)) { ColoredConsole.WriteLine($"Writing {pair.Key}"); await FileSystemHelpers.WriteAllTextToFileAsync(pair.Key.Value, pair.Value); } else { ColoredConsole.WriteLine($"{pair.Key} already exists. Skipped!"); } } var setupNodeDebugResult = await DebuggerHelper.TrySetupNodeDebuggerAsync(); if (setupNodeDebugResult == NodeDebuggerStatus.Created) { ColoredConsole.WriteLine("Created launch.json"); } else if (setupNodeDebugResult == NodeDebuggerStatus.Updated) { ColoredConsole.WriteLine("Added Azure Functions attach target to existing launch.json"); } else if (setupNodeDebugResult == NodeDebuggerStatus.AlreadyCreated) { ColoredConsole.WriteLine("launch.json already configured. Skipped!"); } else if (setupNodeDebugResult == NodeDebuggerStatus.Error) { ColoredConsole.Error.WriteLine(ErrorColor("Unable to configure launch.json. Check the file for more info")); } if (InitSourceControl) { try { var checkGitRepoExe = new Executable("git", "rev-parse --git-dir"); var result = await checkGitRepoExe.RunAsync(); if (result != 0) { var exe = new Executable("git", $"init"); await exe.RunAsync(l => ColoredConsole.WriteLine(l), l => ColoredConsole.Error.WriteLine(l)); } else { ColoredConsole.WriteLine("Directory already a git repository."); } } catch (FileNotFoundException) { ColoredConsole.WriteLine(WarningColor("unable to find git on the path")); } } }
protected override string GenerateInitialization() { return(DebuggerHelper.GetValue(_variableName).Replace(",", ".")); }