How to run Dotnet run command smoothly using Declarative pipeline - asp.net-core

I am new to Jenkins and the pipeline, I have created Web API and using Declarative pipeline to build and deploy the project on my localhost.
I am facing an issue in executing the Dotnet Run command through my declarative pipeline, it works fine however it does not complete the stage (it keep running) and I have to manually abort it.
The reason is because dotnet run uses Kestrel web server to run the .net core app.
Below is my script:
def BatchFile = "C:\\WorkSpace\\Thoughts\\DotnetEXEC.bat"
pipeline{
agent any
environment {
dotnet ='C:\\Program Files (x86)\\dotnet\\'
sln = 'C:\\WorkSpace\\Thoughts\\Thoughts\\Thoughts.sln'
nugetexe = 'C:\\ProgramData\\chocolatey\\lib\\NuGet.CommandLine\\tools\\NuGet.exe'
packagedir='C:\\WorkSpace\\Thoughts\\packages'
trxFilePath= 'C:\\WorkSpace\\Thoughts\\Thoughts\\ThoughtsUnitTest\\TestResults'
mainDirectory='C:\\WorkSpace\\Thoughts'
testResultFileName='UnitTestRestult.trx'
publishDirectory='C:\\WorkSpace\\Thoughts\\Publish'
webAPIProjectFile='C:\\WorkSpace\\Thoughts\\Thoughts\\ThoughtsService\\ThoughtsService.csproj'
webAPIBuild='\\Thoughts\\Libraries\\ThoughtsService\\netcoreapp2.1'
}
triggers {
pollSCM 'H/15 * * * *'
}
stages {
stage('Checkout') {
steps {
git credentialsId: 'be9c1836-afb8-4e2a-9f8a-96888c92c77d', url: 'https://github.com/gargankurg/Thoughts', branch: 'develop'
}
}
stage('Restore packages'){
steps{
bat "%nugetexe% restore %sln%"
}
}
stage('Clean'){
steps{
bat "dotnet clean %sln%"
}
}
stage('Build'){
steps{
bat "dotnet build %sln% --configuration Release"
}
}
stage('Test: Unit Test'){
steps {
bat "dotnet test %sln% -l:trx;LogFileName=%testResultFileName%"
bat "copy %trxFilePath%\\%testResultFileName% %mainDirectory%"
}
}
stage('Publish'){
steps{
bat "dotnet publish %webAPIProjectFile% --framework netcoreapp2.1 --output %publishDirectory% --self-contained true --runtime osx.10.11-x64 "
}
}
stage('Run'){
steps{
bat "%mainDirectory%\\DotnetEXEC.bat"
}
}
}
}
Here is my .bat file content
cd C:\WorkSpace\Thoughts\Thoughts\ThoughtsService
dotnet run --verbosity N

Related

Playwright not working in docker container of asp.net core application

I created a simple Asp.net core application and want to test playwright in my project. its is working fine in local Environment but when I am trying to deploy in docker container getting Error as Driver not found: /app/.playwright/node/linux/playwright.sh.
Test.csproj
<ItemGroup>
<PackageReference Include="Microsoft.Playwright" Version="1.12.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.10.13" />
</ItemGroup>
DockerFile
FROM mcr.microsoft.com/dotnet/aspnet:3.1-bionic AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
WORKDIR /src
COPY ["Test.csproj", "./"]
RUN dotnet restore "./Test.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "Test.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "Test.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Test.dll"]
SampleApplication.cs
public async Task<string> Get()
{
try
{
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
Headless = false,
SlowMo = 250,
Args = new[] { "--disable-dev-shm-usage", "--no-sandbox", "--user pwuser" },
});
var page = await browser.NewPageAsync();
// Navigate to the home page
await page.GotoAsync("https://www.facebook.com/");
await page.WaitForTimeoutAsync(10000);
}
catch (Exception e)
{
return e.Message.ToString();
}
return "This will open facebook page";
}
}
Any help is Appreciated .

Jenkins job doesnt continue after starting selenium server

I am building a jenkins job that needs to run some tests against a selenium server. I have have defined a stage where I start the selenium server in 1 container, and after that I want to run my tests from another container, against the selenium server.
The selenium server seems to start fine, but after that the job just hangs, displaying a spinner:
This is what my pipeline script looks like:
agent {
kubernetes {
defaultContainer 'jnlp'
yaml """
apiVersion: v1
kind: Pod
spec:
containers:
- name: node
image: node:12.14.1
- name: selenium
image: vvoyer/selenium-standalone
"""
}
}
stages {
stage('Checkout codebase') {
// do checkout
}
stage('start selenium') {
steps {
container('selenium') {
sh '''
selenium-standalone install
selenium-standalone start //script hangs after this command
'''
}
}
}
stage('test') {
steps {
container('node') {
//build test project & run tests
}
}
}
}
}
Can anyone tell me what I am doing wrong here and how I can fix it?
Yeah Thanks, solved similar error by adding '&' at the end of shell script step inside Jenkinsfile.
ex:
sh label: '',script: 'docker-compose -f TestAutomation_UI_API/docker-compose-v3.yml up --scale chrome=3 &'

