Build with dotnet (#571).

This commit is contained in:
Cesar Blum Silveira 2016-01-13 11:01:16 -08:00
parent 1209eca3fa
commit 6757a31fd2
40 changed files with 331 additions and 734 deletions

2
.gitattributes vendored
View File

@ -48,3 +48,5 @@
*.fsproj text=auto *.fsproj text=auto
*.dbproj text=auto *.dbproj text=auto
*.sln text=auto eol=crlf *.sln text=auto eol=crlf
*.sh eol=lf

4
.gitignore vendored
View File

@ -26,4 +26,6 @@ nuget.exe
*.*sdf *.*sdf
*.ipch *.ipch
project.lock.json project.lock.json
runtimes/ runtimes/
.build/
.testPublish/

View File

@ -11,7 +11,7 @@ addons:
- libunwind8 - libunwind8
- zlib1g - zlib1g
env: env:
- KOREBUILD_DNU_RESTORE_CORECLR=true KOREBUILD_TEST_DNXCORE=true - KOREBUILD_TEST_SKIPMONO=true
install: install:
- curl -sSL https://github.com/libuv/libuv/archive/v1.4.2.tar.gz | tar zxfv - -C /tmp && cd /tmp/libuv-1.4.2/ - curl -sSL https://github.com/libuv/libuv/archive/v1.4.2.tar.gz | tar zxfv - -C /tmp && cd /tmp/libuv-1.4.2/
- sh autogen.sh - sh autogen.sh
@ -22,5 +22,6 @@ install:
- cd $OLDPWD - cd $OLDPWD
mono: mono:
- 4.0.5 - 4.0.5
osx_image: xcode7.1
script: script:
- ./build.sh --quiet verify - ./build.sh --quiet verify

View File

@ -1,7 +1,7 @@
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14 # Visual Studio 14
VisualStudioVersion = 14.0.23107.0 VisualStudioVersion = 14.0.24709.0
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Server.Kestrel", "src\Microsoft.AspNetCore.Server.Kestrel\Microsoft.AspNetCore.Server.Kestrel.xproj", "{F510611A-3BEE-4B88-A613-5F4A74ED82A1}" Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Server.Kestrel", "src\Microsoft.AspNetCore.Server.Kestrel\Microsoft.AspNetCore.Server.Kestrel.xproj", "{F510611A-3BEE-4B88-A613-5F4A74ED82A1}"
EndProject EndProject
@ -29,8 +29,6 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Server
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{327F7880-D9AF-46BD-B45C-3B7E34A01DFD}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{327F7880-D9AF-46BD-B45C-3B7E34A01DFD}"
EndProject EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.StandardsPolice", "tools\Microsoft.StandardsPolice\Microsoft.StandardsPolice.xproj", "{82295647-7C1C-4671-BAB6-0FEF58F949EC}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Server.Kestrel.LibuvCopier", "tools\Microsoft.AspNetCore.Server.Kestrel.LibuvCopier\Microsoft.AspNetCore.Server.Kestrel.LibuvCopier.xproj", "{8CBA6FE3-3CC9-4420-8AA3-123E983734C2}" Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Server.Kestrel.LibuvCopier", "tools\Microsoft.AspNetCore.Server.Kestrel.LibuvCopier\Microsoft.AspNetCore.Server.Kestrel.LibuvCopier.xproj", "{8CBA6FE3-3CC9-4420-8AA3-123E983734C2}"
EndProject EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Server.Kestrel.Https", "src\Microsoft.AspNetCore.Server.Kestrel.Https\Microsoft.AspNetCore.Server.Kestrel.Https.xproj", "{5F64B3C3-0C2E-431A-B820-A81BBFC863DA}" Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNetCore.Server.Kestrel.Https", "src\Microsoft.AspNetCore.Server.Kestrel.Https\Microsoft.AspNetCore.Server.Kestrel.Https.xproj", "{5F64B3C3-0C2E-431A-B820-A81BBFC863DA}"
@ -63,10 +61,6 @@ Global
{BD2D4D29-1BD9-40D0-BB31-337D5416B63C}.Debug|Any CPU.Build.0 = Debug|Any CPU {BD2D4D29-1BD9-40D0-BB31-337D5416B63C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BD2D4D29-1BD9-40D0-BB31-337D5416B63C}.Release|Any CPU.ActiveCfg = Release|Any CPU {BD2D4D29-1BD9-40D0-BB31-337D5416B63C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BD2D4D29-1BD9-40D0-BB31-337D5416B63C}.Release|Any CPU.Build.0 = Release|Any CPU {BD2D4D29-1BD9-40D0-BB31-337D5416B63C}.Release|Any CPU.Build.0 = Release|Any CPU
{82295647-7C1C-4671-BAB6-0FEF58F949EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{82295647-7C1C-4671-BAB6-0FEF58F949EC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{82295647-7C1C-4671-BAB6-0FEF58F949EC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{82295647-7C1C-4671-BAB6-0FEF58F949EC}.Release|Any CPU.Build.0 = Release|Any CPU
{8CBA6FE3-3CC9-4420-8AA3-123E983734C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8CBA6FE3-3CC9-4420-8AA3-123E983734C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8CBA6FE3-3CC9-4420-8AA3-123E983734C2}.Debug|Any CPU.Build.0 = Debug|Any CPU {8CBA6FE3-3CC9-4420-8AA3-123E983734C2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8CBA6FE3-3CC9-4420-8AA3-123E983734C2}.Release|Any CPU.ActiveCfg = Release|Any CPU {8CBA6FE3-3CC9-4420-8AA3-123E983734C2}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -89,7 +83,6 @@ Global
{2C3CB3DC-EEBF-4F52-9E1C-4F2F972E76C3} = {8A3D00B8-1CCF-4BE6-A060-11104CE2D9CE} {2C3CB3DC-EEBF-4F52-9E1C-4F2F972E76C3} = {8A3D00B8-1CCF-4BE6-A060-11104CE2D9CE}
{B35D4D31-E74C-4646-8A11-7A7A40F0021E} = {8A3D00B8-1CCF-4BE6-A060-11104CE2D9CE} {B35D4D31-E74C-4646-8A11-7A7A40F0021E} = {8A3D00B8-1CCF-4BE6-A060-11104CE2D9CE}
{BD2D4D29-1BD9-40D0-BB31-337D5416B63C} = {327F7880-D9AF-46BD-B45C-3B7E34A01DFD} {BD2D4D29-1BD9-40D0-BB31-337D5416B63C} = {327F7880-D9AF-46BD-B45C-3B7E34A01DFD}
{82295647-7C1C-4671-BAB6-0FEF58F949EC} = {327F7880-D9AF-46BD-B45C-3B7E34A01DFD}
{8CBA6FE3-3CC9-4420-8AA3-123E983734C2} = {327F7880-D9AF-46BD-B45C-3B7E34A01DFD} {8CBA6FE3-3CC9-4420-8AA3-123E983734C2} = {327F7880-D9AF-46BD-B45C-3B7E34A01DFD}
{5F64B3C3-0C2E-431A-B820-A81BBFC863DA} = {2D5D5227-4DBD-499A-96B1-76A36B03B750} {5F64B3C3-0C2E-431A-B820-A81BBFC863DA} = {2D5D5227-4DBD-499A-96B1-76A36B03B750}
{9559A5F1-080C-4909-B6CF-7E4B3DC55748} = {D3273454-EA07-41D2-BF0B-FCC3675C2483} {9559A5F1-080C-4909-B6CF-7E4B3DC55748} = {D3273454-EA07-41D2-BF0B-FCC3675C2483}

View File

@ -4,4 +4,6 @@ build_script:
- build.cmd --quiet verify - build.cmd --quiet verify
clone_depth: 1 clone_depth: 1
test: off test: off
deploy: off deploy: off
environment:
NO_PARALLEL_TEST_PROJECTS: Microsoft.AspNetCore.Server.Kestrel.FunctionalTests

View File

@ -1,40 +1,40 @@
@echo off @ECHO off
cd %~dp0
SETLOCAL SETLOCAL
SET REPO_FOLDER=%~dp0
CD %REPO_FOLDER%
SET BUILD_FOLDER=.build
SET KOREBUILD_FOLDER=%BUILD_FOLDER%\KoreBuild-dotnet
SET KOREBUILD_VERSION=
SET NUGET_PATH=%BUILD_FOLDER%\NuGet.exe
SET NUGET_VERSION=latest SET NUGET_VERSION=latest
SET CACHED_NUGET=%LocalAppData%\NuGet\nuget.%NUGET_VERSION%.exe SET CACHED_NUGET=%LocalAppData%\NuGet\nuget.%NUGET_VERSION%.exe
SET BUILDCMD_KOREBUILD_VERSION=
SET BUILDCMD_DNX_VERSION=
IF EXIST %CACHED_NUGET% goto copynuget IF NOT EXIST %BUILD_FOLDER% (
echo Downloading latest version of NuGet.exe... md %BUILD_FOLDER%
IF NOT EXIST %LocalAppData%\NuGet md %LocalAppData%\NuGet
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest 'https://dist.nuget.org/win-x86-commandline/%NUGET_VERSION%/nuget.exe' -OutFile '%CACHED_NUGET%'"
:copynuget
IF EXIST .nuget\nuget.exe goto restore
md .nuget
copy %CACHED_NUGET% .nuget\nuget.exe > nul
:restore
IF EXIST packages\Sake goto getdnx
IF "%BUILDCMD_KOREBUILD_VERSION%"=="" (
.nuget\nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre
) ELSE (
.nuget\nuget.exe install KoreBuild -version %BUILDCMD_KOREBUILD_VERSION% -ExcludeVersion -o packages -nocache -pre
)
.nuget\NuGet.exe install Sake -ExcludeVersion -Source https://www.nuget.org/api/v2/ -Out packages
:getdnx
IF "%BUILDCMD_DNX_VERSION%"=="" (
SET BUILDCMD_DNX_VERSION=latest
)
IF "%SKIP_DNX_INSTALL%"=="" (
CALL packages\KoreBuild\build\dnvm install %BUILDCMD_DNX_VERSION% -runtime CoreCLR -arch x86 -alias default
CALL packages\KoreBuild\build\dnvm install default -runtime CLR -arch x86 -alias default
) ELSE (
CALL packages\KoreBuild\build\dnvm use default -runtime CLR -arch x86
) )
packages\Sake\tools\Sake.exe -I packages\KoreBuild\build -f makefile.shade %* IF NOT EXIST %NUGET_PATH% (
IF NOT EXIST %CACHED_NUGET% (
echo Downloading latest version of NuGet.exe...
IF NOT EXIST %LocalAppData%\NuGet (
md %LocalAppData%\NuGet
)
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest 'https://dist.nuget.org/win-x86-commandline/%NUGET_VERSION%/nuget.exe' -OutFile '%CACHED_NUGET%'"
)
copy %CACHED_NUGET% %NUGET_PATH% > nul
)
IF NOT EXIST %KOREBUILD_FOLDER% (
SET KOREBUILD_DOWNLOAD_ARGS=
IF NOT "%KOREBUILD_VERSION%"=="" (
SET KOREBUILD_DOWNLOAD_ARGS=-version %KOREBUILD_VERSION%
)
%BUILD_FOLDER%\nuget.exe install KoreBuild-dotnet -ExcludeVersion -o %BUILD_FOLDER% -nocache -pre %KOREBUILD_DOWNLOAD_ARGS%
)
"%KOREBUILD_FOLDER%\build\KoreBuild.cmd" %*

View File

@ -1,5 +1,10 @@
#!/usr/bin/env bash #!/usr/bin/env bash
buildFolder=.build
koreBuildFolder=$buildFolder/KoreBuild-dotnet
nugetPath=$buildFolder/nuget.exe
if test `uname` = Darwin; then if test `uname` = Darwin; then
cachedir=~/Library/Caches/KBuild cachedir=~/Library/Caches/KBuild
else else
@ -11,33 +16,30 @@ else
fi fi
mkdir -p $cachedir mkdir -p $cachedir
nugetVersion=latest nugetVersion=latest
cachePath=$cachedir/nuget.$nugetVersion.exe cacheNuget=$cachedir/nuget.$nugetVersion.exe
url=https://dist.nuget.org/win-x86-commandline/$nugetVersion/nuget.exe nugetUrl=https://dist.nuget.org/win-x86-commandline/$nugetVersion/nuget.exe
if test ! -f $cachePath; then if test ! -d $buildFolder; then
wget -O $cachePath $url 2>/dev/null || curl -o $cachePath --location $url /dev/null mkdir $buildFolder
fi fi
if test ! -e .nuget; then if test ! -f $nugetPath; then
mkdir .nuget if test ! -f $cacheNuget; then
cp $cachePath .nuget/nuget.exe wget -O $cacheNuget $nugetUrl 2>/dev/null || curl -o $cacheNuget --location $nugetUrl /dev/null
fi
cp $cacheNuget $nugetPath
fi fi
if test ! -d packages/Sake; then if test ! -d $koreBuildFolder; then
mono .nuget/nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre mono $nugetPath install KoreBuild-dotnet -ExcludeVersion -o $buildFolder -nocache -pre
mono .nuget/nuget.exe install Sake -ExcludeVersion -Source https://www.nuget.org/api/v2/ -Out packages chmod +x $koreBuildFolder/build/KoreBuild.sh
fi fi
if ! type dnvm > /dev/null 2>&1; then makeFile=makefile.shade
source packages/KoreBuild/build/dnvm.sh if [ ! -e $makeFile ]; then
makeFile=$koreBuildFolder/build/makefile.shade
fi fi
if ! type dnx > /dev/null 2>&1 || [ -z "$SKIP_DNX_INSTALL" ]; then ./$koreBuildFolder/build/KoreBuild.sh -n $nugetPath -m $makeFile "$@"
dnvm install latest -runtime coreclr -alias default
dnvm install default -runtime mono -alias default
else
dnvm use default -runtime mono
fi
mono packages/Sake/tools/Sake.exe -I packages/KoreBuild/build -f makefile.shade "$@"

View File

@ -1,8 +1,15 @@
var VERSION='0.1' var VERSION='0.1'
var FULL_VERSION='0.1' var FULL_VERSION='0.1'
var AUTHORS='Microsoft' var AUTHORS='Microsoft'
var kestrelSrcDir='${Path.Combine(Directory.GetCurrentDirectory(), "src/Microsoft.AspNetCore.Server.Kestrel")}'
use-standard-lifecycle use-standard-lifecycle
k-standard-goals k-standard-goals
custom-goals custom-goals
exec program='dotnet' commandline='restore ../../tools/Microsoft.AspNetCore.Server.Kestrel.GeneratedCode' workingdir='${kestrelSrcDir}'
exec program='dotnet' commandline='run -p ../../tools/Microsoft.AspNetCore.Server.Kestrel.GeneratedCode Http/FrameHeaders.Generated.cs Http/Frame.Generated.cs' workingdir='${kestrelSrcDir}'
exec program='dotnet' commandline='restore' workingdir='${kestrelSrcDir}'
exec program='dotnet' commandline='restore ../../tools/Microsoft.AspNetCore.Server.Kestrel.LibuvCopier' workingdir='${kestrelSrcDir}'
exec program='dotnet' commandline='run -p ../../tools/Microsoft.AspNetCore.Server.Kestrel.LibuvCopier' workingdir='${kestrelSrcDir}'

View File

@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved. // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
@ -40,6 +41,7 @@ namespace LargeResponseApp
{ {
var host = new WebHostBuilder() var host = new WebHostBuilder()
.UseDefaultConfiguration(args) .UseDefaultConfiguration(args)
.UseApplicationBasePath(Directory.GetCurrentDirectory())
.UseStartup<Startup>() .UseStartup<Startup>()
.Build(); .Build();

View File

@ -8,9 +8,11 @@
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "dnx451": { },
"dnxcore50": { } "dnxcore50": {
"dependencies": {
"NETStandard.Library": "1.0.0-*"
}
}
}, },
"commands": { "content": [ "hosting.json" ]
"web": "LargeResponseApp"
}
} }

View File

@ -65,6 +65,7 @@ namespace SampleApp
{ {
var host = new WebHostBuilder() var host = new WebHostBuilder()
.UseDefaultConfiguration(args) .UseDefaultConfiguration(args)
.UseApplicationBasePath(Directory.GetCurrentDirectory())
.UseStartup<Startup>() .UseStartup<Startup>()
.Build(); .Build();

View File

@ -9,15 +9,13 @@
"emitEntryPoint": true "emitEntryPoint": true
}, },
"frameworks": { "frameworks": {
"dnx451": { "dnx451": { },
},
"dnxcore50": { "dnxcore50": {
"dependencies": { "dependencies": {
"NETStandard.Library": "1.0.0-*",
"System.Console": "4.0.0-*" "System.Console": "4.0.0-*"
} }
} }
}, },
"commands": { "content": [ "hosting.json" ]
"web": "SampleApp"
}
} }

