added test cases to Dev branch (#72)

This commit is contained in:
jhkimnew 2017-02-14 11:15:45 -08:00 committed by GitHub
parent 135aa12529
commit b4e3ccf67f
68 changed files with 10008 additions and 0 deletions

View File

@ -12,6 +12,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "IISLib", "src\IISLib\IISLib
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{02F461DC-5166-4E88-AAD5-CF110016A647}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "AspNetCoreModule.Test", "test\AspNetCoreModule.Test\AspNetCoreModule.Test.xproj", "{4DDA7560-AA29-4161-A5EA-A7E8F3997321}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{2097C03C-E2F7-4396-B3BC-4335F1B87B5E}"
ProjectSection(SolutionItems) = preProject
global.json = global.json
@ -19,6 +21,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{FDD2EDF8-1B62-4978-9815-9D95260B8B91}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "AspnetCoreModule.TestSites.Standard", "test\AspNetCoreModule.TestSites.Standard\AspnetCoreModule.TestSites.Standard.xproj", "{030225D8-4EE8-47E5-B692-2A96B3B51A38}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -49,6 +53,30 @@ Global
{4787A64F-9A3E-4867-A55A-70CB4B2B2FFE}.Release|Win32.Build.0 = Release|Win32
{4787A64F-9A3E-4867-A55A-70CB4B2B2FFE}.Release|x64.ActiveCfg = Release|Win32
{4787A64F-9A3E-4867-A55A-70CB4B2B2FFE}.Release|x64.Build.0 = Release|Win32
{4DDA7560-AA29-4161-A5EA-A7E8F3997321}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4DDA7560-AA29-4161-A5EA-A7E8F3997321}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4DDA7560-AA29-4161-A5EA-A7E8F3997321}.Debug|Win32.ActiveCfg = Debug|Any CPU
{4DDA7560-AA29-4161-A5EA-A7E8F3997321}.Debug|Win32.Build.0 = Debug|Any CPU
{4DDA7560-AA29-4161-A5EA-A7E8F3997321}.Debug|x64.ActiveCfg = Debug|Any CPU
{4DDA7560-AA29-4161-A5EA-A7E8F3997321}.Debug|x64.Build.0 = Debug|Any CPU
{4DDA7560-AA29-4161-A5EA-A7E8F3997321}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4DDA7560-AA29-4161-A5EA-A7E8F3997321}.Release|Any CPU.Build.0 = Release|Any CPU
{4DDA7560-AA29-4161-A5EA-A7E8F3997321}.Release|Win32.ActiveCfg = Release|Any CPU
{4DDA7560-AA29-4161-A5EA-A7E8F3997321}.Release|Win32.Build.0 = Release|Any CPU
{4DDA7560-AA29-4161-A5EA-A7E8F3997321}.Release|x64.ActiveCfg = Release|Any CPU
{4DDA7560-AA29-4161-A5EA-A7E8F3997321}.Release|x64.Build.0 = Release|Any CPU
{030225D8-4EE8-47E5-B692-2A96B3B51A38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{030225D8-4EE8-47E5-B692-2A96B3B51A38}.Debug|Any CPU.Build.0 = Debug|Any CPU
{030225D8-4EE8-47E5-B692-2A96B3B51A38}.Debug|Win32.ActiveCfg = Debug|Any CPU
{030225D8-4EE8-47E5-B692-2A96B3B51A38}.Debug|Win32.Build.0 = Debug|Any CPU
{030225D8-4EE8-47E5-B692-2A96B3B51A38}.Debug|x64.ActiveCfg = Debug|Any CPU
{030225D8-4EE8-47E5-B692-2A96B3B51A38}.Debug|x64.Build.0 = Debug|Any CPU
{030225D8-4EE8-47E5-B692-2A96B3B51A38}.Release|Any CPU.ActiveCfg = Release|Any CPU
{030225D8-4EE8-47E5-B692-2A96B3B51A38}.Release|Any CPU.Build.0 = Release|Any CPU
{030225D8-4EE8-47E5-B692-2A96B3B51A38}.Release|Win32.ActiveCfg = Release|Any CPU
{030225D8-4EE8-47E5-B692-2A96B3B51A38}.Release|Win32.Build.0 = Release|Any CPU
{030225D8-4EE8-47E5-B692-2A96B3B51A38}.Release|x64.ActiveCfg = Release|Any CPU
{030225D8-4EE8-47E5-B692-2A96B3B51A38}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -56,5 +84,7 @@ Global
GlobalSection(NestedProjects) = preSolution
{439824F9-1455-4CC4-BD79-B44FA0A16552} = {FDD2EDF8-1B62-4978-9815-9D95260B8B91}
{4787A64F-9A3E-4867-A55A-70CB4B2B2FFE} = {FDD2EDF8-1B62-4978-9815-9D95260B8B91}
{4DDA7560-AA29-4161-A5EA-A7E8F3997321} = {02F461DC-5166-4E88-AAD5-CF110016A647}
{030225D8-4EE8-47E5-B692-2A96B3B51A38} = {02F461DC-5166-4E88-AAD5-CF110016A647}
EndGlobalSection
EndGlobal

8
NuGet.config Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="AspNetCore" value="https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json" />
<add key="AspNetCore-Patch" value="https://dotnet.myget.org/F/aspnetcore-rel-1-0-3/api/v3/index.json" />
<add key="NuGet" value="https://api.nuget.org/v3/index.json" />
</packageSources>
</configuration>

View File

@ -0,0 +1,155 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{FB383E4C-A762-4FEA-BEFF-B3E6F4FA40C5}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>AspNetCoreModule.FunctionalTest</RootNamespace>
<AssemblyName>AspNetCoreModule.FunctionalTest</AssemblyName>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="dotnet-test-xunit, Version=99.99.99.0, Culture=neutral, processorArchitecture=AMD64">
<HintPath>..\..\packages\dotnet-test-xunit.2.2.0-preview2-build1029\lib\net451\dotnet-test-xunit.exe</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.AspNetCore.Server.IntegrationTesting">
<HintPath>..\..\..\..\Users\jhkim\.nuget\packages\Microsoft.AspNetCore.Server.IntegrationTesting\0.3.0-preview1-22821\lib\net451\Microsoft.AspNetCore.Server.IntegrationTesting.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Server.Testing, Version=0.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Server.Testing.0.2.0-alpha1-21873\lib\net451\Microsoft.AspNetCore.Server.Testing.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.AspNetCore.Testing, Version=1.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Testing.1.2.0-preview1-22815\lib\net451\Microsoft.AspNetCore.Testing.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Abstractions, Version=1.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Configuration.Abstractions.1.2.0-preview1-22821\lib\netstandard1.0\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=1.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.1.2.0-preview1-22821\lib\netstandard1.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.FileProviders.Abstractions, Version=1.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.FileProviders.Abstractions.1.1.0-preview1-final\lib\netstandard1.0\Microsoft.Extensions.FileProviders.Abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.FileProviders.Embedded, Version=1.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.FileProviders.Embedded.1.1.0-preview1-final\lib\net451\Microsoft.Extensions.FileProviders.Embedded.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Logging, Version=1.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Logging.1.2.0-preview1-22821\lib\netstandard1.1\Microsoft.Extensions.Logging.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=1.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Logging.Abstractions.1.2.0-preview1-22821\lib\netstandard1.1\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Console, Version=1.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Logging.Console.1.2.0-preview1-22821\lib\net451\Microsoft.Extensions.Logging.Console.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.PlatformAbstractions, Version=1.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.PlatformAbstractions.1.2.0-preview1-22821\lib\net451\Microsoft.Extensions.PlatformAbstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Extensions.Primitives, Version=1.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Primitives.1.2.0-preview1-22821\lib\netstandard1.0\Microsoft.Extensions.Primitives.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Net.Http.Headers, Version=1.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Net.Http.Headers.1.2.0-preview1-22821\lib\netstandard1.1\Microsoft.Net.Http.Headers.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Web.Administration, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Web.Administration.7.0.0.0\lib\net20\Microsoft.Web.Administration.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Buffers.4.3.0\lib\netstandard1.1\System.Buffers.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Core" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.IO.Compression.FileSystem" />
<Reference Include="System.Management" />
<Reference Include="System.Net.Http.WebRequest" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Runtime.CompilerServices.Unsafe.4.3.0\lib\netstandard1.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="xunit.assert, Version=2.2.0.3444, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.assert.2.2.0-beta4-build3444\lib\netstandard1.0\xunit.assert.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="xunit.core, Version=2.2.0.3444, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.extensibility.core.2.2.0-beta4-build3444\lib\net45\xunit.core.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="xunit.execution.desktop, Version=2.2.0.3444, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\..\packages\xunit.extensibility.execution.2.2.0-beta4-build3444\lib\net45\xunit.execution.desktop.dll</HintPath>
<Private>True</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="*.cs" />
<Compile Include="WebSocketClientHelper\*.cs" />
<Compile Include="HttpClientHelper\*.cs" />
<Compile Include="Framework\*.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,20 @@
<?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)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>4dda7560-aa29-4161-a5ea-a7e8f3997321</ProjectGuid>
<RootNamespace>AspNetCoreModule.Test</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@ -0,0 +1,41 @@
// 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.AspNetCore.Testing.xunit;
namespace AspNetCoreModule.Test.Framework
{
/// <summary>
/// Skip test if a given environment variable is not enabled. To enable the test, set environment variable
/// to "true" for the test process.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class EnvironmentVariableTestConditionAttribute : Attribute, ITestCondition
{
private readonly string _environmentVariableName;
public EnvironmentVariableTestConditionAttribute(string environmentVariableName)
{
_environmentVariableName = environmentVariableName;
}
public bool IsMet
{
get
{
return string.Compare(Environment.GetEnvironmentVariable(_environmentVariableName), "true", ignoreCase: true) == 0;
}
}
public string SkipReason
{
get
{
return $"To run this test, set the environment variable {_environmentVariableName}=\"true\". {AdditionalInfo}";
}
}
public string AdditionalInfo { get; set; }
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,244 @@
// 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 System.IO;
using System.Threading;
using Microsoft.Extensions.PlatformAbstractions;
namespace AspNetCoreModule.Test.Framework
{
public class InitializeTestMachine : IDisposable
{
//
// By default, we don't use the private AspNetCoreFile
//
public static bool UsePrivateAspNetCoreFile = false;
public static int SiteId = 40000;
public static string Aspnetcore_path = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "system32", "inetsrv", "aspnetcore_private.dll");
public static string Aspnetcore_path_original = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "system32", "inetsrv", "aspnetcore.dll");
public static string Aspnetcore_X86_path = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "syswow64", "inetsrv", "aspnetcore_private.dll");
public static string IISExpressAspnetcoreSchema_path = Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles%"), "IIS Express", "config", "schema", "aspnetcore_schema.xml");
public static string IISAspnetcoreSchema_path = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "system32", "inetsrv", "config", "schema", "aspnetcore_schema.xml");
public static int _referenceCount = 0;
private static bool _InitializeTestMachineCompleted = false;
private string _setupScriptPath = null;
public InitializeTestMachine()
{
_referenceCount++;
if (_referenceCount == 1)
{
TestUtility.LogInformation("InitializeTestMachine::InitializeTestMachine() Start");
_InitializeTestMachineCompleted = false;
TestUtility.LogInformation("InitializeTestMachine::Start");
if (Environment.ExpandEnvironmentVariables("%ANCMDebug%").ToLower() == "true")
{
System.Diagnostics.Debugger.Launch();
}
TestUtility.ResetHelper(ResetHelperMode.KillIISExpress);
TestUtility.ResetHelper(ResetHelperMode.KillWorkerProcess);
// cleanup before starting
string siteRootPath = Path.Combine(Environment.ExpandEnvironmentVariables("%SystemDrive%") + @"\", "inetpub", "ANCMTest");
try
{
if (IISConfigUtility.IsIISInstalled == true)
{
IISConfigUtility.RestoreAppHostConfig();
}
}
catch
{
TestUtility.LogInformation("Failed to restore applicationhost.config");
}
if (!Directory.Exists(siteRootPath))
{
Directory.CreateDirectory(siteRootPath);
}
foreach (string directory in Directory.GetDirectories(siteRootPath))
{
bool successDeleteChildDirectory = true;
try
{
TestUtility.DeleteDirectory(directory);
}
catch
{
successDeleteChildDirectory = false;
TestUtility.LogInformation("Failed to delete " + directory);
}
if (successDeleteChildDirectory)
{
try
{
TestUtility.DeleteDirectory(siteRootPath);
}
catch
{
TestUtility.LogInformation("Failed to delete " + siteRootPath);
}
}
}
if (InitializeTestMachine.UsePrivateAspNetCoreFile)
{
PreparePrivateANCMFiles();
// update applicationhost.config for IIS server
if (IISConfigUtility.IsIISInstalled == true)
{
using (var iisConfig = new IISConfigUtility(ServerType.IIS))
{
iisConfig.AddModule("AspNetCoreModule", Aspnetcore_path, null);
}
}
}
_InitializeTestMachineCompleted = true;
TestUtility.LogInformation("InitializeTestMachine::InitializeTestMachine() End");
}
for (int i=0; i<120; i++)
{
if (_InitializeTestMachineCompleted)
{
break;
}
else
{
TestUtility.LogInformation("InitializeTestMachine::InitializeTestMachine() Waiting...");
Thread.Sleep(500);
}
}
if (!_InitializeTestMachineCompleted)
{
throw new System.ApplicationException("InitializeTestMachine failed");
}
}
public void Dispose()
{
_referenceCount--;
if (_referenceCount == 0)
{
TestUtility.LogInformation("InitializeTestMachine::Dispose() Start");
TestUtility.ResetHelper(ResetHelperMode.KillIISExpress);
if (InitializeTestMachine.UsePrivateAspNetCoreFile)
{
if (IISConfigUtility.IsIISInstalled == true)
{
using (var iisConfig = new IISConfigUtility(ServerType.IIS))
{
try
{
iisConfig.AddModule("AspNetCoreModule", Aspnetcore_path_original, null);
}
catch
{
TestUtility.LogInformation("Failed to restore aspnetcore.dll path!!!");
}
}
}
}
TestUtility.LogInformation("InitializeTestMachine::Dispose() End");
}
}
private void PreparePrivateANCMFiles()
{
var solutionRoot = GetSolutionDirectory();
string outputPath = string.Empty;
_setupScriptPath = Path.Combine(solutionRoot, "tools");
// First try with debug build
outputPath = Path.Combine(solutionRoot, "artifacts", "build", "AspNetCore", "bin", "Debug");
// If debug build does is not available, try with release build
if (!File.Exists(Path.Combine(outputPath, "Win32", "aspnetcore.dll"))
|| !File.Exists(Path.Combine(outputPath, "x64", "aspnetcore.dll"))
|| !File.Exists(Path.Combine(outputPath, "x64", "aspnetcore_schema.xml")))
{
outputPath = Path.Combine(solutionRoot, "artifacts", "build", "AspNetCore", "bin", "Release");
}
if (!File.Exists(Path.Combine(outputPath, "Win32", "aspnetcore.dll"))
|| !File.Exists(Path.Combine(outputPath, "x64", "aspnetcore.dll"))
|| !File.Exists(Path.Combine(outputPath, "x64", "aspnetcore_schema.xml")))
{
outputPath = Path.Combine(solutionRoot, "src", "AspNetCore", "bin", "Debug");
}
if (!File.Exists(Path.Combine(outputPath, "Win32", "aspnetcore.dll"))
|| !File.Exists(Path.Combine(outputPath, "x64", "aspnetcore.dll"))
|| !File.Exists(Path.Combine(outputPath, "x64", "aspnetcore_schema.xml")))
{
throw new ApplicationException("aspnetcore.dll is not available; build aspnetcore.dll for both x86 and x64 and then try again!!!");
}
// create an extra private copy of the private file on IISExpress directory
if (InitializeTestMachine.UsePrivateAspNetCoreFile)
{
bool updateSuccess = false;
for (int i = 0; i < 3; i++)
{
updateSuccess = false;
try
{
TestUtility.ResetHelper(ResetHelperMode.KillWorkerProcess);
TestUtility.ResetHelper(ResetHelperMode.StopW3svcStartW3svc);
Thread.Sleep(1000);
TestUtility.FileCopy(Path.Combine(outputPath, "x64", "aspnetcore.dll"), Aspnetcore_path);
if (TestUtility.IsOSAmd64)
{
TestUtility.FileCopy(Path.Combine(outputPath, "Win32", "aspnetcore.dll"), Aspnetcore_X86_path);
}
updateSuccess = true;
}
catch
{
updateSuccess = false;
}
if (updateSuccess)
{
break;
}
}
if (!updateSuccess)
{
throw new System.ApplicationException("Failed to update aspnetcore.dll");
}
}
}
public static string GetSolutionDirectory()
{
var applicationBasePath = PlatformServices.Default.Application.ApplicationBasePath;
var directoryInfo = new DirectoryInfo(applicationBasePath);
do
{
var solutionFile = new FileInfo(Path.Combine(directoryInfo.FullName, "AspNetCoreModule.sln"));
if (solutionFile.Exists)
{
return directoryInfo.FullName;
}
directoryInfo = directoryInfo.Parent;
}
while (directoryInfo.Parent != null);
throw new Exception($"Solution root could not be located using application root {applicationBasePath}.");
}
}
}