Nancy support for .NETCoreApp

Trying to add the Nancy package to a new project. In project.json (dependencies segment) red squigly under "Nancy": "1.4.3". Mouseover displays an error relating to support for .NETCoreApp
The master branch of Nancy on github already runs on .net core.We are moving from Rake to Cake for the build script , hoping to wrap that up this week so .netcore support can be pushed to Nuget.So yes wait just a bit.
This example was original written on Stack Overflow Documentation:
Setup Nancyfx with Dotnet core v1.1, Kestrel, and Visual Studio Code on *nix systems
Prerequiste steps:
Get dotnet core for your platform:
Dotnet Core
Follow instructions and make sure dotnet core is working
Get Visual Studio Code for your platform:
VS Code
Launch Visual Studio Code (VS code) and install the C# extension then reload
Create self hosted NancyFx project:
Setup a project with a correct project directory structure.
Open Bash Terminal and type:
mkdir nancydotnetcore
cd nancydotnetcore
mkdir src
mkdir test
touch global.json
Open global.json and enter the following code:
{
"projects":["src", "test"]
}
In Bash terminal:
cd src
mkdir NancyProject1
dotnet new
Open folder NancyProject1 in VS code
You will get a warning: "Required assets to build and debug are missing from 'nancyproject1'."
Click "Yes"
Also you will see: There are unresolved dependencies from 'project.json'. Please execute the restore command to continue.
Click "Close" we will get to this soon.
Add the dependencies, open "project.json" and overwrite it with the following:
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable",
"emitEntryPoint": true
},
"frameworks": {
"netcoreapp1.1": {
"dependencies": {
"Microsoft.AspNetCore.Hosting": "1.1.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
"Microsoft.AspNetCore.Owin": "1.1.0",
"Nancy": "2.0.0-barneyrubble",
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.1.0"
}
}
}
}
}
VS code will ask to restore click "Restore"
Create folder "Modules" in VSCode project
In the Modules folder add a file named "IndexModule.cs" then copy and save the following:
namespace NancyProject1
{
using Nancy;
public class IndexModule : NancyModule
{
public IndexModule()
{
Get("/", _ => "Hello dotnet core world!");
}
}
}
In the root directory of the project create a file called "Startup.cs" and copy and paste the following:
namespace NancyProject1
{
using Microsoft.AspNetCore.Builder;
using Nancy.Owin;
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseOwin(x => x.UseNancy());
}
}
}
Open file "Program.cs" and overwrite the content with the following and save:
namespace NancyProject1
{
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseKestrel()
.UseStartup()
.Build();
host.Run();
}
}
}
Done! Now lets run this and see the output.
Click the debug symbol in VS Code, and Click the run button. It should compile and start the project.
Open the browser # http://localhost:5000
Pat yourself on the back and enjoy!
still pre release version but works with .net core as the time of this writing, view engines are very limited on core.
Install-Package Nancy -Version 2.0.0-barneyrubble -Pre

protractor could not find protractor/selenium/chromedriver.exe at codeship

i'm trying to configure the integration to run portractor tests.
I'm using grunt-protractor-runner task
with following configuration:
protractor: {
options: {
configFile: "protractor.conf.js", //your protractor config file
keepAlive: true, // If false, the grunt process stops when the test fails.
noColor: false, // If true, protractor will not use colors in its output.
args: {
// Arguments passed to the command
}
},
run: {},
chrome: {
options: {
args: {
browser: "chrome"
}
}
}
}
and here is grunt task which i use for running the protractor after the server is running:
grunt.registerTask('prot', [
'connect:test',
'replace:includemocks',//for uncommenting angular-mocks reference
'protractor:run',
'replace:removemocks',//for commenting out angular-mocks reference
]);
It is running well on my local machine, but at codeship i'm getting following error:
Error: Could not find chromedriver at /home/rof/src/bitbucket.org/myrepo/myFirstRepo/node_modules/grunt-protractor-runner/node_modules/protractor/selenium/chromedriver.exe
Which i guess, a result of not having this "chromedriver.exe" at this path.
How can i solve it in codeship environment?
Thanks forwards
Add postinstall to your package.json file and that way npm install will take care of placing the binaries for you ahead of time:
"scripts": {
"postinstall": "echo -n $NODE_ENV | \
grep -v 'production' && \
./node_modules/protractor/bin/webdriver-manager update || \
echo 'will skip the webdriver install/update in production'",
...
},
And don't forget to set NODE_ENV ... not setting it at all will result in echo 'will skip the webdriver install/update in production' piece running. Setting it to dev or staging will get desired results.
Short answer (pulkitsinghal gave the original solution):
./node_modules/grunt-protractor-runner/node_modules/protractor/bin/webdriver-manager update
I'm one of the founders at Codeship.
The error seems to be because you are trying to use the exe file, but we're on Linux on our system. Did you hardcode that executable?
Could you send us an in-app support request so we have a link to look at and can help you fix this?

Setting up Continuous Integration of Protractor using Jenkins