View File

@ -16,7 +16,8 @@
"dotnet5.4": { "dotnet5.4": {
"dependencies": { "dependencies": {
"System.Net.Security": "4.0.0-*" "System.Net.Security": "4.0.0-*"
} },
"imports": "portable-net45+win8"
} }
} }
} }

View File

@ -7,14 +7,11 @@
}, },
"dependencies": { "dependencies": {
"System.Buffers": "4.0.0-*", "System.Buffers": "4.0.0-*",
"System.Numerics.Vectors": "4.1.1-*",
"System.Threading.Tasks.Extensions": "4.0.0-*",
"Microsoft.AspNetCore.Hosting": "1.0.0-*", "Microsoft.AspNetCore.Hosting": "1.0.0-*",
"Microsoft.Extensions.Logging.Abstractions": "1.0.0-*", "Microsoft.Extensions.Logging.Abstractions": "1.0.0-*",
"Microsoft.Extensions.PlatformAbstractions": "1.0.0-*", "Microsoft.Extensions.PlatformAbstractions": "1.0.0-*",
"System.Numerics.Vectors": "4.1.1-*",
"Microsoft.StandardsPolice": {
"version": "1.0.0-*",
"type": "build"
},
"Microsoft.AspNetCore.Internal.libuv-Darwin": { "Microsoft.AspNetCore.Internal.libuv-Darwin": {
"version": "1.0.0-*", "version": "1.0.0-*",
"type": "build" "type": "build"
@ -22,11 +19,14 @@
"Microsoft.AspNetCore.Internal.libuv-Windows": { "Microsoft.AspNetCore.Internal.libuv-Windows": {
"version": "1.0.0-*", "version": "1.0.0-*",
"type": "build" "type": "build"
}, }
"System.Threading.Tasks.Extensions": "4.0.0-*"
}, },
"frameworks": { "frameworks": {
"net451": { }, "net451": {
"frameworkAssemblies": {
"System.Threading.Tasks": ""
}
},
"dotnet5.4": { "dotnet5.4": {
"dependencies": { "dependencies": {
"System.Collections": "4.0.11-*", "System.Collections": "4.0.11-*",
@ -45,23 +45,14 @@
"System.Threading.Thread": "4.0.0-*", "System.Threading.Thread": "4.0.0-*",
"System.Threading.ThreadPool": "4.0.10-*", "System.Threading.ThreadPool": "4.0.10-*",
"System.Threading.Timer": "4.0.1-*" "System.Threading.Timer": "4.0.1-*"
} },
"imports": "portable-net45+win8"
} }
}, },
"compilationOptions": { "compilationOptions": {
"allowUnsafe": true, "allowUnsafe": true,
"keyFile": "../../tools/Key.snk" "keyFile": "../../tools/Key.snk"
}, },
"scripts": {
"prepare": [
"dnu restore ../../tools/Microsoft.AspNetCore.Server.Kestrel.GeneratedCode",
"dnx -p ../../tools/Microsoft.AspNetCore.Server.Kestrel.GeneratedCode run Http/FrameHeaders.Generated.cs Http/Frame.Generated.cs"
],
"postrestore": [
"dnu restore ../../tools/Microsoft.AspNetCore.Server.Kestrel.LibuvCopier",
"dnx -p ../../tools/Microsoft.AspNetCore.Server.Kestrel.LibuvCopier run"
]
},
"packInclude": { "packInclude": {
"/": "../../content/thirdpartynotices.txt", "/": "../../content/thirdpartynotices.txt",
"runtimes/win7-x64/native/": "runtimes/win7-x64/native/*", "runtimes/win7-x64/native/": "runtimes/win7-x64/native/*",

View File

@ -64,11 +64,13 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{ {
get get
{ {
var port1 = PortManager.GetPort();
var port2 = PortManager.GetPort();
var dataset = new TheoryData<string, string[]>(); var dataset = new TheoryData<string, string[]>();
dataset.Add("8787", new[] { "http://localhost:8787/" }); dataset.Add($"{port1}", new[] { $"http://localhost:{port1}/" });
dataset.Add("8787;8788", new[] { "http://localhost:8787/", "http://localhost:8788/" }); dataset.Add($"{port1};{port2}", new[] { $"http://localhost:{port1}/", $"http://localhost:{port2}/" });
dataset.Add("http://127.0.0.1:8787/", new[] { "http://127.0.0.1:8787/", }); dataset.Add($"http://127.0.0.1:{port1}/", new[] { $"http://127.0.0.1:{port1}/", });
dataset.Add("http://localhost:8787/base/path", new[] { "http://localhost:8787/base/path" }); dataset.Add($"http://localhost:{port1}/base/path", new[] { $"http://localhost:{port1}/base/path" });
return dataset; return dataset;
} }
@ -78,14 +80,15 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{ {
get get
{ {
var port = PortManager.GetPort();
var dataset = new TheoryData<string, string[]>(); var dataset = new TheoryData<string, string[]>();
dataset.Add("http://*:8787/", new[] { "http://localhost:8787/", "http://127.0.0.1:8787/", "http://[::1]:8787/" }); dataset.Add($"http://*:{port}/", new[] { $"http://localhost:{port}/", $"http://127.0.0.1:{port}/", $"http://[::1]:{port}/" });
dataset.Add("http://localhost:8787/", new[] { "http://localhost:8787/", "http://127.0.0.1:8787/", dataset.Add($"http://localhost:{port}/", new[] { $"http://localhost:{port}/", $"http://127.0.0.1:{port}/",
/* // https://github.com/aspnet/KestrelHttpServer/issues/231 /* // https://github.com/aspnet/KestrelHttpServer/issues/231
"http://[::1]:8787/" $"http://[::1]:{port}/"
*/ }); */ });
dataset.Add("http://[::1]:8787/", new[] { "http://[::1]:8787/", }); dataset.Add($"http://[::1]:{port}/", new[] { $"http://[::1]:{port}/", });
dataset.Add("http://127.0.0.1:8787/;http://[::1]:8787/", new[] { "http://127.0.0.1:8787/", "http://[::1]:8787/" }); dataset.Add($"http://127.0.0.1:{port}/;http://[::1]:{port}/", new[] { $"http://127.0.0.1:{port}/", $"http://[::1]:{port}/" });
return dataset; return dataset;
} }

View File

@ -18,65 +18,66 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
public class PathBaseTests public class PathBaseTests
{ {
[ConditionalTheory] [ConditionalTheory]
[InlineData("http://localhost:8791/base", "http://localhost:8791/base", "/base", "")] [InlineData("/base", "/base", "/base", "")]
[InlineData("http://localhost:8791/base", "http://localhost:8791/base/", "/base", "/")] [InlineData("/base", "/base/", "/base", "/")]
[InlineData("http://localhost:8791/base", "http://localhost:8791/base/something", "/base", "/something")] [InlineData("/base", "/base/something", "/base", "/something")]
[InlineData("http://localhost:8791/base", "http://localhost:8791/base/something/", "/base", "/something/")] [InlineData("/base", "/base/something/", "/base", "/something/")]
[InlineData("http://localhost:8791/base/more", "http://localhost:8791/base/more", "/base/more", "")] [InlineData("/base/more", "/base/more", "/base/more", "")]
[InlineData("http://localhost:8791/base/more", "http://localhost:8791/base/more/something", "/base/more", "/something")] [InlineData("/base/more", "/base/more/something", "/base/more", "/something")]
[InlineData("http://localhost:8791/base/more", "http://localhost:8791/base/more/something/", "/base/more", "/something/")] [InlineData("/base/more", "/base/more/something/", "/base/more", "/something/")]
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")]
public Task RequestPathBaseIsServerPathBase(string registerAddress, string requestAddress, string expectedPathBase, string expectedPath) public Task RequestPathBaseIsServerPathBase(string registerPathBase, string requestPath, string expectedPathBase, string expectedPath)
{ {
return TestPathBase(registerAddress, requestAddress, expectedPathBase, expectedPath); return TestPathBase(registerPathBase, requestPath, expectedPathBase, expectedPath);
} }
[ConditionalTheory] [ConditionalTheory]
[InlineData("http://localhost:8791", "http://localhost:8791/", "", "/")] [InlineData("", "/", "", "/")]
[InlineData("http://localhost:8791", "http://localhost:8791/something", "", "/something")] [InlineData("", "/something", "", "/something")]
[InlineData("http://localhost:8791/", "http://localhost:8791/", "", "/")] [InlineData("/", "/", "", "/")]
[InlineData("http://localhost:8791/base", "http://localhost:8791/", "", "/")] [InlineData("/base", "/", "", "/")]
[InlineData("http://localhost:8791/base", "http://localhost:8791/something", "", "/something")] [InlineData("/base", "/something", "", "/something")]
[InlineData("http://localhost:8791/base", "http://localhost:8791/baseandsomething", "", "/baseandsomething")] [InlineData("/base", "/baseandsomething", "", "/baseandsomething")]
[InlineData("http://localhost:8791/base", "http://localhost:8791/ba", "", "/ba")] [InlineData("/base", "/ba", "", "/ba")]
[InlineData("http://localhost:8791/base", "http://localhost:8791/ba/se", "", "/ba/se")] [InlineData("/base", "/ba/se", "", "/ba/se")]
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")]
public Task DefaultPathBaseIsEmpty(string registerAddress, string requestAddress, string expectedPathBase, string expectedPath) public Task DefaultPathBaseIsEmpty(string registerPathBase, string requestPath, string expectedPathBase, string expectedPath)
{ {
return TestPathBase(registerAddress, requestAddress, expectedPathBase, expectedPath); return TestPathBase(registerPathBase, requestPath, expectedPathBase, expectedPath);
} }
[ConditionalTheory] [ConditionalTheory]
[InlineData("http://localhost:8791", "http://localhost:8791/", "", "/")] [InlineData("", "/", "", "/")]
[InlineData("http://localhost:8791/", "http://localhost:8791/", "", "/")] [InlineData("/", "/", "", "/")]
[InlineData("http://localhost:8791/base", "http://localhost:8791/base/", "/base", "/")] [InlineData("/base", "/base/", "/base", "/")]
[InlineData("http://localhost:8791/base/", "http://localhost:8791/base", "/base", "")] [InlineData("/base/", "/base", "/base", "")]
[InlineData("http://localhost:8791/base/", "http://localhost:8791/base/", "/base", "/")] [InlineData("/base/", "/base/", "/base", "/")]
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")]
public Task PathBaseNeverEndsWithSlash(string registerAddress, string requestAddress, string expectedPathBase, string expectedPath) public Task PathBaseNeverEndsWithSlash(string registerPathBase, string requestPath, string expectedPathBase, string expectedPath)
{ {
return TestPathBase(registerAddress, requestAddress, expectedPathBase, expectedPath); return TestPathBase(registerPathBase, requestPath, expectedPathBase, expectedPath);
} }
[ConditionalFact] [ConditionalFact]
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")]
public Task PathBaseAndPathPreserveRequestCasing() public Task PathBaseAndPathPreserveRequestCasing()
{ {
return TestPathBase("http://localhost:8791/base", "http://localhost:8791/Base/Something", "/Base", "/Something"); return TestPathBase("/base", "/Base/Something", "/Base", "/Something");
} }
[ConditionalFact] [ConditionalFact]
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")]
public Task PathBaseCanHaveUTF8Characters() public Task PathBaseCanHaveUTF8Characters()
{ {
return TestPathBase("http://localhost:8791/b♫se", "http://localhost:8791/b♫se/something", "/b♫se", "/something"); return TestPathBase("/b♫se", "/b♫se/something", "/b♫se", "/something");
} }
private async Task TestPathBase(string registerAddress, string requestAddress, string expectedPathBase, string expectedPath) private async Task TestPathBase(string registerPathBase, string requestPath, string expectedPathBase, string expectedPath)
{ {
var port = PortManager.GetPort();
var config = new ConfigurationBuilder().AddInMemoryCollection( var config = new ConfigurationBuilder().AddInMemoryCollection(
new Dictionary<string, string> { new Dictionary<string, string> {
{ "server.urls", registerAddress } { "server.urls", $"http://localhost:{port}{registerPathBase}" }
}).Build(); }).Build();
var builder = new WebHostBuilder() var builder = new WebHostBuilder()
@ -100,7 +101,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {
var response = await client.GetAsync(requestAddress); var response = await client.GetAsync($"http://localhost:{port}{requestPath}");
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var responseText = await response.Content.ReadAsStringAsync(); var responseText = await response.Content.ReadAsStringAsync();

View File

@ -0,0 +1,17 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{
public static class PortManager
{
private static int _nextPort = 8001;
public static int GetPort()
{
return Interlocked.Increment(ref _nextPort);
}
}
}

View File

@ -25,10 +25,11 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")]
public async Task LargeUpload() public async Task LargeUpload()
{ {
var port = PortManager.GetPort();
var config = new ConfigurationBuilder() var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string> .AddInMemoryCollection(new Dictionary<string, string>
{ {
{ "server.urls", "http://localhost:8791/" } { "server.urls", $"http://localhost:{port}/" }
}) })
.Build(); .Build();
@ -69,7 +70,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
bytes[i] = (byte)i; bytes[i] = (byte)i;
} }
var response = await client.PostAsync("http://localhost:8791/", new ByteArrayContent(bytes)); var response = await client.PostAsync($"http://localhost:{port}/", new ByteArrayContent(bytes));
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var sizeString = await response.Content.ReadAsStringAsync(); var sizeString = await response.Content.ReadAsStringAsync();
Assert.Equal(sizeString, bytes.Length.ToString(CultureInfo.InvariantCulture)); Assert.Equal(sizeString, bytes.Length.ToString(CultureInfo.InvariantCulture));
@ -78,12 +79,12 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
[ConditionalTheory] [ConditionalTheory]
[InlineData("127.0.0.1", "127.0.0.1", "8792")] [InlineData("127.0.0.1", "127.0.0.1")]
[InlineData("localhost", "127.0.0.1", "8792")] [InlineData("localhost", "127.0.0.1")]
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")]
public Task RemoteIPv4Address(string requestAddress, string expectAddress, string port) public Task RemoteIPv4Address(string requestAddress, string expectAddress)
{ {
return TestRemoteIPAddress("localhost", requestAddress, expectAddress, port); return TestRemoteIPAddress("localhost", requestAddress, expectAddress);
} }
[ConditionalFact] [ConditionalFact]
@ -91,16 +92,17 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
[IPv6SupportedCondition] [IPv6SupportedCondition]
public Task RemoteIPv6Address() public Task RemoteIPv6Address()
{ {
return TestRemoteIPAddress("[::1]", "[::1]", "::1", "8793"); return TestRemoteIPAddress("[::1]", "[::1]", "::1");
} }
[ConditionalFact] [ConditionalFact]
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")]
public async Task DoesNotHangOnConnectionCloseRequest() public async Task DoesNotHangOnConnectionCloseRequest()
{ {
var port = PortManager.GetPort();
var config = new ConfigurationBuilder().AddInMemoryCollection( var config = new ConfigurationBuilder().AddInMemoryCollection(
new Dictionary<string, string> { new Dictionary<string, string> {
{ "server.urls", "http://localhost:8794" } { "server.urls", $"http://localhost:{port}" }
}).Build(); }).Build();
var builder = new WebHostBuilder() var builder = new WebHostBuilder()
@ -123,7 +125,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
client.DefaultRequestHeaders.Connection.Clear(); client.DefaultRequestHeaders.Connection.Clear();
client.DefaultRequestHeaders.Connection.Add("close"); client.DefaultRequestHeaders.Connection.Add("close");
var response = await client.GetAsync("http://localhost:8794/"); var response = await client.GetAsync($"http://localhost:{port}/");
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
} }
} }
@ -132,9 +134,10 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")]
public async Task RequestPathIsNormalized() public async Task RequestPathIsNormalized()
{ {
var port = PortManager.GetPort();
var config = new ConfigurationBuilder().AddInMemoryCollection( var config = new ConfigurationBuilder().AddInMemoryCollection(
new Dictionary<string, string> { new Dictionary<string, string> {
{ "server.urls", "http://localhost:8795/\u0041\u030A" } { "server.urls", $"http://localhost:{port}/\u0041\u030A" }
}).Build(); }).Build();
var builder = new WebHostBuilder() var builder = new WebHostBuilder()
@ -157,7 +160,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{ {
socket.Connect(new IPEndPoint(IPAddress.Loopback, 8795)); socket.Connect(new IPEndPoint(IPAddress.Loopback, port));
socket.Send(Encoding.ASCII.GetBytes("GET /%41%CC%8A/A/../B/%41%CC%8A HTTP/1.1\r\n\r\n")); socket.Send(Encoding.ASCII.GetBytes("GET /%41%CC%8A/A/../B/%41%CC%8A HTTP/1.1\r\n\r\n"));
socket.Shutdown(SocketShutdown.Send); socket.Shutdown(SocketShutdown.Send);
@ -179,8 +182,9 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
} }
} }
private async Task TestRemoteIPAddress(string registerAddress, string requestAddress, string expectAddress, string port) private async Task TestRemoteIPAddress(string registerAddress, string requestAddress, string expectAddress)
{ {
var port = PortManager.GetPort();
var config = new ConfigurationBuilder().AddInMemoryCollection( var config = new ConfigurationBuilder().AddInMemoryCollection(
new Dictionary<string, string> { new Dictionary<string, string> {
{ "server.urls", $"http://{registerAddress}:{port}" } { "server.urls", $"http://{registerAddress}:{port}" }

View File

@ -23,10 +23,11 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on mono.")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on mono.")]
public async Task LargeDownload() public async Task LargeDownload()
{ {
var port = PortManager.GetPort();
var config = new ConfigurationBuilder() var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string> .AddInMemoryCollection(new Dictionary<string, string>
{ {
{ "server.urls", "http://localhost:8792/" } { "server.urls", $"http://localhost:{port}/" }
}) })
.Build(); .Build();
@ -58,7 +59,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {
var response = await client.GetAsync("http://localhost:8792/"); var response = await client.GetAsync($"http://localhost:{port}/");
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStreamAsync(); var responseBody = await response.Content.ReadAsStreamAsync();
@ -83,10 +84,11 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on mono.")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on mono.")]
public async Task IgnoreNullHeaderValues(string headerName, StringValues headerValue, string expectedValue) public async Task IgnoreNullHeaderValues(string headerName, StringValues headerValue, string expectedValue)
{ {
var port = PortManager.GetPort();
var config = new ConfigurationBuilder() var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string> .AddInMemoryCollection(new Dictionary<string, string>
{ {
{ "server.urls", "http://localhost:8793/" } { "server.urls", $"http://localhost:{port}/" }
}) })
.Build(); .Build();
@ -109,7 +111,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {
var response = await client.GetAsync("http://localhost:8793/"); var response = await client.GetAsync($"http://localhost:{port}/");
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var headers = response.Headers; var headers = response.Headers;
@ -131,10 +133,11 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on mono.")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on mono.")]
public async Task OnCompleteCalledEvenWhenOnStartingNotCalled() public async Task OnCompleteCalledEvenWhenOnStartingNotCalled()
{ {
var port = PortManager.GetPort();
var config = new ConfigurationBuilder() var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string> .AddInMemoryCollection(new Dictionary<string, string>
{ {
{ "server.urls", "http://localhost:8794/" } { "server.urls", $"http://localhost:{port}/" }
}) })
.Build(); .Build();
@ -162,7 +165,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {
var response = await client.GetAsync("http://localhost:8794/"); var response = await client.GetAsync($"http://localhost:{port}/");
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.False(onStartingCalled); Assert.False(onStartingCalled);

View File

@ -16,10 +16,11 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{ {
public async Task ZeroToTenThreads(int threadCount) public async Task ZeroToTenThreads(int threadCount)
{ {
var port = PortManager.GetPort();
var config = new ConfigurationBuilder() var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string> .AddInMemoryCollection(new Dictionary<string, string>
{ {
{ "server.urls", "http://localhost:8790/" } { "server.urls", $"http://localhost:{port}/" }
}) })
.Build(); .Build();
@ -46,7 +47,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
var requestTasks = new List<Task<string>>(); var requestTasks = new List<Task<string>>();
for (int i = 0; i < 20; i++) for (int i = 0; i < 20; i++)
{ {
var requestTask = client.GetStringAsync("http://localhost:8790/"); var requestTask = client.GetStringAsync($"http://localhost:{port}/");
requestTasks.Add(requestTask); requestTasks.Add(requestTask);
} }

View File

@ -4,17 +4,28 @@
"Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*", "Microsoft.AspNetCore.Http.Abstractions": "1.0.0-*",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*",
"Microsoft.AspNetCore.Testing": "1.0.0-*", "Microsoft.AspNetCore.Testing": "1.0.0-*",
"Microsoft.NETCore.Platforms": "1.0.1-*",
"System.Net.Http": "4.0.1-*", "System.Net.Http": "4.0.1-*",
"xunit.runner.aspnet": "2.0.0-aspnet-*" "xunit": "2.1.0"
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "dnx451": {
"dnxcore50": { } "dependencies": {
"xunit.runner.console": "2.1.0"
}
},
"dnxcore50": {
"dependencies": {
"xunit.runner.aspnet": "2.0.0-aspnet-*"
},
"imports": "portable-net45+win8"
}
}, },
"compilationOptions": { "compilationOptions": {
"allowUnsafe": true "allowUnsafe": true
}, },
"testRunner": "xunit",
"commands": { "commands": {
"test": "xunit.runner.aspnet -parallel none" "test": "xunit.runner.aspnet"
} }
} }

View File

@ -24,7 +24,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
await response.Body.WriteAsync(Encoding.ASCII.GetBytes("World!"), 0, 6); await response.Body.WriteAsync(Encoding.ASCII.GetBytes("World!"), 0, 6);
})) }))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -58,7 +58,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
await response.Body.WriteAsync(Encoding.ASCII.GetBytes("World!"), 0, 6); await response.Body.WriteAsync(Encoding.ASCII.GetBytes("World!"), 0, 6);
})) }))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -90,7 +90,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
await response.Body.WriteAsync(new byte[0], 0, 0); await response.Body.WriteAsync(new byte[0], 0, 0);
})) }))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -119,7 +119,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
throw new Exception(); throw new Exception();
})) }))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
// SendEnd is not called, so it isn't the client closing the connection. // SendEnd is not called, so it isn't the client closing the connection.
// client closing the connection. // client closing the connection.
@ -150,7 +150,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
throw new Exception(); throw new Exception();
})) }))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
// SendEnd is not called, so it isn't the client closing the connection. // SendEnd is not called, so it isn't the client closing the connection.
await connection.Send( await connection.Send(
@ -186,7 +186,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
await response.Body.WriteAsync(Encoding.ASCII.GetBytes("World!"), 0, 6); await response.Body.WriteAsync(Encoding.ASCII.GetBytes("World!"), 0, 6);
})) }))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.1", "GET / HTTP/1.1",

