Not able to debug Azure Functions in Visual Studio Code. Debugger stops - azure

I am using http trigger Azure Function. When I am running my application (by pressing F5), after clicking http://localhost:7071/api/HttpTrigger1, I am getting response in browser but code doesn't stop at breakpoints.
After careful observation, I saw that debugger starts for 0.5 seconds and closes automatically.
I have posted the video here. At 5th second, we can see that debugger starts but closes instantly (Orange screen at 5th second).
There is a similar question on Stackoverflow, but that didn't solve my problem.

I have experienced the same, while debugging Azure Functions in VS Code on a Mac. I found this open issue on the Omnisharp GitHub about this issue:
https://github.com/OmniSharp/omnisharp-vscode/issues/4903
In the end, basilfx's workaround ended up helping me:
I was triggered by a log line about code signing in the logging above. I therefore tried the following:
Create self-signed code signing certificate: https://stackoverflow.com/a/58363510/1423623
Navigate to the debugger folder (in my case, ~/.vscode/extensions/ms-dotnettools.csharp-1.24.4-darwin-x64/.debugger/x86_64)
Run codesign --remove-signature vsdbg-ui && codesign --remove-signature vsdbg
Run codesign -s my-codesign-cert vsdbg-ui && codesign -s my-codesign-cert vsdbg
I can now attach to a running instance of ./vsdbg-ui --server --consoleLogging --engineLogging from VS Code that stops at breakpoints. It's a work-around, but it shows something is wrong with the code signing of vsdbg and/or vsdbg-ui.
2022-04-20: can confirm that this still works, using OmniSharp 1.24.4.

Prerequisites to run/debug the Azure Functions in Visual Studio Code:
Azure Tools Extension
Azure Functions Core Tools
Also, Ensure that the Storage Emulator installed on your system, even it is deprecated but still used for local environment debugging and testing purposes
Azurite Extension on VS Code Extensions Menu
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
.csproj file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.0.1" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
Debug Result:
Put a breakpoint at some code line inside the Run Method and Start debugging.
All the code files and debugging video is available in the GitHub Repository and debugging video, please compare each file to your code.
As specified in this VS Code Official Documentation, need to install the language runtime extension for debugging purposes like C# for .NET, Python, Java, JavaScript, PowerShell etc.
For example, for the above .NET Azure Functions Project I have installed this extension in VS Code:
Links to Install these extensions are given in prerequisites and in hyperlink wording formats.
References of VS Code debugging the Azure Functions:
Debugging Azure Functions Locally in VS Code
Microsoft Official Documentation of Azure Functions debugging in VS Code

I have a similar issue.
I have multiple python azure function repositories which i work on in vs-code.
If a file open in the editor has errors (lint errors, mypy errors, etc..)
Whenever i try to launch a debug session the function starts but eventually detach from the debug session.
After this log print:
INFO: Detaching console logging.
Then it won't stop at breakpoints and log debug logs.
Unfortunately I don't have a solution yet.
I do have a working workaround you can try:
Close any open file which has an error (you can close all the files), and launch the debug session (f5), I found this way it's working, stopping at breakpoints and not detaching the debugger.
If you (or anyone) find a working solution please share.

In my case, I'm running on a mac. and this answer worked:
https://github.com/OmniSharp/omnisharp-vscode/issues/4900
Basically I changed my launch.json from:
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to .NET Functions",
"type": "coreclr",
"request": "attach",
"processId": "${command:azureFunctions.pickProcess}"
}
]
}
to this:
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to .NET Functions",
"type": "coreclr",
"request": "attach",
"processId": "${command:azureFunctions.pickProcess}",
"targetArchitecture": "x86_64"
}
]
}

Related

An assembly specified in the application dependencies manifest was not found

