repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using AWS.Deploy.Orchestration.Utilities; namespace AWS.Deploy.Orchestration.UnitTests { public class TestCommandLineWrapper : ICommandLineWrapper { public List<(string command, string workingDirectory, bool streamOutputToInteractiveService)> Commands { get; } = new(); public List<TryRunResult> Results { get; } = new(); public Task Run( string command, string workingDirectory = "", bool streamOutputToInteractiveService = true, Action<TryRunResult> onComplete = null, bool redirectIO = true, string stdin = null, IDictionary<string, string> environmentVariables = null, CancellationToken cancelToken = default, bool needAwsCredentials = false) { Commands.Add((command, workingDirectory, streamOutputToInteractiveService)); onComplete?.Invoke(Results.Last()); return Task.CompletedTask; } public void ConfigureProcess(Action<ProcessStartInfo> processStartInfoAction) => throw new NotImplementedException(); } }
38
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using AWS.Deploy.Common.IO; using System.Linq; namespace AWS.Deploy.Orchestration.UnitTests { public class TestDirectoryManager : IDirectoryManager { public readonly HashSet<string> CreatedDirectories = new(); public readonly Dictionary<string, HashSet<string>> AddedFiles = new(); public DirectoryInfo CreateDirectory(string path) { CreatedDirectories.Add(path); return new DirectoryInfo(path); } public DirectoryInfo GetDirectoryInfo(string path) => new DirectoryInfo(path); public string GetRelativePath(string referenceFullPath, string targetFullPath) => Path.GetRelativePath(referenceFullPath, targetFullPath); public string GetAbsolutePath(string referenceFullPath, string targetRelativePath) => Path.GetFullPath(targetRelativePath, referenceFullPath); public string[] GetProjFiles(string path) => throw new NotImplementedException("If your test needs this method, you'll need to implement this."); public void Delete(string path, bool recursive = false) => throw new NotImplementedException("If your test needs this method, you'll need to implement this."); public bool ExistsInsideDirectory(string parentDirectoryPath, string childPath) => throw new NotImplementedException("If your test needs this method, you'll need to implement this."); public bool Exists(string path) { return CreatedDirectories.Contains(path); } public bool Exists(string path, string relativeTo) => throw new NotImplementedException("If your test needs this method, you'll need to implement this."); public string[] GetDirectories(string path, string searchPattern = null, SearchOption searchOption = SearchOption.TopDirectoryOnly) => throw new NotImplementedException("If your test needs this method, you'll need to implement this."); public string[] GetFiles(string path, string searchPattern = null, SearchOption searchOption = SearchOption.TopDirectoryOnly) => AddedFiles.ContainsKey(path) ? AddedFiles[path].ToArray() : new string[0]; public bool IsEmpty(string path) => throw new NotImplementedException("If your test needs this method, you'll need to implement this."); } }
56
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using AWS.Deploy.Common.IO; namespace AWS.Deploy.Orchestration.UnitTests { public class TestFileManager : IFileManager { public readonly Dictionary<string, string> InMemoryStore = new Dictionary<string, string>(); public bool Exists(string path) { return InMemoryStore.ContainsKey(path); } public bool Exists(string path, string directory) => throw new NotImplementedException(); public Task<string> ReadAllTextAsync(string path) { var text = InMemoryStore[path]; return Task.FromResult(text); } public async Task<string[]> ReadAllLinesAsync(string path) { return (await ReadAllTextAsync(path)).Split(Environment.NewLine); } public Task WriteAllTextAsync(string filePath, string contents, CancellationToken cancellationToken = default) { InMemoryStore[filePath] = contents; return Task.CompletedTask; } public FileStream OpenRead(string filePath) => throw new NotImplementedException(); public string GetExtension(string filePath) => throw new NotImplementedException(); public long GetSizeInBytes(string filePath) => throw new NotImplementedException(); public bool IsFileValidPath(string filePath) => throw new NotImplementedException(); } public static class TestFileManagerExtensions { /// <summary> /// Adds a virtual csproj file with valid xml contents /// </summary> /// <returns> /// Returns the correct full path for <paramref name="relativePath"/> /// </returns> public static string AddEmptyProjectFile(this TestFileManager fileManager, string relativePath) { relativePath = relativePath.Replace('\\', Path.DirectorySeparatorChar); var fullPath = Path.Join(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "c:\\" : "/", relativePath); fileManager.InMemoryStore.Add(fullPath, "<Project Sdk=\"Microsoft.NET.Sdk\"></Project>"); return fullPath; } } }
65
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Threading.Tasks; using AWS.Deploy.Common.IO; using AWS.Deploy.Orchestration.CDK; using AWS.Deploy.Orchestration.Utilities; using Xunit; namespace AWS.Deploy.Orchestration.UnitTests.CDK { public class CDKInstallerTests { private readonly TestCommandLineWrapper _commandLineWrapper; private readonly CDKInstaller _cdkInstaller; private readonly IDirectoryManager _directoryManager; private const string _workingDirectory = @"c:\fake\path"; public CDKInstallerTests() { _commandLineWrapper = new TestCommandLineWrapper(); _directoryManager = new TestDirectoryManager(); _cdkInstaller = new CDKInstaller(_commandLineWrapper, _directoryManager); } [Fact] public async Task GetVersion_OutputContainsVersionOnly() { // Arrange: add empty version information to return _commandLineWrapper.Results.Add(new TryRunResult { StandardOut = @"1.127.0 (build 0ea309a)" }); // Act var version = await _cdkInstaller.GetVersion(_workingDirectory); // Assert Assert.True(version.Success); Assert.Equal(0, Version.Parse("1.127.0").CompareTo(version.Result)); Assert.Contains(("npx --no-install cdk --version", _workingDirectory, false), _commandLineWrapper.Commands); } [Fact] public async Task GetVersion_OutputContainsMessage() { // Arrange: add fake version information to return _commandLineWrapper.Results.Add(new TryRunResult { StandardOut = @"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !! !! !! Node v10.19.0 has reached end-of-life and is not supported. !! !! You may to encounter runtime issues, and should switch to a supported release. !! !! !! !! As of the current release, supported versions of node are: !! !! - ^12.7.0 !! !! - ^14.5.0 !! !! - ^16.3.0 !! !! !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 1.127.0 (build 0ea309a)" }); // Act var version = await _cdkInstaller.GetVersion(_workingDirectory); // Assert Assert.True(version.Success); Assert.Equal(0, Version.Parse("1.127.0").CompareTo(version.Result)); Assert.Contains(("npx --no-install cdk --version", _workingDirectory, false), _commandLineWrapper.Commands); } [Fact] public async Task Install_InLocalNodeModules() { // Act await _cdkInstaller.Install(_workingDirectory, Version.Parse("1.0.2")); // Assert Assert.Contains(("npm install [email protected]", _workingDirectory, false), _commandLineWrapper.Commands); } } }
86
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Threading.Tasks; using AWS.Deploy.Orchestration.CDK; using AWS.Deploy.Orchestration.Utilities; using Moq; using Xunit; namespace AWS.Deploy.Orchestration.UnitTests.CDK { public class CDKManagerTests { private readonly Mock<ICDKInstaller> _mockCdkManager; private readonly Mock<INPMPackageInitializer> _mockNodeInitializer; private readonly Mock<IOrchestratorInteractiveService> _mockInteractiveService; private readonly CDKManager _cdkManager; private readonly Mock<IEnvironmentVariableManager> _environmentVariableManager; private const string _workingDirectory = @"c:\fake\path"; public CDKManagerTests() { _mockCdkManager = new Mock<ICDKInstaller>(); _mockNodeInitializer = new Mock<INPMPackageInitializer>(); _mockInteractiveService = new Mock<IOrchestratorInteractiveService>(); _environmentVariableManager = new Mock<IEnvironmentVariableManager>(); _environmentVariableManager .Setup(x => x.GetEnvironmentVariable(It.IsAny<string>())) .Returns(() => null); _cdkManager = new CDKManager(_mockCdkManager.Object, _mockNodeInitializer.Object, _mockInteractiveService.Object); } [Theory] [InlineData("1.0.1", "1.0.0")] [InlineData("1.0.1", "1.0.1")] public async Task EnsureCompatibleCDKExists_CompatibleGlobalCDKExists(string installedVersion, string requiredVersion) { // Arrange _mockCdkManager .Setup(cm => cm.GetVersion(_workingDirectory)) .Returns(Task.FromResult(TryGetResult.FromResult(Version.Parse(installedVersion)))); // Act await _cdkManager.EnsureCompatibleCDKExists(_workingDirectory, Version.Parse(requiredVersion)); // Assert: when CDK CLI is installed, installation is not performed. _mockCdkManager.Verify(cm => cm.Install(_workingDirectory, Version.Parse(requiredVersion)), Times.Never); } [Theory] [InlineData("1.0.1")] public async Task EnsureCompatibleCDKExists_NPMPackageIsNotInitialized(string requiredVersion) { // Arrange _mockCdkManager .Setup(cm => cm.GetVersion(_workingDirectory)) .Returns(Task.FromResult(TryGetResult.Failure<Version>())); _mockNodeInitializer .Setup(nodeInitializer => nodeInitializer.IsInitialized(_workingDirectory)) .Returns(false); // Act await _cdkManager.EnsureCompatibleCDKExists(_workingDirectory, Version.Parse(requiredVersion)); // Assert: node app must be initialized if global node_modules doesn't contain CDK CLI. _mockNodeInitializer.Verify(nodeInitializer => nodeInitializer.Initialize(_workingDirectory, Version.Parse(requiredVersion)), Times.Once); } [Theory] [InlineData("1.0.0", "2.0.0")] public async Task EnsureCompatibleCDKExists_CompatibleLocalCDKDoesNotExist(string localVersion, string requiredVersion) { // Arrange _mockCdkManager .Setup(cm => cm.GetVersion(_workingDirectory)) .Returns(Task.FromResult(TryGetResult.Failure<Version>())); _mockNodeInitializer .Setup(nodeInitializer => nodeInitializer.IsInitialized(_workingDirectory)) .Returns(true); _mockCdkManager .Setup(cm => cm.GetVersion(_workingDirectory)) .Returns(Task.FromResult(TryGetResult.FromResult(Version.Parse(localVersion)))); // Act await _cdkManager.EnsureCompatibleCDKExists(_workingDirectory, Version.Parse(requiredVersion)); // Assert: when a local node_modules doesn't contain a compatible CDK CLI, CDKManager installs required CDK CLI package. _mockCdkManager.Verify(cm => cm.Install(_workingDirectory, Version.Parse(requiredVersion)), Times.Once); } } }
98
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Threading.Tasks; using AWS.Deploy.Common.IO; using AWS.Deploy.Orchestration.CDK; using AWS.Deploy.Orchestration.Data; using AWS.Deploy.Orchestration.Utilities; using Moq; using Xunit; using Amazon.CloudFormation.Model; using System.Collections.Generic; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.Extensions; using AWS.Deploy.Common; namespace AWS.Deploy.Orchestration.UnitTests.CDK { public class CDKProjectHandlerTests { private readonly IOptionSettingHandler _optionSettingHandler; private readonly Mock<IAWSResourceQueryer> _awsResourceQueryer; private readonly Mock<ICdkAppSettingsSerializer> _cdkAppSettingsSerializer; private readonly Mock<IServiceProvider> _serviceProvider; private readonly Mock<IDeployToolWorkspaceMetadata> _workspaceMetadata; private readonly Mock<ICloudFormationTemplateReader> _cloudFormationTemplateReader; private readonly Mock<IFileManager> _fileManager; private readonly Mock<IDirectoryManager> _directoryManager; private readonly string _cdkBootstrapTemplate; public CDKProjectHandlerTests() { _awsResourceQueryer = new Mock<IAWSResourceQueryer>(); _cdkAppSettingsSerializer = new Mock<ICdkAppSettingsSerializer>(); _serviceProvider = new Mock<IServiceProvider>(); _serviceProvider .Setup(x => x.GetService(typeof(IAWSResourceQueryer))) .Returns(_awsResourceQueryer.Object); _optionSettingHandler = new OptionSettingHandler(new ValidatorFactory(_serviceProvider.Object)); _workspaceMetadata = new Mock<IDeployToolWorkspaceMetadata>(); _cloudFormationTemplateReader = new Mock<ICloudFormationTemplateReader>(); _fileManager = new Mock<IFileManager>(); _directoryManager = new Mock<IDirectoryManager>(); var templateIdentifier = "AWS.Deploy.Orchestration.CDK.CDKBootstrapTemplate.yaml"; _cdkBootstrapTemplate = typeof(CdkProjectHandler).Assembly.ReadEmbeddedFile(templateIdentifier); } [Fact] public async Task CheckCDKBootstrap_DoesNotExist() { var interactiveService = new Mock<IOrchestratorInteractiveService>(); var commandLineWrapper = new Mock<ICommandLineWrapper>(); var awsResourceQuery = new Mock<IAWSResourceQueryer>(); awsResourceQuery.Setup(x => x.GetCloudFormationStack(It.IsAny<string>())).Returns(Task.FromResult<Stack>(null)); var cdkProjectHandler = new CdkProjectHandler(interactiveService.Object, commandLineWrapper.Object, awsResourceQuery.Object, _cdkAppSettingsSerializer.Object, _fileManager.Object, _directoryManager.Object, _optionSettingHandler, _workspaceMetadata.Object, _cloudFormationTemplateReader.Object); Assert.True(await cdkProjectHandler.DetermineIfCDKBootstrapShouldRun()); } [Fact] public async Task CheckCDKBootstrap_NoCFParameter() { var interactiveService = new Mock<IOrchestratorInteractiveService>(); var commandLineWrapper = new Mock<ICommandLineWrapper>(); var awsResourceQuery = new Mock<IAWSResourceQueryer>(); awsResourceQuery.Setup(x => x.GetCloudFormationStack(It.IsAny<string>())).Returns(Task.FromResult<Stack>(new Stack { Parameters = new List<Parameter>() })); var cdkProjectHandler = new CdkProjectHandler(interactiveService.Object, commandLineWrapper.Object, awsResourceQuery.Object, _cdkAppSettingsSerializer.Object, _fileManager.Object, _directoryManager.Object, _optionSettingHandler, _workspaceMetadata.Object, _cloudFormationTemplateReader.Object); Assert.True(await cdkProjectHandler.DetermineIfCDKBootstrapShouldRun()); } [Fact] public async Task CheckCDKBootstrap_NoSSMParameter() { var interactiveService = new Mock<IOrchestratorInteractiveService>(); var commandLineWrapper = new Mock<ICommandLineWrapper>(); var awsResourceQuery = new Mock<IAWSResourceQueryer>(); awsResourceQuery.Setup(x => x.GetCloudFormationStack(It.IsAny<string>())).Returns(Task.FromResult<Stack>( new Stack { Parameters = new List<Parameter>() { new Parameter { ParameterKey = "Qualifier", ParameterValue = "q1" } } })); var cdkProjectHandler = new CdkProjectHandler(interactiveService.Object, commandLineWrapper.Object, awsResourceQuery.Object, _cdkAppSettingsSerializer.Object, _fileManager.Object, _directoryManager.Object, _optionSettingHandler, _workspaceMetadata.Object, _cloudFormationTemplateReader.Object); Assert.True(await cdkProjectHandler.DetermineIfCDKBootstrapShouldRun()); } [Fact] public async Task CheckCDKBootstrap_SSMParameterOld() { var interactiveService = new Mock<IOrchestratorInteractiveService>(); var commandLineWrapper = new Mock<ICommandLineWrapper>(); var deployToolWorkspaceMetadata = new Mock<IDeployToolWorkspaceMetadata>(); var awsClientFactory = new Mock<IAWSClientFactory>(); var awsResourceQuery = new Mock<IAWSResourceQueryer>(); awsResourceQuery.Setup(x => x.GetCloudFormationStack(It.IsAny<string>())).Returns(Task.FromResult<Stack>( new Stack { Parameters = new List<Parameter>() { new Parameter { ParameterKey = "Qualifier", ParameterValue = "q1" } } })); _fileManager.Setup(x => x.ReadAllTextAsync(It.IsAny<string>())).ReturnsAsync(_cdkBootstrapTemplate); var cloudFormationTemplateReader = new CloudFormationTemplateReader(awsClientFactory.Object, deployToolWorkspaceMetadata.Object, _fileManager.Object); awsResourceQuery.Setup(x => x.GetParameterStoreTextValue(It.IsAny<string>())).Returns(Task.FromResult<string>("1")); var cdkProjectHandler = new CdkProjectHandler(interactiveService.Object, commandLineWrapper.Object, awsResourceQuery.Object, _cdkAppSettingsSerializer.Object, _fileManager.Object, _directoryManager.Object, _optionSettingHandler, _workspaceMetadata.Object, cloudFormationTemplateReader); Assert.True(await cdkProjectHandler.DetermineIfCDKBootstrapShouldRun()); } [Fact] public async Task CheckCDKBootstrap_SSMParameterNewer() { var interactiveService = new Mock<IOrchestratorInteractiveService>(); var commandLineWrapper = new Mock<ICommandLineWrapper>(); var deployToolWorkspaceMetadata = new Mock<IDeployToolWorkspaceMetadata>(); var awsClientFactory = new Mock<IAWSClientFactory>(); var awsResourceQuery = new Mock<IAWSResourceQueryer>(); awsResourceQuery.Setup(x => x.GetCloudFormationStack(It.IsAny<string>())).Returns(Task.FromResult<Stack>( new Stack { Parameters = new List<Parameter>() { new Parameter { ParameterKey = "Qualifier", ParameterValue = "q1" } } })); _fileManager.Setup(x => x.ReadAllTextAsync(It.IsAny<string>())).ReturnsAsync(_cdkBootstrapTemplate); var cloudFormationTemplateReader = new CloudFormationTemplateReader(awsClientFactory.Object, deployToolWorkspaceMetadata.Object, _fileManager.Object); awsResourceQuery.Setup(x => x.GetParameterStoreTextValue(It.IsAny<string>())).Returns(Task.FromResult<string>("100")); var cdkProjectHandler = new CdkProjectHandler(interactiveService.Object, commandLineWrapper.Object, awsResourceQuery.Object, _cdkAppSettingsSerializer.Object, _fileManager.Object, _directoryManager.Object, _optionSettingHandler, _workspaceMetadata.Object, cloudFormationTemplateReader); Assert.False(await cdkProjectHandler.DetermineIfCDKBootstrapShouldRun()); } [Fact] public async Task CheckCDKBootstrap_SSMParameterSame() { var interactiveService = new Mock<IOrchestratorInteractiveService>(); var commandLineWrapper = new Mock<ICommandLineWrapper>(); var deployToolWorkspaceMetadata = new Mock<IDeployToolWorkspaceMetadata>(); var awsClientFactory = new Mock<IAWSClientFactory>(); var awsResourceQuery = new Mock<IAWSResourceQueryer>(); awsResourceQuery.Setup(x => x.GetCloudFormationStack(It.IsAny<string>())).Returns(Task.FromResult<Stack>( new Stack { Parameters = new List<Parameter>() { new Parameter { ParameterKey = "Qualifier", ParameterValue = "q1" } } })); _fileManager.Setup(x => x.ReadAllTextAsync(It.IsAny<string>())).ReturnsAsync(_cdkBootstrapTemplate); var cloudFormationTemplateReader = new CloudFormationTemplateReader(awsClientFactory.Object, deployToolWorkspaceMetadata.Object, _fileManager.Object); var templateVersion = await cloudFormationTemplateReader.ReadCDKTemplateVersion(); awsResourceQuery.Setup(x => x.GetParameterStoreTextValue(It.IsAny<string>())).Returns(Task.FromResult<string>(templateVersion.ToString())); var cdkProjectHandler = new CdkProjectHandler(interactiveService.Object, commandLineWrapper.Object, awsResourceQuery.Object, _cdkAppSettingsSerializer.Object, _fileManager.Object, _directoryManager.Object, _optionSettingHandler, _workspaceMetadata.Object, cloudFormationTemplateReader); Assert.False(await cdkProjectHandler.DetermineIfCDKBootstrapShouldRun()); } } }
161
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.IO; using System.Linq; using AWS.Deploy.Orchestration.CDK; using Xunit; namespace AWS.Deploy.Orchestration.UnitTests.CDK { public class CDKVersionDetectorTests { private readonly ICDKVersionDetector _cdkVersionDetector; public CDKVersionDetectorTests() { _cdkVersionDetector = new CDKVersionDetector(); } [Theory] [InlineData("MixedReferences", "2.15.0")] [InlineData("SameReferences", "2.14.0")] [InlineData("NoReferences", "2.13.0")] public void Detect_CSProjPath(string fileName, string expectedVersion) { var csprojPath = Path.Combine("CDK", "CSProjFiles", fileName); var version = _cdkVersionDetector.Detect(csprojPath); Assert.Equal(expectedVersion, version.ToString()); } [Fact] public void Detect_CSProjPaths() { var csprojPaths = new [] { "MixedReferences", "SameReferences", "NoReferences" }.Select(fileName => Path.Combine("CDK", "CSProjFiles", fileName)); var version = _cdkVersionDetector.Detect(csprojPaths); Assert.Equal("2.15.0", version.ToString()); } } }
45
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Threading.Tasks; using AWS.Deploy.CLI; using AWS.Deploy.CLI.Common.UnitTests.IO; using AWS.Deploy.Orchestration.CDK; using Moq; using Xunit; namespace AWS.Deploy.Orchestration.UnitTests.CDK { public class NPMPackageInitializerTests { private readonly TestCommandLineWrapper _testCommandLineWrapper; private readonly INPMPackageInitializer _npmPackageInitializer; private readonly TestFileManager _fileManager; private readonly TestDirectoryManager _directoryManager; private readonly Mock<IOrchestratorInteractiveService> _mockInteractiveService; private const string _workingDirectory = @"c:\fake\path"; private const string _packageJsonContent = @" {{ ""devDependencies"": {{ ""aws-cdk"": ""1.0.1"" }}, ""scripts"": {{ ""cdk"": ""cdk"" }} }}"; private const string _packageJsonTemplate = @" {{ ""devDependencies"": {{ ""aws-cdk"": ""{aws-cdk-version}"" }}, ""scripts"": {{ ""cdk"": ""cdk"" }} }}"; private const string _packageJsonFileName = "package.json"; public NPMPackageInitializerTests() { _mockInteractiveService = new Mock<IOrchestratorInteractiveService>(); _fileManager = new TestFileManager(); _directoryManager = new TestDirectoryManager(); _testCommandLineWrapper = new TestCommandLineWrapper(); var packageJsonGenerator = new PackageJsonGenerator(_packageJsonTemplate); _npmPackageInitializer = new NPMPackageInitializer(_testCommandLineWrapper, packageJsonGenerator, _fileManager, _directoryManager, _mockInteractiveService.Object); } [Fact] public async Task IsInitialized_PackagesJsonExists() { // Arrange: create a fake package.json file await _fileManager.WriteAllTextAsync(Path.Combine(_workingDirectory, _packageJsonFileName), _packageJsonContent); // Act var isInitialized = _npmPackageInitializer.IsInitialized(_workingDirectory); // Assert Assert.True(isInitialized); } [Fact] public void IsInitialized_PackagesJsonDoesNotExist() { Assert.False(_npmPackageInitializer.IsInitialized(_workingDirectory)); } [Fact] public async Task Initialize_PackageJsonDoesNotExist() { // Arrange: Setup template file _fileManager.InMemoryStore[_packageJsonFileName] = _packageJsonTemplate; // Act: Initialize node app await _npmPackageInitializer.Initialize(_workingDirectory, Version.Parse("1.0.1")); // Assert: verify initialized package.json var actualPackageJsonContent = await _fileManager.ReadAllTextAsync(Path.Combine(_workingDirectory, _packageJsonFileName)); Assert.Equal(_packageJsonContent, actualPackageJsonContent); Assert.Contains(("npm install", _workingDirectory, false), _testCommandLineWrapper.Commands); Assert.True(_directoryManager.Exists(_workingDirectory)); } } }
94
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Reflection; namespace AWS.Deploy.Orchestration.UnitTests.Utilities { internal static class SystemIOUtilities { public static string ResolvePath(string projectName) { var testsPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); while (testsPath != null && !string.Equals(new DirectoryInfo(testsPath).Name, "test", StringComparison.OrdinalIgnoreCase)) { testsPath = Directory.GetParent(testsPath).FullName; } return Path.Combine(testsPath, "..", "testapps", projectName); } } }
25
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; namespace AWS.Deploy.Orchestration.UnitTests.Utilities { public class TestToolOrchestratorInteractiveService : IOrchestratorInteractiveService { public IList<string> SectionStartMessages { get; } = new List<string>(); public IList<string> DebugMessages { get; } = new List<string>(); public IList<string> OutputMessages { get; } = new List<string>(); public IList<string> ErrorMessages { get; } = new List<string>(); public void LogSectionStart(string message, string description) => SectionStartMessages.Add(message); public void LogDebugMessage(string message) => DebugMessages.Add(message); public void LogErrorMessage(string message) => ErrorMessages.Add(message); public void LogInfoMessage(string message) => OutputMessages.Add(message); } }
21
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using AWS.Deploy.ServerMode.Client.Utilities; using Xunit; namespace AWS.Deploy.ServerMode.Client.UnitTests { public class CappedStringBuilderTests { private readonly CappedStringBuilder _cappedStringBuilder; public CappedStringBuilderTests() { _cappedStringBuilder = new CappedStringBuilder(5); } [Fact] public void AppendLineTest() { _cappedStringBuilder.AppendLine("test1"); _cappedStringBuilder.AppendLine("test2"); _cappedStringBuilder.AppendLine("test3"); Assert.Equal(3, _cappedStringBuilder.LineCount); Assert.Equal($"test1{Environment.NewLine}test2{Environment.NewLine}test3", _cappedStringBuilder.ToString()); } [Fact] public void GetLastLinesTest() { _cappedStringBuilder.AppendLine("test1"); _cappedStringBuilder.AppendLine("test2"); Assert.Equal(2, _cappedStringBuilder.LineCount); Assert.Equal("test2", _cappedStringBuilder.GetLastLines(1)); Assert.Equal($"test1{Environment.NewLine}test2", _cappedStringBuilder.GetLastLines(2)); } } }
42
aws-dotnet-deploy
aws
C#
using System; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; using Moq; using Moq.Protected; using Xunit; namespace AWS.Deploy.ServerMode.Client.UnitTests { public class ServerModeSessionTests { private readonly ServerModeSession _serverModeSession; private readonly Mock<HttpClientHandler> _httpClientHandlerMock; private readonly Mock<CommandLineWrapper> _commandLineWrapper; public ServerModeSessionTests() { _httpClientHandlerMock = new Mock<HttpClientHandler>(); _commandLineWrapper = new Mock<CommandLineWrapper>(false); _serverModeSession = new ServerModeSession(_commandLineWrapper.Object, _httpClientHandlerMock.Object, TimeSpan.FromSeconds(5)); } [Fact] public async Task Start() { // Arrange var runResult = new RunResult { ExitCode = 0 }; MockCommandLineWrapperRun(runResult, TimeSpan.FromSeconds(100)); MockHttpGet(HttpStatusCode.OK); // Act var exception = await Record.ExceptionAsync(async () => { await _serverModeSession.Start(CancellationToken.None); }); // Assert Assert.Null(exception); } [Fact] public async Task Start_PortUnavailable() { // Arrange var runResult = new RunResult { ExitCode = -100 }; MockCommandLineWrapperRun(runResult); MockHttpGet(HttpStatusCode.NotFound, TimeSpan.FromSeconds(5)); // Act & Assert await Assert.ThrowsAsync<PortUnavailableException>(async () => { await _serverModeSession.Start(CancellationToken.None); }); } [Fact] public async Task Start_HttpGetThrows() { // Arrange var runResult = new RunResult { ExitCode = 0 }; MockCommandLineWrapperRun(runResult, TimeSpan.FromSeconds(100)); MockHttpGetThrows(); // Act & Assert await Assert.ThrowsAsync<InternalServerModeException>(async () => { await _serverModeSession.Start(CancellationToken.None); }); } [Fact] public async Task Start_HttpGetForbidden() { // Arrange var runResult = new RunResult { ExitCode = 0 }; MockCommandLineWrapperRun(runResult, TimeSpan.FromSeconds(100)); MockHttpGet(HttpStatusCode.Forbidden); // Act & Assert await Assert.ThrowsAsync<InternalServerModeException>(async () => { await _serverModeSession.Start(CancellationToken.None); }); } [Fact] public async Task IsAlive_BaseUrlNotInitialized() { // Act var isAlive = await _serverModeSession.IsAlive(CancellationToken.None); // Assert Assert.False(isAlive); } [Fact] public async Task IsAlive_GetAsyncThrows() { // Arrange var runResult = new RunResult { ExitCode = 0 }; MockCommandLineWrapperRun(runResult, TimeSpan.FromSeconds(100)); MockHttpGet(HttpStatusCode.OK); await _serverModeSession.Start(CancellationToken.None); MockHttpGetThrows(); // Act var isAlive = await _serverModeSession.IsAlive(CancellationToken.None); // Assert Assert.False(isAlive); } [Fact] public async Task IsAlive_HttpResponseSuccess() { // Arrange var runResult = new RunResult { ExitCode = 0 }; MockCommandLineWrapperRun(runResult, TimeSpan.FromSeconds(100)); MockHttpGet(HttpStatusCode.OK); await _serverModeSession.Start(CancellationToken.None); // Act var isAlive = await _serverModeSession.IsAlive(CancellationToken.None); // Assert Assert.True(isAlive); } [Fact] public async Task IsAlive_HttpResponseFailure() { // Arrange var runResult = new RunResult { ExitCode = 0 }; MockCommandLineWrapperRun(runResult, TimeSpan.FromSeconds(100)); MockHttpGet(HttpStatusCode.OK); await _serverModeSession.Start(CancellationToken.None); MockHttpGet(HttpStatusCode.Forbidden); // Act var isAlive = await _serverModeSession.IsAlive(CancellationToken.None); // Assert Assert.False(isAlive); } [Fact] public async Task TryGetRestAPIClient() { // Arrange var runResult = new RunResult { ExitCode = 0 }; MockCommandLineWrapperRun(runResult, TimeSpan.FromSeconds(100)); MockHttpGet(HttpStatusCode.OK); await _serverModeSession.Start(CancellationToken.None); // Act var success = _serverModeSession.TryGetRestAPIClient(CredentialGenerator, out var restApiClient); // Assert Assert.True(success); Assert.NotNull(restApiClient); } [Fact] public void TryGetRestAPIClient_WithoutStart() { // Arrange var runResult = new RunResult { ExitCode = 0 }; MockCommandLineWrapperRun(runResult, TimeSpan.FromSeconds(100)); MockHttpGet(HttpStatusCode.OK); // Act var success = _serverModeSession.TryGetRestAPIClient(CredentialGenerator, out var restApiClient); // Assert Assert.False(success); Assert.Null(restApiClient); } [Fact] public async Task TryGetDeploymentCommunicationClient() { // Arrange var runResult = new RunResult { ExitCode = 0 }; MockCommandLineWrapperRun(runResult, TimeSpan.FromSeconds(100)); MockHttpGet(HttpStatusCode.OK); await _serverModeSession.Start(CancellationToken.None); // Act var success = _serverModeSession.TryGetDeploymentCommunicationClient(out var deploymentCommunicationClient); // Assert Assert.True(success); Assert.NotNull(deploymentCommunicationClient); } [Fact] public void TryGetDeploymentCommunicationClient_WithoutStart() { var success = _serverModeSession.TryGetDeploymentCommunicationClient(out var deploymentCommunicationClient); Assert.False(success); Assert.Null(deploymentCommunicationClient); } private void MockHttpGet(HttpStatusCode httpStatusCode) { var response = new HttpResponseMessage(httpStatusCode); _httpClientHandlerMock .Protected() .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) .ReturnsAsync(response); } private void MockHttpGet(HttpStatusCode httpStatusCode, TimeSpan delay) { var response = new HttpResponseMessage(httpStatusCode); _httpClientHandlerMock .Protected() .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) .ReturnsAsync(response, delay); } private void MockHttpGetThrows() => _httpClientHandlerMock .Protected() .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) .Throws(new Exception()); private void MockCommandLineWrapperRun(RunResult runResult) => _commandLineWrapper .Setup(wrapper => wrapper.Run(It.IsAny<string>(), It.IsAny<string[]>())) .ReturnsAsync(runResult); private void MockCommandLineWrapperRun(RunResult runResult, TimeSpan delay) => _commandLineWrapper .Setup(wrapper => wrapper.Run(It.IsAny<string>(), It.IsAny<string[]>())) .ReturnsAsync(runResult, delay); private Task<AWSCredentials> CredentialGenerator() => throw new NotImplementedException(); } }
254
aws-dotnet-deploy
aws
C#
using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace BlazorWasm60 { public class Program { public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("#app"); builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); await builder.Build().RunAsync(); } } }
26
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Threading.Tasks; namespace ConsoleAppService { internal class Program { private static async Task Main(string[] args) { while (true) { Console.WriteLine("Hello World!"); await Task.Delay(500); } } } }
21
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; namespace ConsoleAppTask { internal class Program { private static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
16
aws-dotnet-deploy
aws
C#
using ContosoUniversityBackendService.Data; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ContosoUniversityBackendService { public class ContosoService : BackgroundService { SchoolContext Context { get; } public ContosoService(SchoolContext context) { Context = context; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { Console.WriteLine("Student List"); Console.WriteLine("------------"); foreach(var student in Context.Students) { Console.WriteLine(student.FirstMidName + student.LastName); } Console.WriteLine(string.Empty); await Task.Delay(1000); } } } }
37
aws-dotnet-deploy
aws
C#
using ContosoUniversityBackendService.Data; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; namespace ContosoUniversityBackendService { class Program { static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); CreateDbIfNotExists(host); host.Run(); } private static void CreateDbIfNotExists(IHost host) { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService<SchoolContext>(); // context.Database.EnsureCreated(); DbInitializer.Initialize(context); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred creating the DB."); } } } public static IHostBuilder CreateHostBuilder(string[] args) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json"); #if DEBUG builder.AddJsonFile("appsettings.Development.json", true); #endif var configuration = builder.Build(); var hostBuilder = Host.CreateDefaultBuilder() .ConfigureServices(services => { services.AddSingleton<IConfiguration>(builder.Build()); services.AddDbContext<SchoolContext>(options => { options.UseSqlServer(configuration.GetConnectionString("SchoolContext")); }); services.AddHostedService<ContosoService>(); }); return hostBuilder; } } }
70
aws-dotnet-deploy
aws
C#
using ContosoUniversityBackendService.Data; using ContosoUniversityBackendService.Models; using System; using System.Linq; namespace ContosoUniversityBackendService.Data { public static class DbInitializer { public static void Initialize(SchoolContext context) { context.Database.EnsureCreated(); // Look for any students. if (context.Students.Any()) { return; // DB has been seeded } var students = new Student[] { new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2019-09-01")}, new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2017-09-01")}, new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2018-09-01")}, new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2017-09-01")}, new Student{FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse("2017-09-01")}, new Student{FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse("2016-09-01")}, new Student{FirstMidName="Laura",LastName="Norman",EnrollmentDate=DateTime.Parse("2018-09-01")}, new Student{FirstMidName="Nino",LastName="Olivetto",EnrollmentDate=DateTime.Parse("2019-09-01")} }; context.Students.AddRange(students); context.SaveChanges(); var courses = new Course[] { new Course{CourseID=1050,Title="Chemistry",Credits=3}, new Course{CourseID=4022,Title="Microeconomics",Credits=3}, new Course{CourseID=4041,Title="Macroeconomics",Credits=3}, new Course{CourseID=1045,Title="Calculus",Credits=4}, new Course{CourseID=3141,Title="Trigonometry",Credits=4}, new Course{CourseID=2021,Title="Composition",Credits=3}, new Course{CourseID=2042,Title="Literature",Credits=4} }; context.Courses.AddRange(courses); context.SaveChanges(); var enrollments = new Enrollment[] { new Enrollment{StudentID=1,CourseID=1050,Grade=Grade.A}, new Enrollment{StudentID=1,CourseID=4022,Grade=Grade.C}, new Enrollment{StudentID=1,CourseID=4041,Grade=Grade.B}, new Enrollment{StudentID=2,CourseID=1045,Grade=Grade.B}, new Enrollment{StudentID=2,CourseID=3141,Grade=Grade.F}, new Enrollment{StudentID=2,CourseID=2021,Grade=Grade.F}, new Enrollment{StudentID=3,CourseID=1050}, new Enrollment{StudentID=4,CourseID=1050}, new Enrollment{StudentID=4,CourseID=4022,Grade=Grade.F}, new Enrollment{StudentID=5,CourseID=4041,Grade=Grade.C}, new Enrollment{StudentID=6,CourseID=1045}, new Enrollment{StudentID=7,CourseID=3141,Grade=Grade.A}, }; context.Enrollments.AddRange(enrollments); context.SaveChanges(); } } }
69
aws-dotnet-deploy
aws
C#
using Microsoft.EntityFrameworkCore; using ContosoUniversityBackendService.Models; namespace ContosoUniversityBackendService.Data { public class SchoolContext : DbContext { public SchoolContext(DbContextOptions<SchoolContext> options) : base(options) { } public DbSet<Student> Students { get; set; } public DbSet<Enrollment> Enrollments { get; set; } public DbSet<Course> Courses { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Course>().ToTable("Course"); modelBuilder.Entity<Enrollment>().ToTable("Enrollment"); modelBuilder.Entity<Student>().ToTable("Student"); } } }
24
aws-dotnet-deploy
aws
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace ContosoUniversityBackendService.Models { public class Course { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } public ICollection<Enrollment> Enrollments { get; set; } } }
15
aws-dotnet-deploy
aws
C#
namespace ContosoUniversityBackendService.Models { public enum Grade { A, B, C, D, F } public class Enrollment { public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public Grade? Grade { get; set; } public Course Course { get; set; } public Student Student { get; set; } } }
18
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; namespace ContosoUniversityBackendService.Models { public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public ICollection<Enrollment> Enrollments { get; set; } } }
15
aws-dotnet-deploy
aws
C#
using System; using System.ComponentModel.DataAnnotations; namespace ContosoUniversityBackendService.Models.SchoolViewModels { public class EnrollmentDateGroup { [DataType(DataType.Date)] public DateTime? EnrollmentDate { get; set; } public int StudentCount { get; set; } } }
13
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace ContosoUniversity { public class PaginatedList<T> : List<T> { public int PageIndex { get; private set; } public int TotalPages { get; private set; } public PaginatedList(List<T> items, int count, int pageIndex, int pageSize) { PageIndex = pageIndex; TotalPages = (int)Math.Ceiling(count / (double)pageSize); this.AddRange(items); } public bool HasPreviousPage { get { return (PageIndex > 1); } } public bool HasNextPage { get { return (PageIndex < TotalPages); } } public static async Task<PaginatedList<T>> CreateAsync( IQueryable<T> source, int pageIndex, int pageSize) { var count = await source.CountAsync(); var items = await source.Skip( (pageIndex - 1) * pageSize) .Take(pageSize).ToListAsync(); return new PaginatedList<T>(items, count, pageIndex, pageSize); } } }
48
aws-dotnet-deploy
aws
C#
using ContosoUniversity.Data; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; namespace ContosoUniversity { public class Program { public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); CreateDbIfNotExists(host); host.Run(); } private static void CreateDbIfNotExists(IHost host) { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService<SchoolContext>(); // context.Database.EnsureCreated(); DbInitializer.Initialize(context); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred creating the DB."); } } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
48
aws-dotnet-deploy
aws
C#
using ContosoUniversity.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ContosoUniversity { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } #region snippet_ConfigureServices public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddDbContext<SchoolContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SchoolContext"))); services.AddDatabaseDeveloperPageExceptionFilter(); } #endregion public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // if (env.IsDevelopment()) // { app.UseDeveloperExceptionPage(); // } // else // { // app.UseExceptionHandler("/Error"); // app.UseHsts(); // } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
58
aws-dotnet-deploy
aws
C#
using ContosoUniversity.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; namespace ContosoUniversity { public class StartupMaxMBsize { public StartupMaxMBsize(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } #region snippet_ConfigureServices public void ConfigureServices(IServiceCollection services) { int MyMaxModelBindingCollectionSize = 100; Int32.TryParse(Configuration["MyMaxModelBindingCollectionSize"], out MyMaxModelBindingCollectionSize); services.Configure<MvcOptions>(options => options.MaxModelBindingCollectionSize = MyMaxModelBindingCollectionSize); services.AddRazorPages(); services.AddDbContext<SchoolContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SchoolContext"))); services.AddDatabaseDeveloperPageExceptionFilter(); } #endregion public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
67
aws-dotnet-deploy
aws
C#
using ContosoUniversity.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ContosoUniversity { public class StartupSQLite { public StartupSQLite(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } #region snippet_ConfigureServices public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddDbContext<SchoolContext>(options => options.UseSqlite(Configuration.GetConnectionString("SchoolContext"))); services.AddDatabaseDeveloperPageExceptionFilter(); } #endregion public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
58
aws-dotnet-deploy
aws
C#
using ContosoUniversity.Data; using ContosoUniversity.Models; using System; using System.Linq; namespace ContosoUniversity.Data { public static class DbInitializer { public static void Initialize(SchoolContext context) { context.Database.EnsureCreated(); // Look for any students. if (context.Students.Any()) { return; // DB has been seeded } var students = new Student[] { new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2019-09-01")}, new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2017-09-01")}, new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2018-09-01")}, new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2017-09-01")}, new Student{FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse("2017-09-01")}, new Student{FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse("2016-09-01")}, new Student{FirstMidName="Laura",LastName="Norman",EnrollmentDate=DateTime.Parse("2018-09-01")}, new Student{FirstMidName="Nino",LastName="Olivetto",EnrollmentDate=DateTime.Parse("2019-09-01")} }; context.Students.AddRange(students); context.SaveChanges(); var courses = new Course[] { new Course{CourseID=1050,Title="Chemistry",Credits=3}, new Course{CourseID=4022,Title="Microeconomics",Credits=3}, new Course{CourseID=4041,Title="Macroeconomics",Credits=3}, new Course{CourseID=1045,Title="Calculus",Credits=4}, new Course{CourseID=3141,Title="Trigonometry",Credits=4}, new Course{CourseID=2021,Title="Composition",Credits=3}, new Course{CourseID=2042,Title="Literature",Credits=4} }; context.Courses.AddRange(courses); context.SaveChanges(); var enrollments = new Enrollment[] { new Enrollment{StudentID=1,CourseID=1050,Grade=Grade.A}, new Enrollment{StudentID=1,CourseID=4022,Grade=Grade.C}, new Enrollment{StudentID=1,CourseID=4041,Grade=Grade.B}, new Enrollment{StudentID=2,CourseID=1045,Grade=Grade.B}, new Enrollment{StudentID=2,CourseID=3141,Grade=Grade.F}, new Enrollment{StudentID=2,CourseID=2021,Grade=Grade.F}, new Enrollment{StudentID=3,CourseID=1050}, new Enrollment{StudentID=4,CourseID=1050}, new Enrollment{StudentID=4,CourseID=4022,Grade=Grade.F}, new Enrollment{StudentID=5,CourseID=4041,Grade=Grade.C}, new Enrollment{StudentID=6,CourseID=1045}, new Enrollment{StudentID=7,CourseID=3141,Grade=Grade.A}, }; context.Enrollments.AddRange(enrollments); context.SaveChanges(); } } }
69
aws-dotnet-deploy
aws
C#
using Microsoft.EntityFrameworkCore; using ContosoUniversity.Models; namespace ContosoUniversity.Data { public class SchoolContext : DbContext { public SchoolContext(DbContextOptions<SchoolContext> options) : base(options) { } public DbSet<Student> Students { get; set; } public DbSet<Enrollment> Enrollments { get; set; } public DbSet<Course> Courses { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Course>().ToTable("Course"); modelBuilder.Entity<Enrollment>().ToTable("Enrollment"); modelBuilder.Entity<Student>().ToTable("Student"); } } }
24
aws-dotnet-deploy
aws
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace ContosoUniversity.Models { public class Course { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } public ICollection<Enrollment> Enrollments { get; set; } } }
15
aws-dotnet-deploy
aws
C#
namespace ContosoUniversity.Models { public enum Grade { A, B, C, D, F } public class Enrollment { public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public Grade? Grade { get; set; } public Course Course { get; set; } public Student Student { get; set; } } }
18
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; namespace ContosoUniversity.Models { public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public ICollection<Enrollment> Enrollments { get; set; } } }
15
aws-dotnet-deploy
aws
C#
using System; using System.ComponentModel.DataAnnotations; namespace ContosoUniversity.Models.SchoolViewModels { public class EnrollmentDateGroup { [DataType(DataType.Date)] public DateTime? EnrollmentDate { get; set; } public int StudentCount { get; set; } } }
13
aws-dotnet-deploy
aws
C#
using ContosoUniversity.Models.SchoolViewModels; using ContosoUniversity.Data; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ContosoUniversity.Models; namespace ContosoUniversity.Pages { public class AboutModel : PageModel { private readonly SchoolContext _context; public AboutModel(SchoolContext context) { _context = context; } public IList<EnrollmentDateGroup> Students { get; set; } public async Task OnGetAsync() { IQueryable<EnrollmentDateGroup> data = from student in _context.Students group student by student.EnrollmentDate into dateGroup select new EnrollmentDateGroup() { EnrollmentDate = dateGroup.Key, StudentCount = dateGroup.Count() }; Students = await data.AsNoTracking().ToListAsync(); } } }
37
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace ContosoUniversity.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [IgnoreAntiforgeryToken] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
33
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace ContosoUniversity.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { } } }
26
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace ContosoUniversity.Pages { public class PrivacyModel : PageModel { private readonly ILogger<PrivacyModel> _logger; public PrivacyModel(ILogger<PrivacyModel> logger) { _logger = logger; } public void OnGet() { } } }
25
aws-dotnet-deploy
aws
C#
using ContosoUniversity.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System; using System.Threading.Tasks; namespace ContosoUniversity.Pages.Students { public class CreateModel : PageModel { private readonly ContosoUniversity.Data.SchoolContext _context; public CreateModel(ContosoUniversity.Data.SchoolContext context) { _context = context; } public IActionResult OnGet() { Student = new Student { EnrollmentDate = DateTime.Now, FirstMidName = "Joe", LastName = "Smith" }; return Page(); } [BindProperty] public Student Student { get; set; } public async Task<IActionResult> OnPostAsync() { var emptyStudent = new Student(); if (await TryUpdateModelAsync<Student>( emptyStudent, "student", // Prefix for form value. s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate)) { _context.Students.Add(emptyStudent); await _context.SaveChangesAsync(); return RedirectToPage("./Index"); } return Page(); } } }
50
aws-dotnet-deploy
aws
C#
using ContosoUniversity.Models; using ContosoUniversity.ViewModels; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System; using System.Threading.Tasks; namespace ContosoUniversity.Pages.Students { public class CreateVMModel : PageModel { private readonly ContosoUniversity.Data.SchoolContext _context; public CreateVMModel(ContosoUniversity.Data.SchoolContext context) { _context = context; } public IActionResult OnGet() { StudentVM = new StudentVM { EnrollmentDate = DateTime.Now, FirstMidName = "Joe VM", LastName = "Smith VM" }; return Page(); } #region snippet [BindProperty] public StudentVM StudentVM { get; set; } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } var entry = _context.Add(new Student()); entry.CurrentValues.SetValues(StudentVM); await _context.SaveChangesAsync(); return RedirectToPage("./Index"); } #endregion } }
48
aws-dotnet-deploy
aws
C#
using ContosoUniversity.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; namespace ContosoUniversity.Pages.Students { #region snippet_All public class DeleteModel : PageModel { private readonly ContosoUniversity.Data.SchoolContext _context; public DeleteModel(ContosoUniversity.Data.SchoolContext context) { _context = context; } [BindProperty] public Student Student { get; set; } public string ErrorMessage { get; set; } public async Task<IActionResult> OnGetAsync(int? id, bool? saveChangesError = false) { if (id == null) { return NotFound(); } Student = await _context.Students .AsNoTracking() .FirstOrDefaultAsync(m => m.ID == id); if (Student == null) { return NotFound(); } if (saveChangesError.GetValueOrDefault()) { ErrorMessage = "Delete failed. Try again"; } return Page(); } public async Task<IActionResult> OnPostAsync(int? id) { if (id == null) { return NotFound(); } var student = await _context.Students.FindAsync(id); if (student == null) { return NotFound(); } try { _context.Students.Remove(student); await _context.SaveChangesAsync(); return RedirectToPage("./Index"); } catch (DbUpdateException /* ex */) { //Log the error (uncomment ex variable name and write a log.) return RedirectToAction("./Delete", new { id, saveChangesError = true }); } } } #endregion }
76
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using ContosoUniversity.Data; using ContosoUniversity.Models; namespace ContosoUniversity.Pages.Students { public class DetailsModel : PageModel { private readonly ContosoUniversity.Data.SchoolContext _context; public DetailsModel(ContosoUniversity.Data.SchoolContext context) { _context = context; } public Student Student { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } Student = await _context.Students .Include(s => s.Enrollments) .ThenInclude(e => e.Course) .AsNoTracking() .FirstOrDefaultAsync(m => m.ID == id); if (Student == null) { return NotFound(); } return Page(); } } }
45
aws-dotnet-deploy
aws
C#
using ContosoUniversity.Data; using ContosoUniversity.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.Threading.Tasks; namespace ContosoUniversity.Pages.Students { public class EditModel : PageModel { private readonly SchoolContext _context; public EditModel(SchoolContext context) { _context = context; } [BindProperty] public Student Student { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } Student = await _context.Students.FindAsync(id); if (Student == null) { return NotFound(); } return Page(); } public async Task<IActionResult> OnPostAsync(int id) { var studentToUpdate = await _context.Students.FindAsync(id); if (studentToUpdate == null) { return NotFound(); } if (await TryUpdateModelAsync<Student>( studentToUpdate, "student", s => s.FirstMidName, s => s.LastName, s => s.EnrollmentDate)) { await _context.SaveChangesAsync(); return RedirectToPage("./Index"); } return Page(); } } }
59
aws-dotnet-deploy
aws
C#
using ContosoUniversity.Data; using ContosoUniversity.Models; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ContosoUniversity.Pages.Students { public class IndexModel : PageModel { private readonly SchoolContext _context; public IndexModel(SchoolContext context) { _context = context; } public string NameSort { get; set; } public string DateSort { get; set; } public string CurrentFilter { get; set; } public string CurrentSort { get; set; } public PaginatedList<Student> Students { get; set; } public async Task OnGetAsync(string sortOrder, string currentFilter, string searchString, int? pageIndex) { CurrentSort = sortOrder; NameSort = String.IsNullOrEmpty(sortOrder) ? "name_desc" : ""; DateSort = sortOrder == "Date" ? "date_desc" : "Date"; if (searchString != null) { pageIndex = 1; } else { searchString = currentFilter; } CurrentFilter = searchString; IQueryable<Student> studentsIQ = from s in _context.Students select s; if (!String.IsNullOrEmpty(searchString)) { studentsIQ = studentsIQ.Where(s => s.LastName.Contains(searchString) || s.FirstMidName.Contains(searchString)); } switch (sortOrder) { case "name_desc": studentsIQ = studentsIQ.OrderByDescending(s => s.LastName); break; case "Date": studentsIQ = studentsIQ.OrderBy(s => s.EnrollmentDate); break; case "date_desc": studentsIQ = studentsIQ.OrderByDescending(s => s.EnrollmentDate); break; default: studentsIQ = studentsIQ.OrderBy(s => s.LastName); break; } int pageSize = 3; Students = await PaginatedList<Student>.CreateAsync( studentsIQ.AsNoTracking(), pageIndex ?? 1, pageSize); } } }
73
aws-dotnet-deploy
aws
C#
using System; namespace ContosoUniversity.ViewModels { #region snippet public class StudentVM { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } } #endregion }
15
aws-dotnet-deploy
aws
C#
using System; namespace ConsoleSdkType { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
13
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace WebAppDifferentAssemblyName { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
27
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace WebAppDifferentAssemblyName { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
57
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppDifferentAssemblyName.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
32
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppDifferentAssemblyName.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { } } }
26
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppDifferentAssemblyName.Pages { public class PrivacyModel : PageModel { private readonly ILogger<PrivacyModel> _logger; public PrivacyModel(ILogger<PrivacyModel> logger) { _logger = logger; } public void OnGet() { } } }
25
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace WebAppDifferentTargetFramework { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
25
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace WebAppDifferentTargetFramework { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(); } } }
58
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.RazorPages; namespace WebAppDifferentTargetFramework.Pages { public class AboutModel : PageModel { public string Message { get; set; } public void OnGet() { Message = "Your application description page."; } } }
19
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.RazorPages; namespace WebAppDifferentTargetFramework.Pages { public class ContactModel : PageModel { public string Message { get; set; } public void OnGet() { Message = "Your contact page."; } } }
19
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace WebAppDifferentTargetFramework.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
24
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace WebAppDifferentTargetFramework.Pages { public class IndexModel : PageModel { public void OnGet() { } } }
18
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace WebAppDifferentTargetFramework.Pages { public class PrivacyModel : PageModel { public void OnGet() { } } }
16
aws-dotnet-deploy
aws
C#
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Test .NET 7"); app.Run();
7
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace WebAppNoSolution { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
27
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace WebAppNoSolution { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
57
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppNoSolution.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
32
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppNoSolution.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { } } }
26
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppNoSolution.Pages { public class PrivacyModel : PageModel { private readonly ILogger<PrivacyModel> _logger; public PrivacyModel(ILogger<PrivacyModel> logger) { _logger = logger; } public void OnGet() { } } }
25
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using WebAppProjectDependenciesLibrary; namespace WebAppProjectDependencies { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); Class1 cls = new Class1(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
29
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace WebAppProjectDependencies { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
57
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppProjectDependencies.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
32
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppProjectDependencies.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { } } }
26
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppProjectDependencies.Pages { public class PrivacyModel : PageModel { private readonly ILogger<PrivacyModel> _logger; public PrivacyModel(ILogger<PrivacyModel> logger) { _logger = logger; } public void OnGet() { } } }
25
aws-dotnet-deploy
aws
C#
using System; namespace WebAppProjectDependenciesLibrary { public class Class1 { } }
9
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using WebAppProjectDependenciesLibrary; namespace WebAppProjectDependencies { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); Class1 cls = new Class1(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
29
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace WebAppProjectDependencies { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
57
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppProjectDependencies.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
32
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppProjectDependencies.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { } } }
26
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppProjectDependencies.Pages { public class PrivacyModel : PageModel { private readonly ILogger<PrivacyModel> _logger; public PrivacyModel(ILogger<PrivacyModel> logger) { _logger = logger; } public void OnGet() { } } }
25
aws-dotnet-deploy
aws
C#
using System; namespace WebAppProjectDependenciesLibrary { public class Class1 { } }
9
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace WebAppWithSolutionParentLevel { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
27
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace WebAppWithSolutionParentLevel { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
57
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppWithSolutionParentLevel.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
32
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppWithSolutionParentLevel.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { } } }
26
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppWithSolutionParentLevel.Pages { public class PrivacyModel : PageModel { private readonly ILogger<PrivacyModel> _logger; public PrivacyModel(ILogger<PrivacyModel> logger) { _logger = logger; } public void OnGet() { } } }
25
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace WebAppWithSolutionSameLevel { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
27
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace WebAppWithSolutionSameLevel { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
57
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppWithSolutionSameLevel.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
32
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppWithSolutionSameLevel.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { } } }
26
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppWithSolutionSameLevel.Pages { public class PrivacyModel : PageModel { private readonly ILogger<PrivacyModel> _logger; public PrivacyModel(ILogger<PrivacyModel> logger) { _logger = logger; } public void OnGet() { } } }
25
aws-dotnet-deploy
aws
C#
using WorkerServiceExample; IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices(services => { services.AddHostedService<Worker>(); }) .Build(); await host.RunAsync();
11
aws-dotnet-deploy
aws
C#
namespace WorkerServiceExample { public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; public Worker(ILogger<Worker> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } } }
21
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; namespace MessageProcessingApp { internal class Program { private static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
16
aws-dotnet-deploy
aws
C#
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.UseHttpsRedirection(); app.MapGet("/", () => { return "Hello"; }); app.Run();
13
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace WebAppNoDockerFile { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
21
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace WebAppNoDockerFile { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
52
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppNoDockerFile.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
31
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppNoDockerFile.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { } } }
24
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppNoDockerFile.Pages { public class PrivacyModel : PageModel { private readonly ILogger<PrivacyModel> _logger; public PrivacyModel(ILogger<PrivacyModel> logger) { _logger = logger; } public void OnGet() { } } }
23
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace WebAppWithDockerFile { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
24
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace WebAppWithDockerFile { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapRazorPages(); }); } } }
57
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace WebAppWithDockerFile.Controllers { [ApiController] [Route("[controller]")] public class EnvVarController : ControllerBase { ILogger<EnvVarController> _logger; public EnvVarController(ILogger<EnvVarController> logger) { this._logger = logger; } [HttpGet()] public string Default(string name) { return "Hello"; } [HttpGet("{name}")] public IActionResult Get(string name) { _logger.LogInformation("Fetching environment variable " + name); // Only expose environment variables starting with TEST_ if (!name.StartsWith("TEST_")) { _logger.LogError("Fetch failed because environment variable name didn't start with TEST_"); return BadRequest(); } return Ok(Environment.GetEnvironmentVariable(name)); } } }
41
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppWithDockerFile.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
31
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace WebAppWithDockerFile.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { } } }
24