View File

@ -0,0 +1,830 @@
// 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 System.Text;
using System.IO;
using System.Xml;
using System.Management;
using System.Threading;
using System.Diagnostics;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Security.Principal;
using System.Security.AccessControl;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net;
namespace AspNetCoreModule.Test.Framework
{
public enum ResetHelperMode
{
CallIISReset,
StopHttpStartW3svc,
StopWasStartW3svc,
StopW3svcStartW3svc,
KillWorkerProcess,
KillVSJitDebugger,
KillIISExpress
}
public enum ServerType
{
IISExpress = 0,
IIS = 1,
}
public class TestUtility
{
public static ILogger _logger = null;
public static ILogger Logger
{
get
{
if (_logger == null)
{
_logger = new LoggerFactory()
.AddConsole()
.CreateLogger("TestUtility");
}
return _logger;
}
}
public TestUtility(ILogger logger)
{
_logger = logger;
}
/// <summary>
/// Retries every 1 sec for 60 times by default.
/// </summary>
/// <param name="retryBlock"></param>
/// <param name="logger"></param>
/// <param name="cancellationToken"></param>
/// <param name="retryCount"></param>
public static async Task<HttpResponseMessage> RetryRequest(
Func<Task<HttpResponseMessage>> retryBlock,
ILogger logger,
CancellationToken cancellationToken = default(CancellationToken),
int retryCount = 60)
{
for (var retry = 0; retry < retryCount; retry++)
{
if (cancellationToken.IsCancellationRequested)
{
logger.LogInformation("Failed to connect, retry canceled.");
throw new OperationCanceledException("Failed to connect, retry canceled.", cancellationToken);
}
try
{
logger.LogWarning("Retry count {retryCount}..", retry + 1);
var response = await retryBlock().ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
{
// Automatically retry on 503. May be application is still booting.
logger.LogWarning("Retrying a service unavailable error.");
continue;
}
return response; // Went through successfully
}
catch (Exception exception)
{
if (retry == retryCount - 1)
{
logger.LogError(0, exception, "Failed to connect, retry limit exceeded.");
throw;
}
else
{
if (exception is HttpRequestException
#if NET451
|| exception is System.Net.WebException
#endif
)
{
logger.LogWarning("Failed to complete the request : {0}.", exception.Message);
await Task.Delay(1 * 1000); //Wait for a while before retry.
}
}
}
}
logger.LogInformation("Failed to connect, retry limit exceeded.");
throw new OperationCanceledException("Failed to connect, retry limit exceeded.");
}
public static void RetryOperation(
Action retryBlock,
Action<Exception> exceptionBlock,
int retryCount = 3,
int retryDelayMilliseconds = 0)
{
for (var retry = 0; retry < retryCount; ++retry)
{
try
{
retryBlock();
break;
}
catch (Exception exception)
{
exceptionBlock(exception);
}
Thread.Sleep(retryDelayMilliseconds);
}
}
public static bool RetryHelper<T> (
Func<T, bool> verifier,
T arg,
Action<Exception> exceptionBlock = null,
int retryCount = 3,
int retryDelayMilliseconds = 1000
)
{
for (var retry = 0; retry < retryCount; ++retry)
{
try
{
if (verifier(arg))
return true;
}
catch (Exception exception)
{
exceptionBlock?.Invoke(exception);
}
Thread.Sleep(retryDelayMilliseconds);
}
return false;
}
public static bool RetryHelper<T1, T2>(
Func<T1, T2, bool> verifier,
T1 arg1,
T2 arg2,
Action<Exception> exceptionBlock = null,
int retryCount = 3,
int retryDelayMilliseconds = 1000
)
{
for (var retry = 0; retry < retryCount; ++retry)
{
try
{
if (verifier(arg1, arg2))
return true;
}
catch (Exception exception)
{
exceptionBlock?.Invoke(exception);
}
Thread.Sleep(retryDelayMilliseconds);
}
return false;
}
public static bool RetryHelper<T1, T2, T3>(
Func<T1, T2, T3, bool> verifier,
T1 arg1,
T2 arg2,
T3 arg3,
Action<Exception> exceptionBlock = null,
int retryCount = 3,
int retryDelayMilliseconds = 1000
)
{
for (var retry = 0; retry < retryCount; ++retry)
{
try
{
if (verifier(arg1, arg2, arg3))
return true;
}
catch (Exception exception)
{
exceptionBlock?.Invoke(exception);
}
Thread.Sleep(retryDelayMilliseconds);
}
return false;
}
public static void GiveWritePermissionTo(string folder, SecurityIdentifier sid)
{
DirectorySecurity fsecurity = Directory.GetAccessControl(folder);
FileSystemAccessRule writerule = new FileSystemAccessRule(sid, FileSystemRights.Write, AccessControlType.Allow);
fsecurity.AddAccessRule(writerule);
Directory.SetAccessControl(folder, fsecurity);
Thread.Sleep(500);
}
public static bool IsOSAmd64
{
get
{
if (Environment.ExpandEnvironmentVariables("%PROCESSOR_ARCHITECTURE%") == "AMD64")
{
return true;
}
else
{
return false;
}
}
}
public static void LogTrace(string format, params object[] parameters)
{
if (format != null)
{
Logger.LogTrace(format);
}
}
public static void LogError(string format, params object[] parameters)
{
if (format != null)
{
Logger.LogError(format);
}
}
public static void LogInformation(string format, params object[] parameters)
{
if (format != null)
{
Logger.LogInformation(format);
}
}
public static void DeleteFile(string filePath)
{
if (File.Exists(filePath))
{
RunCommand("cmd.exe", "/c del \"" + filePath + "\"");
}
if (File.Exists(filePath))
{
throw new ApplicationException("Failed to delete file: " + filePath);
}
}
public static void FileMove(string from, string to, bool overWrite = true)
{
if (overWrite)
{
DeleteFile(to);
}
if (File.Exists(from))
{
if (File.Exists(to) && overWrite == false)
{
return;
}
File.Move(from, to);
if (!File.Exists(to))
{
throw new ApplicationException("Failed to rename from : " + from + ", to : " + to);
}
if (File.Exists(from))
{
throw new ApplicationException("Failed to rename from : " + from + ", to : " + to);
}
}
else
{
throw new ApplicationException("File not found " + from);
}
}
public static void FileCopy(string from, string to, bool overWrite = true, bool ignoreExceptionWhileDeletingExistingFile = false)
{
if (overWrite)
{
try
{
DeleteFile(to);
}
catch
{
if (!ignoreExceptionWhileDeletingExistingFile)
{
throw;
}
}
}
if (File.Exists(from))
{
if (File.Exists(to) && overWrite == false)
{
return;
}
RunCommand("cmd.exe", "/c copy /y \"" + from + "\" \"" + to + "\"");
if (!File.Exists(to))
{
throw new ApplicationException("Failed to move from : " + from + ", to : " + to);
}
}
else
{
LogError("File not found " + from);
}
}
public static void DeleteDirectory(string directoryPath)
{
if (Directory.Exists(directoryPath))
{
RunCommand("cmd.exe", "/c rd \"" + directoryPath + "\" /s /q");
}
if (Directory.Exists(directoryPath))
{
throw new ApplicationException("Failed to delete directory: " + directoryPath);
}
}
public static void CreateDirectory(string directoryPath)
{
if (!Directory.Exists(directoryPath))
{
RunCommand("cmd.exe", "/c md \"" + directoryPath + "\"");
}
if (!Directory.Exists(directoryPath))
{
throw new ApplicationException("Failed to create directory: " + directoryPath);
}
}
public static void DirectoryCopy(string from, string to)
{
if (Directory.Exists(to))
{
DeleteDirectory(to);
}
if (!Directory.Exists(to))
{
CreateDirectory(to);
}
if (Directory.Exists(from))
{
RunCommand("cmd.exe", "/c xcopy \"" + from + "\" \"" + to + "\" /s");
}
else
{
TestUtility.LogInformation("Directory not found " + from);
}
}
public static string FileReadAllText(string file)
{
string result = null;
if (File.Exists(file))
{
result = File.ReadAllText(file);
}
return result;
}
public static void CreateFile(string file, string[] stringArray)
{
DeleteFile(file);
using (StreamWriter sw = new StreamWriter(file))
{
foreach (string line in stringArray)
{
sw.WriteLine(line);
}
}
if (!File.Exists(file))
{
throw new ApplicationException("Failed to create " + file);
}
}
public static void KillProcess(string processFileName)
{
string query = "Select * from Win32_Process Where Name = \"" + processFileName + "\"";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
obj.InvokeMethod("Terminate", null);
}
Thread.Sleep(1000);
processList = searcher.Get();
if (processList.Count > 0)
{
TestUtility.LogInformation("Failed to kill process " + processFileName);
}
}
public static int GetNumberOfProcess(string processFileName, int expectedNumber = 1, int retry = 0)
{
int result = 0;
string query = "Select * from Win32_Process Where Name = \"" + processFileName + "\"";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
result = processList.Count;
for (int i = 0; i < retry; i++)
{
if (result == expectedNumber)
{
break;
}
Thread.Sleep(1000);
processList = searcher.Get();
result = processList.Count;
}
return result;
}
public static object GetProcessWMIAttributeValue(string processFileName, string attributeName, string owner = null)
{
string query = "Select * from Win32_Process Where Name = \"" + processFileName + "\"";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
object result = null;
foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty };
bool found = true;
if (owner != null)
{
found = false;
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
if (argList[0].ToUpper() == owner.ToUpper())
{
found = true;
}
}
}
if (found)
{
result = obj.GetPropertyValue(attributeName);
break;
}
}
return result;
}
public static string GetHttpUri(string Url, TestWebSite siteContext)
{
string tempUrl = Url.TrimStart(new char[] { '/' });
return "http://" + siteContext.HostName + ":" + siteContext.TcpPort + "/" + tempUrl;
}
public static string XmlParser(string xmlFileContent, string elementName, string attributeName, string childkeyValue)
{
string result = string.Empty;
XmlDocument serviceStateXml = new XmlDocument();
serviceStateXml.LoadXml(xmlFileContent);
XmlNodeList elements = serviceStateXml.GetElementsByTagName(elementName);
foreach (XmlNode item in elements)
{
if (childkeyValue == null)
{
if (item.Attributes[attributeName].Value != null)
{
string newValueFound = item.Attributes[attributeName].Value;
if (result != string.Empty)
{
newValueFound += "," + newValueFound; // make the result value in comma seperated format if there are multiple nodes
}
result += newValueFound;
}
}
else
{
//int groupIndex = 0;
foreach (XmlNode groupNode in item.ChildNodes)
{
/*UrlGroup urlGroup = new UrlGroup();
urlGroup._requestQueue = requestQueue._requestQueueName;
urlGroup._urlGroupId = groupIndex.ToString();
foreach (XmlNode urlNode in groupNode)
urlGroup._urls.Add(urlNode.InnerText.ToUpper());
requestQueue._urlGroupIds.Add(groupIndex);
requestQueue._urlGroups.Add(urlGroup);
groupIndex++; */
}
}
}
return result;
}
public static string RandomString(long size)
{
var random = new Random((int)DateTime.Now.Ticks);
var builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
public static bool ResetHelper(ResetHelperMode mode)
{
bool result = false;
switch (mode)
{
case ResetHelperMode.CallIISReset:
result = CallIISReset();
break;
case ResetHelperMode.StopHttpStartW3svc:
StopHttp();
result = StartW3svc();
break;
case ResetHelperMode.StopWasStartW3svc:
StopWas();
result = StartW3svc();
break;
case ResetHelperMode.StopW3svcStartW3svc:
StopW3svc();
result = StartW3svc();
break;
case ResetHelperMode.KillWorkerProcess:
result = KillWorkerProcess();
break;
case ResetHelperMode.KillVSJitDebugger:
result = KillVSJitDebugger();
break;
case ResetHelperMode.KillIISExpress:
result = KillIISExpress();
break;
};
return result;
}
public static bool KillIISExpress()
{
bool result = false;
string query = "Select * from Win32_Process Where Name = \"iisexpress.exe\"";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty };
bool foundProcess = true;
if (foundProcess)
{
obj.InvokeMethod("Terminate", null);
result = true;
}
}
return result;
}
public static bool KillVSJitDebugger()
{
bool result = false;
string query = "Select * from Win32_Process Where Name = \"vsjitdebugger.exe\"";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty };
bool foundProcess = true;
if (foundProcess)
{
LogError("Jit Debugger found");
obj.InvokeMethod("Terminate", null);
result = true;
}
}
return result;
}
public static bool KillWorkerProcess(string owner = null)
{
bool result = false;
string query = "Select * from Win32_Process Where Name = \"w3wp.exe\"";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
if (owner != null)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
bool foundProcess = true;
if (String.Compare(argList[0], owner, true) != 0)
{
foundProcess = false;
}
if (foundProcess)
{
obj.InvokeMethod("Terminate", null);
result = true;
}
}
}
else
{
obj.InvokeMethod("Terminate", null);
result = true;
}
}
return result;
}
public static bool KillIISExpressProcess(string owner = null)
{
bool result = false;
string query = "Select * from Win32_Process Where Name = \"iisexpress.exe\"";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
if (owner != null)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
bool foundProcess = true;
if (String.Compare(argList[0], owner, true) != 0)
{
foundProcess = false;
}
if (foundProcess)
{
obj.InvokeMethod("Terminate", null);
result = true;
}
}
}
else
{
obj.InvokeMethod("Terminate", null);
result = true;
}
}
return result;
}
public static int RunCommand(string fileName, string arguments = null, bool checkStandardError = true, bool waitForExit=true)
{
int pid = -1;
Process p = new Process();
p.StartInfo.FileName = fileName;
if (arguments != null)
{
p.StartInfo.Arguments = arguments;
}
if (waitForExit)
{
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
}
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start();
pid = p.Id;
string standardOutput = string.Empty;
string standardError = string.Empty;
if (waitForExit)
{
standardOutput = p.StandardOutput.ReadToEnd();
standardError = p.StandardError.ReadToEnd();
p.WaitForExit();
}
if (checkStandardError && standardError != string.Empty)
{
throw new Exception("Failed to run " + fileName + " " + arguments + ", Error: " + standardError + ", StandardOutput: " + standardOutput);
}
return pid;
}
public static bool CallIISReset()
{
int result = RunCommand("iisreset", null, false);
return (result != -1);
}
public static bool StopHttp()
{
int result = RunCommand("net", "stop http /y", false);
return (result != -1);
}
public static bool StopWas()
{
int result = RunCommand("net", "stop was /y", false);
return (result != -1);
}
public static bool StartWas()
{
int result = RunCommand("net", "start was", false);
return (result != -1);
}
public static bool StopW3svc()
{
int result = RunCommand("net", "stop w3svc /y", false);
return (result != -1);
}
public static bool StartW3svc()
{
int result = RunCommand("net", "start w3svc", false);
return (result != -1);
}
public static string GetApplicationPath()
{
var applicationBasePath = PlatformServices.Default.Application.ApplicationBasePath;
string solutionPath = InitializeTestMachine.GetSolutionDirectory();
string applicationPath = string.Empty;
applicationPath = Path.Combine(solutionPath, "test", "AspNetCoreModule.TestSites.Standard");
return applicationPath;
}
public static string GetConfigContent(ServerType serverType, string iisConfig)
{
string content = null;
if (serverType == ServerType.IISExpress)
{
content = File.ReadAllText(iisConfig);
}
return content;
}
public static void ClearApplicationEventLog()
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Clear();
}
for (int i = 0; i < 5; i++)
{
TestUtility.LogInformation("Waiting 1 seconds for eventlog to clear...");
Thread.Sleep(1000);
EventLog systemLog = new EventLog("Application");
if (systemLog.Entries.Count == 0)
{
break;
}
}
}
public static List<String> GetApplicationEvent(int id, DateTime startFrom)
{
var result = new List<String>();
TestUtility.LogInformation("Waiting 1 seconds for eventlog to update...");
Thread.Sleep(1000);
EventLog systemLog = new EventLog("Application");
foreach (EventLogEntry entry in systemLog.Entries)
{
if (entry.InstanceId == id && entry.TimeWritten >= startFrom)
{
result.Add(entry.ReplacementStrings[0]);
}
}
return result;
}
public static string ConvertToPunycode(string domain)
{
Uri uri = new Uri("http://" + domain);
return uri.DnsSafeHost;
}
}
}

