diff --git a/IISIntegration.sln b/IISIntegration.sln index af31823288..9fea4e8327 100644 --- a/IISIntegration.sln +++ b/IISIntegration.sln @@ -18,7 +18,6 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{EF30B533-D715-421A-92B7-92FEF460AC9C}" ProjectSection(SolutionItems) = preProject test\Directory.Build.props = test\Directory.Build.props - test\WebSocketClientEXE\WebSocketClientEXE.csproj = test\WebSocketClientEXE\WebSocketClientEXE.csproj EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{C74B8F36-FD2F-45C9-9B8A-00E7CF0126A9}" @@ -54,10 +53,6 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CommonLib", "src\CommonLib\ EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RequestHandler", "src\RequestHandler\RequestHandler.vcxproj", "{D57EA297-6DC2-4BC0-8C91-334863327863}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNetCoreModule.Test", "test\AspNetCoreModule.Test\AspNetCoreModule.Test.csproj", "{5F31656B-4990-44FE-9090-00E32D933376}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNetCoreModule.TestSites.Standard", "test\AspNetCoreModule.TestSites.Standard\AspNetCoreModule.TestSites.Standard.csproj", "{93ECA06C-767E-4A4D-AC59-21F250381297}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -203,30 +198,6 @@ Global {D57EA297-6DC2-4BC0-8C91-334863327863}.Release|x64.Build.0 = Release|x64 {D57EA297-6DC2-4BC0-8C91-334863327863}.Release|x86.ActiveCfg = Release|Win32 {D57EA297-6DC2-4BC0-8C91-334863327863}.Release|x86.Build.0 = Release|Win32 - {5F31656B-4990-44FE-9090-00E32D933376}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5F31656B-4990-44FE-9090-00E32D933376}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5F31656B-4990-44FE-9090-00E32D933376}.Debug|x64.ActiveCfg = Debug|Any CPU - {5F31656B-4990-44FE-9090-00E32D933376}.Debug|x64.Build.0 = Debug|Any CPU - {5F31656B-4990-44FE-9090-00E32D933376}.Debug|x86.ActiveCfg = Debug|Any CPU - {5F31656B-4990-44FE-9090-00E32D933376}.Debug|x86.Build.0 = Debug|Any CPU - {5F31656B-4990-44FE-9090-00E32D933376}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5F31656B-4990-44FE-9090-00E32D933376}.Release|Any CPU.Build.0 = Release|Any CPU - {5F31656B-4990-44FE-9090-00E32D933376}.Release|x64.ActiveCfg = Release|Any CPU - {5F31656B-4990-44FE-9090-00E32D933376}.Release|x64.Build.0 = Release|Any CPU - {5F31656B-4990-44FE-9090-00E32D933376}.Release|x86.ActiveCfg = Release|Any CPU - {5F31656B-4990-44FE-9090-00E32D933376}.Release|x86.Build.0 = Release|Any CPU - {93ECA06C-767E-4A4D-AC59-21F250381297}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {93ECA06C-767E-4A4D-AC59-21F250381297}.Debug|Any CPU.Build.0 = Debug|Any CPU - {93ECA06C-767E-4A4D-AC59-21F250381297}.Debug|x64.ActiveCfg = Debug|Any CPU - {93ECA06C-767E-4A4D-AC59-21F250381297}.Debug|x64.Build.0 = Debug|Any CPU - {93ECA06C-767E-4A4D-AC59-21F250381297}.Debug|x86.ActiveCfg = Debug|Any CPU - {93ECA06C-767E-4A4D-AC59-21F250381297}.Debug|x86.Build.0 = Debug|Any CPU - {93ECA06C-767E-4A4D-AC59-21F250381297}.Release|Any CPU.ActiveCfg = Release|Any CPU - {93ECA06C-767E-4A4D-AC59-21F250381297}.Release|Any CPU.Build.0 = Release|Any CPU - {93ECA06C-767E-4A4D-AC59-21F250381297}.Release|x64.ActiveCfg = Release|Any CPU - {93ECA06C-767E-4A4D-AC59-21F250381297}.Release|x64.Build.0 = Release|Any CPU - {93ECA06C-767E-4A4D-AC59-21F250381297}.Release|x86.ActiveCfg = Release|Any CPU - {93ECA06C-767E-4A4D-AC59-21F250381297}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -244,8 +215,6 @@ Global {4787A64F-9A3E-4867-A55A-70CB4B2B2FFE} = {04B1EDB6-E967-4D25-89B9-E6F8304038CD} {55494E58-E061-4C4C-A0A8-837008E72F85} = {04B1EDB6-E967-4D25-89B9-E6F8304038CD} {D57EA297-6DC2-4BC0-8C91-334863327863} = {04B1EDB6-E967-4D25-89B9-E6F8304038CD} - {5F31656B-4990-44FE-9090-00E32D933376} = {EF30B533-D715-421A-92B7-92FEF460AC9C} - {93ECA06C-767E-4A4D-AC59-21F250381297} = {EF30B533-D715-421A-92B7-92FEF460AC9C} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {DB4F868D-E1AE-4FD7-9333-69FA15B268C5} diff --git a/test/AspNetCoreModule.Test/AspNetCoreModule.Test.csproj b/test/AspNetCoreModule.Test/AspNetCoreModule.Test.csproj deleted file mode 100644 index 882330ad6f..0000000000 --- a/test/AspNetCoreModule.Test/AspNetCoreModule.Test.csproj +++ /dev/null @@ -1,55 +0,0 @@ - - - net461 - true - true - AspNetCoreModule.Test - - - - - - - - - PreserveNewest - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/AspNetCoreModule.Test/Framework/IISConfigUtility.cs b/test/AspNetCoreModule.Test/Framework/IISConfigUtility.cs deleted file mode 100644 index 2286c63b4d..0000000000 --- a/test/AspNetCoreModule.Test/Framework/IISConfigUtility.cs +++ /dev/null @@ -1,1385 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using AspNetCoreModule.Test.HttpClientHelper; -using Microsoft.Web.Administration; -using System; -using System.IO; -using System.ServiceProcess; -using System.Threading; - -namespace AspNetCoreModule.Test.Framework -{ - public class IISConfigUtility : IDisposable - { - public class Strings - { - public static string AppHostConfigPath = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "system32", "inetsrv", "config", "applicationHost.config"); - public static string IIS64BitPath = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "system32", "inetsrv"); - public static string IIS32BitPath = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "syswow64", "inetsrv"); - public static string IISExpress64BitPath = Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles%"), "IIS Express"); - public static string IISExpress32BitPath = Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%"), "IIS Express"); - public static string DefaultAppPool = "DefaultAppPool"; - } - - public static string ApppHostTemporaryBackupFileExtention = null; - private ServerType _serverType = ServerType.IIS; - private string _iisExpressConfigPath = null; - - public enum AppPoolBitness - { - enable32Bit, - noChange - } - - public void Dispose() - { - } - - public ServerManager GetServerManager() - { - if (_serverType == ServerType.IISExpress) - { - return new ServerManager( - false, // readOnly - _iisExpressConfigPath // applicationhost.config path for IISExpress - ); - } - else - { - return new ServerManager( - false, // readOnly - Strings.AppHostConfigPath // applicationhost.config path for IIS - ); - } - } - - public IISConfigUtility(ServerType type, string iisExpressConfigPath) - { - _serverType = type; - _iisExpressConfigPath = iisExpressConfigPath; - } - - public static bool BackupAppHostConfig(string fileExtenstion, bool overWriteMode) - { - bool result = true; - string fromfile = Strings.AppHostConfigPath; - string tofile = Strings.AppHostConfigPath + fileExtenstion; - if (File.Exists(fromfile)) - { - try - { - TestUtility.FileCopy(fromfile, tofile, overWrite: overWriteMode); - } - catch - { - result = false; - } - } - return result; - } - - public static void RestoreAppHostConfig(string fileExtenstion, bool overWriteMode) - { - string tofile = Strings.AppHostConfigPath; - string fromfile = Strings.AppHostConfigPath + fileExtenstion; - if (File.Exists(fromfile)) - { - try - { - TestUtility.FileCopy(fromfile, tofile, overWrite:overWriteMode); - } - catch - { - TestUtility.LogInformation("Failed to Restore applicationhost.config"); - throw; - } - } - } - - public static void RestoreAppHostConfig(bool restoreFromMasterBackupFile = true) - { - string masterBackupFileExtension = ".ancmtest.masterbackup"; - string masterBackupFilePath = Strings.AppHostConfigPath + masterBackupFileExtension; - string temporaryBackupFileExtenstion = null; - string temporaryBackupFilePath = null; - string tofile = Strings.AppHostConfigPath; - - string backupFileExentsionForDebug = ".ancmtest.debug"; - string backupFilePathForDebug = Strings.AppHostConfigPath + backupFileExentsionForDebug; - TestUtility.DeleteFile(backupFilePathForDebug); - - // Create a master backup file - if (restoreFromMasterBackupFile) - { - // Create a master backup file if it does not exist - if (!File.Exists(masterBackupFilePath)) - { - if (!File.Exists(tofile)) - { - throw new ApplicationException("Can't find " + tofile); - } - BackupAppHostConfig(masterBackupFileExtension, overWriteMode: false); - } - - if (!File.Exists(masterBackupFilePath)) - { - throw new ApplicationException("Not found master backup file " + masterBackupFilePath); - } - } - - // if applicationhost.config does not exist but master backup file is available, create a new applicationhost.config from the master backup file first - if (!File.Exists(tofile)) - { - CopyAppHostConfig(masterBackupFilePath, tofile); - } - - // Create a temporary backup file with the current applicationhost.config to rollback after test is completed. - if (ApppHostTemporaryBackupFileExtention == null) - { - // retry 10 times until it really creates the temporary backup file - for (int i = 0; i < 10; i++) - { - temporaryBackupFileExtenstion = "." + TestUtility.RandomString(5); - string tempFile = Strings.AppHostConfigPath + temporaryBackupFileExtenstion; - if (File.Exists(tempFile)) - { - // file already exists, try with a different file name - continue; - } - - bool backupSuccess = BackupAppHostConfig(temporaryBackupFileExtenstion, overWriteMode: false); - if (backupSuccess && File.Exists(tempFile)) - { - if (File.Exists(tempFile)) - { - ApppHostTemporaryBackupFileExtention = temporaryBackupFileExtenstion; - break; - } - } - } - - if (ApppHostTemporaryBackupFileExtention == null) - { - throw new ApplicationException("Can't make a temporary backup file"); - } - } - - if (restoreFromMasterBackupFile) - { - // restoring applicationhost.config from the master backup file - CopyAppHostConfig(masterBackupFilePath, tofile); - } - else - { - // Create a temporary backup file to preserve the last state for debugging purpose before rolling back from the temporary backup file - try - { - BackupAppHostConfig(backupFileExentsionForDebug, overWriteMode: true); - } - catch - { - TestUtility.LogInformation("Failed to create a backup file for debugging"); - } - - // restoring applicationhost.config from the temporary backup file - temporaryBackupFilePath = Strings.AppHostConfigPath + ApppHostTemporaryBackupFileExtention; - CopyAppHostConfig(temporaryBackupFilePath, tofile); - - // delete the temporary backup file because it is not used anymore - try - { - TestUtility.DeleteFile(temporaryBackupFilePath); - } - catch - { - TestUtility.LogInformation("Failed to cleanup temporary backup file : " + temporaryBackupFilePath); - } - } - } - - private static void CopyAppHostConfig(string fromfile, string tofile) - { - if (!File.Exists(fromfile) && !File.Exists(tofile)) - { - // IIS is not installed, don't do anything here - return; - } - - if (!File.Exists(fromfile)) - { - throw new ApplicationException("Failed to backup " + tofile); - } - - // try restoring applicationhost.config again after the ininial clean up for better reliability - try - { - TestUtility.FileCopy(fromfile, tofile, true, true); - } - catch - { - // ignore - } - - // try again - if (!File.Exists(tofile) || File.ReadAllBytes(fromfile).Length != File.ReadAllBytes(tofile).Length) - { - // try again - TestUtility.ResetHelper(ResetHelperMode.KillWorkerProcess); - TestUtility.FileCopy(fromfile, tofile, true, true); - } - - // verify restoration is done successfully - if (File.ReadAllBytes(fromfile).Length != File.ReadAllBytes(tofile).Length) - { - throw new ApplicationException("Failed to restore applicationhost.config from " + fromfile + " to " + tofile); - } - } - - public void SetAppPoolSetting(string appPoolName, string attribute, object value) - { - TestUtility.LogInformation("Setting Apppool : " + appPoolName + "::" + attribute.ToString() + " <== " + value.ToString()); - using (ServerManager serverManager = GetServerManager()) - { - Configuration config = serverManager.GetApplicationHostConfiguration(); - ConfigurationSection applicationPoolsSection = config.GetSection("system.applicationHost/applicationPools"); - ConfigurationElementCollection applicationPoolsCollection = applicationPoolsSection.GetCollection(); - ConfigurationElement addElement = FindElement(applicationPoolsCollection, "add", "name", appPoolName); - if (addElement == null) throw new InvalidOperationException("Element not found!"); - - switch (attribute) - { - case "privateMemory": - case "memory": - ConfigurationElement recyclingElement = addElement.GetChildElement("recycling"); - ConfigurationElement periodicRestartElement = recyclingElement.GetChildElement("periodicRestart"); - periodicRestartElement[attribute] = value; - break; - case "rapidFailProtectionMaxCrashes": - ConfigurationElement failureElement = addElement.GetChildElement("failure"); - failureElement["rapidFailProtectionMaxCrashes"] = value; - break; - default: - addElement[attribute] = value; - break; - } - serverManager.CommitChanges(); - } - } - - public void RecycleAppPool(string appPoolName) - { - using (ServerManager serverManager = GetServerManager()) - { - serverManager.ApplicationPools[appPoolName].Recycle(); - } - } - - public void StopAppPool(string appPoolName) - { - using (ServerManager serverManager = GetServerManager()) - { - serverManager.ApplicationPools[appPoolName].Stop(); - } - } - - public void StartAppPool(string appPoolName) - { - using (ServerManager serverManager = GetServerManager()) - { - serverManager.ApplicationPools[appPoolName].Start(); - } - } - - public void CreateSite(string siteName, string hostname, string physicalPath, int siteId, int tcpPort, string appPoolName = "DefaultAppPool") - { - TestUtility.LogInformation("Creating web site : " + siteName); - - using (ServerManager serverManager = GetServerManager()) - { - Configuration config = serverManager.GetApplicationHostConfiguration(); - ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites"); - ConfigurationElementCollection sitesCollection = sitesSection.GetCollection(); - ConfigurationElement siteElement = FindElement(sitesCollection, "site", "name", siteName); - if (siteElement != null) - { - sitesCollection.Remove(siteElement); - } - siteElement = sitesCollection.CreateElement("site"); - siteElement["id"] = siteId; - siteElement["name"] = siteName; - ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings"); - - ConfigurationElement bindingElement = bindingsCollection.CreateElement("binding"); - bindingElement["protocol"] = @"http"; - bindingElement["bindingInformation"] = "*:" + tcpPort + ":" + hostname; - bindingsCollection.Add(bindingElement); - - ConfigurationElementCollection siteCollection = siteElement.GetCollection(); - ConfigurationElement applicationElement = siteCollection.CreateElement("application"); - applicationElement["path"] = @"/"; - applicationElement["applicationPool"] = appPoolName; - - ConfigurationElementCollection applicationCollection = applicationElement.GetCollection(); - ConfigurationElement virtualDirectoryElement = applicationCollection.CreateElement("virtualDirectory"); - virtualDirectoryElement["path"] = @"/"; - virtualDirectoryElement["physicalPath"] = physicalPath; - applicationCollection.Add(virtualDirectoryElement); - siteCollection.Add(applicationElement); - sitesCollection.Add(siteElement); - serverManager.CommitChanges(); - } - } - - public void CreateApp(string siteName, string appName, string physicalPath, string appPoolName = "DefaultAppPool") - { - TestUtility.LogInformation("Creating web app : " + siteName + "/" + appName); - using (ServerManager serverManager = GetServerManager()) - { - Configuration config = serverManager.GetApplicationHostConfiguration(); - - ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites"); - - ConfigurationElementCollection sitesCollection = sitesSection.GetCollection(); - - ConfigurationElement siteElement = FindElement(sitesCollection, "site", "name", siteName); - if (siteElement == null) throw new InvalidOperationException("Element not found!"); - - ConfigurationElementCollection siteCollection = siteElement.GetCollection(); - - ConfigurationElement applicationElement = siteCollection.CreateElement("application"); - string appPath = @"/" + appName; - appPath = appPath.Replace("//", "/"); - applicationElement["path"] = appPath; - applicationElement["applicationPool"] = appPoolName; - - ConfigurationElementCollection applicationCollection = applicationElement.GetCollection(); - - ConfigurationElement virtualDirectoryElement = applicationCollection.CreateElement("virtualDirectory"); - virtualDirectoryElement["path"] = @"/"; - virtualDirectoryElement["physicalPath"] = physicalPath; - applicationCollection.Add(virtualDirectoryElement); - siteCollection.Add(applicationElement); - serverManager.CommitChanges(); - } - } - - public void EnableIISAuthentication(string siteName, bool windows, bool basic, bool anonymous) - { - TestUtility.LogInformation("Enable Windows authentication : " + siteName); - using (ServerManager serverManager = GetServerManager()) - { - Configuration config = serverManager.GetApplicationHostConfiguration(); - - ConfigurationSection anonymousAuthenticationSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication", siteName); - anonymousAuthenticationSection["enabled"] = anonymous; - ConfigurationSection basicAuthenticationSection = config.GetSection("system.webServer/security/authentication/basicAuthentication", siteName); - basicAuthenticationSection["enabled"] = basic; - ConfigurationSection windowsAuthenticationSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", siteName); - windowsAuthenticationSection["enabled"] = windows; - serverManager.CommitChanges(); - } - } - - public void EnableOneToOneClientCertificateMapping(string siteName, string userName, string password, string publicKey) - { - TestUtility.LogInformation("Enable one-to-one client certificate mapping authentication : " + siteName); - using (ServerManager serverManager = GetServerManager()) - { - Configuration config = serverManager.GetApplicationHostConfiguration(); - - ConfigurationSection iisClientCertificateMappingAuthenticationSection = config.GetSection("system.webServer/security/authentication/iisClientCertificateMappingAuthentication", siteName); - - // enable iisClientCertificateMappingAuthentication - ConfigurationElementCollection oneToOneMappingsCollection = iisClientCertificateMappingAuthenticationSection.GetCollection("oneToOneMappings"); - iisClientCertificateMappingAuthenticationSection["enabled"] = true; - - // add a new oneToOne mapping collection item - ConfigurationElement addElement = oneToOneMappingsCollection.CreateElement("add"); - addElement["userName"] = userName; - if (password != null) - { - addElement["password"] = password; - } - addElement["certificate"] = publicKey; - oneToOneMappingsCollection.Add(addElement); - - // set sslFlags with SslNegotiateCert - ConfigurationSection accessSection = config.GetSection("system.webServer/security/access", siteName); - accessSection["sslFlags"] = "Ssl, SslNegotiateCert, SslRequireCert"; - - // disable other authentication to avoid any noise affected by other authentications - ConfigurationSection anonymousAuthenticationSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication", siteName); - anonymousAuthenticationSection["enabled"] = false; - ConfigurationSection windowsAuthenticationSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", siteName); - windowsAuthenticationSection["enabled"] = false; - serverManager.CommitChanges(); - } - } - - public void SetCompression(string siteName, bool enabled) - { - TestUtility.LogInformation("Enable Compression : " + siteName); - using (ServerManager serverManager = GetServerManager()) - { - Configuration config = serverManager.GetApplicationHostConfiguration(); - - ConfigurationSection urlCompressionSection = config.GetSection("system.webServer/urlCompression", siteName); - urlCompressionSection["doStaticCompression"] = enabled; - urlCompressionSection["doDynamicCompression"] = enabled; - serverManager.CommitChanges(); - } - } - - public void DisableWindowsAuthentication(string siteName) - { - TestUtility.LogInformation("Enable Windows authentication : " + siteName); - using (ServerManager serverManager = GetServerManager()) - { - Configuration config = serverManager.GetApplicationHostConfiguration(); - - ConfigurationSection anonymousAuthenticationSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication", siteName); - anonymousAuthenticationSection["enabled"] = true; - ConfigurationSection windowsAuthenticationSection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", siteName); - windowsAuthenticationSection["enabled"] = false; - serverManager.CommitChanges(); - } - } - - public void SetANCMConfig(string siteName, string appName, string attributeName, object attributeValue) - { - try - { - using (ServerManager serverManager = GetServerManager()) - { - Configuration config = serverManager.GetWebConfiguration(siteName, appName); - ConfigurationSection aspNetCoreSection = config.GetSection("system.webServer/aspNetCore"); - if (attributeName == "environmentVariable") - { - string name = ((string[])attributeValue)[0]; - string value = ((string[])attributeValue)[1]; - ConfigurationElementCollection environmentVariablesCollection = aspNetCoreSection.GetCollection("environmentVariables"); - ConfigurationElement environmentVariableElement = environmentVariablesCollection.CreateElement("environmentVariable"); - environmentVariableElement["name"] = name; - environmentVariableElement["value"] = value; - var element = FindElement(environmentVariablesCollection, "add", "name", value); - if (element != null) - { - throw new ApplicationException("duplicated collection item"); - } - environmentVariablesCollection.Add(environmentVariableElement); - } - else - { - aspNetCoreSection[attributeName] = attributeValue; - } - - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - throw ex; - } - } - - public void ConfigureCustomLogging(string siteName, string appName, int statusCode, int subStatusCode, string path) - { - using (ServerManager serverManager = GetServerManager()) - { - Configuration config = serverManager.GetWebConfiguration(siteName, appName); - ConfigurationSection httpErrorsSection = config.GetSection("system.webServer/httpErrors"); - httpErrorsSection["errorMode"] = @"Custom"; - - ConfigurationElementCollection httpErrorsCollection = httpErrorsSection.GetCollection(); - ConfigurationElement errorElement = FindElement(httpErrorsCollection, "error", "statusCode", statusCode.ToString(), "subStatusCode", subStatusCode.ToString()); - if (errorElement != null) - { - httpErrorsCollection.Remove(errorElement); - } - - ConfigurationElement errorElement2 = httpErrorsCollection.CreateElement("error"); - errorElement2["statusCode"] = statusCode; - errorElement2["subStatusCode"] = subStatusCode; - errorElement2["path"] = path; - httpErrorsCollection.Add(errorElement2); - serverManager.CommitChanges(); - } - Thread.Sleep(500); - } - - public bool IsAncmInstalled(ServerType servertype) - { - bool result = true; - if (servertype == ServerType.IIS) - { - if (!File.Exists(InitializeTestMachine.FullIisAspnetcoreSchema_path)) - { - result = false; - } - } - else - { - if (!File.Exists(InitializeTestMachine.IisExpressAspnetcoreSchema_path)) - { - result = false; - } - } - return result; - } - - public static string GetServiceStatus(string serviceName) - { - ServiceController sc = new ServiceController(serviceName); - - switch (sc.Status) - { - case ServiceControllerStatus.Running: - return "Running"; - case ServiceControllerStatus.Stopped: - return "Stopped"; - case ServiceControllerStatus.Paused: - return "Paused"; - case ServiceControllerStatus.StopPending: - return "Stopping"; - case ServiceControllerStatus.StartPending: - return "Starting"; - default: - return "Status Changing"; - } - } - - public bool IsUrlRewriteInstalledForIIS() - { - bool result = true; - var toRewrite64 = Path.Combine(Strings.IIS64BitPath, "rewrite.dll"); - var toRewrite32 = Path.Combine(Strings.IIS32BitPath, "rewrite.dll"); - - if (TestUtility.IsOSAmd64) - { - if (!File.Exists(toRewrite64)) - { - result = false; - } - } - - if (!File.Exists(toRewrite32)) - { - result = false; - } - - using (ServerManager serverManager = GetServerManager()) - { - Configuration config = serverManager.GetApplicationHostConfiguration(); - ConfigurationSection globalModulesSection = config.GetSection("system.webServer/globalModules"); - ConfigurationElementCollection globalModulesCollection = globalModulesSection.GetCollection(); - if (FindElement(globalModulesCollection, "add", "name", "RewriteModule") == null) - { - result = false; - } - - ConfigurationSection modulesSection = config.GetSection("system.webServer/modules"); - ConfigurationElementCollection modulesCollection = modulesSection.GetCollection(); - if (FindElement(modulesCollection, "add", "name", "RewriteModule") == null) - { - result = false; - } - } - return result; - } - - public bool RemoveModule(string moduleName) - { - bool result = true; - using (ServerManager serverManager = GetServerManager()) - { - Configuration config = serverManager.GetApplicationHostConfiguration(); - ConfigurationSection globalModulesSection = config.GetSection("system.webServer/globalModules"); - ConfigurationElementCollection globalModulesCollection = globalModulesSection.GetCollection(); - var globalModule = FindElement(globalModulesCollection, "add", "name", moduleName); - if (globalModule != null) - { - globalModulesCollection.Remove(globalModule); - - } - ConfigurationSection modulesSection = config.GetSection("system.webServer/modules"); - ConfigurationElementCollection modulesCollection = modulesSection.GetCollection(); - var module = FindElement(modulesCollection, "add", "name", moduleName); - if (module != null) - { - modulesCollection.Remove(module); - } - - serverManager.CommitChanges(); - } - return result; - } - - public bool AddModule(string moduleName, string image, string preCondition) - { - RemoveModule(moduleName); - - bool result = true; - using (ServerManager serverManager = GetServerManager()) - { - Configuration config = serverManager.GetApplicationHostConfiguration(); - ConfigurationSection globalModulesSection = config.GetSection("system.webServer/globalModules"); - ConfigurationElementCollection globalModulesCollection = globalModulesSection.GetCollection(); - - ConfigurationElement globalModule = globalModulesCollection.CreateElement("add"); - globalModule["name"] = moduleName; - globalModule["image"] = image; - if (preCondition != null) - { - globalModule["preCondition"] = preCondition; - } - globalModulesCollection.Add(globalModule); - - ConfigurationSection modulesSection = config.GetSection("system.webServer/modules"); - ConfigurationElementCollection modulesCollection = modulesSection.GetCollection(); - ConfigurationElement module = modulesCollection.CreateElement("add"); - module["name"] = moduleName; - modulesCollection.Add(module); - - serverManager.CommitChanges(); - } - return result; - } - - private static ConfigurationElement FindElement(ConfigurationElementCollection collection, string elementTagName, params string[] keyValues) - { - foreach (ConfigurationElement element in collection) - { - if (String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase)) - { - bool matches = true; - - for (int i = 0; i < keyValues.Length; i += 2) - { - object o = element.GetAttributeValue(keyValues[i]); - string value = null; - if (o != null) - { - value = o.ToString(); - } - - if (!String.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase)) - { - matches = false; - break; - } - } - if (matches) - { - return element; - } - } - } - return null; - } - - public void CreateAppPool(string poolName, bool alwaysRunning = false) - { - try - { - TestUtility.LogTrace(String.Format("#################### Adding App Pool {0} with startMode = {1} ####################", poolName, alwaysRunning ? "AlwaysRunning" : "OnDemand")); - using (ServerManager serverManager = GetServerManager()) - { - if (serverManager.ApplicationPools[poolName] != null) - { - TestUtility.LogInformation("Removing existing apppool"); - serverManager.ApplicationPools.Remove(serverManager.ApplicationPools[poolName]); - } - serverManager.ApplicationPools.Add(poolName); - ApplicationPool apppool = serverManager.ApplicationPools[poolName]; - apppool.ManagedPipelineMode = ManagedPipelineMode.Integrated; - if (alwaysRunning) - { - apppool.SetAttributeValue("startMode", "AlwaysRunning"); - } - - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Create app pool {0} failed. Reason: {1} ####################", poolName, ex.Message)); - } - } - - public void SetIdleTimeoutForAppPool(string appPoolName, int idleTimeoutMinutes) - { - TestUtility.LogTrace(String.Format("#################### Setting idleTimeout to {0} minutes for AppPool {1} ####################", idleTimeoutMinutes, appPoolName)); - try - { - using (ServerManager serverManager = GetServerManager()) - { - ApplicationPoolCollection appPools = serverManager.ApplicationPools; - appPools[appPoolName].ProcessModel.IdleTimeout = TimeSpan.FromMinutes(idleTimeoutMinutes); - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Setting idleTimeout to {0} minutes for AppPool {1} failed. Reason: {2} ####################", idleTimeoutMinutes, appPoolName, ex.Message)); - } - } - - public void SetMaxProcessesForAppPool(string appPoolName, int maxProcesses) - { - TestUtility.LogTrace(String.Format("#################### Setting maxProcesses to {0} for AppPool {1} ####################", maxProcesses, appPoolName)); - try - { - using (ServerManager serverManager = GetServerManager()) - { - ApplicationPoolCollection appPools = serverManager.ApplicationPools; - appPools[appPoolName].ProcessModel.MaxProcesses = maxProcesses; - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Setting maxProcesses to {0} for AppPool {1} failed. Reason: {2} ####################", maxProcesses, appPoolName, ex.Message)); - } - } - - public void SetIdentityForAppPool(string appPoolName, string userName, string password) - { - TestUtility.LogTrace(String.Format("#################### Setting userName {0} and password {1} for AppPool {2} ####################", userName, password, appPoolName)); - try - { - using (ServerManager serverManager = GetServerManager()) - { - ApplicationPoolCollection appPools = serverManager.ApplicationPools; - appPools[appPoolName].ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser; - appPools[appPoolName].ProcessModel.UserName = userName; - appPools[appPoolName].ProcessModel.Password = password; - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Setting userName {0} and password {1} for AppPool {2} failed. Reason: {2} ####################", userName, password, appPoolName, ex.Message)); - } - } - - public void SetStartModeAlwaysRunningForAppPool(string appPoolName, bool alwaysRunning) - { - string startMode = alwaysRunning ? "AlwaysRunning" : "OnDemand"; - - TestUtility.LogTrace(String.Format("#################### Setting startMode to {0} for AppPool {1} ####################", startMode, appPoolName)); - - try - { - using (ServerManager serverManager = GetServerManager()) - { - ApplicationPoolCollection appPools = serverManager.ApplicationPools; - appPools[appPoolName]["startMode"] = startMode; - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Setting startMode to {0} for AppPool {1} failed. Reason: {2} ####################", startMode, appPoolName, ex.Message)); - } - } - - public void StartAppPoolEx(string appPoolName) - { - StartOrStopAppPool(appPoolName, true); - } - - public void StopAppPoolEx(string appPoolName) - { - StartOrStopAppPool(appPoolName, false); - } - - private void StartOrStopAppPool(string appPoolName, bool start) - { - string action = start ? "Starting" : "Stopping"; - TestUtility.LogTrace(String.Format("#################### {0} app pool {1} ####################", action, appPoolName)); - - try - { - using (ServerManager serverManager = GetServerManager()) - { - ApplicationPoolCollection appPools = serverManager.ApplicationPools; - if (start) - { - appPools[appPoolName].Start(); - } - else - { - appPools[appPoolName].Stop(); - } - } - } - catch (Exception ex) - { - string message = ex.Message; - TestUtility.LogInformation(String.Format("#################### {0} app pool {1} failed. Reason: {2} ####################", action, appPoolName, ex.Message)); - } - } - - public void VerifyAppPoolState(string appPoolName, Microsoft.Web.Administration.ObjectState state) - { - try - { - using (ServerManager serverManager = GetServerManager()) - { - ApplicationPoolCollection appPools = serverManager.ApplicationPools; - if (appPools[appPoolName].State == state) - TestUtility.LogInformation(String.Format("Verified state for app pool {0} is {1}.", appPoolName, state.ToString())); - else - TestUtility.LogInformation(String.Format("Unexpected state {0} for app pool {1}.", state, appPoolName.ToString())); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Failed to verify state for app pool {0}. Reason: {1} ####################", appPoolName, ex.Message)); - } - } - - public void DeleteAppPool(string poolName) - { - try - { - using (ServerManager serverManager = GetServerManager()) - { - TestUtility.LogTrace(String.Format("#################### Deleting App Pool {0} ####################", poolName)); - - ApplicationPoolCollection appPools = serverManager.ApplicationPools; - appPools.Remove(appPools[poolName]); - - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Delete app pool {0} failed. Reason: {1} ####################", poolName, ex.Message)); - } - } - - public void DeleteAllAppPools(bool commitDelay = false) - { - TestUtility.LogTrace(String.Format("#################### Deleting all app pools ####################")); - - using (ServerManager serverManager = GetServerManager()) - { - ApplicationPoolCollection appPools = serverManager.ApplicationPools; - while (appPools.Count > 0) - { - appPools.RemoveAt(0); - } - serverManager.CommitChanges(); - } - } - - public void CreateSiteEx(int siteId, string siteName, string poolName, string dirRoot, string Ip, int Port, string host) - { - try - { - using (ServerManager serverManager = GetServerManager()) - { - string bindingInfo = ""; - if (Ip == null) - Ip = "*"; - bindingInfo += Ip; - bindingInfo += ":"; - bindingInfo += Port; - bindingInfo += ":"; - if (host != null) - bindingInfo += host; - - TestUtility.LogTrace(String.Format("#################### Adding Site {0} with App Pool {1} with BindingInfo {2} ####################", siteName, poolName, bindingInfo)); - - SiteCollection sites = serverManager.Sites; - Site site = sites.CreateElement(); - site.Id = siteId; - site.SetAttributeValue("name", siteName); - sites.Add(site); - - Application app = site.Applications.CreateElement(); - app.SetAttributeValue("path", "/"); - app.SetAttributeValue("applicationPool", poolName); - site.Applications.Add(app); - - VirtualDirectory vdir = app.VirtualDirectories.CreateElement(); - vdir.SetAttributeValue("path", "/"); - vdir.SetAttributeValue("physicalPath", dirRoot); - - app.VirtualDirectories.Add(vdir); - - Binding b = site.Bindings.CreateElement(); - b.SetAttributeValue("protocol", "http"); - b.SetAttributeValue("bindingInformation", bindingInfo); - - site.Bindings.Add(b); - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Create site {0} failed. Reason: {1} ####################", siteName, ex.Message)); - } - } - - public void StartSite(string siteName) - { - StartOrStopSite(siteName, true); - } - - public void StopSite(string siteName) - { - StartOrStopSite(siteName, false); - } - - private void StartOrStopSite(string siteName, bool start) - { - string action = start ? "Starting" : "Stopping"; - TestUtility.LogTrace(String.Format("#################### {0} site {1} ####################", action, siteName)); - - try - { - using (ServerManager serverManager = GetServerManager()) - { - SiteCollection sites = serverManager.Sites; - if (start) - { - sites[siteName].Start(); - sites[siteName].SetAttributeValue("serverAutoStart", true); - } - else - { - sites[siteName].Stop(); - sites[siteName].SetAttributeValue("serverAutoStart", false); - } - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### {0} site {1} failed. Reason: {2} ####################", action, siteName, ex.Message)); - } - } - - public ObjectState GetSiteState(string siteName) - { - using (ServerManager serverManager = GetServerManager()) - { - SiteCollection sites = serverManager.Sites; - if (sites[siteName] != null) - { - return sites[siteName].State; - } - else - { - return ObjectState.Unknown; - } - } - } - - public void AddApplicationToSite(string siteName, string appPath, string physicalPath, string poolName) - { - try - { - using (ServerManager serverManager = GetServerManager()) - { - TestUtility.LogTrace(String.Format("#################### Adding Application {0} with App Pool {1} to Site {2} ####################", appPath, poolName, siteName)); - - SiteCollection sites = serverManager.Sites; - Application app = sites[siteName].Applications.CreateElement(); - app.SetAttributeValue("path", appPath); - app.SetAttributeValue("applicationPool", poolName); - sites[siteName].Applications.Add(app); - - VirtualDirectory vdir = app.VirtualDirectories.CreateElement(); - vdir.SetAttributeValue("path", "/"); - vdir.SetAttributeValue("physicalPath", physicalPath); - - app.VirtualDirectories.Add(vdir); - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Add Application {0} with App Pool {1} to Site {2} failed. Reason: {3} ####################", appPath, poolName, siteName, ex.Message)); - } - } - - public void ChangeApplicationPool(string siteName, int appIndex, string poolName) - { - try - { - using (ServerManager serverManager = GetServerManager()) - { - TestUtility.LogTrace(String.Format("#################### Changing Application Pool for App {0} of Site {1} to {2} ####################", appIndex, siteName, poolName)); - - serverManager.Sites[siteName].Applications[appIndex].SetAttributeValue("applicationPool", poolName); - - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Changing Application Pool for App {0} of Site {1} to {2} failed. Reason: {3} ####################", appIndex, siteName, poolName, ex.Message)); - } - } - - public void ChangeApplicationPath(string siteName, int appIndex, string path) - { - try - { - using (ServerManager serverManager = GetServerManager()) - { - TestUtility.LogTrace(String.Format("#################### Changing Path for App {0} of Site {1} to {2} ####################", appIndex, siteName, path)); - - serverManager.Sites[siteName].Applications[appIndex].SetAttributeValue("path", path); - - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Changing Path for App {0} of Site {1} to {2} failed. Reason: {3} ####################", appIndex, siteName, path, ex.Message)); - } - } - - public void RemoveApplication(string siteName, int appIndex) - { - try - { - using (ServerManager serverManager = GetServerManager()) - { - TestUtility.LogTrace(String.Format("#################### Deleting App {0} from Site {1} ####################", appIndex, siteName)); - - serverManager.Sites[siteName].Applications.RemoveAt(appIndex); - - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Deleting App {0} from Site {1} failed. Reason: {2} ####################", appIndex, siteName, ex.Message)); - } - } - - public string CreateSelfSignedCertificateWithMakeCert(string subjectName, string issuerName = null, string extendedKeyUsage = null) - { - string makecertExeFilePath = TestUtility.GetMakeCertPath(); - - string parameter; - string targetSSLStore = string.Empty; - if (issuerName == null) - { - // if issuer Name is null, you are going to create a root level certificate - parameter = "-r -pe -n \"CN = " + subjectName + "\" -b 12/22/2013 -e 12/23/2020 -ss root -sr localmachine -len 2048 -a sha256"; - targetSSLStore = @"Cert:\LocalMachine\Root"; // => -ss root -sr localmachine - } - else - { - // if issuer Name is *not* null, you are going to create a child evel certificate from the given issuer certificate - switch (extendedKeyUsage) - { - // for web server certificate - case "1.3.6.1.5.5.7.3.1": - parameter = "-pe -n \"CN=" + subjectName + "\" -b 12/22/2013 -e 12/23/" + (System.DateTime.Now.Year + 10).ToString() + " -eku " + extendedKeyUsage + " -is root -ir localmachine -in \"" + issuerName + "\" -len 2048 -ss my -sr localmachine -a sha256"; - targetSSLStore = @"Cert:\LocalMachine\My"; // => -ss my -sr localmachine - break; - - // for client authentication - case "1.3.6.1.5.5.7.3.2": - parameter = "-pe -n \"CN=" + subjectName + "\" -eku " + extendedKeyUsage + " -is root -ir localmachine -in \"" + issuerName + "\" -ss my -sr currentuser -len 2048 -a sha256"; - targetSSLStore = @"Cert:\CurrentUser\My"; // => -ss my -sr currentuser - break; - - default: - throw new NotImplementedException(extendedKeyUsage); - } - } - try - { - TestUtility.RunCommand(makecertExeFilePath, parameter); - } - catch (Exception ex) - { - TestUtility.LogInformation("Failed to run makecert.exe. Makecert.exe is installed with Visual Studio or SDK. Please make sure setting PATH environment to include the directory path of the makecert.exe file"); - throw ex; - } - - string toolsPath = Path.Combine(InitializeTestMachine.GetSolutionDirectory(), "tools"); - string powershellScript = Path.Combine(toolsPath, "certificate.ps1") - + " -Command Get-CertificateThumbPrint" + - " -Subject " + subjectName + - " -TargetSSLStore \"" + targetSSLStore + "\""; - - if (issuerName != null) - { - powershellScript += " -IssuerName " + issuerName; - } - - string output = TestUtility.RunPowershellScript(powershellScript); - if (output.Length != 40) - { - throw new ApplicationException("Failed to create a certificate, output: " + output); - } - return output; - } - - public string CreateSelfSignedCertificate(string subjectName) - { - string toolsPath = Path.Combine(InitializeTestMachine.GetSolutionDirectory(), "tools"); - string powershellScript = Path.Combine(toolsPath, "certificate.ps1") - + " -Command Create-SelfSignedCertificate" - + " -Subject " + subjectName; - - string output = TestUtility.RunPowershellScript(powershellScript); - if (output.Length != 40) - { - throw new ApplicationException("Failed to create a certificate, output: " + output); - } - return output; - } - - public string ExportCertificateTo(string thumbPrint, string sslStoreFrom = @"Cert:\LocalMachine\My", string sslStoreTo = @"Cert:\LocalMachine\Root", string pfxPassword = null) - { - string toolsPath = Path.Combine(InitializeTestMachine.GetSolutionDirectory(), "tools"); - string powershellScript = Path.Combine(toolsPath, "certificate.ps1") + - " -Command Export-CertificateTo" + - " -TargetThumbPrint " + thumbPrint + - " -TargetSSLStore " + sslStoreFrom + - " -ExportToSSLStore " + sslStoreTo; - - if (pfxPassword != null) - { - powershellScript += " -PfxPassword " + pfxPassword; - } - - string output = TestUtility.RunPowershellScript(powershellScript); - if (output != string.Empty) - { - throw new ApplicationException("Failed to export a certificate to RootCA, output: " + output); - } - return output; - } - - public string GetCertificatePublicKey(string thumbPrint, string sslStore = @"Cert:\LocalMachine\My") - { - string toolsPath = Path.Combine(InitializeTestMachine.GetSolutionDirectory(), "tools"); - string powershellScript = Path.Combine(toolsPath, "certificate.ps1") + - " -Command Get-CertificatePublicKey" + - " -TargetThumbPrint " + thumbPrint + - " -TargetSSLStore " + sslStore; - - string output = TestUtility.RunPowershellScript(powershellScript); - if (output.Length < 500) - { - throw new ApplicationException("Failed to get certificate public key, output: " + output); - } - return output; - } - - public string DeleteCertificate(string thumbPrint, string sslStore= @"Cert:\LocalMachine\My") - { - string toolsPath = Path.Combine(InitializeTestMachine.GetSolutionDirectory(), "tools"); - string powershellScript = Path.Combine(toolsPath, "certificate.ps1") + - " -Command Delete-Certificate" + - " -TargetThumbPrint " + thumbPrint + - " -TargetSSLStore " + sslStore; - - string output = TestUtility.RunPowershellScript(powershellScript); - if (output != string.Empty) - { - throw new ApplicationException("Failed to delete a certificate (thumbprint: " + thumbPrint + ", output: " + output); - } - return output; - } - - public void SetSSLCertificate(int port, string hexIpAddress, string thumbPrint, string sslStore = @"Cert:\LocalMachine\My") - { - // Remove a certificate mapping if it exists - RemoveSSLCertificate(port, hexIpAddress); - - // Configure certificate mapping with the newly created certificate - string toolsPath = Path.Combine(InitializeTestMachine.GetSolutionDirectory(), "tools"); - string powershellScript = Path.Combine(toolsPath, "httpsys.ps1") + - " -Command Add-SslBinding" + - " -IpAddress " + hexIpAddress + - " -Port " + port.ToString() + - " –Thumbprint \"" + thumbPrint + "\"" + - " -TargetSSLStore " + sslStore; - - string output = TestUtility.RunPowershellScript(powershellScript); - if (output != string.Empty) - { - throw new ApplicationException("Failed to configure certificate, output: " + output); - } - } - - public void RemoveSSLCertificate(int port, string hexIpAddress, string sslStore = @"Cert:\LocalMachine\My") - { - string toolsPath = Path.Combine(InitializeTestMachine.GetSolutionDirectory(), "tools"); - string powershellScript = Path.Combine(toolsPath, "httpsys.ps1") + - " -Command Get-SslBinding" + - " -IpAddress " + hexIpAddress + - " -Port " + port.ToString(); - - string output = TestUtility.RunPowershellScript(powershellScript); - if (output != string.Empty) - { - // Delete a certificate mapping if it exists - powershellScript = Path.Combine(toolsPath, "httpsys.ps1") + " -Command Delete-SslBinding -IpAddress " + hexIpAddress + " -Port " + port.ToString(); - output = TestUtility.RunPowershellScript(powershellScript); - if (output != string.Empty) - { - throw new ApplicationException("Failed to delete certificate, output: " + output); - } - } - } - - public void AddBindingToSite(string siteName, string ipAddress, int port, string host, string protocol = "http") - { - string bindingInfo = ""; - if (ipAddress == null) - ipAddress = "*"; - bindingInfo += ipAddress; - bindingInfo += ":"; - bindingInfo += port; - bindingInfo += ":"; - if (host != null) - bindingInfo += host; - - TestUtility.LogInformation(String.Format("#################### Adding Binding {0} to Site {1} ####################", bindingInfo, siteName)); - - try - { - using (ServerManager serverManager = GetServerManager()) - { - SiteCollection sites = serverManager.Sites; - Binding b = sites[siteName].Bindings.CreateElement(); - b.SetAttributeValue("protocol", protocol); - b.SetAttributeValue("bindingInformation", bindingInfo); - - sites[siteName].Bindings.Add(b); - - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Adding Binding {0} to Site {1} failed. Reason: {2} ####################", bindingInfo, siteName, ex.Message)); - } - } - - public void RemoveBindingFromSite(string siteName, BindingInfo bindingInfo) - { - try - { - using (ServerManager serverManager = GetServerManager()) - { - TestUtility.LogTrace(String.Format("#################### Removing Binding {0} from Site {1} ####################", bindingInfo.ToBindingString(), siteName)); - - for (int i = 0; i < serverManager.Sites[siteName].Bindings.Count; i++) - { - if (serverManager.Sites[siteName].Bindings[i].BindingInformation.ToString() == bindingInfo.ToBindingString()) - { - serverManager.Sites[siteName].Bindings.RemoveAt(i); - - serverManager.CommitChanges(); - return; - } - } - - TestUtility.LogInformation(String.Format("#################### Remove binding failed because binding was not found ####################")); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Remove binding failed. Reason: {0} ####################", ex.Message)); - } - } - - public void ModifyBindingForSite(string siteName, BindingInfo bindingInfoOld, BindingInfo bindingInfoNew) - { - try - { - using (ServerManager serverManager = GetServerManager()) - { - TestUtility.LogTrace(String.Format("#################### Changing Binding {0} for Site {1} to {2} ####################", bindingInfoOld.ToBindingString(), siteName, bindingInfoNew.ToBindingString())); - - for (int i = 0; i < serverManager.Sites[siteName].Bindings.Count; i++) - { - if (serverManager.Sites[siteName].Bindings[i].BindingInformation.ToString() == bindingInfoOld.ToBindingString()) - { - serverManager.Sites[siteName].Bindings[i].SetAttributeValue("bindingInformation", bindingInfoNew.ToBindingString()); - - serverManager.CommitChanges(); - return; - } - } - - TestUtility.LogInformation(String.Format("#################### Modify binding failed because binding was not found ####################")); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Changing binding failed. Reason: {0} ####################", ex.Message)); - } - } - - public void DeleteSite(string siteName) - { - try - { - using (ServerManager serverManager = GetServerManager()) - { - TestUtility.LogTrace(String.Format("#################### Deleting Site {0} ####################", siteName)); - - SiteCollection sites = serverManager.Sites; - sites.Remove(sites[siteName]); - - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogInformation(String.Format("#################### Delete site {0} failed. Reason: {1} ####################", siteName, ex.Message)); - } - } - - public void DeleteAllSites(bool commitDelay = false) - { - using (ServerManager serverManager = GetServerManager()) - { - TestUtility.LogTrace(String.Format("#################### Deleting all sites ####################")); - - SiteCollection sites = serverManager.Sites; - while (sites.Count > 0) - { - sites.RemoveAt(0); - } - serverManager.CommitChanges(); - } - } - - public void SetDynamicSiteRegistrationThreshold(int threshold) - { - try - { - TestUtility.LogTrace(String.Format("#################### Changing dynamicRegistrationThreshold to {0} ####################", threshold)); - - using (ServerManager serverManager = new ServerManager()) - { - Configuration config = serverManager.GetApplicationHostConfiguration(); - ConfigurationSection webLimitsSection = config.GetSection("system.applicationHost/webLimits"); - webLimitsSection["dynamicRegistrationThreshold"] = threshold; - serverManager.CommitChanges(); - } - } - catch (Exception ex) - { - TestUtility.LogTrace(String.Format("#################### Changing dynamicRegistrationThreshold failed. Reason: {0} ####################", ex.Message)); - } - } - } -} \ No newline at end of file diff --git a/test/AspNetCoreModule.Test/Framework/InitializeTestMachine.cs b/test/AspNetCoreModule.Test/Framework/InitializeTestMachine.cs deleted file mode 100644 index fa8f3a11c6..0000000000 --- a/test/AspNetCoreModule.Test/Framework/InitializeTestMachine.cs +++ /dev/null @@ -1,513 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading; -using Microsoft.Extensions.PlatformAbstractions; -using System.Security.Principal; -using System.Security.AccessControl; - -namespace AspNetCoreModule.Test.Framework -{ - public static class TestFlags - { - public const string SkipTest = "SkipTest"; - public const string UsePrivateANCM = "UsePrivateANCM"; - public const string UseIISExpress = "UseIISExpress"; - public const string UseFullIIS = "UseFullIIS"; - public const string RunAsAdministrator = "RunAsAdministrator"; - public const string MakeCertExeAvailable = "MakeCertExeAvailable"; - public const string WebSocketModuleAvailable = "WebSocketModuleAvailable"; - public const string UrlRewriteModuleAvailable = "UrlRewriteModuleAvailable"; - public const string X86Platform = "X86Platform"; - public const string Wow64BitMode = "Wow64BitMode"; - public const string RequireRunAsAdministrator = "RequireRunAsAdministrator"; - public const string Default = "Default"; - - public static bool Enabled(string flagValue) - { - return InitializeTestMachine.GlobalTestFlags.IndexOf(flagValue, StringComparison.OrdinalIgnoreCase) > -1; - } - } - - public class InitializeTestMachine : IDisposable - { - public const string ANCMTestFlagsEnvironmentVariable = "%ANCMTestFlags%"; - - public static int SiteId = 40000; - public const string PrivateFileName = "aspnetcore_private.dll"; - public static string FullIisAspnetcore_path = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "system32", "inetsrv", PrivateFileName); - public static string FullIisAspnetcore_path_original = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "system32", "inetsrv", "aspnetcore.dll"); - public static string FullIisAspnetcore_X86_path = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "syswow64", "inetsrv", PrivateFileName); - public static string IisExpressAspnetcore_path; - public static string IisExpressAspnetcore_X86_path; - - public static string IisExpressAspnetcoreSchema_path = Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles%"), "IIS Express", "config", "schema", "aspnetcore_schema.xml"); - public static string IisExpressAspnetcoreSchema_X86_path = Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%"), "IIS Express", "config", "schema", "aspnetcore_schema.xml"); - public static string FullIisAspnetcoreSchema_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; - - private static bool? _makeCertExeAvailable = null; - public static bool MakeCertExeAvailable - { - get - { - if (_makeCertExeAvailable == null) - { - _makeCertExeAvailable = false; - try - { - string makecertExeFilePath = TestUtility.GetMakeCertPath(); - TestUtility.RunCommand(makecertExeFilePath, null, true, true); - TestUtility.LogInformation("Verified makecert.exe is available : " + makecertExeFilePath); - _makeCertExeAvailable = true; - } - catch - { - // ignore exception - } - } - return (_makeCertExeAvailable == true); - } - } - - public static string TestRootDirectory - { - get - { - return Path.Combine(Environment.ExpandEnvironmentVariables("%SystemDrive%") + @"\", "_ANCMTest"); - } - } - - private static string _globalTestFlags = null; - public static string GlobalTestFlags - { - get - { - if (_globalTestFlags == null) - { - WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); - bool isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator); - - // check if this test process is started with the Run As Administrator start option - _globalTestFlags = Environment.ExpandEnvironmentVariables(ANCMTestFlagsEnvironmentVariable); - - // - // Check if ANCMTestFlags environment is not defined and the test program was started - // without using the Run As Administrator start option. - // In that case, we have to use the default TestFlags of UseIISExpress and UsePrivateANCM - // - if (!isElevated) - { - if (_globalTestFlags.ToLower().Contains("%" + ANCMTestFlagsEnvironmentVariable.ToLower() + "%")) - { - _globalTestFlags = TestFlags.UsePrivateANCM + ";" + TestFlags.UseIISExpress; - } - } - - // - // convert in lower case - // - _globalTestFlags = _globalTestFlags.ToLower(); - - // - // error handling: UseIISExpress and UseFullIIS can be used together. - // - if (_globalTestFlags.Contains(TestFlags.UseIISExpress.ToLower()) && _globalTestFlags.Contains(TestFlags.UseFullIIS.ToLower())) - { - _globalTestFlags = _globalTestFlags.Replace(TestFlags.UseFullIIS.ToLower(), ""); - } - - // - // adjust the default test context in run time to figure out wrong test context values - // - if (isElevated) - { - // add RunAsAdministrator - if (!_globalTestFlags.Contains(TestFlags.RunAsAdministrator.ToLower())) - { - TestUtility.LogInformation("Added test context of " + TestFlags.RunAsAdministrator); - _globalTestFlags += ";" + TestFlags.RunAsAdministrator; - } - } - else - { - // add UseIISExpress - if (!_globalTestFlags.Contains(TestFlags.UseIISExpress.ToLower())) - { - TestUtility.LogInformation("Added test context of " + TestFlags.UseIISExpress); - _globalTestFlags += ";" + TestFlags.UseIISExpress; - } - - // remove UseFullIIS - if (_globalTestFlags.Contains(TestFlags.UseFullIIS.ToLower())) - { - _globalTestFlags = _globalTestFlags.Replace(TestFlags.UseFullIIS.ToLower(), ""); - } - - // remove RunAsAdmistrator - if (_globalTestFlags.Contains(TestFlags.RunAsAdministrator.ToLower())) - { - _globalTestFlags = _globalTestFlags.Replace(TestFlags.RunAsAdministrator.ToLower(), ""); - } - } - - if (MakeCertExeAvailable) - { - // Add MakeCertExeAvailable - if (!_globalTestFlags.Contains(TestFlags.MakeCertExeAvailable.ToLower())) - { - TestUtility.LogInformation("Added test context of " + TestFlags.MakeCertExeAvailable); - _globalTestFlags += ";" + TestFlags.MakeCertExeAvailable; - } - } - - if (!Environment.Is64BitOperatingSystem) - { - // Add X86Platform - if (!_globalTestFlags.Contains(TestFlags.X86Platform.ToLower())) - { - TestUtility.LogInformation("Added test context of " + TestFlags.X86Platform); - _globalTestFlags += ";" + TestFlags.X86Platform; - } - } - - if (Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess) - { - // Add Wow64bitMode - if (!_globalTestFlags.Contains(TestFlags.Wow64BitMode.ToLower())) - { - TestUtility.LogInformation("Added test context of " + TestFlags.Wow64BitMode); - _globalTestFlags += ";" + TestFlags.Wow64BitMode; - } - - // remove X86Platform - if (_globalTestFlags.Contains(TestFlags.X86Platform.ToLower())) - { - _globalTestFlags = _globalTestFlags.Replace(TestFlags.X86Platform.ToLower(), ""); - } - } - - if (File.Exists(Path.Combine(IISConfigUtility.Strings.IIS64BitPath, "iiswsock.dll"))) - { - // Add WebSocketModuleAvailable - if (!_globalTestFlags.Contains(TestFlags.WebSocketModuleAvailable.ToLower())) - { - TestUtility.LogInformation("Added test context of " + TestFlags.WebSocketModuleAvailable); - _globalTestFlags += ";" + TestFlags.WebSocketModuleAvailable; - } - } - - if (File.Exists(Path.Combine(IISConfigUtility.Strings.IIS64BitPath, "rewrite.dll"))) - { - // Add UrlRewriteModuleAvailable - if (!_globalTestFlags.Contains(TestFlags.UrlRewriteModuleAvailable.ToLower())) - { - TestUtility.LogInformation("Added test context of " + TestFlags.UrlRewriteModuleAvailable); - _globalTestFlags += ";" + TestFlags.UrlRewriteModuleAvailable; - } - } - - _globalTestFlags = _globalTestFlags.ToLower(); - } - - return _globalTestFlags; - } - } - - public void InitializeIISServer() - { - // Check if IIS server is installed or not - bool isIISInstalled = true; - if (!File.Exists(Path.Combine(IISConfigUtility.Strings.IIS64BitPath, "iiscore.dll"))) - { - isIISInstalled = false; - } - - if (!File.Exists(Path.Combine(IISConfigUtility.Strings.IIS64BitPath, "config", "applicationhost.config"))) - { - isIISInstalled = false; - } - - if (!isIISInstalled) - { - throw new ApplicationException("IIS server is not installed"); - } - - // Clean up IIS worker process - TestUtility.ResetHelper(ResetHelperMode.KillWorkerProcess); - - // Reset applicationhost.config - TestUtility.LogInformation("Restoring applicationhost.config"); - IISConfigUtility.RestoreAppHostConfig(restoreFromMasterBackupFile: true); - TestUtility.StartW3svc(); - - // check w3svc is running after resetting applicationhost.config - if (IISConfigUtility.GetServiceStatus("w3svc") == "Running") - { - TestUtility.LogInformation("W3SVC service is restarted after restoring applicationhost.config"); - } - else - { - throw new ApplicationException("WWW service can't start"); - } - - if (IISConfigUtility.ApppHostTemporaryBackupFileExtention == null) - { - throw new ApplicationException("Failed to backup applicationhost.config"); - } - } - - public InitializeTestMachine() - { - _referenceCount++; - - // This method should be called only one time - if (_referenceCount == 1) - { - TestUtility.LogInformation("InitializeTestMachine::InitializeTestMachine() Start"); - - _InitializeTestMachineCompleted = false; - - TestUtility.LogInformation("InitializeTestMachine::Start"); - if (Environment.ExpandEnvironmentVariables("%ANCMTEST_DEBUG%").ToLower() == "true") - { - System.Diagnostics.Debugger.Launch(); - } - - // - // Clean up IISExpress processes - // - TestUtility.ResetHelper(ResetHelperMode.KillIISExpress); - - // - // Initalize IIS server - // - - if (TestFlags.Enabled(TestFlags.UseFullIIS)) - { - InitializeIISServer(); - } - - string siteRootPath = TestRootDirectory; - if (!Directory.Exists(siteRootPath)) - { - // - // Create a new directory and set the write permission for the SID of AuthenticatedUser - // - Directory.CreateDirectory(siteRootPath); - DirectorySecurity sec = Directory.GetAccessControl(siteRootPath); - SecurityIdentifier authenticatedUser = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null); - sec.AddAccessRule(new FileSystemAccessRule(authenticatedUser, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); - Directory.SetAccessControl(siteRootPath, sec); - } - - 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); - } - } - } - - // - // Intialize Private ANCM files for Full IIS server or IISExpress - // - if (TestFlags.Enabled(TestFlags.UsePrivateANCM)) - { - PreparePrivateANCMFiles(); - } - - _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 ApplicationException("InitializeTestMachine failed"); - } - } - - public void Dispose() - { - _referenceCount--; - - if (_referenceCount == 0) - { - TestUtility.LogInformation("InitializeTestMachine::Dispose() Start"); - TestUtility.ResetHelper(ResetHelperMode.KillIISExpress); - RollbackIISApplicationhostConfigFile(); - TestUtility.LogInformation("InitializeTestMachine::Dispose() End"); - } - } - - private void RollbackIISApplicationhostConfigFile() - { - if (IISConfigUtility.ApppHostTemporaryBackupFileExtention != null) - { - try - { - TestUtility.ResetHelper(ResetHelperMode.KillWorkerProcess); - } - catch - { - TestUtility.LogInformation("Failed to stop IIS worker processes"); - } - try - { - IISConfigUtility.RestoreAppHostConfig(restoreFromMasterBackupFile: false); - } - catch - { - TestUtility.LogInformation("Failed to rollback applicationhost.config"); - } - try - { - TestUtility.StartW3svc(); - } - catch - { - TestUtility.LogInformation("Failed to start w3svc"); - } - IISConfigUtility.ApppHostTemporaryBackupFileExtention = null; - } - } - - private void PreparePrivateANCMFiles() - { - var solutionRoot = GetSolutionDirectory(); - string outputPath = string.Empty; - _setupScriptPath = Path.Combine(solutionRoot, "tools"); - - // First try with release build - outputPath = Path.Combine(solutionRoot, "artifacts", "build", "AspNetCore", "bin", "Release"); - - // If release build is not available, try with debug 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", "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; check if there is any build issue!!!"); - } - - // - // NOTE: - // ANCM schema file can't be overwritten here - // If there is any schema change, that should be updated with installing setup or manually copied with the new schema file. - // - - if (TestFlags.Enabled(TestFlags.UseIISExpress)) - { - // - // Initialize 32 bit IisExpressAspnetcore_path - // - IisExpressAspnetcore_path = Path.Combine(outputPath, "x64", "aspnetcore.dll"); - IisExpressAspnetcore_X86_path = Path.Combine(outputPath, "Win32", "aspnetcore.dll"); - } - else // if use Full IIS server - { - bool updateSuccess = false; - for (int i = 0; i < 3; i++) - { - updateSuccess = false; - try - { - TestUtility.ResetHelper(ResetHelperMode.KillWorkerProcess); - TestUtility.ResetHelper(ResetHelperMode.StopW3svcStartW3svc); - Thread.Sleep(1000); - - // Copy private file on Inetsrv directory - TestUtility.FileCopy(Path.Combine(outputPath, "x64", "aspnetcore.dll"), FullIisAspnetcore_path, overWrite: true, ignoreExceptionWhileDeletingExistingFile: false); - - if (TestUtility.IsOSAmd64) - { - - // Copy 32bit private file on Inetsrv directory - TestUtility.FileCopy(Path.Combine(outputPath, "Win32", "aspnetcore.dll"), FullIisAspnetcore_X86_path, overWrite: true, ignoreExceptionWhileDeletingExistingFile: false); - } - updateSuccess = true; - } - catch - { - updateSuccess = false; - } - if (updateSuccess) - { - break; - } - } - if (!updateSuccess) - { - throw new ApplicationException("Failed to update aspnetcore.dll"); - } - - // update applicationhost.config for IIS server with the new private ASPNET Core file name - if (TestFlags.Enabled(TestFlags.UseFullIIS)) - { - using (var iisConfig = new IISConfigUtility(ServerType.IIS, null)) - { - iisConfig.AddModule("AspNetCoreModule", FullIisAspnetcore_path, null); - } - } - } - } - - 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}."); - } - } -} diff --git a/test/AspNetCoreModule.Test/Framework/TestUtility.cs b/test/AspNetCoreModule.Test/Framework/TestUtility.cs deleted file mode 100644 index dd2bd67c5b..0000000000 --- a/test/AspNetCoreModule.Test/Framework/TestUtility.cs +++ /dev/null @@ -1,966 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. 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.Management.Automation.Runspaces; -using System.Net.Http; -using System.Threading.Tasks; -using System.Net; -using System.Collections.ObjectModel; -using System.Management.Automation; - -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; - } - - /// - /// Retries every 1 sec for 60 times by default. - /// - /// - /// - /// - /// - public static async Task RetryRequest( - Func> 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 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 ( - Func verifier, - T arg, - Action 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( - Func verifier, - T1 arg1, - T2 arg2, - Action 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( - Func verifier, - T1 arg1, - T2 arg2, - T3 arg3, - Action 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); - } - LogInformation("ANCMTEST::RetryHelper Retrying " + retry); - 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, parameters); - } - } - public static void LogError(string format, params object[] parameters) - { - if (format != null) - { - Logger.LogError(format, parameters); - } - } - public static void LogInformation(string format, params object[] parameters) - { - if (format != null) - { - Logger.LogInformation(format, parameters); - } - } - - 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) - { - 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) - { - 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 string GetMakeCertPath() - { - string makecertExeFilePath = "makecert.exe"; - var makecertExeFilePaths = new Dictionary(); - makecertExeFilePaths.Add("default", Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles%"), "Windows Kits")); - if (IsOSAmd64) - { - makecertExeFilePaths.Add("wow64mode", Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%"), "Windows Kits")); - } - - foreach (var item in makecertExeFilePaths) - { - string[] files = null; - if (!Directory.Exists(item.Value)) - { - continue; - } - files = Directory.GetFiles(item.Value, "makecert.exe", SearchOption.AllDirectories); - - foreach (string makecert in files) - { - if (makecert.Contains("arm")) - { - // arm process version is skipped here - continue; - } - makecertExeFilePath = makecert; - try - { - TestUtility.RunCommand(makecertExeFilePath, null, true, true); - } - catch - { - continue; - } - break; - } - } - return makecertExeFilePath; - } - - 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 string RunPowershellScript(string scriptText) - { - IPEndPoint a = new IPEndPoint(0, 443); - - // create Powershell runspace - Runspace runspace = null; - try - { - runspace = RunspaceFactory.CreateRunspace(); - } - catch - { - LogInformation("Failed to instantiate powershell Runspace; if this is Win7, install Powershell 4.0 to fix this problem"); - throw new ApplicationException("Failed to instantiate powershell Runspace"); - } - - // open it - runspace.Open(); - - // create a pipeline and feed it the script text - Pipeline pipeline = runspace.CreatePipeline(); - pipeline.Commands.AddScript(scriptText); - - // add an extra command to transform the script output objects into nicely formatted strings - // remove this line to get the actual objects that the script returns. For example, the script - // "Get-Process" returns a collection of System.Diagnostics.Process instances. - pipeline.Commands.Add("Out-String"); - Collection results = null; - try - { - // execute the script - results = pipeline.Invoke(); - } - catch (System.Exception ex) - { - throw new Exception("Failed to run " + scriptText + " " + ex.ToString()); - } - - // close the runspace - runspace.Close(); - - // convert the script result into a single string - StringBuilder stringBuilder = new StringBuilder(); - foreach (PSObject obj in results) - { - stringBuilder.AppendLine(obj.ToString()); - } - - return stringBuilder.ToString().Trim(new char[] { ' ', '\r', '\n' }); - } - - public static void RunPowershellScript(string scriptText, string expectedResult, int retryCount = 3) - { - bool isReady = false; - string result = string.Empty; - - for (int i = 0; i < retryCount; i++) - { - try - { - result = TestUtility.RunPowershellScript(scriptText); - } - catch - { - result = "ExceptionError"; - } - - if (expectedResult != null) - { - if (expectedResult == result) - { - isReady = true; - break; - } - else - { - System.Threading.Thread.Sleep(1000); - } - } - else - { - isReady = true; - break; - } - } - if (!isReady) - { - throw new ApplicationException("Failed to execute command: " + scriptText + ", expected result: " + expectedResult + ", actual result = " + 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 GetApplicationEvent(int id, DateTime startFrom) - { - var result = new List(); - 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; - } - } -} diff --git a/test/AspNetCoreModule.Test/Framework/TestWebApplication.cs b/test/AspNetCoreModule.Test/Framework/TestWebApplication.cs deleted file mode 100644 index 83f0b03e32..0000000000 --- a/test/AspNetCoreModule.Test/Framework/TestWebApplication.cs +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. 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 GetUri() - { - return new Uri("http://" + _testSite.HostName + ":" + _testSite.TcpPort.ToString() + URL); - } - - public Uri GetUri(string subPath, int port = -1, string protocol = "http") - { - if (port == -1) - { - port = _testSite.TcpPort; - } - - string tempSubPath = string.Empty; - if (subPath != null) - { - tempSubPath = subPath; - if (!tempSubPath.StartsWith("/")) - { - tempSubPath = "/" + tempSubPath; - } - } - return new Uri(protocol + "://" + _testSite.HostName + ":" + port.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 arguments 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(fromfile)) - { - 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); - } - } -} \ No newline at end of file diff --git a/test/AspNetCoreModule.Test/Framework/TestWebSite.cs b/test/AspNetCoreModule.Test/Framework/TestWebSite.cs deleted file mode 100644 index 21e1c9cfb3..0000000000 --- a/test/AspNetCoreModule.Test/Framework/TestWebSite.cs +++ /dev/null @@ -1,536 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. 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)); - try - { - iisExpressProcess.Kill(); - iisExpressProcess.WaitForExit(); - iisExpressProcess.Close(); - } - catch - { - TestUtility.RunPowershellScript("stop-process -id " + _iisExpressPidBackup); - } - } - 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 string _postFix = null; - public string PostFix - { - get - { - return _postFix; - } - set - { - _postFix = value; - } - } - - public int _tcpPort = 8080; - public int TcpPort - { - get - { - return _tcpPort; - } - set - { - _tcpPort = value; - } - } - - private int _workerProcessID = 0; - public int WorkerProcessID - { - get - { - if (_workerProcessID == 0) - { - try - { - if (IisServerType == ServerType.IISExpress) - { - _workerProcessID = Convert.ToInt32(TestUtility.GetProcessWMIAttributeValue("iisexpress.exe", "Handle", null)); - } - else - { - _workerProcessID = Convert.ToInt32(TestUtility.GetProcessWMIAttributeValue("w3wp.exe", "Handle", null)); - } - } - catch - { - TestUtility.LogInformation("Failed to get process id of w3wp.exe"); - } - } - return _workerProcessID; - } - set - { - _workerProcessID = value; - } - } - - public string HostNameBinding - { - get - { - if (IisServerType == ServerType.IISExpress) - { - return "localhost"; - } - else - { - return ""; - } - } - } - - public ServerType IisServerType { get; set; } - public string IisExpressConfigPath { get; set; } - private int _siteId { get; set; } - private IISConfigUtility.AppPoolBitness _appPoolBitness { get; set; } - - public TestWebSite(IISConfigUtility.AppPoolBitness appPoolBitness, string loggerPrefix = "ANCMTest", bool startIISExpress = true, bool copyAllPublishedFiles = false, bool attachAppVerifier = false) - { - _appPoolBitness = appPoolBitness; - - // - // Initialize IisServerType - // - if (TestFlags.Enabled(TestFlags.UseFullIIS)) - { - IisServerType = ServerType.IIS; - } - else - { - IisServerType = ServerType.IISExpress; - } - - // - // Use localhost hostname for IISExpress - // - - - if (IisServerType == ServerType.IISExpress - && TestFlags.Enabled(TestFlags.Wow64BitMode)) - { - // - // In Wow64/IISExpress test context, always use 32 bit worker process - // - if (_appPoolBitness == IISConfigUtility.AppPoolBitness.noChange) - { - TestUtility.LogInformation("Warning!!! In Wow64, _appPoolBitness should be set with enable32bit"); - _appPoolBitness = IISConfigUtility.AppPoolBitness.enable32Bit; - } - } - - TestUtility.LogInformation("TestWebSite::TestWebSite() Start"); - - string solutionPath = InitializeTestMachine.GetSolutionDirectory(); - - if (IisServerType == 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; - string postfix = string.Empty; - - // repeat three times until getting the valid temporary directory path - for (int i = 0; i < 3; i++) - { - postfix = Path.GetRandomFileName(); - siteName = loggerPrefix.Replace(" ", "") + "_" + postfix; - siteRootPath = Path.Combine(InitializeTestMachine.TestRootDirectory, siteName); - if (!Directory.Exists(siteRootPath)) - { - break; - } - } - - TestUtility.DirectoryCopy(Path.Combine(solutionPath, "test", "WebRoot"), siteRootPath); - string aspnetCoreAppRootPath = Path.Combine(siteRootPath, "AspNetCoreApp"); - string srcPath = TestUtility.GetApplicationPath(); - - // copy http.config to the test site root directory and initialize iisExpressConfigPath with the path - if (IisServerType == ServerType.IISExpress) - { - IisExpressConfigPath = Path.Combine(siteRootPath, "http.config"); - TestUtility.FileCopy(Path.Combine(solutionPath, "test", "AspNetCoreModule.Test", "http.config"), IisExpressConfigPath); - } - - // - // Currently we use DotnetCore v2.0 - // - string publishPath = Path.Combine(srcPath, "bin", "Debug", "netcoreapp2.0", "publish"); - string publishPathOutput = Path.Combine(InitializeTestMachine.TestRootDirectory, "publishPathOutput"); - - // - // Publish aspnetcore app - // - if (_publishedAspnetCoreApp != true) - { - string argumentForDotNet = "publish " + srcPath + " --framework netcoreapp2.0"; - TestUtility.LogInformation("TestWebSite::TestWebSite() StandardTestApp is not published, trying to publish on the fly: dotnet.exe " + argumentForDotNet); - TestUtility.DeleteDirectory(publishPath); - TestUtility.RunCommand("dotnet", argumentForDotNet); - if (!File.Exists(Path.Combine(publishPath, "AspNetCoreModule.TestSites.Standard.dll"))) - { - throw new Exception("Failed to publish"); - } - TestUtility.DirectoryCopy(publishPath, publishPathOutput); - TestUtility.FileCopy(Path.Combine(publishPathOutput, "web.config"), Path.Combine(publishPathOutput, "web.config.bak")); - - // Adjust the arguments attribute value with IISConfigUtility from a temporary site - using (var iisConfig = new IISConfigUtility(IisServerType, IisExpressConfigPath)) - { - string tempSiteName = "ANCMTest_Temp"; - int tempId = InitializeTestMachine.SiteId - 1; - string argumentFileName = (new TestWebApplication("/", publishPathOutput, null)).GetArgumentFileName(); - if (string.IsNullOrEmpty(argumentFileName)) - { - argumentFileName = "AspNetCoreModule.TestSites.Standard.dll"; - } - iisConfig.CreateSite(tempSiteName, HostNameBinding, publishPathOutput, tempId, tempId); - iisConfig.SetANCMConfig(tempSiteName, "/", "arguments", Path.Combine(publishPathOutput, argumentFileName)); - iisConfig.DeleteSite(tempSiteName); - } - _publishedAspnetCoreApp = true; - } - - if (copyAllPublishedFiles) - { - // Copy all the files in the pubishpath to the standardAppRootPath - TestUtility.DirectoryCopy(publishPath, aspnetCoreAppRootPath); - TestUtility.FileCopy(Path.Combine(publishPathOutput, "web.config.bak"), Path.Combine(aspnetCoreAppRootPath, "web.config")); - } - else - { - // Copy only web.config file, which points to the shared publishPathOutput, to the standardAppRootPath - TestUtility.CreateDirectory(aspnetCoreAppRootPath); - TestUtility.FileCopy(Path.Combine(publishPathOutput, "web.config"), Path.Combine(aspnetCoreAppRootPath, "web.config")); - } - - int tcpPort = InitializeTestMachine.SiteId++; - _siteId = tcpPort; - - // - // initialize class member variables - // - string appPoolName = null; - if (IisServerType == ServerType.IIS) - { - appPoolName = "AspNetCoreModuleTestAppPool"; - } - else if (IisServerType == ServerType.IISExpress) - { - appPoolName = "Clr4IntegratedAppPool"; - } - - // Initialize member variables - _hostName = "localhost"; - _siteName = siteName; - _postFix = postfix; - _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"); - - // - // Create site and apps - // - using (var iisConfig = new IISConfigUtility(IisServerType, IisExpressConfigPath)) - { - // Create apppool - if (IisServerType == ServerType.IIS) - { - iisConfig.CreateAppPool(appPoolName); - - // Switch bitness - if (TestUtility.IsOSAmd64 && appPoolBitness == IISConfigUtility.AppPoolBitness.enable32Bit) - { - iisConfig.SetAppPoolSetting(appPoolName, "enable32BitAppOnWin64", true); - } - } - - if (TestFlags.Enabled(TestFlags.UsePrivateANCM) && IisServerType == ServerType.IISExpress) - { - if (TestUtility.IsOSAmd64) - { - if (_appPoolBitness == IISConfigUtility.AppPoolBitness.enable32Bit) - { - iisConfig.AddModule("AspNetCoreModule", (InitializeTestMachine.IisExpressAspnetcore_X86_path), null); - } - else - { - iisConfig.AddModule("AspNetCoreModule", (InitializeTestMachine.IisExpressAspnetcore_path), null); - } - } - else - { - iisConfig.AddModule("AspNetCoreModule", (InitializeTestMachine.IisExpressAspnetcore_path), null); - } - } - - iisConfig.CreateSite(siteName, HostNameBinding, RootAppContext.PhysicalPath, _siteId, 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 (startIISExpress) - { - // clean up IISExpress before starting a new instance - TestUtility.KillIISExpressProcess(); - - StartIISExpress(); - - // send a startup request to IISExpress instance to make sure that it is fully ready to use before starting actual test scenarios - TestUtility.RunPowershellScript("( invoke-webrequest http://localhost:" + TcpPort + " ).StatusCode", "200"); - } - TestUtility.LogInformation("TestWebSite::TestWebSite() End"); - } - - public void StartIISExpress() - { - if (IisServerType == ServerType.IIS) - { - return; - } - - // reset workerProcessID - this.WorkerProcessID = 0; - - 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); - } - - public void AttachAppverifier() - { - string cmdline; - string processName = "iisexpress.exe"; - if (IisServerType == ServerType.IIS) - { - processName = "w3wp.exe"; - } - string argument = "-enable Heaps COM RPC Handles Locks Memory TLS Exceptions Threadpool Leak SRWLock -for " + processName; - if (Directory.Exists(Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%")) && _appPoolBitness == IISConfigUtility.AppPoolBitness.enable32Bit) - { - cmdline = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "syswow64", "appverif.exe"); - if (!File.Exists(cmdline)) - { - throw new ApplicationException("Not found :" + cmdline + "; this test requires appverif.exe."); - } - } - else - { - cmdline = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "system32", "appverif.exe"); - if (!File.Exists(cmdline)) - { - throw new ApplicationException("Not found :" + cmdline + "; this test requires appverif.exe."); - } - } - - try - { - TestUtility.LogInformation("Configure Appverifier: " + cmdline + " " + argument); - TestUtility.RunCommand(cmdline, argument, true, false); - } - catch - { - throw new ApplicationException("Failed to configure Appverifier"); - } - } - - public void AttachWinDbg(int processIdOfWorkerProcess) - { - string processName = "iisexpress.exe"; - string debuggerCmdline; - if (IisServerType == ServerType.IIS) - { - processName = "w3wp.exe"; - } - string argument = "-enable Heaps COM RPC Handles Locks Memory TLS Exceptions Threadpool Leak SRWLock -for " + processName; - if (Directory.Exists(Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%")) && _appPoolBitness == IISConfigUtility.AppPoolBitness.enable32Bit) - { - debuggerCmdline = Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles%"), "Debugging Tools for Windows (x64)", "wow64", "windbg.exe"); - if (!File.Exists(debuggerCmdline)) - { - throw new ApplicationException("Not found :" + debuggerCmdline + "; this test requires windbg.exe."); - } - } - else - { - if (Directory.Exists(Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%"))) - { - debuggerCmdline = Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles%"), "Debugging Tools for Windows (x64)", "windbg.exe"); - } - else - { - debuggerCmdline = Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles%"), "Debugging Tools for Windows (x86)", "windbg.exe"); - } - if (!File.Exists(debuggerCmdline)) - { - throw new ApplicationException("Not found :" + debuggerCmdline + "; this test requires windbg.exe."); - } - } - - try - { - TestUtility.RunCommand(debuggerCmdline, " -g -G -p " + processIdOfWorkerProcess.ToString(), true, false); - System.Threading.Thread.Sleep(3000); - } - catch - { - throw new ApplicationException("Failed to attach debuger"); - } - } - - public void DetachAppverifier() - { - try - { - string cmdline; - string processName = "iisexpress.exe"; - string debuggerCmdline; - if (IisServerType == ServerType.IIS) - { - processName = "w3wp.exe"; - } - - string argument = "-disable * -for " + processName; - if (Directory.Exists(Environment.ExpandEnvironmentVariables("%ProgramFiles(x86)%")) && _appPoolBitness == IISConfigUtility.AppPoolBitness.enable32Bit) - { - cmdline = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "syswow64", "appverif.exe"); - if (!File.Exists(cmdline)) - { - throw new ApplicationException("Not found :" + cmdline); - } - debuggerCmdline = Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles%"), "Debugging Tools for Windows (x64)", "wow64", "windbg.exe"); - if (!File.Exists(debuggerCmdline)) - { - throw new ApplicationException("Not found :" + debuggerCmdline); - } - } - else - { - cmdline = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "system32", "appverif.exe"); - if (!File.Exists(cmdline)) - { - throw new ApplicationException("Not found :" + cmdline); - } - debuggerCmdline = Path.Combine(Environment.ExpandEnvironmentVariables("%ProgramFiles%"), "Debugging Tools for Windows (x64)", "windbg.exe"); - if (!File.Exists(debuggerCmdline)) - { - throw new ApplicationException("Not found :" + debuggerCmdline); - } - } - TestUtility.RunCommand(cmdline, argument, true, false); - } - catch - { - TestUtility.LogInformation("Failed to detach Appverifier"); - } - } - } -} diff --git a/test/AspNetCoreModule.Test/FunctionalTest.cs b/test/AspNetCoreModule.Test/FunctionalTest.cs deleted file mode 100644 index 0268367dd0..0000000000 --- a/test/AspNetCoreModule.Test/FunctionalTest.cs +++ /dev/null @@ -1,370 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using AspNetCoreModule.Test.Framework; -using Microsoft.AspNetCore.Testing.xunit; -using System; -using System.Threading.Tasks; -using Xunit; - -namespace AspNetCoreModule.Test -{ - public class FunctionalTest : FunctionalTestHelper, IClassFixture - { - private const string ANCMTestCondition = TestFlags.SkipTest; - //private const string ANCMTestCondition = TestFlags.RunAsAdministrator; - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - public async void BasicTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - await DoBasicTest(appPoolBitness); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [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); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 25, 19, false)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 25, 19, true)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, 25, 19, false)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, 25, 19, true)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 5, 4, true)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 5, 4, false)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, 5, 4, true)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, 5, 4, false)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 0, 0, false)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, 0, 0, true)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, 0, 0, false)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, 0, 0, true)] - public Task ShutdownTimeLimitTest(IISConfigUtility.AppPoolBitness appPoolBitness, int valueOfshutdownTimeLimit, int expectedClosingTime, bool isGraceFullShutdownEnabled) - { - return DoShutdownTimeLimitTest(appPoolBitness, valueOfshutdownTimeLimit, expectedClosingTime, isGraceFullShutdownEnabled); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [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); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - public Task RecycleApplicationAfterBackendProcessBeingKilled(IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoRecycleApplicationAfterBackendProcessBeingKilled(appPoolBitness); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - public Task RecycleApplicationAfterW3WPProcessBeingKilled(IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoRecycleApplicationAfterW3WPProcessBeingKilled(appPoolBitness); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - public Task RecycleApplicationAfterWebConfigUpdated(IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoRecycleApplicationAfterWebConfigUpdated(appPoolBitness); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - public Task RecycleApplicationWithURLRewrite(IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoRecycleApplicationWithURLRewrite(appPoolBitness); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - public Task RecycleParentApplicationWithURLRewrite(IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoRecycleParentApplicationWithURLRewrite(appPoolBitness); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData("ANCMTestBar", "bar", "bar", IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData("ASPNETCORE_HOSTINGSTARTUPASSEMBLIES", "NA", "Microsoft.AspNetCore.Server.IISIntegration", IISConfigUtility.AppPoolBitness.noChange)] - [InlineData("ASPNETCORE_HOSTINGSTARTUPASSEMBLIES", "newValue", "newValue", IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData("ASPNETCORE_IIS_HTTPAUTH", "anonymous;", "anonymous;", IISConfigUtility.AppPoolBitness.noChange)] - [InlineData("ASPNETCORE_IIS_HTTPAUTH", "basic;anonymous;", "basic;anonymous;", IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData("ASPNETCORE_IIS_HTTPAUTH", "windows;anonymous;", "windows;anonymous;", IISConfigUtility.AppPoolBitness.noChange)] - [InlineData("ASPNETCORE_IIS_HTTPAUTH", "windows;basic;anonymous;", "windows;basic;anonymous;", IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData("ASPNETCORE_IIS_HTTPAUTH", "ignoredValue", "anonymous;", IISConfigUtility.AppPoolBitness.noChange)] - public Task EnvironmentVariablesTest(string environmentVariableName, string environmentVariableValue, string expectedEnvironmentVariableValue, IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoEnvironmentVariablesTest(environmentVariableName, environmentVariableValue, expectedEnvironmentVariableValue, appPoolBitness); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - public Task AppOfflineTestWithRenaming(IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoAppOfflineTestWithRenaming(appPoolBitness); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - public Task AppOfflineTestWithUrlRewriteAndDeleting(IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoAppOfflineTestWithUrlRewriteAndDeleting(appPoolBitness); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [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); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - public Task DisableStartUpErrorPageTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoDisableStartUpErrorPageTest(appPoolBitness); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [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); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [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); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - public Task StdoutLogEnabledTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoStdoutLogEnabledTest(appPoolBitness); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [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); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [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); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [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); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - public Task CachingTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoCachingTest(appPoolBitness); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - public Task SendHTTPSRequestTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoSendHTTPSRequestTest(appPoolBitness); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, "MS-ASPNETCORE", "f")] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, "mS-ASPNETCORE", "fo")] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, "MS-ASPNETCORE-", "foo")] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, "mS-ASPNETCORE-f", "fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo")] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, "MS-ASPNETCORE-foo", "foo")] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, "MS-ASPNETCORE-foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo", "bar")] - public Task FilterOutMSRequestHeadersTest(IISConfigUtility.AppPoolBitness appPoolBitness, string requestHeader, string requestHeaderValue) - { - return DoFilterOutMSRequestHeadersTest(appPoolBitness, requestHeader, requestHeaderValue); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, true)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, true)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, false)] - public Task ClientCertificateMappingTest(IISConfigUtility.AppPoolBitness appPoolBitness, bool useHTTPSMiddleWare) - { - return DoClientCertificateMappingTest(appPoolBitness, useHTTPSMiddleWare); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, false, DoAppVerifierTest_StartUpMode.UseGracefulShutdown, DoAppVerifierTest_ShutDownMode.RecycleAppPool, 1)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, false, DoAppVerifierTest_StartUpMode.DontUseGracefulShutdown, DoAppVerifierTest_ShutDownMode.RecycleAppPool, 1)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, false, DoAppVerifierTest_StartUpMode.UseGracefulShutdown, DoAppVerifierTest_ShutDownMode.StopAndStartAppPool, 1)] - public Task AppVerifierTest(IISConfigUtility.AppPoolBitness appPoolBitness, bool shutdownTimeout, DoAppVerifierTest_StartUpMode startUpMode, DoAppVerifierTest_ShutDownMode shutDownMode, int repeatCount) - { - return DoAppVerifierTest(appPoolBitness, shutdownTimeout, startUpMode, shutDownMode, repeatCount); - } - - ////////////////////////////////////////////////////////// - // NOTE: below test scenarios are not valid for Win7 OS - ////////////////////////////////////////////////////////// - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - public Task WebSocketErrorhandlingTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoWebSocketErrorhandlingTest(appPoolBitness); - } - - ////////////////////////////////////////////////////////// - // NOTE: below test scenarios are not valid for Win7 OS - ////////////////////////////////////////////////////////// - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [OSSkipCondition(OperatingSystems.Windows, WindowsVersions.Win7, SkipReason = "IIS does not support Websocket on Win7")] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, "abcdefghijklmnopqrstuvwxyz0123456789")] - [InlineData(IISConfigUtility.AppPoolBitness.noChange, "a")] - // Test reliablitiy issue with lenghty data; disabled until the reason of the test issue is figured out - //[InlineData(IISConfigUtility.AppPoolBitness.enable32Bit, "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789")] - public Task WebSocketTest(IISConfigUtility.AppPoolBitness appPoolBitness, string testData) - { - return DoWebSocketTest(appPoolBitness, testData); - } - - [ConditionalTheory] - [ANCMTestFlags(ANCMTestCondition)] - [OSSkipCondition(OperatingSystems.Linux)] - [OSSkipCondition(OperatingSystems.MacOSX)] - [OSSkipCondition(OperatingSystems.Windows, WindowsVersions.Win7, SkipReason = "WAS does not handle private memory limitation with Job object on Win7")] - [InlineData(IISConfigUtility.AppPoolBitness.enable32Bit)] - [InlineData(IISConfigUtility.AppPoolBitness.noChange)] - public Task RecylingAppPoolTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - return DoRecylingAppPoolTest(appPoolBitness); - } - } -} \ No newline at end of file diff --git a/test/AspNetCoreModule.Test/FunctionalTestHelper.cs b/test/AspNetCoreModule.Test/FunctionalTestHelper.cs deleted file mode 100644 index 4094e3f477..0000000000 --- a/test/AspNetCoreModule.Test/FunctionalTestHelper.cs +++ /dev/null @@ -1,2306 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using AspNetCoreModule.Test.Framework; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Threading.Tasks; -using Microsoft.Net.Http.Headers; -using Xunit; -using Xunit.Sdk; -using System.Diagnostics; -using System.Net; -using System.Threading; -using AspNetCoreModule.Test.WebSocketClient; -using System.Text; -using System.IO; -using System.Security.Principal; -using System.IO.Compression; -using Microsoft.AspNetCore.Testing.xunit; - -namespace AspNetCoreModule.Test -{ - [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] - public class ANCMTestFlags : Attribute, ITestCondition - { - private readonly string _attributeValue; - public ANCMTestFlags(string attributeValue) - { - _attributeValue = attributeValue.ToString(); - } - - public bool IsMet - { - get - { - if (_attributeValue == TestFlags.SkipTest) - { - AdditionalInfo = TestFlags.SkipTest + " is set"; - return false; - } - - if (_attributeValue == TestFlags.RequireRunAsAdministrator - && !TestFlags.Enabled(TestFlags.RunAsAdministrator)) - { - AdditionalInfo = _attributeValue + " is not belong to the given global test context(" + InitializeTestMachine.GlobalTestFlags + ")"; - return false; - } - return true; - } - } - - public string SkipReason - { - get - { - return $"Skip condition: ANCMTestFlags: this test case is skipped becauset {AdditionalInfo}."; - } - } - - public string AdditionalInfo { get; set; } - } - - public class FunctionalTestHelper - { - public FunctionalTestHelper() - { - } - - private const int _repeatCount = 3; - - public static async Task DoBasicTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoBasicTest")) - { - string backendProcessId_old = null; - - DateTime startTime = DateTime.Now; - Thread.Sleep(3000); - - string backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - Assert.NotEqual(backendProcessId_old, backendProcessId); - var backendProcess = Process.GetProcessById(Convert.ToInt32(backendProcessId)); - Assert.Equal(backendProcess.ProcessName.ToLower().Replace(".exe", ""), testSite.AspNetCoreApp.GetProcessFileName().ToLower().Replace(".exe", "")); - - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMStartEvent(arg1, arg2), startTime, backendProcessId)); - - var httpClientHandler = new HttpClientHandler(); - var httpClient = new HttpClient(httpClientHandler) - { - BaseAddress = testSite.AspNetCoreApp.GetUri(), - Timeout = TimeSpan.FromSeconds(5), - }; - - // Invoke given test scenario function - await CheckChunkedAsync(httpClient, testSite.AspNetCoreApp); - } - } - - public static async Task DoRecycleApplicationAfterBackendProcessBeingKilled(IISConfigUtility.AppPoolBitness appPoolBitness) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoRecycleApplicationAfterBackendProcessBeingKilled")) - { - string backendProcessId_old = null; - const int repeatCount = 3; - for (int i = 0; i < repeatCount; i++) - { - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - DateTime startTime = DateTime.Now; - Thread.Sleep(1000); - - string backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - Assert.NotEqual(backendProcessId_old, backendProcessId); - backendProcessId_old = backendProcessId; - var backendProcess = Process.GetProcessById(Convert.ToInt32(backendProcessId)); - Assert.Equal(backendProcess.ProcessName.ToLower().Replace(".exe", ""), testSite.AspNetCoreApp.GetProcessFileName().ToLower().Replace(".exe", "")); - - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMStartEvent(arg1, arg2), startTime, backendProcessId)); - backendProcess.Kill(); - Thread.Sleep(500); - } - } - } - - public static async Task DoRecycleApplicationAfterW3WPProcessBeingKilled(IISConfigUtility.AppPoolBitness appPoolBitness) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoRecycleApplicationAfterW3WPProcessBeingKilled")) - { - string appDllFileName = testSite.AspNetCoreApp.GetArgumentFileName(); - - if (testSite.IisServerType == ServerType.IISExpress) - { - TestUtility.LogInformation("This test is not valid for IISExpress server type"); - return; - } - - string backendProcessId_old = null; - const int repeatCount = 3; - for (int i = 0; i < repeatCount; i++) - { - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - DateTime startTime = DateTime.Now; - Thread.Sleep(1000); - - string backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - Assert.NotEqual(backendProcessId_old, backendProcessId); - backendProcessId_old = backendProcessId; - var backendProcess = Process.GetProcessById(Convert.ToInt32(backendProcessId)); - Assert.Equal(backendProcess.ProcessName.ToLower().Replace(".exe", ""), testSite.AspNetCoreApp.GetProcessFileName().ToLower().Replace(".exe", "")); - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMStartEvent(arg1, arg2), startTime, backendProcessId)); - - // get process id of IIS worker process (w3wp.exe) - string userName = testSite.SiteName; - int processIdOfWorkerProcess = Convert.ToInt32(TestUtility.GetProcessWMIAttributeValue("w3wp.exe", "Handle", userName)); - var workerProcess = Process.GetProcessById(Convert.ToInt32(processIdOfWorkerProcess)); - workerProcess.Kill(); - - Thread.Sleep(500); - - // Verify the application file can be removed after worker process is stopped - testSite.AspNetCoreApp.BackupFile(appDllFileName); - testSite.AspNetCoreApp.DeleteFile(appDllFileName); - testSite.AspNetCoreApp.RestoreFile(appDllFileName); - } - } - } - - public static async Task DoRecycleApplicationAfterWebConfigUpdated(IISConfigUtility.AppPoolBitness appPoolBitness) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoRecycleApplicationAfterWebConfigUpdated")) - { - string backendProcessId_old = null; - string appDllFileName = testSite.AspNetCoreApp.GetArgumentFileName(); - - const int repeatCount = 3; - for (int i = 0; i < repeatCount; i++) - { - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - DateTime startTime = DateTime.Now; - Thread.Sleep(1000); - - string backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - var backendProcess = Process.GetProcessById(Convert.ToInt32(backendProcessId)); - Assert.NotEqual(backendProcessId_old, backendProcessId); - backendProcessId_old = backendProcessId; - Assert.Equal(backendProcess.ProcessName.ToLower().Replace(".exe", ""), testSite.AspNetCoreApp.GetProcessFileName().ToLower().Replace(".exe", "")); - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMStartEvent(arg1, arg2), startTime, backendProcessId)); - testSite.AspNetCoreApp.MoveFile("web.config", "_web.config"); - Thread.Sleep(500); - testSite.AspNetCoreApp.MoveFile("_web.config", "web.config"); - - // Verify the application file can be removed after backend process is restarted - testSite.AspNetCoreApp.BackupFile(appDllFileName); - testSite.AspNetCoreApp.DeleteFile(appDllFileName); - testSite.AspNetCoreApp.RestoreFile(appDllFileName); - } - - // restore web.config - testSite.AspNetCoreApp.RestoreFile("web.config"); - - } - } - - public static async Task DoRecycleApplicationWithURLRewrite(IISConfigUtility.AppPoolBitness appPoolBitness) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoRecycleApplicationWithURLRewrite")) - { - string backendProcessId_old = null; - const int repeatCount = 3; - for (int i = 0; i < repeatCount; i++) - { - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - DateTime startTime = DateTime.Now; - Thread.Sleep(1100); - - string urlForUrlRewrite = testSite.URLRewriteApp.URL + "/Rewrite2/" + testSite.AspNetCoreApp.URL + "/GetProcessId"; - string backendProcessId = (await SendReceive(testSite.RootAppContext.GetUri(urlForUrlRewrite))).ResponseBody; - var backendProcess = Process.GetProcessById(Convert.ToInt32(backendProcessId)); - Assert.NotEqual(backendProcessId_old, backendProcessId); - backendProcessId_old = backendProcessId; - Assert.Equal(backendProcess.ProcessName.ToLower().Replace(".exe", ""), testSite.AspNetCoreApp.GetProcessFileName().ToLower().Replace(".exe", "")); - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMStartEvent(arg1, arg2), startTime, backendProcessId)); - - testSite.AspNetCoreApp.MoveFile("web.config", "_web.config"); - Thread.Sleep(500); - testSite.AspNetCoreApp.MoveFile("_web.config", "web.config"); - } - - // restore web.config - testSite.AspNetCoreApp.RestoreFile("web.config"); - - } - } - - public static async Task DoRecycleParentApplicationWithURLRewrite(IISConfigUtility.AppPoolBitness appPoolBitness) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoRecycleParentApplicationWithURLRewrite")) - { - string backendProcessId_old = null; - const int repeatCount = 3; - for (int i = 0; i < repeatCount; i++) - { - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - DateTime startTime = DateTime.Now; - Thread.Sleep(1000); - - string urlForUrlRewrite = testSite.URLRewriteApp.URL + "/Rewrite2/" + testSite.AspNetCoreApp.URL + "/GetProcessId"; - string backendProcessId = (await SendReceive(testSite.RootAppContext.GetUri(urlForUrlRewrite))).ResponseBody; - var backendProcess = Process.GetProcessById(Convert.ToInt32(backendProcessId)); - Assert.NotEqual(backendProcessId_old, backendProcessId); - backendProcessId_old = backendProcessId; - Assert.Equal(backendProcess.ProcessName.ToLower().Replace(".exe", ""), testSite.AspNetCoreApp.GetProcessFileName().ToLower().Replace(".exe", "")); - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMStartEvent(arg1, arg2), startTime, backendProcessId)); - testSite.RootAppContext.MoveFile("web.config", "_web.config"); - Thread.Sleep(500); - testSite.RootAppContext.MoveFile("_web.config", "web.config"); - } - - // restore web.config - testSite.RootAppContext.RestoreFile("web.config"); - } - } - - public static async Task DoEnvironmentVariablesTest(string environmentVariableName, string environmentVariableValue, string expectedEnvironmentVariableValue, IISConfigUtility.AppPoolBitness appPoolBitness) - { - if (environmentVariableName == null) - { - throw new InvalidDataException("envrionmentVarialbeName is null"); - } - using (var testSite = new TestWebSite(appPoolBitness, "DoEnvironmentVariablesTest")) - { - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - DateTime startTime = DateTime.Now; - Thread.Sleep(500); - - string totalNumber = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetEnvironmentVariables"))).ResponseBody; - Assert.True(totalNumber == (await SendReceive(testSite.AspNetCoreApp.GetUri("GetEnvironmentVariables"))).ResponseBody); - - iisConfig.SetANCMConfig( - testSite.SiteName, - testSite.AspNetCoreApp.Name, - "environmentVariable", - new string[] { "ANCMTestFoo", "foo" } - ); - - Thread.Sleep(500); - - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - int expectedValue = Convert.ToInt32(totalNumber) + 1; - string totalResult = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetEnvironmentVariables"))).ResponseBody; - Assert.True(expectedValue.ToString() == (await SendReceive(testSite.AspNetCoreApp.GetUri("GetEnvironmentVariables"))).ResponseBody); - - bool setEnvironmentVariableConfiguration = true; - - // Set authentication for ASPNETCORE_IIS_HTTPAUTH test scenarios - if (environmentVariableName == "ASPNETCORE_IIS_HTTPAUTH" && environmentVariableValue != "ignoredValue") - { - setEnvironmentVariableConfiguration = false; - bool windows = false; - bool basic = false; - bool anonymous = false; - if (environmentVariableValue.Contains("windows;")) - { - windows = true; - } - if (environmentVariableValue.Contains("basic;")) - { - basic = true; - } - if (environmentVariableValue.Contains("anonymous;")) - { - anonymous = true; - } - iisConfig.EnableIISAuthentication(testSite.SiteName, windows, basic, anonymous); - } - - if (environmentVariableValue == "NA" || environmentVariableValue == null) - { - setEnvironmentVariableConfiguration = false; - } - - // Add a new environment variable - if (setEnvironmentVariableConfiguration) - { - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "environmentVariable", new string[] { environmentVariableName, environmentVariableValue }); - - // Adjust the new expected total number of environment variables - if (environmentVariableName != "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES" && - environmentVariableName != "ASPNETCORE_IIS_HTTPAUTH") - { - expectedValue++; - } - } - Thread.Sleep(500); - - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - totalResult = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetEnvironmentVariables"))).ResponseBody; - Assert.True(expectedValue.ToString() == totalResult); - Assert.True("foo" == (await SendReceive(testSite.AspNetCoreApp.GetUri("ExpandEnvironmentVariablesANCMTestFoo"))).ResponseBody); - Assert.True(expectedEnvironmentVariableValue == (await SendReceive(testSite.AspNetCoreApp.GetUri("ExpandEnvironmentVariables" + environmentVariableName))).ResponseBody); - - // Verify other common environment variables - string temp = (await SendReceive(testSite.AspNetCoreApp.GetUri("DumpEnvironmentVariables"))).ResponseBody; - Assert.Contains("ASPNETCORE_PORT", temp); - Assert.Contains("ASPNETCORE_APPL_PATH", temp); - Assert.Contains("ASPNETCORE_IIS_HTTPAUTH", temp); - Assert.Contains("ASPNETCORE_TOKEN", temp); - Assert.Contains("ASPNETCORE_HOSTINGSTARTUPASSEMBLIES", temp); - - // Verify other inherited environment variables - Assert.Contains("PROCESSOR_ARCHITECTURE", temp); - Assert.Contains("USERNAME", temp); - Assert.Contains("USERDOMAIN", temp); - Assert.Contains("USERPROFILE", temp); - } - - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoAppOfflineTestWithRenaming(IISConfigUtility.AppPoolBitness appPoolBitness) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoAppOfflineTestWithRenaming")) - { - string backendProcessId_old = null; - string fileContent = "BackEndAppOffline"; - string appDllFileName = testSite.AspNetCoreApp.GetArgumentFileName(); - - testSite.AspNetCoreApp.CreateFile(new string[] { fileContent }, "App_Offline.Htm"); - - for (int i = 0; i < _repeatCount; i++) - { - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - DateTime startTime = DateTime.Now; - Thread.Sleep(1100); - - // verify 503 - await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseBody: fileContent + "\r\n", expectedResponseStatus: HttpStatusCode.ServiceUnavailable); - - // Verify the application file can be removed under app_offline mode - testSite.AspNetCoreApp.BackupFile(appDllFileName); - testSite.AspNetCoreApp.DeleteFile(appDllFileName); - testSite.AspNetCoreApp.RestoreFile(appDllFileName); - - // rename app_offline.htm to _app_offline.htm and verify 200 - testSite.AspNetCoreApp.MoveFile("App_Offline.Htm", "_App_Offline.Htm"); - string backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - var backendProcess = Process.GetProcessById(Convert.ToInt32(backendProcessId)); - Assert.Equal(backendProcess.ProcessName.ToLower().Replace(".exe", ""), testSite.AspNetCoreApp.GetProcessFileName().ToLower().Replace(".exe", "")); - Assert.NotEqual(backendProcessId_old, backendProcessId); - backendProcessId_old = backendProcessId; - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMStartEvent(arg1, arg2), startTime, backendProcessId)); - - // rename back to app_offline.htm - testSite.AspNetCoreApp.MoveFile("_App_Offline.Htm", "App_Offline.Htm"); - } - } - } - - public static async Task DoAppOfflineTestWithUrlRewriteAndDeleting(IISConfigUtility.AppPoolBitness appPoolBitness) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoAppOfflineTestWithUrlRewriteAndDeleting")) - { - string backendProcessId_old = null; - string fileContent = "BackEndAppOffline2"; - string appDllFileName = testSite.AspNetCoreApp.GetArgumentFileName(); - - testSite.AspNetCoreApp.CreateFile(new string[] { fileContent }, "App_Offline.Htm"); - - for (int i = 0; i < _repeatCount; i++) - { - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - DateTime startTime = DateTime.Now; - Thread.Sleep(1100); - - // verify 503 - string urlForUrlRewrite = testSite.URLRewriteApp.URL + "/Rewrite2/" + testSite.AspNetCoreApp.URL + "/GetProcessId"; - await SendReceive(testSite.RootAppContext.GetUri(urlForUrlRewrite), expectedResponseBody: fileContent + "\r\n", expectedResponseStatus: HttpStatusCode.ServiceUnavailable); - - // Verify the application file can be removed under app_offline mode - testSite.AspNetCoreApp.BackupFile(appDllFileName); - testSite.AspNetCoreApp.DeleteFile(appDllFileName); - testSite.AspNetCoreApp.RestoreFile(appDllFileName); - - // delete app_offline.htm and verify 200 - testSite.AspNetCoreApp.DeleteFile("App_Offline.Htm"); - string backendProcessId = (await SendReceive(testSite.RootAppContext.GetUri(urlForUrlRewrite))).ResponseBody; - var backendProcess = Process.GetProcessById(Convert.ToInt32(backendProcessId)); - Assert.Equal(backendProcess.ProcessName.ToLower().Replace(".exe", ""), testSite.AspNetCoreApp.GetProcessFileName().ToLower().Replace(".exe", "")); - Assert.NotEqual(backendProcessId_old, backendProcessId); - backendProcessId_old = backendProcessId; - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMStartEvent(arg1, arg2), startTime, backendProcessId)); - - // create app_offline.htm again - testSite.AspNetCoreApp.CreateFile(new string[] { fileContent }, "App_Offline.Htm"); - } - } - } - - public static async Task DoPostMethodTest(IISConfigUtility.AppPoolBitness appPoolBitness, string testData) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoPostMethodTest")) - { - var postFormData = new[] - { - new KeyValuePair("FirstName", "Mickey"), - new KeyValuePair("LastName", "Mouse"), - new KeyValuePair("TestData", testData), - }; - var expectedResponseBody = "FirstName=Mickey&LastName=Mouse&TestData=" + testData; - await SendReceive(testSite.AspNetCoreApp.GetUri("EchoPostData"), postData: postFormData, expectedResponseBody: expectedResponseBody); - } - } - - public static async Task DoDisableStartUpErrorPageTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - int errorEventId = 1000; - string errorMessageContainThis = "bogus"; // bogus path value to cause 502.3 error - - using (var testSite = new TestWebSite(appPoolBitness, "DoDisableStartUpErrorPageTest")) - { - testSite.AspNetCoreApp.DeleteFile("custom502-3.htm"); - string curstomErrorMessage = "ANCMTest502-3"; - testSite.AspNetCoreApp.CreateFile(new string[] { curstomErrorMessage }, "custom502-3.htm"); - - Thread.Sleep(500); - - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - DateTime startTime = DateTime.Now; - Thread.Sleep(500); - - iisConfig.ConfigureCustomLogging(testSite.SiteName, testSite.AspNetCoreApp.Name, 502, 3, "custom502-3.htm"); - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "disableStartUpErrorPage", true); - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "processPath", errorMessageContainThis); - - var responseBody = (await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseStatus:HttpStatusCode.BadGateway)).ResponseBody; - responseBody = responseBody.Replace("\r", "").Replace("\n", "").Trim(); - Assert.True(responseBody == curstomErrorMessage); - - // verify event error log - Assert.True(TestUtility.RetryHelper((arg1, arg2, arg3) => VerifyApplicationEventLog(arg1, arg2, arg3), errorEventId, startTime, errorMessageContainThis)); - - // try again after setting "false" value - startTime = DateTime.Now; - Thread.Sleep(500); - - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "disableStartUpErrorPage", false); - Thread.Sleep(500); - - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - responseBody = (await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseStatus:HttpStatusCode.BadGateway)).ResponseBody; - Assert.Contains("808681", responseBody); - - // verify event error log - Assert.True(TestUtility.RetryHelper((arg1, arg2, arg3) => VerifyApplicationEventLog(arg1, arg2, arg3), errorEventId, startTime, errorMessageContainThis)); - } - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoRapidFailsPerMinuteTest(IISConfigUtility.AppPoolBitness appPoolBitness, int valueOfRapidFailsPerMinute) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoRapidFailsPerMinuteTest")) - { - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - bool rapidFailsTriggered = false; - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "rapidFailsPerMinute", valueOfRapidFailsPerMinute); - - string backendProcessId_old = null; - const int repeatCount = 10; - - DateTime startTime = DateTime.Now; - Thread.Sleep(50); - - for (int i = 0; i < repeatCount; i++) - { - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - DateTime startTimeInsideLooping = DateTime.Now; - Thread.Sleep(50); - - var sendReceiveContext = await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId")); - var statusCode = sendReceiveContext.ResponseStatus; - - if (statusCode != HttpStatusCode.OK.ToString()) - { - Assert.True(i >= valueOfRapidFailsPerMinute, i.ToString() + "is greater than or equals to " + valueOfRapidFailsPerMinute.ToString()); - Assert.True(i < valueOfRapidFailsPerMinute + 3, i.ToString() + "is less than " + (valueOfRapidFailsPerMinute + 3).ToString()); - rapidFailsTriggered = true; - break; - } - - string backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - Assert.NotEqual(backendProcessId_old, backendProcessId); - backendProcessId_old = backendProcessId; - var backendProcess = Process.GetProcessById(Convert.ToInt32(backendProcessId)); - Assert.Equal(backendProcess.ProcessName.ToLower().Replace(".exe", ""), testSite.AspNetCoreApp.GetProcessFileName().ToLower().Replace(".exe", "")); - - //Verifying EventID of new backend process is not necesssary and removed in order to fix some test reliablity issues - //Thread.Sleep(3000); - //Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMStartEvent(arg1, arg2), startTimeInsideLooping, backendProcessId), "Verifying event log of new backend process id " + backendProcessId); - - backendProcess.Kill(); - Thread.Sleep(3000); - } - Assert.True(rapidFailsTriggered, "Verify 502 Bad Gateway error"); - - // verify event error log - int errorEventId = 1003; - string errorMessageContainThis = "'" + valueOfRapidFailsPerMinute + "'"; // part of error message - Assert.True(TestUtility.RetryHelper((arg1, arg2, arg3) => VerifyApplicationEventLog(arg1, arg2, arg3), errorEventId, startTime, errorMessageContainThis)); - } - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoProcessesPerApplicationTest(IISConfigUtility.AppPoolBitness appPoolBitness, int valueOfProcessesPerApplication) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoProcessesPerApplicationTest")) - { - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - DateTime startTime = DateTime.Now; - Thread.Sleep(3000); - - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "processesPerApplication", valueOfProcessesPerApplication); - HashSet processIDs = new HashSet(); - - for (int i = 0; i < 20; i++) - { - string backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - int id = Convert.ToInt32(backendProcessId); - if (!processIDs.Contains(id)) - { - processIDs.Add(id); - } - - if (i == (valueOfProcessesPerApplication - 1)) - { - Assert.Equal(valueOfProcessesPerApplication, processIDs.Count); - } - } - - Assert.Equal(valueOfProcessesPerApplication, processIDs.Count); - - foreach (var id in processIDs) - { - var backendProcess = Process.GetProcessById(id); - Assert.Equal(backendProcess.ProcessName.ToLower().Replace(".exe", ""), testSite.AspNetCoreApp.GetProcessFileName().ToLower().Replace(".exe", "")); - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMStartEvent(arg1, arg2), startTime, id.ToString())); - } - - // reset the value with 1 again - processIDs = new HashSet(); - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "processesPerApplication", 1); - Thread.Sleep(3000); - - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - Thread.Sleep(500); - - for (int i = 0; i < 20; i++) - { - string backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - int id = Convert.ToInt32(backendProcessId); - if (!processIDs.Contains(id)) - { - processIDs.Add(id); - } - } - Assert.Single(processIDs); - } - - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoStartupTimeLimitTest(IISConfigUtility.AppPoolBitness appPoolBitness, int startupTimeLimit) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoStartupTimeLimitTest")) - { - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - int startupDelay = 3; //3 seconds - iisConfig.SetANCMConfig( - testSite.SiteName, - testSite.AspNetCoreApp.Name, - "environmentVariable", - new string[] { "ANCMTestStartUpDelay", (startupDelay * 1000).ToString() } - ); - - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "requestTimeout", TimeSpan.Parse("00:01:00")); // 1 minute - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "startupTimeLimit", startupTimeLimit); - - Thread.Sleep(500); - if (startupTimeLimit < startupDelay) - { - await SendReceive(testSite.AspNetCoreApp.GetUri("DoSleep3000"), HttpStatusCode.BadGateway); - } - else - { - await SendReceive(testSite.AspNetCoreApp.GetUri("DoSleep3000"), expectedResponseBody: "Running"); - } - } - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoRequestTimeoutTest(IISConfigUtility.AppPoolBitness appPoolBitness, string requestTimeout) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoRequestTimeoutTest")) - { - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "requestTimeout", TimeSpan.Parse(requestTimeout)); - Thread.Sleep(500); - - if (requestTimeout.ToString() == "00:02:00") - { - await SendReceive(testSite.AspNetCoreApp.GetUri("DoSleep65000"), expectedResponseBody: "Running", timeout: 70); - } - else if (requestTimeout.ToString() == "00:01:00") - { - await SendReceive(testSite.AspNetCoreApp.GetUri("DoSleep65000"), HttpStatusCode.BadGateway, timeout: 70); - } - else - { - throw new ApplicationException("wrong data"); - } - } - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoShutdownTimeLimitTest(IISConfigUtility.AppPoolBitness appPoolBitness, int valueOfshutdownTimeLimit, int expectedClosingTime, bool isGraceFullShutdownEnabled) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoShutdownTimeLimitTest")) - { - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - DateTime startTime = DateTime.Now; - - // Make shutdownDelay time with hard coded value such as 20 seconds and test vairious shutdonwTimeLimit, either less than 20 seconds or bigger then 20 seconds - int shutdownDelayTime = 20000; - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "shutdownTimeLimit", valueOfshutdownTimeLimit); - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "environmentVariable", new string[] { "ANCMTestShutdownDelay", shutdownDelayTime.ToString() }); - string expectedGracefulShutdownResponseStatusCode = "202"; - if (!isGraceFullShutdownEnabled) - { - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "environmentVariable", new string[] { "GracefulShutdown", "disabled" }); - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "environmentVariable", new string[] { "ANCMTestStartupClassName", "StartupWithShutdownDisabled" }); - expectedGracefulShutdownResponseStatusCode = "200"; - } - - string response = (await SendReceive(testSite.AspNetCoreApp.GetUri(""))).ResponseBody; - Assert.True(response == "Running"); - - string backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - var backendProcess = Process.GetProcessById(Convert.ToInt32(backendProcessId)); - - // Set a new configuration value to make the backend process being recycled - DateTime startTime2 = DateTime.Now; - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "shutdownTimeLimit", 100); - backendProcess.WaitForExit(30000); - DateTime endTime = DateTime.Now; - var difference = endTime - startTime2; - Assert.True(difference.Seconds >= expectedClosingTime); - Assert.True(difference.Seconds < expectedClosingTime + 3); - string newBackendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - Assert.True(backendProcessId != newBackendProcessId); - await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseBody: "Running"); - - // if expectedClosing time is less than the shutdownDelay time, gracefulshutdown is supposed to fail and failure event is expected - if (expectedClosingTime * 1000 + 1000 == shutdownDelayTime) - { - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMGracefulShutdownEvent(arg1, arg2), startTime, backendProcessId)); - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMGracefulShutdownEvent(arg1, arg2), startTime, expectedGracefulShutdownResponseStatusCode)); - } - else - { - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMGracefulShutdownFailureEvent(arg1, arg2), startTime, backendProcessId)); - } - } - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - public static async Task DoStdoutLogEnabledTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoStdoutLogEnabledTest")) - { - testSite.AspNetCoreApp.DeleteDirectory("logs"); - - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - DateTime startTime = DateTime.Now; - Thread.Sleep(3000); - - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "stdoutLogEnabled", true); - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "stdoutLogFile", @".\logs\stdout"); - - string backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - string logPath = testSite.AspNetCoreApp.GetDirectoryPathWith("logs"); - Assert.False(Directory.Exists(logPath)); - - Assert.True(TestUtility.RetryHelper((arg1, arg2, arg3) => VerifyApplicationEventLog(arg1, arg2, arg3), 1004, startTime, @"logs\stdout")); - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMStartEvent(arg1, arg2), startTime, backendProcessId)); - - testSite.AspNetCoreApp.CreateDirectory("logs"); - - // verify the log file is not created because backend process is not recycled - Assert.True(Directory.GetFiles(logPath).Length == 0); - Assert.True(backendProcessId == (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody); - - // reset web.config to recycle backend process and give write permission to the Users local group to which IIS workerprocess identity belongs - SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); - TestUtility.GiveWritePermissionTo(logPath, sid); - - startTime = DateTime.Now; - Thread.Sleep(500); - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "stdoutLogEnabled", false); - - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "stdoutLogEnabled", true); - - Assert.True(backendProcessId != (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody); - - // Verify log file is created now after backend process is recycled - Assert.True(TestUtility.RetryHelper(p => { return Directory.GetFiles(p).Length > 0 ? true : false; }, logPath)); - } - - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoProcessPathAndArgumentsTest(IISConfigUtility.AppPoolBitness appPoolBitness, string processPath, string argumentsPrefix) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoProcessPathAndArgumentsTest", copyAllPublishedFiles: true)) - { - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - string arguments = argumentsPrefix + testSite.AspNetCoreApp.GetArgumentFileName(); - string tempProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - var tempBackendProcess = Process.GetProcessById(Convert.ToInt32(tempProcessId)); - - // replace $env with the actual test value - if (processPath == "$env") - { - string tempString = Environment.ExpandEnvironmentVariables("%systemdrive%").ToLower(); - processPath = Path.Combine(tempBackendProcess.MainModule.FileName).ToLower().Replace(tempString, "%systemdrive%"); - arguments = testSite.AspNetCoreApp.GetDirectoryPathWith(arguments).ToLower().Replace(tempString, "%systemdrive%"); - } - - DateTime startTime = DateTime.Now; - Thread.Sleep(500); - - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "processPath", processPath); - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "arguments", arguments); - Thread.Sleep(500); - - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - Thread.Sleep(500); - - string backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - Assert.True(TestUtility.RetryHelper((arg1, arg2) => VerifyANCMStartEvent(arg1, arg2), startTime, backendProcessId)); - } - - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoForwardWindowsAuthTokenTest(IISConfigUtility.AppPoolBitness appPoolBitness, bool enabledForwardWindowsAuthToken) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoForwardWindowsAuthTokenTest")) - { - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - string responseBody = string.Empty; - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "forwardWindowsAuthToken", enabledForwardWindowsAuthToken); - string requestHeaders = (await SendReceive(testSite.AspNetCoreApp.GetUri("DumpRequestHeaders"))).ResponseBody; - Assert.DoesNotContain("MS-ASPNETCORE-WINAUTHTOKEN", requestHeaders, StringComparison.InvariantCultureIgnoreCase); - - iisConfig.EnableIISAuthentication(testSite.SiteName, windows: true, basic: false, anonymous: false); - Thread.Sleep(500); - - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - Thread.Sleep(500); - - requestHeaders = (await SendReceive(testSite.AspNetCoreApp.GetUri("DumpRequestHeaders"))).ResponseBody; - if (enabledForwardWindowsAuthToken) - { - - Assert.Contains("MS-ASPNETCORE-WINAUTHTOKEN", requestHeaders.ToUpper()); - - responseBody = (await SendReceive(testSite.AspNetCoreApp.GetUri("ImpersonateMiddleware"))).ResponseBody; - bool compare = false; - - string expectedValue1 = "ImpersonateMiddleware-UserName = " + Environment.ExpandEnvironmentVariables("%USERDOMAIN%") + "\\" + Environment.ExpandEnvironmentVariables("%USERNAME%"); - if (responseBody.ToLower().Contains(expectedValue1.ToLower())) - { - compare = true; - } - - string expectedValue2 = "ImpersonateMiddleware-UserName = " + Environment.ExpandEnvironmentVariables("%USERNAME%"); - if (responseBody.ToLower().Contains(expectedValue2.ToLower())) - { - compare = true; - } - - Assert.True(compare); - } - else - { - Assert.DoesNotContain("MS-ASPNETCORE-WINAUTHTOKEN", requestHeaders, StringComparison.InvariantCultureIgnoreCase); - - responseBody = (await SendReceive(testSite.AspNetCoreApp.GetUri("ImpersonateMiddleware"))).ResponseBody; - Assert.Contains("ImpersonateMiddleware-UserName = NoAuthentication", responseBody); - } - } - - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoRecylingAppPoolTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoRecylingAppPoolTest")) - { - if (testSite.IisServerType == ServerType.IISExpress) - { - TestUtility.LogInformation("This test is not valid for IISExpress server type"); - return; - } - - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - - // allocating 1024,000 KB - await SendReceive(testSite.AspNetCoreApp.GetUri("MemoryLeak1024000")); - - // get backend process id - string pocessIdBackendProcess = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - - // get process id of IIS worker process (w3wp.exe) - string userName = testSite.SiteName; - int processIdOfWorkerProcess = Convert.ToInt32(TestUtility.GetProcessWMIAttributeValue("w3wp.exe", "Handle", userName)); - var workerProcess = Process.GetProcessById(Convert.ToInt32(processIdOfWorkerProcess)); - var backendProcess = Process.GetProcessById(Convert.ToInt32(pocessIdBackendProcess)); - - var privateMemoryKB = workerProcess.PrivateMemorySize64 / 1024; - var virtualMemoryKB = workerProcess.VirtualMemorySize64 / 1024; - var privateMemoryKBBackend = backendProcess.PrivateMemorySize64 / 1024; - var virtualMemoryKBBackend = backendProcess.VirtualMemorySize64 / 1024; - var totalPrivateMemoryKB = privateMemoryKB + privateMemoryKBBackend; - var totalVirtualMemoryKB = virtualMemoryKB + virtualMemoryKBBackend; - - // terminate backend process - backendProcess.Kill(); - backendProcess.Dispose(); - - // terminate IIS worker process - workerProcess.Kill(); - workerProcess.Dispose(); - Thread.Sleep(3000); - - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - iisConfig.SetAppPoolSetting(testSite.AspNetCoreApp.AppPoolName, "privateMemory", totalPrivateMemoryKB); - - // set 100 for rapidFailProtection counter for both IIS worker process and aspnetcore backend process - iisConfig.SetAppPoolSetting(testSite.AspNetCoreApp.AppPoolName, "rapidFailProtectionMaxCrashes", 100); - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "rapidFailsPerMinute", 100); - Thread.Sleep(3000); - - await SendReceive(testSite.RootAppContext.GetUri("small.htm")); - Thread.Sleep(1000); - int x = Convert.ToInt32(TestUtility.GetProcessWMIAttributeValue("w3wp.exe", "Handle", userName)); - - // Verify that IIS recycling does not happen while there is no memory leak - bool foundVSJit = false; - for (int i = 0; i < 10; i++) - { - // check JitDebugger before continuing - foundVSJit = TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - await SendReceive(testSite.RootAppContext.GetUri("small.htm")); - Thread.Sleep(3000); - } - - int y = Convert.ToInt32(TestUtility.GetProcessWMIAttributeValue("w3wp.exe", "Handle", userName)); - Assert.True(x == y && !foundVSJit, "worker process is not recycled after 30 seconds"); - - string backupPocessIdBackendProcess = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - string newPocessIdBackendProcess = backupPocessIdBackendProcess; - - // Verify IIS recycling happens while there is memory leak - for (int i = 0; i < 10; i++) - { - // check JitDebugger before continuing - foundVSJit = TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - // allocating 2048,000 KB - await SendReceive(testSite.AspNetCoreApp.GetUri("MemoryLeak2048000")); - - newPocessIdBackendProcess = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - if (foundVSJit || backupPocessIdBackendProcess != newPocessIdBackendProcess) - { - // worker process is recycled expectedly and backend process is recycled together - break; - } - Thread.Sleep(3000); - } - // check JitDebugger before continuing - TestUtility.ResetHelper(ResetHelperMode.KillVSJitDebugger); - - int z = 0; - for (int i = 0; i < 10; i++) - { - z = Convert.ToInt32(TestUtility.GetProcessWMIAttributeValue("w3wp.exe", "Handle", userName)); - if (x != z) - { - break; - } - else - { - Thread.Sleep(1000); - } - } - z = Convert.ToInt32(TestUtility.GetProcessWMIAttributeValue("w3wp.exe", "Handle", userName)); - Assert.True(x != z, "worker process is recycled"); - - newPocessIdBackendProcess = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - Assert.True(backupPocessIdBackendProcess != newPocessIdBackendProcess, "backend process is recycled"); - } - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoCompressionTest(IISConfigUtility.AppPoolBitness appPoolBitness, bool useCompressionMiddleWare, bool enableIISCompression) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoCompressionTest")) - { - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - string startupClass = "StartupCompressionCaching"; - if (!useCompressionMiddleWare) - { - startupClass = "StartupNoCompressionCaching"; - } - - // set startup class - iisConfig.SetANCMConfig( - testSite.SiteName, - testSite.AspNetCoreApp.Name, - "environmentVariable", - new string[] { "ANCMTestStartupClassName", startupClass } - ); - - // enable or IIS compression - // Note: IIS compression, however, will be ignored if AspnetCore compression middleware is enabled. - iisConfig.SetCompression(testSite.SiteName, enableIISCompression); - - // prepare static contents - testSite.AspNetCoreApp.CreateDirectory("wwwroot"); - testSite.AspNetCoreApp.CreateDirectory(@"wwwroot\pdir"); - - testSite.AspNetCoreApp.CreateFile(new string[] { "foohtm" }, @"wwwroot\foo.htm"); - testSite.AspNetCoreApp.CreateFile(new string[] { "barhtm" }, @"wwwroot\pdir\bar.htm"); - testSite.AspNetCoreApp.CreateFile(new string[] { "defaulthtm" }, @"wwwroot\default.htm"); - - SendReceiveContext result = null; - if (!useCompressionMiddleWare && !enableIISCompression) - { - result = await SendReceive(testSite.AspNetCoreApp.GetUri("foo.htm"), requestHeaders: new string[] { "Accept-Encoding", "gzip" }); - Assert.True(result.ResponseBody.Contains("foohtm"), "verify response body"); - Assert.False(result.ResponseHeader.Contains("Content-Encoding"), "verify response header"); - - result = await SendReceive(testSite.AspNetCoreApp.GetUri("pdir/bar.htm"), requestHeaders: new string[] { "Accept-Encoding", "gzip" }); - Assert.True(result.ResponseBody.Contains("barhtm"), "verify response body"); - Assert.False(result.ResponseHeader.Contains("Content-Encoding"), "verify response header"); - - result = await SendReceive(testSite.AspNetCoreApp.GetUri(), requestHeaders: new string[] { "Accept-Encoding", "gzip" }); - Assert.True(result.ResponseBody.Contains("defaulthtm"), "verify response body"); - Assert.False(result.ResponseHeader.Contains("Content-Encoding"), "verify response header"); - } - else - { - result = await SendReceive(testSite.AspNetCoreApp.GetUri("foo.htm"), requestHeaders: new string[] { "Accept-Encoding", "gzip" }); - Assert.True(result.ResponseBody.Contains("foohtm"), "verify response body"); - Assert.Equal("gzip", GetHeaderValue(result.ResponseHeader, "Content-Encoding")); - - result = await SendReceive(testSite.AspNetCoreApp.GetUri("pdir/bar.htm"), requestHeaders: new string[] { "Accept-Encoding", "gzip" }); - Assert.True(result.ResponseBody.Contains("barhtm"), "verify response body"); - Assert.Equal("gzip", GetHeaderValue(result.ResponseHeader, "Content-Encoding")); - - result = await SendReceive(testSite.AspNetCoreApp.GetUri(), requestHeaders: new string[] { "Accept-Encoding", "gzip" }); - Assert.True(result.ResponseBody.Contains("defaulthtm"), "verify response body"); - Assert.Equal("gzip", GetHeaderValue(result.ResponseHeader, "Content-Encoding")); - } - } - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoCachingTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoCachingTest")) - { - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - string startupClass = "StartupCompressionCaching"; - - // set startup class - iisConfig.SetANCMConfig( - testSite.SiteName, - testSite.AspNetCoreApp.Name, - "environmentVariable", - new string[] { "ANCMTestStartupClassName", startupClass } - ); - - // enable IIS compression - // Note: IIS compression, however, will be ignored if AspnetCore compression middleware is enabled. - iisConfig.SetCompression(testSite.SiteName, true); - - // prepare static contents - testSite.AspNetCoreApp.CreateDirectory("wwwroot"); - testSite.AspNetCoreApp.CreateDirectory(@"wwwroot\pdir"); - - testSite.AspNetCoreApp.CreateFile(new string[] { "foohtm" }, @"wwwroot\foo.htm"); - testSite.AspNetCoreApp.CreateFile(new string[] { "barhtm" }, @"wwwroot\pdir\bar.htm"); - testSite.AspNetCoreApp.CreateFile(new string[] { "defaulthtm" }, @"wwwroot\default.htm"); - - const int retryCount = 3; - string headerValue = string.Empty; - string headerValue2 = string.Empty; - SendReceiveContext result = null; - for (int i = 0; i < retryCount; i++) - { - result = await SendReceive(testSite.AspNetCoreApp.GetUri("foo.htm"), requestHeaders: new string[] { "Accept-Encoding", "gzip" }); - headerValue = GetHeaderValue(result.ResponseHeader, "MyCustomHeader"); - Assert.True(result.ResponseBody.Contains("foohtm"), "verify response body"); - Assert.Equal("gzip", GetHeaderValue(result.ResponseHeader, "Content-Encoding")); - Thread.Sleep(1500); - - result = await SendReceive(testSite.AspNetCoreApp.GetUri("foo.htm"), requestHeaders: new string[] { "Accept-Encoding", "gzip" }); - headerValue2 = GetHeaderValue(result.ResponseHeader, "MyCustomHeader"); - Assert.True(result.ResponseBody.Contains("foohtm"), "verify response body"); - Assert.Equal("gzip", GetHeaderValue(result.ResponseHeader, "Content-Encoding")); - if (headerValue == headerValue2) - { - break; - } - } - Assert.Equal(headerValue, headerValue2); - - Thread.Sleep(12000); - result = await SendReceive(testSite.AspNetCoreApp.GetUri("foo.htm"), requestHeaders: new string[] { "Accept-Encoding", "gzip" }); - Assert.True(result.ResponseBody.Contains("foohtm"), "verify response body"); - Assert.Equal("gzip", GetHeaderValue(result.ResponseHeader, "Content-Encoding")); - string headerValue3 = GetHeaderValue(result.ResponseHeader, "MyCustomHeader"); - Assert.NotEqual(headerValue2, headerValue3); - } - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoSendHTTPSRequestTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoSendHTTPSRequestTest", startIISExpress: false)) - { - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - string hostName = ""; - string subjectName = "localhost"; - string ipAddress = "*"; - string hexIPAddress = "0x00"; - int sslPort = InitializeTestMachine.SiteId + 6300; - - // Add https binding and get https uri information - iisConfig.AddBindingToSite(testSite.SiteName, ipAddress, sslPort, hostName, "https"); - - // Create a self signed certificate - string thumbPrint = iisConfig.CreateSelfSignedCertificate(subjectName); - - // Export the self signed certificate to rootCA - iisConfig.ExportCertificateTo(thumbPrint, sslStoreTo: @"Cert:\LocalMachine\Root"); - - // Configure http.sys ssl certificate mapping to IP:Port endpoint with the newly created self signed certificage - iisConfig.SetSSLCertificate(sslPort, hexIPAddress, thumbPrint); - - // starting IISExpress was deffered after creating test applications and now it is ready to start it - testSite.StartIISExpress(); - - // Verify http request - var result = await SendReceive(testSite.AspNetCoreApp.GetUri(), requestHeaders: new string[] { "Accept-Encoding", "gzip" }); - Assert.True(result.ResponseBody.Contains("Running"), "verify response body"); - - // Verify https request - Uri targetHttpsUri = testSite.AspNetCoreApp.GetUri(null, sslPort, protocol: "https"); - result = await SendReceive(targetHttpsUri, requestHeaders: new string[] { "Accept-Encoding", "gzip" }); - Assert.True(result.ResponseBody.Contains("Running"), "verify response body"); - - // Remove the SSL Certificate mapping - iisConfig.RemoveSSLCertificate(sslPort, hexIPAddress); - - // Remove the newly created self signed certificate - iisConfig.DeleteCertificate(thumbPrint); - - // Remove the exported self signed certificate on rootCA - iisConfig.DeleteCertificate(thumbPrint, @"Cert:\LocalMachine\Root"); - } - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoFilterOutMSRequestHeadersTest(IISConfigUtility.AppPoolBitness appPoolBitness, string requestHeader, string requestHeaderValue) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoSendHTTPSRequestTest", startIISExpress: false)) - { - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - string hostName = ""; - string subjectName = "localhost"; - string ipAddress = "*"; - string hexIPAddress = "0x00"; - int sslPort = InitializeTestMachine.SiteId + 6300; - - // Add https binding and get https uri information - iisConfig.AddBindingToSite(testSite.SiteName, ipAddress, sslPort, hostName, "https"); - - // Create a self signed certificate - string thumbPrint = iisConfig.CreateSelfSignedCertificate(subjectName); - - // Export the self signed certificate to rootCA - iisConfig.ExportCertificateTo(thumbPrint, sslStoreTo: @"Cert:\LocalMachine\Root"); - - // Configure http.sys ssl certificate mapping to IP:Port endpoint with the newly created self signed certificage - iisConfig.SetSSLCertificate(sslPort, hexIPAddress, thumbPrint); - - // starting IISExpress was deffered after creating test applications and now it is ready to start it - testSite.StartIISExpress(); - - // Verify http request - var result = await SendReceive(testSite.AspNetCoreApp.GetUri("DumpRequestHeaders"), requestHeaders: new string[] { "Accept-Encoding", "gzip", requestHeader, requestHeaderValue }); - string requestHeaders = result.ResponseHeader.Replace(" ", ""); - Assert.DoesNotContain(requestHeader + ":", requestHeaders, StringComparison.InvariantCultureIgnoreCase); - - // Verify https request - Uri targetHttpsUri = testSite.AspNetCoreApp.GetUri(null, sslPort, protocol: "https"); - result = await SendReceive(targetHttpsUri, requestHeaders: new string[] { "Accept-Encoding", "gzip", requestHeader, requestHeaderValue }); - requestHeaders = result.ResponseHeader.Replace(" ", ""); - Assert.DoesNotContain(requestHeader + ":", requestHeaders, StringComparison.InvariantCultureIgnoreCase); - - // Remove the SSL Certificate mapping - iisConfig.RemoveSSLCertificate(sslPort, hexIPAddress); - - // Remove the newly created self signed certificate - iisConfig.DeleteCertificate(thumbPrint); - - // Remove the exported self signed certificate on rootCA - iisConfig.DeleteCertificate(thumbPrint, @"Cert:\LocalMachine\Root"); - } - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoClientCertificateMappingTest(IISConfigUtility.AppPoolBitness appPoolBitness, bool useHTTPSMiddleWare) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoClientCertificateMappingTest", startIISExpress: false)) - { - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - string hostName = ""; - string rootCN = "ANCMTest" + testSite.PostFix; - string webServerCN = "localhost"; - string kestrelServerCN = "localhost"; - string clientCN = "ANCMClient-" + testSite.PostFix; - - string ipAddress = "*"; - string hexIPAddress = "0x00"; - int sslPort = InitializeTestMachine.SiteId + 6300; - - // Add https binding and get https uri information - iisConfig.AddBindingToSite(testSite.SiteName, ipAddress, sslPort, hostName, "https"); - - // Create a root certificate - string thumbPrintForRoot = iisConfig.CreateSelfSignedCertificateWithMakeCert(rootCN); - - // Create a certificate for web server setting its issuer with the root certificate subject name - string thumbPrintForWebServer = iisConfig.CreateSelfSignedCertificateWithMakeCert(webServerCN, rootCN, extendedKeyUsage: "1.3.6.1.5.5.7.3.1"); - string thumbPrintForKestrel = null; - - // Create a certificate for client authentication setting its issuer with the root certificate subject name - string thumbPrintForClientAuthentication = iisConfig.CreateSelfSignedCertificateWithMakeCert(clientCN, rootCN, extendedKeyUsage: "1.3.6.1.5.5.7.3.2"); - - // Configure http.sys ssl certificate mapping to IP:Port endpoint with the newly created self signed certificage - iisConfig.SetSSLCertificate(sslPort, hexIPAddress, thumbPrintForWebServer); - - // Create a new local administrator user - string userName = "tempuser" + TestUtility.RandomString(5); - string password = "AncmTest123!"; - string temp; - temp = TestUtility.RunPowershellScript("net localgroup IIS_IUSRS /Delete " + userName); - temp = TestUtility.RunPowershellScript("net user " + userName + " /Delete"); - temp = TestUtility.RunPowershellScript("net user " + userName + " " + password + " /ADD"); - temp = TestUtility.RunPowershellScript("net localgroup IIS_IUSRS /Add " + userName); - - // Get public key of the client certificate and Configure OnetToOneClientCertificateMapping the public key and disable anonymous authentication and set SSL flags for Client certificate authentication - string publicKey = iisConfig.GetCertificatePublicKey(thumbPrintForClientAuthentication, @"Cert:\CurrentUser\My"); - - bool setPasswordSeperately = false; - if (testSite.IisServerType == ServerType.IISExpress) - { - setPasswordSeperately = true; - iisConfig.EnableOneToOneClientCertificateMapping(testSite.SiteName, ".\\" + userName, null, publicKey); - } - else - { - iisConfig.EnableOneToOneClientCertificateMapping(testSite.SiteName, ".\\" + userName, password, publicKey); - } - - // IISExpress uses a differnt encryption from full IIS version's and it is not easy to override the encryption methong with MWA. - // As a work-around, password is set with updating the config file directly. - if (setPasswordSeperately) - { - // Search userName property and replace it with userName + password - string text = File.ReadAllText(testSite.IisExpressConfigPath); - text = text.Replace(userName + "\"", userName + "\"" + " " + "password=" + "\"" + password + "\""); - File.WriteAllText(testSite.IisExpressConfigPath, text); - } - - // Configure kestrel SSL test environment - if (useHTTPSMiddleWare) - { - // set startup class - string startupClass = "StartupHTTPS"; - iisConfig.SetANCMConfig( - testSite.SiteName, - testSite.AspNetCoreApp.Name, - "environmentVariable", - new string[] { "ANCMTestStartupClassName", startupClass } - ); - - // Create a certificate for Kestrel web server and export to TestResources\testcert.pfx - // NOTE: directory name "TestResources", file name "testcert.pfx" and password "testPassword" should be matched to AspnetCoreModule.TestSites.Standard web application - thumbPrintForKestrel = iisConfig.CreateSelfSignedCertificateWithMakeCert(kestrelServerCN, rootCN, extendedKeyUsage: "1.3.6.1.5.5.7.3.1"); - testSite.AspNetCoreApp.CreateDirectory("TestResources"); - string pfxFilePath = Path.Combine(testSite.AspNetCoreApp.GetDirectoryPathWith("TestResources"), "testcert.pfx"); - iisConfig.ExportCertificateTo(thumbPrintForKestrel, sslStoreFrom: "Cert:\\LocalMachine\\My", sslStoreTo: pfxFilePath, pfxPassword: "testPassword"); - Assert.True(File.Exists(pfxFilePath)); - } - - // starting IISExpress was deffered after creating test applications and now it is ready to start it - Uri rootHttpsUri = testSite.RootAppContext.GetUri(null, sslPort, protocol: "https"); - testSite.StartIISExpress(); - TestUtility.RunPowershellScript("( invoke-webrequest " + rootHttpsUri.OriginalString + " -CertificateThumbprint " + thumbPrintForClientAuthentication + ").StatusCode", "200"); - - // Verify http request with using client certificate - Uri targetHttpsUri = testSite.AspNetCoreApp.GetUri(null, sslPort, protocol: "https"); - string statusCode = TestUtility.RunPowershellScript("( invoke-webrequest " + targetHttpsUri.OriginalString + " -CertificateThumbprint " + thumbPrintForClientAuthentication + ").StatusCode"); - Assert.Equal("200", statusCode); - - // Verify https request with client certificate includes the certificate header "MS-ASPNETCORE-CLIENTCERT" - Uri targetHttpsUriForDumpRequestHeaders = testSite.AspNetCoreApp.GetUri("DumpRequestHeaders", sslPort, protocol: "https"); - string outputRawContent = TestUtility.RunPowershellScript("( invoke-webrequest " + targetHttpsUriForDumpRequestHeaders.OriginalString + " -CertificateThumbprint " + thumbPrintForClientAuthentication + ").RawContent.ToString()"); - - Assert.Contains("MS-ASPNETCORE-CLIENTCERT", outputRawContent); - - // Get the value of MS-ASPNETCORE-CLIENTCERT request header again and verify it is matched to its configured public key - Uri targetHttpsUriForCLIENTCERTRequestHeader = testSite.AspNetCoreApp.GetUri("GetRequestHeaderValueMS-ASPNETCORE-CLIENTCERT", sslPort, protocol: "https"); - outputRawContent = TestUtility.RunPowershellScript("( invoke-webrequest " + targetHttpsUriForCLIENTCERTRequestHeader.OriginalString + " -CertificateThumbprint " + thumbPrintForClientAuthentication + ").RawContent.ToString()"); - Assert.Contains(publicKey, outputRawContent); - - // Verify non-https request returns 403.4 error - var result = await SendReceive(testSite.AspNetCoreApp.GetUri(), requestHeaders: new string[] { "Accept-Encoding", "gzip" }, expectedResponseStatus: HttpStatusCode.Forbidden); - Assert.Contains("403.4", result.ResponseBody); - - // Verify https request without using client certificate returns 403.7 - result = await SendReceive(targetHttpsUri, requestHeaders: new string[] { "Accept-Encoding", "gzip" }, expectedResponseStatus: HttpStatusCode.Forbidden); - Assert.Contains("403.7", result.ResponseBody); - - // Clean up user - temp = TestUtility.RunPowershellScript("net localgroup IIS_IUSRS /Delete " + userName); - temp = TestUtility.RunPowershellScript("net user " + userName + " /Delete"); - - // Remove the SSL Certificate mapping - iisConfig.RemoveSSLCertificate(sslPort, hexIPAddress); - - // Clean up certificates - iisConfig.DeleteCertificate(thumbPrintForRoot, @"Cert:\LocalMachine\Root"); - iisConfig.DeleteCertificate(thumbPrintForWebServer, @"Cert:\LocalMachine\My"); - if (useHTTPSMiddleWare) - { - iisConfig.DeleteCertificate(thumbPrintForKestrel, @"Cert:\LocalMachine\My"); - } - iisConfig.DeleteCertificate(thumbPrintForClientAuthentication, @"Cert:\CurrentUser\My"); - } - testSite.AspNetCoreApp.RestoreFile("web.config"); - } - } - - public static async Task DoWebSocketTest(IISConfigUtility.AppPoolBitness appPoolBitness, string testData) - { - using (var testSite = new TestWebSite(appPoolBitness, "DoWebSocketTest")) - { - string appDllFileName = testSite.AspNetCoreApp.GetArgumentFileName(); - - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "shutdownTimeLimit", 10); - } - - DateTime startTime = DateTime.Now; - - await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseBody: "Running"); - - // Get Process ID - string backendProcessId_old = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - - // Verify WebSocket without setting subprotocol - await SendReceive(testSite.WebSocketApp.GetUri("echo.aspx"), expectedStringsInResponseBody: new string[] { "Socket Open" }); // echo.aspx has hard coded path for the websocket server - - // Verify WebSocket subprotocol - await SendReceive(testSite.WebSocketApp.GetUri("echoSubProtocol.aspx"), expectedStringsInResponseBody: new string[] { "Socket Open", "mywebsocketsubprotocol" }); // echoSubProtocol.aspx has hard coded path for the websocket server - - // Verify websocket - using (WebSocketClientHelper websocketClient = new WebSocketClientHelper()) - { - var frameReturned = websocketClient.Connect(testSite.AspNetCoreApp.GetUri("websocket"), true, true); - Assert.Contains("Connection: Upgrade", frameReturned.Content); - Assert.Contains("HTTP/1.1 101 Switching Protocols", frameReturned.Content); - Thread.Sleep(500); - - VerifySendingWebSocketData(websocketClient, testData); - Thread.Sleep(500); - - frameReturned = websocketClient.Close(); - Thread.Sleep(500); - - Assert.True(frameReturned.FrameType == FrameType.Close, "Closing Handshake"); - } - - // send a simple request and verify the response body - await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseBody: "Running"); - - Thread.Sleep(500); - string backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - Assert.Equal(backendProcessId_old, backendProcessId); - - // Verify server side websocket disconnection - using (WebSocketClientHelper websocketClient = new WebSocketClientHelper()) - { - for (int jj = 0; jj < 3; jj++) - { - var frameReturned = websocketClient.Connect(testSite.AspNetCoreApp.GetUri("websocket"), true, true); - Assert.Contains("Connection: Upgrade", frameReturned.Content); - Assert.Contains("HTTP/1.1 101 Switching Protocols", frameReturned.Content); - Thread.Sleep(500); - - Assert.True(websocketClient.IsOpened, "Check active connection before starting"); - - // Send a special string to initiate the server side connection closing - websocketClient.SendTextData("CloseFromServer"); - bool connectionClosedFromServer = websocketClient.WaitForWebSocketState(WebSocketState.ConnectionClosed); - - // Verify server side connection closing is done successfully - Assert.True(connectionClosedFromServer, "Closing Handshake initiated from Server"); - - // extract text data from the last frame, which is the close frame - int lastIndex = websocketClient.Connection.DataReceived.Count - 1; - - // Verify text data is matched to the string sent by server - Assert.Contains("ClosingFromServer", websocketClient.Connection.DataReceived[lastIndex].TextData); - } - } - - // send a simple request and verify the response body - await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseBody: "Running"); - - Thread.Sleep(500); - backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - Assert.Equal(backendProcessId_old, backendProcessId); - - // Verify websocket with app_offline.htm - using (WebSocketClientHelper websocketClient = new WebSocketClientHelper()) - { - for (int jj = 0; jj < 3; jj++) - { - testSite.AspNetCoreApp.DeleteFile("App_Offline.Htm"); - Thread.Sleep(1000); - - var frameReturned = websocketClient.Connect(testSite.AspNetCoreApp.GetUri("websocket"), true, true); - Assert.Contains("Connection: Upgrade", frameReturned.Content); - Assert.Contains("HTTP/1.1 101 Switching Protocols", frameReturned.Content); - Thread.Sleep(500); - - VerifySendingWebSocketData(websocketClient, testData); - Thread.Sleep(500); - - // put app_offline - testSite.AspNetCoreApp.CreateFile(new string[] { "test" }, "App_Offline.Htm"); - Thread.Sleep(1000); - - // ToDo: This should be replaced when the server can handle this automaticially - // send a websocket data to invoke the server side websocket disconnection after the app_offline - websocketClient.SendTextData("test"); - bool connectionClosedFromServer = websocketClient.WaitForWebSocketState(WebSocketState.ConnectionClosed); - - // Verify server side connection closing is done successfully - Assert.True(connectionClosedFromServer, "Closing Handshake initiated from Server"); - - // extract text data from the last frame, which is the close frame - int lastIndex = websocketClient.Connection.DataReceived.Count - 1; - - // Verify text data is matched to the string sent by server - Assert.Contains("ClosingFromServer", websocketClient.Connection.DataReceived[lastIndex].TextData); - - // Verify the application file can be removed under app_offline mode - testSite.AspNetCoreApp.BackupFile(appDllFileName); - testSite.AspNetCoreApp.DeleteFile(appDllFileName); - testSite.AspNetCoreApp.RestoreFile(appDllFileName); - } - } - - // remove app_offline.htm - testSite.AspNetCoreApp.DeleteFile("App_Offline.Htm"); - Thread.Sleep(1000); - - /* - BugBug!!! configuration change does not invoke the shutdown message - because IIS does not trigger the change notification event until all websocket connection is gone. - This scenario should be added back when the issue is resolved. - - // Verify websocket with configuration change notification - using (WebSocketClientHelper websocketClient = new WebSocketClientHelper()) - { - for (int jj = 0; jj < 10; jj++) - { - var frameReturned = websocketClient.Connect(testSite.AspNetCoreApp.GetUri("websocket"), true, true); - Assert.Contains("Connection: Upgrade", frameReturned.Content); - Assert.Contains("HTTP/1.1 101 Switching Protocols", frameReturned.Content); - Thread.Sleep(500); - - VerifySendingWebSocketData(websocketClient, testData); - Thread.Sleep(500); - - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "startupTimeLimit", 11 + jj); - Thread.Sleep(1000); - } - - // ToDo: This should be replaced when the server can handle this automaticially - // send a websocket data to invoke the server side websocket disconnection after the app_offline - websocketClient.SendTextData("test"); - bool connectionClosedFromServer = websocketClient.WaitForWebSocketState(WebSocketState.ConnectionClosed); - - // Verify server side connection closing is done successfully - Assert.True(connectionClosedFromServer, "Closing Handshake initiated from Server"); - - // extract text data from the last frame, which is the close frame - int lastIndex = websocketClient.Connection.DataReceived.Count - 1; - - // Verify text data is matched to the string sent by server - Assert.Contains("ClosingFromServer", websocketClient.Connection.DataReceived[lastIndex].TextData); - } - } - */ - - // send a simple request and verify the response body - await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseBody: "Running"); - } - } - - public static async Task DoWebSocketErrorhandlingTest(IISConfigUtility.AppPoolBitness appPoolBitness) - { - try - { - using (var testSite = new TestWebSite(appPoolBitness, "DoWebSocketErrorhandlingTest")) - { - // Verify websocket returns 404 when websocket module is not registered - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - // Remove websocketModule - IISConfigUtility.BackupAppHostConfig("DoWebSocketErrorhandlingTest", true); - iisConfig.RemoveModule("WebSocketModule"); - Thread.Sleep(3000); - using (WebSocketClientHelper websocketClient = new WebSocketClientHelper()) - { - var frameReturned = websocketClient.Connect(testSite.AspNetCoreApp.GetUri("websocket"), true, true, waitForConnectionOpen:false); - Assert.DoesNotContain("Connection: Upgrade", frameReturned.Content, StringComparison.InvariantCultureIgnoreCase); - - //BugBug: Currently we returns 101 here. - //Assert.DoesNotContain("HTTP/1.1 101 Switching Protocols", frameReturned.Content); - } - } - - // send a simple request again and verify the response body - await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseBody: "Running"); - - // roback configuration - IISConfigUtility.RestoreAppHostConfig("DoWebSocketErrorhandlingTest", true); - } - } - catch - { - // roback configuration - IISConfigUtility.RestoreAppHostConfig("DoWebSocketErrorhandlingTest", true); - throw; - } - } - - public enum DoAppVerifierTest_ShutDownMode - { - RecycleAppPool, - CreateAppOfflineHtm, - StopAndStartAppPool, - RestartW3SVC, - ConfigurationChangeNotification - } - - public enum DoAppVerifierTest_StartUpMode - { - UseGracefulShutdown, - DontUseGracefulShutdown - } - - public static async Task DoAppVerifierTest(IISConfigUtility.AppPoolBitness appPoolBitness, bool verifyTimeout, DoAppVerifierTest_StartUpMode startUpMode, DoAppVerifierTest_ShutDownMode shutDownMode, int repeatCount = 2) - { - TestWebSite testSite = null; - bool testResult = false; - - testSite = new TestWebSite(appPoolBitness, "DoAppVerifierTest", startIISExpress: false); - if (testSite.IisServerType == ServerType.IISExpress) - { - TestUtility.LogInformation("This test is not valid for IISExpress server type because of IISExpress bug; Once it is resolved, we should activate this test for IISExpress as well"); - return; - } - - // enable AppVerifier - testSite.AttachAppverifier(); - - using (var iisConfig = new IISConfigUtility(testSite.IisServerType, testSite.IisExpressConfigPath)) - { - // Prepare https binding - string hostName = ""; - string subjectName = "localhost"; - string ipAddress = "*"; - string hexIPAddress = "0x00"; - int sslPort = InitializeTestMachine.SiteId + 6300; - - // Add https binding and get https uri information - iisConfig.AddBindingToSite(testSite.SiteName, ipAddress, sslPort, hostName, "https"); - - // Create a self signed certificate - string thumbPrint = iisConfig.CreateSelfSignedCertificate(subjectName); - - // Export the self signed certificate to rootCA - iisConfig.ExportCertificateTo(thumbPrint, sslStoreTo: @"Cert:\LocalMachine\Root"); - - // Configure http.sys ssl certificate mapping to IP:Port endpoint with the newly created self signed certificage - iisConfig.SetSSLCertificate(sslPort, hexIPAddress, thumbPrint); - - // Set shutdownTimeLimit with 3 seconds and use 5 seconds for delay time to make the shutdownTimeout happen - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "shutdownTimeLimit", 3); - - int timeoutValue = 3; - if (verifyTimeout) - { - // set requestTimeout - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "requestTimeout", TimeSpan.Parse("00:01:00")); // 1 minute - - // set startupTimeout - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "startupTimeLimit", timeoutValue); - - // Set shutdownTimeLimit with 3 seconds and use 5 seconds for delay time to make the shutdownTimeout happen - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "shutdownTimeLimit", timeoutValue); - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "environmentVariable", new string[] { "ANCMTestShutdownDelay", "10" }); - } - - // starting IISExpress was deffered after creating test applications and now it is ready to start. - testSite.StartIISExpress(); - - if (verifyTimeout) - { - Thread.Sleep(500); - - // initial request which requires more than startup timeout should fails - await SendReceive(testSite.AspNetCoreApp.GetUri("DoSleep5000"), HttpStatusCode.BadGateway, timeout: 10); - await SendReceive(testSite.AspNetCoreApp.GetUri("DoSleep5000"), expectedResponseBody: "Running", timeout: 10); - - // request which requires more than request timeout should fails - await SendReceive(testSite.AspNetCoreApp.GetUri("DoSleep65000"), HttpStatusCode.BadGateway, timeout: 70); - await SendReceive(testSite.AspNetCoreApp.GetUri("DoSleep50000"), expectedResponseBody: "Running", timeout: 70); - } - - /////////////////////////////////// - // Start test sceanrio - /////////////////////////////////// - if (startUpMode == DoAppVerifierTest_StartUpMode.DontUseGracefulShutdown) - { - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "environmentVariable", new string[] { "GracefulShutdown", "disabled" }); - } - - // reset existing worker process process - TestUtility.ResetHelper(ResetHelperMode.KillWorkerProcess); - - for (int i = 0; i < repeatCount; i++) - { - // reset worker process id to refresh - testSite.WorkerProcessID = 0; - - // send a startup request to start a new worker process - TestUtility.RunPowershellScript("( invoke-webrequest http://localhost:" + testSite.TcpPort + " ).StatusCode", "200", retryCount: 5); - - // attach debugger to the worker process - testSite.AttachWinDbg(testSite.WorkerProcessID); - TestUtility.RunPowershellScript("( invoke-webrequest http://localhost:" + testSite.TcpPort + " ).StatusCode", "200", retryCount: 30); - - // verify windbg process is started - TestUtility.RunPowershellScript("(get-process -name windbg 2> $null).count", "1", retryCount: 5); - - DateTime startTime = DateTime.Now; - - // Verify http request - await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseBody: "Running"); - - // Get Process ID - string backendProcessId_old = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - - // Verify WebSocket without setting subprotocol - await SendReceive(testSite.WebSocketApp.GetUri("echo.aspx"), expectedStringsInResponseBody: new string[] { "Socket Open" }); // echo.aspx has hard coded path for the websocket server - - // Verify WebSocket subprotocol - await SendReceive(testSite.WebSocketApp.GetUri("echoSubProtocol.aspx"), expectedStringsInResponseBody: new string[] { "Socket Open", "mywebsocketsubprotocol" }); // echoSubProtocol.aspx has hard coded path for the websocket server - - string testData = "test"; - - // Verify websocket - using (WebSocketClientHelper websocketClient = new WebSocketClientHelper()) - { - var frameReturned = websocketClient.Connect(testSite.AspNetCoreApp.GetUri("websocket"), true, true); - Assert.Contains("Connection: Upgrade", frameReturned.Content); - Assert.Contains("HTTP/1.1 101 Switching Protocols", frameReturned.Content); - Thread.Sleep(500); - - VerifySendingWebSocketData(websocketClient, testData); - Thread.Sleep(500); - - frameReturned = websocketClient.Close(); - Thread.Sleep(500); - - Assert.True(frameReturned.FrameType == FrameType.Close, "Closing Handshake"); - } - - // send a simple request and verify the response body - await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseBody: "Running"); - - Thread.Sleep(500); - string backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - Assert.Equal(backendProcessId_old, backendProcessId); - - // Verify server side websocket disconnection - using (WebSocketClientHelper websocketClient = new WebSocketClientHelper()) - { - var frameReturned = websocketClient.Connect(testSite.AspNetCoreApp.GetUri("websocket"), true, true); - Assert.Contains("Connection: Upgrade", frameReturned.Content); - Assert.Contains("HTTP/1.1 101 Switching Protocols", frameReturned.Content); - Thread.Sleep(500); - - Assert.True(websocketClient.IsOpened, "Check active connection before starting"); - - // Send a special string to initiate the server side connection closing - websocketClient.SendTextData("CloseFromServer"); - bool connectionClosedFromServer = websocketClient.WaitForWebSocketState(WebSocketState.ConnectionClosed); - - // Verify server side connection closing is done successfully - Assert.True(connectionClosedFromServer, "Closing Handshake initiated from Server"); - - // extract text data from the last frame, which is the close frame - int lastIndex = websocketClient.Connection.DataReceived.Count - 1; - - // Verify text data is matched to the string sent by server - Assert.Contains("ClosingFromServer", websocketClient.Connection.DataReceived[lastIndex].TextData); - } - - // send a simple request and verify the response body - await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseBody: "Running"); - - Thread.Sleep(500); - backendProcessId = (await SendReceive(testSite.AspNetCoreApp.GetUri("GetProcessId"))).ResponseBody; - Assert.Equal(backendProcessId_old, backendProcessId); - - if (startUpMode != DoAppVerifierTest_StartUpMode.DontUseGracefulShutdown) - { - // Verify websocket with app_offline.htm - using (WebSocketClientHelper websocketClient = new WebSocketClientHelper()) - { - for (int jj = 0; jj < 10; jj++) - { - testSite.AspNetCoreApp.DeleteFile("App_Offline.Htm"); - Thread.Sleep(1000); - - var frameReturned = websocketClient.Connect(testSite.AspNetCoreApp.GetUri("websocket"), true, true); - Assert.Contains("Connection: Upgrade", frameReturned.Content); - Assert.Contains("HTTP/1.1 101 Switching Protocols", frameReturned.Content); - Thread.Sleep(500); - - VerifySendingWebSocketData(websocketClient, testData); - Thread.Sleep(500); - - // put app_offline - testSite.AspNetCoreApp.CreateFile(new string[] { "test" }, "App_Offline.Htm"); - Thread.Sleep(500); - - // ToDo: remove this when server can handle this automatically - // send a websocket data to invoke the server side websocket disconnection after the app_offline - websocketClient.SendTextData("test"); - bool connectionClosedFromServer = websocketClient.WaitForWebSocketState(WebSocketState.ConnectionClosed); - - // Verify server side connection closing is done successfully - Assert.True(connectionClosedFromServer, "Closing Handshake initiated from Server"); - } - } - - // remove app_offline.htm - testSite.AspNetCoreApp.DeleteFile("App_Offline.Htm"); - Thread.Sleep(500); - } - - // Verify websocket again - using (WebSocketClientHelper websocketClient = new WebSocketClientHelper()) - { - var frameReturned = websocketClient.Connect(testSite.AspNetCoreApp.GetUri("websocket"), true, true); - Assert.Contains("Connection: Upgrade", frameReturned.Content); - Assert.Contains("HTTP/1.1 101 Switching Protocols", frameReturned.Content); - Thread.Sleep(500); - - VerifySendingWebSocketData(websocketClient, testData); - Thread.Sleep(500); - - frameReturned = websocketClient.Close(); - Thread.Sleep(500); - - Assert.True(frameReturned.FrameType == FrameType.Close, "Closing Handshake"); - } - - // send a simple request and verify the response body - await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseBody: "Running"); - - // Verify https request - Uri targetHttpsUri = testSite.AspNetCoreApp.GetUri(null, sslPort, protocol: "https"); - var result = await SendReceive(targetHttpsUri, requestHeaders: new string[] { "Accept-Encoding", "gzip" }); - Assert.True(result.ResponseBody.Contains("Running"), "verify response body"); - - switch (shutDownMode) - { - case DoAppVerifierTest_ShutDownMode.StopAndStartAppPool: - iisConfig.StopAppPool(testSite.AspNetCoreApp.AppPoolName); - Thread.Sleep(5000); - iisConfig.StartAppPool(testSite.AspNetCoreApp.AppPoolName); - break; - case DoAppVerifierTest_ShutDownMode.RestartW3SVC: - TestUtility.ResetHelper(ResetHelperMode.StopWasStartW3svc); - break; - case DoAppVerifierTest_ShutDownMode.CreateAppOfflineHtm: - testSite.AspNetCoreApp.DeleteFile("App_Offline.Htm"); - testSite.AspNetCoreApp.CreateFile(new string[] { "test" }, "App_Offline.Htm"); - break; - case DoAppVerifierTest_ShutDownMode.ConfigurationChangeNotification: - iisConfig.SetANCMConfig(testSite.SiteName, testSite.AspNetCoreApp.Name, "startupTimeLimit", timeoutValue + 1); - iisConfig.RecycleAppPool(testSite.AspNetCoreApp.AppPoolName); - break; - case DoAppVerifierTest_ShutDownMode.RecycleAppPool: - iisConfig.RecycleAppPool(testSite.AspNetCoreApp.AppPoolName); - break; - } - Thread.Sleep(2000); - - if (verifyTimeout) - { - // Wait for shutdown delay additionally - Thread.Sleep(timeoutValue * 1000); - } - - switch (shutDownMode) - { - case DoAppVerifierTest_ShutDownMode.CreateAppOfflineHtm: - // verify app_offline.htm file works - await SendReceive(testSite.AspNetCoreApp.GetUri(), expectedResponseBody: "test" + "\r\n", expectedResponseStatus: HttpStatusCode.ServiceUnavailable); - - // remove app_offline.htm file and then recycle apppool - testSite.AspNetCoreApp.MoveFile("App_Offline.Htm", "_App_Offline.Htm"); - iisConfig.RecycleAppPool(testSite.AspNetCoreApp.AppPoolName); - Thread.Sleep(2000); - break; - } - - // verify windbg process is gone, which means there was no unexpected error - TestUtility.RunPowershellScript("(get-process -name windbg 2> $null).count", "0", retryCount: 5); - } - - // clean up https test environment - - // Remove the SSL Certificate mapping - iisConfig.RemoveSSLCertificate(sslPort, hexIPAddress); - - // Remove the newly created self signed certificate - iisConfig.DeleteCertificate(thumbPrint); - - // Remove the exported self signed certificate on rootCA - iisConfig.DeleteCertificate(thumbPrint, @"Cert:\LocalMachine\Root"); - } - - // cleanup - if (testSite != null) - { - testSite.DetachAppverifier(); - } - TestUtility.ResetHelper(ResetHelperMode.KillWorkerProcess); - - // cleanup windbg process incase it is still running - if (!testResult) - { - TestUtility.RunPowershellScript("stop-process -Name windbg -Force -Confirm:$false 2> $null"); - } - } - - private static string GetHeaderValue(string inputData, string headerName) - { - string result = string.Empty; - foreach (string item in inputData.Split(new char[] { ',', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)) - { - if (item.Contains(headerName)) - { - var tokens = item.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); - if (tokens.Length == 2) - { - result = tokens[1].Trim(); - break; - } - } - } - return result; - } - - private static bool VerifySendingWebSocketData(WebSocketClientHelper websocketClient, string testData) - { - bool result = false; - - // - // send complete or partial text data and ping multiple times - // - websocketClient.SendTextData(testData); - websocketClient.SendPing(); - websocketClient.SendTextData(testData); - websocketClient.SendPing(); - websocketClient.SendPing(); - websocketClient.SendTextData(testData, 0x01); // 0x01: start of sending partial data - websocketClient.SendPing(); - websocketClient.SendTextData(testData, 0x80); // 0x80: end of sending partial data - websocketClient.SendPing(); - websocketClient.SendPing(); - websocketClient.SendTextData(testData); - websocketClient.SendTextData(testData); - websocketClient.SendTextData(testData); - websocketClient.SendPing(); - Thread.Sleep(3000); - - // Verify test result - for (int i = 0; i < 3; i++) - { - if (!DoVerifyDataSentAndReceived(websocketClient)) - { - // retrying after 1 second sleeping - Thread.Sleep(1000); - } - else - { - result = true; - break; - } - } - return result; - } - - private static bool DoVerifyDataSentAndReceived(WebSocketClientHelper websocketClient) - { - var result = true; - var sentString = new StringBuilder(); - var recString = new StringBuilder(); - var pingString = new StringBuilder(); - var pongString = new StringBuilder(); - - foreach (Frame frame in websocketClient.Connection.DataSent.ToArray()) - { - if (frame.FrameType == FrameType.Continuation - || frame.FrameType == FrameType.SegmentedText - || frame.FrameType == FrameType.Text - || frame.FrameType == FrameType.ContinuationFrameEnd) - { - sentString.Append(frame.Content); - } - - if (frame.FrameType == FrameType.Ping) - { - pingString.Append(frame.Content); - } - } - - foreach (Frame frame in websocketClient.Connection.DataReceived.ToArray()) - { - if (frame.FrameType == FrameType.Continuation - || frame.FrameType == FrameType.SegmentedText - || frame.FrameType == FrameType.Text - || frame.FrameType == FrameType.ContinuationFrameEnd) - { - recString.Append(frame.Content); - } - - if (frame.FrameType == FrameType.Pong) - { - pongString.Append(frame.Content); - } - } - - if (sentString.Length == recString.Length && pongString.Length == pingString.Length) - { - if (sentString.Length != recString.Length) - { - result = false; - TestUtility.LogInformation("Same size of data sent(" + sentString.Length + ") and received(" + recString.Length + ")"); - } - - if (sentString.ToString() != recString.ToString()) - { - result = false; - TestUtility.LogInformation("Not matched string in sent and received"); - } - if (pongString.Length != pingString.Length) - { - result = false; - TestUtility.LogInformation("Ping received; Ping (" + pingString.Length + ") and Pong (" + pongString.Length + ")"); - } - websocketClient.Connection.DataSent.Clear(); - websocketClient.Connection.DataReceived.Clear(); - } - else - { - TestUtility.LogInformation("Retrying... so far data sent(" + sentString.Length + ") and received(" + recString.Length + ")"); - result = false; - } - return result; - } - - private static async Task CheckChunkedAsync(HttpClient client, TestWebApplication webApp) - { - var response = await client.GetAsync(webApp.GetUri("chunked")); - var responseText = await response.Content.ReadAsStringAsync(); - try - { - Assert.Equal("Chunked", responseText); - Assert.True(response.Headers.TransferEncodingChunked, "/chunked, chunked?"); - Assert.Null(response.Headers.ConnectionClose); - Assert.Null(GetContentLength(response)); - } - catch (XunitException ex) - { - TestUtility.LogInformation(response.ToString()); - TestUtility.LogInformation(responseText); - throw ex; - } - } - - private static string GetContentLength(HttpResponseMessage response) - { - // Don't use response.Content.Headers.ContentLength, it will dynamically calculate the value if it can. - IEnumerable values; - return response.Content.Headers.TryGetValues(HeaderNames.ContentLength, out values) ? values.FirstOrDefault() : null; - } - - private static bool VerifyANCMStartEvent(DateTime startFrom, string includeThis) - { - return VerifyEventLog(1001, startFrom, includeThis); - } - - private static bool VerifyANCMGracefulShutdownEvent(DateTime startFrom, string includeThis) - { - return VerifyEventLog(1006, startFrom, includeThis); - } - - private static bool VerifyANCMGracefulShutdownFailureEvent(DateTime startFrom, string includeThis) - { - return VerifyEventLog(1005, startFrom, includeThis); - } - - private static bool VerifyApplicationEventLog(int eventID, DateTime startFrom, string includeThis) - { - return VerifyEventLog(eventID, startFrom, includeThis); - } - - private static bool VerifyEventLog(int eventId, DateTime startFrom, string includeThis = null) - { - var events = TestUtility.GetApplicationEvent(eventId, startFrom); - Assert.True(events.Count > 0, "Verfiy expected event logs"); - bool findEvent = false; - foreach (string item in events) - { - if (item.Contains(includeThis)) - { - findEvent = true; - break; - } - } - return findEvent; - } - - public class SendReceiveContext : IDisposable - { - public Uri Uri = null; - public string[] RequestHeaders = null; - public string ExpectedResponseBody = null; - public string[] ExpectedStringsInResponseBody = null; - public HttpStatusCode ExpectedResponseStatus; - public int NumberOfRetryCount = 2; - public bool VerifyResponseFlag = true; - public KeyValuePair[] PostData = null; - public int Timeout = 5; // second - - // output variables - public string ResponseBody = null; - public string ResponseHeader = null; - public string ResponseStatus = null; - - public string ResponseHeaderBody - { - get { return ResponseBody + ", " + ResponseHeader; } - } - - public void Dispose() - { - } - } - - private static async Task SendReceive(Uri uri, HttpStatusCode expectedResponseStatus = HttpStatusCode.OK, string[] requestHeaders = null, string expectedResponseBody = null, string[] expectedStringsInResponseBody = null, int timeout = 5, int numberOfRetryCount = 1, bool verifyResponseFlag = true, KeyValuePair[] postData = null) - { - using (SendReceiveContext context = new SendReceiveContext()) - { - context.Uri = uri; - context.RequestHeaders = requestHeaders; - context.ExpectedResponseBody = expectedResponseBody; - context.ExpectedStringsInResponseBody = expectedStringsInResponseBody; - context.ExpectedResponseStatus = expectedResponseStatus; - context.NumberOfRetryCount = numberOfRetryCount; - context.VerifyResponseFlag = verifyResponseFlag; - context.PostData = postData; - context.Timeout = timeout; - return await SendReceive(context); - } - } - - private static async Task ReadContent(HttpResponseMessage response) - { - bool unZipContent = false; - string result = String.Empty; - - IEnumerable values; - if (response.Headers.TryGetValues("Vary", out values)) - { - unZipContent = true; - } - - if (unZipContent) - { - var inputStream = await response.Content.ReadAsStreamAsync(); - - // for debugging purpose - //byte[] temp = new byte[inputStream.Length]; - //inputStream.Read(temp, 0, (int) inputStream.Length); - //inputStream.Position = 0; - - using (var gzip = new GZipStream(inputStream, CompressionMode.Decompress)) - { - var outputStream = new MemoryStream(); - try - { - await gzip.CopyToAsync(outputStream); - } - catch (Exception ex) - { - // Even though "Vary" response header exists, the content is not actually compressed. - // We should ignore this execption until we find a proper way to determine if the body is compressed or not. - if (ex.Message.IndexOf("gzip", StringComparison.InvariantCultureIgnoreCase) >= 0) - { - result = await response.Content.ReadAsStringAsync(); - return result; - } - throw ex; - } - gzip.Close(); - inputStream.Close(); - outputStream.Position = 0; - using (StreamReader reader = new StreamReader(outputStream, Encoding.UTF8)) - { - result = reader.ReadToEnd(); - outputStream.Close(); - } - } - } - else - { - result = await response.Content.ReadAsStringAsync(); - } - return result; - } - - private static async Task SendReceive(SendReceiveContext context) - { - Uri uri = context.Uri; - string[] requestHeaders = context.RequestHeaders; - string expectedResponseBody = context.ExpectedResponseBody; - string[] expectedStringsInResponseBody = context.ExpectedStringsInResponseBody; - HttpStatusCode expectedResponseStatus = context.ExpectedResponseStatus; - int numberOfRetryCount = context.NumberOfRetryCount; - bool verifyResponseFlag = context.VerifyResponseFlag; - KeyValuePair[] postData = context.PostData; - int timeout = context.Timeout; - - string responseText = "NotInitialized"; - string responseStatus = "NotInitialized"; - - var httpClientHandler = new HttpClientHandler(); - httpClientHandler.UseDefaultCredentials = true; - httpClientHandler.AutomaticDecompression = DecompressionMethods.None; - - var httpClient = new HttpClient(httpClientHandler) - { - BaseAddress = uri, - Timeout = TimeSpan.FromSeconds(timeout), - }; - - if (requestHeaders != null) - { - for (int i = 0; i < requestHeaders.Length; i=i+2) - { - httpClient.DefaultRequestHeaders.Add(requestHeaders[i], requestHeaders[i+1]); - } - } - - HttpResponseMessage response = null; - try - { - FormUrlEncodedContent postHttpContent = null; - if (postData != null) - { - postHttpContent = new FormUrlEncodedContent(postData); - } - - if (numberOfRetryCount > 1 && expectedResponseStatus == HttpStatusCode.OK) - { - if (postData == null) - { - response = await TestUtility.RetryRequest(() => - { - return httpClient.GetAsync(string.Empty); - }, TestUtility.Logger, retryCount: numberOfRetryCount); - } - else - { - response = await TestUtility.RetryRequest(() => - { - return httpClient.PostAsync(string.Empty, postHttpContent); - }, TestUtility.Logger, retryCount: numberOfRetryCount); - } - } - else - { - if (postData == null) - { - response = await httpClient.GetAsync(string.Empty); - } - else - { - response = await httpClient.PostAsync(string.Empty, postHttpContent); - } - } - - if (response != null) - { - responseStatus = response.StatusCode.ToString(); - if (verifyResponseFlag) - { - if (expectedResponseBody != null) - { - if (responseText == "NotInitialized") - { - responseText = await ReadContent(response); - } - Assert.Equal(expectedResponseBody, responseText); - } - - if (expectedStringsInResponseBody != null) - { - if (responseText == "NotInitialized") - { - responseText = await ReadContent(response); - } - foreach (string item in expectedStringsInResponseBody) - { - Assert.Contains(item, responseText); - } - } - Assert.Equal(expectedResponseStatus, response.StatusCode); - } - - if (responseText == "NotInitialized") - { - responseText = await ReadContent(response); - } - context.ResponseBody = responseText; - context.ResponseHeader = response.ToString(); - context.ResponseStatus = response.StatusCode.ToString(); - } - } - catch (XunitException) - { - if (response != null) - { - TestUtility.LogInformation(response.ToString()); - } - TestUtility.LogInformation(responseText); - TestUtility.LogInformation(responseStatus); - } - return context; - } - } - -} diff --git a/test/AspNetCoreModule.Test/Http.config b/test/AspNetCoreModule.Test/Http.config deleted file mode 100644 index 1518e1800f..0000000000 --- a/test/AspNetCoreModule.Test/Http.config +++ /dev/null @@ -1,1032 +0,0 @@ - - - - - - - -
-
-
-
-
-
-
-
- - - -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -
-
- -
-
-
-
-
-
- -
-
-
-
-
- -
-
-
- -
-
- -
-
- -
-
-
- - -
-
-
-
-
-
- -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/AspNetCoreModule.Test/HttpClientHelper/HttpClientHelper.cs b/test/AspNetCoreModule.Test/HttpClientHelper/HttpClientHelper.cs deleted file mode 100644 index 2266931c5b..0000000000 --- a/test/AspNetCoreModule.Test/HttpClientHelper/HttpClientHelper.cs +++ /dev/null @@ -1,336 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. 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(); - } - } -} - diff --git a/test/AspNetCoreModule.Test/WebSocketClientHelper/Frame.cs b/test/AspNetCoreModule.Test/WebSocketClientHelper/Frame.cs deleted file mode 100644 index 5e7d66a9d5..0000000000 --- a/test/AspNetCoreModule.Test/WebSocketClientHelper/Frame.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System.Text; - -namespace AspNetCoreModule.Test.WebSocketClient -{ - public class Frame - { - private int startingIndex; // This will be initialized as output parameter of GetFrameString() - public int DataLength = 0; // 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 TextData - { - get - { - if (DataLength == 0) - { - throw new System.Exception("DataLength is zero"); - } - return Encoding.ASCII.GetString(Data, startingIndex, DataLength); - } - } - - 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; - } - } -} diff --git a/test/AspNetCoreModule.Test/WebSocketClientHelper/FrameType.cs b/test/AspNetCoreModule.Test/WebSocketClientHelper/FrameType.cs deleted file mode 100644 index 50fd11aca2..0000000000 --- a/test/AspNetCoreModule.Test/WebSocketClientHelper/FrameType.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. 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, - } -} diff --git a/test/AspNetCoreModule.Test/WebSocketClientHelper/Frames.cs b/test/AspNetCoreModule.Test/WebSocketClientHelper/Frames.cs deleted file mode 100644 index f42edd644c..0000000000 --- a/test/AspNetCoreModule.Test/WebSocketClientHelper/Frames.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using System.Text; - -namespace AspNetCoreModule.Test.WebSocketClient -{ - public class Frames - { - public static byte[] CLOSE_FRAME = new byte[] { 0x88, 0x85, 0xBD, 0x60, 0x97, 0x72, 0xBE, 0x88, 0xA5, 0x40, 0x8F }; - public static byte[] PING = new byte[] { 0x89, 0x88, 0,0,0,0, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB }; - public static byte[] PONG = new byte[] { 0x8A, 0x08, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB }; - public static byte[] HELLO = new byte[] { 0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f }; - public static byte[] FRAME_4096 = new byte[] { 0x81, 0xFE, 0x10, 0x00, 0x88, 0x48, 0x9B, 0xE7, 0xDA, 0x0D, 0xD4, 0xB7, 0xCA, 0x0E, 0xD2, 0xA1, 0xD2, 0x0C, 0xD7, 0xB0, 0xCB, 0x1A, 0xC9, 0xB4, 0xC0, 0x1B, 0xD8, 0xA8, 0xC5, 0x05, 0xDC, 0xBF, 0xC7, 0x19, 0xC2, 0xAD, 0xD0, 0x1B, 0xC9, 0xA8, 0xDF, 0x0E, 0xDF, 0xB4, 0xD8, 0x12, 0xDF, 0xBD, 0xC6, 0x04, 0xCD, 0xB5, 0xD9, 0x05, 0xDA, 0xBD, 0xC5, 0x1B, 0xD9, 0xBF, 0xCD, 0x1F, 0xDF, 0xA2, 0xD0, 0x1A, 0xDA, 0xAC, 0xC0, 0x12, 0xD2, 0xA0, 0xC4, 0x10, 0xDA, 0xB0, 0xC7, 0x11, 0xD8, 0xAE, 0xD8, 0x0B, 0xD9, 0xA5, 0xDA, 0x18, 0xD3, 0xA4, 0xD8, 0x12, 0xCC, 0xA1, 0xDA, 0x1D, 0xD0, 0xA6, 0xCB, 0x11, 0xCE, 0xBE, 0xD2, 0x1B, 0xC9, 0xA9, 0xCB, 0x07, 0xDD, 0xB3, 0xC5, 0x0D, 0xD7, 0xA9, 0xD8, 0x1C, 0xD2, 0xA5, 0xDD, 0x0B, 0xD5, 0xAE, 0xC3, 0x11, 0xCD, 0xAE, 0xCB, 0x0C, 0xCB, 0xB5, 0xC5, 0x12, 0xCE, 0xB7, 0xCD, 0x0D, 0xD2, 0xB0, 0xC3, 0x06, 0xC2, 0xA3, 0xC3, 0x06, 0xCB, 0xAB, 0xC6, 0x02, 0xCB, 0xBE, 0xC4, 0x01, 0xDD, 0xBD, 0xC4, 0x05, 0xD5, 0xA5, 0xDF, 0x02, 0xD7, 0xBD, 0xD1, 0x07, 0xDC, 0xAA, 0xC3, 0x1E, 0xD1, 0xAB, 0xC3, 0x04, 0xCA, 0xAF, 0xCD, 0x02, 0xC2, 0xB0, 0xC1, 0x03, 0xCE, 0xB4, 0xC7, 0x1A, 0xDD, 0xA3, 0xDD, 0x1D, 0xDE, 0xB5, 0xD9, 0x00, 0xDA, 0xA5, 0xCA, 0x12, 0xDE, 0xB1, 0xC0, 0x0C, 0xDA, 0xB4, 0xC9, 0x0D, 0xD5, 0xA6, 0xDB, 0x10, 0xCD, 0xA5, 0xC7, 0x1A, 0xC8, 0xAA, 0xD8, 0x1C, 0xD0, 0xAF, 0xC1, 0x0B, 0xC8, 0xB7, 0xDA, 0x1A, 0xCE, 0xA4, 0xC4, 0x18, 0xDC, 0xA1, 0xCD, 0x0B, 0xCB, 0xA1, 0xC2, 0x0B, 0xC8, 0xAC, 0xCC, 0x0E, 0xD7, 0xB0, 0xD2, 0x0B, 0xDF, 0xBD, 0xD8, 0x07, 0xD6, 0xAF, 0xC7, 0x10, 0xD5, 0xA2, 0xC4, 0x04, 0xD9, 0xAE, 0xC2, 0x03, 0xD4, 0xA3, 0xDA, 0x19, 0xCC, 0xAA, 0xCB, 0x06, 0xD8, 0xA9, 0xCA, 0x09, 0xDF, 0xA3, 0xDA, 0x1E, 0xCA, 0xA8, 0xC7, 0x1E, 0xD5, 0xBF, 0xCC, 0x11, 0xCA, 0xAF, 0xC7, 0x03, 0xCE, 0xBE, 0xCA, 0x02, 0xDA, 0xB4, 0xD9, 0x01, 0xDD, 0xAE, 0xCE, 0x19, 0xCC, 0xA5, 0xC4, 0x12, 0xDC, 0xA9, 0xDC, 0x03, 0xD5, 0xB7, 0xDE, 0x05, 0xCE, 0xA9, 0xD0, 0x1A, 0xDA, 0xB4, 0xD2, 0x18, 0xC3, 0xB5, 0xDC, 0x0D, 0xD6, 0xB4, 0xC9, 0x04, 0xD6, 0xAE, 0xD8, 0x00, 0xD2, 0xBF, 0xD1, 0x05, 0xD7, 0xA2, 0xDA, 0x0B, 0xD4, 0xA2, 0xDF, 0x0D, 0xD8, 0xA8, 0xD8, 0x05, 0xCD, 0xBE, 0xC1, 0x05, 0xD2, 0xB6, 0xDC, 0x0E, 0xD2, 0xA0, 0xC5, 0x07, 0xD5, 0xAE, 0xD0, 0x0E, 0xDA, 0xA9, 0xCD, 0x1F, 0xD4, 0xAB, 0xCF, 0x1F, 0xD9, 0xBF, 0xC9, 0x1B, 0xCE, 0xB7, 0xCA, 0x10, 0xD8, 0xA9, 0xD8, 0x07, 0xDA, 0xA3, 0xD2, 0x1A, 0xDE, 0xB3, 0xCC, 0x0D, 0xC9, 0xA3, 0xD8, 0x0F, 0xDC, 0xB5, 0xCC, 0x18, 0xD0, 0xB3, 0xD1, 0x03, 0xC8, 0xAA, 0xC4, 0x04, 0xCB, 0xA6, 0xC3, 0x1C, 0xDD, 0xB7, 0xC4, 0x09, 0xC8, 0xAD, 0xCD, 0x10, 0xD4, 0xAA, 0xDA, 0x1E, 0xD3, 0xA5, 0xCE, 0x10, 0xD3, 0xB2, 0xC5, 0x0B, 0xD7, 0xAA, 0xC6, 0x02, 0xCB, 0xA1, 0xDE, 0x07, 0xC9, 0xA9, 0xCA, 0x0D, 0xD2, 0xAC, 0xD2, 0x0A, 0xC9, 0xA8, 0xC7, 0x10, 0xD5, 0xA0, 0xCA, 0x10, 0xD9, 0xA4, 0xCB, 0x1A, 0xD3, 0xA8, 0xCC, 0x1E, 0xD4, 0xAF, 0xC1, 0x1C, 0xD9, 0xA5, 0xC4, 0x05, 0xD5, 0xB6, 0xCE, 0x0A, 0xD0, 0xA9, 0xC5, 0x1F, 0xD9, 0xA3, 0xCE, 0x1C, 0xDC, 0xA8, 0xD8, 0x0D, 0xD7, 0xB7, 0xC1, 0x05, 0xD8, 0xA2, 0xC0, 0x0C, 0xD1, 0xA0, 0xD8, 0x09, 0xD8, 0xA0, 0xC9, 0x19, 0xDF, 0xA5, 0xC2, 0x1F, 0xD9, 0xBD, 0xC6, 0x06, 0xCB, 0xA1, 0xD8, 0x0C, 0xD2, 0xAC, 0xC7, 0x12, 0xC9, 0xA3, 0xC0, 0x04, 0xCF, 0xBE, 0xC2, 0x02, 0xD1, 0xA5, 0xDA, 0x0D, 0xC2, 0xAB, 0xDD, 0x1E, 0xDF, 0xB7, 0xD8, 0x0E, 0xDE, 0xB3, 0xCC, 0x04, 0xD8, 0xB2, 0xDF, 0x10, 0xD4, 0xA3, 0xDE, 0x11, 0xC9, 0xB7, 0xC2, 0x11, 0xC2, 0xA8, 0xDF, 0x0D, 0xC9, 0xBD, 0xC6, 0x12, 0xD2, 0xAD, 0xD8, 0x0C, 0xD7, 0xB2, 0xC9, 0x1B, 0xCE, 0xAD, 0xDE, 0x11, 0xDA, 0xB0, 0xC1, 0x11, 0xD9, 0xAA, 0xDE, 0x0E, 0xDC, 0xB3, 0xC5, 0x01, 0xD8, 0xB1, 0xD0, 0x07, 0xCF, 0xAB, 0xC6, 0x0E, 0xDD, 0xA3, 0xCB, 0x1C, 0xDE, 0xB3, 0xC4, 0x1D, 0xDF, 0xA4, 0xCC, 0x00, 0xCE, 0xAC, 0xD1, 0x0A, 0xDD, 0xBF, 0xCB, 0x0E, 0xDE, 0xAF, 0xDB, 0x18, 0xCC, 0xAF, 0xCA, 0x18, 0xCC, 0xAA, 0xD2, 0x02, 0xCC, 0xB6, 0xDB, 0x1F, 0xCF, 0xB7, 0xDD, 0x01, 0xDA, 0xA6, 0xCB, 0x0D, 0xCB, 0xA2, 0xC6, 0x1B, 0xC3, 0xB1, 0xC1, 0x1E, 0xD1, 0xAF, 0xC9, 0x10, 0xD7, 0xA9, 0xD0, 0x10, 0xC8, 0xB0, 0xD0, 0x19, 0xD8, 0xB2, 0xC4, 0x0D, 0xC9, 0xA5, 0xC0, 0x19, 0xDF, 0xB3, 0xCE, 0x0C, 0xDD, 0xA9, 0xD2, 0x1B, 0xCF, 0xAE, 0xDB, 0x0A, 0xDF, 0xA3, 0xD2, 0x07, 0xCB, 0xB1, 0xC3, 0x0F, 0xC8, 0xB0, 0xD9, 0x0D, 0xDF, 0xAB, 0xCA, 0x1E, 0xC8, 0xAD, 0xC9, 0x1E, 0xD5, 0xB5, 0xDB, 0x18, 0xD8, 0xBF, 0xDB, 0x10, 0xD4, 0xA2, 0xCC, 0x02, 0xDF, 0xB1, 0xC6, 0x11, 0xCE, 0xBF, 0xC7, 0x1F, 0xCA, 0xA5, 0xD1, 0x0F, 0xD8, 0xA6, 0xD2, 0x1C, 0xD6, 0xA2, 0xD2, 0x03, 0xD3, 0xBF, 0xC6, 0x04, 0xD7, 0xAD, 0xC4, 0x1B, 0xD8, 0xA9, 0xDA, 0x06, 0xC8, 0xAF, 0xC9, 0x00, 0xC3, 0xA3, 0xC9, 0x1E, 0xCE, 0xA2, 0xCD, 0x05, 0xCF, 0xAB, 0xC6, 0x0A, 0xC3, 0xBE, 0xC4, 0x02, 0xDD, 0xB3, 0xCA, 0x0F, 0xD2, 0xA4, 0xC6, 0x03, 0xD7, 0xB0, 0xDC, 0x0C, 0xD1, 0xAB, 0xC7, 0x1E, 0xDA, 0xB4, 0xDE, 0x01, 0xDE, 0xA2, 0xD9, 0x0C, 0xCF, 0xA5, 0xDB, 0x09, 0xCC, 0xAD, 0xDE, 0x0C, 0xD9, 0xAF, 0xC1, 0x12, 0xDD, 0xB2, 0xD2, 0x1E, 0xCA, 0xB7, 0xC2, 0x10, 0xD0, 0xA6, 0xCB, 0x00, 0xCC, 0xB5, 0xCA, 0x0D, 0xDF, 0xA4, 0xCE, 0x09, 0xDF, 0xBE, 0xC5, 0x00, 0xD1, 0xAA, 0xC7, 0x0B, 0xD9, 0xB6, 0xCB, 0x0A, 0xDF, 0xA8, 0xD8, 0x0F, 0xCF, 0xBD, 0xDB, 0x07, 0xCE, 0xB4, 0xDB, 0x1B, 0xC2, 0xAC, 0xCC, 0x0D, 0xD3, 0xB6, 0xC9, 0x11, 0xD8, 0xAF, 0xDE, 0x00, 0xD3, 0xB5, 0xC5, 0x0C, 0xDA, 0xAF, 0xDF, 0x1D, 0xC2, 0xA6, 0xCD, 0x01, 0xD8, 0xB1, 0xC4, 0x0C, 0xD1, 0xB5, 0xCF, 0x04, 0xDD, 0xB2, 0xC2, 0x11, 0xD1, 0xAD, 0xDD, 0x04, 0xCB, 0xA3, 0xD2, 0x1E, 0xCF, 0xAE, 0xD1, 0x0A, 0xD5, 0xB7, 0xC6, 0x06, 0xCD, 0xBF, 0xDD, 0x10, 0xDC, 0xB1, 0xCB, 0x05, 0xDE, 0xBF, 0xD8, 0x03, 0xD9, 0xAC, 0xCA, 0x06, 0xD2, 0xA9, 0xDD, 0x19, 0xD6, 0xAB, 0xCD, 0x1E, 0xD9, 0xAD, 0xC7, 0x1C, 0xCC, 0xAD, 0xD9, 0x1D, 0xDF, 0xB4, 0xD8, 0x00, 0xC1, 0xAB, 0xDB, 0x06, 0xD3, 0xAF, 0xCF, 0x1B, 0xD4, 0xA8, 0xDD, 0x01, 0xD3, 0xAB, 0xDC, 0x12, 0xCE, 0xB0, 0xC9, 0x03, 0xCF, 0xBD, 0xDF, 0x10, 0xDC, 0xAE, 0xD9, 0x1E, 0xDC, 0xB2, 0xC0, 0x01, 0xCD, 0xB3, 0xC6, 0x10, 0xCD, 0xA0, 0xC2, 0x0E, 0xDE, 0xAA, 0xC0, 0x05, 0xD4, 0xA0, 0xC5, 0x03, 0xCA, 0xB6, 0xD2, 0x0F, 0xC8, 0xA2, 0xC7, 0x09, 0xCB, 0xB1, 0xC0, 0x11, 0xC9, 0xAB, 0xC4, 0x1C, 0xD3, 0xAA, 0xC5, 0x06, 0xC2, 0xB1, 0xCD, 0x07, 0xD5, 0xB1, 0xCE, 0x0F, 0xC8, 0xAC, 0xC1, 0x12, 0xCC, 0xA1, 0xCD, 0x19, 0xCD, 0xA5, 0xD9, 0x19, 0xDE, 0xAA, 0xC0, 0x09, 0xC1, 0xAB, 0xC6, 0x1C, 0xDA, 0xA9, 0xCE, 0x0B, 0xCF, 0xBE, 0xC5, 0x1D, 0xD6, 0xAB, 0xDC, 0x1F, 0xC1, 0xAF, 0xC1, 0x0E, 0xD6, 0xAF, 0xCA, 0x04, 0xDC, 0xB1, 0xD1, 0x0F, 0xCD, 0xB0, 0xC1, 0x05, 0xD4, 0xA3, 0xC7, 0x0A, 0xD3, 0xAB, 0xCF, 0x0D, 0xDD, 0xA0, 0xCE, 0x10, 0xCF, 0xAD, 0xCC, 0x02, 0xD3, 0xB3, 0xDA, 0x1F, 0xDF, 0xA4, 0xC6, 0x1B, 0xD1, 0xA5, 0xC6, 0x0E, 0xCB, 0xBE, 0xCF, 0x10, 0xCA, 0xBD, 0xCF, 0x01, 0xCC, 0xB5, 0xC7, 0x06, 0xD9, 0xA2, 0xC9, 0x0F, 0xD9, 0xA2, 0xDB, 0x10, 0xC9, 0xA8, 0xD1, 0x0B, 0xDD, 0xAA, 0xC1, 0x04, 0xCA, 0xB0, 0xDB, 0x0F, 0xC2, 0xA5, 0xD8, 0x0F, 0xC1, 0xAE, 0xC0, 0x1C, 0xD8, 0xB1, 0xC6, 0x19, 0xDE, 0xA3, 0xDE, 0x12, 0xD8, 0xA0, 0xD9, 0x0D, 0xD1, 0xB7, 0xC6, 0x09, 0xDA, 0xA2, 0xDB, 0x0C, 0xC9, 0xB1, 0xDA, 0x09, 0xC2, 0xAE, 0xC7, 0x09, 0xD4, 0xB3, 0xC0, 0x1B, 0xC3, 0xBE, 0xDD, 0x1F, 0xD9, 0xAF, 0xD0, 0x0A, 0xC9, 0xAE, 0xC1, 0x02, 0xDD, 0xA9, 0xDF, 0x02, 0xD5, 0xA8, 0xCE, 0x1E, 0xCA, 0xA3, 0xCB, 0x00, 0xDF, 0xAA, 0xDA, 0x1E, 0xD4, 0xB2, 0xC3, 0x01, 0xC1, 0xBE, 0xC0, 0x03, 0xCD, 0xB6, 0xD2, 0x1C, 0xDC, 0xB6, 0xC5, 0x01, 0xD5, 0xAF, 0xDD, 0x04, 0xD6, 0xA1, 0xC5, 0x09, 0xD4, 0xAA, 0xCB, 0x1C, 0xCC, 0xA9, 0xDC, 0x07, 0xCA, 0xA4, 0xC6, 0x1F, 0xC2, 0xBD, 0xC3, 0x00, 0xDC, 0xAB, 0xC7, 0x1F, 0xD4, 0xAA, 0xC7, 0x09, 0xCA, 0xB3, 0xDD, 0x1E, 0xC8, 0xA0, 0xC2, 0x01, 0xD3, 0xAC, 0xDD, 0x06, 0xCD, 0xA9, 0xC7, 0x00, 0xC3, 0xAB, 0xCC, 0x0D, 0xDF, 0xB6, 0xC3, 0x06, 0xC3, 0xA9, 0xCD, 0x09, 0xC9, 0xB7, 0xC4, 0x0B, 0xC3, 0xA5, 0xCB, 0x0B, 0xCF, 0xBE, 0xDF, 0x02, 0xC8, 0xA2, 0xC7, 0x07, 0xDD, 0xBF, 0xC4, 0x1B, 0xC3, 0xA0, 0xD2, 0x0B, 0xD1, 0xAC, 0xD0, 0x09, 0xD1, 0xA0, 0xD0, 0x0D, 0xD9, 0xAD, 0xD9, 0x1A, 0xC2, 0xB5, 0xD8, 0x1D, 0xD7, 0xAB, 0xC6, 0x11, 0xCB, 0xB3, 0xC4, 0x11, 0xD9, 0xB0, 0xC0, 0x12, 0xD8, 0xAA, 0xCC, 0x04, 0xCA, 0xAD, 0xDC, 0x05, 0xDE, 0xA4, 0xDC, 0x05, 0xDA, 0xB5, 0xC0, 0x02, 0xD5, 0xB0, 0xD8, 0x06, 0xD3, 0xB5, 0xCF, 0x04, 0xC8, 0xA5, 0xC5, 0x18, 0xC1, 0xBE, 0xD1, 0x06, 0xC2, 0xBE, 0xCB, 0x18, 0xDD, 0xA1, 0xCA, 0x07, 0xC2, 0xA3, 0xD8, 0x02, 0xC8, 0xA6, 0xD0, 0x11, 0xD6, 0xA4, 0xC4, 0x0D, 0xDC, 0xB2, 0xDA, 0x04, 0xDD, 0xB4, 0xDB, 0x18, 0xCC, 0xA3, 0xC6, 0x0F }; - public static byte[] FRAME_5000 = new byte[] { 0x81, 0xFE, 0x13, 0x88, 0x17, 0x84, 0x25, 0xB2, 0x58, 0xC6, 0x71, 0xE0, 0x4E, 0xD5, 0x77, 0xE0, 0x50, 0xD0, 0x69, 0xFA, 0x43, 0xCF, 0x75, 0xFF, 0x5C, 0xCB, 0x60, 0xE1, 0x52, 0xD0, 0x70, 0xFE, 0x5D, 0xCE, 0x71, 0xF3, 0x44, 0xC7, 0x60, 0xF0, 0x58, 0xC8, 0x6D, 0xE8, 0x5E, 0xDE, 0x60, 0xFF, 0x51, 0xCA, 0x6A, 0xF0, 0x44, 0xDE, 0x62, 0xE6, 0x59, 0xC5, 0x67, 0xEB, 0x4E, 0xC1, 0x77, 0xE4, 0x50, 0xCC, 0x6D, 0xE2, 0x40, 0xD5, 0x7C, 0xF6, 0x58, 0xCF, 0x76, 0xFA, 0x54, 0xD4, 0x60, 0xFE, 0x5D, 0xD6, 0x68, 0xE0, 0x52, 0xD0, 0x71, 0xF9, 0x54, 0xDE, 0x6B, 0xE0, 0x55, 0xC3, 0x66, 0xF8, 0x42, 0xC8, 0x71, 0xF3, 0x45, 0xD4, 0x75, 0xFD, 0x58, 0xC8, 0x68, 0xFA, 0x50, 0xDE, 0x77, 0xEA, 0x40, 0xD4, 0x6A, 0xF5, 0x44, 0xC5, 0x74, 0xFC, 0x58, 0xDC, 0x68, 0xEA, 0x53, 0xC3, 0x67, 0xFB, 0x5F, 0xCE, 0x6B, 0xE3, 0x40, 0xC0, 0x71, 0xE6, 0x55, 0xDC, 0x66, 0xE6, 0x50, 0xC8, 0x61, 0xF1, 0x5E, 0xD4, 0x73, 0xFE, 0x45, 0xD2, 0x77, 0xE6, 0x41, 0xC2, 0x68, 0xE7, 0x54, 0xD7, 0x69, 0xFA, 0x5D, 0xC1, 0x7F, 0xEA, 0x5A, 0xC5, 0x67, 0xE6, 0x40, 0xD2, 0x63, 0xE7, 0x4F, 0xDC, 0x62, 0xF6, 0x43, 0xCE, 0x6A, 0xFC, 0x5B, 0xD4, 0x74, 0xFF, 0x45, 0xD0, 0x73, 0xE3, 0x46, 0xDD, 0x74, 0xFB, 0x5A, 0xD2, 0x6F, 0xF1, 0x5B, 0xC3, 0x74, 0xFB, 0x58, 0xC7, 0x75, 0xE5, 0x46, 0xDC, 0x72, 0xEA, 0x4E, 0xCE, 0x67, 0xE6, 0x52, 0xDC, 0x72, 0xE7, 0x59, 0xCA, 0x63, 0xE1, 0x52, 0xCF, 0x66, 0xEA, 0x52, 0xD3, 0x6D, 0xF1, 0x58, 0xC0, 0x77, 0xFC, 0x43, 0xC3, 0x7F, 0xF8, 0x56, 0xD0, 0x73, 0xE7, 0x4F, 0xDD, 0x76, 0xFA, 0x4F, 0xDC, 0x60, 0xFD, 0x4D, 0xCB, 0x6A, 0xEA, 0x56, 0xDC, 0x61, 0xF7, 0x4D, 0xD6, 0x76, 0xE6, 0x47, 0xD0, 0x6C, 0xE7, 0x45, 0xCB, 0x7F, 0xEB, 0x4E, 0xC9, 0x71, 0xE7, 0x44, 0xCF, 0x73, 0xF5, 0x44, 0xD1, 0x64, 0xF5, 0x44, 0xD7, 0x61, 0xE8, 0x58, 0xD1, 0x68, 0xE4, 0x54, 0xD1, 0x6F, 0xFB, 0x56, 0xC7, 0x63, 0xF6, 0x47, 0xDC, 0x74, 0xF8, 0x4F, 0xC2, 0x74, 0xFF, 0x41, 0xD1, 0x63, 0xE3, 0x54, 0xD3, 0x68, 0xF4, 0x46, 0xC9, 0x64, 0xE5, 0x46, 0xCE, 0x63, 0xEA, 0x55, 0xC1, 0x73, 0xF6, 0x54, 0xC8, 0x71, 0xE3, 0x52, 0xD7, 0x77, 0xE7, 0x52, 0xD6, 0x6C, 0xFF, 0x54, 0xD5, 0x60, 0xE7, 0x58, 0xD3, 0x76, 0xF5, 0x5E, 0xC1, 0x77, 0xFD, 0x55, 0xCE, 0x6B, 0xF4, 0x45, 0xD0, 0x6D, 0xE6, 0x5C, 0xC9, 0x6F, 0xF8, 0x55, 0xD4, 0x69, 0xF9, 0x52, 0xD6, 0x67, 0xE8, 0x53, 0xCB, 0x71, 0xE8, 0x52, 0xC8, 0x6C, 0xF4, 0x5B, 0xCB, 0x73, 0xEB, 0x43, 0xC1, 0x75, 0xE4, 0x51, 0xC8, 0x61, 0xF9, 0x5C, 0xD4, 0x66, 0xE2, 0x5F, 0xD1, 0x76, 0xE8, 0x5C, 0xCD, 0x67, 0xE0, 0x53, 0xD7, 0x6E, 0xFF, 0x47, 0xCA, 0x64, 0xF4, 0x5C, 0xC6, 0x6D, 0xE4, 0x45, 0xC8, 0x74, 0xE5, 0x56, 0xD4, 0x63, 0xE6, 0x59, 0xD5, 0x6A, 0xFD, 0x5B, 0xC0, 0x76, 0xF9, 0x44, 0xCD, 0x70, 0xF6, 0x59, 0xC1, 0x73, 0xF3, 0x43, 0xC7, 0x62, 0xE0, 0x5B, 0xDD, 0x7F, 0xFB, 0x5F, 0xCC, 0x7C, 0xE5, 0x52, 0xD2, 0x7F, 0xE4, 0x53, 0xCD, 0x61, 0xFF, 0x53, 0xD3, 0x67, 0xFE, 0x41, 0xD5, 0x68, 0xF1, 0x5F, 0xC1, 0x6D, 0xFF, 0x47, 0xD4, 0x61, 0xEA, 0x5D, 0xCA, 0x6D, 0xE2, 0x46, 0xC3, 0x6D, 0xF7, 0x51, 0xD2, 0x62, 0xEA, 0x5D, 0xDE, 0x7F, 0xF7, 0x55, 0xCD, 0x72, 0xEA, 0x56, 0xD1, 0x72, 0xE7, 0x5B, 0xDC, 0x67, 0xF6, 0x4D, 0xC8, 0x62, 0xFD, 0x44, 0xC6, 0x69, 0xE2, 0x56, 0xCA, 0x72, 0xEA, 0x47, 0xDC, 0x62, 0xE8, 0x5D, 0xD4, 0x71, 0xFA, 0x52, 0xC0, 0x69, 0xFA, 0x43, 0xC2, 0x7D, 0xE2, 0x45, 0xCA, 0x60, 0xE1, 0x51, 0xC0, 0x60, 0xE6, 0x47, 0xD7, 0x60, 0xFA, 0x59, 0xCE, 0x60, 0xFC, 0x5A, 0xDE, 0x6C, 0xF6, 0x58, 0xDC, 0x6E, 0xE5, 0x52, 0xD0, 0x7C, 0xE5, 0x4D, 0xDE, 0x73, 0xFF, 0x52, 0xD3, 0x7C, 0xFC, 0x5D, 0xC0, 0x77, 0xFE, 0x44, 0xC9, 0x6F, 0xE0, 0x5C, 0xC8, 0x71, 0xE4, 0x4E, 0xDD, 0x73, 0xE6, 0x4F, 0xD1, 0x64, 0xE7, 0x54, 0xCC, 0x6A, 0xFE, 0x51, 0xCD, 0x71, 0xE3, 0x4F, 0xD6, 0x61, 0xE0, 0x5B, 0xD5, 0x61, 0xFB, 0x5F, 0xDC, 0x6E, 0xF0, 0x59, 0xD0, 0x69, 0xE6, 0x4D, 0xC0, 0x7D, 0xF0, 0x53, 0xC6, 0x75, 0xF9, 0x41, 0xC1, 0x69, 0xF0, 0x47, 0xC2, 0x62, 0xF8, 0x44, 0xD0, 0x70, 0xE6, 0x5E, 0xC7, 0x6F, 0xFB, 0x42, 0xC9, 0x69, 0xF3, 0x5D, 0xDE, 0x62, 0xFB, 0x40, 0xD2, 0x68, 0xF1, 0x5B, 0xD7, 0x68, 0xE4, 0x55, 0xD0, 0x73, 0xFA, 0x52, 0xC7, 0x71, 0xF1, 0x45, 0xC5, 0x6C, 0xE7, 0x4D, 0xD7, 0x6E, 0xE5, 0x43, 0xCB, 0x62, 0xE0, 0x46, 0xD4, 0x64, 0xE5, 0x4F, 0xC7, 0x60, 0xE6, 0x43, 0xC0, 0x7C, 0xF3, 0x50, 0xDD, 0x77, 0xE2, 0x5F, 0xC7, 0x61, 0xE1, 0x44, 0xCE, 0x6F, 0xFB, 0x46, 0xC9, 0x6F, 0xF7, 0x5C, 0xD4, 0x6C, 0xE5, 0x5A, 0xD1, 0x60, 0xFF, 0x44, 0xDD, 0x6F, 0xF1, 0x4F, 0xDE, 0x6C, 0xFC, 0x54, 0xCD, 0x6B, 0xF3, 0x56, 0xD2, 0x75, 0xE3, 0x5B, 0xCA, 0x7F, 0xFA, 0x50, 0xD7, 0x62, 0xF9, 0x43, 0xC5, 0x6F, 0xF6, 0x41, 0xC7, 0x6B, 0xFE, 0x43, 0xC2, 0x7D, 0xFB, 0x43, 0xC6, 0x73, 0xE1, 0x56, 0xD2, 0x62, 0xFA, 0x4D, 0xCE, 0x61, 0xE2, 0x56, 0xD6, 0x6E, 0xEB, 0x41, 0xDC, 0x63, 0xF3, 0x45, 0xDE, 0x6C, 0xE5, 0x46, 0xC2, 0x77, 0xF3, 0x41, 0xC6, 0x62, 0xE4, 0x4E, 0xC3, 0x7D, 0xF9, 0x44, 0xC3, 0x6D, 0xF9, 0x5B, 0xDE, 0x6E, 0xF8, 0x4F, 0xD1, 0x66, 0xF6, 0x45, 0xD4, 0x74, 0xE5, 0x4D, 0xD3, 0x74, 0xE6, 0x44, 0xDD, 0x66, 0xE7, 0x52, 0xC2, 0x68, 0xEB, 0x53, 0xCC, 0x74, 0xE7, 0x42, 0xC5, 0x63, 0xE2, 0x46, 0xD2, 0x6A, 0xE1, 0x58, 0xDE, 0x7F, 0xE5, 0x54, 0xCB, 0x6F, 0xF4, 0x5B, 0xCE, 0x72, 0xF0, 0x47, 0xC1, 0x77, 0xE6, 0x52, 0xC9, 0x62, 0xF4, 0x5A, 0xC9, 0x62, 0xE2, 0x53, 0xCD, 0x6F, 0xE3, 0x5D, 0xC5, 0x63, 0xF7, 0x5E, 0xDD, 0x60, 0xE6, 0x4D, 0xC2, 0x76, 0xE3, 0x40, 0xC3, 0x6B, 0xE6, 0x5C, 0xD4, 0x60, 0xE3, 0x5D, 0xC8, 0x6E, 0xF7, 0x58, 0xCD, 0x63, 0xF1, 0x43, 0xCE, 0x71, 0xE7, 0x52, 0xD7, 0x72, 0xF9, 0x52, 0xD7, 0x76, 0xE0, 0x4D, 0xDD, 0x70, 0xEB, 0x42, 0xD5, 0x6F, 0xF5, 0x4D, 0xCA, 0x63, 0xFC, 0x53, 0xD0, 0x6D, 0xEA, 0x46, 0xC6, 0x75, 0xF3, 0x44, 0xC7, 0x7F, 0xE3, 0x5A, 0xDC, 0x69, 0xF6, 0x5C, 0xC7, 0x75, 0xE1, 0x40, 0xCA, 0x74, 0xF9, 0x45, 0xC8, 0x6E, 0xEB, 0x4D, 0xDE, 0x61, 0xF5, 0x52, 0xC2, 0x74, 0xFE, 0x5B, 0xDD, 0x70, 0xF1, 0x53, 0xD7, 0x7C, 0xE5, 0x4E, 0xC1, 0x68, 0xE5, 0x52, 0xC2, 0x73, 0xE5, 0x4F, 0xCA, 0x74, 0xE3, 0x54, 0xD3, 0x62, 0xF7, 0x45, 0xD5, 0x67, 0xE6, 0x4D, 0xD0, 0x68, 0xFA, 0x5F, 0xC5, 0x76, 0xFF, 0x5E, 0xC9, 0x6A, 0xF7, 0x47, 0xD1, 0x69, 0xFF, 0x4D, 0xCA, 0x70, 0xE6, 0x53, 0xC3, 0x6C, 0xE0, 0x58, 0xC5, 0x6F, 0xE2, 0x45, 0xD5, 0x69, 0xFF, 0x45, 0xC1, 0x7D, 0xF7, 0x44, 0xC2, 0x6A, 0xF7, 0x59, 0xCE, 0x6A, 0xFE, 0x4E, 0xC8, 0x64, 0xFA, 0x5B, 0xD0, 0x60, 0xF6, 0x40, 0xCC, 0x74, 0xE1, 0x5B, 0xD1, 0x76, 0xFA, 0x45, 0xC0, 0x70, 0xE0, 0x55, 0xC6, 0x6B, 0xF9, 0x4F, 0xC3, 0x70, 0xE7, 0x4D, 0xD4, 0x62, 0xE6, 0x44, 0xD3, 0x76, 0xF1, 0x4D, 0xC6, 0x61, 0xEA, 0x5B, 0xCC, 0x74, 0xF8, 0x58, 0xC1, 0x71, 0xEA, 0x59, 0xCC, 0x6B, 0xF9, 0x47, 0xD3, 0x6E, 0xE5, 0x4E, 0xD4, 0x6E, 0xF7, 0x4D, 0xCF, 0x60, 0xF5, 0x56, 0xD3, 0x64, 0xE2, 0x54, 0xD4, 0x6C, 0xE2, 0x4D, 0xD3, 0x62, 0xE6, 0x5C, 0xC0, 0x72, 0xE6, 0x59, 0xDC, 0x6D, 0xE0, 0x54, 0xD3, 0x60, 0xE4, 0x5A, 0xD3, 0x60, 0xF8, 0x46, 0xDE, 0x7C, 0xF0, 0x54, 0xCF, 0x6C, 0xE1, 0x53, 0xC0, 0x73, 0xEA, 0x4D, 0xDC, 0x69, 0xE1, 0x46, 0xD5, 0x69, 0xE7, 0x43, 0xD6, 0x74, 0xF1, 0x54, 0xC9, 0x61, 0xF7, 0x45, 0xC2, 0x66, 0xF4, 0x5C, 0xDD, 0x7F, 0xE8, 0x4F, 0xC1, 0x74, 0xF3, 0x41, 0xC0, 0x75, 0xF8, 0x55, 0xCE, 0x76, 0xF7, 0x5B, 0xC8, 0x63, 0xE5, 0x5B, 0xCF, 0x75, 0xE8, 0x5D, 0xD3, 0x7C, 0xE3, 0x5F, 0xC1, 0x64, 0xEB, 0x55, 0xD5, 0x68, 0xF3, 0x4E, 0xC8, 0x70, 0xFE, 0x4D, 0xC8, 0x7F, 0xE3, 0x55, 0xC3, 0x64, 0xE6, 0x42, 0xDD, 0x71, 0xF4, 0x4D, 0xC3, 0x71, 0xF3, 0x5D, 0xDE, 0x74, 0xF0, 0x50, 0xC5, 0x76, 0xE3, 0x53, 0xD6, 0x6C, 0xFE, 0x40, 0xD7, 0x62, 0xE8, 0x45, 0xD0, 0x72, 0xF3, 0x5C, 0xDE, 0x7D, 0xF1, 0x41, 0xC2, 0x72, 0xFB, 0x5B, 0xD1, 0x7C, 0xE7, 0x40, 0xC9, 0x77, 0xEB, 0x41, 0xD0, 0x63, 0xE8, 0x44, 0xCD, 0x68, 0xF9, 0x4E, 0xD4, 0x72, 0xF0, 0x45, 0xD0, 0x6A, 0xF4, 0x5C, 0xD0, 0x75, 0xF8, 0x54, 0xCB, 0x63, 0xF3, 0x52, 0xCF, 0x63, 0xFB, 0x43, 0xCA, 0x75, 0xF9, 0x56, 0xCD, 0x61, 0xEA, 0x58, 0xDC, 0x6C, 0xF1, 0x5A, 0xCA, 0x61, 0xF5, 0x5E, 0xD1, 0x74, 0xE0, 0x50, 0xD7, 0x6E, 0xF6, 0x40, 0xCC, 0x72, 0xFA, 0x59, 0xC1, 0x73, 0xFB, 0x54, 0xC1, 0x74, 0xFE, 0x56, 0xC9, 0x64, 0xF8, 0x46, 0xD5, 0x77, 0xFC, 0x5B, 0xCA, 0x7D, 0xFD, 0x5C, 0xDE, 0x76, 0xF8, 0x43, 0xCB, 0x67, 0xF3, 0x53, 0xC9, 0x6B, 0xE6, 0x5A, 0xD3, 0x6F, 0xF9, 0x54, 0xC5, 0x7F, 0xFA, 0x40, 0xD7, 0x62, 0xE5, 0x43, 0xC3, 0x67, 0xE2, 0x56, 0xDC, 0x77, 0xFB, 0x5C, 0xCC, 0x72, 0xFD, 0x5A, 0xC8, 0x6A, 0xFD, 0x53, 0xD4, 0x6D, 0xFD, 0x4E, 0xCC, 0x7D, 0xE6, 0x50, 0xCC, 0x6E, 0xFE, 0x58, 0xD4, 0x77, 0xE1, 0x44, 0xD3, 0x74, 0xFF, 0x59, 0xC9, 0x64, 0xF4, 0x42, 0xC1, 0x6C, 0xF7, 0x56, 0xD2, 0x7C, 0xE3, 0x5B, 0xCF, 0x60, 0xFA, 0x5C, 0xD7 }; - - public static byte[][] GetHandShakeFrame(string url, int websocketVersion) - { - var address = new Uri(url); - - return new[] - { - Encoding.UTF8.GetBytes("GET " + address.PathAndQuery), - Encoding.UTF8.GetBytes(" HTTP/1.1\r\n"), - Encoding.UTF8.GetBytes(string.Format("Host: {0}:{1}", address.Host, address.Port)), - Encoding.UTF8.GetBytes("\r\nUpgrade: WebSocket\r\n"), - Encoding.UTF8.GetBytes("connection: upgrade\r\n"), - Encoding.UTF8.GetBytes("Sec-WebSocket-Origin: http://localhost:80\r\n"), - Encoding.UTF8.GetBytes("Sec-WebSocket-Version: "+websocketVersion+"\r\n"), - Encoding.UTF8.GetBytes("Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"), - Encoding.UTF8.GetBytes("Sec-WebSocket-Protocol: mywebsocketsubprotocol\r\n"), - Encoding.UTF8.GetBytes("\r"), - Encoding.UTF8.GetBytes("\n") - }; - } - - - public static byte[][] GetHandShakeFrameWithAffinityCookie(string url, int websocketVersion, string AffinityCookie) - { - var address = new Uri(url); - - return new[] - { - Encoding.UTF8.GetBytes("GET " + address.PathAndQuery), - Encoding.UTF8.GetBytes(" HTTP/1.1\r\n"), - Encoding.UTF8.GetBytes(string.Format("Host: {0}:{1}", address.Host, address.Port)), - Encoding.UTF8.GetBytes("\r\nUpgrade: WebSocket\r\n"), - Encoding.UTF8.GetBytes("connection: upgrade\r\n"), - Encoding.UTF8.GetBytes("Sec-WebSocket-Origin: http://localhost:80\r\n"), - Encoding.UTF8.GetBytes("Sec-WebSocket-Version: "+websocketVersion+"\r\n"), - Encoding.UTF8.GetBytes("Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"), - Encoding.UTF8.GetBytes("Cookie: "+AffinityCookie+"\r\n"), - Encoding.UTF8.GetBytes("\r"), - Encoding.UTF8.GetBytes("\n") - }; - } - - } -} diff --git a/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketClientHelper.cs b/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketClientHelper.cs deleted file mode 100644 index 76b038c792..0000000000 --- a/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketClientHelper.cs +++ /dev/null @@ -1,445 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. 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; - -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 bool WaitForWebSocketState(WebSocketState expectedState, int timeout = 3000) - { - bool result = false; - int RETRYMAX = 300; - int INTERVAL = 100; // ms - if (timeout > RETRYMAX * INTERVAL) - { - throw new Exception("timeout should be less than " + 100 * 300); - } - for (int i=0; i timeout) - { - break; - } - if (this.WebSocketState == expectedState) - { - result = true; - break; - } - else - { - Thread.Sleep(INTERVAL); - } - } - return result; - } - - public Frame Connect(Uri address, bool storeData, bool isAlwaysReading, bool waitForConnectionOpen = true) - { - Address = address; - StoreData = storeData; - - Connection = new WebSocketConnect(); - if (isAlwaysReading) - { - InitiateWithAlwaysReading(); - } - SendWebSocketRequest(WebSocketClientUtility.WebSocketVersion); - - if (waitForConnectionOpen) - { - if (!WaitForWebSocketState(WebSocketState.ConnectionOpen)) - { - throw new Exception("Failed to open a connection"); - } - } - else - { - Thread.Sleep(3000); - } - - if (this.WebSocketState == WebSocketState.ConnectionOpen) - { - IsOpened = true; - } - else - { - IsOpened = false; - } - - Frame openingFrame = null; - - if (!IsAlwaysReading) - openingFrame = ReadData(); - else - openingFrame = Connection.DataReceived[0]; - - return openingFrame; - } - - public Frame Close() - { - CloseConnection(); - - 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(); - Connection.DataReceived = new List(); - } - } - - 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); - ProcessReceivedData(frame); - int nextFrameIndex = frame.IndexOfNextFrame; - - while (nextFrameIndex != -1) - { - tempBuffer = tempBuffer.SubArray(frame.IndexOfNextFrame, tempBuffer.Length - frame.IndexOfNextFrame); - frame = new Frame(tempBuffer); - ProcessReceivedData(frame); - nextFrameIndex = frame.IndexOfNextFrame; - } - - 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 SendClose() - { - Send(Frames.CLOSE_FRAME); - } - - 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() - { - this.WebSocketState = WebSocketState.ClosingFromClientStarted; - Send(Frames.CLOSE_FRAME); - - if (!WaitForWebSocketState(WebSocketState.ConnectionClosed)) - { - throw new Exception("Failed to close a connection"); - } - } - - 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) - { - TestUtility.LogInformation("ReadDataCallback: Client {0:D3}: Read Type {1} : {2} ", Connection.Id, frame.FrameType, frame.DataLength); - if (frame.FrameType == FrameType.NonControlFrame) - { - string content = frame.Content.ToLower(); - if (content.Contains("connection: upgrade") - && content.Contains("upgrade: websocket") - && content.Contains("http/1.1 101 switching protocols")) - { - TestUtility.LogInformation("Connection opened..."); - TestUtility.LogInformation(frame.Content); - WebSocketState = WebSocketState.ConnectionOpen; - } - } - else - { - // Send Pong if the frame was Ping - if (frame.FrameType == FrameType.Ping) - SendPong(frame); - - // Send Close if the frame was Close - if (frame.FrameType == FrameType.Close) - { - if (WebSocketState == WebSocketState.ConnectionClosed) - { - throw new Exception("Connection was already closed"); - } - else - { - if (WebSocketState != WebSocketState.ClosingFromClientStarted) - { - TestUtility.LogInformation("Send back Close frame to responsd server closing..."); - SendClose(); - } - TestUtility.LogInformation(frame.Content); - WebSocketState = WebSocketState.ConnectionClosed; - IsOpened = false; - } - } - } - 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 - } -} diff --git a/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketClientUtility.cs b/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketClientUtility.cs deleted file mode 100644 index 4c2e728437..0000000000 --- a/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketClientUtility.cs +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. 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(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; } } - } -} \ No newline at end of file diff --git a/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketConnect.cs b/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketConnect.cs deleted file mode 100644 index 284b65e32a..0000000000 --- a/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketConnect.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. 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 int Id { get; set; } - - public MyTcpClient TcpClient { get; set; } - public Stream Stream { get; set; } - - public List DataSent { get; set; } - public long TotalDataSent { get; set; } - public List DataReceived { get; set; } - public long TotalDataReceived { get; set; } - - override public string ToString() - { - return Id+""; - - } - - #region IDisposable Members - - /// - /// Dispose this instance. - /// - public void Dispose() - { - Console.WriteLine("Client object is disposed"); - - IsDisposed = true; - if (Stream != null) - Stream.Close(); - - if (TcpClient != null) - TcpClient.Close(); - } - - #endregion - } -} diff --git a/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketConstants.cs b/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketConstants.cs deleted file mode 100644 index ba5a43daf0..0000000000 --- a/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketConstants.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. 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; - - } -} diff --git a/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketState.cs b/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketState.cs deleted file mode 100644 index 0c25d95f7b..0000000000 --- a/test/AspNetCoreModule.Test/WebSocketClientHelper/WebSocketState.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -namespace AspNetCoreModule.Test.WebSocketClient -{ - public enum WebSocketState - { - NonWebSocket, - ConnectionOpen, - ClosingFromClientStarted, - ConnectionClosed - } -} diff --git a/test/AspNetCoreModule.Test/app.config b/test/AspNetCoreModule.Test/app.config deleted file mode 100644 index 49e0f8825c..0000000000 --- a/test/AspNetCoreModule.Test/app.config +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/AspNetCoreModule.TestSites.Standard/AspNetCoreModule.TestSites.Standard.csproj b/test/AspNetCoreModule.TestSites.Standard/AspNetCoreModule.TestSites.Standard.csproj deleted file mode 100644 index 1f278529c8..0000000000 --- a/test/AspNetCoreModule.TestSites.Standard/AspNetCoreModule.TestSites.Standard.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - netcoreapp2.0 - - - - - - - - - - - - - - - diff --git a/test/AspNetCoreModule.TestSites.Standard/IISSetupFilter.cs b/test/AspNetCoreModule.TestSites.Standard/IISSetupFilter.cs deleted file mode 100644 index 7c9a92a664..0000000000 --- a/test/AspNetCoreModule.TestSites.Standard/IISSetupFilter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Server.IISIntegration; - -namespace AspnetCoreModule.TestSites.Standard -{ - internal class IISSetupFilter : IStartupFilter - { - private readonly string _pairingToken; - - internal IISSetupFilter(string pairingToken) - { - _pairingToken = pairingToken; - } - - public Action Configure(Action next) - { - return app => - { - app.UseMiddleware(); - app.UseMiddleware(_pairingToken); - next(app); - }; - } - } -} \ No newline at end of file diff --git a/test/AspNetCoreModule.TestSites.Standard/ImpersonateMiddleware.cs b/test/AspNetCoreModule.TestSites.Standard/ImpersonateMiddleware.cs deleted file mode 100644 index d3b9aa8b01..0000000000 --- a/test/AspNetCoreModule.TestSites.Standard/ImpersonateMiddleware.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. 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); - }); - } - } - } -} diff --git a/test/AspNetCoreModule.TestSites.Standard/Program.cs b/test/AspNetCoreModule.TestSites.Standard/Program.cs deleted file mode 100644 index c7c10424c9..0000000000 --- a/test/AspNetCoreModule.TestSites.Standard/Program.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using System; -using System.IO; -using System.Security.Cryptography.X509Certificates; -using System.Threading; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; - -namespace AspnetCoreModule.TestSites.Standard -{ - public static class Program - { - public static IApplicationLifetime AappLifetime; - public static bool AappLifetimeStopping = false; - public static int GracefulShutdownDelayTime = 0; - - private static X509Certificate2 _x509Certificate2; - - 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 == "StartupHTTPS") - { - // load .\testresources\testcert.pfx - string pfxPassword = "testPassword"; - if (File.Exists(@".\TestResources\testcert.pfx")) - { - _x509Certificate2 = new X509Certificate2(@".\TestResources\testcert.pfx", pfxPassword); - } - else - { - throw new Exception(@"Certificate file not found: .\TestResources\testcert.pfx of which password should " + pfxPassword); - } - - builder = new WebHostBuilder() - .UseConfiguration(config) - .UseIISIntegration() - .UseKestrel() - .UseStartup(); - } - else if (startUpClassString == "StartupCompressionCaching") - { - builder = new WebHostBuilder() - .UseConfiguration(config) - .UseIISIntegration() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseStartup(); - } - else if (startUpClassString == "StartupNoCompressionCaching") - { - StartupCompressionCaching.CompressionMode = false; - builder = new WebHostBuilder() - .UseConfiguration(config) - .UseIISIntegration() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseStartup(); - } - else if (startUpClassString == "StartupHelloWorld") - { - builder = new WebHostBuilder() - .UseConfiguration(config) - .UseIISIntegration() - .UseStartup(); - } - else if (startUpClassString == "StartupNtlmAuthentication") - { - builder = new WebHostBuilder() - .UseConfiguration(config) - .UseIISIntegration() - .UseStartup(); - } - else if (startUpClassString == "StartupWithShutdownDisabled") - { - builder = new WebHostBuilder() - .ConfigureServices(services => - { - const string PairingToken = "TOKEN"; - string paringToken = builder.GetSetting(PairingToken) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{PairingToken}"); - services.AddSingleton( - new IISSetupFilter(paringToken) - ); - }) - .UseConfiguration(config) - .UseStartup(); - } - else - { - throw new Exception("Invalid startup class name : " + startUpClassString); - } - } - else - { - builder = new WebHostBuilder() - .UseConfiguration(config) - .UseIISIntegration() - .UseStartup(); - } - - 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); - } - - builder.UseKestrel(); - - var host = builder.Build(); - AappLifetime = (IApplicationLifetime)host.Services.GetService(typeof(IApplicationLifetime)); - - string gracefulShutdownDelay = Environment.GetEnvironmentVariable("GracefulShutdownDelayTime"); - if (!string.IsNullOrEmpty(gracefulShutdownDelay)) - { - GracefulShutdownDelayTime = Convert.ToInt32(gracefulShutdownDelay); - } - AappLifetime.ApplicationStarted.Register( - () => { - Thread.Sleep(1000); - } - ); - AappLifetime.ApplicationStopping.Register( - () => { - AappLifetimeStopping = true; - Thread.Sleep(Startup.SleeptimeWhileClosing / 2); - } - ); - AappLifetime.ApplicationStopped.Register( - () => { - Thread.Sleep(Startup.SleeptimeWhileClosing / 2); - Startup.SleeptimeWhileClosing = 0; // All of SleeptimeWhileClosing is used now - } - ); - try - { - host.Run(); - } - catch - { - // ignore - } - - if (Startup.SleeptimeWhileClosing != 0) - { - Thread.Sleep(Startup.SleeptimeWhileClosing); - } - } - } -} - diff --git a/test/AspNetCoreModule.TestSites.Standard/Properties/launchSettings.json b/test/AspNetCoreModule.TestSites.Standard/Properties/launchSettings.json deleted file mode 100644 index 76176b9680..0000000000 --- a/test/AspNetCoreModule.TestSites.Standard/Properties/launchSettings.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "iisSettings": { - "windowsAuthentication": true, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:39982/", - "sslPort": 44375 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "https://localhost:44375/", - "environmentVariables": { - "ANCMTestStartupClassName": "StartupHTTPS", - "ASPNET_ENVIRONMENT": "HelloWorld" - } - }, - "web": { - "commandName": "web", - "environmentVariables": { - "ASPNET_ENVIRONMENT": "HelloWorld" - } - } - } -} \ No newline at end of file diff --git a/test/AspNetCoreModule.TestSites.Standard/Startup.cs b/test/AspNetCoreModule.TestSites.Standard/Startup.cs deleted file mode 100644 index af68d68aa4..0000000000 --- a/test/AspNetCoreModule.TestSites.Standard/Startup.cs +++ /dev/null @@ -1,351 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -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 MemoryLeakList = new List(); - - public void ConfigureServices(IServiceCollection services) - { - services.Configure(options => { - }); - } - - private async Task Echo(WebSocket webSocket) - { - var buffer = new byte[1024 * 4]; - var result = await webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); - bool closeFromServer = false; - - while (!result.CloseStatus.HasValue) - { - if ((result.Count == "CloseFromServer".Length && System.Text.Encoding.ASCII.GetString(buffer).Substring(0, result.Count) == "CloseFromServer") - || Program.AappLifetimeStopping == true) - { - // start closing handshake from backend process - await webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "ClosingFromServer", CancellationToken.None); - closeFromServer = true; - } - else - { - await webSocket.SendAsync(new ArraySegment(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); - } - - result = await webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); - } - - if (closeFromServer) - { - return; - } - - 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 - { - }); - - 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 - { - }); - - 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(); - 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 + "
"; - } - } - - 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 + "
"; - } - } - - // This action can be used for testing invalid Transfer-Encoding response header - action = "SetTransferEncoding"; - if (item.StartsWith(action)) - { - if (item.Length > action.Length) - { - // this is the default response which is valid for chunked encoding - response = "10\r\nManually Chunked\r\n0\r\n\r\n"; - parameter = item.Substring(action.Length); - - // valid encoding value: "chunked" or "chunked,gzip" - string encoding = parameter; - var tokens = parameter.Split("_"); - - // if respons body value was also given after "_" delimeter, use the value as response data. - if (tokens.Length == 2) - { - encoding = tokens[0]; - response = tokens[1]; - } - context.Response.Headers[HeaderNames.TransferEncoding] = encoding; - return context.Response.WriteAsync(response); - } - } - } - return context.Response.WriteAsync(response); - }); - } - } -} diff --git a/test/AspNetCoreModule.TestSites.Standard/StartupCompressionCaching.cs b/test/AspNetCoreModule.TestSites.Standard/StartupCompressionCaching.cs deleted file mode 100644 index fb22ff3c24..0000000000 --- a/test/AspNetCoreModule.TestSites.Standard/StartupCompressionCaching.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. 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"; - } - } - ); - } - } -} diff --git a/test/AspNetCoreModule.TestSites.Standard/StartupHelloWorld.cs b/test/AspNetCoreModule.TestSites.Standard/StartupHelloWorld.cs deleted file mode 100644 index 7399bac55d..0000000000 --- a/test/AspNetCoreModule.TestSites.Standard/StartupHelloWorld.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. 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"); - }); - } - } -} \ No newline at end of file diff --git a/test/AspNetCoreModule.TestSites.Standard/StartupNtlmAuthentication.cs b/test/AspNetCoreModule.TestSites.Standard/StartupNtlmAuthentication.cs deleted file mode 100644 index bab2f1e32f..0000000000 --- a/test/AspNetCoreModule.TestSites.Standard/StartupNtlmAuthentication.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Authentication; -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.ChallengeAsync(); - } - } - - if (context.Request.Path.Equals("/Forbidden")) - { - return context.ForbidAsync(); - - } - - if (context.Request.Path.Equals("/AutoForbid")) - { - return context.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.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.ChallengeAsync("NTLM"); - } - } - - return context.Response.WriteAsync("Running NTLM"); - }); - } - } -} \ No newline at end of file diff --git a/test/AspNetCoreModule.TestSites.Standard/TestMiddleWareBeforeIISMiddleWare.cs b/test/AspNetCoreModule.TestSites.Standard/TestMiddleWareBeforeIISMiddleWare.cs deleted file mode 100644 index f2b4e87e08..0000000000 --- a/test/AspNetCoreModule.TestSites.Standard/TestMiddleWareBeforeIISMiddleWare.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using Microsoft.AspNetCore.Http; -using System; -using System.Security.Principal; -using System.Threading.Tasks; - - -namespace AspnetCoreModule.TestSites.Standard - -{ - public class TestMiddleWareBeforeIISMiddleWare - { - private readonly RequestDelegate next; - - public TestMiddleWareBeforeIISMiddleWare(RequestDelegate next) - { - this.next = next; - } - - public async Task Invoke(HttpContext context) - { - // if the given request is shutdown message from ANCM and the value of GracefulShutdown environment variable is set, - // the shutdown message is handled by this middleware instead of IISMiddleware. - - if (HttpMethods.IsPost(context.Request.Method) && - context.Request.Path.ToString().EndsWith("/iisintegration") && - string.Equals("shutdown", context.Request.Headers["MS-ASPNETCORE-EVENT"], StringComparison.OrdinalIgnoreCase)) - { - string shutdownMode = Environment.GetEnvironmentVariable("GracefulShutdown"); - if (!string.IsNullOrWhiteSpace(shutdownMode) && shutdownMode.ToLower().StartsWith("disabled")) - { - //ignore shutdown Message returning 200 instead of 202 because the gracefulshutdown is disabled - context.Response.StatusCode = StatusCodes.Status200OK; - await context.Response.WriteAsync("Called ShutdownMessage with disabled of GracefulShutdown"); - return; - } - } - await next.Invoke(context); - } - } -} diff --git a/test/AspNetCoreModule.TestSites.Standard/TestResources/testCert.pfx b/test/AspNetCoreModule.TestSites.Standard/TestResources/testCert.pfx deleted file mode 100644 index 7118908c2d..0000000000 Binary files a/test/AspNetCoreModule.TestSites.Standard/TestResources/testCert.pfx and /dev/null differ diff --git a/test/AspNetCoreModule.TestSites.Standard/web.config b/test/AspNetCoreModule.TestSites.Standard/web.config deleted file mode 100644 index 21a7c68e2d..0000000000 --- a/test/AspNetCoreModule.TestSites.Standard/web.config +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/test/WebSocketClientEXE/App.config b/test/WebSocketClientEXE/App.config deleted file mode 100644 index 8324aa6ff1..0000000000 --- a/test/WebSocketClientEXE/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/test/WebSocketClientEXE/Program.cs b/test/WebSocketClientEXE/Program.cs deleted file mode 100644 index ea45603a33..0000000000 --- a/test/WebSocketClientEXE/Program.cs +++ /dev/null @@ -1,53 +0,0 @@ -using AspNetCoreModule.Test.Framework; -using AspNetCoreModule.Test.WebSocketClient; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace WebSocketClientEXE -{ - class Program - { - static void Main(string[] args) - { - using (WebSocketClientHelper websocketClient = new WebSocketClientHelper()) - { - if (args.Length == 0) - { - TestUtility.LogInformation("Usage: WebSocketClientEXE http://localhost:40000/aspnetcoreapp/websocket"); - return; - } - string url = "http://localhost:40000/aspnetcoreapp/websocket"; - if (args[0].Contains("http:")) - { - url = args[0]; - } - var frameReturned = websocketClient.Connect(new Uri(url), true, true); - TestUtility.LogInformation(frameReturned.Content); - TestUtility.LogInformation("Type any data and Enter key ('Q' to quit): "); - - while (true) - { - Thread.Sleep(500); - if (!websocketClient.IsOpened) - { - TestUtility.LogInformation("Connection closed..."); - break; - } - - string data = Console.ReadLine(); - if (data.Trim().ToLower() == "q") - { - frameReturned = websocketClient.Close(); - TestUtility.LogInformation(frameReturned.Content); - break; - } - websocketClient.SendTextData(data); - } - } - } - } -} diff --git a/test/WebSocketClientEXE/Properties/AssemblyInfo.cs b/test/WebSocketClientEXE/Properties/AssemblyInfo.cs deleted file mode 100644 index ed897b706e..0000000000 --- a/test/WebSocketClientEXE/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("WebSocketClientEXE")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("WebSocketClientEXE")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("4062ea94-75f5-4691-86dc-c8594ba896de")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/test/WebSocketClientEXE/TestUtility.cs b/test/WebSocketClientEXE/TestUtility.cs deleted file mode 100644 index 852bda62bc..0000000000 --- a/test/WebSocketClientEXE/TestUtility.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for license information. - -using System; - -namespace AspNetCoreModule.Test.Framework -{ - public class TestUtility - { - public static void LogInformation(string format, params object[] parameters) - { - Console.WriteLine(format, parameters); - } - } -} \ No newline at end of file diff --git a/test/WebSocketClientEXE/WebSocketClientEXE.csproj b/test/WebSocketClientEXE/WebSocketClientEXE.csproj deleted file mode 100644 index 486d2188af..0000000000 --- a/test/WebSocketClientEXE/WebSocketClientEXE.csproj +++ /dev/null @@ -1,66 +0,0 @@ - - - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - Frame.cs - - - Frames.cs - - - FrameType.cs - - - WebSocketClientHelper.cs - - - WebSocketClientUtility.cs - - - WebSocketConnect.cs - - - WebSocketConstants.cs - - - WebSocketState.cs - - - - - - - - - - \ No newline at end of file