I am writing automation test scripts using Protractor and now I need to set up the CI for this using Jenkins.
Tasks it needs to perform are:
Starting the selenium standalon server.
Starting the test using conf.js file.
Stopping the selenium standalone server.
Can anyone help in this regard?
I created a small bash script to do this.
# start selenium
./node_modules/protractor/bin/webdriver-manager start > /dev/null 2>&1 &
# wait until selenium is up
while ! curl http://localhost:4444/wd/hub/status &>/dev/null; do :; done
# run the build
grunt cibuild --force
# stop selenium
curl -s -L http://localhost:4444/selenium-server/driver?cmd=shutDownSeleniumServer > /dev/null 2>&1
This script is invoked from a free-style project in jenkins (Build > Execute shell)
Then the test result report is generated by reading the protractor test results. Hence, you have to produce junit reports from protractor, (look here) :
onPrepare: function() {
// The require statement must be down here, since jasmine-reporters
// needs jasmine to be in the global and protractor does not guarantee
// this until inside the onPrepare function.
require('jasmine-reporters');
jasmine.getEnv().addReporter(
new jasmine.JUnitXmlReporter('xmloutput', true, true));
},
To make the report visible in jenkins i add a post build action in the job: Publish JUnit test result report:
Alternatively, you could run this as a Grunt Task. First install grunt on Jenkins. Install the NPM packages for protractor_webdriver and protractor. Setup the configuration file to point the the node_module path and config file paths.
http://sideroad.secret.jp/articles/grunt-on-jenkins/
Then install protractor node modules. The Gruntfile would look similar to this. I created a test directory where the conf and spec files would be located.
module.exports = function (grunt) {
grunt.initConfig({
protractor_webdriver: {
your_target: {
options: {
path: 'node_modules/protractor/bin/',
command: 'webdriver-manager start'
}
}
},
protractor: {
options: {
configFile: "node_modules/protractor/referenceConf.js", // Default config file
keepAlive: true, // If false, the grunt process stops when the test fails.
noColor: false, // If true, protractor will not use colors in its output.
args: {
// Arguments passed to the command
}
},
your_target: {
options: {
configFile: "test/conf.js", // Target-specific config file
args: {} // Target-specific arguments
}
}
}
});
grunt.registerTask('p:test', [
'protractor_webdriver',
'protractor'
]);
});
The newest protractor allows you to run the selenium standalone server directly from the conf.js (or whatever protractor entry point you have).
comment out (or delete) the seleniumAddress: 'http://localhost:4444/wd/hub', line, and replace it with seleniumServerJar: './node_modules/protractor/selenium/latest.jar'.
latest.jar isn't installed by default, I created it as a symlink to the latest version installed via npm install protractor --save. This gives longer life to my conf.js files in the same directory.
Within the ./node_modules/protractor/selenium/ folder I ran ln -s selenium-server-standalone-2.48.2.jar latest.jar
You can use Gulp which is far simpler.
After installing gulp in Jenkins System , you may install the npm dependencies(npm install) & run gulp tasks directly as windows batch command in Jenkins as below:
In the background to make selenium server up and running and providing various other parameters , you may use packages like 'gulp-angular-protractor' in the gulpfile.js as below:
gulpfile.js
'use strict';
var gulp = require('gulp'),
gulpProtractorAngular = require('gulp-angular-protractor'),
gulpStart = gulp.Gulp.prototype.start,
currentStartTaskName;
gulp.Gulp.prototype.start = function (task) {
currentStartTaskName = task;
gulpStart.apply(this, arguments);
};
function executeWebTests(suiteName, appName) {
return gulp.src([])
.pipe(gulpProtractorAngular({
'configFile': './conf.js',
'debug': false,
'autoStartStopServer': true,
args: [
'--suite', suiteName,
'--capabilities.browserName', 'chrome',
'--params.APPNAME', appName,
'--params.SUITENAME', currentStartTaskName,
'--capabilities.platformName', 'Windows'],
keepAlive: false
}))
.on('error', function (e) {
console.log('Ended with below ERROR::',e);
process.exit(1);
})
.on('end', function () {
console.log('Test complete');
process.exit();
});
}
gulp.task('RegressionSuiteTask', function () {
executeWebTests('regressionTests,','Application_Name');
});
conf.js
suites: {
regressionTests: ['testCases/**/*.js']//will run all specs in subfolders
},
I know this already resolved and want to target for beginner to create Jenkins job and running test. I suggest to use selenium-server-standalone jar in configuration file and call configuration file from Jenkins.
conf.js
..
exports.config = {
//seleniumAddress: 'http://localhost:4444/wd/hub',
seleniumServerJar: 'node_modules/protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-3.5.3.jar',
....
//html reporter logic
.....
Creating Jenkins Job
Install node js on Jenkins Server
Install Html Publisher Plugin for end to end testing report
Create Freestyle Project or whatever your needs
Go to Build Section -> Add build step and choose Execute Windows
batch command if Jenkins server in Windows otherwise choose Execute
Shell for Linux
Call conf.js (install packages and call your configuration file)
For reporting Got to Post-Build Actions Section -> Add Publish Html
Reports and call your report file (file assuming from root of your
project)
However you can customize execution command using gulp or similar other packages. Thanks