View File

@ -0,0 +1,234 @@
// 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 System.IO;
namespace AspNetCoreModule.Test.Framework
{
public class TestWebApplication : IDisposable
{
private TestWebSite _testSite;
public TestWebSite TestSite
{
get
{
return _testSite;
}
set
{
_testSite = value;
}
}
public TestWebApplication(string name, string physicalPath, string url = null)
: this(name, physicalPath, null, url)
{
}
public TestWebApplication(string name, string physicalPath, TestWebSite siteContext, string url = null)
{
_testSite = siteContext;
_name = name;
string temp = physicalPath;
if (physicalPath.Contains("%"))
{
temp = System.Environment.ExpandEnvironmentVariables(physicalPath);
}
_physicalPath = temp;
if (url != null)
{
_url = url;
}
else
{
string tempUrl = name.Trim();
if (tempUrl[0] != '/')
{
_url = "/" + tempUrl;
}
else
{
_url = tempUrl;
}
}
BackupFile("web.config");
}
public void Dispose()
{
DeleteFile("app_offline.htm");
RestoreFile("web.config");
}
private string _name = null;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
private string _physicalPath = null;
public string PhysicalPath
{
get
{
return _physicalPath;
}
set
{
_physicalPath = value;
}
}
private string _url = null;
public string URL
{
get
{
return _url;
}
set
{
_url = value;
}
}
public Uri GetHttpUri()
{
return new Uri("http://" + _testSite.HostName + ":" + _testSite.TcpPort.ToString() + URL);
}
public Uri GetHttpUri(string subPath)
{
string tempSubPath = subPath;
if (!tempSubPath.StartsWith("/"))
{
tempSubPath = "/" + tempSubPath;
}
return new Uri("http://" + _testSite.HostName + ":" + _testSite.TcpPort.ToString() + URL + tempSubPath);
}
public string _appPoolName = null;
public string AppPoolName
{
get
{
if (_appPoolName == null)
{
_appPoolName = "DefaultAppPool";
}
return _appPoolName;
}
set
{
_appPoolName = value;
}
}
public string GetProcessFileName()
{
string filePath = Path.Combine(_physicalPath, "web.config");
string result = null;
// read web.config
string fileContent = TestUtility.FileReadAllText(filePath);
// get the value of processPath attribute of aspNetCore element
if (fileContent != null)
{
result = TestUtility.XmlParser(fileContent, "aspNetCore", "processPath", null);
}
// split fileName from full path
result = Path.GetFileName(result);
// append .exe if it wasn't used
if (!result.Contains(".exe"))
{
result = result + ".exe";
}
return result;
}
public string GetArgumentFileName()
{
string filePath = Path.Combine(_physicalPath, "web.config");
string result = null;
// read web.config
string fileContent = TestUtility.FileReadAllText(filePath);
// get the value of processPath attribute of aspNetCore element
if (fileContent != null)
{
result = TestUtility.XmlParser(fileContent, "aspNetCore", "arguments", null);
}
// split fileName from full path
result = Path.GetFileName(result);
return result;
}
public void BackupFile(string from)
{
string fromfile = Path.Combine(_physicalPath, from);
string tofile = Path.Combine(_physicalPath, fromfile + ".bak");
TestUtility.FileCopy(fromfile, tofile, overWrite: false);
}
public void RestoreFile(string from)
{
string fromfile = Path.Combine(_physicalPath, from + ".bak");
string tofile = Path.Combine(_physicalPath, from);
if (!File.Exists(tofile))
{
BackupFile(from);
}
TestUtility.FileCopy(fromfile, tofile);
}
public string GetDirectoryPathWith(string subPath)
{
return Path.Combine(_physicalPath, subPath);
}
public void DeleteFile(string file = "app_offline.htm")
{
string filePath = Path.Combine(_physicalPath, file);
TestUtility.DeleteFile(filePath);
}
public void CreateFile(string[] content, string file = "app_offline.htm")
{
string filePath = Path.Combine(_physicalPath, file);
TestUtility.CreateFile(filePath, content);
}
public void MoveFile(string from, string to)
{
string fromfile = Path.Combine(_physicalPath, from);
string tofile = Path.Combine(_physicalPath, to);
TestUtility.FileMove(fromfile, tofile);
}
public void DeleteDirectory(string directory)
{
string directoryPath = Path.Combine(_physicalPath, directory);
TestUtility.DeleteDirectory(directoryPath);
}
public void CreateDirectory(string directory)
{
string directoryPath = Path.Combine(_physicalPath, directory);
TestUtility.CreateDirectory(directoryPath);
}
}
}

View File