View File

@ -44,7 +44,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
using (var server = new TestServer(App, serviceContext)) using (var server = new TestServer(App, serviceContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
// "?" changes to "!" // "?" changes to "!"
await connection.SendEnd(sendString); await connection.SendEnd(sendString);
@ -69,7 +69,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
using (var server = new TestServer(App, serviceContext)) using (var server = new TestServer(App, serviceContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"POST / HTTP/1.0", "POST / HTTP/1.0",
@ -94,7 +94,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
using (var server = new TestServer(App, serviceContext)) using (var server = new TestServer(App, serviceContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
try try
{ {

View File

@ -98,7 +98,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
testContext.App = App; testContext.App = App;
var engine = new KestrelEngine(testContext); var engine = new KestrelEngine(testContext);
engine.Start(1); engine.Start(1);
var address = ServerAddress.FromUrl("http://localhost:54321/"); var address = ServerAddress.FromUrl($"http://localhost:{TestServer.GetNextPort()}/");
var started = engine.CreateServer(address); var started = engine.CreateServer(address);
started.Dispose(); started.Dispose();
engine.Dispose(); engine.Dispose();
@ -109,15 +109,16 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
[FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")] [FrameworkSkipCondition(RuntimeFrameworks.Mono, SkipReason = "Test hangs after execution on Mono.")]
public void ConnectionCanReadAndWrite(TestServiceContext testContext) public void ConnectionCanReadAndWrite(TestServiceContext testContext)
{ {
var port = TestServer.GetNextPort();
testContext.App = App; testContext.App = App;
var engine = new KestrelEngine(testContext); var engine = new KestrelEngine(testContext);
engine.Start(1); engine.Start(1);
var address = ServerAddress.FromUrl("http://localhost:54321/"); var address = ServerAddress.FromUrl($"http://localhost:{port}/");
var started = engine.CreateServer(address); var started = engine.CreateServer(address);
Console.WriteLine("Started"); Console.WriteLine("Started");
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(new IPEndPoint(IPAddress.Loopback, 54321)); socket.Connect(new IPEndPoint(IPAddress.Loopback, port));
socket.Send(Encoding.ASCII.GetBytes("POST / HTTP/1.0\r\n\r\nHello World")); socket.Send(Encoding.ASCII.GetBytes("POST / HTTP/1.0\r\n\r\nHello World"));
socket.Shutdown(SocketShutdown.Send); socket.Shutdown(SocketShutdown.Send);
var buffer = new byte[8192]; var buffer = new byte[8192];
@ -139,7 +140,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(App, testContext)) using (var server = new TestServer(App, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"POST / HTTP/1.0", "POST / HTTP/1.0",
@ -161,7 +162,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(AppChunked, testContext)) using (var server = new TestServer(AppChunked, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -207,7 +208,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
testContext)) testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
var requestData = var requestData =
Enumerable.Repeat("GET / HTTP/1.1\r\n", loopCount) Enumerable.Repeat("GET / HTTP/1.1\r\n", loopCount)
@ -250,7 +251,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
testContext)) testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
var requestData = var requestData =
Enumerable.Repeat("GET / HTTP/1.1\r\n", loopCount) Enumerable.Repeat("GET / HTTP/1.1\r\n", loopCount)
@ -276,7 +277,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(App, testContext)) using (var server = new TestServer(App, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.Send( await connection.Send(
"POST / HTTP/1.0", "POST / HTTP/1.0",
@ -298,7 +299,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(App, testContext)) using (var server = new TestServer(App, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.Send( await connection.Send(
"POST / HTTP/1.0", "POST / HTTP/1.0",
@ -320,7 +321,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(AppChunked, testContext)) using (var server = new TestServer(AppChunked, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.0", "GET / HTTP/1.0",
@ -350,7 +351,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(App, testContext)) using (var server = new TestServer(App, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.0", "GET / HTTP/1.0",
@ -381,7 +382,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(AppChunked, testContext)) using (var server = new TestServer(AppChunked, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"POST / HTTP/1.0", "POST / HTTP/1.0",
@ -413,7 +414,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(AppChunked, testContext)) using (var server = new TestServer(AppChunked, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"POST / HTTP/1.0", "POST / HTTP/1.0",
@ -446,7 +447,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(AppChunked, testContext)) using (var server = new TestServer(AppChunked, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.Send( await connection.Send(
"POST / HTTP/1.1", "POST / HTTP/1.1",
@ -474,11 +475,12 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
using (var server = new TestServer(App, testContext)) using (var server = new TestServer(App, testContext))
{ {
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
socket.Connect(IPAddress.Loopback, 54321); socket.Connect(IPAddress.Loopback, server.Port);
await Task.Delay(200);
socket.Dispose(); socket.Dispose();
await Task.Delay(200); await Task.Delay(200);
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.0", "GET / HTTP/1.0",
@ -497,7 +499,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(EmptyApp, testContext)) using (var server = new TestServer(EmptyApp, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -526,7 +528,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(EmptyApp, testContext)) using (var server = new TestServer(EmptyApp, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -540,7 +542,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
""); "");
} }
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.0", "GET / HTTP/1.0",
@ -561,7 +563,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(EmptyApp, testContext)) using (var server = new TestServer(EmptyApp, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"HEAD / HTTP/1.1", "HEAD / HTTP/1.1",
@ -593,7 +595,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
} }
}, testContext)) }, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"POST / HTTP/1.1", "POST / HTTP/1.1",
@ -654,7 +656,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
throw new Exception(); throw new Exception();
}, testContext)) }, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -713,7 +715,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
throw new Exception(); throw new Exception();
}, testContext)) }, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.Send( await connection.Send(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -756,7 +758,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
throw new Exception(); throw new Exception();
}, testContext)) }, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.Send( await connection.Send(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -781,7 +783,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(AppChunked, testContext)) using (var server = new TestServer(AppChunked, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -809,14 +811,14 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
{ {
using (var server = new TestServer(AppChunked, testContext)) using (var server = new TestServer(AppChunked, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET /"); "GET /");
await connection.ReceiveEnd(); await connection.ReceiveEnd();
} }
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -829,7 +831,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
""); "");
} }
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -884,7 +886,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
failedWriteCount++; failedWriteCount++;
}, testContext)) }, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -950,7 +952,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
await response.Body.WriteAsync(Encoding.ASCII.GetBytes("Hello World"), 0, 11); await response.Body.WriteAsync(Encoding.ASCII.GetBytes("Hello World"), 0, 11);
}, testContext)) }, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.Send( await connection.Send(
"GET / HTTP/1.1", "GET / HTTP/1.1",
@ -988,7 +990,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
await response.Body.WriteAsync(Encoding.ASCII.GetBytes("Hello World"), 0, 11); await response.Body.WriteAsync(Encoding.ASCII.GetBytes("Hello World"), 0, 11);
}, testContext)) }, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.SendEnd( await connection.SendEnd(
"POST / HTTP/1.1", "POST / HTTP/1.1",
@ -1063,7 +1065,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
} }
}, testContext)) }, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
// Never send the body so CopyToAsync always fails. // Never send the body so CopyToAsync always fails.
await connection.Send( await connection.Send(
@ -1134,7 +1136,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
writeTcs.SetException(new Exception("This shouldn't be reached.")); writeTcs.SetException(new Exception("This shouldn't be reached."));
}, testContext)) }, testContext))
{ {
using (var connection = new TestConnection()) using (var connection = new TestConnection(server.Port))
{ {
await connection.Send( await connection.Send(
"POST / HTTP/1.1", "POST / HTTP/1.1",

View File

@ -58,8 +58,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
var handler = new WinHttpHandler(); var handler = new WinHttpHandler();
handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
#endif #endif
var serverAddress = $"https://localhost:{TestServer.GetNextPort()}/";
var serverAddress = "https://localhost:54321/";
var serviceContext = new TestServiceContext() var serviceContext = new TestServiceContext()
{ {
ConnectionFilter = new HttpsConnectionFilter( ConnectionFilter = new HttpsConnectionFilter(
@ -108,7 +107,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
#endif #endif
var serverAddress = "https://localhost:54321/"; var serverAddress = $"https://localhost:{TestServer.GetNextPort()}/";
var serviceContext = new TestServiceContext() var serviceContext = new TestServiceContext()
{ {
ConnectionFilter = new HttpsConnectionFilter( ConnectionFilter = new HttpsConnectionFilter(
@ -157,7 +156,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
#endif #endif
var serverAddress = "https://localhost:54321/"; var serverAddress = $"https://localhost:{TestServer.GetNextPort()}/";
var serviceContext = new TestServiceContext() var serviceContext = new TestServiceContext()
{ {
ConnectionFilter = new HttpsConnectionFilter( ConnectionFilter = new HttpsConnectionFilter(
@ -209,7 +208,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
ServicePointManager.ServerCertificateValidationCallback += validationCallback; ServicePointManager.ServerCertificateValidationCallback += validationCallback;
#endif #endif
var serverAddress = "https://localhost:54321/"; var serverAddress = $"https://localhost:{TestServer.GetNextPort()}/";
var serviceContext = new TestServiceContext() var serviceContext = new TestServiceContext()
{ {
ConnectionFilter = new HttpsConnectionFilter( ConnectionFilter = new HttpsConnectionFilter(
@ -238,7 +237,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
// of the certificate authorities sent by the server in the SSL handshake. // of the certificate authorities sent by the server in the SSL handshake.
using (var client = new TcpClient()) using (var client = new TcpClient())
{ {
await client.ConnectAsync("127.0.0.1", 54321); await client.ConnectAsync("127.0.0.1", server.Port);
SslStream stream = new SslStream(client.GetStream(), false, (sender, certificate, chain, errors) => true, SslStream stream = new SslStream(client.GetStream(), false, (sender, certificate, chain, errors) => true,
(sender, host, certificates, certificate, issuers) => new X509Certificate2(@"TestResources/testCert.pfx", "testPassword")); (sender, host, certificates, certificate, issuers) => new X509Certificate2(@"TestResources/testCert.pfx", "testPassword"));
@ -281,7 +280,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
#endif #endif
var serverAddress = "https://localhost:54321/"; var serverAddress = $"https://localhost:{TestServer.GetNextPort()}/";
var serviceContext = new TestServiceContext() var serviceContext = new TestServiceContext()
{ {
ConnectionFilter = new HttpsConnectionFilter( ConnectionFilter = new HttpsConnectionFilter(

View File

@ -76,7 +76,8 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
loop.Init(_uv); loop.Init(_uv);
var tcp = new UvTcpHandle(_logger); var tcp = new UvTcpHandle(_logger);
tcp.Init(loop); tcp.Init(loop);
var address = ServerAddress.FromUrl("http://localhost:54321/"); var port = TestServer.GetNextPort();
var address = ServerAddress.FromUrl($"http://localhost:{port}/");
tcp.Bind(address); tcp.Bind(address);
tcp.Listen(10, (stream, status, error, state) => tcp.Listen(10, (stream, status, error, state) =>
{ {
@ -96,11 +97,11 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
await Task.Factory.FromAsync( await Task.Factory.FromAsync(
socket.BeginConnect, socket.BeginConnect,
socket.EndConnect, socket.EndConnect,
new IPEndPoint(IPAddress.Loopback, 54321), new IPEndPoint(IPAddress.Loopback, port),
null, null,
TaskCreationOptions.None); TaskCreationOptions.None);
#else #else
await socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 54321)); await socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, port));
#endif #endif
socket.Dispose(); socket.Dispose();
}); });
@ -117,7 +118,8 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
loop.Init(_uv); loop.Init(_uv);
var tcp = new UvTcpHandle(_logger); var tcp = new UvTcpHandle(_logger);
tcp.Init(loop); tcp.Init(loop);
var address = ServerAddress.FromUrl("http://localhost:54321/"); var port = TestServer.GetNextPort();
var address = ServerAddress.FromUrl($"http://localhost:{port}/");
tcp.Bind(address); tcp.Bind(address);
tcp.Listen(10, (_, status, error, state) => tcp.Listen(10, (_, status, error, state) =>
{ {
@ -149,7 +151,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
await Task.Factory.FromAsync( await Task.Factory.FromAsync(
socket.BeginConnect, socket.BeginConnect,
socket.EndConnect, socket.EndConnect,
new IPEndPoint(IPAddress.Loopback, 54321), new IPEndPoint(IPAddress.Loopback, port),
null, null,
TaskCreationOptions.None); TaskCreationOptions.None);
await Task.Factory.FromAsync( await Task.Factory.FromAsync(
@ -160,7 +162,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
null, null,
TaskCreationOptions.None); TaskCreationOptions.None);
#else #else
await socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 54321)); await socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, port));
await socket.SendAsync(new[] { new ArraySegment<byte>(new byte[] { 1, 2, 3, 4, 5 }) }, await socket.SendAsync(new[] { new ArraySegment<byte>(new byte[] { 1, 2, 3, 4, 5 }) },
SocketFlags.None); SocketFlags.None);
#endif #endif
@ -178,7 +180,8 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
loop.Init(_uv); loop.Init(_uv);
var tcp = new UvTcpHandle(_logger); var tcp = new UvTcpHandle(_logger);
tcp.Init(loop); tcp.Init(loop);
var address = ServerAddress.FromUrl("http://localhost:54321/"); var port = TestServer.GetNextPort();
var address = ServerAddress.FromUrl($"http://localhost:{port}/");
tcp.Bind(address); tcp.Bind(address);
tcp.Listen(10, (_, status, error, state) => tcp.Listen(10, (_, status, error, state) =>
{ {
@ -235,7 +238,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
await Task.Factory.FromAsync( await Task.Factory.FromAsync(
socket.BeginConnect, socket.BeginConnect,
socket.EndConnect, socket.EndConnect,
new IPEndPoint(IPAddress.Loopback, 54321), new IPEndPoint(IPAddress.Loopback, port),
null, null,
TaskCreationOptions.None); TaskCreationOptions.None);
await Task.Factory.FromAsync( await Task.Factory.FromAsync(
@ -246,7 +249,7 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
null, null,
TaskCreationOptions.None); TaskCreationOptions.None);
#else #else
await socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 54321)); await socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, port));
await socket.SendAsync(new[] { new ArraySegment<byte>(new byte[] { 1, 2, 3, 4, 5 }) }, await socket.SendAsync(new[] { new ArraySegment<byte>(new byte[] { 1, 2, 3, 4, 5 }) },
SocketFlags.None); SocketFlags.None);
#endif #endif

View File

@ -1,37 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Extensions.PlatformAbstractions;
namespace Microsoft.AspNetCore.Server.KestrelTests
{
/// <summary>
/// Summary description for Program
/// </summary>
public class Program
{
private readonly IApplicationEnvironment env;
private readonly IServiceProvider sp;
private readonly ILibraryManager _libraryManager;
public Program(
IApplicationEnvironment env,
IServiceProvider sp,
ILibraryManager libraryManager)
{
this.env = env;
this.sp = sp;
_libraryManager = libraryManager;
}
public int Main()
{
return Xunit.Runner.Dnx.Program.Main(new string[]
{
"-class",
typeof(MultipleLoopTests).FullName
});
}
}
}

View File

@ -21,15 +21,15 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
private NetworkStream _stream; private NetworkStream _stream;
private StreamReader _reader; private StreamReader _reader;
public TestConnection() public TestConnection(int port)
{ {
Create(); Create(port);
} }
public void Create() public void Create(int port)
{ {
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(new IPEndPoint(IPAddress.Loopback, 54321)); _socket.Connect(new IPEndPoint(IPAddress.Loopback, port));
_stream = new NetworkStream(_socket, false); _stream = new NetworkStream(_socket, false);
_reader = new StreamReader(_stream, Encoding.ASCII); _reader = new StreamReader(_stream, Encoding.ASCII);

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Threading;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel; using Microsoft.AspNetCore.Server.Kestrel;
using Microsoft.AspNetCore.Server.Kestrel.Http; using Microsoft.AspNetCore.Server.Kestrel.Http;
@ -13,8 +14,11 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
/// </summary> /// </summary>
public class TestServer : IDisposable public class TestServer : IDisposable
{ {
private static int _nextPort = 9001;
private KestrelEngine _engine; private KestrelEngine _engine;
private IDisposable _server; private IDisposable _server;
ServerAddress _address;
public TestServer(RequestDelegate app) public TestServer(RequestDelegate app)
: this(app, new TestServiceContext()) : this(app, new TestServiceContext())
@ -22,15 +26,17 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
} }
public TestServer(RequestDelegate app, ServiceContext context) public TestServer(RequestDelegate app, ServiceContext context)
: this(app, context, "http://localhost:54321/") : this(app, context, $"http://localhost:{GetNextPort()}/")
{ {
} }
public int Port => _address.Port;
public TestServer(RequestDelegate app, ServiceContext context, string serverAddress) public TestServer(RequestDelegate app, ServiceContext context, string serverAddress)
{ {
Create(app, context, serverAddress); Create(app, context, serverAddress);
} }
public void Create(RequestDelegate app, ServiceContext context, string serverAddress) public void Create(RequestDelegate app, ServiceContext context, string serverAddress)
{ {
context.FrameFactory = (connectionContext, remoteEP, localEP, prepareRequest) => context.FrameFactory = (connectionContext, remoteEP, localEP, prepareRequest) =>
@ -39,8 +45,8 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
}; };
_engine = new KestrelEngine(context); _engine = new KestrelEngine(context);
_engine.Start(1); _engine.Start(1);
_server = _engine.CreateServer( _address = ServerAddress.FromUrl(serverAddress);
ServerAddress.FromUrl(serverAddress)); _server = _engine.CreateServer(_address);
} }
public void Dispose() public void Dispose()
@ -48,5 +54,10 @@ namespace Microsoft.AspNetCore.Server.KestrelTests
_server.Dispose(); _server.Dispose();
_engine.Dispose(); _engine.Dispose();
} }
public static int GetNextPort()
{
return Interlocked.Increment(ref _nextPort);
}
} }
} }

View File

@ -1,14 +1,19 @@
{ {
"version": "1.0.0-*", "version": "1.0.0-*",
"dependencies": { "dependencies": {
"xunit.runner.aspnet": "2.0.0-aspnet-*",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*",
"Microsoft.AspNetCore.Server.Kestrel.Https": "1.0.0-*", "Microsoft.AspNetCore.Server.Kestrel.Https": "1.0.0-*",
"Microsoft.AspNetCore.Testing": "1.0.0-*", "Microsoft.AspNetCore.Testing": "1.0.0-*",
"System.Net.Http": "4.0.1-*" "Microsoft.NETCore.Platforms": "1.0.1-*",
"System.Net.Http": "4.0.1-*",
"xunit": "2.1.0"
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "dnx451": {
"dependencies": {
"xunit.runner.console": "2.1.0"
}
},
"dnxcore50": { "dnxcore50": {
"dependencies": { "dependencies": {
"System.Diagnostics.TraceSource": "4.0.0-*", "System.Diagnostics.TraceSource": "4.0.0-*",
@ -16,16 +21,21 @@
"System.IO": "4.1.0-*", "System.IO": "4.1.0-*",
"System.Net.Http.WinHttpHandler": "4.0.0-*", "System.Net.Http.WinHttpHandler": "4.0.0-*",
"System.Net.Sockets": "4.1.0-*", "System.Net.Sockets": "4.1.0-*",
"System.Runtime.Handles": "4.0.1-*" "System.Runtime.Handles": "4.0.1-*",
} "xunit.runner.aspnet": "2.0.0-aspnet-*"
},
"imports": "portable-net45+win8"
} }
}, },
"compilationOptions": { "compilationOptions": {
"allowUnsafe": true, "allowUnsafe": true,
"keyFile": "../../tools/Key.snk" "keyFile": "../../tools/Key.snk"
}, },
"testRunner": "xunit",
"commands": { "commands": {
"run": "Microsoft.AspNetCore.Server.KestrelTests", "test": "xunit.runner.aspnet"
"test": "xunit.runner.aspnet -parallel none" },
} "content": [
"TestResources/testCert.pfx"
]
} }

View File

@ -2,7 +2,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Http.Features;
using Microsoft.Dnx.Compilation.CSharp;
using Microsoft.AspNetCore.Http.Features.Internal; using Microsoft.AspNetCore.Http.Features.Internal;
using Microsoft.AspNetCore.Http.Features.Authentication; using Microsoft.AspNetCore.Http.Features.Authentication;
@ -10,19 +9,13 @@ namespace Microsoft.AspNetCore.Server.Kestrel.GeneratedCode
{ {
// This project can output the Class library as a NuGet Package. // This project can output the Class library as a NuGet Package.
// To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build". // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build".
public class FrameFeatureCollection : ICompileModule public class FrameFeatureCollection
{ {
static string Each<T>(IEnumerable<T> values, Func<T, string> formatter) static string Each<T>(IEnumerable<T> values, Func<T, string> formatter)
{ {
return values.Select(formatter).Aggregate((a, b) => a + b); return values.Select(formatter).Aggregate((a, b) => a + b);
} }
public virtual void BeforeCompile(BeforeCompileContext context)
{
var syntaxTree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(GeneratedFile());
context.Compilation = context.Compilation.AddSyntaxTrees(syntaxTree);
}
public static string GeneratedFile() public static string GeneratedFile()
{ {
var alwaysFeatures = new[] var alwaysFeatures = new[]
@ -129,9 +122,5 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Http
}} }}
"; ";
} }
public virtual void AfterCompile(AfterCompileContext context)
{
}
} }
} }

View File

@ -1,14 +1,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Microsoft.Dnx.Compilation.CSharp;
using System.Text; using System.Text;
namespace Microsoft.AspNetCore.Server.Kestrel.GeneratedCode namespace Microsoft.AspNetCore.Server.Kestrel.GeneratedCode
{ {
// This project can output the Class library as a NuGet Package. // This project can output the Class library as a NuGet Package.
// To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build". // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build".
public class KnownHeaders : ICompileModule public class KnownHeaders
{ {
static string Each<T>(IEnumerable<T> values, Func<T, string> formatter) static string Each<T>(IEnumerable<T> values, Func<T, string> formatter)
{ {
@ -73,11 +72,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.GeneratedCode
return $"(({array}[{offset / count}] & {mask}{suffix}) == {comp}{suffix})"; return $"(({array}[{offset / count}] & {mask}{suffix}) == {comp}{suffix})";
} }
} }
public virtual void BeforeCompile(BeforeCompileContext context)
{
var syntaxTree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(GeneratedFile());
context.Compilation = context.Compilation.AddSyntaxTrees(syntaxTree);
}
public static string GeneratedFile() public static string GeneratedFile()
{ {
var commonHeaders = new[] var commonHeaders = new[]
@ -488,8 +483,5 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Http
}} }}
")}}}"; ")}}}";
} }
public virtual void AfterCompile(AfterCompileContext context)
{
}
} }
} }

View File

@ -5,7 +5,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.GeneratedCode
{ {
public class Program public class Program
{ {
public int Main(string[] args) public static int Main(string[] args)
{ {
var text0 = KnownHeaders.GeneratedFile(); var text0 = KnownHeaders.GeneratedFile();
var text1 = FrameFeatureCollection.GeneratedFile(); var text1 = FrameFeatureCollection.GeneratedFile();

View File

@ -1,28 +1,24 @@
{ {
"version": "1.0.0-*", "version": "1.0.0-*",
"compilationOptions": {
"emitEntryPoint": true
},
"dependencies": { "dependencies": {
"Microsoft.Dnx.Compilation.CSharp.Abstractions": "1.0.0-*",
"Microsoft.AspNetCore.Http.Features": "1.0.0-*", "Microsoft.AspNetCore.Http.Features": "1.0.0-*",
"Microsoft.AspNetCore.Hosting": "1.0.0-*" "Microsoft.AspNetCore.Hosting": "1.0.0-*"
}, },
"commands": {
"run": "Microsoft.AspNetCore.Server.Kestrel.GeneratedCode"
},
"frameworks": { "frameworks": {
"dnxcore50": {
"dependencies": {
"NETStandard.Library": "1.0.0-*"
}
},
"dnx451": { "dnx451": {
"frameworkAssemblies": { "frameworkAssemblies": {
"System.Runtime": "", "System.Runtime": "",
"System.Text.Encoding": "", "System.Text.Encoding": "",
"System.Threading.Tasks": "" "System.Threading.Tasks": ""
} }
},
"dnxcore50": {
"dependencies": {
"System.Console": "4.0.0-*"
}
} }
} }
} }

View File

@ -1,18 +1,23 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using Microsoft.Extensions.PlatformAbstractions;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
namespace Microsoft.AspNetCore.Server.Kestrel.LibuvCopier namespace Microsoft.AspNetCore.Server.Kestrel.LibuvCopier
{ {
public class Program public class Program
{ {
public void Main(string[] args) public static void Main(string[] args)
{ {
try try
{ {
var packagesFolder = Environment.GetEnvironmentVariable("DNX_PACKAGES") ?? var packagesFolder = Environment.GetEnvironmentVariable("NUGET_PACKAGES");
Path.Combine(GetHome(), ".nuget", "packages");
if (string.IsNullOrEmpty(packagesFolder))
{
packagesFolder = Path.Combine(GetHome(), ".nuget", "packages");
}
packagesFolder = Environment.ExpandEnvironmentVariables(packagesFolder); packagesFolder = Environment.ExpandEnvironmentVariables(packagesFolder);
@ -39,12 +44,12 @@ namespace Microsoft.AspNetCore.Server.Kestrel.LibuvCopier
} }
// Copied from DNX's DnuEnvironment.cs // Copied from DNX's DnuEnvironment.cs
private string GetHome() private static string GetHome()
{ {
#if DNX451 #if DNX451
return Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); return Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
#else #else
var runtimeEnv = Extensions.PlatformAbstractions.PlatformServices.Default.Runtime; var runtimeEnv = PlatformServices.Default.Runtime;
if (runtimeEnv.OperatingSystem == "Windows") if (runtimeEnv.OperatingSystem == "Windows")
{ {
return Environment.GetEnvironmentVariable("USERPROFILE") ?? return Environment.GetEnvironmentVariable("USERPROFILE") ??

View File

@ -1,31 +1,19 @@
{ {
"version": "1.0.0-*", "version": "1.0.0-*",
"description": "Microsoft.AspNetCore.Server.Kestrel.LibuvCopier Console Application", "compilationOptions": {
"authors": [ "pawelka" ], "emitEntryPoint": true
"tags": [ "" ], },
"projectUrl": "",
"licenseUrl": "",
"dependencies": { "dependencies": {
"Microsoft.Extensions.PlatformAbstractions": "1.0.0-*", "Microsoft.Extensions.PlatformAbstractions": "1.0.0-*",
"Newtonsoft.Json": "7.0.1" "Newtonsoft.Json": "7.0.1"
}, },
"commands": {
"Microsoft.AspNetCore.Server.Kestrel.LibuvCopier": "Microsoft.AspNetCore.Server.Kestrel.LibuvCopier"
},
"frameworks": { "frameworks": {
"dnx451": { },
"dnxcore50": { "dnxcore50": {
"dependencies": { "dependencies": {
"Microsoft.CSharp": "4.0.1-*", "NETStandard.Library": "1.0.0-*",
"System.Collections": "4.0.11-*", "System.Dynamic.Runtime": "4.0.11-*"
"System.Console": "4.0.0-*",
"System.Linq": "4.0.1-*",
"System.Threading": "4.0.11-*",
"System.IO.FileSystem": "4.0.1-*"
} }
} },
"dnx451": { }
} }
} }

View File

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>82295647-7c1c-4671-bab6-0fef58f949ec</ProjectGuid>
<RootNamespace>Microsoft.StandardsPolice</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\..\artifacts\bin\$(MSBuildProjectName)\</OutputPath>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@ -1,49 +0,0 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.StandardsPolice
{
public class Program
{
public int Main(string[] args)
{
var tree = CSharpSyntaxTree.ParseText(@"
public class Hello { public Hello(int foo){}; protected int _foo; int _bar; }
public class World { public World(int foo){}; protected int _foo; int _bar; static int _quux = 4; enum Blah{} class Clazz{} }
");
var diags = new List<Diagnostic>();
var comp = CSharpCompilation.Create("Comp", new[] { tree });
StandardsPoliceCompileModule.ScanCompilation(diags, comp);
var hello = comp.GetTypeByMetadataName("Hello");
foreach (var f in hello.GetMembers().OfType<IFieldSymbol>())
{
var syntax = f.DeclaringSyntaxReferences.Single().GetSyntax();
Console.WriteLine($"{syntax.ToFullString()}");
var fds = syntax.Parent.Parent as FieldDeclarationSyntax;
var toks = syntax.DescendantTokens().ToArray();
var nods = syntax.DescendantNodesAndSelf().ToArray();
var mods = fds.Modifiers;
foreach (var mod in fds.Modifiers)
{
Console.WriteLine($"{mod.Kind()} {mod.ToFullString()}");
}
var locs = f.Locations.ToArray();
}
foreach(var d in diags)
{
Console.WriteLine(d);
}
return 0;
}
}
}

View File

@ -1,292 +0,0 @@
using Microsoft.Dnx.Compilation.CSharp;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp;
using System;
namespace Microsoft.StandardsPolice
{
public class StandardsPoliceCompileModule : ICompileModule
{
public void BeforeCompile(BeforeCompileContext context)
{
ScanCompilation(context.Diagnostics, context.Compilation);
}
internal static void ScanCompilation(IList<Diagnostic> diagnostics, CSharpCompilation compilation)
{
ScanNamespace(diagnostics, compilation.GlobalNamespace);
foreach (var st in compilation.SyntaxTrees)
{
if (!st.FilePath.EndsWith(".Generated.cs"))
{
ScanSyntaxTree(diagnostics, st);
}
}
}
internal static void ScanSyntaxTree(IList<Diagnostic> diagnostics, SyntaxTree syntaxTree)
{
var root = syntaxTree.GetRoot();
var typeDeclarations = root.DescendantNodes(descendIntoChildren: node => !(node is TypeDeclarationSyntax))
.OfType<TypeDeclarationSyntax>()
.ToArray();
if (typeDeclarations.Length > 1)
{
foreach (var typeDeclaration in typeDeclarations)
{
diagnostics.Add(Diagnostic.Create(
"SP1002", "StandardsPolice", "more than one type per file",
DiagnosticSeverity.Warning,
DiagnosticSeverity.Warning,
false,
3,
location: typeDeclaration.GetLocation()));
}
}
var usingDirectives = root.DescendantNodes(descendIntoChildren: node => !(node is TypeDeclarationSyntax))
.OfType<UsingDirectiveSyntax>()
.ToArray();
var priorUsingDirective = default(UsingDirectiveSyntax);
foreach (var usingDirective in usingDirectives)
{
var acceptableOrder = false;
if (!acceptableOrder && priorUsingDirective == null)
{
acceptableOrder = true;
}
if (!acceptableOrder && string.Compare(priorUsingDirective.Name.ToString(), usingDirective.Name.ToString(), StringComparison.OrdinalIgnoreCase) < 0)
{
acceptableOrder = true;
}
if (!acceptableOrder && priorUsingDirective.Name.ToString() == "System")
{
acceptableOrder = true;
}
if (!acceptableOrder &&
priorUsingDirective.Name.ToString().StartsWith("System") &&
!usingDirective.Name.ToString().StartsWith("System"))
{
acceptableOrder = true;
}
if (!acceptableOrder)
{
diagnostics.Add(Diagnostic.Create(
"SP1004", "StandardsPolice", "namespaces not alphabetized",
DiagnosticSeverity.Warning,
DiagnosticSeverity.Warning,
false,
3,
location: usingDirective.GetLocation()));
}
priorUsingDirective = usingDirective;
}
}
private static void ScanNamespace(IList<Diagnostic> diagnostics, INamespaceSymbol namespaceSymbol)
{
foreach (var member in namespaceSymbol.GetNamespaceMembers())
{
ScanNamespace(diagnostics, member);
}
foreach (var member in namespaceSymbol.GetTypeMembers())
{
ScanType(diagnostics, member);
}
}
private static void ScanType(IList<Diagnostic> diagnostics, INamedTypeSymbol typeSymbol)
{
if (typeSymbol.Locations.Any(location => location.IsInSource))
{
RuleFieldPrivateKeyword(diagnostics, typeSymbol);
RuleMembersAreInCorrectOrder(diagnostics, typeSymbol, MapClassMembers);
}
foreach (var member in typeSymbol.GetTypeMembers())
{
ScanType(diagnostics, member);
}
}
private static void RuleFieldPrivateKeyword(IList<Diagnostic> diagnostics, INamedTypeSymbol typeSymbol)
{
foreach (var member in typeSymbol.GetMembers().OfType<IFieldSymbol>())
{
if (member.DeclaredAccessibility != Accessibility.Private)
{
continue;
}
foreach (var syntaxReference in member.DeclaringSyntaxReferences)
{
var fieldHasPrivateKeyword = false;
var syntax = syntaxReference.GetSyntax();
var fds = syntax?.Parent?.Parent as FieldDeclarationSyntax;
if (fds == null)
{
continue;
}
foreach (var mod in fds.Modifiers)
{
if (mod.IsKind(CodeAnalysis.CSharp.SyntaxKind.PrivateKeyword))
{
fieldHasPrivateKeyword = true;
}
}
if (!fieldHasPrivateKeyword)
{
diagnostics.Add(Diagnostic.Create(
"SP1001", "StandardsPolice", "private keyword missing",
DiagnosticSeverity.Warning,
DiagnosticSeverity.Warning,
false,
3,
location: member.Locations.SingleOrDefault()));
}
}
}
}
private static void RuleMembersAreInCorrectOrder(IList<Diagnostic> diagnostics, INamedTypeSymbol typeSymbol, Func<ISymbol, ClassZone> mapZone)
{
if (typeSymbol.Locations.Length >= 2 || typeSymbol.Name == "Libuv")
{
// Don't apply to partial classes. All members are enumerated, but are not merged by zone order.
return;
}
var currentZone = ClassZone.BeforeStart;
var currentZoneExample = default(ISymbol);
foreach (var member in typeSymbol.GetMembers())
{
var memberZone = mapZone(member);
if (memberZone == ClassZone.Ignored)
{
continue;
}
if (currentZone <= memberZone)
{
currentZone = memberZone;
currentZoneExample = member;
}
if (memberZone >= ClassZone.OtherThings)
{
continue;
}
if (memberZone < currentZone)
{
if (member.Locations.Count() == 1)
{
diagnostics.Add(Diagnostic.Create(
"SP1003", "StandardsPolice", $"{memberZone} like {typeSymbol.Name}::{member.Name} shouldn't be after {currentZone} like {currentZoneExample.Name}",
DiagnosticSeverity.Warning,
DiagnosticSeverity.Warning,
false,
3,
location: member.Locations.Single(),
additionalLocations: currentZoneExample.Locations));
}
}
}
currentZone = ClassZone.AfterEnd;
currentZoneExample = null;
foreach (var member in typeSymbol.GetMembers().Reverse())
{
var memberZone = mapZone(member);
if (memberZone == ClassZone.Ignored)
{
continue;
}
if (currentZone >= memberZone)
{
currentZone = memberZone;
currentZoneExample = member;
}
if (memberZone <= ClassZone.OtherThings)
{
continue;
}
if (memberZone > currentZone)
{
if (member.Locations.Count() == 1)
{
diagnostics.Add(Diagnostic.Create(
"SP1003", "StandardsPolice", $"{memberZone} like {typeSymbol.Name}::{member.Name} shouldn't be before {currentZone} like {currentZoneExample.Name}",
DiagnosticSeverity.Warning,
DiagnosticSeverity.Warning,
false,
3,
location: member.Locations.Single(),
additionalLocations: currentZoneExample.Locations));
}
}
}
}
private static ClassZone MapClassMembers(ISymbol member)
{
if (member.IsImplicitlyDeclared)
{
return ClassZone.Ignored;
}
if (member.Kind == SymbolKind.Field)
{
return ClassZone.Fields;
}
if (member.Kind == SymbolKind.Method)
{
var method = (IMethodSymbol)member;
if (method.MethodKind == MethodKind.Constructor ||
method.MethodKind == MethodKind.StaticConstructor)
{
return ClassZone.Constructors;
}
if (method.MethodKind == MethodKind.PropertyGet ||
method.MethodKind == MethodKind.PropertySet)
{
return ClassZone.Properties;
}
}
if (member.Kind == SymbolKind.Property)
{
return ClassZone.Properties;
}
if (member.Kind == SymbolKind.NamedType)
{
var namedType = (INamedTypeSymbol)member;
if (namedType.TypeKind == TypeKind.Class ||
namedType.TypeKind == TypeKind.Enum ||
namedType.TypeKind == TypeKind.Struct)
{
return ClassZone.NestedTypes;
}
}
return ClassZone.OtherThings;
}
public void AfterCompile(AfterCompileContext context)
{
}
private enum ClassZone
{
Ignored,
BeforeStart,
Fields,
Constructors,
Properties,
OtherThings,
NestedTypes,
AfterEnd
}
}
}

View File

@ -1,44 +0,0 @@
{
"version": "1.0.0-*",
"compilationOptions": {
"keyFile": "../../tools/Key.snk"
},
"description": "Microsoft.StandardsPolice Class Library",
"dependencies": {
"Microsoft.Dnx.Compilation.CSharp.Abstractions": "1.0.0-*"
},
"commands": {
"Microsoft.StandardsPolice": "Microsoft.StandardsPolice"
},
"frameworks": {
"net451": {
"frameworkAssemblies": {
"System.Runtime": "",
"System.Text.Encoding": "",
"System.Threading.Tasks": ""
}
},
"dnx451": {
"frameworkAssemblies": {
"System.Runtime": "",
"System.Text.Encoding": "",
"System.Threading.Tasks": ""
}
},
"dotnet5.4": {
"dependencies": {
"System.Console": "4.0.0-*"
}
},
"dnxcore50": {
"dependencies": {
"System.Console": "4.0.0-*"
}
}
}
}