How do I access .env variables in tasks.json within vscode? - c#

I am trying to use environment variables within task in my tasks.json file of a C# project in vscode.
In my launch.json file I have this code to parse a .env file:
"configurations": [
{
...
"envFile": "${workspaceFolder}/.env",
}
]
I then have in the tasks.json file this task:
{
"label": "login",
"command": "sh",
"type": "shell",
"args": [
"${workspaceFolder}/etc/login.sh",
"${env:USERNAME}",
"${env:PASSWORD}"
]
}
This seems to be the code that's implied from https://code.visualstudio.com/docs/editor/tasks, however (from testing by echoing in another task) I have found these last two args to be blank. After researching online I think I have found the reason, the configurations..env is used by the tasks themselves rather than being accessible by task.json that run and so can't be accessed.
How do I create (use) these env variables within the tasks.json?

Checkout https://code.visualstudio.com/docs/editor/tasks-appendix
/**
* The environment of the executed program or shell. If omitted
* the parent process' environment is used.
*/
env?: { [key: string]: string };
example
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "diagnostic",
"type": "shell",
"options": {
"cwd": "${workspaceFolder}/beam",
"env": {
"FOO": "baz",
}
},
"command": "printenv",
"problemMatcher": []
}
]
}
There is no way I am aware of to pull these from a file like with launch.json
I would open an issue on the vscode repo

I had the same problem.
I am using Windows.
I was able to fix it.
The issue for me was, in VSCode I had this setting set:
"terminal.integrated.automationShell.windows": "C:/Program Files/Git/bin/bash.exe"
And this was causing the env to not load properly.
I was able to access the windows settings, that you would set from that windows GUI env variable tool. But I could not access env variables set in my .bashrc.
I commented out that setting.
I also have the Terminal > Integrated > Default Profile: Windows
set to Git Bash.
With these changes, I was able to access env variables in my .bashrc file.

Related

Getting data from Blazor Monaco editor fails/timeout if there is a lot of data

I am using a Blazor app with the Monaco editor. I use the SetValue() and GetValue() methods to write and read the content of the editor, which is working fine in most cases.
However, if there is a lot of data in there, then Blazor gets a timeout when GetValue() is called. I am reading in a JSON file, so I could remove some lines, and at some point, it is working fine again.
This is the code I am using to read the content of the editor:
string userRequirementsJson = await UserRequirementsEditor.GetValue();
The data that is in the editor is pasted below. It goes on for about 2000 lines, so I removed most of it.
[{
"feature": "<redacted>",
"path": [],
"priority": 9999
}, {
"feature": "<redacted>",
"path": [],
"priority": 9998
},
...
, {
"feature": "<redacted>",
"path": [],
"priority": 9996
}, {
"feature": "<redacted>",
"path": ["<redacted>", "<redacted>"],
"priority": 9999
}]
Does anyone know why it is possible to read around 1000 lines, but not 2000? And how can I fix this? Thanks in advance.

"Invalid URI: The format of the URI could not be determined", Need a solution or alternative method to create a connection to the DB

This is the error that I'm facing
System.UriFormatException: 'Invalid URI: The format of the URI could
not be determined.'
I have used IDocumentClient to create a connection to the DB
services.AddSingleton<IDocumentClient>(x => new DocumentClient(new Uri(Configuration["CosmosDB:URL"]), Configuration["CosmosDB:PrimaryKey"]));
Below given is my appsetings.json file from where the credentials are being acquired
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"CosmosDB": {
"URL": "https://localhost:8081",
"PrimaryKey": "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="
},
"DatabaseId": "FinanceProd"
}
UPDATE
This problem is very strange, I tried to reduce the package version, but they all work normally. So I think the problem is not the package version.
Maybe you can debug your program with breakpoints. Like ,
string URL = Configuration["CosmosDB:URL"];
string PrimaryKey = Configuration["CosmosDB:PrimaryKey"];
services.AddSingleton<IDocumentClient>(x => new DocumentClient(new Uri(Configuration["CosmosDB:URL"]), Configuration["CosmosDB:PrimaryKey"]));
If the problem is not solved, there really is no better way to configure the parameters
PRIVIOUS
Your code is right, but now you face this issue. I guess it may be caused by the version of the package.
I have created a core app which db is in local and try it success. My package version like bellow.
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.8.0" />
<PackageReference Include="Microsoft.Azure.DocumentDB.Core" Version="2.10.1" />
</ItemGroup>
So I suggest you update the package version first. If this is not possible, I suggest that you recreate the demo for testing. Perhaps the other part of the code interfered.