@ -0,0 +1,244 @@
// 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 System.IO;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
namespace AspNetCoreModule.Test.Framework
{
public class TestWebSite : IDisposable
{
static private bool _publishedAspnetCoreApp = false;
public TestWebApplication RootAppContext;
public TestWebApplication AspNetCoreApp;
public TestWebApplication WebSocketApp;
public TestWebApplication URLRewriteApp;
public TestUtility testHelper;
private ILogger _logger;
private int _iisExpressPidBackup = -1;
private string postfix = string.Empty;
public void Dispose()
{
TestUtility.LogInformation("TestWebSite::Dispose() Start");
if (_iisExpressPidBackup != -1)
{
var iisExpressProcess = Process.GetProcessById(Convert.ToInt32(_iisExpressPidBackup));
iisExpressProcess.Kill();
iisExpressProcess.WaitForExit();
}
TestUtility.LogInformation("TestWebSite::Dispose() End");
}
public string _hostName = null;
public string HostName
{
get
{
if (_hostName == null)
{
_hostName = "localhost";
}
return _hostName;
}
set
{
_hostName = value;
}
}
public string _siteName = null;
public string SiteName
{
get
{
return _siteName;
}
set
{
_siteName = value;
}
}
public int _tcpPort = 8080;
public int TcpPort
{
get
{
return _tcpPort;
}
set
{
_tcpPort = value;
}
}
public TestWebSite(IISConfigUtility.AppPoolBitness appPoolBitness, string loggerPrefix = "ANCMTest", ServerType serverType = ServerType.IIS)
{
TestUtility.LogInformation("TestWebSite::TestWebSite() Start");
string solutionPath = InitializeTestMachine.GetSolutionDirectory();
if (serverType == ServerType.IIS)
{
// check JitDebugger before continuing
TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger);
}
// initialize logger for TestUtility
_logger = new LoggerFactory()
.AddConsole()
.CreateLogger(string.Format(loggerPrefix));
testHelper = new TestUtility(_logger);
//
// Initialize context variables
//
string siteRootPath = string.Empty;
string siteName = string.Empty;
// repeat three times until getting the valid temporary directory path
for (int i = 0; i < 3; i++)
{
string postfix = Path.GetRandomFileName();
siteName = loggerPrefix.Replace(" ", "") + "_" + postfix;
siteRootPath = Path.Combine(Environment.ExpandEnvironmentVariables("%SystemDrive%") + @"\", "inetpub", "ANCMTest", siteName);
if (!Directory.Exists(siteRootPath))
{
break;
}
}
TestUtility.DirectoryCopy(Path.Combine(solutionPath, "test", "WebRoot"), siteRootPath);
string aspnetCoreAppRootPath = Path.Combine(siteRootPath, "AspNetCoreApp");
string srcPath = TestUtility.GetApplicationPath();
//
// Currently we use only DotnetCore v1.1
//
string publishPath = Path.Combine(srcPath, "bin", "Debug", "netcoreapp1.1", "publish");
//
// Publish aspnetcore app
//
if (_publishedAspnetCoreApp != true)
{
string argumentForDotNet = "publish " + srcPath;
TestUtility.LogInformation("TestWebSite::TestWebSite() StandardTestApp is not published, trying to publish on the fly: dotnet.exe " + argumentForDotNet);
TestUtility.RunCommand("dotnet", argumentForDotNet);
_publishedAspnetCoreApp = true;
}
// check published files
bool checkPublishedFiles = false;
string[] publishedFiles = Directory.GetFiles(publishPath);
foreach (var item in publishedFiles)
{
if (Path.GetFileName(item) == "web.config")
{
checkPublishedFiles = true;
}
}
if (!checkPublishedFiles)
{
throw new System.ApplicationException("web.config is not available in " + publishPath);
}
// Copy the pubishpath to standardAppRootPath
TestUtility.DirectoryCopy(publishPath, aspnetCoreAppRootPath);
int tcpPort = InitializeTestMachine.SiteId++;
int siteId = tcpPort;
//
// initialize class member variables
//
string appPoolName = null;
if (serverType == ServerType.IIS)
{
appPoolName = siteName;
}
else if (serverType == ServerType.IISExpress)
{
appPoolName = "Clr4IntegratedAppPool";
}
// Initialize member variables
_hostName = "localhost";
_siteName = siteName;
_tcpPort = tcpPort;
RootAppContext = new TestWebApplication("/", Path.Combine(siteRootPath, "WebSite1"), this);
RootAppContext.RestoreFile("web.config");
RootAppContext.DeleteFile("app_offline.htm");
RootAppContext.AppPoolName = appPoolName;
AspNetCoreApp = new TestWebApplication("/AspNetCoreApp", aspnetCoreAppRootPath, this);
AspNetCoreApp.AppPoolName = appPoolName;
AspNetCoreApp.RestoreFile("web.config");
AspNetCoreApp.DeleteFile("app_offline.htm");
WebSocketApp = new TestWebApplication("/WebSocketApp", Path.Combine(siteRootPath, "WebSocket"), this);
WebSocketApp.AppPoolName = appPoolName;
WebSocketApp.RestoreFile("web.config");
WebSocketApp.DeleteFile("app_offline.htm");
URLRewriteApp = new TestWebApplication("/URLRewriteApp", Path.Combine(siteRootPath, "URLRewrite"), this);
URLRewriteApp.AppPoolName = appPoolName;
URLRewriteApp.RestoreFile("web.config");
URLRewriteApp.DeleteFile("app_offline.htm");
// copy http.config to the test site root directory and initialize iisExpressConfigPath with the path
string iisExpressConfigPath = null;
if (serverType == ServerType.IISExpress)
{
iisExpressConfigPath = Path.Combine(siteRootPath, "http.config");
TestUtility.FileCopy(Path.Combine(solutionPath, "test", "AspNetCoreModule.Test", "http.config"), iisExpressConfigPath);
}
//
// Create site and apps
//
using (var iisConfig = new IISConfigUtility(serverType, iisExpressConfigPath))
{
if (serverType == ServerType.IIS)
{
iisConfig.CreateAppPool(appPoolName);
bool is32bit = (appPoolBitness == IISConfigUtility.AppPoolBitness.enable32Bit);
iisConfig.SetAppPoolSetting(appPoolName, "enable32BitAppOnWin64", is32bit);
}
iisConfig.CreateSite(siteName, RootAppContext.PhysicalPath, siteId, this.TcpPort, appPoolName);
iisConfig.CreateApp(siteName, AspNetCoreApp.Name, AspNetCoreApp.PhysicalPath, appPoolName);
iisConfig.CreateApp(siteName, WebSocketApp.Name, WebSocketApp.PhysicalPath, appPoolName);
iisConfig.CreateApp(siteName, URLRewriteApp.Name, URLRewriteApp.PhysicalPath, appPoolName);
}
if (serverType == ServerType.IISExpress)
{
string cmdline;
string argument = "/siteid:" + siteId + " /config:" + iisExpressConfigPath;
if (Directory.Exists(Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%")) && appPoolBitness == IISConfigUtility.AppPoolBitness.enable32Bit)
{
cmdline = Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%"), "IIS Express", "iisexpress.exe");
}
else
{
cmdline = Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles%"), "IIS Express", "iisexpress.exe");
}
TestUtility.LogInformation("TestWebSite::TestWebSite() Start IISExpress: " + cmdline + " " + argument);
_iisExpressPidBackup = TestUtility.RunCommand(cmdline, argument, false, false);
}
TestUtility.LogInformation("TestWebSite::TestWebSite() End");
}
}
}

View File

@ -0,0 +1,293 @@
// 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 AspNetCoreModule.Test.Framework;
using Microsoft.AspNetCore.Testing.xunit;
using System.Threading.Tasks;
using Xunit;
namespace AspNetCoreModule.Test
{
public class FunctionalTest : FunctionalTestHelper, IClassFixture<InitializeTestMachine>
{
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(ServerType.IISExpress, IISConfigUtility.AppPoolBitness.noChange)]
[InlineData(ServerType.IISExpress, IISConfigUtility.AppPoolBitness.enable32Bit)]
public Task BasicTestOnIISExpress(ServerType serverType, IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoBasicTest(serverType, appPoolBitness);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(ServerType.IIS, IISConfigUtility.AppPoolBitness.noChange)]
[InlineData(ServerType.IIS, IISConfigUtility.AppPoolBitness.enable32Bit)]
public Task BasicTestOnIIS(ServerType serverType, IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoBasicTest(serverType, appPoolBitness);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, 5)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 5)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, 1)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 0)]
public Task RapidFailsPerMinuteTest(IISConfigUtility.AppPoolBitness appPoolBitness, int valueOfRapidFailsPerMinute)
{
return DoRapidFailsPerMinuteTest(appPoolBitness, valueOfRapidFailsPerMinute);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 25, 19)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, 25, 19)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 5, 4)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, 5, 4)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 0, 0)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, 0, 0)]
public Task ShutdownTimeLimitTest(IISConfigUtility.AppPoolBitness appPoolBitness, int valueOfshutdownTimeLimit, int expectedClosingTime)
{
return DoShutdownTimeLimitTest(appPoolBitness, valueOfshutdownTimeLimit, expectedClosingTime);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 10)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, 10)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 1)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, 1)]
public Task StartupTimeLimitTest(IISConfigUtility.AppPoolBitness appPoolBitness, int starupTimeLimit)
{
return DoStartupTimeLimitTest(appPoolBitness, starupTimeLimit);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789")]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, "a")]
public Task WebSocketTest(IISConfigUtility.AppPoolBitness appPoolBitness, string testData)
{
return DoWebSocketTest(appPoolBitness, testData);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange)]
public Task RecycleApplicationAfterBackendProcessBeingKilled(IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoRecycleApplicationAfterBackendProcessBeingKilled(appPoolBitness);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange)]
public Task RecycleApplicationAfterW3WPProcessBeingKilled(IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoRecycleApplicationAfterW3WPProcessBeingKilled(appPoolBitness);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange)]
public Task RecycleApplicationAfterWebConfigUpdated(IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoRecycleApplicationAfterWebConfigUpdated(appPoolBitness);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange)]
public Task RecycleApplicationWithURLRewrite(IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoRecycleApplicationWithURLRewrite(appPoolBitness);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange)]
public Task RecycleParentApplicationWithURLRewrite(IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoRecycleParentApplicationWithURLRewrite(appPoolBitness);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange)]
public Task EnvironmentVariablesTest(IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoEnvironmentVariablesTest(appPoolBitness);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange)]
public Task AppOfflineTestWithRenaming(IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoAppOfflineTestWithRenaming(appPoolBitness);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange)]
public Task AppOfflineTestWithUrlRewriteAndDeleting(IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoAppOfflineTestWithUrlRewriteAndDeleting(appPoolBitness);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789")]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, "a")]
public Task PostMethodTest(IISConfigUtility.AppPoolBitness appPoolBitness, string testData)
{
return DoPostMethodTest(appPoolBitness, testData);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange)]
public Task DisableStartUpErrorPageTest(IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoDisableStartUpErrorPageTest(appPoolBitness);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 10)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, 2)]
public Task ProcessesPerApplicationTest(IISConfigUtility.AppPoolBitness appPoolBitness, int valueOfProcessesPerApplication)
{
return DoProcessesPerApplicationTest(appPoolBitness, valueOfProcessesPerApplication);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, "00:02:00")]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, "00:02:00")]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, "00:01:00")]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, "00:01:00")]
public Task RequestTimeoutTest(IISConfigUtility.AppPoolBitness appPoolBitness, string requestTimeout)
{
return DoRequestTimeoutTest(appPoolBitness, requestTimeout);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange)]
public Task StdoutLogEnabledTest(IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoStdoutLogEnabledTest(appPoolBitness);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, "dotnet.exe", "./")]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, "dotnet", @".\")]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, "$env", "")]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, "$env", "")]
public Task ProcessPathAndArgumentsTest(IISConfigUtility.AppPoolBitness appPoolBitness, string processPath, string argumentsPrefix)
{
return DoProcessPathAndArgumentsTest(appPoolBitness, processPath, argumentsPrefix);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, true)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, false)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, true)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, false)]
public Task ForwardWindowsAuthTokenTest(IISConfigUtility.AppPoolBitness appPoolBitness, bool enabledForwardWindowsAuthToken)
{
return DoForwardWindowsAuthTokenTest(appPoolBitness, enabledForwardWindowsAuthToken);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange)]
public Task RecylingAppPoolTest(IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoRecylingAppPoolTest(appPoolBitness);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, true, true)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, false, false)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, true, false)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange, false, true)]
public Task CompressionTest(IISConfigUtility.AppPoolBitness appPoolBitness, bool useCompressionMiddleWare, bool enableIISCompression)
{
return DoCompressionTest(appPoolBitness, useCompressionMiddleWare, enableIISCompression);
}
[EnvironmentVariableTestCondition("IIS_VARIATIONS_ENABLED")]
[ConditionalTheory]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)]
[InlineData(IISConfigUtility.AppPoolBitness.noChange)]
public Task CachingTest(IISConfigUtility.AppPoolBitness appPoolBitness)
{
return DoCachingTest(appPoolBitness);
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,336 @@
// 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 AspNetCoreModule.Test.Framework;
using System;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Threading;
using System.Net.Sockets;
namespace AspNetCoreModule.Test.HttpClientHelper
{
public class HttpClientHelper
{
private IPHostEntry _host = Dns.GetHostEntry(Dns.GetHostName());
private string _ipv4Loopback = "127.0.0.1";
private string _ipv4One = null;
private string _ipv4Two = null;
private string _ipv6Loopback = "[::1]";
private string _ipv6One = null;
private string _ipv6Two = null;
public HttpClientHelper()
{
ReadMachineIpAddressInfo();
_Ips = new string[] { _ipv4Loopback, _ipv4One, _ipv6Loopback, _ipv6One, _ipv6Two };
_Hosts = new string[] { "foo", "bar", "foobar", "barfoo" };
_unusedIp = _ipv6Two;
}
// callback used to validate the certificate in an SSL conversation
public static bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
{
return true;
}
public static int sendRequest(string uri, string hostName, string expectedCN, bool useLegacy, bool displayContent, bool doLogging = true)
{
int status = -1;
if (doLogging)
{
if (hostName == null)
TestUtility.LogInformation(String.Format("HttpClient::sendRequest() {0} with no hostname", uri));
else
TestUtility.LogInformation(String.Format("HttpClient::sendRequest() {0} with hostname {1}", uri, hostName));
}
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
if (useLegacy)
{
TestUtility.LogInformation(String.Format("Using SSL3"));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
}
HttpWebRequest myRequest;
myRequest = (HttpWebRequest)WebRequest.Create(uri);
myRequest.Proxy = null;
myRequest.KeepAlive = false;
if (hostName != null)
myRequest.Host = hostName;
ServicePoint point = myRequest.ServicePoint;
point.ConnectionLeaseTimeout = 0;
try
{
using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
{
using (Stream myStream = myResponse.GetResponseStream())
{
if (displayContent)
{
using (StreamReader myReader = new StreamReader(myStream))
{
string text = myReader.ReadToEnd();
TestUtility.LogInformation("\n\n");
TestUtility.LogInformation(text);
TestUtility.LogInformation("\n\n");
}
}
}
status = (int)myResponse.StatusCode;
}
}
catch (WebException ex)
{
if ((HttpWebResponse)ex.Response == null)
status = 0;
else
status = (int)((HttpWebResponse)ex.Response).StatusCode;
}
return status;
}
public string IPv4Loopback
{
get { return _ipv4Loopback; }
}
public string IPv4One
{
get { return _ipv4One; }
}
public string IPv4Two
{
get { return _ipv4Two; }
}
public string IPv6Loopback
{
get { return _ipv6Loopback; }
}
public string IPv6One
{
get { return _ipv6One; }
}
public string IPv6Two
{
get { return _ipv6Two; }
}
private string[] _Ips;
private string[] _Hosts = { "foo", "bar", "foobar", "barfoo" };
private string _unusedIp;
private Thread _backgroundRequestThread = null;
public void ReadMachineIpAddressInfo()
{
foreach (IPAddress ip in _host.AddressList)
{
if (IPAddress.IsLoopback(ip))
continue;
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
if (_ipv4One == null)
_ipv4One = ip.ToString();
else if (_ipv4Two == null)
_ipv4Two = ip.ToString();
}
else if (ip.AddressFamily == AddressFamily.InterNetworkV6)
{
if (!ip.ToString().Contains("%"))
{
if (_ipv6One == null)
_ipv6One = "[" + ip.ToString() + "]";
else if (_ipv6Two == null)
_ipv6Two = "[" + ip.ToString() + "]";
}
}
}
}
public int SendReceiveStatus(string path = "/", string protocol = "http", string ip = "127.0.0.1", int port = 8080, string host = "localhost", int expectedStatus = 200, int retryCount = 0)
{
string uri = protocol + "://" + ip + ":" + port + path;
int status = HttpClientHelper.sendRequest(uri, host, "CN=NULL", false, false);
for (int i = 0; i < retryCount; i++)
{
if (status == expectedStatus)
{
break;
}
DoSleep(1000);
status = HttpClientHelper.sendRequest(uri, host, "CN=NULL", false, false);
}
return status;
}
public void DoRequest(string uri, string host = null, string expectedCN = "CN=NULL", bool useLegacy = false, bool displayContent = false)
{
HttpClientHelper.sendRequest(uri, host, expectedCN, useLegacy, displayContent);
}
private void BackgroundRequestLoop(object req)
{
String[] uriHost = (String[])req;
while (true)
{
HttpClientHelper.sendRequest(uriHost[0], uriHost[1], "CN=NULL", false, false, false);
Thread.Sleep(5000);
}
}
public void StartBackgroundRequests(string uri, string host = null)
{
if (_backgroundRequestThread != null && _backgroundRequestThread.ThreadState == System.Threading.ThreadState.Running)
_backgroundRequestThread.Abort();
if (host == null)
TestUtility.LogInformation(String.Format("########## Starting background requests to {0} with no hostname ##########", uri));
else
TestUtility.LogInformation(String.Format("########## Starting background requests to {0} with hostname {1} ##########", uri, host));
ParameterizedThreadStart threadStart = new ParameterizedThreadStart(BackgroundRequestLoop);
_backgroundRequestThread = new Thread(threadStart);
_backgroundRequestThread.IsBackground = true;
_backgroundRequestThread.Start(new string[] { uri, host });
}
public void StopBackgroundRequests()
{
TestUtility.LogInformation(String.Format("####################### Stopping background requests #######################"));
if (_backgroundRequestThread != null && _backgroundRequestThread.ThreadState == System.Threading.ThreadState.Running)
_backgroundRequestThread.Abort();
_backgroundRequestThread = null;
}
public void DoSleep(int sleepMs)
{
TestUtility.LogInformation(String.Format("################## Sleeping for {0} ms ##################", sleepMs));
Thread.Sleep(sleepMs);
}
}
public class RequestInfo
{
public string ip;
public int port;
public string host;
public int status;
public RequestInfo(string ipIn, int portIn, string hostIn, int statusIn)
{
ip = ipIn;
port = portIn;
host = hostIn;
status = statusIn;
}
public string ToUrlRegistration()
{
if ((ip == null || ip == "*") && (host == null || host == "*"))
return String.Format("HTTP://*:{0}/", port).ToUpper();
if (ip == null || ip == "*")
return String.Format("HTTP://{0}:{1}/", host, port).ToUpper();
if (host == null || host == "*")
return String.Format("HTTP://{0}:{1}:{0}/", ip, port).ToUpper();
return String.Format("HTTP://{0}:{1}:{2}/", host, port, ip).ToUpper();
}
}
public class BindingInfo
{
public string ip;
public int port;
public string host;
public BindingInfo(string ip, int port, string host)
{
this.ip = ip;
this.port = port;
this.host = host;
}
public int GetBindingType()
{
if (ip == null)
{
if (host == null)
return 5;
else
return 3;
}
else
{
if (host == null)
return 4;
else
return 2;
}
}
public bool IsSupportedForDynamic()
{
return GetBindingType() == 2 || GetBindingType() == 5;
}
public bool Match(RequestInfo req)
{
if (ip != null && ip != req.ip)
return false;
if (port != req.port)
return false;
if (host != null && host != req.host)
return false;
return true;
}
public string ToBindingString()
{
string bindingInfoString = "";
bindingInfoString += (ip == null) ? "*" : ip;
bindingInfoString += ":";
bindingInfoString += port;
bindingInfoString += ":";
if (host != null)
bindingInfoString += host;
return bindingInfoString;
}
public string ToUrlRegistration()
{
if ((ip == null || ip == "*") && (host == null || host == "*"))
return String.Format("HTTP://*:{0}/", port).ToUpper();
if (ip == null || ip == "*")
return String.Format("HTTP://{0}:{1}/", host, port).ToUpper();
if (host == null || host == "*")
return String.Format("HTTP://{0}:{1}:{0}/", ip, port).ToUpper();
return String.Format("HTTP://{0}:{1}:{2}/", host, port, ip).ToUpper();
}
}
}

View File

@ -0,0 +1,44 @@
// 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.
namespace AspNetCoreModule.Test.WebSocketClient
{
public class Frame
{
private int startingIndex; // This will be initialized as output parameter of GetFrameString()
public int DataLength; // This will be initialized as output parameter of GetFrameString()
public Frame(byte[] data)
{
Data = data;
FrameType = WebSocketClientUtility.GetFrameType(Data);
Content = WebSocketClientUtility.GetFrameString(Data, out startingIndex, out DataLength);
IsMasked = WebSocketClientUtility.IsFrameMasked(Data);
}
public FrameType FrameType { get; set; }
public byte[] Data { get; private set; }
public string Content { get; private set; }
public bool IsMasked { get; private set; }
public int IndexOfNextFrame
{
get
{
if (startingIndex > 0 && Data.Length > Content.Length + startingIndex)
{
return Content.Length + startingIndex;
}
else
{
return -1;
}
}
}
override public string ToString()
{
return FrameType + ": " + Content;
}
}
}

View File