So I have a .NET Core 2.2 web application.
I added the EPPlus library to it and now, when it is released to Azure (App Service) it won't start and I get the error:
HTTP Error 502.5 - ANCM Out-Of-Process Startup Failure
I narrowed this down by running a console in Azure and the command: "dotnet my.project.dll" - and got the actual error:
An assembly specified in the application dependencies manifest
(my.project.deps.json) was not found:
package: 'Microsoft.Win32.SystemEvents', version: '4.5.0'
path: 'runtimes/win/lib/netcoreapp2.0/Microsoft.Win32.SystemEvents.dll'
The Microsoft.Win32.SystemEvents.dll is present in the main wwwroot folder the application is deployed to.
But the whole runtimes/win/libs/ folder I don't think exists at all.
The my.project.deps.json files has the section which looks like this:
"Microsoft.Win32.SystemEvents/4.5.0": {
"dependencies": {
"Microsoft.NETCore.Platforms": "2.2.0"
},
"runtime": {
"lib/netstandard2.0/Microsoft.Win32.SystemEvents.dll": {
"assemblyVersion": "4.0.0.0",
"fileVersion": "4.6.26515.6"
}
},
"runtimeTargets": {
"runtimes/win/lib/netcoreapp2.0/Microsoft.Win32.SystemEvents.dll": {
"rid": "win",
"assetType": "runtime",
"assemblyVersion": "4.0.0.0",
"fileVersion": "4.6.26515.6"
}
}
}
If I delete the whole "runtimeTargets" section, then the application works! (Well, I have to do the same for a few more dll's too: System.Drawing.Common and System.Security.Cryptography.Pkcs)
But the file gets regenerated fully whenever it is published and released - so it is not a viable solution.
I also don't know what that section of the file does. It might be important to leave it in. Though it all works so it can't be that vital...
It is built and published through TeamCity - I'm not an expert on the process but I think the command being run amounts to this:
dotnet publish my.proj.csproj --configuration RELEASE --no-restore --no-build
Other things tried: < PublishWithAspNetCoreTargetManifest>false< / PublishWithAspNetCoreTargetManifest>
had no effect
Anyone have any ideas?
As it turns out, it was my fault :(
Team City was created a NuGet package from the published output. But the /runtimes folder was not included in the package so was never released as part of the site.
I edited the nuspec file to include it /runtimes and all works OK.
I've had same issue. After the build I copied all files to the "production" directory by DOS command copy so then the files from "runtimes" subfolder were missing. Copying all files including all subdirectories (by using xcopy) fixed the issue.

Azure function multiple output binding Extensions error

I'm developing an Azure function through the portal,
My function is an HttpTrigger with httpResponse.
I add a TableStorage output binding and install its Extension (everything is fine).
I add a SendGrid output binding and install its Extension (the extension installer give me a message saying "it takes longer than expected" and seems to fail. Afterward, my function is broken.
I tried creating my bindings in reverse order (SendGrid then TableStorage). It now fails on TableStorage installation.
Any way to resolve this issue?
Thanks
It's a known issue that sometimes filesystem for Consumption plans reacts slow, e.g during extension installation with many file I/O operations.
The first suggestion is to delete the extensions and retry.
Stop Function app.
In portal, Platform features> App Service Editor.
Right click on bin folder and extensions.csproj, Delete.
Start Function app.
Delete existing output bindings and add them again to install extensions.
If this doesn't work, try to manually install the extensions.
Stop Function app.
In portal, Platform features> App Service Editor.
Right clik on the blank under WWWROOT, New File extensions.csproj then add content below.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsAsErrors />
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.SendGrid" Version="3.0.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="3.0.2" />
<PackageReference Include="Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator" Version="1.0.*" />
</ItemGroup>
</Project>
Press Ctrl+Shift+C to open console, or click the second button Open Console from the bottom on the sidebar.
Input dotnet build extensions.csproj -o bin --no-incremental --packages D:\home\.nuget and wait for the command to finish.
Start Function app.

Cannot run PowerShell scripts in Azure Functions v2

I'm trying to write a Function App using .NET Core in Azure Functions v2. When using the Microsoft.Powershell.SDK package from Nuget (required for .NET Core PowerShell runtime) I cannot get Visual Studio to copy the System.Management.Automation library to the bin with my Function App.
This results in the following error:
System.Private.CoreLib: Exception while executing function: Function1. TestPowershellInFunction: Could not load file or assembly 'System.Management.Automation, Version=6.1.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified. System.Private.CoreLib: Could not load the specified file.
I've reproduced this in an existing Azure Function and a new Solution by simply creating a Timer function and adding the following snippet:
PowerShell shell = PowerShell.Create();
IEnumerable<PSObject> result = shell.AddScript("Write-Output 'Hello, World!'").Invoke();
foreach(PSObject line in result)
{
log.LogInformation(line.ToString());
}
This works on a new Console App with the PowerShell Nuget installed, but when added to the Function App I get the error. I do notice that System.Management.Automation doesn't get put in the bin directory with a regular Console App but I'm not sure how to interpret this. I know it's a System library but I can't use it unless the Nuget is installed, so I don't know if this is a special case. In both scenarios I'm using v6.1.1 of the PowerShell Nuget.
Is this a known bug with Functions v2? Or am I missing something?
It's a known issue that Function can't load runtime assemblies([FunctionProject]\bin\Debug\netcoreapp2.1\bin\runtimes) correctly.
The workaround is to move assemblies to output dir bin manually. Right click on your function project and Edit <FunctionProject>.csproj. Add following items to achieve our goal.
<PropertyGroup>
<SDKVersion>6.1.1</SDKVersion>
<SDKPlatform>win-x86</SDKPlatform>
</PropertyGroup>
<ItemGroup>
<None Include="
$(USERPROFILE)\.nuget\packages\system.directoryservices\4.5.0\runtimes\win\lib\netcoreapp2.0\System.DirectoryServices.dll;
$(USERPROFILE)\.nuget\packages\system.management\4.5.0\runtimes\win\lib\netcoreapp2.0\System.Management.dll;
$(USERPROFILE)\.nuget\packages\system.management.automation\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\System.Management.Automation.dll;
$(USERPROFILE)\.nuget\packages\microsoft.management.infrastructure\1.0.0\runtimes\win10-x86\lib\netstandard1.6\Microsoft.Management.Infrastructure.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.commands.management\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.Commands.Management.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.commands.utility\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.Commands.Utility.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.commands.diagnostics\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.Commands.Diagnostics.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.sdk\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.SDK.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.security\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.Security.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.coreclr.eventing\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.CoreCLR.Eventing.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.consolehost\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.ConsoleHost.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.markdownrender\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.MarkdownRender.dll;
$(USERPROFILE)\.nuget\packages\microsoft.wsman.runtime\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.WSMan.Runtime.dll;
$(USERPROFILE)\.nuget\packages\microsoft.wsman.management\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.WSMan.Management.dll;
">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<Target Name="CopyRuntimeToBin" AfterTargets="Build">
<Copy SourceFiles="
$(USERPROFILE)\.nuget\packages\system.directoryservices\4.5.0\runtimes\win\lib\netcoreapp2.0\System.DirectoryServices.dll;
$(USERPROFILE)\.nuget\packages\system.management\4.5.0\runtimes\win\lib\netcoreapp2.0\System.Management.dll;
$(USERPROFILE)\.nuget\packages\system.management.automation\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\System.Management.Automation.dll;
$(USERPROFILE)\.nuget\packages\microsoft.management.infrastructure\1.0.0\runtimes\win10-x86\lib\netstandard1.6\Microsoft.Management.Infrastructure.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.commands.management\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.Commands.Management.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.commands.utility\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.Commands.Utility.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.commands.diagnostics\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.Commands.Diagnostics.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.sdk\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.SDK.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.security\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.Security.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.coreclr.eventing\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.CoreCLR.Eventing.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.consolehost\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.ConsoleHost.dll;
$(USERPROFILE)\.nuget\packages\microsoft.powershell.markdownrender\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.PowerShell.MarkdownRender.dll;
$(USERPROFILE)\.nuget\packages\microsoft.wsman.runtime\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.WSMan.Runtime.dll;
$(USERPROFILE)\.nuget\packages\microsoft.wsman.management\$(SDKVersion)\runtimes\$(SDKPlatform)\lib\netstandard2.0\Microsoft.WSMan.Management.dll;
" DestinationFolder="$(OutputPath)\bin" />
</Target>
Note that microsoft.management.infrastructure is set to win10-x86 on my side(Win10), you may need to change according to your pc platform. Assemblies are x86 as VS uses x86 Function CLi by default, we don't need to worry about it unless we need to work with x64.

Deploy Function App .csproj from Github

I have a function app project in multi project visual studio solution. I have an ARM template set up with GitHub as the source:
"properties": {
"RepoUrl": "[parameters('funcapp_reponame')]",
"branch": "[parameters('funcapp_branch')]",
"IsManualIntegration": true,
}
I have also added the following to deploy from the function app project:
"siteConfig": {
"appSettings": [
{
"name": "Project",
"value": "ProjectName"
}]
},
The template successfully creates the Function app resource, but not the functions. Looking at the deployment error log in the Azure portal I get:
'D:\home\site\repository\ProjectName\ProjectName.csproj' is not a deployable project
Looking at the files copied to Azure via FTP I can see that the full solution has been copied over and the deployment process looks to be selecting the correct folder. Is the presence of the .csproj causing the issue? The various example ARM templates for deploying functions on github don't appear to use visual studio projects.
In your Function App's csproj, you have:
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs" Version="2.1.0-beta1" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Http" Version="1.0.0-beta1" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.0-alpha6" />
</ItemGroup>
So it's referencing a very old Microsoft.NET.Sdk.Functions package. In your project, go to Manage NuGet Packages, and update to the latest, which right now is 1.0.7. Also, make sure to install any relevant VS updates under Tools / Extension and Updates.

TypeScript Unit-Testing on VSTS with Continuous Integration in a C# Web Application

I have a web application with continuous integration via visual studio team services and I want to add unit tests for my typescript code.
First try
At first I tried to create a Blank Node.js Console Application in my solution. I wrote some tests (with 'mocha',etc...) which worked fine locally. But as I commited the solution I noticed the build server not being able to...well...build:
Error : web.config not found in project, to create a project to deploy to Microsoft Azure you must create an Azure Node.js project.
This message suggested that msbuild wanted to create a deployable package of my NodeJS Project even though I only used it for testing purposes. The first thing that came to mind was to add a minimal web.config even though I did not want to publish the NodeJS project:
Error MSB4062: The "TypeScript.Tasks.FormatLocalizedString" task could not be loaded from the assembly C:\xxx\Microsoft.TypeScript.MSBuild.2.3.3\build\\..\tools\net45\TypeScript.Tasks.dll. Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.
I don't really see any way out of this...
Second try
Then I tried to use a UnitTest Project instead of the NodeJS Project. Surely this will work, or so I thought. With this approach I ran into the problem that VS Test did not recognize my Unit Tests (which worked fine on my NodeJS project) as there was no option to mark my files with the appropriate "Test Framework" attribute which was present on the file properties in the NodeJS Project. Instead there were the default file options for "Custom Tool", etc:
No Problem! I'll just adjust the .csproj file directly!
<TypeScriptCompile Include="main.test.ts">
<SubType>Code</SubType>
<TestFramework>Mocha</TestFramework>
<Publish>False</Publish>
</TypeScriptCompile>
But, alas, no dice...The Tests still could not be found by VS Test
Question
What is the best practices approach here? Is there something I'm not thinking of? Was the 'First try' correct and I just did not find the correct option to disable the publishing of my NodeJS App?
PS
I now think my first approach was the correct one. Just to be clear: A lot of things already worked:
Installed Node Tools for Visual Studio on the Build Server
Compiling typescript via VSTS
Running Tests in VS Test locally
List item
Running npm install on build (in VSTS)
Now all I need is for the build to go through :/
I now notice that I did not write the full error message for the last error in the first approach:
##[error]C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\TypeScript\Microsoft.TypeScript.targets(60,5): Error MSB4062: The "TypeScript.Tasks.FormatLocalizedString" task could not be loaded from the assembly C:\Agent-PaketBuildIntern1\_work\54\s\packages\Microsoft.TypeScript.MSBuild.2.3.3\build\\..\tools\net45\TypeScript.Tasks.dll. Confirm that the <UsingTask> declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.
So we see here that it uses the .targets file under C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\TypeScript\ and not the one under ......\packages\Microsoft.TypeScript.MSBuild.2.3.3\tools
Could this be the problem? How do I go about correcting that?
.njsproj file:
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<VisualStudioVersion>14.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<Name>MyProjectName</Name>
<RootNamespace>MyProjectName</RootNamespace>
<SccProjectName>SAK</SccProjectName>
<SccProvider>SAK</SccProvider>
<SccAuxPath>SAK</SccAuxPath>
<SccLocalPath>SAK</SccLocalPath>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>5697a590-d15f-401b-b8d8-138bbd5d3330</ProjectGuid>
<ProjectHome>.</ProjectHome>
<StartupFile>
</StartupFile>
<StartWebBrowser>False</StartWebBrowser>
<SearchPath>
</SearchPath>
<WorkingDirectory>.</WorkingDirectory>
<OutputPath>.</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<ProjectTypeGuids>{3AF33F2E-1136-4D97-BBB7-1795711AC8B8};{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}</ProjectTypeGuids>
<TypeScriptSourceMap>true</TypeScriptSourceMap>
<TypeScriptModuleKind>CommonJS</TypeScriptModuleKind>
<EnableTypeScript>true</EnableTypeScript>
<StartWebBrowser>false</StartWebBrowser>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<Content Include="tsconfig.json">
<SubType>Code</SubType>
</Content>
<Content Include="package.json" />
<Content Include="README.md" />
<Content Include="Web.config" />
<TypeScriptCompile Include="Scripts\typings\node\node.d.ts" />
<TypeScriptCompile Include="bootstrap.test.ts">
<SubType>Code</SubType>
<TestFramework>Mocha</TestFramework>
<Publish>False</Publish>
</TypeScriptCompile>
<TypeScriptCompile Include="util\templates.ts">
<SubType>Code</SubType>
</TypeScriptCompile>
</ItemGroup>
<ItemGroup>
<Folder Include="util\" />
<Folder Include="Scripts\" />
<Folder Include="Scripts\typings\" />
<Folder Include="Scripts\typings\node\" />
</ItemGroup>
<PropertyGroup>
<PreBuildEvent>cd $(ProjectDir)
call npm install
</PreBuildEvent>
</PropertyGroup>
<Import Project="..\..\..\packages\Microsoft.TypeScript.MSBuild.2.3.3\build\Microsoft.TypeScript.MSBuild.targets" Condition="Exists('..\..\..\packages\Microsoft.TypeScript.MSBuild.2.3.3\build\Microsoft.TypeScript.MSBuild.targets')" />
<Import Project="$(VSToolsPath)\Node.js Tools\Microsoft.NodejsTools.targets" />
</Project>
Refer to these steps (vs2015):
Create a new Node.js Console Application
Update package.json dependencies and scripts like this
:
{
"name": "nodejs-console-app-demo",
"version": "0.0.0",
"description": "NodejsConsoleAppDemo",
"main": "app.js",
"author": {
"name": "XXX",
"email": ""
},
"dependencies": {
"#types/mocha": "^2.2.41",
"assert": "^1.4.1",
"mocha": "^3.4.2",
"typescript": "^2.4.1"
},
"scripts": {
"tsc": "tsc"
}
}
Right click the project/folder >Add> New Item> Select TypeScript Mocha UnitTest file
Add your test code
Add a folder to your project (e.g. ntvs)
Copy 1.1 folder in C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Node.js Tools for Visual Studio to that ntvs folder
Right click your project > Add > New Item> Select Json template> add a new json file to project > Rename it to tsconfig.json
:
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "ES6",
"module": "commonjs",
"moduleResolution": "node",
"watch": false
},
"exclude": [
"node_modules"
],
"include": [
"src/**/*",
"test/**/*"
]
}
Right click your project > Unload project
Right click your project > Edit [projectname].njsproj
Change <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion> to <VisualStudioVersion>14.0</VisualStudioVersion>
Save all changes and add files to source control (by default .dll files will be ignored, so make sure all files in ntvs folder have been added to source control, you can right click ntvs folder > add files to source control)
Create a build definition
Npm install task (Command: install; Working folder: [package.json file path, such as $(Build.SourcesDirectory)\NodejsConsoleAppDemo]
Npm install task (Command: custom; Working folder: [tsconfig.json file path, such as $(Build.SourcesDirectory)\NodejsConsoleAppDemo]; Command and arguments: run tsc)
Visual Studio Test task (Test assemblies: [project file path, such as NodejsConsoleAppDemo\NodejsConsoleAppDemo.njsproj; Search folder: $(System.DefaultWorkingDirectory); Test platform version: Visual Studio 2015; Path to custom test adapters: [ntvs folder path, such as NodejsConsoleAppDemo/ntvs]]
Queue build with Hosted agent
There is an article that can help you: nodejstools.
If you are using VS 2017, you can refer to this thread: Running node.js tests locally in vstest.console.exe gives … Error: An exception occurred while invoking executor 'executor://nodejstestexecutor/v1.
After several attempts to make this work I decided to solve the problem at hand by putting the Mocha tests inside the Web Application Project and running them via npm (in the build steps). Inside the CI build definition I published the result of these tests via mocha-junit-reporter (https://www.npmjs.com/package/mocha-junit-reporter - see this answer for details).
This works for my requirements, although I would have liked to have the unit tests in a seperate project.

Resources