Microsoft Graph search files result misses path property in parentReference

When searching files in OneDrive for Business, the path of the parentReference is empty. Is there any reason for this limitation?
Example in MS Graph explorer:
GET https://graph.microsoft.com/v1.0/me/drive/root/search(q='finance')?select=name,parentReference
snippet from result:
"value": [
{
"#odata.type": "#microsoft.graph.driveItem",
"name": "CR-227 Product Overview.pptx",
"parentReference": {
"driveId": "b!-RIj2DuyvEyV1T4NlOaMHk8XkS_I8MdFlUCq1BlcjgmhRfAj3-Z8RY2VpuvV_tpd",
"driveType": "business",
"id": "01BYE5RZ6TAJHXA5GMWZB2HDLD7SNEXFFU",
"path": "/path/to/folder" <--- THIS IS MISSING
}
},
I would be glad if the path is returned because I need it. Otherwise I need to add additional overhead to query for the parent's paths.

TimeoutException: The Angular CLI process did not start listening for requests within the timeout period of 0 seconds

I'm getting this error after upgrading to angular 9. I'm using visual studio 2019, ASP .NET core with angular. Even if I create new project and update angular to 9 version, It stops working.
Complete list of page response is :
TimeoutException: The Angular CLI process did not start listening for requests within the timeout period of 0 seconds. Check the log output for error information. Microsoft.AspNetCore.SpaServices.Extensions.Util.TaskTimeoutExtensions.WithTimeout(Task task, TimeSpan timeoutDelay, string message) Microsoft.AspNetCore.SpaServices.Extensions.Proxy.SpaProxy.PerformProxyRequest(HttpContext context, HttpClient httpClient, Task baseUriTask, CancellationToken applicationStoppingToken, bool proxy404s) Microsoft.AspNetCore.Builder.SpaProxyingExtensions+<>c__DisplayClass2_0+<b__0>d.MoveNext() Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
My package.json is:
{
"name": "webapplication10",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"build:ssr": "ng run WebApplication10:server:dev",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"#angular/animations": "9.0.0",
"#angular/cdk": "~9.0.0",
"#angular/common": "9.0.0",
"#angular/compiler": "9.0.0",
"#angular/core": "9.0.0",
"#angular/forms": "9.0.0",
"#angular/material": "~9.0.0",
"#angular/platform-browser": "9.0.0",
"#angular/platform-browser-dynamic": "9.0.0",
"#angular/platform-server": "9.0.0",
"#angular/router": "9.0.0",
"#nguniversal/module-map-ngfactory-loader": "8.1.1",
"aspnet-prerendering": "^3.0.1",
"bootstrap": "^4.4.1",
"core-js": "^3.6.4",
"jquery": "3.4.1",
"oidc-client": "^1.10.1",
"popper.js": "^1.16.1",
"rxjs": "^6.5.4",
"tslib": "^1.10.0",
"zone.js": "~0.10.2"
},
"devDependencies": {
"#angular-devkit/build-angular": "^0.900.1",
"#angular/cli": "9.0.1",
"#angular/compiler-cli": "9.0.0",
"#angular/language-service": "9.0.0",
"#types/jasmine": "^3.5.3",
"#types/jasminewd2": "~2.0.8",
"#types/node": "^12.12.27",
"codelyzer": "^5.2.1",
"jasmine-core": "~3.5.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "^4.4.1",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "^2.1.1",
"karma-jasmine": "~3.1.1",
"karma-jasmine-html-reporter": "^1.5.2",
"typescript": "3.7.5"
},
"optionalDependencies": {
"node-sass": "^4.12.0",
"protractor": "~5.4.2",
"ts-node": "~8.4.1",
"tslint": "~5.20.0"
}
}
```
TL;DR
Sadly the issue seems related to some changes in the way Angular CLI starts up the angular part of the application. As per this issue:
https://github.com/dotnet/aspnetcore/issues/17277
proposed solutions are to set progress: true in angular.json or perform a simple echo prior to ng serve (https://github.com/dotnet/aspnetcore/issues/17277#issuecomment-562433864).
Full answer
I dug the asp.net core code base (https://github.com/dotnet/aspnetcore), looking how the Angular template starts up the Angular application.
The core engine that starts up the angular server is represented by two classes: AngularCliMiddleware (https://git.io/JvlaL) and NodeScriptRunner (https://git.io/Jvlaq).
In AngularCliMiddleware we find this code (I removed the original comments and added some of my own to explain a couple of things):
public static void Attach(ISpaBuilder spaBuilder, string npmScriptName)
{
var sourcePath = spaBuilder.Options.SourcePath;
if (string.IsNullOrEmpty(sourcePath))
{
throw new ArgumentException("Cannot be null or empty", nameof(sourcePath));
}
if (string.IsNullOrEmpty(npmScriptName))
{
throw new ArgumentException("Cannot be null or empty", nameof(npmScriptName));
}
// Start Angular CLI and attach to middleware pipeline
var appBuilder = spaBuilder.ApplicationBuilder;
var logger = LoggerFinder.GetOrCreateLogger(appBuilder, LogCategoryName);
var angularCliServerInfoTask = StartAngularCliServerAsync(sourcePath, npmScriptName, logger);
var targetUriTask = angularCliServerInfoTask.ContinueWith(
task => new UriBuilder("http", "localhost", task.Result.Port).Uri);
SpaProxyingExtensions.UseProxyToSpaDevelopmentServer(spaBuilder, () =>
{
var timeout = spaBuilder.Options.StartupTimeout;
return targetUriTask.WithTimeout(timeout,
$"The Angular CLI process did not start listening for requests " +
// === NOTE THIS LINE, THAT CARRIES THE "0 seconds" BUG!!!
$"within the timeout period of {timeout.Seconds} seconds. " +
$"Check the log output for error information.");
});
}
private static async Task<AngularCliServerInfo> StartAngularCliServerAsync(
string sourcePath, string npmScriptName, ILogger logger)
{
var portNumber = TcpPortFinder.FindAvailablePort();
logger.LogInformation($"Starting #angular/cli on port {portNumber}...");
var npmScriptRunner = new NpmScriptRunner(
sourcePath, npmScriptName, $"--port {portNumber}", null);
npmScriptRunner.AttachToLogger(logger);
Match openBrowserLine;
using (var stdErrReader = new EventedStreamStringReader(npmScriptRunner.StdErr))
{
try
{
// THIS LINE: awaits for the angular server to output
// the 'open your browser...' string to stdout stream
openBrowserLine = await npmScriptRunner.StdOut.WaitForMatch(
new Regex("open your browser on (http\\S+)", RegexOptions.None, RegexMatchTimeout));
}
catch (EndOfStreamException ex)
{
throw new InvalidOperationException(
$"The NPM script '{npmScriptName}' exited without indicating that the " +
$"Angular CLI was listening for requests. The error output was: " +
$"{stdErrReader.ReadAsString()}", ex);
}
}
var uri = new Uri(openBrowserLine.Groups[1].Value);
var serverInfo = new AngularCliServerInfo { Port = uri.Port };
await WaitForAngularCliServerToAcceptRequests(uri);
return serverInfo;
}
As you can see, the StartAngularCliServerAsync method creates a new NpmScriptRunner object, that is a wrapper around a Process.Start method call, basically, attaches the logger and then waits for the StdOut of the process to emit something that matches "open your browser on httpSOMETHING...".
Fun thing is this should work!
If you run ng serve (or npm run start) in ClientApp folder, once the server starts it still emit the output "open your browser on http...".
If you dotnet run the application, the node server actually starts, just enable all the logs in Debug mode, find the "Starting #angular/cli on port ..." line and try visiting localhost on that port, you'll see that your angular application IS running.
Problem is that for some reason the StdOut is not getting the "open your browser on" line anymore, nor it is written by the logger... it seems that in some way that particular output line from ng serve is held back, like it's no longer sent in the Stardard Output stream. The WaitForMatch method hits his timeout after 5 seconds and is catched from the code of the WithTimeout extension method, that outputs the (bugged) "... 0 seconds ..." message.
For what I could see, once you dotnet run your application, a series of processes is spawn in sequence, but i couldn't notice any difference in the command lines from Angular 8 to Angular 9.
My theory is that something has been changed in Angular CLI that prevents that line to be sent in stdout, so the .net proxy doesn't catch it and can't detect when the angular server is started.
As per this issue:
https://github.com/dotnet/aspnetcore/issues/17277
proposed solutions are to set progress: true in angular.json or perform a simple echo prior to ng serve (https://github.com/dotnet/aspnetcore/issues/17277#issuecomment-562433864).
I resolved it by changing:
"scripts": {
"start": "ng serve",
to:
"scripts": {
"start": "echo Starting... && ng serve",
in package.json
Here is what I did
from Fairlie Agile, commented out this line in main.ts
export { renderModule, renderModuleFactory } from '#angular/platform-server';
From Claudio Valerio
In angular.json , set
"progress": true,
Now I can run the app by clicking on F5 / Run IIS Express
Here is a workaround:
In package.json change the start-script from "ng serve" to "ngserve"
"scripts": {
"start": "ngserve",
In the same directory create a file ngserve.cmd with the following content:
#echo ** Angular Live Development Server is listening on localhost:%~2, open your browser on http://localhost:%~2/ **
ng serve %1 %~2
Now Dotnet gets the line it is waiting for. After that the command ng serve will start the server (so in fact the Angular Live Development Server is not yet listening), the browser will open, and first it won't work (ng serve still compiling), but if you press reload after a while, it should be fine.
This is just a workaround, but it works for us.
As suggested in https://developercommunity.visualstudio.com/solutions/446713/view.html, you should setup the StartupTimeout configuration setting.
Basically in Startup.cs:
app.UseSpa(spa =>
{
spa.Options.SourcePath = "./";
//Configure the timeout to 5 minutes to avoid "The Angular CLI process did not start listening for requests within the timeout period of 50 seconds." issue
spa.Options.StartupTimeout = new TimeSpan(0, 5, 0);
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
I added verbosity to the serving process in the file package.json like this.
"scripts": {
"ng": "ng",
"start": "ng serve --verbose",
"build": "ng build", ...
}, ...
No idea why it worked but I sense it somehow relates to causing the same slowdown as echo does.
to resolve the strict mode error remove this line from main.ts
export { renderModule, renderModuleFactory } from '#angular/platform-server';
This doesn't resolve the timeout issue however. I am also getting this error after upgrading to Angular 9 and using .NET core.
Running the angular app using "ng serve" and then changing your startup spa script to use UseProxyToSpaDevelopmentServer works as a work-around
I have changed in use spa pipeline configuration in configure method of startup class, It works for me.
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.StartupTimeout = new System.TimeSpan(0, 15, 0);
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
If you are doing backend work only, in your startup.cs comment out
spa.UseAngularCliServer(npmScript: "start");
and add
spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
Like so...
//spa.UseAngularCliServer(npmScript: "start");
spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");//Todo Switch back for SPA Dev
Run the SPA from cmd (in ClientApp Directory) via npm start.
Then when your run or debug your full app from Visual Studio, it will spin up so much faster.
In package.json change ng serve to ng serve --host 0.0.0.0
In my case there were TypeScript compile errors that were not caught by SpaServices or ts-node. There were references using the same file name with different namespaces that confused the runtime compiler. Execute ng build in the ClientApp folder and make sure there are no errors.
None of the solutions here worked for me.
The problem began after I upgrade components of my solution to their last versions.
The only thing that works for me is to upgrade my global angular cli to have same version as my local one :
npm uninstall -g angular-cli
npm cache clean
npm cache verify
npm install -g #angular/cli#latest
run npm install -g #angular/cli from command prompt
Change to .NET5 solves my problem.
You can also try this:
"scripts": {
"start": "echo start && ng serve",
or
"start": "ng serve --port 0000",
in package.json
I ran into a similar issue and I made the following updates in the package.json file
"scripts": {
"ng": "ng",
"start": "echo hello && ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
}
See github resolution in [dotnet/angular - issues/17277]
For development purpose if you are getting the error as 'TimeoutException: The Angular CLI process did not start listening for requests within the timeout period of 0 seconds.' .
Please follow these 2 steps which work for me as well :
In command prompt, Run the 'ng serve' command to run the angular solution.
In startup.cs file, change the start up timeout to minutes. even it will not take that much of time as angular solution is already running.
-> spa.Options.StartupTimeout = new TimeSpan(0, 5, 0);
Please mark the answer if it helps you !!
Thanks.
"scripts": {
"ng": "ng",
"start": **"ng serve --port 33719 --open",**
"build": "ng build",
Use the setting present in bold font in package.json
I did all of these successful suggestions. But the timeout issue was still there. In my case the following worked for me, (Will attach all the steps)
Comment the following line in main.ts to fix the strict mode issue
export { renderModule, renderModuleFactory } from '#angular/platform-server';
Change ng serve to echo Starting && ng serve in the package.json file
Just ran ng serve command manually using the Node.js Command Prompt. Then attempt to run the project in Visual Studio.
I received this error after my Visual Studio crashed while debugging. I couldn't make it go away using any of the above solutions. Eventually I deleted my project and cloned the code from the source. After that it loaded up just fine.
This was what worked for me:
In angular.json file,
I set
progress:true
Then run the app in visual studio 2019
None of the above worked consistently for me.
I experienced this even after upgrading to Angular 14 and net7.0. My symptoms were it would load fine the first couple of runs but then start to get bogged down after the app was stopped/run multiple times in one session.
I checked task manager and noticed multiple Node.js JavaScript Runtime processes piling up. Once I Ended those tasks, running the project from Visual Studio went back to normal and started up without issue.
The best approach is to insert this line at Startup
spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
And then run or debug your app from Visual Studio.

How can I make a VSCode theme recognize C# interfaces?

I am trying to get a theme for Visual Studio Code working to what I want. Currently, I'm trying to use Obsidian working with C# rules, but I'm not sure which key word to use to override color customizations. VSCode does not seem to recognize interfaces as they're language specific.
"editor.tokenColorCustomizations": {
"functions" :{
"foreground": "#F1F2F3"
},
"interface": { //not valid
"foreground": "#B48C8C"
}
}
How can I get VSCode color customizations to recognize c# specific syntaxes?
editor.tokenColorCustomizations can use a number of values: comments, functions, keywords, numbers, strings, types and variables. If none of those work for you textMateRules is available as well. So you can do something like:
"editor.tokenColorCustomizations": {
"textMateRules": [{
"scope": "yourScopeHere",
"settings": {
"fontStyle": "italic",
"foreground": "#C69650"
}
}]
},
So you just have to figure out what scope you need for "interface".
For that, try CTRL-Shift-P and type scope: choose
Developer: Inspect Editor Tokens and Scopes
and for whichever keyword is selected, like interface you will get a listing of its textmate scope. That should be inserted as the scope value above. [In my experience, it is more accurate to open the "Inspect TM Scopes" panel and then click a couple of items and then the one, like interface, that you want - the scope panel will remain open.] You can copy from the scopes panel.
You may need only the main scope listed, but if need to narrow its scope you can include the others listed in a comma-separated list in the scopes: ..., ..., ...
Based on Davi's answer:
Edit "C:\Program Files\Microsoft VS Code\resources\app\extensions\csharp\syntaxes\csharp.tmLanguage.json":
Find:
{"name":"storage.type.cs","match":"#?[[:alpha:]][[:alnum:]]*"}
Replace with:
{"name":"storage.type.interface.cs","match":"#?[I][[:upper:]][[:alpha:]][[:alnum:]]"},{"name":"storage.type.cs","match":"#?[_[:alpha:]][_[:alnum:]]"}
Add to settings.json:
"editor.tokenColorCustomizations": {
"[Default Dark+]": { // remove scope to apply to all themes
"textMateRules": [
{
"scope": "entity.name.type.interface.cs",
"settings": {
"foreground": "#b8d7a3"
}
},
{
"scope": "storage.type.interface.cs",
"settings": {
"foreground": "#b8d7a3"
}
}
]
}
},
VSCode 1.63.2:
Ctrl + Shift + P > Open Settings (JSON)
Paste this:
"editor.tokenColorCustomizations": {
"[Default Dark+]": {
"textMateRules": [
{
"scope": "entity.name.type.interface",
"settings": {
"foreground": "#a4ddaf"
}
}
]
}
},
I believe it can be partially done by editing "Program Files\Microsoft VS Code\resources\app\extensions\csharp\syntaxes" by adding support for "storage.type.interface.cs" with a regular expression that matches the convention.
Something like [I]([A-Z][a-z][A-Za-z]*)
You could also exclude possible mismatches like
IISManager, IPhoneDevice
https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide
https://www.apeth.com/nonblog/stories/textmatebundle.html
good luck with that and please let me know if you got it done

Categories

Resources