@ -0,0 +1,27 @@
// 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.
namespace AspNetCoreModule.Test.WebSocketClient
{
//* %x0 denotes a continuation frame
//* %x1 denotes a text frame
//* %x2 denotes a binary frame
//* %x3-7 are reserved for further non-control frames
//* %x8 denotes a connection close
//* %x9 denotes a ping
//* %xA denotes a pong
public enum FrameType
{
NonControlFrame,
Ping,
Pong,
Text,
SegmentedText,
Binary,
SegmentedBinary,
Continuation,
ContinuationControlled,
ContinuationFrameEnd,
Close,
}
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,370 @@
// 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 AspNetCoreModule.Test.Framework;
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using Xunit;
namespace AspNetCoreModule.Test.WebSocketClient
{
public class WebSocketClientHelper : IDisposable
{
public bool IsOpened { get; private set; }
public WebSocketConnect Connection { get; set; }
public bool StoreData { get; set; }
public bool IsAlwaysReading { get; private set; }
public Uri Address { get; set; }
public byte[][] HandShakeRequest { get; set; }
public WebSocketState WebSocketState { get; set; }
public WebSocketClientHelper()
{
}
public void Dispose()
{
if (IsOpened)
{
Close();
}
}
public Frame Connect(Uri address, bool storeData, bool isAlwaysReading)
{
Address = address;
StoreData = storeData;
Connection = new WebSocketConnect();
if (isAlwaysReading)
{
InitiateWithAlwaysReading();
}
SendWebSocketRequest(WebSocketClientUtility.WebSocketVersion);
Thread.Sleep(3000);
Frame openingFrame = null;
if (!IsAlwaysReading)
openingFrame = ReadData();
else
openingFrame = Connection.DataReceived[0];
Thread.Sleep(1000);
IsOpened = true;
return openingFrame;
}
public Frame Close()
{
CloseConnection();
Thread.Sleep(1000);
Frame closeFrame = null;
if (!IsAlwaysReading)
closeFrame = ReadData();
else
closeFrame = Connection.DataReceived[Connection.DataReceived.Count - 1];
IsOpened = false;
return closeFrame;
}
public void Initiate()
{
string host = Address.DnsSafeHost;
int port = Address.Port;
Connection = new WebSocketConnect();
TestUtility.LogInformation("Connecting to {0} on {1}", host, port);
Connection.TcpClient = new MyTcpClient(host, port);
Connection.Stream = Connection.TcpClient.GetStream();
IsAlwaysReading = false;
if (StoreData)
{
Connection.DataSent = new List<Frame>();
Connection.DataReceived = new List<Frame>();
}
}
public void InitiateWithAlwaysReading()
{
Initiate();
Connection.Stream.BeginRead(Connection.InputData, 0, Connection.InputData.Length, ReadDataCallback, Connection);
IsAlwaysReading = true;
}
public void SendWebSocketRequest(int websocketVersion)
{
HandShakeRequest = Frames.GetHandShakeFrame(Address.AbsoluteUri, websocketVersion);
byte[] outputData = null;
int offset = 0;
while (offset < HandShakeRequest.Length)
{
outputData = HandShakeRequest[offset++];
var result = Connection.Stream.BeginWrite(outputData, 0, outputData.Length, WriteCallback, Connection);
//jhkim debug
//result.AsyncWaitHandle.WaitOne();
TestUtility.LogInformation("Client {0:D3}: Write {1} bytes: {2} ", Connection.Id, outputData.Length,
Encoding.UTF8.GetString(outputData, 0, outputData.Length));
//result.AsyncWaitHandle.Close();
}
}
public void SendWebSocketRequest(int websocketVersion, string AffinityCookie)
{
HandShakeRequest = Frames.GetHandShakeFrameWithAffinityCookie(Address.AbsoluteUri, websocketVersion, AffinityCookie);
byte[] outputData = null;
int offset = 0;
while (offset < HandShakeRequest.Length)
{
outputData = HandShakeRequest[offset++];
Connection.Stream.BeginWrite(outputData, 0, outputData.Length, WriteCallback, Connection);
TestUtility.LogInformation("Client {0:D3}: Write {1} bytes: {2} ", Connection.Id, outputData.Length,
Encoding.UTF8.GetString(outputData, 0, outputData.Length));
}
}
public void ReadDataCallback(IAsyncResult result)
{
WebSocketConnect client = (WebSocketConnect) result.AsyncState;
if (client.IsDisposed)
return;
int bytesRead = client.Stream.EndRead(result); // wait until the buffer is filled
int bytesReadIntotal = bytesRead;
ArrayList InputDataArray = new ArrayList();
byte[] tempBuffer = null;
if (bytesRead > 0)
{
tempBuffer = WebSocketClientUtility.SubArray(Connection.InputData, 0, bytesRead);
Frame temp = new Frame(tempBuffer);
// start looping if there is still remaining data
if (tempBuffer.Length < temp.DataLength)
{
if (client.TcpClient.GetStream().DataAvailable)
{
// add the first buffer to the arrayList
InputDataArray.Add(tempBuffer);
// start looping appending to the arrayList
while (client.TcpClient.GetStream().DataAvailable)
{
bytesRead = client.TcpClient.GetStream().Read(Connection.InputData, 0, Connection.InputData.Length);
tempBuffer = WebSocketClientUtility.SubArray(Connection.InputData, 0, bytesRead);
InputDataArray.Add(tempBuffer);
bytesReadIntotal += bytesRead;
TestUtility.LogInformation("ReadDataCallback: Looping: Client {0:D3}: bytesReadHere {1} ", Connection.Id, bytesRead);
}
// create a single byte array with the arrayList
tempBuffer = new byte[bytesReadIntotal];
int arrayIndex = 0;
foreach (byte[] item in InputDataArray.ToArray())
{
for (int i = 0; i < item.Length; i++)
{
tempBuffer[arrayIndex] = item[i];
arrayIndex++;
}
}
}
}
// Create frame with the tempBuffer
Frame frame = new Frame(tempBuffer);
int nextFrameIndex = 0;
while (nextFrameIndex != -1)
{
TestUtility.LogInformation("ReadDataCallback: Client {0:D3}: Read Type {1} : {2} ", Connection.Id, frame.FrameType, bytesReadIntotal);
ProcessReceivedData(frame);
// Send Pong if the frame was Ping
if (frame.FrameType == FrameType.Ping)
SendPong(frame);
nextFrameIndex = frame.IndexOfNextFrame;
if (nextFrameIndex != -1)
{
tempBuffer = tempBuffer.SubArray(frame.IndexOfNextFrame, tempBuffer.Length - frame.IndexOfNextFrame);
frame = new Frame(tempBuffer);
}
}
// Send Pong if the frame was Ping
if (frame.FrameType == FrameType.Ping)
SendPong(frame);
if (client.IsDisposed)
return;
// Start the Async Read to handle the next frame comming from server
client.Stream.BeginRead(client.InputData, 0, client.InputData.Length, ReadDataCallback, client);
}
else
{
client.Dispose();
}
}
public Frame ReadData()
{
Frame frame = new Frame(new byte[] { });
IAsyncResult result = Connection.Stream.BeginRead(Connection.InputData, 0, Connection.InputData.Length, null, Connection);
if (result != null)
{
int bytesRead = Connection.Stream.EndRead(result);
if (bytesRead > 0)
{
frame = new Frame(WebSocketClientUtility.SubArray(Connection.InputData, 0, bytesRead));
ProcessReceivedData(frame);
TestUtility.LogInformation("Client {0:D3}: Read Type {1} : {2} ", Connection.Id, frame.FrameType, frame.Content.Length);
}
}
return frame;
}
public void SendTextData(string data)
{
Send(WebSocketClientUtility.GetFramedTextDataInBytes(data));
}
public void SendTextData(string data, byte opCode)
{
Send(WebSocketClientUtility.GetFramedTextDataInBytes(data, opCode));
}
public void SendHello()
{
Send(Frames.HELLO);
}
public void SendPing()
{
Send(Frames.PING);
}
public void SendPong()
{
Send(Frames.PONG);
}
public void SendPong(Frame receivedPing)
{
var pong = new byte[receivedPing.Data.Length+4];
for (int i = 1; i < receivedPing.Data.Length; i++)
{
if(i<2)
pong[i] = receivedPing.Data[i];
else
pong[i+4] = receivedPing.Data[i];
}
pong[0] = 0x8A;
pong[1] = (byte)((int)pong[1] | 128);
Send(pong);
}
public void CloseConnection()
{
Connection.Done = true;
Send(Frames.CLOSE_FRAME);
}
public static void WriteCallback(IAsyncResult result)
{
var client = result.AsyncState as WebSocketConnect;
if (client.IsDisposed)
return;
client.Stream.EndWrite(result);
}
override public string ToString()
{
return Connection.Id + ": " + WebSocketState.ToString();
}
#region Private Methods
public Frame Send(byte[] outputData)
{
var frame = new Frame(outputData);
ProcessSentData(frame);
if (Connection.TcpClient.Connected)
{
var result = Connection.Stream.BeginWrite(outputData, 0, outputData.Length, WriteCallback, Connection);
TestUtility.LogInformation("Client {0:D3}: Write Type {1} : {2} ", Connection.Id, frame.FrameType,
frame.Content.Length);
}
else
{
TestUtility.LogInformation("Connection is disconnected");
}
return frame;
}
private void ProcessSentData(Frame frame)
{
ProcessData(frame, true);
}
private void ProcessReceivedData(Frame frame)
{
if (frame.Content.Contains("Connection: Upgrade")
&& frame.Content.Contains("Upgrade: Websocket")
&& frame.Content.Contains("HTTP/1.1 101 Switching Protocols"))
WebSocketState = WebSocketState.ConnectionOpen;
if (frame.FrameType == FrameType.Close)
WebSocketState = WebSocketState.ConnectionClosed;
ProcessData(frame, false);
}
private void ProcessData(Frame frame, bool isSentData)
{
if (isSentData && StoreData)
StoreDataSent(frame);
else if (StoreData)
StoreDataReceived(frame);
}
private void StoreDataReceived(Frame frame)
{
Connection.DataReceived.Add(frame);
Connection.TotalDataReceived += frame.Content.Length;
}
private void StoreDataSent(Frame frame)
{
Connection.DataSent.Add(frame);
Connection.TotalDataSent += frame.Content.Length;
}
#endregion
}
}

View File

@ -0,0 +1,231 @@
// 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 System.Linq;
using System.Text;
namespace AspNetCoreModule.Test.WebSocketClient
{
public static class WebSocketClientUtility
{
public static FrameType GetFrameType(byte[] inputData)
{
if(inputData.Length==0)
return FrameType.NonControlFrame;
byte firstByte = inputData[0];
switch (firstByte)
{
case 0x80:
return FrameType.ContinuationFrameEnd;
case 0:
return FrameType.Continuation;
case 0x81:
return FrameType.Text;
case 0x01:
return FrameType.SegmentedText;
case 0x82:
return FrameType.Binary;
case 0x02:
return FrameType.SegmentedBinary;
case 0x88:
return FrameType.Close;
case 0x89:
return FrameType.Ping;
case 0x8A:
return FrameType.Pong;
}
return FrameType.NonControlFrame;
}
public static string GetFrameString(byte[] inputData)
{
int frameStartingIndex;
int dataLength;
return GetFrameString(inputData, out frameStartingIndex, out dataLength);
}
public static string GetFrameString(byte[] inputData, out int frameStartingIndex, out int frameDataLength)
{
string content;
FrameType frameType = GetFrameType(inputData);
int startingIndex = 2;
int dataLength = 0;
if (frameType != FrameType.NonControlFrame && frameType != FrameType.ContinuationControlled)
{
int frameLength = inputData[1];
if (IsFrameMasked(inputData))
{
frameLength = inputData[1] ^ 128;
if (frameLength < WebSocketConstants.SMALL_LENGTH_FLAG)
{
startingIndex = 6;
dataLength = inputData[1] ^ 128;
}
else if (frameLength == WebSocketConstants.SMALL_LENGTH_FLAG)
{
startingIndex = 8;
dataLength = (int)GetFrameSize(inputData, 2, 4);
}
else if (frameLength == WebSocketConstants.LARGE_LENGTH_FLAG)
{
startingIndex = 14;
dataLength = (int)GetFrameSize(inputData, 2, 10);
}
}
else
{
if (frameLength < WebSocketConstants.SMALL_LENGTH_FLAG)
{
startingIndex = 2;
dataLength = inputData[1];
}
else if (frameLength == WebSocketConstants.SMALL_LENGTH_FLAG)
{
startingIndex = 4;
dataLength = (int)GetFrameSize(inputData, 2, 4);
}
else if (frameLength == WebSocketConstants.LARGE_LENGTH_FLAG)
{
startingIndex = 10;
dataLength = (int)GetFrameSize(inputData, 2, 10);
}
}
content = Encoding.UTF8.GetString(inputData, startingIndex, (inputData.Length - startingIndex < dataLength) ? inputData.Length - startingIndex : dataLength);
}
else
{
startingIndex = 0;
dataLength = 0;
content = Encoding.UTF8.GetString(inputData, 0, inputData.Length);
}
frameStartingIndex = startingIndex;
frameDataLength = dataLength;
return content;
}
public static uint GetFrameSize(byte[] inputData, int start, int length)
{
byte[] bytes = SubArray(inputData, 2, length - 2);
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
if (length > 4)
return BitConverter.ToUInt32(bytes, 0);
else
return BitConverter.ToUInt16(bytes, 0);
}
public static byte[] GetFramedTextDataInBytes(string data)
{
return GetFramedDataInBytes(0x81, data);
}
public static byte[] GetFramedTextDataInBytes(string data, byte opCode)
{
return GetFramedDataInBytes(opCode, data);
}
public static byte[] GetFramedBinaryDataInBytes(string data)
{
return GetFramedDataInBytes(0x82, data);
}
private static byte[] GetFramedDataInBytes(byte dataType, string data)
{
var a = BitConverter.GetBytes(data.Length);
var framelist = GetByteArrayFromNumber(dataType, data.Length);
byte[] datalist = Encoding.UTF8.GetBytes(data);
var frame = JoinTwoArrays(framelist, datalist);
return frame;
}
public static byte[] GetByteArrayFromNumber(byte dataType, int number)
{
if (number < 126)
{
return new byte[] {dataType, (byte)(number | 128),0,0,0,0 };
}
else
{
byte lengthByte = WebSocketConstants.LARGE_LENGTH_BYTE;
int lengthBits = 16;
if (number < 65536)
{
lengthByte = WebSocketConstants.SMALL_LENGTH_BYTE;
lengthBits = 4;
}
var framelist = new byte[] { dataType, lengthByte };
string hexValue = (number).ToString("X");
hexValue = PrependZeroes(hexValue, lengthBits - hexValue.Length);
var sizeArray = JoinTwoArrays(StringToByteArray(hexValue), new byte[]{0,0,0,0});
return JoinTwoArrays(framelist, sizeArray);
}
}
public static string PrependZeroes(string hex, int zeroes)
{
for (int i = 0; i < zeroes; i++)
{
hex = "0" + hex;
}
return hex;
}
public static byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public static bool IsFrameMasked(byte[] inputData)
{
bool frameMasked = false;
FrameType frameType = GetFrameType(inputData);
if (frameType != FrameType.NonControlFrame && inputData[1] > 127)
frameMasked = true;
return frameMasked;
}
public static byte[] JoinTwoArrays(byte[] aArray, byte[] bArray)
{
var concat = new byte[aArray.Length + bArray.Length];
Buffer.BlockCopy(aArray, 0, concat, 0, aArray.Length);
Buffer.BlockCopy(bArray, 0, concat, aArray.Length, bArray.Length);
return concat;
}
public static T[] SubArray<T>(this T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
public static string WebSocketUri = null;
public static int WebSocketVersion { get { return 13; } }
}
}

View File

@ -0,0 +1,76 @@
// 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 System.Collections.Generic;
using System.Net.Sockets;
using System.IO;
namespace AspNetCoreModule.Test.WebSocketClient
{
public class MyTcpClient : TcpClient
{
public MyTcpClient(string hostname, int port) : base(hostname, port)
{
}
public bool IsDead { get; set; }
protected override void Dispose(bool disposing)
{
Console.WriteLine("MyClient is disposed");
IsDead = true;
base.Dispose(disposing);
}
}
public class WebSocketConnect : IDisposable
{
private static int globalID;
public WebSocketConnect()
{
Id = ++globalID;
InputData = new byte[10240];
}
public byte[] InputData { get; set; }
public bool IsDisposed { get; set; }
public bool Done { get; set; }
public int Id { get; set; }
public MyTcpClient TcpClient { get; set; }
public Stream Stream { get; set; }
public List<Frame> DataSent { get; set; }
public long TotalDataSent { get; set; }
public List<Frame> DataReceived { get; set; }
public long TotalDataReceived { get; set; }
override public string ToString()
{
return Id+"";
}
#region IDisposable Members
/// <summary>
/// Dispose this instance.
/// </summary>
public void Dispose()
{
Console.WriteLine("Client object is disposed");
IsDisposed = true;
if (Stream != null)
Stream.Close();
if (TcpClient != null)
TcpClient.Close();
}
#endregion
}
}

View File

@ -0,0 +1,15 @@
// 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.
namespace AspNetCoreModule.Test.WebSocketClient
{
public static class WebSocketConstants
{
public static int SMALL_LENGTH_FLAG = 126;
public static int LARGE_LENGTH_FLAG = 127;
public static byte SMALL_LENGTH_BYTE = 0XFE;
public static byte LARGE_LENGTH_BYTE = 0XFF;
}
}

View File

@ -0,0 +1,12 @@
// 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.
namespace AspNetCoreModule.Test.WebSocketClient
{
public enum WebSocketState
{
NonWebSocket,
ConnectionOpen,
ConnectionClosed
}
}

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Primitives" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.2.0.0" newVersion="1.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.2.0.0" newVersion="1.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.AspNetCore.Testing" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.2.0.0" newVersion="1.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.FileProviders.Embedded" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.FileProviders.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" /></startup></configuration>

View File

@ -0,0 +1,35 @@
{
"buildOptions": {
"warningsAsErrors": true,
"copyToOutput": {
"include": [
"Http.config"
]
}
},
"testRunner": "xunit",
"dependencies": {
"Microsoft.Web.Administration": "7.0.0",
"dotnet-test-xunit": "2.2.0-*",
"Microsoft.AspNetCore.Testing": "1.2.0-*",
"Microsoft.Extensions.Logging": "1.2.0-*",
"Microsoft.Extensions.Logging.Console": "1.2.0-*",
"Microsoft.Extensions.PlatformAbstractions": "1.2.0-*",
"Microsoft.Net.Http.Headers": "1.1.0-*",
"xunit": "2.2.0-*"
},
"frameworks": {
"net451": {
"frameworkAssemblies": {
"System.Data": "",
"System.IO.Compression.FileSystem": "",
"System.Management": "",
"System.Net.Http": "",
"System.Net.Http.WebRequest": "",
"System.Runtime": "",
"System.ServiceProcess": "",
"System.Xml": ""
}
}
}
}

View File

@ -0,0 +1,38 @@
{
"version": "1.1.0-*",
"dependencies": {
"Microsoft.AspNetCore.WebSockets.Server": "*",
"Microsoft.AspNetCore.Server.IISIntegration": "1.2.0-*",
"Microsoft.AspNetCore.Server.Kestrel": "1.2.0-*",
"Microsoft.AspNetCore.Server.WebListener": "1.2.0-*",
"Microsoft.AspNetCore.WebUtilities": "1.2.0-*",
"Microsoft.Extensions.Configuration.CommandLine": "1.2.0-*",
"Microsoft.Extensions.Configuration.Json": "1.2.0-*",
"Microsoft.Extensions.Logging.Console": "1.2.0-*",
"Microsoft.Net.Http.Headers": "1.2.0-*"
},
"buildOptions": {
"emitEntryPoint": true
},
"publishOptions": {
"include": [
"web.config"
]
},
"frameworks": {
"netcoreapp1.1": {
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.1.0-*",
"type": "platform"
}
}
}
},
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"scripts": {
"postpublish": "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%"
}
}

View File

@ -0,0 +1,18 @@
<?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>030225d8-4ee8-47e5-b692-2a96b3b51a38</ProjectGuid>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
<DevelopmentServerPort>49212</DevelopmentServerPort>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@ -0,0 +1,36 @@
// 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 Microsoft.AspNetCore.Http;
using System.Security.Principal;
using System.Threading.Tasks;
namespace AspnetCoreModule.TestSites.Standard
{
public class ImpersonateMiddleware
{
private readonly RequestDelegate next;
public ImpersonateMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
var winIdent = context.User.Identity as WindowsIdentity;
if (winIdent == null)
{
await context.Response.WriteAsync("ImpersonateMiddleware-UserName = NoAuthentication");
await next.Invoke(context);
}
else
{
await WindowsIdentity.RunImpersonated(winIdent.AccessToken, async () => {
string currentUserName = $"{ WindowsIdentity.GetCurrent().Name}";
await context.Response.WriteAsync("ImpersonateMiddleware-UserName = " + currentUserName);
await next.Invoke(context);
});
}
}
}
}

View File

@ -0,0 +1,123 @@
// 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 Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Net.Http.Server;
using System;
using System.IO;
using System.Threading;
namespace AspnetCoreModule.TestSites.Standard
{
public static class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
string startUpClassString = Environment.GetEnvironmentVariable("ANCMTestStartupClassName");
IWebHostBuilder builder = null;
if (!string.IsNullOrEmpty(startUpClassString))
{
if (startUpClassString == "StartupCompressionCaching")
{
builder = new WebHostBuilder()
.UseConfiguration(config)
.UseIISIntegration()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<StartupCompressionCaching>();
}
else if (startUpClassString == "StartupNoCompressionCaching")
{
StartupCompressionCaching.CompressionMode = false;
builder = new WebHostBuilder()
.UseConfiguration(config)
.UseIISIntegration()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<StartupCompressionCaching>();
}
else if (startUpClassString == "StartupHelloWorld")
{
builder = new WebHostBuilder()
.UseConfiguration(config)
.UseIISIntegration()
.UseStartup<StartupHelloWorld>();
}
else if (startUpClassString == "StartupNtlmAuthentication")
{
builder = new WebHostBuilder()
.UseConfiguration(config)
.UseIISIntegration()
.UseStartup<StartupNtlmAuthentication>();
}
else
{
throw new System.Exception("Invalid startup class name : " + startUpClassString);
}
}
else
{
builder = new WebHostBuilder()
.UseConfiguration(config)
.UseIISIntegration()
.UseStartup<Startup>();
}
string startupDelay = Environment.GetEnvironmentVariable("ANCMTestStartUpDelay");
if (!string.IsNullOrEmpty(startupDelay))
{
Startup.SleeptimeWhileStarting = Convert.ToInt32(startupDelay);
}
if (Startup.SleeptimeWhileStarting != 0)
{
Thread.Sleep(Startup.SleeptimeWhileStarting);
}
string shutdownDelay = Environment.GetEnvironmentVariable("ANCMTestShutdownDelay");
if (!string.IsNullOrEmpty(shutdownDelay))
{
Startup.SleeptimeWhileClosing = Convert.ToInt32(shutdownDelay);
}
// Switch between Kestrel and WebListener for different tests. Default to Kestrel for normal app execution.
if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.WebListener", System.StringComparison.Ordinal))
{
if (string.Equals(builder.GetSetting("environment") ??
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"),
"NtlmAuthentication", System.StringComparison.Ordinal))
{
// Set up NTLM authentication for WebListener as follows.
// For IIS and IISExpress use inetmgr to setup NTLM authentication on the application or
// modify the applicationHost.config to enable NTLM.
builder.UseWebListener(options =>
{
options.ListenerSettings.Authentication.AllowAnonymous = true;
options.ListenerSettings.Authentication.Schemes =
AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM;
});
}
else
{
builder.UseWebListener();
}
}
else
{
builder.UseKestrel();
}
var host = builder.Build();
host.Run();
if (Startup.SleeptimeWhileClosing != 0)
{
Thread.Sleep(Startup.SleeptimeWhileClosing);
}
}
}
}

View File

@ -0,0 +1,26 @@
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:39982/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ANCMTestStartupClassName": "StartupCompression",
"ASPNET_ENVIRONMENT": "HelloWorld"
}
},
"web": {
"commandName": "web",
"environmentVariables": {
"ASPNET_ENVIRONMENT": "HelloWorld"
}
}
}
}

View File

@ -0,0 +1,311 @@
// 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 Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AspnetCoreModule.TestSites.Standard
{
public class Startup
{
public static int SleeptimeWhileClosing = 0;
public static int SleeptimeWhileStarting = 0;
public static List<byte[]> MemoryLeakList = new List<byte[]>();
public void ConfigureServices(IServiceCollection services)
{
services.Configure<IISOptions>(options => {
// Considering the default value of ForwardWindowsAuthentication is true,
// the below line is not required at present, however keeping in case the default value is changed later.
options.ForwardWindowsAuthentication = true;
});
}
private async Task Echo(WebSocket webSocket)
{
var buffer = new byte[1024 * 4];
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(minLevel: LogLevel.Warning);
app.Map("/websocketSubProtocol", subApp =>
{
app.UseWebSockets(new WebSocketOptions
{
ReplaceFeature = true
});
subApp.Use(async (context, next) =>
{
if (context.WebSockets.IsWebSocketRequest)
{
var webSocket = await context.WebSockets.AcceptWebSocketAsync("mywebsocketsubprotocol");
await Echo(webSocket);
}
else
{
var wsScheme = context.Request.IsHttps ? "wss" : "ws";
var wsUrl = $"{wsScheme}://{context.Request.Host.Host}:{context.Request.Host.Port}{context.Request.Path}";
await context.Response.WriteAsync($"Ready to accept a WebSocket request at: {wsUrl}");
}
});
});
app.Map("/websocket", subApp =>
{
app.UseWebSockets(new WebSocketOptions
{
ReplaceFeature = true
});
subApp.Use(async (context, next) =>
{
if (context.WebSockets.IsWebSocketRequest)
{
var webSocket = await context.WebSockets.AcceptWebSocketAsync("");
await Echo(webSocket);
}
else
{
var wsScheme = context.Request.IsHttps ? "wss" : "ws";
var wsUrl = $"{wsScheme}://{context.Request.Host.Host}:{context.Request.Host.Port}{context.Request.Path}";
await context.Response.WriteAsync($"Ready to accept a WebSocket request at: {wsUrl}");
}
});
});
app.Map("/GetProcessId", subApp =>
{
subApp.Run(context =>
{
var process = Process.GetCurrentProcess();
return context.Response.WriteAsync(process.Id.ToString());
});
});
app.Map("/EchoPostData", subApp =>
{
subApp.Run(context =>
{
string responseBody = string.Empty;
if (string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase))
{
var form = context.Request.ReadFormAsync().GetAwaiter().GetResult();
int counter = 0;
foreach (var key in form.Keys)
{
StringValues output;
if (form.TryGetValue(key, out output))
{
responseBody += key + "=";
foreach (var line in output)
{
responseBody += line;
}
if (++counter < form.Count)
{
responseBody += "&";
}
}
}
}
else
{
responseBody = "NoAction";
}
return context.Response.WriteAsync(responseBody);
});
});
app.Map("/contentlength", subApp =>
{
subApp.Run(context =>
{
context.Response.ContentLength = 14;
return context.Response.WriteAsync("Content Length");
});
});
app.Map("/connectionclose", subApp =>
{
subApp.Run(async context =>
{
context.Response.Headers[HeaderNames.Connection] = "close";
await context.Response.WriteAsync("Connnection Close");
await context.Response.Body.FlushAsync(); // Bypass IIS write-behind buffering
});
});
app.Map("/notchunked", subApp =>
{
subApp.Run(async context =>
{
var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
//context.Response.ContentLength = encoding.GetByteCount(document);
context.Response.ContentType = "text/html;charset=UTF-8";
await context.Response.WriteAsync("NotChunked", encoding, context.RequestAborted);
await context.Response.Body.FlushAsync(); // Bypass IIS write-behind buffering
});
});
app.Map("/chunked", subApp =>
{
subApp.Run(async context =>
{
await context.Response.WriteAsync("Chunked");
await context.Response.Body.FlushAsync(); // Bypass IIS write-behind buffering
});
});
app.Map("/manuallychunked", subApp =>
{
subApp.Run(context =>
{
context.Response.Headers[HeaderNames.TransferEncoding] = "chunked";
return context.Response.WriteAsync("10\r\nManually Chunked\r\n0\r\n\r\n");
});
});
app.Map("/manuallychunkedandclose", subApp =>
{
subApp.Run(context =>
{
context.Response.Headers[HeaderNames.Connection] = "close";
context.Response.Headers[HeaderNames.TransferEncoding] = "chunked";
return context.Response.WriteAsync("1A\r\nManually Chunked and Close\r\n0\r\n\r\n");
});
});
app.Map("/ImpersonateMiddleware", subApp =>
{
subApp.UseMiddleware<ImpersonateMiddleware>();
subApp.Run(context =>
{
return context.Response.WriteAsync("");
});
});
app.Run(context =>
{
string response = "Running";
string[] paths = context.Request.Path.Value.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in paths)
{
string action = string.Empty;
string parameter = string.Empty;
action = "DoSleep";
if (item.StartsWith(action))
{
/*
Process "DoSleep" command here.
For example, if path contains "DoSleep" such as /DoSleep1000, run Thread.Sleep(1000)
*/
int sleepTime = 1000;
if (item.Length > action.Length)
{
parameter = item.Substring(action.Length);
sleepTime = Convert.ToInt32(parameter);
}
Thread.Sleep(sleepTime);
}
action = "MemoryLeak";
if (item.StartsWith(action))
{
parameter = "1024";
if (item.Length > action.Length)
{
parameter = item.Substring(action.Length);
}
long size = Convert.ToInt32(parameter);
var rnd = new Random();
byte[] b = new byte[size*1024];
b[rnd.Next(0, b.Length)] = byte.MaxValue;
MemoryLeakList.Add(b);
response = "MemoryLeak, size:" + size.ToString() + " KB, total: " + MemoryLeakList.Count.ToString();
}
action = "ExpandEnvironmentVariables";
if (item.StartsWith(action))
{
if (item.Length > action.Length)
{
parameter = item.Substring(action.Length);
response = Environment.ExpandEnvironmentVariables("%" + parameter + "%");
}
}
action = "GetEnvironmentVariables";
if (item.StartsWith(action))
{
parameter = item.Substring(action.Length);
response = Environment.GetEnvironmentVariables().Count.ToString();
}
action = "DumpEnvironmentVariables";
if (item.StartsWith(action))
{
response = String.Empty;
foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
{
response += de.Key + ":" + de.Value + "<br/>";
}
}
action = "GetRequestHeaderValue";
if (item.StartsWith(action))
{
if (item.Length > action.Length)
{
parameter = item.Substring(action.Length);
if (context.Request.Headers.ContainsKey(parameter))
{
response = context.Request.Headers[parameter];
}
else
{
response = "";
}
}
}
action = "DumpRequestHeaders";
if (item.StartsWith(action))
{
response = String.Empty;
foreach (var de in context.Request.Headers)
{
response += de.Key + ":" + de.Value + "<br/>";
}
}
}
return context.Response.WriteAsync(response);
});
}
}
}

View File

@ -0,0 +1,61 @@
// 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 Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using System;
namespace AspnetCoreModule.TestSites.Standard
{
public class StartupCompressionCaching
{
public static bool CompressionMode = true;
public void ConfigureServices(IServiceCollection services)
{
if (CompressionMode)
{
services.AddResponseCompression();
}
services.AddResponseCaching();
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
if (CompressionMode)
{
app.UseResponseCompression();
}
app.UseResponseCaching();
app.UseDefaultFiles();
app.UseStaticFiles(
new StaticFileOptions()
{
OnPrepareResponse = context =>
{
//
// FYI, below line can be simplified with
// context.Context.Response.Headers[HeaderNames.CacheControl] = "public,max-age=10";
//
context.Context.Response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue()
{
Public = true,
MaxAge = TimeSpan.FromSeconds(10)
};
context.Context.Response.Headers.Append("MyCustomHeader", DateTime.Now.Second.ToString());
var accept = context.Context.Request.Headers[HeaderNames.AcceptEncoding];
if (!StringValues.IsNullOrEmpty(accept))
{
context.Context.Response.Headers.Append(HeaderNames.Vary, HeaderNames.AcceptEncoding);
}
context.Context.Response.ContentType = "text/plain";
}
}
);
}
}
}

View File

@ -0,0 +1,22 @@
// 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 Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace AspnetCoreModule.TestSites.Standard
{
public class StartupHelloWorld
{
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(minLevel: LogLevel.Warning);
app.Run(ctx =>
{
return ctx.Response.WriteAsync("Hello World");
});
}
}
}

View File

@ -0,0 +1,92 @@
// 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.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace AspnetCoreModule.TestSites.Standard
{
public class StartupNtlmAuthentication
{
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(minLevel: LogLevel.Warning);
app.Use(async (context, next) =>
{
try
{
await next();
}
catch (Exception ex)
{
if (context.Response.HasStarted)
{
throw;
}
context.Response.Clear();
context.Response.StatusCode = 500;
await context.Response.WriteAsync(ex.ToString());
}
});
app.Use((context, next) =>
{
if (context.Request.Path.Equals("/Anonymous"))
{
return context.Response.WriteAsync("Anonymous?" + !context.User.Identity.IsAuthenticated);
}
if (context.Request.Path.Equals("/Restricted"))
{
if (context.User.Identity.IsAuthenticated)
{
return context.Response.WriteAsync(context.User.Identity.AuthenticationType);
}
else
{
return context.Authentication.ChallengeAsync();
}
}
if (context.Request.Path.Equals("/Forbidden"))
{
return context.Authentication.ForbidAsync(Microsoft.AspNetCore.Http.Authentication.AuthenticationManager.AutomaticScheme);
}
if (context.Request.Path.Equals("/AutoForbid"))
{
return context.Authentication.ChallengeAsync();
}
if (context.Request.Path.Equals("/RestrictedNegotiate"))
{
if (string.Equals("Negotiate", context.User.Identity.AuthenticationType, System.StringComparison.Ordinal))
{
return context.Response.WriteAsync("Negotiate");
}
else
{
return context.Authentication.ChallengeAsync("Negotiate");
}
}
if (context.Request.Path.Equals("/RestrictedNTLM"))
{
if (string.Equals("NTLM", context.User.Identity.AuthenticationType, System.StringComparison.Ordinal))
{
return context.Response.WriteAsync("NTLM");
}
else
{
return context.Authentication.ChallengeAsync("NTLM");
}
}
return context.Response.WriteAsync("Running NTLM");
});
}
}
}

View File

@ -0,0 +1,46 @@
{
"dependencies": {
"Microsoft.AspNetCore.WebSockets.Server": "0.1.0-rc2-final",
"Microsoft.AspNetCore.Diagnostics": "1.0.1-*",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.1-*",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1-*",
"Microsoft.AspNetCore.Server.WebListener": "1.0.1-*",
"Microsoft.AspNetCore.Server.Kestrel.Https": "1.0.1-*",
"Microsoft.AspNetCore.ResponseCompression": "*",
"Microsoft.AspNetCore.ResponseCaching": "*",
"Microsoft.AspNetCore.StaticFiles": "*",
"Microsoft.Extensions.Configuration.CommandLine": "1.0.1-*",
"Microsoft.Extensions.Logging.Console": "1.0.1-*"
},
"buildOptions": {
"emitEntryPoint": true,
"copyToOutput": [
]
},
"publishOptions": {
"include": [
"web.config"
]
},
"frameworks": {
"netcoreapp1.1": {
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1-*",
"type": "platform"
}
}
}
},
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"scripts": {
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true" />
</system.webServer>
</configuration>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\NotExisting.exe" arguments=".\NotExisting.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true" disableStartUpErrorPage="false" />
</system.webServer>
</configuration>

View File

@ -0,0 +1,25 @@
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>URL Rewrite Module Test</title>
</head>
<body>
<h1>URL Rewrite Module Test Page</h1>
<table>
<tr>
<th>Server Variable</th>
<th>Value</th>
</tr>
<tr>
<td>Original URL: </td>
<td><%= Request.ServerVariables["HTTP_X_ORIGINAL_URL"] %></td>
</tr>
<tr>
<td>Final URL: </td>
<td><%= Request.ServerVariables["SCRIPT_NAME"] + "?" + Request.ServerVariables["QUERY_STRING"] %></td>
</tr>
</table>
</body>
</html>

View File

@ -0,0 +1,11 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>IIS Windows</title>
</style>
</head>
<body>
URLRewrite
</body>
</html>

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Rewrite to foo">
<match url="^rewrite/([_.0-9a-z-]+)" />
<action type="Rewrite" url="/{R:1}" />
</rule>
<rule name="Rewrite to foo-bar">
<match url="^rewrite2/([_0-9a-z-]+)/([_.0-9a-z-]+)" />
<action type="Rewrite" url="/{R:1}/{R:2}" />
</rule>
<rule name="Rewrite to EchoHandler.ashx">
<match url="^rewrite3/([_0-9a-z-]+)/([_.0-9a-z-]+)" />
<action type="Rewrite" url="/wsclient/EchoHandler.ashx" />
</rule>
<rule name="Rewrite to article.aspx">
<match url="^rewrite4/([_0-9a-z-]+)/([_.0-9a-z-]+)" />
<action type="Rewrite" url="/URLRewrite/article.aspx?id={R:1}&amp;title={R:2}" />
</rule>
<rule name="RemoveAppName" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<action type="Rewrite" url="/{R:0}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Rewrite to foo">
<match url="^rewrite/([_.0-9a-z-]+)" />
<action type="Rewrite" url="/{R:1}" />
</rule>
<rule name="Rewrite to foo-bar">
<match url="^rewrite2/([_0-9a-z-]+)/([_.0-9a-z-]+)" />
<action type="Rewrite" url="/{R:1}/{R:2}" />
</rule>
<rule name="Rewrite to EchoHandler.ashx">
<match url="^rewrite3/([_0-9a-z-]+)/([_.0-9a-z-]+)" />
<action type="Rewrite" url="/wsclient/EchoHandler.ashx" />
</rule>
<rule name="Rewrite to article.aspx">
<match url="^rewrite4/([_0-9a-z-]+)/([_.0-9a-z-]+)" />
<action type="Rewrite" url="/URLRewrite/article.aspx?id={R:1}&amp;title={R:2}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

Binary file not shown.

After

Width:  |  Height:  |  Size: 283 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

View File

@ -0,0 +1,32 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>IIS Windows</title>
<style type="text/css">
<!--
body {
color:#000000;
background-color:#0072C6;
margin:0;
}
#container {
margin-left:auto;
margin-right:auto;
text-align:center;
}
a img {
border:none;
}
-->
</style>
</head>
<body>
<div id="container">
<a href="http://go.microsoft.com/fwlink/?linkid=66138&amp;clcid=0x409"><img src="iis.png" alt="IIS" width="960" height="600" /></a>
</div>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1 @@
small

View File

@ -0,0 +1,13 @@
<html>
<body>
<%
if request.form("cars") = "volvo" then
Response.write ("Hello " & Request.form("title") & " " & Request.form("FirstName") & " " & Request.form("LastName"))
Response.write ("<br>How are you today?")
Response.Write("<br>you have a " & Request.form("cars"))
Response.write("<br>comment " & Request.form("textarea"))
end if
%>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<aspNetCore shutdownTimeLimit="1" rapidFailsPerMinute="100" requestTimeout="00:01:00" />
</system.webServer>
</configuration>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<aspNetCore shutdownTimeLimit="1" rapidFailsPerMinute="100" requestTimeout="00:01:00" />
</system.webServer>
</configuration>

View File

@ -0,0 +1,70 @@
<%@ WebHandler Language="C#" Class="ChatStartHandler" %>
using System;
using System.Web;
using System.Net.WebSockets;
using System.Web.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Collections.Generic;
using System.Collections.Concurrent;
public class ChatStartHandler : IHttpHandler
{
static int clientCount=0;
public void ProcessRequest(HttpContext context)
{
context.AcceptWebSocketRequest(async wsContext =>
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
WebSocket socket = wsContext.WebSocket;
ChatList.ActiveChatSessions.TryAdd(clientCount++, socket);
// set up the loop
while (true)
{
Thread.Sleep(100);
var input = await socket.ReceiveAsync(buffer, CancellationToken.None);
if (input.CloseStatus != null)
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
break;
}
else
{
foreach (KeyValuePair<int, WebSocket> kvp in ChatList.ActiveChatSessions)
{
WebSocket ws = kvp.Value;
if (ws.State == WebSocketState.Open)
{
var outputBuffer = new ArraySegment<byte>(buffer.Array, 0, input.Count);
await ws.SendAsync(outputBuffer, input.MessageType, input.EndOfMessage, CancellationToken.None);
}
}
}
}
});
//}, new System.Web.WebSockets.AspNetWebSocketOptions { Subprotocol = "ECHO" });
}
public bool IsReusable
{
get
{
return false;
}
}
}
public static class ChatList
{
public static ConcurrentDictionary<int, WebSocket> ActiveChatSessions = new ConcurrentDictionary<int, WebSocket>();
}

View File

@ -0,0 +1,50 @@
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Net.WebSockets;
using System.Web.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.AcceptWebSocketRequest(async wsContext =>
{
//ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024*1024]);
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
WebSocket socket = wsContext.WebSocket;
// set up the loop
while (true)
{
var input = await socket.ReceiveAsync(buffer, CancellationToken.None);
//Thread.Sleep(100);
if (input.CloseStatus != null)
{
await socket.CloseAsync(input.CloseStatus.Value, input.CloseStatusDescription, CancellationToken.None);
break;
}
else
{
var outputBuffer = new ArraySegment<byte>(buffer.Array, 0, input.Count);
await socket.SendAsync(outputBuffer, input.MessageType, input.EndOfMessage, CancellationToken.None);
}
}
});
}
public bool IsReusable
{
get
{
return false;
}
}
}

View File

@ -0,0 +1,69 @@
<%@ WebHandler Language="C#" Class="ChatStartHandler" %>
using System;
using System.Web;
using System.Net.WebSockets;
using System.Web.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Collections.Generic;
using System.Collections.Concurrent;
public class ChatStartHandler : IHttpHandler
{
static int clientCount=0;
public void ProcessRequest(HttpContext context)
{
context.AcceptWebSocketRequest(async wsContext =>
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
WebSocket socket = wsContext.WebSocket;
ChatList.ActiveChatSessions.TryAdd(clientCount++, socket);
// set up the loop
while (true)
{
var input = await socket.ReceiveAsync(buffer, CancellationToken.None);
if (input.CloseStatus != null)
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
break;
}
else
{
foreach (KeyValuePair<int, WebSocket> kvp in ChatList.ActiveChatSessions)
{
WebSocket ws = kvp.Value;
if (ws.State == WebSocketState.Open)
{
var outputBuffer = new ArraySegment<byte>(buffer.Array, 0, input.Count);
await ws.SendAsync(outputBuffer, input.MessageType, input.EndOfMessage, CancellationToken.None);
}
}
}
}
});
//}, new System.Web.WebSockets.AspNetWebSocketOptions { Subprotocol = "ECHO" });
}
public bool IsReusable
{
get
{
return false;
}
}
}
public static class ChatList
{
public static ConcurrentDictionary<int, WebSocket> ActiveChatSessions = new ConcurrentDictionary<int, WebSocket>();
}

View File

@ -0,0 +1,70 @@
<%@ Page Language="C#" AutoEventWireUp="true" %>
<html>
<head>
<h1>#active websocket connection <%= "foo" %></h1>
<h1> Web Socket Echo Demo (run from Minefield!) </h1>
<script type="text/javascript">
var socket;
function initializeWebSocket() {
var host = "wss://ecctest.smartscreen.microsoft.com/Handler.ashx";
try {
socket = new WebSocket(host);
socket.onopen = function(msg){
var s = 'WebSocket Status:: Socket Open';
document.getElementById("serverStatus").innerHTML = s;
};
socket.onmessage = function(msg){
var s = 'Server Reply:: ' + msg.data;
document.getElementById("serverData").innerHTML = s;
};
socket.onclose = function(msg){
var s = 'WebSocket Status:: Socket Closed';
document.getElementById("serverStatus").innerHTML = s;
};
}
catch(ex){ console.log(ex); }
}
function send() {
var e = document.getElementById("msgText");
socket.send(e.value);
}
initializeWebSocket();
</script>
<head>
<body>
<p id="serverStatus"> </p>
This text will be sent on the socket: <input id="msgText" type=text size=30>
<input type=button value="Send" onclick="send()">
<p id="serverData" />
</body>
</html>

View File

@ -0,0 +1,70 @@
<%@ Page Language="C#" AutoEventWireUp="true" %>
<html>
<head>
<h1>#active websocket connection <%= "foo" %></h1>
<h1> Web Socket Echo Demo (run from Minefield!) </h1>
<script type="text/javascript">
var socket;
function initializeWebSocket() {
var host = "ws://<%: Request.Url.Host %>:<%: Request.Url.Port %><%: Response.ApplyAppPathModifier("~/Handler.ashx") %>";
try {
socket = new WebSocket(host);
socket.onopen = function(msg){
var s = 'WebSocket Status:: Socket Open';
document.getElementById("serverStatus").innerHTML = s;
};
socket.onmessage = function(msg){
var s = 'Server Reply:: ' + msg.data;
document.getElementById("serverData").innerHTML = s;
};
socket.onclose = function(msg){
var s = 'WebSocket Status:: Socket Closed';
document.getElementById("serverStatus").innerHTML = s;
};
}
catch(ex){ console.log(ex); }
}
function send() {
var e = document.getElementById("msgText");
socket.send(e.value);
}
initializeWebSocket();
</script>
<head>
<body>
<p id="serverStatus"> </p>
This text will be sent on the socket: <input id="msgText" type=text size=30>
<input type=button value="Send" onclick="send()">
<p id="serverData" />
</body>
</html>

View File

@ -0,0 +1,112 @@
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Net.WebSockets;
using System.Web.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Collections.Generic;
using System.Linq;
public class Handler : IHttpHandler
{
const int BUFFER = 1024*5;
bool StopFalg = false;
public void ProcessRequest(HttpContext context)
{
if (!context.IsWebSocketRequest)
{
HttpRequest Request = context.Request;
HttpResponse Response = context.Response;
Response.Write("Simple Http");
return;
}
context.AcceptWebSocketRequest(async wsContext =>
{
// set up the loop
WebSocket socket = wsContext.WebSocket;
WebSocketMessageType responseType = WebSocketMessageType.Text;
int returnSize = 1024*1024;
Thread.Sleep(500);
Task.Run(() =>
{
Recieve(socket);
});
Thread.Sleep(500);
while (socket.State == WebSocketState.Open)
{
int bytesLeft = returnSize;
var tempString = string.Empty;
while (bytesLeft > BUFFER)
{
tempString = RandomString(BUFFER);
bytesLeft -= BUFFER;
await socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(tempString)), responseType, false, CancellationToken.None);
Thread.Sleep(500);
}
if (bytesLeft <= BUFFER && bytesLeft >= 0)
{
tempString = RandomString(bytesLeft);
await socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(tempString)), responseType, true, CancellationToken.None);
Thread.Sleep(500);
}
if (StopFalg) break;
}
});
}
async Task Recieve(WebSocket webSocket)
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
while (webSocket.State == WebSocketState.Open)
{
WebSocketReceiveResult input = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
if (input.CloseStatus == WebSocketCloseStatus.NormalClosure)
{
StopFalg = true;
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
break;
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
public string RandomString(int size)
{
if (size < 1)
return string.Empty;
Random random = new Random((int)DateTime.Now.Ticks);
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
}

View File

@ -0,0 +1,28 @@
<%@ WebHandler Language="C#" Class="GetWebSocketConnectionCount" %>
using System;
using System.Web;
public class GetWebSocketConnectionCount : IHttpHandler {
public void ProcessRequest (HttpContext context) {
System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(@"System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
object mc = assembly.CreateInstance("System.Web.WebSockets.AspNetWebSocketManager");
Type t = mc.GetType();
System.Reflection.BindingFlags bf =System.Reflection.BindingFlags.Static| System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public;
//MethodInfo mi = t.GetProperty
object temp1 = t.GetField("Current", bf).GetValue(null);
object temp2 = t.GetField("_activeSockets", bf).GetValue(temp1);
context.Response.ContentType = "text/plain";
context.Response.Write("Active WebSocket Connections="+((System.Collections.Generic.HashSet<System.Net.WebSockets.WebSocket>)temp2).Count);
}
public bool IsReusable {
get {
return false;
}
}
}

View File

@ -0,0 +1,166 @@
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Net.WebSockets;
using System.Web.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Collections.Generic;
using System.Linq;
public class Handler : IHttpHandler
{
const int BUFFER = 1000 * 1000;
public void ProcessRequest(HttpContext context)
{
if (!context.IsWebSocketRequest)
{
HttpRequest Request = context.Request;
HttpResponse Response = context.Response;
Response.Write("Simple Http");
return;
}
context.AcceptWebSocketRequest(async wsContext =>
{
// set up the loop
WebSocket socket = wsContext.WebSocket;
////determine return type
List<string> query = wsContext.SecWebSocketProtocols.ToList();
WebSocketMessageType responseType = WebSocketMessageType.Text;
if (query[0].Split('-')[0] == WebSocketMessageType.Binary.ToString())
{
responseType = WebSocketMessageType.Binary;
}
WebSocketMessageType requestType = WebSocketMessageType.Text;
if (query[0].Split('-')[1] == WebSocketMessageType.Binary.ToString())
{
requestType = WebSocketMessageType.Binary;
}
int returnSize = Int32.Parse(query[0].Split('-')[2]);
int requestSize = Int32.Parse(query[0].Split('-')[3]);
bool canSend = Boolean.Parse(query[0].Split('-')[4]);
bool canReceive = Boolean.Parse(query[0].Split('-')[5]);
if (canSend && !canReceive)
{
await Send(socket, responseType, returnSize);
}
else if (canReceive && !canSend)
{
await Recieve(socket, requestType);
}
else if (canReceive && canSend)
{
Task.Run(() =>
{
Recieve(socket, requestType);
});
while (socket.State == WebSocketState.Open)
{
int bytesLeft = returnSize;
var tempString = string.Empty;
while (bytesLeft > BUFFER)
{
tempString = RandomString(BUFFER);
bytesLeft -= BUFFER;
await socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(tempString)), responseType, false, CancellationToken.None);
Thread.Sleep(200);
}
if (bytesLeft <= BUFFER && bytesLeft >= 0)
{
tempString = RandomString(bytesLeft);
await socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(tempString)), responseType, true, CancellationToken.None);
Thread.Sleep(500);
}
}
}
else
{
Task.Run(() =>
{
Recieve(socket, requestType);
});
}
});
}
async Task Recieve(WebSocket webSocket, WebSocketMessageType messageType)
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
while (webSocket.State == WebSocketState.Open)
{
WebSocketReceiveResult input = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
if (input.CloseStatus == WebSocketCloseStatus.NormalClosure)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
break;
}
}
}
async Task Send(WebSocket socket, WebSocketMessageType responseType, int returnSize)
{
while (socket.State == WebSocketState.Open)
{
int bytesLeft = returnSize;
while (bytesLeft > BUFFER)
{
bytesLeft -= BUFFER;
await socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(RandomString(BUFFER))), responseType, false, CancellationToken.None);
Thread.Sleep(200);
}
if (bytesLeft <= BUFFER && bytesLeft >= 0)
{
await socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(RandomString(bytesLeft))), responseType, true, CancellationToken.None);
Thread.Sleep(500);
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
public string RandomString(int size)
{
if (size < 1)
return string.Empty;
Random random = new Random((int)DateTime.Now.Ticks);
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
}

View File

@ -0,0 +1,49 @@
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Net.WebSockets;
using System.Web.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.AcceptWebSocketRequest(async wsContext =>
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024*1024]);
WebSocket socket = wsContext.WebSocket;
// set up the loop
while (true)
{
var input = await socket.ReceiveAsync(buffer, CancellationToken.None);
Thread.Sleep(100);
if (input.CloseStatus != null)
{
await socket.CloseAsync(input.CloseStatus.Value, input.CloseStatusDescription, CancellationToken.None);
break;
}
else
{
var outputBuffer = new ArraySegment<byte>(buffer.Array, 0, input.Count);
await socket.SendAsync(outputBuffer, input.MessageType, input.EndOfMessage, CancellationToken.None);
}
}
});
}
public bool IsReusable
{
get
{
return false;
}
}
}

View File

@ -0,0 +1,49 @@
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Net.WebSockets;
using System.Web.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Collections.Generic;
using System.Linq;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.AcceptWebSocketRequest(async wsContext =>
{
// set up the loop
WebSocket socket = wsContext.WebSocket;
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
while (socket.State == WebSocketState.Open)
{
WebSocketReceiveResult input = await socket.ReceiveAsync(buffer, CancellationToken.None);
if (input.CloseStatus == WebSocketCloseStatus.NormalClosure)
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
break;
}
}
});
}
public bool IsReusable
{
get
{
return false;
}
}
}

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
</configuration>

View File

@ -0,0 +1,62 @@
<%@ Page Language="C#" AutoEventWireUp="true" %>
<html>
<head>
<h1>#active websocket connection <%= "foo" %></h1>
<h1> Web Socket Echo Demo (run from Minefield!) </h1>
<script type="text/javascript">
var socket;
var receive_counter = 0;
function initializeWebSocket() {
var host = "ws://localhost:8080/wsclient/ChatHandler.ashx";
try {
socket = new WebSocket(host, "test");
socket.onopen = function(msg){
var s = 'WebSocket Status:: Socket Open';
document.getElementById("serverStatus").innerHTML = s;
};
socket.onmessage = function(msg){
receive_counter++;
var s = 'Server Reply:: ' + receive_counter + ' : ' + msg.data.length + ' : ' + msg.data;
document.getElementById("serverData").innerHTML = s;
};
socket.onclose = function(msg){
var s = 'WebSocket Status:: Socket Closed';
document.getElementById("serverStatus").innerHTML = s;
};
}
catch(ex)
{
console.log(ex);
}
}
function send() {
var e = document.getElementById("msgText");
//var i = 0;
//while (true)
//{
// i++;
//if (i > 100) break;
socket.send(e.value);
//}
}
initializeWebSocket();
</script>
<head>
<body>
<p id="serverStatus"> </p>
This text will be sent on the socket: <input id="msgText" type=text size=30>
<input type=button value="Send" onclick="send()">
<p id="serverData" />
</body>
</html>

View File

@ -0,0 +1,65 @@
<%@ Page Language="C#" AutoEventWireUp="true" %>
<html>
<head>
<h1>#active websocket connection <%= "foo" %></h1>
<h1> Web Socket Echo Demo (run from Minefield!) </h1>
<script type="text/javascript">
var socket;
var receive_counter = 0;
function initializeWebSocket() {
var host = "ws://localhost:1234/StandardTestApp/websocket";
//var host = "ws://localhost:1234/webSocket/EchoHandler.ashx";
//var host = "ws://localhost:1234/URLRewrite/rewrite/wsclient/EchoHandler.ashx";
//var host = "ws://localhost:1234/websocketecho/test";
//var host = "ws://localhost:1234/URLRewrite/rewrite/websocketecho/test";
try {
socket = new WebSocket(host, "");
socket.onopen = function(msg){
var s = 'WebSocket Status:: Socket Open';
document.getElementById("serverStatus").innerHTML = s;
};
socket.onmessage = function(msg){
receive_counter++;
var s = 'Server Reply:: ' + receive_counter + ' : ' + msg.data.length + ' : ' + msg.data;
document.getElementById("serverData").innerHTML = s;
};
socket.onclose = function(msg){
var s = 'WebSocket Status:: Socket Closed';
document.getElementById("serverStatus").innerHTML = s;
};
}
catch(ex)
{
console.log(ex);
}
}
function send() {
var e = document.getElementById("msgText");
//var i = 0;
//while (true)
//{
// i++;
//if (i > 100) break;
socket.send(e.value);
//}
}
initializeWebSocket();
</script>
<head>
<body>
<p id="serverStatus"> </p>
This text will be sent on the socket: <input id="msgText" type=text size=30>
<input type=button value="Send" onclick="send()">
<p id="serverData" />
</body>
</html>

View File

@ -0,0 +1,62 @@
<%@ Page Language="C#" AutoEventWireUp="true" %>
<html>
<head>
<h1>#active websocket connection <%= "foo" %></h1>
<h1> Web Socket Echo Demo (run from Minefield!) </h1>
<script type="text/javascript">
var socket;
var receive_counter = 0;
function initializeWebSocket() {
var host = "ws://localhost:8080/websocketecho";
try {
socket = new WebSocket(host, "mywebsocketsubprotocol");
socket.onopen = function(msg){
var s = 'WebSocket Status:: Socket Open';
document.getElementById("serverStatus").innerHTML = s;
};
socket.onmessage = function(msg){
receive_counter++;
var s = 'Server Reply:: ' + receive_counter + ' : ' + msg.data.length + ' : ' + msg.data;
document.getElementById("serverData").innerHTML = s;
};
socket.onclose = function(msg){
var s = 'WebSocket Status:: Socket Closed';
document.getElementById("serverStatus").innerHTML = s;
};
}
catch(ex)
{
console.log(ex);
}
}
function send() {
var e = document.getElementById("msgText");
//var i = 0;
//while (true)
//{
// i++;
//if (i > 100) break;
socket.send(e.value);
//}
}
initializeWebSocket();
</script>
<head>
<body>
<p id="serverStatus"> </p>
This text will be sent on the socket: <input id="msgText" type=text size=30>
<input type=button value="Send" onclick="send()">
<p id="serverData" />
</body>
</html>

View File

@ -0,0 +1,65 @@
<%@ Page Language="C#" AutoEventWireUp="true" %>
<html>
<head>
<h1>#active websocket connection <%= "foo" %></h1>
<h1> Web Socket Echo Demo (run from Minefield!) </h1>
<script type="text/javascript">
var socket;
var receive_counter = 0;
function initializeWebSocket() {
var host = "ws://localhost:1234/StandardTestApp/websocketSubProtocol";
//var host = "ws://localhost:1234/webSocket/EchoHandler.ashx";
//var host = "ws://localhost:1234/URLRewrite/rewrite/wsclient/EchoHandler.ashx";
//var host = "ws://localhost:1234/websocketecho/test";
//var host = "ws://localhost:1234/URLRewrite/rewrite/websocketecho/test";
try {
socket = new WebSocket(host, "mywebsocketsubprotocol");
socket.onopen = function(msg){
var s = 'WebSocket Status:: Socket Open:: ' + socket.protocol;
document.getElementById("serverStatus").innerHTML = s;
};
socket.onmessage = function(msg){
receive_counter++;
var s = 'Server Reply:: ' + receive_counter + ' : ' + msg.data.length + ' : ' + msg.data;
document.getElementById("serverData").innerHTML = s;
};
socket.onclose = function(msg){
var s = 'WebSocket Status:: Socket Closed';
document.getElementById("serverStatus").innerHTML = s;
};
}
catch(ex)
{
console.log(ex);
}
}
function send() {
var e = document.getElementById("msgText");
//var i = 0;
//while (true)
//{
// i++;
//if (i > 100) break;
socket.send(e.value);
//}
}
initializeWebSocket();
</script>
<head>
<body>
<p id="serverStatus"> </p>
This text will be sent on the socket: <input id="msgText" type=text size=30>
<input type=button value="Send" onclick="send()">
<p id="serverData" />
</body>
</html>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
</configuration>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
</configuration>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
-->
<appSettings>
<add key="foo" value="bar" />
<add key="foo2" value="bar2" />
</appSettings>
<system.webServer>
<aspNetCore disableStartUpErrorPage="false" />
</system.webServer>
</configuration>
<!--ProjectGuid: 9755f612-a155-4bdd-9e20-37ade0b4b3ba-->